|
Hi Guys,
Just a quick question I have c# code working for communicating with a Serial device using the SerialPort Class (see code below):
private void SendEnq(bool blnIncStep)
{
if (blnIncStep)
{
iStep++;
}
byte[] c = new byte[]
{
0x05,
};
spBPDione.Write(c, 0, c.Length);
Console.WriteLine("OUT: " + ByteToHex(c));
}
private void DataRecvEvent()
{
int bytes = spBPDione.BytesToRead;
byte[] comBuffer = new byte[bytes];
spBPDione.Read(comBuffer, 0, bytes);
Console.WriteLine("IN: " + ByteToHex(comBuffer));
Console.WriteLine("STEP:" + iStep);
if (ByteToHex(comBuffer).Trim() == "06")
{
if (iStep >= 2)
{
}
else
{
byte[] c = new byte[] {
0x02, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31,
0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x31, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x03,
0x02
};
spBPDione.Write(c, 0, c.Length);
Console.WriteLine("OUT: " + ByteToHex(c));
iStep++;
}
}
else if (ByteToHex(comBuffer).Trim() == "07")
{
byte[] c = new byte[] {
0x04,
};
spBPDione.Write(c, 0, c.Length);
Console.WriteLine("OUT: " + ByteToHex(c));
iStep++;
}
else if (ByteToHex(comBuffer).Trim() == "05")
{
if (iStep >= 2)
{
byte[] c = new byte[] {
0x06,
};
spBPDione.Write(c, 0, c.Length);
Console.WriteLine("OUT: " + ByteToHex(c));
}
}
else if (ByteToHex(comBuffer).Trim().StartsWith("02"))
{
if (iStep >= 2)
{
byte[] c = new byte[] {
0x07,
};
spBPDione.Write(c, 0, c.Length);
Console.WriteLine("OUT: " + ByteToHex(c));
}
}
else if (ByteToHex(comBuffer).Trim() == "04")
{
if (iStep >= 2)
{
byte[] c = new byte[] {
0x06,
};
spBPDione.Write(c, 0, c.Length);
Console.WriteLine("OUT: " + ByteToHex(c));
}
}
}
Now this works and will do what its supposed to on the device it is not very nice clean maintainable code, could i refactor this into a class that follows the following protocol to make the code more readable and OO.
My System DIRECTION Physical Device
ENQ (05) ->
<- ACK0 (06)
STX (message) ETX LRC ->
<- ACK1 (07)
EOT (04) ->
<- ACK0 (06)
<- ENQ (05)
ACK0 (06) ->
<- STX (message) ETX LRC
ACK1 (07) ->
<- EOT (04)
ACK0 (06) ->
|
|
|
|
|
There are many ways to implement a comm protocol, the best one very much depends on the requirements on reliability, robustness and performance. Here are two extremes:
1.
A very easy approach would do everything in a synchronous way, which means NOT using events (e.g. DataReceived); e.g. have a separate thread that basically does what your protocol diagram shows, including some explicit delays:
Write ENQ
Wait 100
Read 1 and check for ACK0
Write STX msg ETX LRC
Wait 100
Read 1 and check for ACK1
...
The waits are necessary if you want a good chance of getting the next input all in one read(buf); if you read too early, you might get a partial message.
Warning: You have to decide what should happen when something unexpected is read!
2.
The general approach would be completely asynchronous, and it would use a state machine, so the DataReceived handler would consist of a big switch on the state variable, and a number of cases each handling one input line of your protocol diagram. Here too you must make sure your diagram is complete, i.e. in each state what should happen if arbitrary stuff is received?
And then you should also take care of time-outs: what when no data at all, or an insufficient amount of data, is received? Your app probably doesn't want to wait forever...
|
|
|
|
|
Thanks Luc.
Is the If / Else block in my code not already doing what you talk about with the State Machine pattern?
|
|
|
|
|
Not really, you are switching/if-ing on the incoming data; a real state machine would switch on its own state (i.e. on what it expects), not on what it gets. What it gets would make it change states.
If you are fortunate enough to have a situation where one party is basically asking questions (e.g. all starting with a different byte value) which the other party is to answer in one message, then that isn't really a protocol, and you obviously can switch on the question, as there then is no state whatsoever.
|
|
|
|
|
Hi Luc,
Quick question, I have created a class for the message protocol using States I think, i'm just wondering if this is the correct approach:
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace TEST
{
public class clsTEST
{
public enum CurrentCommsState
{
Idle,
SentENQ,
RecvdENQ,
SentACK0,
RecvdACK0,
SentACK1,
RecvdACK1,
SentMessage,
RecvdMessage,
SentEOT,
RecvdEOT
}
private enum MessageDirection
{
In,
Out
}
public CurrentCommsState TheState = new CurrentCommsState();
private MessageDirection TheDirection = new MessageDirection();
private SerialPort spTest= null;
private byte[] btRecvdMsg = new byte[200];
public clsOpenShift(SerialPort spTheSP)
{
spTEST= spTheSP;
TheState = CurrentCommsState.Idle;
TheDirection = MessageDirection.Out;
}
public void SendAndRecv(out byte[] TheBufferRecvd)
{
TheBufferRecvd = new Byte[200];
if (SendMsg())
{
if (RecvMsg(ref btRecvdMsg, 1))
{
Array.Copy(btRecvdMsg, TheBufferRecvd, 200);
}
}
else if (RecvMsg(ref btRecvdMsg, 1))
{
if (SendMsg())
{
}
}
}
private bool RecvMsg(ref byte[] btOutRecvd, int iBytesToRecv)
{
bool blnRetVal = false;
try
{
while (spOpenShiftSP.BytesToRead == 0)
{
System.Threading.Thread.Sleep(100);
}
byte[] theBuffer = new byte[iBytesToRecv];
spTEST.Read(theBuffer, 0, iBytesToRecv);
ChangeState(theBuffer);
Array.Copy(theBuffer, btOutRecvd, theBuffer.Length);
blnRetVal = true;
}
catch (Exception e)
{
blnRetVal = false;
}
return blnRetVal;
}
private bool SendMsg()
{
bool blnRetVal = false;
try
{
byte[] btToSend = MessageToSend();
ChangeState(btToSend);
if (btToSend != null)
{
spTEST.Write(btToSend, 0, btToSend.Length);
blnRetVal = true;
}
else
{
blnRetVal = false;
}
}
catch (Exception e)
{
blnRetVal = false;
}
return blnRetVal;
}
private void ChangeState(byte[] theMessage)
{
if (TheState == CurrentCommsState.Idle)
{
TheState = CurrentCommsState.SentENQ;
}
else if (TheState == CurrentCommsState.SentENQ &&string.Compare(ByteToHex(theMessage).Trim(),"THE CORRECT ACK (EITHER 06 or 07)") == 0)
{
}
}
private byte[] MessageToSend()
{
if (TheState == CurrentCommsState.Idle)
{
byte[] ENQ = new byte[] { 0x05 };
return ENQ;
}
else if (TheState == CurrentCommsState.SentENQ)
{
byte[] STX_MSG_ETX_LRC = new byte[] {
0x02, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31,
0x30, 0x30, 0x30, 0x30, 0x31, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x31, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x31, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x03,
0x02
};
return STX_MSG_ETX_LRC;
}
else if(TheState == CurrentCommsState.SentMessage)
{
byte[] EOT = new byte[] { 0x04 };
return EOT;
}
else if (TheState == CurrentCommsState.SentEOT)
{
return null;
}
else
{
return new byte[1];
}
}
private string ByteToHex(byte[] comByte)
{
StringBuilder builder = new StringBuilder(comByte.Length * 3);
foreach (byte data in comByte)
{
builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
}
return builder.ToString().ToUpper();
}
}
}
I will eventually change the STX_Msg to use Member Vars to populate the correct message not a hardcoded set of values as it is currently.
Also calling the code like so:
byte[] btRecvdMsg = null;
clsTest COMMS = new clsTest(spSerialPort);
while (COMMS.TheState != clsTest.CurrentCommsState.RecvdEOT)
{
COMMS.SendAndRecv(out btRecvdMsg);
System.Threading.Thread.Sleep(100);
}
Am I on the right tracks here?
Thanks in Advance
|
|
|
|
|
Hi Keith,
KeithF wrote: Am I on the right tracks here?
yes, well, maybe. I did not study your code in much detail, I do see a state-machine-like approach, which could be fine; however I have issues in several aspects:
1. I'm not sure I know enough about your "protocol" to judge the approach. As I said, what you need as an implementation heavily depends on your protocol.
e.g. what should happen when an unexpected response is received (say you send an ENQ and then receive an ETX where it "should" have been an ACK)
2. I didn't see your actual transmit and receive operations; is your receiver operating asynchronously (i.e. using a completion event)? or blocking (i.e. just read-and-wait-till-done)?
3. You seem to somewhat merge, then split, inbound and outbound messages; not sure why.
4. Whatever the goals and needs, I'm pretty sure my code would look quite differently, but that is a matter of style. In particular I'm not fond of methods that need data, don't get it as a parameter, and then go fetch it somehow (as your SendMsg-MessageToSend pair is doing).
Here is what I might consider doing if your protocol is somewhat close to what I think you intend:
- I would opt for (pseudo)synchronous transmit and asynchronous receive;
- so I would transmit using SP.Write() and act as if the data is gone instantly (if necessary just include a sleep period that corresponds to the normal transmission time, probably not necessary at all);
- and I would not read except inside the DataReceived handler.
- that would halve the number of states I need, as each state typically would be an "awaiting" state, say "waiting for ACK0";
DataReceived should check the next inbound message;
if it is an ACK0, send a new message (synchronously!), adapt the state (say "waiting for "ACK1"), and return;
if it isn't, send a new message ("aborting"), set state="IDLE" (=waiting for anything), and return;
- so that boils down to a big switch inside DataReceived, switching to the current state (what am I expecting?), then looking at what actually was received, react (probably by sending something) and adapt the state, so the next DataReceived switch will go to another case.
That would work for simple cases; it would not cope well with slow transmission conditions: if you want overlaps (comparable to overlapped file I/O in Windows) or if your state actions are too large to handle in DataReceived itself, you may need a more complex scheme, maybe an input queue, etc.
Hope this helps. But once again, as I said, it all depends on what you need. It would not make sense to create a 1000 LOC class for a thermometer that sends one or two strings per second.
|
|
|
|
|
Dear developers,
Does someone knows how can I iterate all open child forms from the mdi parent
And for each form save the report to one excel file?
|
|
|
|
|
Hope thsi will help you
foreach (Form frm in Application.OpenForms)
{
}
I Love T-SQL
"VB.NET is developed with C#.NET"
If my post helps you kindly save my time by voting my post.
|
|
|
|
|
hi,
the problem i accessing the reports from each form and saving it to one workbook
is it possible?
foreach(Form frm in this.MdiChildren) {
saving each report to a workbook
}
|
|
|
|
|
|
How To Convert The English To Gujarati in The Asp.net With C#
|
|
|
|
|
Language translation, even between similar languages (which Gujarati and English aren't) is not a facile task.I suggest you use an online service like google translate, or find a commercial product that does this. Even so, no translation software is 100% accurate.
|
|
|
|
|
This[^] is a fairly complete guide on this topic.
Its always easier to plan localization in advance (before development starts).
If the site already exists, it will be harder to implement localization.
|
|
|
|
|
|
Hi,
i work with asp.net c#, how can we insert multiple lines text (label) in a single row of datagridview?
Thank you verry mutch.
|
|
|
|
|
Probably by asking in the ASP.NET forum!
Unrequited desire is character building. OriginalGriff
I'm sitting here giving you a standing ovation - Len Goodman
|
|
|
|
|
|
Hey All,
Just d/l your checkers game...http://www.codeproject.com/KB/game/DirectXBoardGameEngine.aspx[^]
However when I open it I am asked to convert it. When I try to build the game it says 'TypeLoadException was unhandled'
Method 'Initialize' in type 'Bornander.Games.Checkers.Direct3D.CheckersModelRepository' from assembly 'Bornander Games Checkers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.
Please advise?
Thanks in advance
|
|
|
|
|
You haven't downloaded my code here, you've downloaded Frederik Bornander's code from that article. Funnily enough, there's a forum at the bottom of the article (all the articles have forums) where you can ask THE ORIGINAL AUTHOR about their code. After all, they are the experts in their code and they are best placed to answer your questions.
|
|
|
|
|
|
MSDN wrote: The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.
|
|
|
|
|
Thanks.
|
|
|
|
|
The ?? is known as the null coalescing operator. That's a fancy dance way of saying that it tests to see if the left hand side is null, and if it is, it uses the right hand side. What this is doing, in your example, is evaluate items to see if it's null, and if it is, it assigns a new list to it and returns that. In practical terms, this is the same as doing this:
if (items == null)
items = new List<Item>();
return items I have missed the addition of the Item instances to the array to simplify this example, but you should get the idea from it.
[Edit]The OP deleted the original message. It was:
public class Item
{
public double X { get; set; }
public double Y { get; set; }
public string Name { get; set; }
public string Color { get; set; }
}
public class ItemsFactory
{
private List items;
public IEnumerable Items
{
get
{
return items ?? (items = new List<item>()
{
new Item { Name = "One", X = 33, Y = 25, Color = "Red" }, new
new Item { Name = "Two", X = 44, Y = 99, Color"Blue" }
});
}
}
}
modified 14-Nov-11 6:11am.
|
|
|
|
|
You put it much better than MSDN!
It’s not because things are difficult that we do not dare, it’s because we do not dare that things are difficult. ~Seneca
|
|
|
|
|
Thanks Annie. That's because, unlike MSDN, I'm trying to educate.
|
|
|
|
|