1 /*
2  * Copyright (c) 2023 Libre Solar Technologies GmbH
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /*
8  * This test suite checks that correct errors are returned when trying to use the ISO-TP
9  * protocol with CAN FD mode even though the controller does not support CAN FD.
10  */
11 
12 #include <zephyr/canbus/isotp.h>
13 #include <zephyr/ztest.h>
14 
15 static const struct device *const can_dev = DEVICE_DT_GET(DT_CHOSEN(zephyr_canbus));
16 static struct isotp_recv_ctx recv_ctx;
17 static struct isotp_send_ctx send_ctx;
18 static bool canfd_capable;
19 
20 static const struct isotp_fc_opts fc_opts = {
21 	.bs = 0,
22 	.stmin = 0
23 };
24 
25 static const struct isotp_msg_id rx_addr = {
26 	.std_id = 0x20,
27 #ifdef CONFIG_TEST_USE_CAN_FD_MODE
28 	.dl = CONFIG_TEST_ISOTP_TX_DL,
29 	.flags = ISOTP_MSG_FDF | ISOTP_MSG_BRS,
30 #endif
31 };
32 
33 static const struct isotp_msg_id tx_addr = {
34 	.std_id = 0x21,
35 #ifdef CONFIG_TEST_USE_CAN_FD_MODE
36 	.dl = CONFIG_TEST_ISOTP_TX_DL,
37 	.flags = ISOTP_MSG_FDF | ISOTP_MSG_BRS,
38 #endif
39 };
40 
ZTEST(isotp_conformance_mode_check,test_bind)41 ZTEST(isotp_conformance_mode_check, test_bind)
42 {
43 	int err;
44 
45 	err = isotp_bind(&recv_ctx, can_dev, &rx_addr, &tx_addr, &fc_opts, K_NO_WAIT);
46 	if (IS_ENABLED(CONFIG_TEST_USE_CAN_FD_MODE) && !canfd_capable) {
47 		zassert_equal(err, ISOTP_N_ERROR);
48 	} else {
49 		zassert_equal(err, ISOTP_N_OK);
50 	}
51 
52 	isotp_unbind(&recv_ctx);
53 }
54 
ZTEST(isotp_conformance_mode_check,test_send)55 ZTEST(isotp_conformance_mode_check, test_send)
56 {
57 	uint8_t buf[] = { 1, 2, 3 };
58 	int err;
59 
60 	err = isotp_send(&send_ctx, can_dev, buf, sizeof(buf), &rx_addr, &tx_addr, NULL, NULL);
61 	if (IS_ENABLED(CONFIG_TEST_USE_CAN_FD_MODE) && !canfd_capable) {
62 		zassert_equal(err, ISOTP_N_ERROR);
63 	} else {
64 		zassert_equal(err, ISOTP_N_OK);
65 	}
66 }
67 
isotp_conformance_mode_check_setup(void)68 static void *isotp_conformance_mode_check_setup(void)
69 {
70 	can_mode_t cap;
71 	int err;
72 
73 	zassert_true(device_is_ready(can_dev), "CAN device not ready");
74 
75 	err = can_get_capabilities(can_dev, &cap);
76 	zassert_equal(err, 0, "failed to get CAN controller capabilities (err %d)", err);
77 
78 	canfd_capable = (cap & CAN_MODE_FD) != 0;
79 
80 	(void)can_stop(can_dev);
81 
82 	err = can_set_mode(can_dev, CAN_MODE_LOOPBACK | (canfd_capable ? CAN_MODE_FD : 0));
83 	zassert_equal(err, 0, "Failed to set mode [%d]", err);
84 
85 	err = can_start(can_dev);
86 	zassert_equal(err, 0, "Failed to start CAN controller [%d]", err);
87 
88 	return NULL;
89 }
90 
91 ZTEST_SUITE(isotp_conformance_mode_check, NULL, isotp_conformance_mode_check_setup, NULL, NULL,
92 	    NULL);
93