C# SerialPort API
Collaboration diagram for C# SerialPort API:

Modules

 Events related with SerialPort Service
 

Classes

class  SerialPortManager
 Implementation of ISerialPortManager. Start point for interacting with Deepsy SerialPort service More...
 
interface  ISerialPort
 Interface for SerialPort Service More...
 
interface  ISerialPortManager
 Serial Port Manager allows to manage the serial port connections devices running deepsy More...
 

Detailed Description

To work with Deepsy SerialPort Manager service it is necessary to use SerialPortManager located in GMV.ITS.HAL.DEEPSY.SerialPort.Facade for getting the initial SerialPortManager object.

SerialPortManager SerialPortManager = new SerialPortManager("");


SerialPortManager has an optional parameter indicating the ip address of remote service. For instance:

SerialPortManager SerialPortManager = new SerialPortManager("172.22.198.103");


SerialPortManager implements IDisposable. It can hold resources (such as socket handles) until it is disposed. The Dispose method is automatically called when existing a using or try / catch block, for which the object has been declared. This construction ensures prompt release, avoiding resource exhaustion exceptions and errors that may otherwise occur.

  • * SerialPortManager SerialPortManager= null;
    try{
    SerialPortManager = new SerialPortManager("172.22.198.103");
    List<ISerialPort> SerialPorts = SerialPortManager.GetSerialPortList().ToList();
    } catch (Exception e) {
    throw e;
    }
    SerialPortManager.Dispose();

Examples

  • Get SerialPorts
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace GMV.ITS.HAL.DEEPSY.Examples.SerialPort
    {
    public class ListSerialPorts
    {
    static void Main(string[] args)
    {
    string deepsyServerIp = args.Length == 0 ? "192.168.0.50" : args[0];
    using (SerialPortManager serialPortManager = new SerialPortManager(deepsyServerIp))
    {
    List<ISerialPort> listSerialPorts = serialPortManager.GetSerialPortList().ToList();
    Console.WriteLine($"There are {listSerialPorts.Count()} SerialPorts");
    foreach (ISerialPort serialPort in listSerialPorts)
    {
    Console.WriteLine($"Serial Port id : {serialPort.Portid}");
    Console.WriteLine($"{"Alias", 20} : {serialPort.Configuration.Alias}");
    Console.WriteLine($"{"Protocol", 20} : {serialPort.Configuration.Protocol}");
    Console.WriteLine($"{"Baud Rate", 20} : {serialPort.Configuration.Baudrate}");
    Console.WriteLine($"{"Data bits", 20} : {serialPort.Configuration.Databits}");
    Console.WriteLine($"{"Stop Bits", 20} : {serialPort.Configuration.Stopbits}");
    Console.WriteLine($"{"Parity", 20} : {serialPort.Configuration.Parity}");
    Console.WriteLine($"{"Flow Control", 20} : {serialPort.Configuration.Flowcontrol}");
    Console.WriteLine($"{"Address", 20} : {serialPort.Information.Address}");
    Console.WriteLine($"{"RS485 pinout", 20} : {serialPort.Information.RS485pinout}");
    Console.WriteLine($"{"RS485 txen", 20} : {serialPort.Information.RS485txen}");
    Console.WriteLine($"{"Allowed Protocols", 20} : ");
    serialPort.Information.ProtocolsAllowed.ForEach(p => Console.WriteLine($"{"- " + p.ToString(), 20}"));
    }
    }
    }
    }
    }

  • Set SerialPort Configuration
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace GMV.ITS.HAL.DEEPSY.Examples.SerialPort
    {
    public class SetSerialPortConfiguration
    {
    static void Main(string[] args)
    {
    string deepsyServerIp = args.Length == 0 ? "192.168.0.50" : args[0];
    using (SerialPortManager serialPortManager = new SerialPortManager(deepsyServerIp))
    {
    List<ISerialPort> listSerialPorts = serialPortManager.GetSerialPortList().ToList();
    Console.WriteLine($"There are {listSerialPorts.Count()} SerialPorts");
    ISerialPort serialPort = listSerialPorts.FirstOrDefault();
    if (serialPort != null)
    {
    string portID = serialPort.Portid;
    string currentAlias = serialPort.Configuration.Alias;
    SerialPortProtocol.Protocol currentProtocol = serialPort.Configuration.Protocol;
    int currentBaudrate = serialPort.Configuration.Baudrate;
    Console.WriteLine($"Initial configuration");
    Console.WriteLine($"{"Alias",20} : {serialPort.Configuration.Alias}");
    Console.WriteLine($"{"Protocol",20} : {serialPort.Configuration.Protocol}");
    Console.WriteLine($"{"Baud Rate",20} : {serialPort.Configuration.Baudrate}");
    ISerialPortConfiguration configuration = serialPort.Configuration;
    configuration.Alias = "New Alias";
    configuration.Protocol = SerialPortProtocol.Protocol.RS485;
    configuration.Baudrate = 115200;
    serialPort.SetConfiguration(configuration);
    ISerialPort serialPort2 = serialPortManager.GetSerialPortList().FirstOrDefault(p => p.Portid == portID);
    Console.WriteLine($"New configuration");
    Console.WriteLine($"{"Alias",20} : {serialPort2.Configuration.Alias}");
    Console.WriteLine($"{"Protocol",20} : {serialPort2.Configuration.Protocol}");
    Console.WriteLine($"{"Baud Rate",20} : {serialPort2.Configuration.Baudrate}");
    //Set configuration as it was
    ISerialPortConfiguration currentConfiguration = serialPort.Configuration;
    configuration.Alias = currentAlias;
    configuration.Protocol = currentProtocol;
    configuration.Baudrate = currentBaudrate;
    serialPort.SetConfiguration(currentConfiguration);
    }
    }
    }
    }
    }

  • Subscrive to SerialPort events
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    namespace GMV.ITS.HAL.DEEPSY.Examples.SerialPort
    {
    class SubscribeSerialPortEvents
    {
    static void Main(string[] args)
    {
    string deepsyServerIp = args.Length == 0 ? "192.168.0.50" : args[0];
    string Portid = "COM1";
    using (SerialPortManager serialPortManager = new SerialPortManager(deepsyServerIp))
    {
    List<ISerialPort> list = serialPortManager.GetSerialPortList().ToList();
    ISerialPort serialPort = list.Where(a => a.Portid == Portid).FirstOrDefault();
    serialPort.ReceiveMessageEvent += SerialPort_MessageReceivedEvent;
    Console.WriteLine("Press any key for exit");
    Console.ReadKey();
    }
    }
    private static void SerialPort_MessageReceivedEvent(object sender, ISerialPortMessageReceivedEvent e)
    {
    Console.WriteLine($"MessageReceived Event. SerialPort {e.Portid}");
    Console.WriteLine($"{"Data",20} : {StringToHex(e.Data)}");
    Console.WriteLine($"{"Data Byte",20} : {String.Join("-", e.Data)}");
    Console.WriteLine($"{"Data Hex",20} : {BitConverter.ToString(e.Data)}");
    }
    private static string StringToHex(byte[] data)
    {
    StringBuilder sb = new StringBuilder();
    foreach (byte b in data)
    {
    if (char.IsControl((char)b) || b > 127)
    {
    sb.Append("\\x");
    sb.Append(b.ToString("x2").ToUpper());
    }
    else
    {
    sb.Append((char)b);
    }
    }
    return sb.ToString();
    }
    }
    }

  • Send Message
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Text;
    namespace GMV.ITS.HAL.DEEPSY.Examples.SerialPort
    {
    public class SendSerialPortMessage
    {
    static void Main(string[] args)
    {
    string deepsyServerIp = args.Length == 0 ? "192.168.0.50" : args[0];
    string Portid = "COM1";
    using (SerialPortManager serialPortManager = new SerialPortManager(deepsyServerIp))
    {
    List<ISerialPort> listSerialPorts = serialPortManager.GetSerialPortList().ToList();
    Console.WriteLine($"There are {listSerialPorts.Count()} SerialPorts");
    ISerialPort serialPort = listSerialPorts.Where(a => a.Portid == Portid).FirstOrDefault();
    if (serialPort != null)
    {
    string message = "Hey\x2C\nhow are you\x3f\nBye.";
    byte[] dataHead = { 0x05, 0x10, 0x1E };
    Encoding code = Encoding.GetEncoding("iso-8859-1");
    byte[] dataFromStr = code.GetBytes(message);
    byte[] data = dataHead.Concat(dataFromStr).ToArray();
    Console.WriteLine($"Message sent to \"{Portid}\":");
    Console.WriteLine($"{"Data",20} : {StringToHex(data)}");
    Console.WriteLine($"{"Data Hex",20} : {BitConverter.ToString(data)}");
    // Send message
    serialPort.Send(data);
    Console.WriteLine($"Execution finished.");
    }
    }
    }
    private static string StringToHex(byte[] data)
    {
    StringBuilder sb = new StringBuilder();
    foreach (byte b in data)
    {
    if (char.IsControl((char)b) || b > 127)
    {
    sb.Append("\\x");
    sb.Append(b.ToString("x2").ToUpper());
    }
    else
    {
    sb.Append((char)b);
    }
    }
    return sb.ToString();
    }
    }
    }

  • Send multiple messages using console
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text.RegularExpressions;
    using System.Text;
    namespace GMV.ITS.HAL.DEEPSY.Examples.SerialPort
    {
    public class SendSerialPortMessageFromConsole
    {
    static void Main(string[] args)
    {
    string deepsyServerIp = args.Length == 0 ? "192.168.0.50" : args[0];
    string Portid = "COM1";
    using (SerialPortManager serialPortManager = new SerialPortManager(deepsyServerIp))
    {
    List<ISerialPort> listSerialPorts = serialPortManager.GetSerialPortList().ToList();
    Console.WriteLine($"There are {listSerialPorts.Count()} SerialPorts");
    ISerialPort serialPort = listSerialPorts.Where(a => a.Portid == Portid).FirstOrDefault();
    if (serialPort != null)
    {
    string portID = serialPort.Portid;
    while (true)
    {
    Console.WriteLine($"Write the message to be send to the port: {portID}");
    Console.WriteLine($"\tWrite \"quit\" to close");
    string message = Console.ReadLine();
    // Only needed when writing message from Console
    message = Regex.Unescape(message);
    if (message == "quit") break;
    Encoding code = Encoding.GetEncoding("iso-8859-1");
    byte[] data = code.GetBytes(message);
    Console.WriteLine($"Message sent to \"{Portid}\":");
    Console.WriteLine($"{"Data",20} : {StringToHex(data)}");
    Console.WriteLine($"{"Data Hex",20} : {BitConverter.ToString(data)}");
    // Send message
    serialPort.Send(data);
    }
    Console.WriteLine($"Execution finished.");
    }
    }
    }
    private static string StringToHex(byte[] data)
    {
    StringBuilder sb = new StringBuilder();
    foreach (byte b in data)
    {
    if (char.IsControl((char)b) || b > 127)
    {
    sb.Append("\\x");
    sb.Append(b.ToString("x2").ToUpper());
    }
    else
    {
    sb.Append((char)b);
    }
    }
    return sb.ToString();
    }
    }
    }

  • Send and receive messages with J1708 and receive their echo

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.IO;
    using System.Text;
    namespace GMV.ITS.HAL.DEEPSY.Examples.SerialPort
    {
    public class SendAndReceiveEchoJ1708
    {
    static void Main(string[] args)
    {
    string deepsyServerIp = args.Length == 0 ? "192.168.1.140" : args[0];
    string Portid = "COM2";
    using (SerialPortManager serialPortManager = new SerialPortManager(deepsyServerIp))
    {
    Console.WriteLine($"Finding SerialPort {Portid}");
    List<ISerialPort> list = serialPortManager.GetSerialPortList().ToList();
    ISerialPort serialPort = list.Where(a => a.Portid == Portid).FirstOrDefault();
    if (serialPort == null)
    {
    Console.WriteLine($"SerialPort {Portid} not found");
    }
    Console.WriteLine($"SerialPort {Portid} found successfully");
    Console.WriteLine($"Configuring SerialPort {Portid}");
    if (!Configure(serialPort))
    {
    Console.WriteLine($"Error configuring SerialPort {Portid}");
    }
    Console.WriteLine($"SerialPort {Portid} configured successfully");
    Console.WriteLine($"Subscribing to SerialPort {Portid} messages");
    serialPort.ReceiveMessageEvent += SerialPort_MessageReceivedEvent;
    Console.WriteLine($"Sending frame 1");
    byte[] data1 = new byte[] { 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00 };
    byte[] frame1 = ParseToJ1708(0x7D, 0x42, data1);
    serialPort.Send(frame1);
    Console.WriteLine($"Waiting time before send next message");
    System.Threading.Thread.Sleep(250);
    Console.WriteLine($"Sending frame 2");
    byte[] data2 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09 };
    byte[] frame2 = ParseToJ1708(0x7D, 0x42, data2);
    serialPort.Send(frame2);
    Console.WriteLine($"Waiting time before send next message");
    System.Threading.Thread.Sleep(250);
    Console.WriteLine($"Sending frame 3");
    byte[] data3 = new byte[] { 0x45, 0x50, 0x32, 0x30, 0x30 };
    byte[] frame3 = ParseToJ1708(0x7D, 0x42, data3);
    serialPort.Send(frame3);
    Console.WriteLine("Press any key for exit");
    Console.ReadKey();
    }
    }
    private static void SerialPort_MessageReceivedEvent(object sender, ISerialPortMessageReceivedEvent e)
    {
    Console.WriteLine($"MessageReceived Event. SerialPort {e.Portid}");
    Console.WriteLine($"{"Data",20} : {StringToHex(e.Data)}");
    Console.WriteLine($"{"Data Byte",20} : {String.Join("-", e.Data)}");
    Console.WriteLine($"{"Data Hex",20} : {BitConverter.ToString(e.Data)}");
    }
    private static byte[] ParseToJ1708(byte mid, byte pid, byte[] data)
    {
    List<byte> frame = new List<byte>();
    frame.Add(mid);
    frame.Add(pid);
    frame.AddRange(data);
    byte checksum = (byte)(256 - (frame.Sum(v => Convert.ToByte(v)) & 255));
    frame.Add(checksum);
    return frame.ToArray();
    }
    private static bool Configure(ISerialPort serialPort)
    {
    try
    {
    string portID = serialPort.Portid;
    string currentAlias = serialPort.Configuration.Alias;
    ISerialPortConfiguration configuration = serialPort.Configuration;
    configuration.Alias = currentAlias;
    configuration.Baudrate = 9600;
    configuration.Databits = 8;
    configuration.Flowcontrol = SerialPortFlowControl.FlowControl.NONE;
    configuration.Parity = SerialPortParity.Parity.NONE;
    configuration.Protocol = SerialPortProtocol.Protocol.RSJ1708;
    configuration.Stopbits = 1;
    serialPort.SetConfiguration(configuration);
    return true;
    }
    catch (HalException deepsyEx)
    {
    Console.WriteLine($"Deepsy error : {deepsyEx.ErrorCode}");
    }
    catch (Exception ex)
    {
    Console.WriteLine($"Error Not Handled exception {ex.Message}");
    }
    return false;
    }
    private static string StringToHex(byte[] data)
    {
    StringBuilder sb = new StringBuilder();
    foreach (byte b in data)
    {
    if (char.IsControl((char)b) || b > 127)
    {
    sb.Append("\\x");
    sb.Append(b.ToString("x2").ToUpper());
    }
    else
    {
    sb.Append((char)b);
    }
    }
    return sb.ToString();
    }
    }
    }