Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

73 lines
2.1 KiB

  1. // -----------------------------------------------------------------------------
  2. // Abstract I2C sensor class (other sensor classes extend this class)
  3. // Copyright (C) 2017-2018 by Xose Pérez <xose dot perez at gmail dot com>
  4. // -----------------------------------------------------------------------------
  5. #if SENSOR_SUPPORT && ( I2C_SUPPORT || EMON_ANALOG_SUPPORT )
  6. #pragma once
  7. #include "BaseSensor.h"
  8. class I2CSensor : public BaseSensor {
  9. public:
  10. void setAddress(unsigned char address) {
  11. if (_address == address) return;
  12. _address = address;
  13. _dirty = true;
  14. }
  15. unsigned char getAddress() {
  16. return _address;
  17. }
  18. // Descriptive name of the slot # index
  19. String slot(unsigned char index) {
  20. return description();
  21. };
  22. // Address of the sensor (it could be the GPIO or I2C address)
  23. String address(unsigned char index) {
  24. char buffer[5];
  25. snprintf(buffer, sizeof(buffer), "0x%02X", _address);
  26. return String(buffer);
  27. }
  28. protected:
  29. // Specific for I2C sensors
  30. unsigned char _begin_i2c(unsigned char address, size_t size, unsigned char * addresses) {
  31. // Check if we should release a previously locked address
  32. if (_previous_address != address) {
  33. i2cReleaseLock(_previous_address);
  34. }
  35. // If we have already an address, check it is not locked
  36. if (address && !i2cGetLock(address)) {
  37. _error = SENSOR_ERROR_I2C;
  38. // If we don't have an address...
  39. } else {
  40. // Trigger auto-discover
  41. address = i2cFindAndLock(size, addresses);
  42. // If still nothing exit with error
  43. if (address == 0) _error = SENSOR_ERROR_I2C;
  44. }
  45. _previous_address = address;
  46. return address;
  47. }
  48. unsigned char _previous_address = 0;
  49. unsigned char _address = 0;
  50. };
  51. #endif // SENSOR_SUPPORT && I2C_SUPPORT