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

相关文章

Ubuntu 22.04 服务器安装部署(nginx+postgresql)

《Ubuntu22.04服务器安装部署(nginx+postgresql)》Ubuntu22.04LTS是迄今为止最好的Ubuntu版本之一,很多linux的应用服务器都是选择的这个版本... 目录是什么让 Ubuntu 22.04 LTS 变得安全?更新了安全包linux 内核改进一、部署环境二、安装系统

MySQL InnoDB引擎ibdata文件损坏/删除后使用frm和ibd文件恢复数据

《MySQLInnoDB引擎ibdata文件损坏/删除后使用frm和ibd文件恢复数据》mysql的ibdata文件被误删、被恶意修改,没有从库和备份数据的情况下的数据恢复,不能保证数据库所有表数据... 参考:mysql Innodb表空间卸载、迁移、装载的使用方法注意!此方法只适用于innodb_fi

mysql通过frm和ibd文件恢复表_mysql5.7根据.frm和.ibd文件恢复表结构和数据

《mysql通过frm和ibd文件恢复表_mysql5.7根据.frm和.ibd文件恢复表结构和数据》文章主要介绍了如何从.frm和.ibd文件恢复MySQLInnoDB表结构和数据,需要的朋友可以参... 目录一、恢复表结构二、恢复表数据补充方法一、恢复表结构(从 .frm 文件)方法 1:使用 mysq

mysql8.0无备份通过idb文件恢复数据的方法、idb文件修复和tablespace id不一致处理

《mysql8.0无备份通过idb文件恢复数据的方法、idb文件修复和tablespaceid不一致处理》文章描述了公司服务器断电后数据库故障的过程,作者通过查看错误日志、重新初始化数据目录、恢复备... 周末突然接到一位一年多没联系的妹妹打来电话,“刘哥,快来救救我”,我脑海瞬间冒出妙瓦底,电信火苲马扁.

golang获取prometheus数据(prometheus/client_golang包)

《golang获取prometheus数据(prometheus/client_golang包)》本文主要介绍了使用Go语言的prometheus/client_golang包来获取Prometheu... 目录1. 创建链接1.1 语法1.2 完整示例2. 简单查询2.1 语法2.2 完整示例3. 范围值

nginx配置多域名共用服务器80端口

《nginx配置多域名共用服务器80端口》本文主要介绍了配置Nginx.conf文件,使得同一台服务器上的服务程序能够根据域名分发到相应的端口进行处理,从而实现用户通过abc.com或xyz.com直... 多个域名,比如两个域名,这两个域名其实共用一台服务器(意味着域名解析到同一个IP),一个域名为abc

Python中conda虚拟环境创建及使用小结

《Python中conda虚拟环境创建及使用小结》本文主要介绍了Python中conda虚拟环境创建及使用小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们... 目录0.前言1.Miniconda安装2.conda本地基本操作3.创建conda虚拟环境4.激活c

pycharm远程连接服务器运行pytorch的过程详解

《pycharm远程连接服务器运行pytorch的过程详解》:本文主要介绍在Linux环境下使用Anaconda管理不同版本的Python环境,并通过PyCharm远程连接服务器来运行PyTorc... 目录linux部署pytorch背景介绍Anaconda安装Linux安装pytorch虚拟环境安装cu

使用Python创建一个能够筛选文件的PDF合并工具

《使用Python创建一个能够筛选文件的PDF合并工具》这篇文章主要为大家详细介绍了如何使用Python创建一个能够筛选文件的PDF合并工具,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下... 目录背景主要功能全部代码代码解析1. 初始化 wx.Frame 窗口2. 创建工具栏3. 创建布局和界面控件4

javaScript在表单提交时获取表单数据的示例代码

《javaScript在表单提交时获取表单数据的示例代码》本文介绍了五种在JavaScript中获取表单数据的方法:使用FormData对象、手动提取表单数据、使用querySelector获取单个字... 方法 1:使用 FormData 对象FormData 是一个方便的内置对象,用于获取表单中的键值