using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GSG.NET.Utils; namespace OHVConnector { public enum eKind { Unknown, // Not Define E, //Error S, //State B, //Battery T, // C, P, I,//수동명령보고,응답 O, A,//Alive Check L, U, F, M,//Move R, H, Z, } public class OCSMessage { const byte STX = 0x02; const byte ETX = 0x03; public string Id { get; set; } public eKind Kind { get; set; } //SubCode 만들기 위한 Bool public bool IsSubCode1 { get; set; } = false; public bool IsSubCode2 { get; set; } = false; public bool IsSubCode3 { get; set; } = false; public string RevID { get; set; } public string SendID { get; set; } public string Tag { get; set; } public string SubCode { get; set; } public string CheckSum { get; set; } string checkSum = string.Empty; public IList ViaRouteList { get; set; } public OCSMessage() { this.ViaRouteList = new List(); } public string LogFormat() { return $"{this.Id} - {this.RevID} <- {this.SendID} : kind [{this.Kind.ToString()}] / Tag [{this.Tag}] / SubCode [{this.SubCode}] / CheckSum [{this.CheckSum}]"; } public int SubCodeToInt() { int result = 0; if ( string.IsNullOrEmpty( this.SubCode ) ) { StringBuilder sb = new StringBuilder(); sb.Append( this.IsSubCode1 ? "1" : "0" ); sb.Append( this.IsSubCode2 ? "1" : "0" ); sb.Append( this.IsSubCode3 ? "1" : "0" ); int.TryParse( sb.ToString(), out result ); } else int.TryParse( this.SubCode, out result ); return result; } string MakeSubcode() { if ( !string.IsNullOrEmpty( this.SubCode ) ) { return this.SubCode; } else { StringBuilder sb = new StringBuilder(); sb.Append( this.IsSubCode1 ? "1" : "0" ); sb.Append( this.IsSubCode2 ? "1" : "0" ); sb.Append( this.IsSubCode3 ? "1" : "0" ); return this.SubCode = sb.ToString(); } } public MemoryBuffer ToMemoryBuffer() { var mb = new MemoryBuffer(); mb.Append( STX ); mb.AppendAscii( RevID ); mb.AppendAscii( SendID ); mb.AppendAscii( this.Kind.ToString() ); mb.AppendAscii( this.Tag ); mb.AppendAscii( MakeSubcode() ); if ( this.Kind == eKind.M) { var viaCountj = this.ViaRouteList.Count.ToString( "0000" ); foreach(var item in this.ViaRouteList ) { mb.AppendAscii( item ); } } this.CheckSum = Convert.ToString( GetCheckSum( mb.ToBytes ), 16 ).ToLower(); mb.AppendAscii( this.CheckSum ); mb.Append( ETX ); return mb; } public byte GetCheckSum() { var mb = new MemoryBuffer( 18 ); mb.Append( STX ); mb.AppendAscii( RevID ); mb.AppendAscii( SendID ); mb.AppendAscii( this.Kind.ToString() ); mb.AppendAscii( this.Tag ); mb.AppendAscii( MakeSubcode() ); //string checkSum = Convert.ToString( GetCheckSum( mb.ToBytes ), 16 ).ToLower(); return GetCheckSum( mb.ToBytes ); } byte GetCheckSum( byte[] bs ) { byte rb = 0; foreach ( var item in bs ) { if ( item == STX ) continue; rb += item; } return (byte)( rb & 0xf ); //&0xff 수정. } } }