Skip to content

Deal with non-ascii messages from serial port #2

@jitterjames

Description

@jitterjames

Sorry. I would have done this the normal way but I can't get GIT to work in Visual Studio and I'm not sure how to do it by the web page.

I propose a change to deal with incoming messages that send non-ascii codes in the string. Currently they come through as unreadable characters and/or truncate the string prematurely.

I can email the updated .cs file but I wanted to highlight the proposed change.

Thanks:

INFO:

in the file: SerialPortActions.cs

Add this method:

private static String decodeHexMessage(string message)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte b in message)
            {  
                try
                {
                    if (b > 33 && b < 127)
                    {
                        sb.Append((char)b);                       
                    }

                    else
                    {
                        sb.Append(@"\x" + b.ToString("X2"));
                    }
                }
                catch (Exception err)
                {
                    sb.Append("[error:" + err.Message + "]");
                }
            }
            
            return sb.ToString();
        }

and modify the port.DataReceived method :

port.DataReceived += delegate {
                // added try catch to fix crashing when closing VC
                try {
                    Plugin.PortMessage = port.ReadExisting();
                    if (!string.IsNullOrWhiteSpace(Plugin.PortMessage)) {
                        if (PluginOptions.GenEventOnReceive) {
                            Plugin.HostInstance.triggerEvent(
                                "Serial.Received", new List<string> {
                                    port.PortName,
                                   decodeHexMessage( Plugin.PortMessage)
                                }
                            );
                        }
                    }
                }
                catch {
                    //
                }
            };

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions