using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MegaRobo.Connections; using MegaRobo.Contract; using MegaRobo.Contract.Abstractions; using MegaRobo.Logger; namespace MegaRobo.C00225155.ControlDevices; public class CameraLightService : DeviceBase, IConnection, IDisposable, IConnectionAsync { public override async Task Initialize(ICoreService coreService, params object[] args) { await Task.Delay(0); try { string portName = "COM1"; if(args is [string portIndex, ..]) { portName = portIndex; } this.CoreService = coreService; this.SerialPortManger = new SerialPortManger(); bool isSuccess = this.SerialPortManger.Open(portName); this.SerialPortManger.SetPort(portName, 19200, DataBits.Eight, StopBits.One, Parity.None); // bool isSuccess = this.SerialPortManger.Open(); // int retCode = ControllerDllCSharp.ClassLibControllerDll.CreateSerialPort(3, ref this._controllerHandle); //创建串口 this.Logger.LogDebug($"打开串口Com3{(isSuccess ? "成功" : "失败")}"); } catch(Exception ex) { this.Logger.LogException(ex); } return string.Empty; } #region properties public SerialPortManger SerialPortManger { get; set; } public ConnectionState ConnectionState { get; set; } public event EventHandler ConnectChanged; public TimeSpan Timeout { get; set; } public bool IsConnected => SerialPortManger?.IsOpen ?? false; #endregion properties #region functions public async Task CheckConnected() { await Task.Delay(0); return ConnectionState.IsConnected; } public async Task ReconnectAsync() { await Task.Delay(0); return ConnectionState.IsConnected; } public async Task SetValue(byte value, params int[] channelIndexs) { if(channelIndexs.Length == 0) channelIndexs = new[] { 1, 2, 3, 4 }; var channelChars = new[] { "0", "A", "B", "C", "D" }; List cmds = channelIndexs.Select(index => $"S{channelChars[index]}{value:D4}#").ToList(); string cmdLine = string.Join("", cmds); var code = await this.SerialPortManger.WriteAndGetReplyAsync(cmdLine, TimeSpan.FromSeconds(1.5)); this.Logger.LogDebug($"设置光源cmd:{cmds} result:{code}"); } public void Close() { this.SerialPortManger.Close(); } public void Dispose() { // TODO release managed resources here } #endregion functions #region events #endregion events }