protected override DeviceAbstract UnpackDeviceSpecific(string custom) { var device = new ModbusDevice(); var jo = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(custom); if (jo.ContainsKey(nameof(device.SlaveId))) { device.SlaveId = (byte)jo[nameof(device.SlaveId)].ToObject(typeof(byte)); } if (jo.ContainsKey(nameof(device.ByteOrder))) { device.ByteOrder = (byte[])jo[nameof(device.ByteOrder)].ToObject(typeof(byte[])); } if (jo.ContainsKey("FrameType")) { device.FrameType = (FrameType)jo["FrameType"].ToObject(typeof(FrameType)); } if (jo.ContainsKey(nameof(device.MaxGroupLength))) { device.MaxGroupLength = (int)jo[nameof(device.MaxGroupLength)].ToObject(typeof(int)); } if (jo.ContainsKey(nameof(device.MaxGroupSpareLength))) { device.MaxGroupSpareLength = (int)jo[nameof(device.MaxGroupSpareLength)].ToObject(typeof(int)); } return(device); }
public void TryConnectNpt(string portname, string connectorId, string PNPDeviceID) { ModbusDevice <NptRegisters> dev = new ModbusDevice <NptRegisters>(); WriteLog("Try connect " + PNPDeviceID + " on " + portname); if (dev.Connect(portname)) { WriteLog("Port Info for " + PNPDeviceID + ":" + dev.PortInfo()); System.Threading.Thread.Sleep(1000); WriteLog("Read DEVTYPE " + PNPDeviceID + " from " + NptRegisters.Registers._DEVTYPE); if (dev.ExecuteRead(NptRegisters.Registers._DEVTYPE, 2)) { System.Threading.Thread.Sleep(50); WriteLog("Read VERSION " + PNPDeviceID + " from " + NptRegisters.Registers._VERSION); if (dev.ExecuteRead(NptRegisters.Registers._VERSION, 2)) { WriteLog("Check DEVTYP " + PNPDeviceID + " for " + dev.RegistersData.DEVTYPE); if (DevTypesList.ContainsKey(dev.RegistersData.DEVTYPE)) { dev.DisConnect(); AttachedDevices.Add(connectorId, PNPDeviceID); DevAttachedEvent(new DevEventArgs() { ConnectorId = connectorId, PortName = portname, NptType = dev.RegistersData.DEVTYPE, PNPDeviceID = PNPDeviceID }); return; } } } } DevNotDetectedEvent(new DevEventArgs()); dev.DisConnect(); }
private void runThread() { ModbusTCP_Device = new MyModbusDevice(address); mbListener = new ModbusTcpListener(ModbusTCP_Device, 502, 5, 1000); Thread.Sleep(100); isRunning = true; ModbusTCP_Device.Start(); while (link_required == true) { if (ModbusTCP_Device.IsRunning == true) { //System.Diagnostics.Debug.WriteLine("Running "); } else { System.Diagnostics.Debug.WriteLine("Modbus Devic is Stopped "); } Thread.Sleep(1000); } isRunning = false; }
public void MasterShouldReadCoilsFromSlave() { var clientMemory = new ModbusMemoryMap(); var client = new ModbusClient(new ModbusRTUTransport(_clientStream)); var clientDevice = new ModbusDevice(clientMemory, 4); var serverMemory = new ModbusMemoryMap(); var server = new ModbusServer(new ModbusRTUTransport(_serverStream)); var serverDevice = new ModbusDevice(serverMemory, 4); serverMemory.OutputCoils[10] = true; serverMemory.OutputCoils[15] = true; clientMemory.OutputCoils[10].ShouldBeFalse(); clientMemory.OutputCoils[15].ShouldBeFalse(); Task.Run(() => server.HandleRequest(serverDevice)); client.ReadCoils(clientDevice, 10, 13); //slave memory not touched serverMemory.OutputCoils[10].ShouldBeTrue(); serverMemory.OutputCoils[15].ShouldBeTrue(); //master memory is synched clientMemory.OutputCoils[10].ShouldBeTrue(); clientMemory.OutputCoils[15].ShouldBeTrue(); }
public IDeviceOperations GetOperations(ModbusDevice device) { Type type = device.GetType(); if (type == typeof(MonitorBox)) { this._logger.LogInformation("Creating MonitorBoxOperations"); return(new MonitorBoxOperations((MonitorBox)device, this._serviceProvider.GetRequiredService <FacilityContext>(), this._serviceProvider.GetRequiredService <IAddMonitorBoxReading>(), this._serviceProvider.GetRequiredService <ILogger <IMonitorBoxOperations> >(), this._serviceProvider.GetRequiredService <IMediator>())); } else if (type == typeof(H2Generator)) { this._logger.LogInformation("Creating GeneratorOperations"); return(new GeneratorOperations((H2Generator)device, this._serviceProvider.GetRequiredService <IAddGeneratorReading>(), this._serviceProvider.GetRequiredService <ILogger <IGeneratorOperations> >())); } else if (type == typeof(TankScale)) { this._logger.LogInformation("Creating TankScaleOperations"); return(new TankScaleOperations((TankScale)device, this._serviceProvider.GetRequiredService <IAddTankScaleReading>(), this._serviceProvider.GetRequiredService <ILogger <ITankScaleOperations> >())); } else { return(null); } }
/// <summary> /// Creates a new Modbus TCP listener. This will start a TCP server listening to the given port. /// </summary> /// <param name="device">Device to add the listeners to.</param> /// <param name="port">Port to listen. The Modbus TCP default port is 502.</param> /// <param name="maxConnections">Maximum number of allowed connections. The default is 5.</param> /// <param name="maxDataLength">Maximum allowed length of function code specific data.</param> /// <remarks> /// For every incomming connection a new <see cref="ModbusTcpInterface"/> is created and added to the <see cref="ModbusDevice"/>. /// </remarks> public ModbusTcpListener(ModbusDevice device, int port, int maxConnections, short maxDataLength) { _device = device; _maxDataLength = maxDataLength; _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(new IPEndPoint(IPAddress.Any, port)); _listenSocket.Listen(1); _listenThread = new Thread(ListenProc); _listenThread.Start(); }
static void Main(string[] args) { var con = new ModbusConnection() { ComNo = "COM2", }; var blOpen = con.Open(); Console.WriteLine(blOpen); var dev = new ModbusDevice <Device1> { ByteOrder = 0, DeviceAddress = 1 }; con.Register(dev); try { var flow = dev.Read(x => x.Year); Console.WriteLine(flow); } catch (ComException ex) { Console.WriteLine(ex.Message); } while (true) { if (!float.TryParse(Console.ReadLine(), out float f)) { continue; } var entity = new Device1 { Two = f }; var result = dev.Write(entity, x => x.Two); Console.WriteLine(result?.ToString()); entity = dev.Read(); Console.WriteLine($"{entity.Year}-{entity.Month}-{entity.Day} {entity.Hour}:{entity.Minute}:{entity.Second}"); } }
private async void Window_Loaded(object sender, RoutedEventArgs e) { ModbusConnection con = new ModbusConnection { ComNo = "COM2", ComType = ComType.SerialPort }; con.Open(); ModbusDevice <Device1> dev = new ModbusDevice <Device1>(); con.Register(dev); while (true) { Device = dev.Read(); Year = dev.Read(x => x.Year); await Task.Delay(50); } }
public bool AddReading(ModbusDevice device) { Type type = device.GetType(); if (type == typeof(MonitorBox)) { return(this._addMonitorBoxReading.AddReading((MonitorBox)device)); } else if (type == typeof(H2Generator)) { return(this._addGenReading.AddReading((H2Generator)device)); } else if (type == typeof(TankScale)) { return(this._addNHReading.AddReading((TankScale)device)); } else { return(false); } }
public bool AddReading(ModbusDevice device) { Type type = device.GetType(); if (type == typeof(GenericMonitorBox)) { return(this._addMonitorBoxReading.AddReading((GenericMonitorBox)device)); } else if (type == typeof(H2Generator)) { return(this._addGenReading.AddReading((H2Generator)device)); } else if (type == typeof(AmmoniaController)) { return(this._addNHReading.AddReading((AmmoniaController)device)); } else { return(false); } }
public static IDeviceOperations OperationFactory(FacilityContext context, ModbusDevice device) { Type type = device.GetType(); if (type == typeof(GenericMonitorBox)) { return(new MonitorBoxController(context.GetMonitorBox(device.Identifier, false))); } else if (type == typeof(H2Generator)) { return(new GeneratorController(context.GetGenerator(device.Identifier, false))); } else if (type == typeof(AmmoniaController)) { return(new NH3Controller(context.GetNHController(device.Identifier, false))); } else { return(null); } }
private static async Task ConnecionLoop(NetworkStream connectedStream, Options options, IConsole diWindow, IConsole doWindow, IConsole inputRegistersWindow, IConsole holdingRegistersWindow) { var masterMemory = new ModbusMemoryMap(); var client = new ModbusClient(new ModbusTCPTransport(connectedStream)); var device = new ModbusDevice(masterMemory, options.SlaveId); while (!Console.KeyAvailable) { if (options.InputCount > 0) { await client.ReadDiscreteInputsAsync(device, options.InputAddress, options.InputCount, CancellationToken.None); diWindow.PrintAt(0, 0, masterMemory.InputCoils.ToString(options.InputAddress, options.InputCount)); } if (options.CoilsCount > 0) { await client.ReadCoilsAsync(device, options.CoilsAddress, options.CoilsCount, CancellationToken.None); doWindow.PrintAt(0, 0, masterMemory.OutputCoils.ToString(options.CoilsAddress, options.CoilsCount)); } if (options.RegisterCount > 0) { await client.ReadInputRegistersAsync(device, options.RegisterAddress, options.RegisterCount, CancellationToken.None); inputRegistersWindow.PrintAt(0, 0, masterMemory.InputRegisters.ToString(options.RegisterAddress, options.RegisterCount)); } if (options.HoldingRegisterCount > 0) { await client.ReadHoldingRegistersAsync(device, options.HoldingRegisterAddress, options.HoldingRegisterCount, CancellationToken.None); holdingRegistersWindow.PrintAt(0, 0, masterMemory.OutputRegisters.ToString(options.HoldingRegisterAddress, options.HoldingRegisterCount)); } await Task.Delay(options.ScanRate); } }
/// <summary> /// Creates a new Modbus TCP listener. This will start a TCP server listening to the given port. /// </summary> /// <param name="device">Device to add the listeners to.</param> /// <param name="port">Port to listen. The Modbus TCP default port is 502.</param> /// <param name="maxConnections">Maximum number of allowed connections. The default is 5.</param> /// <param name="maxDataLength">Maximum allowed length of function code specific data.</param> /// <returns>Returns a new <see cref="ModbusTcpListener"/>.</returns> /// <remarks> /// For every incomming connection a new <see cref="ModbusTcpInterface"/> is created and added to the <see cref="ModbusDevice"/>. /// </remarks> public static ModbusTcpListener StartDeviceListener(ModbusDevice device, int port = 502, int maxConnections = 5, short maxDataLength = 252) { return(new ModbusTcpListener(device, port, maxConnections, maxDataLength)); }
/// <summary> /// Initialize a new device context instance /// </summary> /// <param name="key"></param> private ModbusContextMultiton(Tuple <string, ushort> key) { ModbusContext = new ModbusDevice <TCPContext>(new TCPContext(key.Item1, key.Item2), 0); }
public void Init() { SlaveDeviceContext = new ModbusDevice <TCPContext>(new TCPContext(Hostname, Port), SlaveId); SlaveDeviceContext.Connect(); }
/// <summary> /// Creates a new Modbus TCP listener. This will start a TCP server listening to the given port. /// </summary> /// <param name="device">Device to add the listeners to.</param> /// <param name="port">Port to listen. The Modbus TCP default port is 502.</param> /// <param name="maxConnections">Maximum number of allowed connections. The default is 5.</param> /// <param name="maxDataLength">Maximum allowed length of function code specific data.</param> /// <remarks> /// For every incomming connection a new <see cref="ModbusTcpInterface"/> is created and added to the <see cref="ModbusDevice"/>. /// </remarks> public ModbusTcpListener(ModbusDevice device, int port, int maxConnections, short maxDataLength) { _device = device; _maxDataLength = maxDataLength; _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(new IPEndPoint(IPAddress.Any, port)); _listenSocket.Listen(1); _listenThread = new Thread(ListenProc); _listenThread.Start(); }
/// <summary> /// Creates a new Modbus TCP listener. This will start a TCP server listening to the given port. /// </summary> /// <param name="device">Device to add the listeners to.</param> /// <param name="port">Port to listen. The Modbus TCP default port is 502.</param> /// <param name="maxConnections">Maximum number of allowed connections. The default is 5.</param> /// <param name="maxDataLength">Maximum allowed length of function code specific data.</param> /// <returns>Returns a new <see cref="ModbusTcpListener"/>.</returns> /// <remarks> /// For every incomming connection a new <see cref="ModbusTcpInterface"/> is created and added to the <see cref="ModbusDevice"/>. /// </remarks> public static ModbusTcpListener StartDeviceListener(ModbusDevice device, int port = 502, int maxConnections = 5, short maxDataLength = 252) { return new ModbusTcpListener(device, port, maxConnections, maxDataLength); }
public static Store Get() { var store = new Store(); var connectionSource = new TcpConnectionSource { Port = 11502, Host = "127.0.0.1", Name = "localhost Tests", }; store.ConnectionsSources.AddByName(connectionSource); var facility = new Facility { Name = "TestFacility", AccessName = "orgName$departmentName$FieldName$wellName", }; store.Facilities.AddByName(facility); var device = new ModbusDevice { Name = "Plc1", FrameType = FrameType.Ip, SlaveId = 1, }; facility.Devices.AddByName(device); device.ConnectionSource = connectionSource; var tagGroup1 = new TagsGroup { Name = "currentData", Min = 10_000_000 }; var tagGroup2 = new TagsGroup { Name = "settings", Min = 10_000_000 }; var tag1 = new MTag { Groups = new Dictionary <string, TagsGroup> { [tagGroup1.Name] = tagGroup1, }, TemplateId = 1, Name = "Tag1", Region = ModbusRegion.HoldingRegisters, Begin = 0, ValueType = Common.ValueType.Int16, }; device.Tags.Add("Tag1", tag1); device.Tags.Add("Tag2", new MTag { Groups = new Dictionary <string, TagsGroup> { [tagGroup1.Name] = tagGroup1, [tagGroup2.Name] = tagGroup2, }, TemplateId = 1, Name = "Tag2", Region = ModbusRegion.HoldingRegisters, Begin = 1, ValueType = Common.ValueType.Int16, }); device.Tags.Add("Tag3", new MTag { Groups = new Dictionary <string, TagsGroup> { [tagGroup1.Name] = tagGroup1, }, TemplateId = 2, Name = "Tag3", Region = ModbusRegion.HoldingRegisters, Begin = 2, ValueType = Common.ValueType.Int16, }); device.Tags.Add("Tag4", new MTag { Groups = new Dictionary <string, TagsGroup> { [tagGroup1.Name] = tagGroup1, }, TemplateId = 2, Name = "Tag4", Region = ModbusRegion.HoldingRegisters, Begin = 3, ValueType = Common.ValueType.Float, }); device.Tags.Add("boolTag5", new MTag { Groups = new Dictionary <string, TagsGroup> { [tagGroup1.Name] = tagGroup1, }, TemplateId = 1, Name = "boolTag5", Region = ModbusRegion.Coils, Begin = 3, ValueType = Common.ValueType.Bool, }); store.TagLogService.Configs.Add(new TagLogger.TagLogConfig(tag1) { Hyst = 1, PeriodMaxSec = 600, PeriodMinSec = 1, TagLogInfo = new TagLogger.Entities.TagLogInfo { DeviceName = device.Name, FacilityAccessName = facility.AccessName, TagName = tag1.Name, } }); return(store); }