1 /*
2  * Copyright (c) 2020 PHYTEC Messtechnik GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/kernel.h>
8 #include <zephyr/sys/util.h>
9 #include <zephyr/modbus/modbus.h>
10 
11 #include <zephyr/logging/log.h>
12 LOG_MODULE_REGISTER(mbc_sample, LOG_LEVEL_INF);
13 
14 static int client_iface;
15 
16 const static struct modbus_iface_param client_param = {
17 	.mode = MODBUS_MODE_RTU,
18 	.rx_timeout = 50000,
19 	.serial = {
20 		.baud = 19200,
21 		.parity = UART_CFG_PARITY_NONE,
22 	},
23 };
24 
25 #define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial)
26 
init_modbus_client(void)27 static int init_modbus_client(void)
28 {
29 	const char iface_name[] = {DEVICE_DT_NAME(MODBUS_NODE)};
30 
31 	client_iface = modbus_iface_get_by_name(iface_name);
32 
33 	return modbus_init_client(client_iface, client_param);
34 }
35 
main(void)36 int main(void)
37 {
38 	uint16_t holding_reg[8] = {'H', 'e', 'l', 'l', 'o'};
39 	const uint8_t coil_qty = 3;
40 	uint8_t coil[1] = {0};
41 	const int32_t sleep = 250;
42 	static uint8_t node = 1;
43 	int err;
44 
45 
46 	if (init_modbus_client()) {
47 		LOG_ERR("Modbus RTU client initialization failed");
48 		return 0;
49 	}
50 
51 	err = modbus_write_holding_regs(client_iface, node, 0, holding_reg,
52 					ARRAY_SIZE(holding_reg));
53 	if (err != 0) {
54 		LOG_ERR("FC16 failed with %d", err);
55 		return 0;
56 	}
57 
58 	err = modbus_read_holding_regs(client_iface, node, 0, holding_reg,
59 				       ARRAY_SIZE(holding_reg));
60 	if (err != 0) {
61 		LOG_ERR("FC03 failed with %d", err);
62 		return 0;
63 	}
64 
65 	LOG_HEXDUMP_INF(holding_reg, sizeof(holding_reg),
66 			"WR|RD holding register:");
67 
68 	while (true) {
69 		uint16_t addr = 0;
70 
71 		err = modbus_read_coils(client_iface, node, 0, coil, coil_qty);
72 		if (err != 0) {
73 			LOG_ERR("FC01 failed with %d", err);
74 			return 0;
75 		}
76 
77 		LOG_INF("Coils state 0x%02x", coil[0]);
78 
79 		err = modbus_write_coil(client_iface, node, addr++, true);
80 		if (err != 0) {
81 			LOG_ERR("FC05 failed with %d", err);
82 			return 0;
83 		}
84 
85 		k_msleep(sleep);
86 		err = modbus_write_coil(client_iface, node, addr++, true);
87 		if (err != 0) {
88 			LOG_ERR("FC05 failed with %d", err);
89 			return 0;
90 		}
91 
92 		k_msleep(sleep);
93 		err = modbus_write_coil(client_iface, node, addr++, true);
94 		if (err != 0) {
95 			LOG_ERR("FC05 failed with %d", err);
96 			return 0;
97 		}
98 
99 		k_msleep(sleep);
100 		err = modbus_read_coils(client_iface, node, 0, coil, coil_qty);
101 		if (err != 0) {
102 			LOG_ERR("FC01 failed with %d", err);
103 			return 0;
104 		}
105 
106 		LOG_INF("Coils state 0x%02x", coil[0]);
107 
108 		coil[0] = 0;
109 		err = modbus_write_coils(client_iface, node, 0, coil, coil_qty);
110 		if (err != 0) {
111 			LOG_ERR("FC15 failed with %d", err);
112 			return 0;
113 		}
114 
115 		k_msleep(sleep);
116 	}
117 }
118