I have input COM ports. I receive data from these like binary
. Problem is i can't convert binary
to object
.
I try this.
private void dataRecieved(object sender, SerialDataReceivedEventArgs e)
{
var dataLength = _serialPort.BytesToRead;
var data = new byte[dataLength];
int nbrData = _serialPort.Read(data, 0, dataLength);
var Data = _serialPort.Encoding.GetString(data);
}
public object ByteArrayToObject(byte[] arrBytes)
{
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream(arrBytes))
{
object obj = bf.Deserialize(ms);
return obj;
}
}
It throw exception this line object obj = bf.Deserialize(ms);
System.Runtime.Serialization.SerializationException: The input stream is not a valid binary format. The starting contents (in bytes) are: 02-02-CC-CC-33-33-53-40-33-33-83-40-66-66-A6-40-9A
How can solve this? Answers will be evaluated.
EDIT
I have Ardunio System. Ardunio send data like binary
format on SerialPort
. This data actually is object
. Object like this.
typedef struct MainCompPacket {
uint8_t status;
uint8_t sensorStatus;
float pressure; // mb
float accX; // g
float accY; // g
float accZ; // g
float gyroX; // deg/s
float gyroY; // deg/s
float gyroZ; // deg/s
double latitude;
double longitude;
} MainCompPacket;
I should get data in WPF app. I can't because this data is binary
format. I can't intervention Ardunio system. If i can, i change with sending json
format.
CodePudding user response:
As @padeso said. Binary format need scheme for converting to object.
Firstly i create struct c# side. same data scheme in binary. Second i create static method for converting process. Finally i used Marshal and converting binary to objects
public struct MainCompPacket
{
byte status;
byte sensorStatus;
float pressure; // mb
float accX; // g
float accY; // g
float accZ; // g
float gyroX; // deg/s
float gyroY; // deg/s
float gyroZ; // deg/s
double latitude;
double longitude;
public static MainCompPacket FromBytes(byte[] bytes)
{
GCHandle gcHandle = GCHandle.Alloc(bytes, GCHandleType.Pinned);
var data = (MainCompPacket)Marshal.PtrToStructure(gcHandle.AddrOfPinnedObject(), typeof(Data));
gcHandle.Free();
return data;
}
}