]> sigrok.org Git - libsigrok.git/blob - src/modbus/modbus.c
Actual implementation for the maynuo-m97 driver.
[libsigrok.git] / src / modbus / modbus.c
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
20 #include "libsigrok.h"
21 #include "libsigrok-internal.h"
22
23 #include <glib.h>
24 #include <string.h>
25
26 #define LOG_PREFIX "modbus"
27
28 SR_PRIV extern const struct sr_modbus_dev_inst modbus_serial_rtu_dev;
29
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 */
33 #endif
34 };
35
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))
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) {
47                 sr_info("Couldn't open MODBUS device.");
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);
57         return NULL;
58 }
59
60 /**
61  *  Scan for MODBUS devices which match a probing function.
62  *
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 devices to validate wheter this device matches
67  *                      what we are scanning for.
68  *
69  *  @return a list of the devices found or NULL if no device found.
70  */
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))
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;
80         unsigned i;
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],
106                                                          serialcomm ? serialcomm : res[1],
107                                                          modbusaddr, probe_device))) {
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 /**
131  *  Allocate and initialize struct for a MODBUS device instance.
132  *
133  *  @param resource the resource description string.
134  *  @param serialcomm additionnal parameters for serial port resources.
135  *
136  *  @return the allocated sr_modbus_dev_inst structure or NULL on failure.
137  */
138 SR_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;
144         unsigned i;
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 /**
169  * Open MODBUS device.
170  *
171  * @param modbus Previously initialized MODBUS device structure.
172  *
173  * @return SR_OK on success, SR_ERR on failure.
174  */
175 SR_PRIV int sr_modbus_open(struct sr_modbus_dev_inst *modbus)
176 {
177         return modbus->open(modbus->priv);
178 }
179
180 /**
181  * Add an event source for an MODBUS device.
182  *
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.
189  *
190  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
191  *         SR_ERR_MALLOC upon memory allocation errors.
192  */
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)
196 {
197         return modbus->source_add(session, modbus->priv, events, timeout, cb, cb_data);
198 }
199
200 /**
201  * Remove event source for an MODBUS device.
202  *
203  * @param session The session to remove the event source from.
204  * @param modbus Previously initialized MODBUS device structure.
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  */
210 SR_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 /**
217  * Send a MODBUS command.
218  *
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.
222  *
223  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
224  *         SR_ERR on failure.
225  */
226 SR_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 /**
236  * Receive a MODBUS reply.
237  *
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.
241  *
242  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
243  *         SR_ERR on failure.
244  */
245 SR_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) {
269                         sr_err("Incompletely read MODBUS response.");
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) {
278                         sr_err("Timed out waiting for MODBUS response.");
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 /**
291  * Send a MODBUS command and receive the corresponding reply.
292  *
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.
298  *
299  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments, or
300  *         SR_ERR on failure.
301  */
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)
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
312 enum {
313         MODBUS_READ_COILS               = 0x01,
314         MODBUS_READ_HOLDING_REGISTERS   = 0x03,
315         MODBUS_WRITE_COIL               = 0x05,
316         MODBUS_WRITE_MULTIPLE_REGISTERS = 0x10,
317 };
318
319 static 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:
330                 function = "MODBUS_READ_COILS";  break;
331         case MODBUS_READ_HOLDING_REGISTERS:
332                 function = "READ_HOLDING_REGISTERS";  break;
333         case MODBUS_WRITE_COIL:
334                 function = "WRITE_COIL"; break;
335         case MODBUS_WRITE_MULTIPLE_REGISTERS:
336                 function = "WRITE_MULTIPLE_REGISTERS"; break;
337         }
338
339         switch (reply[1]) {
340         case 0x01:
341                 error = "ILLEGAL FUNCTION";  break;
342         case 0x02:
343                 error = "ILLEGAL DATA ADDRESS";  break;
344         case 0x03:
345                 error = "ILLEGAL DATA VALUE"; break;
346         case 0x04:
347                 error = "SLAVE DEVICE FAILURE"; break;
348         case 0x05:
349                 error = "ACKNOWLEDGE"; break;
350         case 0x06:
351                 error = "SLAVE DEVICE BUSY"; break;
352         case 0x08:
353                 error = "MEMORY PARITY ERROR"; break;
354         case 0x0A:
355                 error = "GATEWAY PATH UNAVAILABLE"; break;
356         case 0x0B:
357                 error = "GATEWAY TARGET DEVICE FAILED TO RESPOND"; break;
358         }
359         if (!error) {
360                 snprintf(buf, sizeof(buf), "0x%X", reply[1]);
361                 error = buf;
362         }
363
364         sr_err("%s error executing %s function.", error, function);
365         return TRUE;
366 }
367
368 /**
369  * Send a MODBUS read coils command and receive the corresponding coils values.
370  *
371  * @param modbus Previously initialized MODBUS device structure.
372  * @param address the MODBUS address of the first coil to read,
373  *                or -1 to read the reply of a previouly sent
374  *                read coils command.
375  * @param nb_coils the number of coils to read.
376  * @param coils buffer to store all the received coils values (1 bit per coil),
377  *              or NULL to send the read coil command without reading the reply.
378  *
379  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
380  *         SR_ERR_DATA upon invalid data, or SR_ERR on failure.
381  */
382 SR_PRIV int sr_modbus_read_coils(struct sr_modbus_dev_inst *modbus,
383                 int address, int nb_coils, uint8_t *coils)
384 {
385         uint8_t request[5], reply[2 + (nb_coils + 7) / 8];
386         int ret;
387
388         if (address < -1 || address > 0xFFFF || nb_coils < 1 || nb_coils > 2000)
389                 return SR_ERR_ARG;
390
391         W8  (request+0, MODBUS_READ_COILS);
392         WB16(request+1, address);
393         WB16(request+3, nb_coils);
394
395         if (address >= 0) {
396                 ret = sr_modbus_request(modbus, request, sizeof(request));
397                 if (ret != SR_OK)
398                         return ret;
399         }
400
401         if (coils) {
402                 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
403                 if (ret != SR_OK)
404                         return ret;
405                 if (sr_modbus_error_check(reply))
406                         return SR_ERR_DATA;
407                 if (reply[0] != request[0] || R8(reply+1) != (uint8_t)((nb_coils+7)/8))
408                         return SR_ERR_DATA;
409                 memcpy(coils, reply+2, (nb_coils+7)/8);
410         }
411
412         return SR_OK;
413 }
414
415 /**
416  * Send a MODBUS read holding registers command and receive the corresponding
417  * registers values.
418  *
419  * @param modbus Previously initialized MODBUS device structure.
420  * @param address the MODBUS address of the first register to read,
421  *                or -1 to read the reply of a previouly sent
422  *                read registers command.
423  * @param nb_registers the number of registers to read.
424  * @param registers buffer to store all the received registers values,
425  *                  or NULL to send the read holding registers command
426  *                  without reading the reply.
427  *
428  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
429  *         SR_ERR_DATA upon invalid data, or SR_ERR on failure.
430  */
431 SR_PRIV int sr_modbus_read_holding_registers(struct sr_modbus_dev_inst *modbus,
432                 int address, int nb_registers, uint16_t *registers)
433 {
434         uint8_t request[5], reply[2 + 2*nb_registers];
435         int ret;
436
437         if (address < -1 || address > 0xFFFF
438             || nb_registers < 1 || nb_registers > 125)
439                 return SR_ERR_ARG;
440
441         W8  (request+0, MODBUS_READ_HOLDING_REGISTERS);
442         WB16(request+1, address);
443         WB16(request+3, nb_registers);
444
445         if (address >= 0) {
446                 ret = sr_modbus_request(modbus, request, sizeof(request));
447                 if (ret != SR_OK)
448                         return ret;
449         }
450
451         if (registers) {
452                 ret = sr_modbus_reply(modbus, reply, sizeof(reply));
453                 if (ret != SR_OK)
454                         return ret;
455                 if (sr_modbus_error_check(reply))
456                         return SR_ERR_DATA;
457                 if (reply[0] != request[0] || R8(reply+1) != (uint8_t)(2*nb_registers))
458                         return SR_ERR_DATA;
459                 memcpy(registers, reply+2, 2*nb_registers);
460         }
461
462         return SR_OK;
463 }
464
465 /**
466  * Send a MODBUS write coil command.
467  *
468  * @param modbus Previously initialized MODBUS device structure.
469  * @param address the MODBUS address of the coil to write.
470  * @param value the new value to assign to this coil.
471  *
472  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
473  *         SR_ERR_DATA upon invalid data, or SR_ERR on failure.
474  */
475 SR_PRIV int sr_modbus_write_coil(struct sr_modbus_dev_inst *modbus,
476                 int address, int value)
477 {
478         uint8_t request[5], reply[5];
479         int ret;
480
481         if (address < 0 || address > 0xFFFF)
482                 return SR_ERR_ARG;
483
484         W8  (request+0, MODBUS_WRITE_COIL);
485         WB16(request+1, address);
486         WB16(request+3, value ? 0xFF00 : 0);
487
488         ret = sr_modbus_request_reply(modbus, request, sizeof(request),
489                                               reply  , sizeof(reply));
490         if (ret != SR_OK)
491                 return ret;
492         if (sr_modbus_error_check(reply))
493                 return SR_ERR_DATA;
494         if (memcmp(request, reply, sizeof(reply)))
495                 return SR_ERR_DATA;
496         return SR_OK;
497 }
498
499 /**
500  * Send a MODBUS write multiple registers command.
501  *
502  * @param modbus Previously initialized MODBUS device structure.
503  * @param address the MODBUS address of the first register to write.
504  * @param nb_registers the number of registers to write.
505  * @param registers buffer holding all the registers values to write.
506  *
507  * @return SR_OK upon success, SR_ERR_ARG upon invalid arguments,
508  *         SR_ERR_DATA upon invalid data, or SR_ERR on failure.
509  */
510 SR_PRIV int sr_modbus_write_multiple_registers(struct sr_modbus_dev_inst*modbus,
511                 int address, int nb_registers, uint16_t *registers)
512 {
513         uint8_t request[6+2*nb_registers], reply[5];
514         int ret;
515
516         if (address < 0 || address > 0xFFFF
517             || nb_registers < 1 || nb_registers > 123 || !registers)
518                 return SR_ERR_ARG;
519
520         W8  (request+0, MODBUS_WRITE_MULTIPLE_REGISTERS);
521         WB16(request+1, address);
522         WB16(request+3, nb_registers);
523         W8  (request+5, 2*nb_registers);
524         memcpy(request+6, registers, 2*nb_registers);
525
526         ret = sr_modbus_request_reply(modbus, request, sizeof(request),
527                                               reply  , sizeof(reply));
528         if (ret != SR_OK)
529                 return ret;
530         if (sr_modbus_error_check(reply))
531                 return SR_ERR_DATA;
532         if (memcmp(request, reply, sizeof(reply)))
533                 return SR_ERR_DATA;
534         return SR_OK;
535 }
536
537 /**
538  * Close MODBUS device.
539  *
540  * @param modbus Previously initialized MODBUS device structure.
541  *
542  * @return SR_OK on success, SR_ERR on failure.
543  */
544 SR_PRIV int sr_modbus_close(struct sr_modbus_dev_inst *modbus)
545 {
546         return modbus->close(modbus->priv);
547 }
548
549 /**
550  * Free MODBUS device.
551  *
552  * @param modbus Previously initialized MODBUS device structure.
553  *
554  * @return SR_OK on success, SR_ERR on failure.
555  */
556 SR_PRIV void sr_modbus_free(struct sr_modbus_dev_inst *modbus)
557 {
558         modbus->free(modbus->priv);
559         g_free(modbus->priv);
560         g_free(modbus);
561 }