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_SERIAL_COMM
32 &modbus_serial_rtu_dev, /* Must be last as it matches any resource. */
36 static const unsigned int modbus_devs_size = ARRAY_SIZE(modbus_devs);
38 static struct sr_dev_inst *sr_modbus_scan_resource(const char *resource,
39 const char *serialcomm, int modbusaddr,
40 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
42 struct sr_modbus_dev_inst *modbus;
43 struct sr_dev_inst *sdi;
45 if (!(modbus = modbus_dev_inst_new(resource, serialcomm, modbusaddr)))
48 if (sr_modbus_open(modbus) != SR_OK) {
49 sr_info("Couldn't open Modbus device.");
50 sr_modbus_free(modbus);
54 sdi = probe_device(modbus);
56 sr_modbus_close(modbus);
59 sr_modbus_free(modbus);
65 * Scan for Modbus devices which match a probing function.
67 * @param drvc The driver context doing the scan.
68 * @param options The scan options to find devies.
69 * @param probe_device The callback function that will be called for each
70 * found device to validate whether this device matches
71 * what we are scanning for.
73 * @return A list of the devices found or NULL if no devices were found.
75 SR_PRIV GSList *sr_modbus_scan(struct drv_context *drvc, GSList *options,
76 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
78 GSList *resources, *l, *devices;
79 struct sr_dev_inst *sdi;
80 const char *resource = NULL;
81 const char *serialcomm = NULL;
86 for (l = options; l; l = l->next) {
87 struct sr_config *src = l->data;
90 resource = g_variant_get_string(src->data, NULL);
92 case SR_CONF_SERIALCOMM:
93 serialcomm = g_variant_get_string(src->data, NULL);
95 case SR_CONF_MODBUSADDR:
96 modbusaddr = g_variant_get_uint64(src->data);
102 for (i = 0; i < modbus_devs_size; i++) {
103 if ((resource && strcmp(resource, modbus_devs[i]->prefix))
104 || !modbus_devs[i]->scan)
106 resources = modbus_devs[i]->scan(modbusaddr);
107 for (l = resources; l; l = l->next) {
108 res = g_strsplit(l->data, ":", 2);
109 if (res[0] && (sdi = sr_modbus_scan_resource(res[0],
110 serialcomm ? serialcomm : res[1],
111 modbusaddr, probe_device))) {
112 devices = g_slist_append(devices, sdi);
113 sdi->connection_id = g_strdup(l->data);
117 g_slist_free_full(resources, g_free);
120 if (!devices && resource) {
121 sdi = sr_modbus_scan_resource(resource, serialcomm, modbusaddr,
124 devices = g_slist_append(NULL, sdi);
127 /* Tack a copy of the newly found devices onto the driver list. */
129 drvc->instances = g_slist_concat(drvc->instances, g_slist_copy(devices));
135 * Allocate and initialize a struct for a Modbus device instance.
137 * @param resource The resource description string.
138 * @param serialcomm Additionnal parameters for serial port resources.
140 * @return The allocated sr_modbus_dev_inst structure or NULL on failure.
142 SR_PRIV struct sr_modbus_dev_inst *modbus_dev_inst_new(const char *resource,
143 const char *serialcomm, int modbusaddr)
145 struct sr_modbus_dev_inst *modbus = NULL;
146 const struct sr_modbus_dev_inst *modbus_dev;
150 for (i = 0; i < modbus_devs_size; i++) {
151 modbus_dev = modbus_devs[i];
152 if (!strncmp(resource, modbus_dev->prefix, strlen(modbus_dev->prefix))) {
153 sr_dbg("Opening %s device %s.", modbus_dev->name, resource);
154 modbus = g_malloc(sizeof(*modbus));
155 *modbus = *modbus_dev;
156 modbus->priv = g_malloc0(modbus->priv_size);
157 modbus->read_timeout_ms = 1000;
158 params = g_strsplit(resource, "/", 0);
159 if (modbus->dev_inst_new(modbus->priv, resource,
160 params, serialcomm, modbusaddr) != SR_OK) {
161 sr_modbus_free(modbus);
173 * Open the specified Modbus device.
175 * @param modbus Previously initialized Modbus device structure.
177 * @return SR_OK on success, SR_ERR on failure.
179 SR_PRIV int sr_modbus_open(struct sr_modbus_dev_inst *modbus)
181 return modbus->open(modbus->priv);
185 * Add an event source for a Modbus device.
187 * @param session The session to add the event source to.
188 * @param modbus Previously initialized Modbus device structure.
189 * @param events Events to check for.
190 * @param timeout Max time to wait before the callback is called, ignored if 0.
191 * @param cb Callback function to add. Must not be NULL.
192 * @param cb_data Data for the callback function. Can be NULL.
194 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
195 * SR_ERR_MALLOC upon memory allocation errors.
197 SR_PRIV int sr_modbus_source_add(struct sr_session *session,
198 struct sr_modbus_dev_inst *modbus, int events, int timeout,
199 sr_receive_data_callback cb, void *cb_data)
201 return modbus->source_add(session, modbus->priv, events, timeout, cb, cb_data);
205 * Remove event source for a Modbus device.
207 * @param session The session to remove the event source from.
208 * @param modbus Previously initialized Modbus device structure.
210 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
211 * SR_ERR_MALLOC upon memory allocation errors, SR_ERR_BUG upon
214 SR_PRIV int sr_modbus_source_remove(struct sr_session *session,
215 struct sr_modbus_dev_inst *modbus)
217 return modbus->source_remove(session, modbus->priv);
221 * Send a Modbus command.
223 * @param modbus Previously initialized Modbus device structure.
224 * @param request Buffer containing the Modbus command to send.
225 * @param request_size The size of the request buffer.
227 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
230 SR_PRIV int sr_modbus_request(struct sr_modbus_dev_inst *modbus,
231 uint8_t *request, int request_size)
233 if (!request || request_size < 1)
236 return modbus->send(modbus->priv, request, request_size);
240 * Receive a Modbus reply.
242 * @param modbus Previously initialized Modbus device structure.
243 * @param reply Buffer to store the received Modbus reply.
244 * @param reply_size The size of the reply buffer.
246 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
249 SR_PRIV int sr_modbus_reply(struct sr_modbus_dev_inst *modbus,
250 uint8_t *reply, int reply_size)
254 unsigned int elapsed_ms;
256 if (!reply || reply_size < 2)
259 laststart = g_get_monotonic_time();
261 ret = modbus->read_begin(modbus->priv, reply);
270 while (reply_size > 0) {
271 len = modbus->read_data(modbus->priv, reply, reply_size);
273 sr_err("Incompletely read Modbus response.");
275 } else if (len > 0) {
276 laststart = g_get_monotonic_time();
280 elapsed_ms = (g_get_monotonic_time() - laststart) / 1000;
281 if (elapsed_ms >= modbus->read_timeout_ms) {
282 sr_err("Timed out waiting for Modbus response.");
287 ret = modbus->read_end(modbus->priv);
295 * Send a Modbus command and receive the corresponding reply.
297 * @param modbus Previously initialized Modbus device structure.
298 * @param request Buffer containing the Modbus command to send.
299 * @param request_size The size of the request buffer.
300 * @param reply Buffer to store the received Modbus reply.
301 * @param reply_size The size of the reply buffer.
303 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
306 SR_PRIV int sr_modbus_request_reply(struct sr_modbus_dev_inst *modbus,
307 uint8_t *request, int request_size, uint8_t *reply, int reply_size)
310 ret = sr_modbus_request(modbus, request, request_size);
313 return sr_modbus_reply(modbus, reply, reply_size);
317 MODBUS_READ_COILS = 0x01,
318 MODBUS_READ_HOLDING_REGISTERS = 0x03,
319 MODBUS_WRITE_COIL = 0x05,
320 MODBUS_WRITE_MULTIPLE_REGISTERS = 0x10,
323 static int sr_modbus_error_check(const uint8_t *reply)
325 const char *function = "UNKNOWN";
326 const char *error = NULL;
329 if (!(reply[0] & 0x80))
332 switch (reply[0] & ~0x80) {
333 case MODBUS_READ_COILS:
334 function = "MODBUS_READ_COILS";
336 case MODBUS_READ_HOLDING_REGISTERS:
337 function = "READ_HOLDING_REGISTERS";
339 case MODBUS_WRITE_COIL:
340 function = "WRITE_COIL";
342 case MODBUS_WRITE_MULTIPLE_REGISTERS:
343 function = "WRITE_MULTIPLE_REGISTERS";
349 error = "ILLEGAL FUNCTION";
352 error = "ILLEGAL DATA ADDRESS";
355 error = "ILLEGAL DATA VALUE";
358 error = "SLAVE DEVICE FAILURE";
361 error = "ACKNOWLEDGE";
364 error = "SLAVE DEVICE BUSY";
367 error = "MEMORY PARITY ERROR";
370 error = "GATEWAY PATH UNAVAILABLE";
373 error = "GATEWAY TARGET DEVICE FAILED TO RESPOND";
377 snprintf(buf, sizeof(buf), "0x%X", reply[1]);
381 sr_err("%s error executing %s function.", error, function);
387 * Send a Modbus read coils command and receive the corresponding coils values.
389 * @param modbus Previously initialized Modbus device structure.
390 * @param address The Modbus address of the first coil to read, or -1 to read
391 * the reply of a previouly sent read coils command.
392 * @param nb_coils The number of coils to read.
393 * @param coils Buffer to store all the received coils values (1 bit per coil),
394 * or NULL to send the read coil command without reading the reply.
396 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
397 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
399 SR_PRIV int sr_modbus_read_coils(struct sr_modbus_dev_inst *modbus,
400 int address, int nb_coils, uint8_t *coils)
402 uint8_t request[5], reply[2 + (nb_coils + 7) / 8];
405 if (address < -1 || address > 0xFFFF || nb_coils < 1 || nb_coils > 2000)
408 W8(request + 0, MODBUS_READ_COILS);
409 WB16(request + 1, address);
410 WB16(request + 3, nb_coils);
413 ret = sr_modbus_request(modbus, request, sizeof(request));
419 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
422 if (sr_modbus_error_check(reply))
424 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)((nb_coils + 7) / 8))
426 memcpy(coils, reply + 2, (nb_coils + 7) / 8);
433 * Send a Modbus read holding registers command and receive the corresponding
436 * @param modbus Previously initialized Modbus device structure.
437 * @param address The Modbus address of the first register to read, or -1 to
438 * read the reply of a previouly sent read registers command.
439 * @param nb_registers The number of registers to read.
440 * @param registers Buffer to store all the received registers values,
441 * or NULL to send the read holding registers command
442 * without reading the reply.
444 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
445 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
447 SR_PRIV int sr_modbus_read_holding_registers(struct sr_modbus_dev_inst *modbus,
448 int address, int nb_registers, uint16_t *registers)
450 uint8_t request[5], reply[2 + (2 * nb_registers)];
453 if (address < -1 || address > 0xFFFF
454 || nb_registers < 1 || nb_registers > 125)
457 W8(request + 0, MODBUS_READ_HOLDING_REGISTERS);
458 WB16(request + 1, address);
459 WB16(request + 3, nb_registers);
462 ret = sr_modbus_request(modbus, request, sizeof(request));
468 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
471 if (sr_modbus_error_check(reply))
473 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)(2 * nb_registers))
475 memcpy(registers, reply + 2, 2 * nb_registers);
482 * Send a Modbus write coil command.
484 * @param modbus Previously initialized Modbus device structure.
485 * @param address The Modbus address of the coil to write.
486 * @param value The new value to assign to this coil.
488 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
489 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
491 SR_PRIV int sr_modbus_write_coil(struct sr_modbus_dev_inst *modbus,
492 int address, int value)
494 uint8_t request[5], reply[5];
497 if (address < 0 || address > 0xFFFF)
500 W8(request + 0, MODBUS_WRITE_COIL);
501 WB16(request + 1, address);
502 WB16(request + 3, value ? 0xFF00 : 0);
504 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
505 reply, sizeof(reply));
508 if (sr_modbus_error_check(reply))
510 if (memcmp(request, reply, sizeof(reply)))
517 * Send a Modbus write multiple registers command.
519 * @param modbus Previously initialized Modbus device structure.
520 * @param address The Modbus address of the first register to write.
521 * @param nb_registers The number of registers to write.
522 * @param registers Buffer holding all the registers values to write.
524 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
525 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
527 SR_PRIV int sr_modbus_write_multiple_registers(struct sr_modbus_dev_inst*modbus,
528 int address, int nb_registers, uint16_t *registers)
530 uint8_t request[6 + (2 * nb_registers)], reply[5];
533 if (address < 0 || address > 0xFFFF
534 || nb_registers < 1 || nb_registers > 123 || !registers)
537 W8(request + 0, MODBUS_WRITE_MULTIPLE_REGISTERS);
538 WB16(request + 1, address);
539 WB16(request + 3, nb_registers);
540 W8(request + 5, 2 * nb_registers);
541 memcpy(request + 6, registers, 2 * nb_registers);
543 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
544 reply, sizeof(reply));
547 if (sr_modbus_error_check(reply))
549 if (memcmp(request, reply, sizeof(reply)))
556 * Close Modbus device.
558 * @param modbus Previously initialized Modbus device structure.
560 * @return SR_OK on success, SR_ERR on failure.
562 SR_PRIV int sr_modbus_close(struct sr_modbus_dev_inst *modbus)
564 return modbus->close(modbus->priv);
568 * Free Modbus device.
570 * @param modbus Previously initialized Modbus device structure.
572 * @return SR_OK on success, SR_ERR on failure.
574 SR_PRIV void sr_modbus_free(struct sr_modbus_dev_inst *modbus)
576 modbus->free(modbus->priv);
577 g_free(modbus->priv);