using Common.Config; using Parser.BinaryParser; using Parser.BinaryParser.MessageEntity; using Parser.BinaryParser.Util; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace HengShan_Pump_NonIC { public class MessageTemplateLookup : IMessageTemplateLookup { private static readonly MessageTemplateLookup defaultInstance = new MessageTemplateLookup(); /// /// Gets the default singleton instance of type MessageTemplateLookup. /// public static MessageTemplateLookup Default => defaultInstance; /// /// resolve from the config /// private static readonly IEnumerable lookup = MessageLookupConfigurationSectionHandler.GetConfig().DeviceTypes.Cast().First(d => d.DeviceTypeString == "hengShan_Pump_NonIC").Cast(); /// /// Create a message entity based on input whole message raw bytes which is: 2bytes Len + 1 byte AppId + 1 byte SSK /// + variable length message code + variable length message body /// /// whole message raw bytes /// new created message entity public MessageTemplateBase GetMessageTemplateByRawBytes(byte[] bytes) { try { string debug = bytes.ToHexLogString();//be convenient to see log var type = GetMessageTemplateTypeByRawBytes(bytes); var targetInstance = (MessageTemplateBase)Activator.CreateInstance(type); return targetInstance; } catch (Exception ex) { throw new ArgumentException("exception message = " + ex.Message); } } /// /// Create a message entity based on input whole message raw bytes which is: 2bytes Len + 1 byte AppId + 1 byte SSK /// + variable length message code + variable length message body /// /// whole message raw bytes /// new created message entity private Type GetMessageTemplateTypeByRawBytes(byte[] bytes) { string debug = bytes.Select(s => s.ToString("X").PadLeft(2, '0')).Aggregate((acc, n) => acc + " " + n);//be convenient to see log //trace.TraceInformation("in the method GetMessageEntityTypeByRawBytes, debug=" + debug); // from protocol definition, the msg body started at 7th byte, and the 7th bytes is always the msg type code. var msgHandleCode = bytes.Skip(2).First(); var found = lookup.FirstOrDefault(a => a.CodeString == ("0x" + msgHandleCode.ToString("X").PadLeft(2, '0'))); if (found != null) { var t = Type.GetType(found.TypeRawString); return t; } else { throw new ArgumentException("Can't find correlated message entity type for incoming raw message bytes: " + bytes.Select(s => s.ToString("X").PadLeft(2, '0')).Aggregate((n, acc) => n + " " + acc)); } } } }