2017-06-04 49 views
0

我使用Arduino IDE和東西網絡arduino庫來創建一個LoRa mote。C++回調類函數

我創建了一個應該處理所有LoRa相關函數的類。在這個類中,如果我收到下行消息,我需要處理回調。 ttn庫有我想在我的init函數中設置的onMessage函數,並解析另一個函數,它們是一個叫做message的類成員。 我收到錯誤「非法使用非靜態成員函數」。

// 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 
} 

和頭文件

// 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 

我曾嘗試:

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

但是正如我此前的預期沒有一次成功。

+3

非靜態成員函數需要調用* object *。如果您沒有對象,則不能使用非靜態成員函數。一旦你有一個對象,我建議你看看['std :: function'](http://en.cppreference.com/w/cpp/utility/functional/function)和['std :: bind']( http://en.cppreference.com/w/cpp/utility/functional/bind)。 –

回答

0

I通過使消息功能成爲課程之外的正常功能來解決問題。不知道這是否是一種好的做法 - 但它有效。

// 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); 
} 
0

你應該將參數傳遞給按摩的原型表示:

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

由於按摩返回void,應該probabaly不能作爲參數傳遞給其他的功能。

2

您試圖在不使用類成員的情況下調用成員函數(即,屬於類類型成員的函數)。這意味着,你通常會做什麼是實例化類LORA的成員,然後再調用它:

LoRa loraMember;  
loraMember.message(); 

既然你想調用該函數從類本身裏面,沒有一個成員類調用init(),你必須做出的功能的靜態,如:

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

然後你就可以在任何地方,只要它是公共使用LORA ::消息(),但調用它,就像這將使你的另一個編譯器錯誤,因爲消息的接口要求「const uint8_t * payload,size_t size,port_t port」。所以,你必須做的就是呼叫消息,如:

LoRa::message(payloadPointer, sizeVar, portVar);` 

當你調用ttn.onMessage(functionCall)發生的事情是,該函數調用獲取評估,然後由該函數返回什麼被放放入圓括號中,然後用那個函數調用ttn.onMessage。由於你的LoRa :: message函數什麼都沒有返回(void),你會在這裏得到另一個錯誤。

我建議在C++基礎知識一本好書,讓你開始 - book list

祝你好運!