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.

77 lines
2.3 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. // If we have already locked this address for this sensor quit
  32. if ((address > 0) && (address == _previous_address)) {
  33. return _previous_address;
  34. }
  35. // Check if we should release a previously locked address
  36. if ((_previous_address > 0) && (_previous_address != address)) {
  37. i2cReleaseLock(_previous_address);
  38. _previous_address = 0;
  39. }
  40. // If requesting a specific address, try to ger a lock to it
  41. if ((0 < address) && i2cGetLock(address)) {
  42. _previous_address = address;
  43. return _previous_address;
  44. }
  45. // If everything else fails, perform an auto-discover
  46. _previous_address = i2cFindAndLock(size, addresses);
  47. // Flag error
  48. if (0 == _previous_address) {
  49. _error = SENSOR_ERROR_I2C;
  50. }
  51. return _previous_address;
  52. }
  53. unsigned char _previous_address = 0;
  54. unsigned char _address = 0;
  55. };
  56. #endif // SENSOR_SUPPORT && I2C_SUPPORT