somose 0.2.0

Driver for the BeFlE i2c soil moisiture sensor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
#![no_std]

use embedded_hal::i2c::I2c;

// I2C command constants
const CMD_HUMIDITY: u8 = 0x76;
const CMD_TEMPERATURE: u8 = 0x74;
const CMD_RAW_HUMIDITY: u8 = 0x72;
const CMD_REFERENCE_DRY: u8 = 0x64;
const CMD_REFERENCE_WET: u8 = 0x75;
const CMD_HARDWARE_VERSION: u8 = 0x68;
const CMD_FIRMWARE_VERSION: u8 = 0x66;
const CMD_SET_REFERENCE_DRY: u8 = 0x44;
const CMD_SET_REFERENCE_WET: u8 = 0x55;
const CMD_SET_NEW_ADDR: u8 = 0x41;
const CMD_RESET: u8 = 0x52;
const CMD_FACTORY_RESET: u8 = 0x46;
const CMD_SET_ENERGY_SAVE: u8 = 0x4C;
const CMD_START_MEASUREMENT: u8 = 0x4D;
const CMD_OPTIONS: u8 = 0x6F;

/// Driver for the BeFlE i2c soil moisture sensor
///
/// This driver provides both synchronous and asynchronous interfaces
/// for communicating with the Somose soil moisture sensor via I2C.
pub struct Somose<I2C> {
    i2c: I2C,
    addr: u8,
}

impl<I2C: I2c> Somose<I2C> {
    /// Create a new Somose driver instance
    ///
    /// # Arguments
    /// * `i2c` - The I2C bus instance
    /// * `addr` - The I2C address of the sensor (typically 0x55)
    ///
    /// # Returns
    /// Returns a Result containing the initialized driver or an I2C error
    pub fn new(i2c: I2C, addr: u8) -> Result<Self, I2C::Error> {
        let mut this = Self { i2c, addr };

        // Verify sensor communication by reading firmware version
        let _ = this.firmware_version()?;

        Ok(this)
    }

    /// Read humidity values from the sensor
    ///
    /// # Returns
    /// Returns a tuple containing (average_humidity, last_measurement)
    /// Both values are percentages (0-100)
    pub fn humidity(&mut self) -> Result<(u8, u8), I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c.write_read(self.addr, &[CMD_HUMIDITY], &mut read)?;
        Ok((read[0], read[1]))
    }

    /// Read temperature from the sensor
    ///
    /// # Returns
    /// Returns the temperature in degrees Celsius
    pub fn temperature(&mut self) -> Result<i8, I2C::Error> {
        let mut read = [0u8; 1];
        self.i2c
            .write_read(self.addr, &[CMD_TEMPERATURE], &mut read)?;
        Ok(read[0] as i8)
    }

    /// Read raw humidity value from the sensor
    ///
    /// # Returns
    /// Returns the raw 16-bit humidity reading
    pub fn raw_humidity(&mut self) -> Result<u16, I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_RAW_HUMIDITY], &mut read)?;
        Ok(u16::from_be_bytes(read))
    }

    /// Read the dry reference value
    ///
    /// # Returns
    /// Returns the 16-bit dry reference calibration value
    pub fn reference_dry(&mut self) -> Result<u16, I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_REFERENCE_DRY], &mut read)?;
        Ok(u16::from_be_bytes(read))
    }

    /// Read the wet reference value
    ///
    /// # Returns
    /// Returns the 16-bit wet reference calibration value
    pub fn reference_wet(&mut self) -> Result<u16, I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_REFERENCE_WET], &mut read)?;
        Ok(u16::from_be_bytes(read))
    }

    /// Read hardware version
    ///
    /// # Returns
    /// Returns a tuple containing (major_version, minor_version)
    pub fn hardware_version(&mut self) -> Result<(u8, u8), I2C::Error> {
        let mut read = [0u8; 4];
        self.i2c
            .write_read(self.addr, &[CMD_HARDWARE_VERSION], &mut read)?;

        debug_assert_eq!(read[0], b'v');
        debug_assert_eq!(read[2], b'.');

        Ok((read[1], read[3]))
    }

    /// Read firmware version
    ///
    /// # Returns
    /// Returns a tuple containing (major_version, minor_version)
    pub fn firmware_version(&mut self) -> Result<(u8, u8), I2C::Error> {
        let mut read = [0u8; 4];
        self.i2c
            .write_read(self.addr, &[CMD_FIRMWARE_VERSION], &mut read)?;

        debug_assert_eq!(read[0], b'v');
        debug_assert_eq!(read[2], b'.');

        Ok((read[1], read[3]))
    }

    /// Set the dry reference calibration value
    ///
    /// # Arguments
    /// * `value` - The 16-bit dry reference value
    pub fn set_reference_dry(&mut self, value: u16) -> Result<(), I2C::Error> {
        let bytes = value.to_be_bytes();
        self.i2c
            .write(self.addr, &[CMD_SET_REFERENCE_DRY, bytes[0], bytes[1]])
    }

    /// Set the wet reference calibration value
    ///
    /// # Arguments
    /// * `value` - The 16-bit wet reference value
    pub fn set_reference_wet(&mut self, value: u16) -> Result<(), I2C::Error> {
        let bytes = value.to_be_bytes();
        self.i2c
            .write(self.addr, &[CMD_SET_REFERENCE_WET, bytes[0], bytes[1]])
    }

    /// Change the I2C address of the sensor
    ///
    /// # Arguments
    /// * `addr` - The new I2C address (7-bit)
    ///
    /// # Note
    /// This change persists after power cycling
    pub fn set_new_addr(&mut self, addr: u8) -> Result<(), I2C::Error> {
        self.i2c.write(self.addr, &[CMD_SET_NEW_ADDR, addr])?;
        self.addr = addr;
        Ok(())
    }

    /// Reset the sensor
    pub fn reset(&mut self) -> Result<(), I2C::Error> {
        self.i2c.write(self.addr, &[CMD_RESET])
    }

    /// Perform a factory reset of the sensor
    ///
    /// # Note
    /// This will reset all calibration values and settings
    pub fn factory_reset(&mut self) -> Result<(), I2C::Error> {
        self.i2c.write(self.addr, &[CMD_FACTORY_RESET])
    }

    /// Enable or disable energy saving mode
    ///
    /// # Arguments
    /// * `enable` - true to enable energy saving, false to disable
    pub fn set_energy_save(&mut self, enable: bool) -> Result<(), I2C::Error> {
        self.i2c.write(
            self.addr,
            &[CMD_SET_ENERGY_SAVE, if enable { 1 } else { 0 }],
        )
    }

    /// Start a measurement cycle
    ///
    /// # Arguments
    /// * `repetitions` - Number of measurement repetitions to perform
    pub fn start_measurement(&mut self, repetitions: u8) -> Result<(), I2C::Error> {
        self.i2c
            .write(self.addr, &[CMD_START_MEASUREMENT, repetitions])
    }

    /// Read current sensor options/status
    ///
    /// # Returns
    /// Returns an Options struct containing current sensor state
    pub fn options(&mut self) -> Result<Options, I2C::Error> {
        let mut read = [0u8; 1];
        self.i2c.write_read(self.addr, &[CMD_OPTIONS], &mut read)?;

        Ok(Options {
            measurement_active: read[0] & 1 != 0,
            energy_save_active: (read[0] & (1 << 1)) != 0,
        })
    }
}

impl<I2C: embedded_hal_async::i2c::I2c> Somose<I2C> {
    /// Create a new Somose driver instance (async version)
    ///
    /// # Arguments
    /// * `i2c` - The async I2C bus instance
    /// * `addr` - The I2C address of the sensor (typically 0x55)
    ///
    /// # Returns
    /// Returns a Result containing the initialized driver or an I2C error
    pub async fn new_async(i2c: I2C, addr: u8) -> Result<Self, I2C::Error> {
        let mut this = Self { i2c, addr };

        // Verify sensor communication by reading firmware version
        let _ = this.firmware_version_async().await?;

        Ok(this)
    }

    /// Read humidity values from the sensor (async version)
    ///
    /// # Returns
    /// Returns a tuple containing (average_humidity, last_measurement)
    /// Both values are percentages (0-100)
    pub async fn humidity_async(&mut self) -> Result<(u8, u8), I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_HUMIDITY], &mut read)
            .await?;
        Ok((read[0], read[1]))
    }

    /// Read temperature from the sensor (async version)
    ///
    /// # Returns
    /// Returns the temperature in degrees Celsius
    pub async fn temperature_async(&mut self) -> Result<i8, I2C::Error> {
        let mut read = [0u8; 1];
        self.i2c
            .write_read(self.addr, &[CMD_TEMPERATURE], &mut read)
            .await?;
        Ok(read[0] as i8)
    }

    /// Read raw humidity value from the sensor (async version)
    ///
    /// # Returns
    /// Returns the raw 16-bit humidity reading
    pub async fn raw_humidity_async(&mut self) -> Result<u16, I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_RAW_HUMIDITY], &mut read)
            .await?;
        Ok(u16::from_be_bytes(read))
    }

    /// Read the dry reference value (async version)
    ///
    /// # Returns
    /// Returns the 16-bit dry reference calibration value
    pub async fn reference_dry_async(&mut self) -> Result<u16, I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_REFERENCE_DRY], &mut read)
            .await?;
        Ok(u16::from_be_bytes(read))
    }

    /// Read the wet reference value (async version)
    ///
    /// # Returns
    /// Returns the 16-bit wet reference calibration value
    pub async fn reference_wet_async(&mut self) -> Result<u16, I2C::Error> {
        let mut read = [0u8; 2];
        self.i2c
            .write_read(self.addr, &[CMD_REFERENCE_WET], &mut read)
            .await?;
        Ok(u16::from_be_bytes(read))
    }

    /// Read hardware version (async version)
    ///
    /// # Returns
    /// Returns a tuple containing (major_version, minor_version)
    pub async fn hardware_version_async(&mut self) -> Result<(u8, u8), I2C::Error> {
        let mut read = [0u8; 4];
        self.i2c
            .write_read(self.addr, &[CMD_HARDWARE_VERSION], &mut read)
            .await?;

        debug_assert_eq!(read[0], b'v');
        debug_assert_eq!(read[2], b'.');

        Ok((read[1], read[3]))
    }

    /// Read firmware version (async version)
    ///
    /// # Returns
    /// Returns a tuple containing (major_version, minor_version)
    pub async fn firmware_version_async(&mut self) -> Result<(u8, u8), I2C::Error> {
        let mut read = [0u8; 4];
        self.i2c
            .write_read(self.addr, &[CMD_FIRMWARE_VERSION], &mut read)
            .await?;

        debug_assert_eq!(read[0], b'v');
        debug_assert_eq!(read[2], b'.');

        Ok((read[1], read[3]))
    }

    /// Set the dry reference calibration value (async version)
    ///
    /// # Arguments
    /// * `value` - The 16-bit dry reference value
    pub async fn set_reference_dry_async(&mut self, value: u16) -> Result<(), I2C::Error> {
        let bytes = value.to_be_bytes();
        self.i2c
            .write(self.addr, &[CMD_SET_REFERENCE_DRY, bytes[0], bytes[1]])
            .await
    }

    /// Set the wet reference calibration value (async version)
    ///
    /// # Arguments
    /// * `value` - The 16-bit wet reference value
    pub async fn set_reference_wet_async(&mut self, value: u16) -> Result<(), I2C::Error> {
        let bytes = value.to_be_bytes();
        self.i2c
            .write(self.addr, &[CMD_SET_REFERENCE_WET, bytes[0], bytes[1]])
            .await
    }

    /// Change the I2C address of the sensor (async version)
    ///
    /// # Arguments
    /// * `addr` - The new I2C address (7-bit)
    ///
    /// # Note
    /// This change persists after power cycling
    pub async fn set_new_addr_async(&mut self, addr: u8) -> Result<(), I2C::Error> {
        self.i2c.write(self.addr, &[CMD_SET_NEW_ADDR, addr]).await?;
        self.addr = addr;
        Ok(())
    }

    /// Reset the sensor (async version)
    pub async fn reset_async(&mut self) -> Result<(), I2C::Error> {
        self.i2c.write(self.addr, &[CMD_RESET]).await
    }

    /// Perform a factory reset of the sensor (async version)
    ///
    /// # Note
    /// This will reset all calibration values and settings
    pub async fn factory_reset_async(&mut self) -> Result<(), I2C::Error> {
        self.i2c.write(self.addr, &[CMD_FACTORY_RESET]).await
    }

    /// Enable or disable energy saving mode (async version)
    ///
    /// # Arguments
    /// * `enable` - true to enable energy saving, false to disable
    pub async fn set_energy_save_async(&mut self, enable: bool) -> Result<(), I2C::Error> {
        self.i2c
            .write(
                self.addr,
                &[CMD_SET_ENERGY_SAVE, if enable { 1 } else { 0 }],
            )
            .await
    }

    /// Start a measurement cycle (async version)
    ///
    /// # Arguments
    /// * `repetitions` - Number of measurement repetitions to perform
    pub async fn start_measurement_async(&mut self, repetitions: u8) -> Result<(), I2C::Error> {
        self.i2c
            .write(self.addr, &[CMD_START_MEASUREMENT, repetitions])
            .await
    }

    /// Read current sensor options/status (async version)
    ///
    /// # Returns
    /// Returns an Options struct containing current sensor state
    pub async fn options_async(&mut self) -> Result<Options, I2C::Error> {
        let mut read = [0u8; 1];
        self.i2c
            .write_read(self.addr, &[CMD_OPTIONS], &mut read)
            .await?;

        Ok(Options {
            measurement_active: read[0] & 1 != 0,
            energy_save_active: (read[0] & (1 << 1)) != 0,
        })
    }
}

/// Sensor options and status information
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Options {
    /// Whether a measurement is currently active
    pub measurement_active: bool,
    /// Whether energy saving mode is enabled
    pub energy_save_active: bool,
}