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/>.
22 #include "libsigrok.h"
23 #include "libsigrok-internal.h"
25 #define LOG_PREFIX "modbus"
27 SR_PRIV extern const struct sr_modbus_dev_inst modbus_serial_rtu_dev;
29 static const struct sr_modbus_dev_inst *modbus_devs[] = {
30 #ifdef HAVE_LIBSERIALPORT
31 &modbus_serial_rtu_dev, /* Must be last as it matches any resource. */
35 static struct sr_dev_inst *sr_modbus_scan_resource(const char *resource,
36 const char *serialcomm, int modbusaddr,
37 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
39 struct sr_modbus_dev_inst *modbus;
40 struct sr_dev_inst *sdi;
42 if (!(modbus = modbus_dev_inst_new(resource, serialcomm, modbusaddr)))
45 if (sr_modbus_open(modbus) != SR_OK) {
46 sr_info("Couldn't open Modbus device.");
47 sr_modbus_free(modbus);
51 if ((sdi = probe_device(modbus)))
54 sr_modbus_close(modbus);
55 sr_modbus_free(modbus);
61 * Scan for Modbus devices which match a probing function.
63 * @param drvc The driver context doing the scan.
64 * @param options The scan options to find devies.
65 * @param probe_device The callback function that will be called for each
66 * found device to validate whether this device matches
67 * what we are scanning for.
69 * @return A list of the devices found or NULL if no devices were found.
71 SR_PRIV GSList *sr_modbus_scan(struct drv_context *drvc, GSList *options,
72 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
74 GSList *resources, *l, *devices;
75 struct sr_dev_inst *sdi;
76 const char *resource = NULL;
77 const char *serialcomm = NULL;
82 for (l = options; l; l = l->next) {
83 struct sr_config *src = l->data;
86 resource = g_variant_get_string(src->data, NULL);
88 case SR_CONF_SERIALCOMM:
89 serialcomm = g_variant_get_string(src->data, NULL);
91 case SR_CONF_MODBUSADDR:
92 modbusaddr = g_variant_get_uint64(src->data);
98 for (i = 0; i < ARRAY_SIZE(modbus_devs); i++) {
99 if ((resource && strcmp(resource, modbus_devs[i]->prefix))
100 || !modbus_devs[i]->scan)
102 resources = modbus_devs[i]->scan(modbusaddr);
103 for (l = resources; l; l = l->next) {
104 res = g_strsplit(l->data, ":", 2);
105 if (res[0] && (sdi = sr_modbus_scan_resource(res[0],
106 serialcomm ? serialcomm : res[1],
107 modbusaddr, probe_device))) {
108 devices = g_slist_append(devices, sdi);
109 sdi->connection_id = g_strdup(l->data);
113 g_slist_free_full(resources, g_free);
116 if (!devices && resource) {
117 sdi = sr_modbus_scan_resource(resource, serialcomm, modbusaddr,
120 devices = g_slist_append(NULL, sdi);
123 /* Tack a copy of the newly found devices onto the driver list. */
125 drvc->instances = g_slist_concat(drvc->instances, g_slist_copy(devices));
131 * Allocate and initialize a struct for a Modbus device instance.
133 * @param resource The resource description string.
134 * @param serialcomm Additionnal parameters for serial port resources.
136 * @return The allocated sr_modbus_dev_inst structure or NULL on failure.
138 SR_PRIV struct sr_modbus_dev_inst *modbus_dev_inst_new(const char *resource,
139 const char *serialcomm, int modbusaddr)
141 struct sr_modbus_dev_inst *modbus = NULL;
142 const struct sr_modbus_dev_inst *modbus_dev;
146 for (i = 0; i < ARRAY_SIZE(modbus_devs); i++) {
147 modbus_dev = modbus_devs[i];
148 if (!strncmp(resource, modbus_dev->prefix, strlen(modbus_dev->prefix))) {
149 sr_dbg("Opening %s device %s.", modbus_dev->name, resource);
150 modbus = g_malloc(sizeof(*modbus));
151 *modbus = *modbus_dev;
152 modbus->priv = g_malloc0(modbus->priv_size);
153 modbus->read_timeout_ms = 1000;
154 params = g_strsplit(resource, "/", 0);
155 if (modbus->dev_inst_new(modbus->priv, resource,
156 params, serialcomm, modbusaddr) != SR_OK) {
157 sr_modbus_free(modbus);
169 * Open the specified Modbus device.
171 * @param modbus Previously initialized Modbus device structure.
173 * @return SR_OK on success, SR_ERR on failure.
175 SR_PRIV int sr_modbus_open(struct sr_modbus_dev_inst *modbus)
177 return modbus->open(modbus->priv);
181 * Add an event source for a Modbus device.
183 * @param session The session to add the event source to.
184 * @param modbus Previously initialized Modbus device structure.
185 * @param events Events to check for.
186 * @param timeout Max time to wait before the callback is called, ignored if 0.
187 * @param cb Callback function to add. Must not be NULL.
188 * @param cb_data Data for the callback function. Can be NULL.
190 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
191 * SR_ERR_MALLOC upon memory allocation errors.
193 SR_PRIV int sr_modbus_source_add(struct sr_session *session,
194 struct sr_modbus_dev_inst *modbus, int events, int timeout,
195 sr_receive_data_callback cb, void *cb_data)
197 return modbus->source_add(session, modbus->priv, events, timeout, cb, cb_data);
201 * Remove event source for a Modbus device.
203 * @param session The session to remove the event source from.
204 * @param modbus Previously initialized Modbus device structure.
206 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
207 * SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
210 SR_PRIV int sr_modbus_source_remove(struct sr_session *session,
211 struct sr_modbus_dev_inst *modbus)
213 return modbus->source_remove(session, modbus->priv);
217 * Send a Modbus command.
219 * @param modbus Previously initialized Modbus device structure.
220 * @param request Buffer containing the Modbus command to send.
221 * @param request_size The size of the request buffer.
223 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
226 SR_PRIV int sr_modbus_request(struct sr_modbus_dev_inst *modbus,
227 uint8_t *request, int request_size)
229 if (!request || request_size < 1)
232 return modbus->send(modbus->priv, request, request_size);
236 * Receive a Modbus reply.
238 * @param modbus Previously initialized Modbus device structure.
239 * @param reply Buffer to store the received Modbus reply.
240 * @param reply_size The size of the reply buffer.
242 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
245 SR_PRIV int sr_modbus_reply(struct sr_modbus_dev_inst *modbus,
246 uint8_t *reply, int reply_size)
250 unsigned int elapsed_ms;
252 if (!reply || reply_size < 2)
255 laststart = g_get_monotonic_time();
257 ret = modbus->read_begin(modbus->priv, reply);
266 while (reply_size > 0) {
267 len = modbus->read_data(modbus->priv, reply, reply_size);
269 sr_err("Incompletely read Modbus response.");
271 } else if (len > 0) {
272 laststart = g_get_monotonic_time();
276 elapsed_ms = (g_get_monotonic_time() - laststart) / 1000;
277 if (elapsed_ms >= modbus->read_timeout_ms) {
278 sr_err("Timed out waiting for Modbus response.");
283 ret = modbus->read_end(modbus->priv);
291 * Send a Modbus command and receive the corresponding reply.
293 * @param modbus Previously initialized Modbus device structure.
294 * @param request Buffer containing the Modbus command to send.
295 * @param request_size The size of the request buffer.
296 * @param reply Buffer to store the received Modbus reply.
297 * @param reply_size The size of the reply buffer.
299 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
302 SR_PRIV int sr_modbus_request_reply(struct sr_modbus_dev_inst *modbus,
303 uint8_t *request, int request_size, uint8_t *reply, int reply_size)
306 ret = sr_modbus_request(modbus, request, request_size);
309 return sr_modbus_reply(modbus, reply, reply_size);
313 MODBUS_READ_COILS = 0x01,
314 MODBUS_READ_HOLDING_REGISTERS = 0x03,
315 MODBUS_WRITE_COIL = 0x05,
316 MODBUS_WRITE_MULTIPLE_REGISTERS = 0x10,
319 static int sr_modbus_error_check(const uint8_t *reply)
321 const char *function = "UNKNOWN";
322 const char *error = NULL;
325 if (!(reply[0] & 0x80))
328 switch (reply[0] & ~0x80) {
329 case MODBUS_READ_COILS:
330 function = "MODBUS_READ_COILS";
332 case MODBUS_READ_HOLDING_REGISTERS:
333 function = "READ_HOLDING_REGISTERS";
335 case MODBUS_WRITE_COIL:
336 function = "WRITE_COIL";
338 case MODBUS_WRITE_MULTIPLE_REGISTERS:
339 function = "WRITE_MULTIPLE_REGISTERS";
345 error = "ILLEGAL FUNCTION";
348 error = "ILLEGAL DATA ADDRESS";
351 error = "ILLEGAL DATA VALUE";
354 error = "SLAVE DEVICE FAILURE";
357 error = "ACKNOWLEDGE";
360 error = "SLAVE DEVICE BUSY";
363 error = "MEMORY PARITY ERROR";
366 error = "GATEWAY PATH UNAVAILABLE";
369 error = "GATEWAY TARGET DEVICE FAILED TO RESPOND";
373 snprintf(buf, sizeof(buf), "0x%X", reply[1]);
377 sr_err("%s error executing %s function.", error, function);
383 * Send a Modbus read coils command and receive the corresponding coils values.
385 * @param modbus Previously initialized Modbus device structure.
386 * @param address The Modbus address of the first coil to read, or -1 to read
387 * the reply of a previouly sent read coils command.
388 * @param nb_coils The number of coils to read.
389 * @param coils Buffer to store all the received coils values (1 bit per coil),
390 * or NULL to send the read coil command without reading the reply.
392 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
393 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
395 SR_PRIV int sr_modbus_read_coils(struct sr_modbus_dev_inst *modbus,
396 int address, int nb_coils, uint8_t *coils)
398 uint8_t request[5], reply[2 + (nb_coils + 7) / 8];
401 if (address < -1 || address > 0xFFFF || nb_coils < 1 || nb_coils > 2000)
404 W8(request + 0, MODBUS_READ_COILS);
405 WB16(request + 1, address);
406 WB16(request + 3, nb_coils);
409 ret = sr_modbus_request(modbus, request, sizeof(request));
415 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
418 if (sr_modbus_error_check(reply))
420 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)((nb_coils + 7) / 8))
422 memcpy(coils, reply + 2, (nb_coils + 7) / 8);
429 * Send a Modbus read holding registers command and receive the corresponding
432 * @param modbus Previously initialized Modbus device structure.
433 * @param address The Modbus address of the first register to read, or -1 to
434 * read the reply of a previouly sent read registers command.
435 * @param nb_registers The number of registers to read.
436 * @param registers Buffer to store all the received registers values,
437 * or NULL to send the read holding registers command
438 * without reading the reply.
440 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
441 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
443 SR_PRIV int sr_modbus_read_holding_registers(struct sr_modbus_dev_inst *modbus,
444 int address, int nb_registers, uint16_t *registers)
446 uint8_t request[5], reply[2 + (2 * nb_registers)];
449 if (address < -1 || address > 0xFFFF
450 || nb_registers < 1 || nb_registers > 125)
453 W8(request + 0, MODBUS_READ_HOLDING_REGISTERS);
454 WB16(request + 1, address);
455 WB16(request + 3, nb_registers);
458 ret = sr_modbus_request(modbus, request, sizeof(request));
464 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
467 if (sr_modbus_error_check(reply))
469 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)(2 * nb_registers))
471 memcpy(registers, reply + 2, 2 * nb_registers);
478 * Send a Modbus write coil command.
480 * @param modbus Previously initialized Modbus device structure.
481 * @param address The Modbus address of the coil to write.
482 * @param value The new value to assign to this coil.
484 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
485 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
487 SR_PRIV int sr_modbus_write_coil(struct sr_modbus_dev_inst *modbus,
488 int address, int value)
490 uint8_t request[5], reply[5];
493 if (address < 0 || address > 0xFFFF)
496 W8(request + 0, MODBUS_WRITE_COIL);
497 WB16(request + 1, address);
498 WB16(request + 3, value ? 0xFF00 : 0);
500 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
501 reply, sizeof(reply));
504 if (sr_modbus_error_check(reply))
506 if (memcmp(request, reply, sizeof(reply)))
513 * Send a Modbus write multiple registers command.
515 * @param modbus Previously initialized Modbus device structure.
516 * @param address The Modbus address of the first register to write.
517 * @param nb_registers The number of registers to write.
518 * @param registers Buffer holding all the registers values to write.
520 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
521 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
523 SR_PRIV int sr_modbus_write_multiple_registers(struct sr_modbus_dev_inst*modbus,
524 int address, int nb_registers, uint16_t *registers)
526 uint8_t request[6 + (2 * nb_registers)], reply[5];
529 if (address < 0 || address > 0xFFFF
530 || nb_registers < 1 || nb_registers > 123 || !registers)
533 W8(request + 0, MODBUS_WRITE_MULTIPLE_REGISTERS);
534 WB16(request + 1, address);
535 WB16(request + 3, nb_registers);
536 W8(request + 5, 2 * nb_registers);
537 memcpy(request + 6, registers, 2 * nb_registers);
539 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
540 reply, sizeof(reply));
543 if (sr_modbus_error_check(reply))
545 if (memcmp(request, reply, sizeof(reply)))
552 * Close Modbus device.
554 * @param modbus Previously initialized Modbus device structure.
556 * @return SR_OK on success, SR_ERR on failure.
558 SR_PRIV int sr_modbus_close(struct sr_modbus_dev_inst *modbus)
560 return modbus->close(modbus->priv);
564 * Free Modbus device.
566 * @param modbus Previously initialized Modbus device structure.
568 * @return SR_OK on success, SR_ERR on failure.
570 SR_PRIV void sr_modbus_free(struct sr_modbus_dev_inst *modbus)
572 modbus->free(modbus->priv);
573 g_free(modbus->priv);