-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathProgram.cs
More file actions
75 lines (54 loc) · 2.18 KB
/
Program.cs
File metadata and controls
75 lines (54 loc) · 2.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
using Microsoft.Extensions.Logging;
using NModbus;
using NModbus.Examples.ModbusClient;
using System.Net;
ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
builder
.SetMinimumLevel(LogLevel.Debug)
.AddConsole();
});
var logger = loggerFactory.CreateLogger<Program>();
//The unit number of the modbus server
const byte unitIdentifier = 1;
var sampleFactory = new ModbusIpClientSampleTransportFactory(loggerFactory);
string sample = "insecure";
await using var transport = sample switch
{
// create a "standard" modbus tcp client
"insecure" => sampleFactory.CreateTcpInsecureClient(IPAddress.Loopback),
// create a modbus secure client, accepting all certificates
"secure" => await sampleFactory.CreateTcpSecureClient("localhost", (snd, cert, chain, errors) => true),
// create a "standard" modbus upd client
"udp" => sampleFactory.CreateUpdClient(IPAddress.Loopback),
_ => throw new NotSupportedException("Only 'insecure', 'secure' or 'udp' is supported as option")
};
var modbusClient = new ModbusClient(transport, loggerFactory);
logger.LogInformation("Writing a single register...");
await modbusClient.WriteSingleRegisterAsync(unitIdentifier, 0, 44);
{
var holdingRegisters = await modbusClient.ReadHoldingRegistersAsync(unitIdentifier, 0, 5);
if (holdingRegisters == null)
{
logger.LogInformation("No response.");
}
else
{
logger.LogInformation("Read Holding Registers: {Registers}", string.Join(", ", holdingRegisters.Select(r => r.ToString())));
}
}
logger.LogInformation("Write multiple registers..");
await modbusClient.WriteMultipleRegistersAsync(unitIdentifier, 0, new ushort[] { 42, 43, 44 });
{
var holdingRegisters = await modbusClient.ReadHoldingRegistersAsync(unitIdentifier, 0, 5);
if (holdingRegisters == null)
{
logger.LogInformation("No response.");
}
else
{
logger.LogInformation("Read Holding Registers: {Registers}", string.Join(", ", holdingRegisters.Select(r => r.ToString())));
}
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();