Example: Protocol configuration in event mode

An example of a NetLogic contained in the serial
Port
object that uses the event mode to read data sent asynchronously from a device. The
OnClick
method, linked to the button pressing event, enables you to stop the current reading and start a new reading.
To use the event mode, you must set the
Timeout
property to
0
. This way,
ReadBytes
will be blocking as long as the requested data do not arrive on the serial port.
You can stop the reading with the
CancelRead
method, or the
Close
method. In both cases, a
ReadCanceledException
exception is generated. To carry out a clean close of the NetLogic, you must terminate any pending read operations by calling the
Close
method in the NetLogic
Stop
.
You can download a sample project from SerialPortDemoEventMode.zip.
public class RuntimeNetlogic1 : BaseNetLogic { private SerialPort serialPort; private LongRunningTask task; public override void Start() { serialPort = (SerialPort)Owner; serialPort.Timeout = TimeSpan.FromMilliseconds(0.0); task = new LongRunningTask(Run, Owner); task.Start(); } [ExportMethod] public void OnClick() { // Cancel current read serialPort.CancelRead(); task.Cancel(); // Start new read task = new LongRunningTask(Run, Owner); task.Start(); } private void Run() { while(!task.IsCancellationRequested) { try { // Block until 3 bytes arrive on serial var result = serialPort.ReadBytes(3); foreach (var b in result) Log.Info(String.Format("0x{0:x2}", b)); } catch (ReadCanceledException ex) { // In case of read canceled, exit from the loop Log.Info(ex.Message); return; } catch (Exception e) { Log.Error(e.Message); } } } public override void Stop() { // Explicit call to Close to cancel pending read (if any) serialPort.Close(); task.Cancel(); } }
Provide Feedback
Have questions or feedback about this documentation? Please submit your feedback here.