一、本文介绍在web环境下unity与usb串口进行通信的代码
本篇使用本地服务器作为unity与串口的中介,unity发送数据到服务器,服务器发送给串口收到响应并解析返回给uinty。
使用websocket协议。
注:
1.我的硬件是检测磁阻液位,用到四字节十六进制浮点数,所以这里会直接转换到十进制。
2.我的硬件会返回9字节响应,所以我会限制响应长度,可以进行适当更改
重要:
1.再开始前一定要改为.NET 4.x,或者.NET Framework,因为.NET standard 2.0或者2.1不包括需要用到的using System.IO.Ports;更换路径为File/Build Setting/Player Settings.../Other Settings/Api Compatibility Level
二、准备文件:
1.使用c#写服务端,需要打开nuget包进行安装websocket,路径:工具/NuGet包管理器/管理解决方案的NuGet程序包/浏览
2.unity端:下载NativeWebSocket,地址:https://github.com/endel/NativeWebSocket
注意:下载了.unitypackage包后拖入到unity中,他会存放到与Assets同级的目录下,打开文件夹将他全部拖到Assets目录就可以了(我不知道不拖行不行,反正我这么做的可以正常使用)
三、服务端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using WebSocketSharp.Server;
using System.Threading;
using WebSocketSharp;
namespace webforeverusb
{
class Program
{
static void Main(string[] args)
{
var wss = new WebSocketServer("ws://localhost:8080");
wss.AddWebSocketService<SerialService>("/serial");
wss.Start();
Console.WriteLine("WebSocket 服务器正在运行...");
Console.ReadLine(); // 保持控制台运行
wss.Stop(); // 优雅关闭服务器
}
}
class SerialService : WebSocketBehavior
{
pr

最低0.47元/天 解锁文章
2080

被折叠的 条评论
为什么被折叠?



