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

相关文章

mysqld_multi在Linux服务器上运行多个MySQL实例

《mysqld_multi在Linux服务器上运行多个MySQL实例》在Linux系统上使用mysqld_multi来启动和管理多个MySQL实例是一种常见的做法,这种方式允许你在同一台机器上运行多个... 目录1. 安装mysql2. 配置文件示例配置文件3. 创建数据目录4. 启动和管理实例启动所有实例

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

VScode连接远程Linux服务器环境配置图文教程

《VScode连接远程Linux服务器环境配置图文教程》:本文主要介绍如何安装和配置VSCode,包括安装步骤、环境配置(如汉化包、远程SSH连接)、语言包安装(如C/C++插件)等,文中给出了详... 目录一、安装vscode二、环境配置1.中文汉化包2.安装remote-ssh,用于远程连接2.1安装2

Java中注解与元数据示例详解

《Java中注解与元数据示例详解》Java注解和元数据是编程中重要的概念,用于描述程序元素的属性和用途,:本文主要介绍Java中注解与元数据的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参... 目录一、引言二、元数据的概念2.1 定义2.2 作用三、Java 注解的基础3.1 注解的定义3.2 内

将sqlserver数据迁移到mysql的详细步骤记录

《将sqlserver数据迁移到mysql的详细步骤记录》:本文主要介绍将SQLServer数据迁移到MySQL的步骤,包括导出数据、转换数据格式和导入数据,通过示例和工具说明,帮助大家顺利完成... 目录前言一、导出SQL Server 数据二、转换数据格式为mysql兼容格式三、导入数据到MySQL数据

C++中使用vector存储并遍历数据的基本步骤

《C++中使用vector存储并遍历数据的基本步骤》C++标准模板库(STL)提供了多种容器类型,包括顺序容器、关联容器、无序关联容器和容器适配器,每种容器都有其特定的用途和特性,:本文主要介绍C... 目录(1)容器及简要描述‌php顺序容器‌‌关联容器‌‌无序关联容器‌(基于哈希表):‌容器适配器‌:(

C#提取PDF表单数据的实现流程

《C#提取PDF表单数据的实现流程》PDF表单是一种常见的数据收集工具,广泛应用于调查问卷、业务合同等场景,凭借出色的跨平台兼容性和标准化特点,PDF表单在各行各业中得到了广泛应用,本文将探讨如何使用... 目录引言使用工具C# 提取多个PDF表单域的数据C# 提取特定PDF表单域的数据引言PDF表单是一

MySQL分表自动化创建的实现方案

《MySQL分表自动化创建的实现方案》在数据库应用场景中,随着数据量的不断增长,单表存储数据可能会面临性能瓶颈,例如查询、插入、更新等操作的效率会逐渐降低,分表是一种有效的优化策略,它将数据分散存储在... 目录一、项目目的二、实现过程(一)mysql 事件调度器结合存储过程方式1. 开启事件调度器2. 创

一文详解Python中数据清洗与处理的常用方法

《一文详解Python中数据清洗与处理的常用方法》在数据处理与分析过程中,缺失值、重复值、异常值等问题是常见的挑战,本文总结了多种数据清洗与处理方法,文中的示例代码简洁易懂,有需要的小伙伴可以参考下... 目录缺失值处理重复值处理异常值处理数据类型转换文本清洗数据分组统计数据分箱数据标准化在数据处理与分析过

大数据小内存排序问题如何巧妙解决

《大数据小内存排序问题如何巧妙解决》文章介绍了大数据小内存排序的三种方法:数据库排序、分治法和位图法,数据库排序简单但速度慢,对设备要求高;分治法高效但实现复杂;位图法可读性差,但存储空间受限... 目录三种方法:方法概要数据库排序(http://www.chinasem.cn对数据库设备要求较高)分治法(常