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

相关文章

SpringBoot集成Milvus实现数据增删改查功能

《SpringBoot集成Milvus实现数据增删改查功能》milvus支持的语言比较多,支持python,Java,Go,node等开发语言,本文主要介绍如何使用Java语言,采用springboo... 目录1、Milvus基本概念2、添加maven依赖3、配置yml文件4、创建MilvusClient

SpringValidation数据校验之约束注解与分组校验方式

《SpringValidation数据校验之约束注解与分组校验方式》本文将深入探讨SpringValidation的核心功能,帮助开发者掌握约束注解的使用技巧和分组校验的高级应用,从而构建更加健壮和可... 目录引言一、Spring Validation基础架构1.1 jsR-380标准与Spring整合1

MySQL 中查询 VARCHAR 类型 JSON 数据的问题记录

《MySQL中查询VARCHAR类型JSON数据的问题记录》在数据库设计中,有时我们会将JSON数据存储在VARCHAR或TEXT类型字段中,本文将详细介绍如何在MySQL中有效查询存储为V... 目录一、问题背景二、mysql jsON 函数2.1 常用 JSON 函数三、查询示例3.1 基本查询3.2

SpringBatch数据写入实现

《SpringBatch数据写入实现》SpringBatch通过ItemWriter接口及其丰富的实现,提供了强大的数据写入能力,本文主要介绍了SpringBatch数据写入实现,具有一定的参考价值,... 目录python引言一、ItemWriter核心概念二、数据库写入实现三、文件写入实现四、多目标写入

使用Python将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用

Mysql如何将数据按照年月分组的统计

《Mysql如何将数据按照年月分组的统计》:本文主要介绍Mysql如何将数据按照年月分组的统计方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录mysql将数据按照年月分组的统计要的效果方案总结Mysql将数据按照年月分组的统计要的效果方案① 使用 DA

鸿蒙中Axios数据请求的封装和配置方法

《鸿蒙中Axios数据请求的封装和配置方法》:本文主要介绍鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.配置权限 应用级权限和系统级权限2.配置网络请求的代码3.下载在Entry中 下载AxIOS4.封装Htt

基于Python打造一个可视化FTP服务器

《基于Python打造一个可视化FTP服务器》在日常办公和团队协作中,文件共享是一个不可或缺的需求,所以本文将使用Python+Tkinter+pyftpdlib开发一款可视化FTP服务器,有需要的小... 目录1. 概述2. 功能介绍3. 如何使用4. 代码解析5. 运行效果6.相关源码7. 总结与展望1

使用Python开发一个简单的本地图片服务器

《使用Python开发一个简单的本地图片服务器》本文介绍了如何结合wxPython构建的图形用户界面GUI和Python内建的Web服务器功能,在本地网络中搭建一个私人的,即开即用的网页相册,文中的示... 目录项目目标核心技术栈代码深度解析完整代码工作流程主要功能与优势潜在改进与思考运行结果总结你是否曾经

Python获取中国节假日数据记录入JSON文件

《Python获取中国节假日数据记录入JSON文件》项目系统内置的日历应用为了提升用户体验,特别设置了在调休日期显示“休”的UI图标功能,那么问题是这些调休数据从哪里来呢?我尝试一种更为智能的方法:P... 目录节假日数据获取存入jsON文件节假日数据读取封装完整代码项目系统内置的日历应用为了提升用户体验,