Radio communication with NRF24

Dependents:   F030

ssRadio.h

Committer:
gume
Date:
2017-10-06
Revision:
0:9f5a444886a8

File content as of revision 0:9f5a444886a8:

#ifndef __SSRADIO_H__
#define __SSRADIO_H__

//#define SERIAL_DEBUG 1

#include "RF24.h"
#include "NodeConfig.h"

#define QUEUELEN 3

typedef union _Packet {
  struct __attribute__((packed)) {
    uint16_t address;     // Source address
    uint8_t type;         // Type. MSB signals extended type (+1 byte). Not implemented yet.
    uint8_t counter;      // Packet counter
    uint8_t payload[28]; 
  } fields;
  uint8_t raw[32];
} Packet;

class SSRadio {

protected:
    NodeConfig *config;
    RF24 rf24;
    
    void (*onReceiveData)(uint8_t *data, uint16_t type, uint8_t len);
    void (*onConnect)();
    void (*onDisconnect)();

    uint16_t txCounter;
    uint16_t rxCounter;
    
    uint8_t packetRx[32];
    long lastSync;  // millis when the last Sync was received
    int8_t sendSlot;    // Transmission slot, when synced
    int8_t freeSlot;    // Free (for everyone) slot, when synced
    uint8_t slot_ms;    // Slot size in ms
    
    void receiveSyncFrame(uint8_t *frame, uint8_t size);
    void receiveDataFrame(uint8_t *frame, uint8_t size);
    
    uint16_t myAddress;
    uint64_t gatewayAddress;
    
    uint8_t txQueue[QUEUELEN * 30]; // 1 length + 1 type + 28 payload
    uint8_t rxQueue[QUEUELEN * 30];
    uint8_t txQueueLength;
    uint8_t rxQueueLength;
    
public:
    SSRadio(SPI *spi, NodeConfig *nc);
    
    void init();
    void loop();
    
    void useIRQ(uint16_t irqPin);
    
    bool isRunning();   // RF24 is connected or not
    bool isConnected(); // There is a GW nearby
    bool isScheduled(); // Sending is scheduled by the GW
    bool isAvailableData(); // Available data
    
    bool sendData(uint8_t *data, uint16_t type, uint8_t len); // Send data to GW
    bool instantData(uint8_t *data, uint16_t type, uint8_t len); // Send data to GW immediately
    bool receiveData(uint8_t *data, uint16_t &type, uint8_t &len); // Receive data from GW
    void setSlotSize(uint8_t slot_ms);
    
    // Callbacks
    void setOnReceiveData(void (*onReceiveData)(uint8_t *data, uint16_t type, uint8_t len));
    void setOnConnect(void (*onConnect)());
    void setOnDisconnect(void (*onDisconnect)());
};

#endif // __SSRADIO_H__