Search code examples
c++classarduinolora

C++ callback to class function


I'm using the Arduino IDE and the things network arduino library to create a LoRa mote.

I have created a class which should handle all the LoRa related functions. In this class I need to handle a callback if i receive a downlink message. The ttn library has the onMessage function which I want to setup in my init function and parse another function, which are a class member, called message. I'm getting the error "invalid use of non-static member function".

// File: LoRa.cpp
#include "Arduino.h"
#include "LoRa.h"
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);

LoRa::LoRa(){ 
}

void LoRa::init(){
  // Set the callback
  ttn.onMessage(this->message);
}

// Other functions

void LoRa::message(const uint8_t *payload, size_t size, port_t port)
{
  // Stuff to do when reciving a downlink
}

and the header file

// File: LoRa.h
#ifndef LoRa_h
#define LoRa_h

#include "Arduino.h"
#include <TheThingsNetwork.h>

// Define serial interface for communication with LoRa module
#define loraSerial Serial1
#define debugSerial Serial


// define the frequency plan - EU or US. (TTN_FP_EU868 or TTN_FP_US915)
#define freqPlan TTN_FP_EU868



class LoRa{
  // const vars



  public:
    LoRa();

    void init();

    // other functions

    void message(const uint8_t *payload, size_t size, port_t port);

  private:
    // Private functions
};


#endif

I have tried:

ttn.onMessage(this->message);
ttn.onMessage(LoRa::message);
ttn.onMessage(message);

However none of them worked as I had expected.


Solution

  • I Solved the problem by making the message function a normal function outside the class. Not sure if it is good practice - but it works.

    // File: LoRa.cpp
    #include "Arduino.h"
    #include "LoRa.h"
    #include <TheThingsNetwork.h>
    
    TheThingsNetwork ttn(loraSerial,debugSerial,freqPlan);
    
    void message(const uint8_t *payload, size_t size, port_t port)
    {
      // Stuff to do when reciving a downlink
    }
    
    LoRa::LoRa(){ 
    }
    
    void LoRa::init(){
      // Set the callback
      ttn.onMessage(message);
    }