Skip to content

Instantly share code, notes, and snippets.

@MartinBspheroid
Created May 6, 2020 07:37
Show Gist options
  • Save MartinBspheroid/68bc2b435d9e66452cff0577f588bf50 to your computer and use it in GitHub Desktop.
Save MartinBspheroid/68bc2b435d9e66452cff0577f588bf50 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
using EasyModbus;
using Fleck;
namespace MODBUS
{
class Program
{
public static string port = "";
public static WebSocketServer server;
public static IWebSocketConnection socketConnection;
public static bool connectionActive = false;
public static void Main(string[] args)
{
server = new WebSocketServer("ws://127.0.0.1:8888");
server.Start(socket =>
{
socket.OnOpen = () =>
{
Console.WriteLine(">>> Connec");
connectionActive = true;
};
socket.OnClose = () =>
{
Console.WriteLine("Close!");
connectionActive = false;
};
socket.OnMessage = message => socket.Send(message);
socketConnection = socket;
});
server.RestartAfterListenError = true;
if (args.Length == 0)
{
port = "COM5";
}
else
{
port = args[0];
Console.WriteLine("cmd> COM port: " + args[0]);
}
string[] ports = System.IO.Ports.SerialPort.GetPortNames();
Console.WriteLine("Available ports: ");
foreach (var item in ports)
{
Console.WriteLine(">> : " + item.ToString());
}
if (ports.Length == 0)
{
Console.WriteLine("ERROR >>>> No serial ports found!");
}
else
{
process();
}
Console.ReadKey(true);
}
public static void process()
{
ModbusClient modbusClient = new ModbusClient(port);
modbusClient.Baudrate = 9600;
modbusClient.Parity = System.IO.Ports.Parity.None;
modbusClient.StopBits = System.IO.Ports.StopBits.One;
modbusClient.ConnectionTimeout = 500;
modbusClient.Connect();
if (modbusClient.Connected)
{
Console.WriteLine("INFO >>> MODBUS Connected");
}
var t = new Thread(() =>
{
Console.WriteLine("Unit id > " + modbusClient.UnitIdentifier.ToString());
while (true)
{
if (modbusClient.Connected)
{
modbusClient.UnitIdentifier = 1;
var LeftRod = modbusClient.ReadHoldingRegisters(62, 1)[0];
modbusClient.UnitIdentifier = 2;
var RightRod = modbusClient.ReadHoldingRegisters(62, 1)[0];
Console.WriteLine(LeftRod.ToString() + " <<< >>> " + RightRod.ToString());
if (connectionActive && socketConnection.IsAvailable)
{
socketConnection.Send("Left/" + LeftRod.ToString());
socketConnection.Send("Right/" + RightRod.ToString());
}
}
Thread.Sleep(10);
}
});
t.Start();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment