1 /*
2  * Copyright (c) 2021 Nordic Semiconductor ASA
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /**
8  * @file
9  *   This file implements the thermometer abstraction that uses Zephyr sensor
10  *   API for the die thermometer.
11  *
12  */
13 
14 #include "platform/nrf_802154_temperature.h"
15 
16 #include <zephyr/device.h>
17 #include <zephyr/drivers/sensor.h>
18 #include <zephyr/init.h>
19 #include <zephyr/kernel.h>
20 #include <zephyr/logging/log.h>
21 
22 /** @brief Default temperature [C] reported if NRF_802154_TEMPERATURE_UPDATE is disabled. */
23 #define DEFAULT_TEMPERATURE 20
24 
25 #define LOG_LEVEL LOG_LEVEL_INFO
26 #define LOG_MODULE_NAME nrf_802154_temperature
27 LOG_MODULE_REGISTER(LOG_MODULE_NAME);
28 
29 static int8_t value = DEFAULT_TEMPERATURE;
30 
31 
32 #if defined(CONFIG_NRF_802154_TEMPERATURE_UPDATE)
33 
34 static const struct device *const device = DEVICE_DT_GET(DT_NODELABEL(temp));
35 static struct k_work_delayable dwork;
36 
work_handler(struct k_work * work)37 static void work_handler(struct k_work *work)
38 {
39 	struct sensor_value val;
40 	int err;
41 
42 	err = sensor_sample_fetch(device);
43 	if (!err) {
44 		err = sensor_channel_get(device, SENSOR_CHAN_DIE_TEMP, &val);
45 	}
46 
47 	if (!err && (value != val.val1)) {
48 		value = val.val1;
49 
50 		nrf_802154_temperature_changed();
51 	}
52 
53 	k_work_reschedule(&dwork, K_MSEC(CONFIG_NRF_802154_TEMPERATURE_UPDATE_PERIOD));
54 }
55 
temperature_update_init(void)56 static int temperature_update_init(void)
57 {
58 
59 	__ASSERT_NO_MSG(device_is_ready(device));
60 
61 	k_work_init_delayable(&dwork, work_handler);
62 	k_work_schedule(&dwork, K_NO_WAIT);
63 
64 	return 0;
65 }
66 
67 SYS_INIT(temperature_update_init, POST_KERNEL, CONFIG_NRF_802154_TEMPERATURE_UPDATE_INIT_PRIO);
68 BUILD_ASSERT(CONFIG_SENSOR_INIT_PRIORITY < CONFIG_NRF_802154_TEMPERATURE_UPDATE_INIT_PRIO,
69 	     "CONFIG_SENSOR_INIT_PRIORITY must be lower than CONFIG_NRF_802154_TEMPERATURE_UPDATE_INIT_PRIO");
70 #endif /* defined(CONFIG_NRF_802154_TEMPERATURE_UPDATE) */
71 
nrf_802154_temperature_init(void)72 void nrf_802154_temperature_init(void)
73 {
74 	/* Intentionally empty. */
75 }
76 
nrf_802154_temperature_deinit(void)77 void nrf_802154_temperature_deinit(void)
78 {
79 	/* Intentionally empty. */
80 }
81 
nrf_802154_temperature_get(void)82 int8_t nrf_802154_temperature_get(void)
83 {
84 	return value;
85 }
86