1 /*
2  * Copyright (c) 2021-2022 Actinius
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/init.h>
8 #include <zephyr/devicetree.h>
9 #include <zephyr/drivers/gpio.h>
10 #include <zephyr/logging/log.h>
11 
12 #if DT_HAS_COMPAT_STATUS_OKAY(actinius_sim_select) \
13 	|| DT_HAS_COMPAT_STATUS_OKAY(actinius_charger_enable)
14 
15 LOG_MODULE_REGISTER(actinius_board_control,
16 					CONFIG_ACTINIUS_BOARD_CONTROL_LOG_LEVEL);
17 
18 #define SIM_SELECT_NODE DT_NODELABEL(sim_select)
19 #define CHARGER_ENABLE_NODE DT_NODELABEL(charger_enable)
20 
21 #if DT_HAS_COMPAT_STATUS_OKAY(actinius_sim_select)
actinius_board_set_sim_select(void)22 static int actinius_board_set_sim_select(void)
23 {
24 	const struct gpio_dt_spec sim =
25 		GPIO_DT_SPEC_GET(SIM_SELECT_NODE, sim_gpios);
26 
27 	if (!gpio_is_ready_dt(&sim)) {
28 		LOG_ERR("The SIM Select Pin port is not ready");
29 
30 		return -ENODEV;
31 	}
32 
33 	if (DT_ENUM_IDX(SIM_SELECT_NODE, sim) == 0) {
34 		(void)gpio_pin_configure_dt(&sim, GPIO_OUTPUT_HIGH);
35 		LOG_INF("eSIM is selected");
36 	} else {
37 		(void)gpio_pin_configure_dt(&sim, GPIO_OUTPUT_LOW);
38 		LOG_INF("External SIM is selected");
39 	}
40 
41 	return 0;
42 }
43 #endif /* SIM_SELECT */
44 
45 #if DT_HAS_COMPAT_STATUS_OKAY(actinius_charger_enable)
actinius_board_set_charger_enable(void)46 static int actinius_board_set_charger_enable(void)
47 {
48 	const struct gpio_dt_spec charger_en =
49 		GPIO_DT_SPEC_GET(CHARGER_ENABLE_NODE, gpios);
50 
51 	if (!gpio_is_ready_dt(&charger_en)) {
52 		LOG_ERR("The Charger Enable Pin port is not ready");
53 		return -ENODEV;
54 	}
55 
56 	if (DT_ENUM_IDX(CHARGER_ENABLE_NODE, charger) == 0) {
57 		(void)gpio_pin_configure_dt(&charger_en, GPIO_OUTPUT_LOW);
58 		LOG_INF("Charger is set to auto");
59 	} else {
60 		(void)gpio_pin_configure_dt(&charger_en, GPIO_OUTPUT_HIGH);
61 		LOG_INF("Charger is disabled");
62 	}
63 
64 	return 0;
65 }
66 #endif /* CHARGER_ENABLE */
67 
actinius_board_init(void)68 static int actinius_board_init(void)
69 {
70 
71 	int result = 0;
72 
73 #if DT_HAS_COMPAT_STATUS_OKAY(actinius_sim_select)
74 	result = actinius_board_set_sim_select();
75 	if (result < 0) {
76 		LOG_ERR("Failed to set the SIM Select Pin (error: %d)", result);
77 		/* do not return so that the rest of the init process is attempted */
78 	}
79 #endif
80 
81 #if DT_HAS_COMPAT_STATUS_OKAY(actinius_charger_enable)
82 	result = actinius_board_set_charger_enable();
83 	if (result < 0) {
84 		LOG_ERR("Failed to set the Charger Enable Pin (error: %d)", result);
85 		/* do not return so that the rest of the init process is attempted */
86 	}
87 #endif
88 
89 	return result;
90 }
91 
92 /* Needs to happen after GPIO driver init */
93 SYS_INIT(actinius_board_init,
94 		POST_KERNEL,
95 		CONFIG_ACTINIUS_BOARD_CONTROL_INIT_PRIORITY);
96 
97 #endif /* SIM_SELECT || CHARGER_ENABLE */
98