Skip to content

Instantly share code, notes, and snippets.

@mniak
Created August 5, 2019 22:26
Show Gist options
  • Save mniak/d9c264874aeba963f365e0ee6d7291f9 to your computer and use it in GitHub Desktop.
Save mniak/d9c264874aeba963f365e0ee6d7291f9 to your computer and use it in GitHub Desktop.
using System.Collections.Generic;
namespace SerialLogger
{
internal static class Crc16
{
public static ushort Compute(IEnumerable<byte> data)
{
const ushort mask = 0x1021;
ushort crc = 0;
foreach (var b in data)
{
var word = b << 8;
for (byte i = 0; i < 8; i++)
{
if (((crc ^ word) & 0x8000) != 0)
{
crc <<= 1;
crc ^= mask;
}
else
{
crc <<= 1;
}
word <<= 1;
}
}
return crc;
}
}
}
using System;
using System.ComponentModel;
using System.IO;
using System.IO.Ports;
namespace SerialLogger
{
class Program
{
static void Main(string[] args)
{
using (var serial = new SerialPort("COM11"))
{
serial.Open();
Console.WriteLine("< STARTED >");
var stream = serial.BaseStream;
ReadBytesAndPrintToScreen(stream);
while (true) HandleKeys(stream);
}
}
private static void HandleKeys(Stream stream)
{
var key = Console.ReadKey(true);
switch (key.Key)
{
case ConsoleKey.Escape:
stream.WriteByte(/* EOT */ 0x04);
break;
case ConsoleKey.Enter:
stream.WriteByte(/* ACK */ 0x06);
break;
case ConsoleKey.Delete:
stream.WriteByte(/* NAK */ 0x15);
break;
case ConsoleKey.NumPad1:
stream.WriteData("OPN000");
break;
default:
return;
}
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"< ");
}
private static void ReadBytesAndPrintToScreen(System.IO.Stream stream)
{
var bw = new BackgroundWorker();
bw.DoWork += (s, e) =>
{
while (true)
{
var b = stream.ReadByte();
if (b >= 0x20 && b <= 0x7f)
{
Console.ForegroundColor = ConsoleColor.Blue;
if (b >= 'A' && b < 'Z' ||
b >= 'a' && b < 'z' ||
b >= 'a' && b < 'z')
{ Console.Write((char)b); }
else
{ Console.Write(b.ToString("X")); }
}
else
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.Write(b.ToString("X"));
}
Console.Write(" ");
}
};
bw.RunWorkerAsync();
}
}
}
using System.IO;
using System.Text;
namespace SerialLogger
{
public static class StreamExtensions
{
public static void WriteData(this Stream stream, byte[] data)
{
stream.WriteByte(/* SYN */ 0x16);
stream.Write(data, 0, data.Length);
var crc = Crc16.Compute(data);
stream.WriteByte((byte)(crc / 256));
stream.WriteByte((byte)(crc % 256));
}
public static void WriteData(this Stream stream, string data)
{
stream.WriteData(Encoding.ASCII.GetBytes(data));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment