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