Skip to content

Commit 69bd759

Browse files
Issue #74 Enable / disable communication (#77)
Created a new private variable: bool _enabled and two methods to change (enable() and disable()), as well as one to check the status (readEnabled()). poll() checks the status of _enable, just before validating the request. If enable is not true, the function returns without processing the request. Tested as working.
1 parent f002129 commit 69bd759

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/ModbusSlave.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,32 @@ void Modbus::setUnitAddress(uint8_t unitAddress)
151151
_slaves[0].setUnitAddress(unitAddress);
152152
}
153153

154+
/**
155+
* Enables communication.
156+
*/
157+
void Modbus::enable()
158+
{
159+
_enabled = true;
160+
}
161+
162+
/**
163+
* Disable communication.
164+
*/
165+
void Modbus::disable()
166+
{
167+
_enabled = false;
168+
}
169+
170+
/**
171+
* Gets the enable status.
172+
*
173+
* @return The enable state.
174+
*/
175+
bool Modbus::readEnabled()
176+
{
177+
return _enabled;
178+
}
179+
154180
/**
155181
* Gets the total number of bytes sent.
156182
*
@@ -233,6 +259,12 @@ uint8_t Modbus::poll()
233259
_responseBuffer[MODBUS_FUNCTION_CODE_INDEX] = _requestBuffer[MODBUS_FUNCTION_CODE_INDEX];
234260
_responseBufferLength = MODBUS_FRAME_SIZE;
235261

262+
// If communication is not enabled, skip processing
263+
if (!_enabled)
264+
{
265+
return 0;
266+
}
267+
236268
// Validate the incoming request.
237269
if (!Modbus::validateRequest())
238270
{

src/ModbusSlave.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,8 @@ class Modbus
104104

105105
void begin(uint64_t boudRate);
106106
void setUnitAddress(uint8_t unitAddress);
107+
void enable();
108+
void disable();
107109
uint8_t poll();
108110

109111
bool readCoilFromBuffer(int offset);
@@ -116,6 +118,7 @@ class Modbus
116118

117119
uint8_t readFunctionCode();
118120
uint8_t readUnitAddress();
121+
bool readEnabled();
119122
bool isBroadcast();
120123

121124
uint64_t getTotalBytesSent();
@@ -134,6 +137,8 @@ class Modbus
134137
ModbusSlave *_slaves = new ModbusSlave();
135138
uint8_t _numberOfSlaves = 1;
136139

140+
bool _enabled = true;
141+
137142
Stream &_serialStream;
138143

139144
#if defined(SERIAL_TX_BUFFER_SIZE)

0 commit comments

Comments
 (0)