forked from emelianov/modbus-esp8266
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Request.ino
66 lines (52 loc) · 1.58 KB
/
Request.ino
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
/*
Modbus-Arduino Example - Using request processing callback to control access to Hreg write operations
(c)2020 Alexander Emelianov ([email protected])
https://github.com/emelianov/modbus-esp8266
*/
#ifdef ESP8266
#include <ESP8266WiFi.h>
#else //ESP32
#include <WiFi.h>
#endif
#include <ModbusTCP.h>
const uint16_t RO_FLAG = 100; // Coil register to allow/disallow Hregs write
const uint16_t RW_HREG = 200; // Sample Hreg
//ModbusIP object
ModbusTCP mb;
Modbus::ResultCode cbPreRequest(Modbus::FunctionCode fc, const Modbus::RequestData data) {
Serial.printf("PRE Function: %02X\n", fc);
if ((fc == Modbus::FC_WRITE_REG || fc == Modbus::FC_WRITE_REGS) && mb.Coil(RO_FLAG))
return Modbus::EX_ILLEGAL_FUNCTION;
return Modbus::EX_SUCCESS;
}
Modbus::ResultCode cbPostRequest(Modbus::FunctionCode fc, const Modbus::RequestData data) {
Serial.printf("POST Function: %02X\n", fc);
return Modbus::EX_SUCCESS;
}
// Callback function for client connect. Returns true to allow connection.
bool cbConn(IPAddress ip) {
Serial.println(ip);
return true;
}
void setup() {
Serial.begin(115200);
WiFi.begin("SID", "PASSWORD");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
mb.onConnect(cbConn); // Add callback on connection event
mb.onRequest(cbPreRequest);
mb.onRequestSuccess(cbPostRequest);
mb.server();
mb.addCoil(RO_FLAG);
mb.addHreg(RW_HREG, 100);
}
void loop() {
mb.task();
delay(10);
}