I am very new to firmware updates and the whole zephyr rtos. I am trying to perform a firmware update using the mcumgr. I ran into some problems. I read the documentation, but it's not very well written and even the autor phrased that it isn't even complete. So the problem is that i split up my bin file into packets and add the header (i think this is working), but when the transfer completes, the firmware isn't uploaded to any slot on the device. I am learning and implementing this code from boogie https://github.com/boogie/mcumgr-web
This is my code. The DfuSend method runs on a button click.
public async void DfuSend()
{
if (SelectedFirmwareFile == null)
{
await Application.Current.MainPage.DisplayAlert("Error", "No file selected", "OK");
return;
}
var service = await Globals.ConnectedDevice.GetServiceAsync(GattIdentifiers.UartGattSMPServiceId);
if (service != null)
{
try
{
sendCharacteristic = await service.GetCharacteristicAsync(GattIdentifiers.UartGattSMPCharacteristicsId);
receiveCharacteristic = await service.GetCharacteristicAsync(GattIdentifiers.UartGattSMPCharacteristicsId);
uploadIsInProgress = true;
sendCharacteristic.WriteType = CharacteristicWriteType.WithoutResponse;
FirmwareFileBytes = File.ReadAllBytes(SelectedFirmwareFile.FullName);
while (uploadIsInProgress == true)
{
await _uploadNext();
HandleUploadProgress(_uploadOffset);
}
sendCharacteristic.WriteType = CharacteristicWriteType.WithResponse;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
else
{
await Application.Current.MainPage.DisplayAlert("Error", "No service found", "OK");
}
The header bytes definition:
byte MGMT_OP_READ = 0;
byte MGMT_OP_READ_RSP = 1;
byte MGMT_OP_WRITE = 2;
byte MGMT_OP_WRITE_RSP = 3;
// Groups
byte MGMT_GROUP_ID_OS = 0;
byte MGMT_GROUP_ID_IMAGE = 1;
byte MGMT_GROUP_ID_STAT = 2;
byte MGMT_GROUP_ID_CONFIG = 3;
byte MGMT_GROUP_ID_LOG = 4;
byte MGMT_GROUP_ID_CRASH = 5;
byte MGMT_GROUP_ID_SPLIT = 6;
byte MGMT_GROUP_ID_RUN = 7;
byte MGMT_GROUP_ID_FS = 8;
byte MGMT_GROUP_ID_SHELL = 9;
// OS group
byte OS_MGMT_ID_ECHO = 0;
byte OS_MGMT_ID_CONS_ECHO_CTRL = 1;
byte OS_MGMT_ID_TASKSTAT = 2;
byte OS_MGMT_ID_MPSTAT = 3;
byte OS_MGMT_ID_DATETIME_STR = 4;
byte OS_MGMT_ID_RESET = 5;
// Image group
byte IMG_MGMT_ID_STATE = 0;
byte IMG_MGMT_ID_UPLOAD = 1;
byte IMG_MGMT_ID_FILE = 2;
byte IMG_MGMT_ID_CORELIST = 3;
byte IMG_MGMT_ID_CORELOAD = 4;
byte IMG_MGMT_ID_ERASE = 5;
private int _seq = 0;
and the uploadnext method:
private async Task _uploadNext()
{
if (_uploadOffset >= SelectedFirmwareFile.Length)
{
uploadIsInProgress = false;
HandleUploadFinished();
return;
}
if (uploadIsInProgress == false)
return;
const int nmpOverhead = 8;
var message = new ImageData();
if (_uploadOffset == 0)
{
message.len = Convert.ToInt32(SelectedFirmwareFile.Length);
using (var sha = SHA256.Create())
{
message.sha = sha.ComputeHash(await File.ReadAllBytesAsync(SelectedFirmwareFile.FullName));
}
}
//the encode function that i am trying to implement
var length = _mtu - Encode(message).Length - nmpOverhead;
message.data = new byte[SelectedFirmwareFile.Length - _uploadOffset > length ? length : SelectedFirmwareFile.Length - _uploadOffset];
Array.Copy(await File.ReadAllBytesAsync(SelectedFirmwareFile.FullName), _uploadOffset, message.data, 0, message.data.Length);
_uploadOffset += message.data.Length;
await SendMessage(MGMT_OP_WRITE, MGMT_GROUP_ID_IMAGE, IMG_MGMT_ID_UPLOAD, message);
}
And then i need to send the packet and encode it using CBOR. There is my code for the SendMessage method (i am really sure that it doesn't work)
async Task SendMessage(byte op, byte group, byte id, ImageData data)
{
var cborMessage = CBORObject.FromObject(new { op, group, id, seq = _seq++, data });
await sendCharacteristic.WriteAsync(cborMessage.EncodeToBytes());
}
BTW the characteristics use the SMP id.
I'll appreciate every comment or an idea. Thank you and have a nice day
Related
I am looking for a little help.
I have a program to communicate with a controller through Modbus TCP.
The only problem is I cannot extend the Nop from 125 to 400 because I got Illegal Data Address error message.
Could you please help me with this?
try
{
byte slaveid = 1;
byte function = 4;
ushort id = function;
ushort startAddress = 0;
uint NoP = 125;
byte[] frame = ReadInputRegistersMsg(id, slaveid, startAddress, function, NoP);
this.Write(frame); //data send to controller
Thread.Sleep(100);
byte[] buffReceiver = this.Read(); //data recieving from controller
int SizeByte = buffReceiver[8]; // Data what I got from the controller
UInt16[] temp = null;
if (function != buffReceiver[7])
{
byte[] byteMsg = new byte[9];
Array.Copy(buffReceiver, 0, byteMsg, 0, byteMsg.Length);
byte[] data = new byte[SizeByte];
textBox2.Text = Display(byteMsg);
byte[] errorbytes = new byte[3];
Array.Copy(buffReceiver, 6, errorbytes, 0, errorbytes.Length);
this.CheckValidate(errorbytes); // check the answer -> error message
}
else
{
byte[] byteMsg = new byte[9 + SizeByte];
Array.Copy(buffReceiver, 0, byteMsg, 0, byteMsg.Length);
byte[] data = new byte[SizeByte];
textBox2.Text = Display(byteMsg); // Show received messages in windows form app
Array.Copy(buffReceiver, 9, data, 0, data.Length);
temp = Word.ConvertByteArrayToWordArray(data); // Convert Byte[]-> Word[]
}
// Result
if (temp == null) return;
string result = string.Empty;
//foreach (var item in temp) // show all the data
for(int i=0;i<100;i++) // show the first 100 data
{
//result += string.Format("{0} ", item);
result += temp[i];
}
textBox3.Text = result; // insert the result into the textbox (windows form app)
}
catch
{
}
The ReadInputRegister Message is the following:
private byte[] ReadInputRegistersMsg(ushort id, byte slaveAddress, ushort startAddress, byte function, uint NoP)
{
byte[] frame = new byte[12];
frame[0] = (byte)(id >> 8); // Transaction Identifier High
frame[1] = (byte)id; // Transaction Identifier Low
frame[2] = 0; // Protocol Identifier High
frame[3] = 0; // Protocol Identifier Low
frame[4] = 0; // Message Length High
frame[5] = 6; // Message Length Low(6 bytes to follow)
frame[6] = slaveAddress; // Slave address(Unit Identifier)
frame[7] = function; // Function
frame[8] = (byte)(startAddress >> 8); // Starting Address High
frame[9] = (byte)startAddress; // Starting Address Low
frame[10] = (byte)(NoP >> 8); // Quantity of Registers High
frame[11] = (byte)NoP; // Quantity of Registers Low
return frame;
}
The hard limit for modbus is 125 NoP
i have a OBEXConnect and OBEXRequest custom functions, i am not using library for it
OBEXConnect function is as following
private bool OBEXConnect()
{
//send client request
byte[] ConnectPacket = new byte[7];
ConnectPacket[0] = 0x80; // Connect
ConnectPacket[1] = 0x00; // Packetlength Hi Byte
ConnectPacket[2] = 0x07; // Packetlength Lo Byte
ConnectPacket[3] = 0x10; // Obex v1
ConnectPacket[4] = 0x00; // no flags
ConnectPacket[5] = 0x20; // 8k max packet size Hi Byte
ConnectPacket[6] = 0x00; // 8k max packet size Lo Byte
stream.Write(ConnectPacket,0,ConnectPacket.Length);
//listen for server response
byte[] ReceiveBufferA = new byte[3];
stream.Read(ReceiveBufferA,0,3);
if (ReceiveBufferA[0] == 160) // 0xa0
{
//success, decode rest of packet
int plength = (0xff * ReceiveBufferA[1]) + ReceiveBufferA[2]; //length of packet is...
//listen for rest of packet
byte[] ReceiveBufferB = new byte[plength-3];
stream.Read(ReceiveBufferB,0,plength-3);
int obver = ReceiveBufferB[0]; //server obex version (16 = v1.0)
int cflags = ReceiveBufferB[1]; //connect flags
int maxpack = (0xff * ReceiveBufferB[2]) + ReceiveBufferB[3]; //max packet size
return true;
}
else
{
return false;
}
}
and here is OBEXRequest function
private int OBEXRequest(string tReqType, string tName, string tType, string tFileContent)
{
//send client request
int i;
int offset;
int packetsize;
byte reqtype = 0x82;
int tTypeLen = 0x03;
int typeheadsize;
int typesizeHi = 0x00;
int typesizeLo = 0x03;
//tName = "contact.vcf";
//tType = "text/x-vCard";
//tFileContent = "BEGIN:VCARD\r\nVERSION:2.1\r\nN:;aardvark\r\nFN:aardvark\r\nEND:VCARD\r\n";
if (tReqType == "GET")
{
reqtype = 0x83; // 131 GET-Final
}
if (tReqType == "PUT")
{
reqtype = 0x82; // 130 PUT-Final
}
packetsize = 3;
//Name Header
int tNameLength = tName.Length;
int nameheadsize = (3 + (tNameLength*2) + 2);
int namesizeHi = (nameheadsize & 0xff00)/0xff;
int namesizeLo = nameheadsize & 0x00ff;
packetsize = packetsize + nameheadsize;
if (tType != "")
{
//Type Header
tTypeLen = tType.Length;
typeheadsize = 3 + tTypeLen + 1;
typesizeHi = (typeheadsize & 0xff00)/0xff;
typesizeLo = typeheadsize & 0x00ff;
packetsize = packetsize + typeheadsize;
}
//Body
int fileLen = tFileContent.Length;
int fileheadsize = 3 + fileLen ;
int filesizeHi = (fileheadsize & 0xff00)/0xff;;
int filesizeLo = fileheadsize & 0x00ff;;
packetsize = packetsize + fileheadsize;
int packetsizeHi = (packetsize & 0xff00)/0xff;
int packetsizeLo = packetsize & 0x00ff;
byte[] tSendByte = new byte[packetsize];
//PUT-final Header
tSendByte[0] = reqtype; // Request type e.g. PUT-final 130
tSendByte[1] = Convert.ToByte(packetsizeHi); // Packetlength Hi
tSendByte[2] = Convert.ToByte(packetsizeLo); // Packetlength Lo
offset = 2;
//Name Header
tSendByte[offset+1] = 0x01; // HI for Name header
tSendByte[offset+2] = Convert.ToByte(namesizeHi); // Length of Name header (2 bytes per char)
tSendByte[offset+3] = Convert.ToByte(namesizeLo); // Length of Name header (2 bytes per char)
// Name+\n\n in unicode
byte[] tNameU = System.Text.Encoding.BigEndianUnicode.GetBytes(tName);
tNameU.CopyTo(tSendByte,offset+4);
offset = offset + 3 + (tNameLength*2);
tSendByte[offset+1] = 0x00; // null term
tSendByte[offset+2] = 0x00; // null term
offset = offset + 2;
if (tType != "")
{
//Type Header
tSendByte[offset+1] = 0x42; // HI for Type Header 66
tSendByte[offset+2] = Convert.ToByte(typesizeHi); // Length of Type Header
tSendByte[offset+3] = Convert.ToByte(typesizeLo); // Length of Type Header
for (i=0;i<=(tTypeLen-1);i++)
{
tSendByte[offset+4+i] = Convert.ToByte(Convert.ToChar(tType.Substring(i,1)));
}
tSendByte[offset+3+tTypeLen+1] = 0x00; // null terminator
offset = offset+3+tTypeLen+1;
}
//Body
tSendByte[offset+1] = 0x49; //HI End of Body 73
tSendByte[offset+2] = Convert.ToByte(filesizeHi); //
tSendByte[offset+3] = Convert.ToByte(filesizeLo); //1k payload + 3 for HI header
for (i=0;i<=(fileLen-1);i++)
{
tSendByte[offset+4+i] = Convert.ToByte(Convert.ToChar(tFileContent.Substring(i,1)));
}
//tSendByte[offset+4+fileLen] = 0x00; // null terminator
offset = offset+3+fileLen;
stream.Write(tSendByte,0,tSendByte.Length );
//listen for server response
//TODO: can hang here forever waiting response...
bool x = stream.DataAvailable; // changed bluetoothclient - public NetworkStream GetStream()
byte[] tArray4 = new byte[3];
stream.Read(tArray4,0,3);
x = stream.DataAvailable;
if (tArray4[0] == 160) // 0xa0
{
int plength = (tArray4[1] * 256) + tArray4[2] - 3;
byte[] tArray5 = new byte[plength];
if (plength >0)
{
stream.Read(tArray5,0,plength);
//TODO: data in returned packet to deal with
}
return 160;
}
if (tArray4[0] == 197) // 0xc5 Method not allowed
{
return 197;
}
if (tArray4[0] == 192) // 0xc0 Bad Request
{
return 192;
}
return 0;
}
i want to read the phone book of mobile but i not succeeded yet
i try on one samsung mobile it gives error bad request i follow the solutions above mentioned but when name = null then obexrequest function gives error
when i try it on huawei mobile it gives unknown error
i try this code as well it throw error that this method is not implemented
Read contacts using obex in c#
i call these functions like this
string tName = "";
string tType = "text/x-vCard";
string tFileContent = "";
int result = OBEXRequest("GET",tName,tType,tFileContent);
switch (result)
{
case 160: // 0xa0
addtolog("OK");
break;
case 197: // 0xc5
addtolog("Method not allowed");
break;
case 192: // 0xc0
addtolog("Bad Request");
break;
default:
addtolog("Other Error");
break;
}
can any body point out my mistake
I am trying to convert the dataObject's data to CF_HDROP format when a drag operation starts. I was able to read the byteArray, which I will store at some point, but for now I am hard-coding the path to a file that actually exists on my drive.
I have used this C# drag-drop problem as a reference.
Here my implementation for OleDragEnter function:
public int OleDragEnter(object pDataObj, int grfKeyState, long pt, ref int pdwEffect)
{
if (pDataObj is IDataObject dataOb)
{
IEnumFORMATETC formatetc = dataOb.EnumFormatEtc(DATADIR.DATADIR_GET);
List<FORMATETC> formatetcList = GetFormatEtcList(formatetc);
if (formatetcList.Exists(f => f.tymed == TYMED.TYMED_ISTREAM))
{
FORMATETC iStreamFormatetc = formatetcList.Find(f => f.tymed == TYMED.TYMED_ISTREAM);
dataOb.GetData(ref iStreamFormatetc, out var stgmedium);
MemoryStream memStream = GetIStream(stgmedium);
byte[] rawData = memStream.ToArray(); //I will store this on the drive at somepoint
var fileName = StreamHelpers.GetFullFileName(); //Constant for now
String[] strFiles = {fileName};
_DROPFILES dropFiles = new _DROPFILES();
int intChar, intFile, intDataLen, intPos;
IntPtr ipGlobal = IntPtr.Zero;
intDataLen = 0;
for (intFile = 0; intFile <= strFiles.GetUpperBound(0); intFile++)
{
intDataLen += strFiles[intFile].Length + 1;
}
intDataLen++;
var byteData = new Byte[intDataLen];
intPos = 0;
for (intFile = 0; intFile <= strFiles.GetUpperBound(0); intFile++)
{
for (intChar = 0; intChar < strFiles[intFile].Length; intChar++)
{
byteData[intPos++] = (byte)strFiles[intFile][intChar];
}
byteData[intPos++] = 0;
}
byteData[intPos++] = 0;
int intTotalLen = Marshal.SizeOf(dropFiles) + intDataLen;
ipGlobal = Marshal.AllocHGlobal(intTotalLen);
if (ipGlobal == IntPtr.Zero)
{
return -1;
}
dropFiles.pFiles = Marshal.SizeOf(dropFiles);
dropFiles.fWide = false;
Marshal.StructureToPtr(dropFiles, ipGlobal, false);
IntPtr ipNew = new IntPtr(ipGlobal.ToInt32() + Marshal.SizeOf(dropFiles));
Marshal.Copy(byteData, 0, ipNew, intDataLen);
var formatEtc = new FORMATETC
{
cfFormat = (short) CLIPFORMAT.CF_HDROP, //15
dwAspect = DVASPECT.DVASPECT_CONTENT,
lindex = -1,
tymed = TYMED.TYMED_HGLOBAL,
ptd = IntPtr.Zero
};
var stgMedium = new STGMEDIUM
{
unionmember = ipGlobal,
tymed = TYMED.TYMED_HGLOBAL,
pUnkForRelease = IntPtr.Zero
};
dataOb.SetData(ref formatEtc, ref stgMedium, false);
}
}
return 0;
}
I keep getting "Invalid FORMATETC structure" error on:
dataOb.SetData(ref formatEtc, ref stgMedium, false);
I have tried running the application in non-debug mode & verified the integrity of the file. I noticed that DATADIR.DATADIR_SET does not return any available formats. Could that be the problem?
Edit: It seems to also be happening when I try to use the same formatEtc Object and stgMedium Object used for reading the data without any change.
I have a server side app written in C
struct recv_packet
{
int magic;
int code;
int length;
char *body;
};
char send_buff[1024+1] = "";
ZeroMemory(&send_buff, 1024);
memset(send_buff, 'A', 1024);
//send_buff[1024] = '\0';
recv_packet rcv_pkt = { 0 };
rcv_pkt.magic = MAGIC;
rcv_pkt.code = 0;
rcv_pkt.length = strlen(send_buff);
rcv_pkt.body = send_buff;
int size = sizeof(rcv_pkt.magic) + sizeof(rcv_pkt.code) + sizeof(rcv_pkt.length) + 1024+1;
if (send(ClientSocket, (char *)&rcv_pkt, size, 0) == SOCKET_ERROR)
{
printf("Error %d\n", WSAGetLastError());
closesocket(ClientSocket);
WSACleanup();
return 1;
}
On the other side i grab this packet like this:
public struct recv_packet
{
public int magic;
public int code;
public int length;
public byte[] body;
};
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int port = 4000;
TcpClient client = new TcpClient("127.0.0.1", 4000);
NetworkStream nws = client.GetStream();
BinaryWriter bw = new BinaryWriter(nws);
BinaryReader br = new BinaryReader(nws);
byte[] buff = new byte[512];
send_packet pkt = new send_packet();
pkt.magic = magic;
pkt.cmd = (int)command.MOVE_MOUSE;
while (true)
{
bw.Write(pkt.magic);
bw.Write(pkt.cmd);
//br.Read(buff, 0, 512);
recv_packet rcv_pkt = new recv_packet();
rcv_pkt.magic = br.ReadInt32();
rcv_pkt.code = br.ReadInt32();
rcv_pkt.length = br.ReadInt32();
rcv_pkt.body = br.ReadBytes(rcv_pkt.length);
//string str = rcv_pkt.length.ToString();
string str = System.Text.Encoding.Default.GetString(rcv_pkt.body);
MessageBox.Show(str);
}
}
So it suppose that body will have only '65', but instead I've got some trash in it.
Why could this happen? Thank you for your time.
As I understood there are few ways of resolving this problem - one of them is to redecrlare struct a little bit and then creare a buffer, where all structure elements will be fitted one-by-one. So the solution looks like this:
char send_buff[1024+1] = "";
ZeroMemory(&send_buff, 1025);
memset(send_buff, 'A', 1024);
recv_packet *rcv_pkt = (recv_packet *)malloc(sizeof(recv_packet)+1024+1);
//recv_packet rcv_pkt = { 0 };
rcv_pkt->magic = MAGIC;
rcv_pkt->code = 0;
rcv_pkt->length = strlen(send_buff);
memcpy(rcv_pkt->body, send_buff, 1025);
int size = sizeof(rcv_pkt->magic) + sizeof(rcv_pkt->code) + sizeof(rcv_pkt->length) + 1024 + 1;
//printf("%d", size);
//getchar();
//return 0;
//if (send(ClientSocket, rcv_pkt.body, rcv_pkt.length, 0) == SOCKET_ERROR)
if (send(ClientSocket, (char *)rcv_pkt, size, 0) == SOCKET_ERROR)
I am working on a new machine at my works which is controlled via a PC. Current stuck on talking to a camera system that is connected via Ethernet.
Here is my code of opening a connection.
TcpClient client;
NetworkStream stream;
public bool OpenConnection()
{
client = new TcpClient();
try
{
//Camera.Open();
client.Connect("192.168.0.10", 8500);
stream = client.GetStream();
}
catch (Exception ex)
{
return false;
}
return true;
}
So far so good. Once the connection is open I then request some information from the camera
The message format I am using has STX(0x02) to indicate the start of the message and ETX(0x03) as the end of the message.
char StartOfPacket = (char)0x02;
char EndOfPacket= (char)0x03;
public bool RetrieveDigits(out string Digits)
{
// Send the trigger cammand to the vision system
Digits = "";
bool EverythingOK = true;
string DataToSend = StartOfPacket + "T1" + EndOfPacket;
byte[] buff = Encoding.ASCII.GetBytes(DataToSend);
if (LogCameraEvent != null)
LogCameraEvent(">> " + DataToSend);
try
{
stream.Write(buff, 0, buff.Length);
}
catch (Exception ex)
{
Logging.Instance.LogExceptionToFile(MethodBase.GetCurrentMethod(), ex);
EverythingOK = false;
}
Thread.Sleep(100);
byte[] buffer;
if (EverythingOK)
{
// Check the response
buffer = ReadCamera(10);
// Process the packets
string[] packets = ProcessPackets(buffer);
if (packets != null)
{
if (packets.Length > 0)
{
bool TriggerFound = false;
for (int i = 0; i < packets.Length; i++)
{
if (packets[i] == "T1")
{
TriggerFound = true;
continue;
}
else if (TriggerFound)
{
// If we are here then we should now be the data that was requested
if (string.IsNullOrEmpty(packets[i]))
{
Digits = packets[i-1]; // previous packet may have data from previous trigger. Need to look into why this happens.
}
else
Digits = packets[i];
EverythingOK = true;
break;
}
else
EverythingOK = false;
}
}
else
{
Console.WriteLine("No Packets Recieved");
EverythingOK = false;
}
}
else
{
Console.WriteLine("No Packets Recieved");
EverythingOK = false;
}
}
return EverythingOK;
}
Here is the part where I think the issue may lie, getting the response.
private byte[] ReadCamera(int ExpectedLength)
{
if(ExpectedLength < 1)
{
ExpectedLength = 100;
}
byte[] Buffer = new byte[ExpectedLength];
int read = 0;
int chunk;
while(stream.DataAvailable)
{
chunk = stream.Read(Buffer, read, Buffer.Length-read);
read += chunk;
// If we have reached the end of our buffer, check to see if theres any more information
if(read == Buffer.Length)
{
if(!stream.DataAvailable)
return Buffer;
// Nope. Resize the buffer, put the byte we've just read and continue
byte[] newBuffer = new byte[Buffer.Length * 2];
Array.Copy(Buffer, newBuffer, Buffer.Length);
Buffer = newBuffer;
//read++;
}
else if(!stream.DataAvailable)
return Buffer;
Thread.Sleep(50);
}
// Buffer is now too big, shrink it
byte[] ret = new byte[read];
Array.Copy(Buffer, ret, read);
return ret;
}
private string[] ProcessPackets(byte[] data)
{
// look for the stat char
List<string> Packets = new List<string>();
byte Start = 0x02;
bool StartFound = false;
byte End = 0x03;
StringBuilder sb = new StringBuilder();
for(int i =0; i<data.Length; i++)
{
if(StartFound)
{
// Check to see if its the end
if (data[i] == End)
{
Packets.Add(sb.ToString());
sb.Clear();
}
else
sb.Append(Encoding.ASCII.GetChars(data, i, 1));
}
// Find the start
if (!StartFound)
{
if (data[i] == Start)
{
StartFound = true;
}
}
}
return Packets.ToArray();
}
Let me explain what should happen and then what is happening. Through RetrieveDigits method I am sending "T1" to the camera. What the camera will do is respond with "T1" followed by 2 ascii characters, for now we will say AA. Using a diagnostic app on the camera system I can monitor the Ethernet and I see the following.
(>> means Received by Camera)
(<< means Sent from Camera)
>>[STX]T1[ETX]
<<[STX]T1[ETX][STX]AA[ETX]
So I see what the camera has sent. I confirmed the PC has has received the data using wire shark.
Now further down in the RetrieveDigits method you can see I process the packets received, loop through the packets until I find "T1" and then assume the next packet will be the data I am after and I set Digits to this value.
What I am finding is that sometimes when I run the app I see that Digits is set to "".
I am also finding that sometimes my data received will be "AA" then "T1" rather than "T1" then "AA". What I suspect is happening is that when its back to front, the "AA" is actually from the previous data sent from the camera and for some reason it was missed when reading from the stream.
Any idea why this could be happening as I am reading the data until Stream.Available is false.
Edit:
Modified the ReadCamera code to process the packets, reading 1 byte at a time.
private string[] ReadCamera(int ExpectedLength, int ExpectedPackets)
{
List<string> Packets = new List<string>();
bool StartFound = false;
StringBuilder sb = new StringBuilder();
if(ExpectedLength < 1)
{
ExpectedLength = 100;
}
byte[] Buffer = new byte[ExpectedLength];
int read = 0;
while (true)
{
read += stream.Read(Buffer, read, 1);
// Check to see if the byte read is the start of a packet
if (Buffer[read - 1] == StartOfPacket)
{
StartFound = true;
}
else if (StartFound)
{
// Check to see if the byte read is the end of a packet
if (Buffer[read - 1] == EndOfPacket)
{
Packets.Add(sb.ToString());
sb.Clear();
StartFound = false;
if (Packets.Count == ExpectedPackets)
break;
}
else
{
sb.Append(Encoding.ASCII.GetChars(Buffer, read - 1, 1));
}
}
}
// For Debuggin purposes
foreach(string s in Packets)
if (LogCameraEvent != null)
LogCameraEvent("<< " + s);
return Packets.ToArray();
}
and modified calling the method like so
// Check the response
string[] packets = ReadCamera(10,2);
// Process the packets
//string[] packets = ProcessPackets(buffer);