bphermansson / EspSparsnasGateway

Reads data from Ikea Sparsnäs energy meter and publish via Mqtt.
MIT License
39 stars 27 forks source link

Suggestion: create a Sparsnas class that handles everything related to the received package #55

Open fredrike opened 4 years ago

fredrike commented 4 years ago

It's been bugging me the whole day yesterday and I think the sparsnäs decoding should be extracted to a separate class. This will enable easy access to multiple sensors like @Sperra suggested and also much cleaner code base.

My suggestion is that we move most parts of interruptHandler() into a class like this one:

class Sparsnas
{
private:
    uint32_t my_sensor_id;
    uint16_t my_pulses_per_kwh;
    uint8_t my_received_data[21];
    uint8_t my_decrypted_data[21];

 static:
    bool check_crc(unit8_t data[18]);

public:
    Sparsnas(uint32_t sensor_id, uint16_t pulses_per_kwh, uint8_t received_data[21);
    bool isValidPackage();  // This will do the decryption and crc_check.
    uint16_t getPower();
    float getWatt();
    uint16_t getSequence();
    char* getStatusString();
    char* getJsonString();
};

This means that https://github.com/fredrike/EspSparsnasGateway/blob/ce54c56d7d22fca426e0615b3bc3ebdf0c01dba9/src/RFM69functions.cpp#L315-L464 can be replaced with (and that the Sparsnas class can be reused in other projects):

    // Read 20 bytes
    for (uint8_t i = 0; i < 20; i++) {
      TEMPDATA[i] = SPI.transfer(0);
    }
    Sparsnas* sp = new Sparsnas(SENSOR_ID, PULSES_PER_KWH, TEMPDATA);

    if(sp->isValidPackage()) {
        mClient.publish(mqtt_status_topic, sp->getJsonString());
    } else {
        mClient.publish(mqtt_debug_topic, sp->getJsonString());
    }

We might need to add some fancy handling of LEDs and such (in my example above), the class should be native c++ but this is a base :).

fredrike commented 4 years ago

We could use the code from https://github.com/merbanan/rtl_433/blame/master/src/devices/ikea_sparsnas.c (it is quite clean). Perhaps @merbanan can help with that (would be really nice to "borrow" his sensor bruteforce part.

merbanan commented 4 years ago

@slundell is the original author. But you are free to use the code under the gplv2 license, if you need another license you have to ask the original author.

bphermansson commented 4 years ago

Looks like a good idea. Why don't make a test branch that uses @merbanans code?

fredrike commented 4 years ago

Looks like a good idea. Why don't make a test branch that uses @merbanans code?

I'll take a look at this after vacation time (perhaps even in November 😄). I need to solder a dev unit as I've actually moved to production now.