Skip to content

Commit 56af9c9

Browse files
committed
Code formating.
1 parent 0fa8e34 commit 56af9c9

File tree

5 files changed

+222
-241
lines changed

5 files changed

+222
-241
lines changed

arduino-modbus-rtu-tcp-gateway/01-interfaces.ino

Lines changed: 32 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -37,24 +37,23 @@
3737
void startSerial() {
3838
mySerial.begin(localConfig.baud, localConfig.serialConfig);
3939
// Calculate Modbus RTU character timeout and frame delay
40-
byte bits = // number of bits per character (11 in default Modbus RTU settings)
41-
1 + // start bit
42-
(((localConfig.serialConfig & 0x06) >> 1) + 5) + // data bits
43-
(((localConfig.serialConfig & 0x08) >> 3) + 1); // stop bits
44-
if (((localConfig.serialConfig & 0x30) >> 4) > 1) bits += 1; // parity bit (if present)
45-
int T = ((unsigned long)bits * 1000000UL) / localConfig.baud; // time to send 1 character over serial in microseconds
40+
byte bits = // number of bits per character (11 in default Modbus RTU settings)
41+
1 + // start bit
42+
(((localConfig.serialConfig & 0x06) >> 1) + 5) + // data bits
43+
(((localConfig.serialConfig & 0x08) >> 3) + 1); // stop bits
44+
if (((localConfig.serialConfig & 0x30) >> 4) > 1) bits += 1; // parity bit (if present)
45+
int T = ((unsigned long)bits * 1000000UL) / localConfig.baud; // time to send 1 character over serial in microseconds
4646
if (localConfig.baud <= 19200) {
47-
charTimeout = 1.5 * T; // inter-character time-out should be 1,5T
48-
frameDelay = 3.5 * T; // inter-frame delay should be 3,5T
49-
}
50-
else {
47+
charTimeout = 1.5 * T; // inter-character time-out should be 1,5T
48+
frameDelay = 3.5 * T; // inter-frame delay should be 3,5T
49+
} else {
5150
charTimeout = 750;
5251
frameDelay = 1750;
5352
}
5453
#ifdef RS485_CONTROL_PIN
5554
pinMode(RS485_CONTROL_PIN, OUTPUT);
5655
digitalWrite(RS485_CONTROL_PIN, RS485_RECEIVE); // Init Transceiver
57-
#endif /* RS485_CONTROL_PIN */
56+
#endif /* RS485_CONTROL_PIN */
5857
}
5958

6059
void startEthernet() {
@@ -66,18 +65,18 @@ void startEthernet() {
6665
delay(500);
6766
}
6867
byte mac[6];
69-
memcpy(mac, MAC_START, 3); // set first 3 bytes
70-
memcpy(mac + 3, localConfig.macEnd, 3); // set last 3 bytes
68+
memcpy(mac, MAC_START, 3); // set first 3 bytes
69+
memcpy(mac + 3, localConfig.macEnd, 3); // set last 3 bytes
7170
#ifdef ENABLE_DHCP
7271
if (localConfig.enableDhcp) {
7372
dhcpSuccess = Ethernet.begin(mac);
7473
}
7574
if (!localConfig.enableDhcp || dhcpSuccess == false) {
7675
Ethernet.begin(mac, localConfig.ip, localConfig.dns, localConfig.gateway, localConfig.subnet);
7776
}
78-
#else /* ENABLE_DHCP */
77+
#else /* ENABLE_DHCP */
7978
Ethernet.begin(mac, localConfig.ip, localConfig.dns, localConfig.gateway, localConfig.subnet);
80-
localConfig.enableDhcp = false; // Make sure Dhcp is disabled in config
79+
localConfig.enableDhcp = false; // Make sure Dhcp is disabled in config
8180
#endif /* ENABLE_DHCP */
8281
modbusServer = EthernetServer(localConfig.tcpPort);
8382
webServer = EthernetServer(localConfig.webPort);
@@ -93,21 +92,19 @@ void startEthernet() {
9392
dbgln(Ethernet.localIP());
9493
}
9594

96-
void(* resetFunc) (void) = 0; //declare reset function at address 0
95+
void (*resetFunc)(void) = 0; //declare reset function at address 0
9796

98-
void maintainDhcp()
99-
{
100-
if (localConfig.enableDhcp && dhcpSuccess == true) { // only call maintain if initial DHCP request by startEthernet was successfull
97+
void maintainDhcp() {
98+
if (localConfig.enableDhcp && dhcpSuccess == true) { // only call maintain if initial DHCP request by startEthernet was successfull
10199
uint8_t maintainResult = Ethernet.maintain();
102-
if (maintainResult == 1 || maintainResult == 3) { // renew failed or rebind failed
100+
if (maintainResult == 1 || maintainResult == 3) { // renew failed or rebind failed
103101
dhcpSuccess = false;
104-
startEthernet(); // another DHCP request, fallback to static IP
102+
startEthernet(); // another DHCP request, fallback to static IP
105103
}
106104
}
107105
}
108106

109-
void maintainUptime()
110-
{
107+
void maintainUptime() {
111108
unsigned long milliseconds = millis();
112109
if (last_milliseconds > milliseconds) {
113110
//in case of millis() overflow, store existing passed seconds
@@ -121,8 +118,7 @@ void maintainUptime()
121118
seconds = (milliseconds / 1000) + remaining_seconds;
122119
}
123120

124-
void maintainCounters()
125-
{
121+
void maintainCounters() {
126122
// synchronize roll-over of data counters to zero, at 0xFFFFFF00 or 0xFF00 respectively
127123
#ifdef ENABLE_EXTRA_DIAG
128124
const unsigned long rollover = 0xFFFFFF00;
@@ -138,23 +134,21 @@ void maintainCounters()
138134
}
139135

140136

141-
void generateMac()
142-
{
137+
void generateMac() {
143138
// Marsaglia algorithm from https://github.com/RobTillaart/randomHelpers
144139
seed1 = 36969L * (seed1 & 65535L) + (seed1 >> 16);
145140
seed2 = 18000L * (seed2 & 65535L) + (seed2 >> 16);
146-
uint32_t randomBuffer = (seed1 << 16) + seed2; /* 32-bit random */
141+
uint32_t randomBuffer = (seed1 << 16) + seed2; /* 32-bit random */
147142

148143
for (byte i = 0; i < 3; i++) {
149144
localConfig.macEnd[i] = randomBuffer & 0xFF;
150145
randomBuffer >>= 8;
151146
}
152147
}
153148

154-
void CreateTrulyRandomSeed()
155-
{
149+
void CreateTrulyRandomSeed() {
156150
seed1 = 0;
157-
nrot = 32; // Must be at least 4, but more increased the uniformity of the produced
151+
nrot = 32; // Must be at least 4, but more increased the uniformity of the produced
158152
// seeds entropy.
159153

160154
// The following five lines of code turn on the watch dog timer interrupt to create
@@ -165,7 +159,8 @@ void CreateTrulyRandomSeed()
165159
_WD_CONTROL_REG = (1 << WDIE);
166160
sei();
167161

168-
while (nrot > 0); // wait here until seed is created
162+
while (nrot > 0)
163+
; // wait here until seed is created
169164

170165
// The following five lines turn off the watch dog timer interrupt
171166
cli();
@@ -175,8 +170,7 @@ void CreateTrulyRandomSeed()
175170
sei();
176171
}
177172

178-
ISR(WDT_vect)
179-
{
173+
ISR(WDT_vect) {
180174
nrot--;
181175
seed1 = seed1 << 8;
182176
seed1 = seed1 ^ TCNT1L;
@@ -194,7 +188,7 @@ ISR(WDT_vect)
194188
#elif defined(__MK20DX128__)
195189
#define BOARD F("Teensy 3.0")
196190
#elif defined(__MK20DX256__)
197-
#define BOARD F("Teensy 3.2") // and Teensy 3.1 (obsolete)
191+
#define BOARD F("Teensy 3.2") // and Teensy 3.1 (obsolete)
198192
#elif defined(__MKL26Z64__)
199193
#define BOARD F("Teensy LC")
200194
#elif defined(__MK64FX512__)
@@ -205,11 +199,11 @@ ISR(WDT_vect)
205199
#error "Unknown board"
206200
#endif
207201

208-
#else // --------------- Arduino ------------------
202+
#else // --------------- Arduino ------------------
209203

210-
#if defined(ARDUINO_AVR_ADK)
204+
#if defined(ARDUINO_AVR_ADK)
211205
#define BOARD F("Arduino Mega Adk")
212-
#elif defined(ARDUINO_AVR_BT) // Bluetooth
206+
#elif defined(ARDUINO_AVR_BT) // Bluetooth
213207
#define BOARD F("Arduino Bt")
214208
#elif defined(ARDUINO_AVR_DUEMILANOVE)
215209
#define BOARD F("Arduino Duemilanove")

arduino-modbus-rtu-tcp-gateway/02-modbus-tcp.ino

Lines changed: 48 additions & 54 deletions
Original file line numberDiff line numberDiff line change
@@ -29,41 +29,39 @@
2929

3030
// bool array for storing Modbus RTU status (responging or not responding). Array index corresponds to slave address.
3131
uint8_t slavesResponding[(maxSlaves + 1 + 7) / 8];
32-
uint8_t masks[8] = {1, 2, 4, 8, 16, 32, 64, 128};
32+
uint8_t masks[8] = { 1, 2, 4, 8, 16, 32, 64, 128 };
3333

3434
typedef struct {
35-
byte tid[2]; // MBAP Transaction ID
36-
byte uid; // MBAP Unit ID (address)
37-
byte PDUlen; // lenght of PDU (func + data) stored in queuePDUs
38-
IPAddress remIP; // remote IP for UDP client (UDP response is sent back to remote IP)
39-
unsigned int remPort; // remote port for UDP client (UDP response is sent back to remote port)
40-
byte clientNum; // TCP client who sent the request, UDP_REQUEST (0xFF) designates UDP client
35+
byte tid[2]; // MBAP Transaction ID
36+
byte uid; // MBAP Unit ID (address)
37+
byte PDUlen; // lenght of PDU (func + data) stored in queuePDUs
38+
IPAddress remIP; // remote IP for UDP client (UDP response is sent back to remote IP)
39+
unsigned int remPort; // remote port for UDP client (UDP response is sent back to remote port)
40+
byte clientNum; // TCP client who sent the request, UDP_REQUEST (0xFF) designates UDP client
4141
} header;
4242

4343
// each request is stored in 3 queues (all queues are written to, read and deleted in sync)
44-
CircularBuffer<header, reqQueueCount> queueHeaders; // queue of requests' headers and metadata (MBAP transaction ID, MBAP unit ID, PDU length, remIP, remPort, TCP client)
45-
CircularBuffer<byte, reqQueueSize> queuePDUs; // queue of PDU data (function code, data)
46-
CircularBuffer<byte, reqQueueCount> queueRetries; // queue of retry counters
44+
CircularBuffer<header, reqQueueCount> queueHeaders; // queue of requests' headers and metadata (MBAP transaction ID, MBAP unit ID, PDU length, remIP, remPort, TCP client)
45+
CircularBuffer<byte, reqQueueSize> queuePDUs; // queue of PDU data (function code, data)
46+
CircularBuffer<byte, reqQueueCount> queueRetries; // queue of retry counters
4747

48-
void recvUdp()
49-
{
48+
void recvUdp() {
5049
unsigned int packetSize = Udp.parsePacket();
51-
if (packetSize)
52-
{
50+
if (packetSize) {
5351
ethRxCount += packetSize;
54-
byte udpInBuffer[modbusSize + 4]; // Modbus TCP frame is 4 bytes longer than Modbus RTU frame
52+
byte udpInBuffer[modbusSize + 4]; // Modbus TCP frame is 4 bytes longer than Modbus RTU frame
5553
// Modbus TCP/UDP frame: [0][1] transaction ID, [2][3] protocol ID, [4][5] length and [6] unit ID (address).....
5654
// Modbus RTU frame: [0] address.....
5755
Udp.read(udpInBuffer, sizeof(udpInBuffer));
5856
Udp.flush();
5957

6058
byte errorCode = checkRequest(udpInBuffer, packetSize);
61-
byte pduStart; // first byte of Protocol Data Unit (i.e. Function code)
62-
if (localConfig.enableRtuOverTcp) pduStart = 1; // In Modbus RTU, Function code is second byte (after address)
63-
else pduStart = 7; // In Modbus TCP/UDP, Function code is 8th byte (after address)
59+
byte pduStart; // first byte of Protocol Data Unit (i.e. Function code)
60+
if (localConfig.enableRtuOverTcp) pduStart = 1; // In Modbus RTU, Function code is second byte (after address)
61+
else pduStart = 7; // In Modbus TCP/UDP, Function code is 8th byte (after address)
6462
if (errorCode == 0) {
6563
// Store in request queue: 2 bytes MBAP Transaction ID (ignored in Modbus RTU over TCP); MBAP Unit ID (address); PDUlen (func + data);remote IP; remote port; TCP client Number (socket) - 0xFF for UDP
66-
queueHeaders.push(header {{udpInBuffer[0], udpInBuffer[1]}, udpInBuffer[pduStart - 1], (byte)(packetSize - pduStart), Udp.remoteIP(), Udp.remotePort(), UDP_REQUEST});
64+
queueHeaders.push(header{ { udpInBuffer[0], udpInBuffer[1] }, udpInBuffer[pduStart - 1], (byte)(packetSize - pduStart), Udp.remoteIP(), Udp.remotePort(), UDP_REQUEST });
6765
queueRetries.push(0);
6866
for (byte i = 0; i < (byte)(packetSize - pduStart); i++) {
6967
queuePDUs.push(udpInBuffer[i + pduStart]);
@@ -75,15 +73,15 @@ void recvUdp()
7573
Udp.write(udpInBuffer, 5);
7674
Udp.write(0x03);
7775
}
78-
Udp.write(udpInBuffer[pduStart - 1]); // address
79-
Udp.write(udpInBuffer[pduStart] + 0x80); // function + 0x80
76+
Udp.write(udpInBuffer[pduStart - 1]); // address
77+
Udp.write(udpInBuffer[pduStart] + 0x80); // function + 0x80
8078
Udp.write(errorCode);
8179
if (localConfig.enableRtuOverTcp) {
8280
crc = 0xFFFF;
8381
calculateCRC(udpInBuffer[pduStart - 1]);
8482
calculateCRC(udpInBuffer[pduStart] + 0x80);
8583
calculateCRC(errorCode);
86-
Udp.write(lowByte(crc)); // send CRC, low byte first
84+
Udp.write(lowByte(crc)); // send CRC, low byte first
8785
Udp.write(highByte(crc));
8886
}
8987
Udp.endPacket();
@@ -96,24 +94,23 @@ void recvUdp()
9694
}
9795

9896

99-
void recvTcp()
100-
{
97+
void recvTcp() {
10198
EthernetClient client = modbusServer.available();
10299
if (client) {
103100
unsigned int packetSize = client.available();
104101
ethRxCount += packetSize;
105-
byte tcpInBuffer[modbusSize + 4]; // Modbus TCP frame is 4 bytes longer than Modbus RTU frame
102+
byte tcpInBuffer[modbusSize + 4]; // Modbus TCP frame is 4 bytes longer than Modbus RTU frame
106103
// Modbus TCP/UDP frame: [0][1] transaction ID, [2][3] protocol ID, [4][5] length and [6] unit ID (address).....
107104
// Modbus RTU frame: [0] address.....
108105
client.read(tcpInBuffer, sizeof(tcpInBuffer));
109106
client.flush();
110107
byte errorCode = checkRequest(tcpInBuffer, packetSize);
111-
byte pduStart; // first byte of Protocol Data Unit (i.e. Function code)
112-
if (localConfig.enableRtuOverTcp) pduStart = 1; // In Modbus RTU, Function code is second byte (after address)
113-
else pduStart = 7; // In Modbus TCP/UDP, Function code is 8th byte (after address)
108+
byte pduStart; // first byte of Protocol Data Unit (i.e. Function code)
109+
if (localConfig.enableRtuOverTcp) pduStart = 1; // In Modbus RTU, Function code is second byte (after address)
110+
else pduStart = 7; // In Modbus TCP/UDP, Function code is 8th byte (after address)
114111
if (errorCode == 0) {
115112
// Store in request queue: 2 bytes MBAP Transaction ID (ignored in Modbus RTU over TCP); MBAP Unit ID (address); PDUlen (func + data);remote IP; remote port; TCP client Number (socket) - 0xFF for UDP
116-
queueHeaders.push(header {{tcpInBuffer[0], tcpInBuffer[1]}, tcpInBuffer[pduStart - 1], (byte)(packetSize - pduStart), {}, 0, client.getSocketNumber()});
113+
queueHeaders.push(header{ { tcpInBuffer[0], tcpInBuffer[1] }, tcpInBuffer[pduStart - 1], (byte)(packetSize - pduStart), {}, 0, client.getSocketNumber() });
117114
queueRetries.push(0);
118115
for (byte i = 0; i < packetSize - pduStart; i++) {
119116
queuePDUs.push(tcpInBuffer[i + pduStart]);
@@ -124,15 +121,15 @@ void recvTcp()
124121
client.write(tcpInBuffer, 5);
125122
client.write(0x03);
126123
}
127-
client.write(tcpInBuffer[pduStart - 1]); // address
128-
client.write(tcpInBuffer[pduStart] + 0x80); // function + 0x80
124+
client.write(tcpInBuffer[pduStart - 1]); // address
125+
client.write(tcpInBuffer[pduStart] + 0x80); // function + 0x80
129126
client.write(errorCode);
130127
if (localConfig.enableRtuOverTcp) {
131128
crc = 0xFFFF;
132129
calculateCRC(tcpInBuffer[pduStart - 1]);
133130
calculateCRC(tcpInBuffer[pduStart] + 0x80);
134131
calculateCRC(errorCode);
135-
client.write(lowByte(crc)); // send CRC, low byte first
132+
client.write(lowByte(crc)); // send CRC, low byte first
136133
client.write(highByte(crc));
137134
}
138135
#ifdef ENABLE_EXTRA_DIAG
@@ -143,13 +140,12 @@ void recvTcp()
143140
}
144141
}
145142

146-
void processRequests()
147-
{
143+
void processRequests() {
148144
// Insert scan request into queue
149145
if (scanCounter != 0 && queueHeaders.available() > 1 && queuePDUs.available() > 1) {
150146
// Store scan request in request queue
151-
queueHeaders.push(header {{0x00, 0x00}, scanCounter, sizeof(scanCommand), {}, 0, SCAN_REQUEST});
152-
queueRetries.push(localConfig.serialRetry - 1); // scan requests are only sent once, so set "queueRetries" to one attempt below limit
147+
queueHeaders.push(header{ { 0x00, 0x00 }, scanCounter, sizeof(scanCommand), {}, 0, SCAN_REQUEST });
148+
queueRetries.push(localConfig.serialRetry - 1); // scan requests are only sent once, so set "queueRetries" to one attempt below limit
153149
for (byte i = 0; i < sizeof(scanCommand); i++) {
154150
queuePDUs.push(scanCommand[i]);
155151
}
@@ -158,9 +154,9 @@ void processRequests()
158154
}
159155

160156
// Optimize queue (prioritize requests from responding slaves) and trigger sending via serial
161-
if (serialState == IDLE) { // send new data over serial only if we are not waiting for response
157+
if (serialState == IDLE) { // send new data over serial only if we are not waiting for response
162158
if (!queueHeaders.isEmpty()) {
163-
boolean queueHasRespondingSlaves; // true if queue holds at least one request to responding slaves
159+
boolean queueHasRespondingSlaves; // true if queue holds at least one request to responding slaves
164160
for (byte i = 0; i < queueHeaders.size(); i++) {
165161
if (getSlaveResponding(queueHeaders[i].uid) == true) {
166162
queueHasRespondingSlaves = true;
@@ -177,7 +173,7 @@ void processRequests()
177173
queueRetries.push(queueRetries.shift());
178174
queueHeaders.push(queueHeaders.shift());
179175
}
180-
serialState = SENDING; // trigger sendSerial()
176+
serialState = SENDING; // trigger sendSerial()
181177
}
182178
}
183179
}
@@ -187,31 +183,31 @@ byte checkRequest(byte buffer[], unsigned int bufferSize) {
187183
if (localConfig.enableRtuOverTcp) address = buffer[0];
188184
else address = buffer[6];
189185

190-
if (localConfig.enableRtuOverTcp) { // check CRC for Modbus RTU over TCP/UDP
186+
if (localConfig.enableRtuOverTcp) { // check CRC for Modbus RTU over TCP/UDP
191187
if (checkCRC(buffer, bufferSize) == false) {
192-
return 0xFF; // reject: do nothing and return no error code
188+
return 0xFF; // reject: do nothing and return no error code
193189
}
194-
} else { // check MBAP header structure for Modbus TCP/UDP
190+
} else { // check MBAP header structure for Modbus TCP/UDP
195191
if (buffer[2] != 0x00 || buffer[3] != 0x00 || buffer[4] != 0x00 || buffer[5] != bufferSize - 6) {
196-
return 0xFF; // reject: do nothing and return no error code
192+
return 0xFF; // reject: do nothing and return no error code
197193
}
198194
}
199-
if (queueHeaders.isEmpty() == false && getSlaveResponding(address) == false) { // allow only one request to non responding slaves
200-
for (byte j = queueHeaders.size(); j > 0 ; j--) { // start searching from tail because requests to non-responsive slaves are usually towards the tail of the queue
195+
if (queueHeaders.isEmpty() == false && getSlaveResponding(address) == false) { // allow only one request to non responding slaves
196+
for (byte j = queueHeaders.size(); j > 0; j--) { // start searching from tail because requests to non-responsive slaves are usually towards the tail of the queue
201197
if (queueHeaders[j - 1].uid == address) {
202-
return 0x0B; // return modbus error 11 (Gateway Target Device Failed to Respond) - usually means that target device (address) is not present
198+
return 0x0B; // return modbus error 11 (Gateway Target Device Failed to Respond) - usually means that target device (address) is not present
203199
}
204200
}
205201
}
206202
// check if we have space in request queue
207203
if (queueHeaders.available() < 1 || (localConfig.enableRtuOverTcp && queuePDUs.available() < bufferSize - 1) || (!localConfig.enableRtuOverTcp && queuePDUs.available() < bufferSize - 7)) {
208-
return 0x06; // return modbus error 6 (Slave Device Busy) - try again later
204+
return 0x06; // return modbus error 6 (Slave Device Busy) - try again later
209205
}
210206
// al checkes passed OK, we can store the incoming data in request queue
211207
return 0;
212208
}
213209

214-
void deleteRequest() // delete request from queue
210+
void deleteRequest() // delete request from queue
215211
{
216212
for (byte i = 0; i < queueHeaders.first().PDUlen; i++) {
217213
queuePDUs.shift();
@@ -221,16 +217,14 @@ void deleteRequest() // delete request from queue
221217
}
222218

223219

224-
bool getSlaveResponding(const uint8_t index)
225-
{
226-
if (index >= maxSlaves) return false; // error
220+
bool getSlaveResponding(const uint8_t index) {
221+
if (index >= maxSlaves) return false; // error
227222
return (slavesResponding[index / 8] & masks[index & 7]) > 0;
228223
}
229224

230225

231-
void setSlaveResponding(const uint8_t index, const bool value)
232-
{
233-
if (index >= maxSlaves) return; // error
226+
void setSlaveResponding(const uint8_t index, const bool value) {
227+
if (index >= maxSlaves) return; // error
234228
if (value == 0) slavesResponding[index / 8] &= ~masks[index & 7];
235229
else slavesResponding[index / 8] |= masks[index & 7];
236230
}

0 commit comments

Comments
 (0)