2 * This file is part of the libsigrok project.
4 * Copyright (C) 2015 Aurelien Jacobs <aurel@gnuage.org>
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include <libsigrok/libsigrok.h>
24 #include "libsigrok-internal.h"
26 #define LOG_PREFIX "modbus"
28 SR_PRIV extern const struct sr_modbus_dev_inst modbus_serial_rtu_dev;
30 static const struct sr_modbus_dev_inst *modbus_devs[] = {
31 #ifdef HAVE_LIBSERIALPORT
32 &modbus_serial_rtu_dev, /* Must be last as it matches any resource. */
36 static struct sr_dev_inst *sr_modbus_scan_resource(const char *resource,
37 const char *serialcomm, int modbusaddr,
38 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
40 struct sr_modbus_dev_inst *modbus;
41 struct sr_dev_inst *sdi;
43 if (!(modbus = modbus_dev_inst_new(resource, serialcomm, modbusaddr)))
46 if (sr_modbus_open(modbus) != SR_OK) {
47 sr_info("Couldn't open Modbus device.");
48 sr_modbus_free(modbus);
52 if ((sdi = probe_device(modbus)))
55 sr_modbus_close(modbus);
56 sr_modbus_free(modbus);
62 * Scan for Modbus devices which match a probing function.
64 * @param drvc The driver context doing the scan.
65 * @param options The scan options to find devies.
66 * @param probe_device The callback function that will be called for each
67 * found device to validate whether this device matches
68 * what we are scanning for.
70 * @return A list of the devices found or NULL if no devices were found.
72 SR_PRIV GSList *sr_modbus_scan(struct drv_context *drvc, GSList *options,
73 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
75 GSList *resources, *l, *devices;
76 struct sr_dev_inst *sdi;
77 const char *resource = NULL;
78 const char *serialcomm = NULL;
83 for (l = options; l; l = l->next) {
84 struct sr_config *src = l->data;
87 resource = g_variant_get_string(src->data, NULL);
89 case SR_CONF_SERIALCOMM:
90 serialcomm = g_variant_get_string(src->data, NULL);
92 case SR_CONF_MODBUSADDR:
93 modbusaddr = g_variant_get_uint64(src->data);
99 for (i = 0; i < ARRAY_SIZE(modbus_devs); i++) {
100 if ((resource && strcmp(resource, modbus_devs[i]->prefix))
101 || !modbus_devs[i]->scan)
103 resources = modbus_devs[i]->scan(modbusaddr);
104 for (l = resources; l; l = l->next) {
105 res = g_strsplit(l->data, ":", 2);
106 if (res[0] && (sdi = sr_modbus_scan_resource(res[0],
107 serialcomm ? serialcomm : res[1],
108 modbusaddr, probe_device))) {
109 devices = g_slist_append(devices, sdi);
110 sdi->connection_id = g_strdup(l->data);
114 g_slist_free_full(resources, g_free);
117 if (!devices && resource) {
118 sdi = sr_modbus_scan_resource(resource, serialcomm, modbusaddr,
121 devices = g_slist_append(NULL, sdi);
124 /* Tack a copy of the newly found devices onto the driver list. */
126 drvc->instances = g_slist_concat(drvc->instances, g_slist_copy(devices));
132 * Allocate and initialize a struct for a Modbus device instance.
134 * @param resource The resource description string.
135 * @param serialcomm Additionnal parameters for serial port resources.
137 * @return The allocated sr_modbus_dev_inst structure or NULL on failure.
139 SR_PRIV struct sr_modbus_dev_inst *modbus_dev_inst_new(const char *resource,
140 const char *serialcomm, int modbusaddr)
142 struct sr_modbus_dev_inst *modbus = NULL;
143 const struct sr_modbus_dev_inst *modbus_dev;
147 for (i = 0; i < ARRAY_SIZE(modbus_devs); i++) {
148 modbus_dev = modbus_devs[i];
149 if (!strncmp(resource, modbus_dev->prefix, strlen(modbus_dev->prefix))) {
150 sr_dbg("Opening %s device %s.", modbus_dev->name, resource);
151 modbus = g_malloc(sizeof(*modbus));
152 *modbus = *modbus_dev;
153 modbus->priv = g_malloc0(modbus->priv_size);
154 modbus->read_timeout_ms = 1000;
155 params = g_strsplit(resource, "/", 0);
156 if (modbus->dev_inst_new(modbus->priv, resource,
157 params, serialcomm, modbusaddr) != SR_OK) {
158 sr_modbus_free(modbus);
170 * Open the specified Modbus device.
172 * @param modbus Previously initialized Modbus device structure.
174 * @return SR_OK on success, SR_ERR on failure.
176 SR_PRIV int sr_modbus_open(struct sr_modbus_dev_inst *modbus)
178 return modbus->open(modbus->priv);
182 * Add an event source for a Modbus device.
184 * @param session The session to add the event source to.
185 * @param modbus Previously initialized Modbus device structure.
186 * @param events Events to check for.
187 * @param timeout Max time to wait before the callback is called, ignored if 0.
188 * @param cb Callback function to add. Must not be NULL.
189 * @param cb_data Data for the callback function. Can be NULL.
191 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
192 * SR_ERR_MALLOC upon memory allocation errors.
194 SR_PRIV int sr_modbus_source_add(struct sr_session *session,
195 struct sr_modbus_dev_inst *modbus, int events, int timeout,
196 sr_receive_data_callback cb, void *cb_data)
198 return modbus->source_add(session, modbus->priv, events, timeout, cb, cb_data);
202 * Remove event source for a Modbus device.
204 * @param session The session to remove the event source from.
205 * @param modbus Previously initialized Modbus device structure.
207 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
208 * SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
211 SR_PRIV int sr_modbus_source_remove(struct sr_session *session,
212 struct sr_modbus_dev_inst *modbus)
214 return modbus->source_remove(session, modbus->priv);
218 * Send a Modbus command.
220 * @param modbus Previously initialized Modbus device structure.
221 * @param request Buffer containing the Modbus command to send.
222 * @param request_size The size of the request buffer.
224 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
227 SR_PRIV int sr_modbus_request(struct sr_modbus_dev_inst *modbus,
228 uint8_t *request, int request_size)
230 if (!request || request_size < 1)
233 return modbus->send(modbus->priv, request, request_size);
237 * Receive a Modbus reply.
239 * @param modbus Previously initialized Modbus device structure.
240 * @param reply Buffer to store the received Modbus reply.
241 * @param reply_size The size of the reply buffer.
243 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
246 SR_PRIV int sr_modbus_reply(struct sr_modbus_dev_inst *modbus,
247 uint8_t *reply, int reply_size)
251 unsigned int elapsed_ms;
253 if (!reply || reply_size < 2)
256 laststart = g_get_monotonic_time();
258 ret = modbus->read_begin(modbus->priv, reply);
267 while (reply_size > 0) {
268 len = modbus->read_data(modbus->priv, reply, reply_size);
270 sr_err("Incompletely read Modbus response.");
272 } else if (len > 0) {
273 laststart = g_get_monotonic_time();
277 elapsed_ms = (g_get_monotonic_time() - laststart) / 1000;
278 if (elapsed_ms >= modbus->read_timeout_ms) {
279 sr_err("Timed out waiting for Modbus response.");
284 ret = modbus->read_end(modbus->priv);
292 * Send a Modbus command and receive the corresponding reply.
294 * @param modbus Previously initialized Modbus device structure.
295 * @param request Buffer containing the Modbus command to send.
296 * @param request_size The size of the request buffer.
297 * @param reply Buffer to store the received Modbus reply.
298 * @param reply_size The size of the reply buffer.
300 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
303 SR_PRIV int sr_modbus_request_reply(struct sr_modbus_dev_inst *modbus,
304 uint8_t *request, int request_size, uint8_t *reply, int reply_size)
307 ret = sr_modbus_request(modbus, request, request_size);
310 return sr_modbus_reply(modbus, reply, reply_size);
314 MODBUS_READ_COILS = 0x01,
315 MODBUS_READ_HOLDING_REGISTERS = 0x03,
316 MODBUS_WRITE_COIL = 0x05,
317 MODBUS_WRITE_MULTIPLE_REGISTERS = 0x10,
320 static int sr_modbus_error_check(const uint8_t *reply)
322 const char *function = "UNKNOWN";
323 const char *error = NULL;
326 if (!(reply[0] & 0x80))
329 switch (reply[0] & ~0x80) {
330 case MODBUS_READ_COILS:
331 function = "MODBUS_READ_COILS";
333 case MODBUS_READ_HOLDING_REGISTERS:
334 function = "READ_HOLDING_REGISTERS";
336 case MODBUS_WRITE_COIL:
337 function = "WRITE_COIL";
339 case MODBUS_WRITE_MULTIPLE_REGISTERS:
340 function = "WRITE_MULTIPLE_REGISTERS";
346 error = "ILLEGAL FUNCTION";
349 error = "ILLEGAL DATA ADDRESS";
352 error = "ILLEGAL DATA VALUE";
355 error = "SLAVE DEVICE FAILURE";
358 error = "ACKNOWLEDGE";
361 error = "SLAVE DEVICE BUSY";
364 error = "MEMORY PARITY ERROR";
367 error = "GATEWAY PATH UNAVAILABLE";
370 error = "GATEWAY TARGET DEVICE FAILED TO RESPOND";
374 snprintf(buf, sizeof(buf), "0x%X", reply[1]);
378 sr_err("%s error executing %s function.", error, function);
384 * Send a Modbus read coils command and receive the corresponding coils values.
386 * @param modbus Previously initialized Modbus device structure.
387 * @param address The Modbus address of the first coil to read, or -1 to read
388 * the reply of a previouly sent read coils command.
389 * @param nb_coils The number of coils to read.
390 * @param coils Buffer to store all the received coils values (1 bit per coil),
391 * or NULL to send the read coil command without reading the reply.
393 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
394 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
396 SR_PRIV int sr_modbus_read_coils(struct sr_modbus_dev_inst *modbus,
397 int address, int nb_coils, uint8_t *coils)
399 uint8_t request[5], reply[2 + (nb_coils + 7) / 8];
402 if (address < -1 || address > 0xFFFF || nb_coils < 1 || nb_coils > 2000)
405 W8(request + 0, MODBUS_READ_COILS);
406 WB16(request + 1, address);
407 WB16(request + 3, nb_coils);
410 ret = sr_modbus_request(modbus, request, sizeof(request));
416 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
419 if (sr_modbus_error_check(reply))
421 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)((nb_coils + 7) / 8))
423 memcpy(coils, reply + 2, (nb_coils + 7) / 8);
430 * Send a Modbus read holding registers command and receive the corresponding
433 * @param modbus Previously initialized Modbus device structure.
434 * @param address The Modbus address of the first register to read, or -1 to
435 * read the reply of a previouly sent read registers command.
436 * @param nb_registers The number of registers to read.
437 * @param registers Buffer to store all the received registers values,
438 * or NULL to send the read holding registers command
439 * without reading the reply.
441 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
442 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
444 SR_PRIV int sr_modbus_read_holding_registers(struct sr_modbus_dev_inst *modbus,
445 int address, int nb_registers, uint16_t *registers)
447 uint8_t request[5], reply[2 + (2 * nb_registers)];
450 if (address < -1 || address > 0xFFFF
451 || nb_registers < 1 || nb_registers > 125)
454 W8(request + 0, MODBUS_READ_HOLDING_REGISTERS);
455 WB16(request + 1, address);
456 WB16(request + 3, nb_registers);
459 ret = sr_modbus_request(modbus, request, sizeof(request));
465 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
468 if (sr_modbus_error_check(reply))
470 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)(2 * nb_registers))
472 memcpy(registers, reply + 2, 2 * nb_registers);
479 * Send a Modbus write coil command.
481 * @param modbus Previously initialized Modbus device structure.
482 * @param address The Modbus address of the coil to write.
483 * @param value The new value to assign to this coil.
485 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
486 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
488 SR_PRIV int sr_modbus_write_coil(struct sr_modbus_dev_inst *modbus,
489 int address, int value)
491 uint8_t request[5], reply[5];
494 if (address < 0 || address > 0xFFFF)
497 W8(request + 0, MODBUS_WRITE_COIL);
498 WB16(request + 1, address);
499 WB16(request + 3, value ? 0xFF00 : 0);
501 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
502 reply, sizeof(reply));
505 if (sr_modbus_error_check(reply))
507 if (memcmp(request, reply, sizeof(reply)))
514 * Send a Modbus write multiple registers command.
516 * @param modbus Previously initialized Modbus device structure.
517 * @param address The Modbus address of the first register to write.
518 * @param nb_registers The number of registers to write.
519 * @param registers Buffer holding all the registers values to write.
521 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
522 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
524 SR_PRIV int sr_modbus_write_multiple_registers(struct sr_modbus_dev_inst*modbus,
525 int address, int nb_registers, uint16_t *registers)
527 uint8_t request[6 + (2 * nb_registers)], reply[5];
530 if (address < 0 || address > 0xFFFF
531 || nb_registers < 1 || nb_registers > 123 || !registers)
534 W8(request + 0, MODBUS_WRITE_MULTIPLE_REGISTERS);
535 WB16(request + 1, address);
536 WB16(request + 3, nb_registers);
537 W8(request + 5, 2 * nb_registers);
538 memcpy(request + 6, registers, 2 * nb_registers);
540 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
541 reply, sizeof(reply));
544 if (sr_modbus_error_check(reply))
546 if (memcmp(request, reply, sizeof(reply)))
553 * Close Modbus device.
555 * @param modbus Previously initialized Modbus device structure.
557 * @return SR_OK on success, SR_ERR on failure.
559 SR_PRIV int sr_modbus_close(struct sr_modbus_dev_inst *modbus)
561 return modbus->close(modbus->priv);
565 * Free Modbus device.
567 * @param modbus Previously initialized Modbus device structure.
569 * @return SR_OK on success, SR_ERR on failure.
571 SR_PRIV void sr_modbus_free(struct sr_modbus_dev_inst *modbus)
573 modbus->free(modbus->priv);
574 g_free(modbus->priv);