1 /*
2  * Copyright (c) 2022 Nordic Semiconductor
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #define LOG_MODULE_NAME app_temp
8 #include <zephyr/logging/log.h>
9 LOG_MODULE_REGISTER(LOG_MODULE_NAME);
10 
11 #include "modules.h"
12 
13 #include <zephyr/drivers/hwinfo.h>
14 #include <zephyr/drivers/sensor.h>
15 #include <zephyr/net/lwm2m.h>
16 #include <zephyr/kernel.h>
17 #include <zephyr/random/random.h>
18 #include <stdint.h>
19 
20 static struct k_work_delayable temp_work;
21 #define PERIOD K_MINUTES(2)
22 
temp_work_cb(struct k_work * work)23 static void temp_work_cb(struct k_work *work)
24 {
25 	double v;
26 
27 	if (IS_ENABLED(CONFIG_FXOS8700_TEMP)) {
28 		const struct device *dev = device_get_binding("nxp_fxos8700");
29 		struct sensor_value val;
30 
31 		if (!dev) {
32 			LOG_ERR("device not ready.");
33 			goto out;
34 		}
35 		if (sensor_sample_fetch(dev)) {
36 			LOG_ERR("temperature data update failed");
37 			goto out;
38 		}
39 
40 		sensor_channel_get(dev, SENSOR_CHAN_DIE_TEMP, &val);
41 
42 		v = sensor_value_to_double(&val);
43 	} else {
44 		/* Generate dummy temperature data */
45 		v = 20.0 + (double)sys_rand32_get() / UINT32_MAX * 5.0;
46 	}
47 
48 	lwm2m_set_f64(&LWM2M_OBJ(3303, 0, 5700), v);
49 
50 out:
51 	k_work_schedule(&temp_work, PERIOD);
52 }
53 
init_temp_sensor(void)54 void init_temp_sensor(void)
55 {
56 	if (lwm2m_create_object_inst(&LWM2M_OBJ(3303, 0)) == 0) {
57 		k_work_init_delayable(&temp_work, temp_work_cb);
58 		k_work_schedule(&temp_work, K_NO_WAIT);
59 	}
60 }
61