using UnityEngine; using System; using System.IO.Ports; using System.Threading; namespace Sensors.USB { [Serializable] public struct USBSensorConfig { public String serialPort; public Int32 baudRate; public Parity parity; public StopBits stopBits; public Int32 dataBits; public Handshake handshake; public Boolean rtsEnable; public Boolean debug; public USBSensorConfig( String port = "COM1", Int32 baudRate = 9600, Parity parity = Parity.None, StopBits stopBits = StopBits.None, Int32 dataBits = 8, Handshake handshake = Handshake.None, Boolean rtsEnable = true, Boolean debug = false ){ this.serialPort = port; this.baudRate = baudRate; this.parity = parity; this.stopBits = stopBits; this.dataBits = dataBits; this.handshake = handshake; this.rtsEnable = rtsEnable; this.debug = debug; } } public struct USBSensorData { public bool isBreaking; public float timeActive; } public class USBReceiver { private USBSensorConfig config; private SerialPort sp = null; private USBSensorData sensorData; private Thread serialThread; private Boolean looping; public USBSensorData SensorData => sensorData; public USBReceiver(USBSensorConfig config){ this.config = config; } public void StartListening() { /*String[] ports = SerialPort.GetPortNames(); foreach(String port in ports){ Debug.Log(port); }*/ this.sp = new SerialPort( this.config.serialPort, this.config.baudRate, this.config.parity, this.config.dataBits, this.config.stopBits ); /*this.sp.Handshake = this.config.handshake; this.sp.RtsEnable = this.config.rtsEnable;*/ this.sp.Open(); this.looping = true; this.serialThread = new Thread(CheckSerialPort); serialThread.Start(); Debug.Log("Started Listening for Serial Port " + this.config.serialPort); } public void StopListening(){ if(this.serialThread != null){ Debug.Log("Stopping Thread!"); this.looping = false; this.serialThread.Join(); this.serialThread.Abort(); } if(this.sp != null){ this.sp.Close(); } } public void Dispose() { Debug.Log("Dispose Serial Port Listening"); StopListening(); } private void CheckSerialPort(){ while(this.looping){ if(this.sp != null){ String content = sp.ReadLine(); if(content.Contains("BS=")){ String status = content.Split('=')[1]; Int32 statCode = Int32.Parse(status); if(statCode == 1){ Debug.Log("Breaking"); this.sensorData.isBreaking = true; }else if(statCode == 0){ this.sensorData.isBreaking = false; } } }else{ Debug.Log("found no Serial Port!"); } Thread.Sleep(500); } } } }