1 /*
2  * Copyright (c) 2021 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "test_modbus.h"
8 
9 #include <zephyr/logging/log.h>
10 LOG_MODULE_REGISTER(raw_test, LOG_LEVEL_INF);
11 
12 static struct modbus_adu tmp_adu;
13 K_SEM_DEFINE(received, 0, 1);
14 
15 /*
16  * Server wants to send the data back.
17  * We just store them in between and pass them to the client.
18  */
server_raw_cb(const int iface,const struct modbus_adu * adu,void * user_data)19 int server_raw_cb(const int iface, const struct modbus_adu *adu,
20 		void *user_data)
21 {
22 	LOG_DBG("Server raw callback from interface %d", iface);
23 
24 	tmp_adu.trans_id = adu->trans_id;
25 	tmp_adu.proto_id = adu->proto_id;
26 	tmp_adu.length = adu->length;
27 	tmp_adu.unit_id = adu->unit_id;
28 	tmp_adu.fc = adu->fc;
29 	memcpy(tmp_adu.data, adu->data,
30 	       MIN(adu->length, sizeof(tmp_adu.data)));
31 
32 	LOG_HEXDUMP_DBG(tmp_adu.data, tmp_adu.length, "resp");
33 	k_sem_give(&received);
34 
35 	return 0;
36 }
37 
38 /*
39  * Client wants to send the data via whatever.
40  * We just store it in between and submit to the server.
41  */
client_raw_cb(const int iface,const struct modbus_adu * adu,void * user_data)42 int client_raw_cb(const int iface, const struct modbus_adu *adu,
43 		void *user_data)
44 {
45 	uint8_t server_iface = test_get_server_iface();
46 	uint8_t client_iface = test_get_client_iface();
47 
48 	LOG_DBG("Client raw callback from interface %d", iface);
49 
50 	tmp_adu.trans_id = adu->trans_id;
51 	tmp_adu.proto_id = adu->proto_id;
52 	tmp_adu.length = adu->length;
53 	tmp_adu.unit_id = adu->unit_id;
54 	tmp_adu.fc = adu->fc;
55 	memcpy(tmp_adu.data, adu->data,
56 	       MIN(adu->length, sizeof(tmp_adu.data)));
57 
58 	LOG_HEXDUMP_DBG(tmp_adu.data, tmp_adu.length, "c->s");
59 
60 	/*
61 	 * modbus_raw_submit_rx() copies the data to the internal memory
62 	 * so that tmp_adu can be used immediately afterwards.
63 	 */
64 	modbus_raw_submit_rx(server_iface, &tmp_adu);
65 
66 	if (k_sem_take(&received, K_MSEC(1000)) != 0) {
67 		zassert_true(0, "MODBUS RAW wait time expired");
68 	}
69 
70 	modbus_raw_submit_rx(client_iface, &tmp_adu);
71 
72 	return 0;
73 }
74