Unity 创建Tobii数据服务器

2023-10-25 09:40

本文主要是介绍Unity 创建Tobii数据服务器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Unity 创建Tobii数据服务器

  • 前言
  • 读取Tobii数据
  • 开启Http服务器
  • 开启服务器并获取数据完整源码(需结合读取Tobii数据)

前言

遇到了一个眼动仪的项目,但是我没空做,给了个会cocos creator的人做,他只能用websocket或者http拿数据,捣鼓了一天.Net,很遗憾失败了,退而求其次,用Unity读到数据,并且开了个Http的服务器。
Tips:文末有工程截图

读取Tobii数据

官网连接: https://developer.tobii.com/product-integration/stream-engine/getting-started/
在.Net中用多线程拿数据会有点小问题,以后有空再说
下面是Unity代码,Start中找到设备并连接Update持续读取数据

using System;
using System.Collections;
using System.Collections.Generic;
using Tobii.StreamEngine;
using UnityEngine;public class Yandongyi : MonoBehaviour
{public static Vector2 GazePoint=Vector2.zero;private static void OnGazePoint(ref tobii_gaze_point_t gazePoint, IntPtr userData){// Check that the data is valid before using itif (gazePoint.validity == tobii_validity_t.TOBII_VALIDITY_VALID){//Debug.Log($"Gaze point: {gazePoint.position.x}, {gazePoint.position.y}");GazePoint.x = gazePoint.position.x;GazePoint.y = gazePoint.position.y;}}// Create API context创建API上下文IntPtr apiContext;// Connect to the first tracker found 连接到找到的第一个跟踪器IntPtr deviceContext;tobii_error_t result;// Enumerate devices to find connected eye trackers 枚举设备查找连接的眼跟踪器List<string> urls;void Start(){result = Interop.tobii_api_create(out apiContext, null);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);result = Interop.tobii_enumerate_local_device_urls(apiContext, out urls);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);if (urls.Count == 0){Console.WriteLine("Error: No device found");return;}result = Interop.tobii_device_create(apiContext, urls[0], Interop.tobii_field_of_use_t.TOBII_FIELD_OF_USE_INTERACTIVE, out deviceContext);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);// Subscribe to gaze data 订阅凝视数据result = Interop.tobii_gaze_point_subscribe(deviceContext, OnGazePoint);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR); This sample will collect 1000 gaze points 此样品将收集1000个凝视点//for (int i = 0; i < 1000; i++)//{//    // Optionally block this thread until data is available. Especially useful if running in a separate thread.可选地阻止此线程,直到数据可用。如果在单独的线程中运行,则特别有用。//    Interop.tobii_wait_for_callbacks(new[] { deviceContext });//    Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR || result == tobii_error_t.TOBII_ERROR_TIMED_OUT);//    // Process callbacks on this thread if data is available 如果数据可用,则此线程上的处理回调//    Interop.tobii_device_process_callbacks(deviceContext);//    Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);//}}// Update is called once per framevoid Update(){if (deviceContext!=null){// Optionally block this thread until data is available. Especially useful if running in a separate thread.//可选地阻止此线程,直到数据可用。如果在单独的线程中运行,则特别有用。Interop.tobii_wait_for_callbacks(new[] { deviceContext });Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR || result == tobii_error_t.TOBII_ERROR_TIMED_OUT);// Process callbacks on this thread if data is available //如果数据可用,则此线程上的处理回调Interop.tobii_device_process_callbacks(deviceContext);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);}}private void OnDestroy(){ Cleanup 清理result = Interop.tobii_gaze_point_unsubscribe(deviceContext);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);result = Interop.tobii_device_destroy(deviceContext);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);result = Interop.tobii_api_destroy(apiContext);Debug.Assert(result == tobii_error_t.TOBII_ERROR_NO_ERROR);}
}

开启Http服务器

下面是Unity开启HTTP服务器的方法

	private void HttpReceiveFunction(){try{httpListener = new HttpListener();httpListener.Prefixes.Add("http://+:8866/");httpListener.Start();//异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托//该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象httpListener.BeginGetContext(Result, null);Debug.Log($"服务端初始化完毕http://127.0.0.1:8866/,正在等待客户端请求,时间:{DateTime.Now.ToString()}\r\n");}catch (Exception e){Console.WriteLine(e);throw;}}/// <summary>/// 当接收到请求后程序流会走到这里/// </summary>/// <param name="ar"></param>private void Result(IAsyncResult ar){if (!opening){return;}//继续异步监听httpListener.BeginGetContext(Result, null);var guid = Guid.NewGuid().ToString();Console.ForegroundColor = ConsoleColor.White;//获得context对象HttpListenerContext context = httpListener.EndGetContext(ar);HttpListenerRequest request = context.Request;HttpListenerResponse response = context.Response;Console.WriteLine($"New Request:{guid},时间:{DateTime.Now.ToString()},内容:{context.Request.Url}");如果是js的ajax请求,还可以设置跨域的ip地址与参数//context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件//context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件//context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息context.Response.ContentEncoding = Encoding.UTF8;string returnObj = null;//定义返回客户端的信息switch (request.HttpMethod){case "POST":{//处理客户端发送的请求并返回处理信息returnObj = HandleRequest(request, response);}break;case "GET":{//处理客户端发送的请求并返回处理信息returnObj = HandleRequest(request, response);}break;default:{returnObj = "null";}break;}var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码response.AddHeader("Content-type", "text/html;charset=UTF-8");response.AddHeader("Access-Control-Allow-Origin", "*");try{using (var stream = response.OutputStream){//把处理信息返回到客户端stream.Write(returnByteArr, 0, returnByteArr.Length);}}catch (Exception ex){Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"网络蹦了:{ex.ToString()}");}//Console.WriteLine($"请求处理完成:{guid},时间:{ DateTime.Now.ToString()}\r\n");}/// <summary>/// 处理客户端发送的请求并返回处理信息/// </summary>/// <param name="request"></param>/// <param name="response"></param>/// <returns></returns>private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response){string data = null;try{var byteList = new List<byte>();var byteArr = new byte[2048];int readLen = 0;int len = 0;//接收客户端传过来的数据并转成字符串类型do{readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);len += readLen;byteList.AddRange(byteArr);} while (readLen != 0);data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);//获取得到数据data可以进行其他操作//Console.WriteLine("客户端发来的是" + data+request.UserAgent);Console.WriteLine(Yandongyi.GazePoint.x + "-" + Yandongyi.GazePoint.y);return Yandongyi.GazePoint.x + "," + Yandongyi.GazePoint.y;}catch (Exception ex){response.StatusDescription = "404";response.StatusCode = 404;Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");return null;//return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考}response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。Console.ForegroundColor = ConsoleColor.Green;Console.WriteLine($"接收数据完成:{data.Trim()},时间:{DateTime.Now.ToString()}");return $"接收数据完成";}

开启服务器并获取数据完整源码(需结合读取Tobii数据)

场景截图

using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Text;
using UnityEngine;public class YandongyiServer : MonoBehaviour
{public GameObject MyCube;public Material redMat;public Material greenMat;private HttpListener httpListener;private bool opening = false;// Start is called before the first frame updatevoid Start(){// 设置分辨率和是否全屏Screen.SetResolution(1024, 768, false);MyCube.GetComponent<MeshRenderer>().material = redMat;}private void Update(){if (MyCube!=null){MyCube.transform.position = new Vector3(Yandongyi.GazePoint.x*10-5,-(Yandongyi.GazePoint.y*6-3));}}public void StartHttpServer(){if (!opening){opening = true;HttpReceiveFunction();MyCube.GetComponent<MeshRenderer>().material = greenMat;}}public void CloseHttpServer(){if (opening){opening = false;if (httpListener.IsListening){httpListener.Stop();httpListener = null;}MyCube.GetComponent<MeshRenderer>().material = redMat;}}private void HttpReceiveFunction(){try{httpListener = new HttpListener();httpListener.Prefixes.Add("http://+:8866/");httpListener.Start();//异步监听客户端请求,当客户端的网络请求到来时会自动执行Result委托//该委托没有返回值,有一个IAsyncResult接口的参数,可通过该参数获取context对象httpListener.BeginGetContext(Result, null);Debug.Log($"服务端初始化完毕http://127.0.0.1:8866/,正在等待客户端请求,时间:{DateTime.Now.ToString()}\r\n");}catch (Exception e){Console.WriteLine(e);throw;}}/// <summary>/// 当接收到请求后程序流会走到这里/// </summary>/// <param name="ar"></param>private void Result(IAsyncResult ar){if (!opening){return;}//继续异步监听httpListener.BeginGetContext(Result, null);var guid = Guid.NewGuid().ToString();Console.ForegroundColor = ConsoleColor.White;//获得context对象HttpListenerContext context = httpListener.EndGetContext(ar);HttpListenerRequest request = context.Request;HttpListenerResponse response = context.Response;Console.WriteLine($"New Request:{guid},时间:{DateTime.Now.ToString()},内容:{context.Request.Url}");如果是js的ajax请求,还可以设置跨域的ip地址与参数//context.Response.AppendHeader("Access-Control-Allow-Origin", "*");//后台跨域请求,通常设置为配置文件//context.Response.AppendHeader("Access-Control-Allow-Headers", "ID,PW");//后台跨域参数设置,通常设置为配置文件//context.Response.AppendHeader("Access-Control-Allow-Method", "post");//后台跨域请求设置,通常设置为配置文件context.Response.ContentType = "text/plain;charset=UTF-8";//告诉客户端返回的ContentType类型为纯文本格式,编码为UTF-8context.Response.AddHeader("Content-type", "text/plain");//添加响应头信息context.Response.ContentEncoding = Encoding.UTF8;string returnObj = null;//定义返回客户端的信息switch (request.HttpMethod){case "POST":{//处理客户端发送的请求并返回处理信息returnObj = HandleRequest(request, response);}break;case "GET":{//处理客户端发送的请求并返回处理信息returnObj = HandleRequest(request, response);}break;default:{returnObj = "null";}break;}var returnByteArr = Encoding.UTF8.GetBytes(returnObj);//设置客户端返回信息的编码response.AddHeader("Content-type", "text/html;charset=UTF-8");response.AddHeader("Access-Control-Allow-Origin", "*");try{using (var stream = response.OutputStream){//把处理信息返回到客户端stream.Write(returnByteArr, 0, returnByteArr.Length);}}catch (Exception ex){Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"网络蹦了:{ex.ToString()}");}//Console.WriteLine($"请求处理完成:{guid},时间:{ DateTime.Now.ToString()}\r\n");}/// <summary>/// 处理客户端发送的请求并返回处理信息/// </summary>/// <param name="request"></param>/// <param name="response"></param>/// <returns></returns>private string HandleRequest(HttpListenerRequest request, HttpListenerResponse response){string data = null;try{var byteList = new List<byte>();var byteArr = new byte[2048];int readLen = 0;int len = 0;//接收客户端传过来的数据并转成字符串类型do{readLen = request.InputStream.Read(byteArr, 0, byteArr.Length);len += readLen;byteList.AddRange(byteArr);} while (readLen != 0);data = Encoding.UTF8.GetString(byteList.ToArray(), 0, len);//获取得到数据data可以进行其他操作//Console.WriteLine("客户端发来的是" + data+request.UserAgent);Console.WriteLine(Yandongyi.GazePoint.x + "-" + Yandongyi.GazePoint.y);return Yandongyi.GazePoint.x + "," + Yandongyi.GazePoint.y;}catch (Exception ex){response.StatusDescription = "404";response.StatusCode = 404;Console.ForegroundColor = ConsoleColor.Red;Console.WriteLine($"在接收数据时发生错误:{ex.ToString()}");return null;//return $"在接收数据时发生错误:{ex.ToString()}";//把服务端错误信息直接返回可能会导致信息不安全,此处仅供参考}response.StatusDescription = "200";//获取或设置返回给客户端的 HTTP 状态代码的文本说明。response.StatusCode = 200;// 获取或设置返回给客户端的 HTTP 状态代码。Console.ForegroundColor = ConsoleColor.Green;Console.WriteLine($"接收数据完成:{data.Trim()},时间:{DateTime.Now.ToString()}");return $"接收数据完成";}private void OnDestroy(){CloseHttpServer();}
}

运行示例

这篇关于Unity 创建Tobii数据服务器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/281697

相关文章

GSON框架下将百度天气JSON数据转JavaBean

《GSON框架下将百度天气JSON数据转JavaBean》这篇文章主要为大家详细介绍了如何在GSON框架下实现将百度天气JSON数据转JavaBean,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录前言一、百度天气jsON1、请求参数2、返回参数3、属性映射二、GSON属性映射实战1、类对象映

Web服务器-Nginx-高并发问题

《Web服务器-Nginx-高并发问题》Nginx通过事件驱动、I/O多路复用和异步非阻塞技术高效处理高并发,结合动静分离和限流策略,提升性能与稳定性... 目录前言一、架构1. 原生多进程架构2. 事件驱动模型3. IO多路复用4. 异步非阻塞 I/O5. Nginx高并发配置实战二、动静分离1. 职责2

C# LiteDB处理时间序列数据的高性能解决方案

《C#LiteDB处理时间序列数据的高性能解决方案》LiteDB作为.NET生态下的轻量级嵌入式NoSQL数据库,一直是时间序列处理的优选方案,本文将为大家大家简单介绍一下LiteDB处理时间序列数... 目录为什么选择LiteDB处理时间序列数据第一章:LiteDB时间序列数据模型设计1.1 核心设计原则

Linux搭建ftp服务器的步骤

《Linux搭建ftp服务器的步骤》本文给大家分享Linux搭建ftp服务器的步骤,本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录ftp搭建1:下载vsftpd工具2:下载客户端工具3:进入配置文件目录vsftpd.conf配置文件4:

Java+AI驱动实现PDF文件数据提取与解析

《Java+AI驱动实现PDF文件数据提取与解析》本文将和大家分享一套基于AI的体检报告智能评估方案,详细介绍从PDF上传、内容提取到AI分析、数据存储的全流程自动化实现方法,感兴趣的可以了解下... 目录一、核心流程:从上传到评估的完整链路二、第一步:解析 PDF,提取体检报告内容1. 引入依赖2. 封装

Spring创建Bean的八种主要方式详解

《Spring创建Bean的八种主要方式详解》Spring(尤其是SpringBoot)提供了多种方式来让容器创建和管理Bean,@Component、@Configuration+@Bean、@En... 目录引言一、Spring 创建 Bean 的 8 种主要方式1. @Component 及其衍生注解

MySQL中查询和展示LONGBLOB类型数据的技巧总结

《MySQL中查询和展示LONGBLOB类型数据的技巧总结》在MySQL中LONGBLOB是一种二进制大对象(BLOB)数据类型,用于存储大量的二进制数据,:本文主要介绍MySQL中查询和展示LO... 目录前言1. 查询 LONGBLOB 数据的大小2. 查询并展示 LONGBLOB 数据2.1 转换为十

使用SpringBoot+InfluxDB实现高效数据存储与查询

《使用SpringBoot+InfluxDB实现高效数据存储与查询》InfluxDB是一个开源的时间序列数据库,特别适合处理带有时间戳的监控数据、指标数据等,下面详细介绍如何在SpringBoot项目... 目录1、项目介绍2、 InfluxDB 介绍3、Spring Boot 配置 InfluxDB4、I

Unity新手入门学习殿堂级知识详细讲解(图文)

《Unity新手入门学习殿堂级知识详细讲解(图文)》Unity是一款跨平台游戏引擎,支持2D/3D及VR/AR开发,核心功能模块包括图形、音频、物理等,通过可视化编辑器与脚本扩展实现开发,项目结构含A... 目录入门概述什么是 UnityUnity引擎基础认知编辑器核心操作Unity 编辑器项目模式分类工程

Java整合Protocol Buffers实现高效数据序列化实践

《Java整合ProtocolBuffers实现高效数据序列化实践》ProtocolBuffers是Google开发的一种语言中立、平台中立、可扩展的结构化数据序列化机制,类似于XML但更小、更快... 目录一、Protocol Buffers简介1.1 什么是Protocol Buffers1.2 Pro