/// <summary> /// 串口数据接收回调 /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private static void SerialPortInput_MessageReceived(object sender, MessageReceivedEventArgs args) { Console.WriteLine("收到: " + BitConverter.ToString(args.Data)); //获取msgid用来分辨是环境应答还是控制应答 uint msgid = BitConverter.ToUInt16(args.Data, 4); //环境数据应答 if (msgid == 2) { Console.WriteLine("收到环境应答"); DataTemp.EnvData = PortEnvResponse.UnPack(args.Data); DataTemp.DateTime = DateTime.Now; } //控制应答 else if (msgid == 4) { Console.WriteLine("收到控制应答"); DataTemp.portControlResponse = PortControlResponse.Unpack(args.Data); } else { Console.WriteLine($"串口应答msgid为{msgid}, 无法解析"); } }
internal static HttpEnvResponse Pack(PortEnvResponse portEnvResponse) { HttpEnvResponse httpEnvResponse = new HttpEnvResponse(); httpEnvResponse.RoomID = "1"; httpEnvResponse.temp = portEnvResponse.temp.ToString(); httpEnvResponse.light = portEnvResponse.light.ToString(); httpEnvResponse.humi = portEnvResponse.humi.ToString(); httpEnvResponse.human = portEnvResponse.human.ToString(); httpEnvResponse.co = portEnvResponse.co.ToString(); httpEnvResponse.pm25 = portEnvResponse.pm25.ToString(); return(httpEnvResponse); }
internal static PortEnvResponse UnPack(byte[] receiveData) { PortEnvResponse portEnvResponse = new PortEnvResponse(); portEnvResponse.cmn = BitConverter.ToUInt32(receiveData, 0); portEnvResponse.msgId = BitConverter.ToUInt16(receiveData, 4); portEnvResponse.msgLen = BitConverter.ToUInt16(receiveData, 6); portEnvResponse.temp = BitConverter.ToUInt16(receiveData, 8); portEnvResponse.light = BitConverter.ToUInt16(receiveData, 10); portEnvResponse.humi = BitConverter.ToUInt16(receiveData, 12); portEnvResponse.human = Convert.ToUInt16(BitConverter.ToChar(receiveData, 14)); portEnvResponse.co = BitConverter.ToUInt16(receiveData, 15); portEnvResponse.pm25 = BitConverter.ToUInt16(receiveData, 17); return(portEnvResponse); }