I2C improvements and fixes (#201)

- Show I2C device name in I2C Scanner app
- Register various I2C devices from board implementations
- Fix M5Stack Core2 power status
- Fix pre-allocation issue in `hal::Device`
This commit is contained in:
Ken Van Hoeylandt
2025-02-02 17:54:36 +01:00
committed by GitHub
parent 2e61aea93c
commit c0f4738abe
13 changed files with 133 additions and 59 deletions
@@ -1,6 +1,8 @@
#pragma once
#include <functional>
#include <memory>
#include <ranges>
#include <string>
#include <vector>
@@ -47,7 +49,6 @@ public:
virtual std::string getDescription() const = 0;
};
/**
* Adds a device to the registry.
* @warning This will leak memory if you want to destroy a device and don't call deregisterDevice()!
@@ -57,6 +58,12 @@ void registerDevice(const std::shared_ptr<Device>& device);
/** Remove a device from the registry. */
void deregisterDevice(const std::shared_ptr<Device>& device);
/** Find a single device with a custom filter */
std::shared_ptr<Device> _Nullable findDevice(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction);
/** Find devices with a custom filter */
std::vector<std::shared_ptr<Device>> findDevices(const std::function<bool(const std::shared_ptr<Device>&)>& filterFunction);
/** Find a device in the registry by its name. */
std::shared_ptr<Device> _Nullable findDevice(std::string name);
@@ -69,6 +76,25 @@ std::vector<std::shared_ptr<Device>> findDevices(Device::Type type);
/** Get a copy of the entire device registry in its current state. */
std::vector<std::shared_ptr<Device>> getDevices();
/** Find devices of a certain type and cast them to the specified class */
template<class DeviceType>
std::vector<std::shared_ptr<DeviceType>> findDevices(Device::Type type) {
auto devices = findDevices(type);
if (devices.empty()) {
return {};
} else {
std::vector<std::shared_ptr<DeviceType>> result;
result.reserve(devices.size());
for (auto& device : devices) {
auto target_device = std::static_pointer_cast<DeviceType>(device);
assert(target_device != nullptr);
result.push_back(target_device);
}
return std::move(result);
}
}
/** Find the first device of the specified type and cast it to the specified class */
template<class DeviceType>
std::shared_ptr<DeviceType> findFirstDevice(Device::Type type) {
auto devices = findDevices(type);
@@ -20,8 +20,6 @@ protected:
static constexpr TickType_t DEFAULT_TIMEOUT = 1000 / portTICK_PERIOD_MS;
Type getType() const override { return Type::I2c; }
bool readRegister8(uint8_t reg, uint8_t& result) const;
bool writeRegister8(uint8_t reg, uint8_t value) const;
bool readRegister12(uint8_t reg, float& out) const;
@@ -35,6 +33,12 @@ protected:
public:
explicit I2cDevice(i2c_port_t port, uint32_t address) : port(port), address(address) {}
Type getType() const override { return Type::I2c; }
i2c_port_t getPort() const { return port; }
uint8_t getAddress() const { return address; }
};
}