]> sigrok.org Git - libsigrok.git/blame - src/modbus/modbus.c
Build: Include <config.h> first in all source files
[libsigrok.git] / src / modbus / modbus.c
CommitLineData
daa39012
AJ
1/*
2 * This file is part of the libsigrok project.
3 *
4 * Copyright (C) 2015 Aurelien Jacobs <aurel@gnuage.org>
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
6ec6c43b 20#include <config.h>
daa39012
AJ
21#include <glib.h>
22#include <string.h>
c1aae900 23#include <libsigrok/libsigrok.h>
f54ebe0c 24#include "libsigrok-internal.h"
daa39012
AJ
25
26#define LOG_PREFIX "modbus"
27
4c938fc2
AJ
28SR_PRIV extern const struct sr_modbus_dev_inst modbus_serial_rtu_dev;
29
daa39012 30static const struct sr_modbus_dev_inst *modbus_devs[] = {
4c938fc2 31#ifdef HAVE_LIBSERIALPORT
f54ebe0c 32 &modbus_serial_rtu_dev, /* Must be last as it matches any resource. */
4c938fc2 33#endif
daa39012
AJ
34};
35
36static struct sr_dev_inst *sr_modbus_scan_resource(const char *resource,
f54ebe0c
UH
37 const char *serialcomm, int modbusaddr,
38 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
daa39012
AJ
39{
40 struct sr_modbus_dev_inst *modbus;
41 struct sr_dev_inst *sdi;
42
43 if (!(modbus = modbus_dev_inst_new(resource, serialcomm, modbusaddr)))
44 return NULL;
45
46 if (sr_modbus_open(modbus) != SR_OK) {
ae1827f5 47 sr_info("Couldn't open Modbus device.");
daa39012
AJ
48 sr_modbus_free(modbus);
49 return NULL;
50 };
51
52 if ((sdi = probe_device(modbus)))
53 return sdi;
54
55 sr_modbus_close(modbus);
56 sr_modbus_free(modbus);
f54ebe0c 57
daa39012
AJ
58 return NULL;
59}
60
61/**
ae1827f5 62 * Scan for Modbus devices which match a probing function.
daa39012 63 *
f54ebe0c
UH
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.
daa39012 69 *
f54ebe0c 70 * @return A list of the devices found or NULL if no devices were found.
daa39012
AJ
71 */
72SR_PRIV GSList *sr_modbus_scan(struct drv_context *drvc, GSList *options,
f54ebe0c 73 struct sr_dev_inst *(*probe_device)(struct sr_modbus_dev_inst *modbus))
daa39012
AJ
74{
75 GSList *resources, *l, *devices;
76 struct sr_dev_inst *sdi;
77 const char *resource = NULL;
78 const char *serialcomm = NULL;
79 int modbusaddr = 1;
80 gchar **res;
f54ebe0c 81 unsigned int i;
daa39012
AJ
82
83 for (l = options; l; l = l->next) {
84 struct sr_config *src = l->data;
85 switch (src->key) {
86 case SR_CONF_CONN:
87 resource = g_variant_get_string(src->data, NULL);
88 break;
89 case SR_CONF_SERIALCOMM:
90 serialcomm = g_variant_get_string(src->data, NULL);
91 break;
92 case SR_CONF_MODBUSADDR:
93 modbusaddr = g_variant_get_uint64(src->data);
94 break;
95 }
96 }
97
98 devices = NULL;
99 for (i = 0; i < ARRAY_SIZE(modbus_devs); i++) {
100 if ((resource && strcmp(resource, modbus_devs[i]->prefix))
101 || !modbus_devs[i]->scan)
102 continue;
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],
f54ebe0c
UH
107 serialcomm ? serialcomm : res[1],
108 modbusaddr, probe_device))) {
daa39012
AJ
109 devices = g_slist_append(devices, sdi);
110 sdi->connection_id = g_strdup(l->data);
111 }
112 g_strfreev(res);
113 }
114 g_slist_free_full(resources, g_free);
115 }
116
117 if (!devices && resource) {
118 sdi = sr_modbus_scan_resource(resource, serialcomm, modbusaddr,
119 probe_device);
120 if (sdi)
121 devices = g_slist_append(NULL, sdi);
122 }
123
124 /* Tack a copy of the newly found devices onto the driver list. */
125 if (devices)
126 drvc->instances = g_slist_concat(drvc->instances, g_slist_copy(devices));
127
128 return devices;
129}
130
131/**
ae1827f5 132 * Allocate and initialize a struct for a Modbus device instance.
daa39012 133 *
f54ebe0c
UH
134 * @param resource The resource description string.
135 * @param serialcomm Additionnal parameters for serial port resources.
daa39012 136 *
f54ebe0c 137 * @return The allocated sr_modbus_dev_inst structure or NULL on failure.
daa39012
AJ
138 */
139SR_PRIV struct sr_modbus_dev_inst *modbus_dev_inst_new(const char *resource,
140 const char *serialcomm, int modbusaddr)
141{
142 struct sr_modbus_dev_inst *modbus = NULL;
143 const struct sr_modbus_dev_inst *modbus_dev;
144 gchar **params;
f54ebe0c 145 unsigned int i;
daa39012
AJ
146
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);
159 modbus = NULL;
160 }
161 g_strfreev(params);
162 break;
163 }
164 }
165
166 return modbus;
167}
168
169/**
ae1827f5 170 * Open the specified Modbus device.
daa39012 171 *
ae1827f5 172 * @param modbus Previously initialized Modbus device structure.
daa39012
AJ
173 *
174 * @return SR_OK on success, SR_ERR on failure.
175 */
176SR_PRIV int sr_modbus_open(struct sr_modbus_dev_inst *modbus)
177{
178 return modbus->open(modbus->priv);
179}
180
181/**
ae1827f5 182 * Add an event source for a Modbus device.
daa39012
AJ
183 *
184 * @param session The session to add the event source to.
ae1827f5 185 * @param modbus Previously initialized Modbus device structure.
daa39012
AJ
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.
190 *
191 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
192 * SR_ERR_MALLOC upon memory allocation errors.
193 */
194SR_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)
197{
198 return modbus->source_add(session, modbus->priv, events, timeout, cb, cb_data);
199}
200
201/**
ae1827f5 202 * Remove event source for a Modbus device.
daa39012
AJ
203 *
204 * @param session The session to remove the event source from.
ae1827f5 205 * @param modbus Previously initialized Modbus device structure.
daa39012
AJ
206 *
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
209 * internal errors.
210 */
211SR_PRIV int sr_modbus_source_remove(struct sr_session *session,
212 struct sr_modbus_dev_inst *modbus)
213{
214 return modbus->source_remove(session, modbus->priv);
215}
216
217/**
ae1827f5 218 * Send a Modbus command.
daa39012 219 *
ae1827f5
UH
220 * @param modbus Previously initialized Modbus device structure.
221 * @param request Buffer containing the Modbus command to send.
f54ebe0c 222 * @param request_size The size of the request buffer.
daa39012
AJ
223 *
224 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
225 * SR_ERR on failure.
226 */
227SR_PRIV int sr_modbus_request(struct sr_modbus_dev_inst *modbus,
228 uint8_t *request, int request_size)
229{
230 if (!request || request_size < 1)
231 return SR_ERR_ARG;
232
233 return modbus->send(modbus->priv, request, request_size);
234}
235
236/**
ae1827f5 237 * Receive a Modbus reply.
daa39012 238 *
ae1827f5
UH
239 * @param modbus Previously initialized Modbus device structure.
240 * @param reply Buffer to store the received Modbus reply.
f54ebe0c 241 * @param reply_size The size of the reply buffer.
daa39012
AJ
242 *
243 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
244 * SR_ERR on failure.
245 */
246SR_PRIV int sr_modbus_reply(struct sr_modbus_dev_inst *modbus,
247 uint8_t *reply, int reply_size)
248{
249 int len, ret;
250 gint64 laststart;
251 unsigned int elapsed_ms;
252
253 if (!reply || reply_size < 2)
254 return SR_ERR_ARG;
255
256 laststart = g_get_monotonic_time();
257
258 ret = modbus->read_begin(modbus->priv, reply);
259 if (ret != SR_OK)
260 return ret;
261 if (*reply & 0x80)
262 reply_size = 2;
263
264 reply++;
265 reply_size--;
266
267 while (reply_size > 0) {
268 len = modbus->read_data(modbus->priv, reply, reply_size);
269 if (len < 0) {
ae1827f5 270 sr_err("Incompletely read Modbus response.");
daa39012
AJ
271 return SR_ERR;
272 } else if (len > 0) {
273 laststart = g_get_monotonic_time();
274 }
275 reply += len;
276 reply_size -= len;
277 elapsed_ms = (g_get_monotonic_time() - laststart) / 1000;
278 if (elapsed_ms >= modbus->read_timeout_ms) {
ae1827f5 279 sr_err("Timed out waiting for Modbus response.");
daa39012
AJ
280 return SR_ERR;
281 }
282 }
283
284 ret = modbus->read_end(modbus->priv);
285 if (ret != SR_OK)
286 return ret;
287
288 return SR_OK;
289}
290
291/**
ae1827f5 292 * Send a Modbus command and receive the corresponding reply.
daa39012 293 *
ae1827f5
UH
294 * @param modbus Previously initialized Modbus device structure.
295 * @param request Buffer containing the Modbus command to send.
f54ebe0c 296 * @param request_size The size of the request buffer.
ae1827f5 297 * @param reply Buffer to store the received Modbus reply.
f54ebe0c 298 * @param reply_size The size of the reply buffer.
daa39012
AJ
299 *
300 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
301 * SR_ERR on failure.
302 */
303SR_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)
305{
306 int ret;
307 ret = sr_modbus_request(modbus, request, request_size);
308 if (ret != SR_OK)
309 return ret;
310 return sr_modbus_reply(modbus, reply, reply_size);
311}
312
313enum {
f54ebe0c
UH
314 MODBUS_READ_COILS = 0x01,
315 MODBUS_READ_HOLDING_REGISTERS = 0x03,
316 MODBUS_WRITE_COIL = 0x05,
daa39012
AJ
317 MODBUS_WRITE_MULTIPLE_REGISTERS = 0x10,
318};
319
320static int sr_modbus_error_check(const uint8_t *reply)
321{
322 const char *function = "UNKNOWN";
323 const char *error = NULL;
324 char buf[8];
325
326 if (!(reply[0] & 0x80))
327 return FALSE;
328
329 switch (reply[0] & ~0x80) {
330 case MODBUS_READ_COILS:
f54ebe0c
UH
331 function = "MODBUS_READ_COILS";
332 break;
daa39012 333 case MODBUS_READ_HOLDING_REGISTERS:
f54ebe0c
UH
334 function = "READ_HOLDING_REGISTERS";
335 break;
daa39012 336 case MODBUS_WRITE_COIL:
f54ebe0c
UH
337 function = "WRITE_COIL";
338 break;
daa39012 339 case MODBUS_WRITE_MULTIPLE_REGISTERS:
f54ebe0c
UH
340 function = "WRITE_MULTIPLE_REGISTERS";
341 break;
daa39012
AJ
342 }
343
344 switch (reply[1]) {
345 case 0x01:
f54ebe0c
UH
346 error = "ILLEGAL FUNCTION";
347 break;
daa39012 348 case 0x02:
f54ebe0c
UH
349 error = "ILLEGAL DATA ADDRESS";
350 break;
daa39012 351 case 0x03:
f54ebe0c
UH
352 error = "ILLEGAL DATA VALUE";
353 break;
daa39012 354 case 0x04:
f54ebe0c
UH
355 error = "SLAVE DEVICE FAILURE";
356 break;
daa39012 357 case 0x05:
f54ebe0c
UH
358 error = "ACKNOWLEDGE";
359 break;
daa39012 360 case 0x06:
f54ebe0c
UH
361 error = "SLAVE DEVICE BUSY";
362 break;
daa39012 363 case 0x08:
f54ebe0c
UH
364 error = "MEMORY PARITY ERROR";
365 break;
daa39012 366 case 0x0A:
f54ebe0c
UH
367 error = "GATEWAY PATH UNAVAILABLE";
368 break;
daa39012 369 case 0x0B:
f54ebe0c
UH
370 error = "GATEWAY TARGET DEVICE FAILED TO RESPOND";
371 break;
daa39012
AJ
372 }
373 if (!error) {
374 snprintf(buf, sizeof(buf), "0x%X", reply[1]);
375 error = buf;
376 }
377
378 sr_err("%s error executing %s function.", error, function);
f54ebe0c 379
daa39012
AJ
380 return TRUE;
381}
382
383/**
ae1827f5 384 * Send a Modbus read coils command and receive the corresponding coils values.
daa39012 385 *
ae1827f5
UH
386 * @param modbus Previously initialized Modbus device structure.
387 * @param address The Modbus address of the first coil to read, or -1 to read
f54ebe0c
UH
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),
daa39012
AJ
391 * or NULL to send the read coil command without reading the reply.
392 *
393 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
394 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
395 */
396SR_PRIV int sr_modbus_read_coils(struct sr_modbus_dev_inst *modbus,
397 int address, int nb_coils, uint8_t *coils)
398{
399 uint8_t request[5], reply[2 + (nb_coils + 7) / 8];
400 int ret;
401
402 if (address < -1 || address > 0xFFFF || nb_coils < 1 || nb_coils > 2000)
403 return SR_ERR_ARG;
404
f54ebe0c
UH
405 W8(request + 0, MODBUS_READ_COILS);
406 WB16(request + 1, address);
407 WB16(request + 3, nb_coils);
daa39012
AJ
408
409 if (address >= 0) {
410 ret = sr_modbus_request(modbus, request, sizeof(request));
411 if (ret != SR_OK)
412 return ret;
413 }
414
415 if (coils) {
416 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
417 if (ret != SR_OK)
418 return ret;
419 if (sr_modbus_error_check(reply))
420 return SR_ERR_DATA;
f54ebe0c 421 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)((nb_coils + 7) / 8))
daa39012 422 return SR_ERR_DATA;
f54ebe0c 423 memcpy(coils, reply + 2, (nb_coils + 7) / 8);
daa39012
AJ
424 }
425
426 return SR_OK;
427}
428
429/**
ae1827f5 430 * Send a Modbus read holding registers command and receive the corresponding
daa39012
AJ
431 * registers values.
432 *
ae1827f5
UH
433 * @param modbus Previously initialized Modbus device structure.
434 * @param address The Modbus address of the first register to read, or -1 to
f54ebe0c
UH
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,
daa39012
AJ
438 * or NULL to send the read holding registers command
439 * without reading the reply.
440 *
441 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
442 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
443 */
444SR_PRIV int sr_modbus_read_holding_registers(struct sr_modbus_dev_inst *modbus,
445 int address, int nb_registers, uint16_t *registers)
446{
f54ebe0c 447 uint8_t request[5], reply[2 + (2 * nb_registers)];
daa39012
AJ
448 int ret;
449
450 if (address < -1 || address > 0xFFFF
451 || nb_registers < 1 || nb_registers > 125)
452 return SR_ERR_ARG;
453
f54ebe0c
UH
454 W8(request + 0, MODBUS_READ_HOLDING_REGISTERS);
455 WB16(request + 1, address);
456 WB16(request + 3, nb_registers);
daa39012
AJ
457
458 if (address >= 0) {
459 ret = sr_modbus_request(modbus, request, sizeof(request));
460 if (ret != SR_OK)
461 return ret;
462 }
463
464 if (registers) {
465 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
466 if (ret != SR_OK)
467 return ret;
468 if (sr_modbus_error_check(reply))
469 return SR_ERR_DATA;
f54ebe0c 470 if (reply[0] != request[0] || R8(reply + 1) != (uint8_t)(2 * nb_registers))
daa39012 471 return SR_ERR_DATA;
f54ebe0c 472 memcpy(registers, reply + 2, 2 * nb_registers);
daa39012
AJ
473 }
474
475 return SR_OK;
476}
477
478/**
ae1827f5 479 * Send a Modbus write coil command.
daa39012 480 *
ae1827f5
UH
481 * @param modbus Previously initialized Modbus device structure.
482 * @param address The Modbus address of the coil to write.
f54ebe0c 483 * @param value The new value to assign to this coil.
daa39012
AJ
484 *
485 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
486 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
487 */
488SR_PRIV int sr_modbus_write_coil(struct sr_modbus_dev_inst *modbus,
489 int address, int value)
490{
491 uint8_t request[5], reply[5];
492 int ret;
493
494 if (address < 0 || address > 0xFFFF)
495 return SR_ERR_ARG;
496
f54ebe0c
UH
497 W8(request + 0, MODBUS_WRITE_COIL);
498 WB16(request + 1, address);
499 WB16(request + 3, value ? 0xFF00 : 0);
daa39012
AJ
500
501 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
f54ebe0c 502 reply, sizeof(reply));
daa39012
AJ
503 if (ret != SR_OK)
504 return ret;
505 if (sr_modbus_error_check(reply))
506 return SR_ERR_DATA;
507 if (memcmp(request, reply, sizeof(reply)))
508 return SR_ERR_DATA;
f54ebe0c 509
daa39012
AJ
510 return SR_OK;
511}
512
513/**
ae1827f5 514 * Send a Modbus write multiple registers command.
daa39012 515 *
ae1827f5
UH
516 * @param modbus Previously initialized Modbus device structure.
517 * @param address The Modbus address of the first register to write.
f54ebe0c
UH
518 * @param nb_registers The number of registers to write.
519 * @param registers Buffer holding all the registers values to write.
daa39012
AJ
520 *
521 * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
522 * SR_ERR_DATA upon invalid data, or SR_ERR on failure.
523 */
524SR_PRIV int sr_modbus_write_multiple_registers(struct sr_modbus_dev_inst*modbus,
525 int address, int nb_registers, uint16_t *registers)
526{
f54ebe0c 527 uint8_t request[6 + (2 * nb_registers)], reply[5];
daa39012
AJ
528 int ret;
529
530 if (address < 0 || address > 0xFFFF
531 || nb_registers < 1 || nb_registers > 123 || !registers)
532 return SR_ERR_ARG;
533
f54ebe0c
UH
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);
daa39012
AJ
539
540 ret = sr_modbus_request_reply(modbus, request, sizeof(request),
f54ebe0c 541 reply, sizeof(reply));
daa39012
AJ
542 if (ret != SR_OK)
543 return ret;
544 if (sr_modbus_error_check(reply))
545 return SR_ERR_DATA;
546 if (memcmp(request, reply, sizeof(reply)))
547 return SR_ERR_DATA;
f54ebe0c 548
daa39012
AJ
549 return SR_OK;
550}
551
552/**
ae1827f5 553 * Close Modbus device.
daa39012 554 *
ae1827f5 555 * @param modbus Previously initialized Modbus device structure.
daa39012
AJ
556 *
557 * @return SR_OK on success, SR_ERR on failure.
558 */
559SR_PRIV int sr_modbus_close(struct sr_modbus_dev_inst *modbus)
560{
561 return modbus->close(modbus->priv);
562}
563
564/**
ae1827f5 565 * Free Modbus device.
daa39012 566 *
ae1827f5 567 * @param modbus Previously initialized Modbus device structure.
daa39012
AJ
568 *
569 * @return SR_OK on success, SR_ERR on failure.
570 */
571SR_PRIV void sr_modbus_free(struct sr_modbus_dev_inst *modbus)
572{
573 modbus->free(modbus->priv);
574 g_free(modbus->priv);
575 g_free(modbus);
576}