public static T ToObject <T>(byte[] data) { T item = (T)Activator.CreateInstance(typeof(T)); object o = (object)item; ByteMethods.ToObject(data, ref o); return((T)o); }
private void SP_DataReceived(object sender, SerialDataReceivedEventArgs e) { try { byte[] bf = new byte[SP.BytesToRead]; SP.Read(bf, 0, bf.Length); RX_Buffer.AddRange(bf); // Search for packages for (int i = 0; i < RX_Buffer.Count; i++) { if (RX_Buffer[i] == '$' && RX_Buffer[i + 1] == '&' && RX_Buffer.Count - i > 4) { int length = BitConverter.ToUInt16(RX_Buffer.ToArray(), i + 2); int id = RX_Buffer[i + 4]; byte[] data = new byte[length]; if (length + i > RX_Buffer.Count && length < 128) { break; } ByteMethods.memcpy(data, RX_Buffer.ToArray(), length, 0, i + 5); DevicePacket packet = new DevicePacket { Data = data, ID = id, Length = length }; if (RX != null) { RX(packet, this); } // Done if (length + i > RX_Buffer.Count) { RX_Buffer.Clear(); } else { RX_Buffer.RemoveRange(i, length + 5); } } } if (RX_Buffer.Count > 300) { RX_Buffer.Clear(); } } catch (Exception ex) { } }
private void TX_Sync(DevicePacket devicePacket) { DashboardPacket packet = new DashboardPacket(); packet.Sync1 = '$'; packet.Sync2 = '&'; packet.length = (UInt16)(devicePacket.Length); packet.id = (byte)devicePacket.ID; // Write header byte[] bPacket = ByteMethods.ToBytes(packet); SP.Write(bPacket, 0, 5); // Write packet data SP.Write(devicePacket.Data, 0, devicePacket.Length); // Write junk incase bytes are missed on embedded system. // This way there is a better chance the next package is received. byte[] bf = new byte[2]; bf[0] = 0; bf[1] = 0; SP.Write(bf, 0, 2); }