1 /*
2 * Copyright (c) 2023 Caspar Friedrich <c.s.w.friedrich@gmail.com>
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include "w1_ds2482-800.h"
8 #include "w1_ds2482_84_common.h"
9
10 #include <zephyr/devicetree.h>
11 #include <zephyr/drivers/i2c.h>
12 #include <zephyr/logging/log.h>
13
14 #define DT_DRV_COMPAT maxim_ds2482_800
15
16 LOG_MODULE_REGISTER(ds2482, CONFIG_W1_LOG_LEVEL);
17
18 struct ds2482_config {
19 const struct i2c_dt_spec i2c_spec;
20 };
21
22 struct ds2482_data {
23 struct k_mutex lock;
24 };
25
ds2482_change_bus_lock_impl(const struct device * dev,bool lock)26 int ds2482_change_bus_lock_impl(const struct device *dev, bool lock)
27 {
28 struct ds2482_data *data = dev->data;
29
30 return lock ? k_mutex_lock(&data->lock, K_FOREVER) : k_mutex_unlock(&data->lock);
31 }
32
ds2482_init(const struct device * dev)33 static int ds2482_init(const struct device *dev)
34 {
35 int ret;
36
37 const struct ds2482_config *config = dev->config;
38 struct ds2482_data *data = dev->data;
39
40 k_mutex_init(&data->lock);
41
42 if (!i2c_is_ready_dt(&config->i2c_spec)) {
43 return -ENODEV;
44 }
45
46 ret = ds2482_84_reset_device(&config->i2c_spec);
47 if (ret < 0) {
48 LOG_ERR("Device reset failed: %d", ret);
49 return ret;
50 }
51
52 return 0;
53 }
54
55 #define DS2482_INIT(inst) \
56 static const struct ds2482_config inst_##inst##_config = { \
57 .i2c_spec = I2C_DT_SPEC_INST_GET(inst), \
58 }; \
59 static struct ds2482_data inst_##inst##_data; \
60 DEVICE_DT_INST_DEFINE(inst, ds2482_init, NULL, &inst_##inst##_data, &inst_##inst##_config, \
61 POST_KERNEL, CONFIG_W1_INIT_PRIORITY, NULL);
62
63 DT_INST_FOREACH_STATUS_OKAY(DS2482_INIT)
64
65 /*
66 * Make sure that this driver is not initialized before the i2c bus is available
67 */
68 BUILD_ASSERT(CONFIG_W1_INIT_PRIORITY > CONFIG_I2C_INIT_PRIORITY);
69