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 		.stop_bits_client = UART_CFG_STOP_BITS_2,
23 	},
24 };
25 
26 #define MODBUS_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_modbus_serial)
27 
init_modbus_client(void)28 static int init_modbus_client(void)
29 {
30 	const char iface_name[] = {DEVICE_DT_NAME(MODBUS_NODE)};
31 
32 	client_iface = modbus_iface_get_by_name(iface_name);
33 
34 	return modbus_init_client(client_iface, client_param);
35 }
36 
main(void)37 int main(void)
38 {
39 	uint16_t holding_reg[8] = {'H', 'e', 'l', 'l', 'o'};
40 	const uint8_t coil_qty = 3;
41 	uint8_t coil[1] = {0};
42 	const int32_t sleep = 250;
43 	static uint8_t node = 1;
44 	int err;
45 
46 
47 	if (init_modbus_client()) {
48 		LOG_ERR("Modbus RTU client initialization failed");
49 		return 0;
50 	}
51 
52 	err = modbus_write_holding_regs(client_iface, node, 0, holding_reg,
53 					ARRAY_SIZE(holding_reg));
54 	if (err != 0) {
55 		LOG_ERR("FC16 failed with %d", err);
56 		return 0;
57 	}
58 
59 	err = modbus_read_holding_regs(client_iface, node, 0, holding_reg,
60 				       ARRAY_SIZE(holding_reg));
61 	if (err != 0) {
62 		LOG_ERR("FC03 failed with %d", err);
63 		return 0;
64 	}
65 
66 	LOG_HEXDUMP_INF(holding_reg, sizeof(holding_reg),
67 			"WR|RD holding register:");
68 
69 	while (true) {
70 		uint16_t addr = 0;
71 
72 		err = modbus_read_coils(client_iface, node, 0, coil, coil_qty);
73 		if (err != 0) {
74 			LOG_ERR("FC01 failed with %d", err);
75 			return 0;
76 		}
77 
78 		LOG_INF("Coils state 0x%02x", coil[0]);
79 
80 		err = modbus_write_coil(client_iface, node, addr++, true);
81 		if (err != 0) {
82 			LOG_ERR("FC05 failed with %d", err);
83 			return 0;
84 		}
85 
86 		k_msleep(sleep);
87 		err = modbus_write_coil(client_iface, node, addr++, true);
88 		if (err != 0) {
89 			LOG_ERR("FC05 failed with %d", err);
90 			return 0;
91 		}
92 
93 		k_msleep(sleep);
94 		err = modbus_write_coil(client_iface, node, addr++, true);
95 		if (err != 0) {
96 			LOG_ERR("FC05 failed with %d", err);
97 			return 0;
98 		}
99 
100 		k_msleep(sleep);
101 		err = modbus_read_coils(client_iface, node, 0, coil, coil_qty);
102 		if (err != 0) {
103 			LOG_ERR("FC01 failed with %d", err);
104 			return 0;
105 		}
106 
107 		LOG_INF("Coils state 0x%02x", coil[0]);
108 
109 		coil[0] = 0;
110 		err = modbus_write_coils(client_iface, node, 0, coil, coil_qty);
111 		if (err != 0) {
112 			LOG_ERR("FC15 failed with %d", err);
113 			return 0;
114 		}
115 
116 		k_msleep(sleep);
117 	}
118 }
119