emelianov / modbus-esp8266

Most complete Modbus library for Arduino. A library that allows your Arduino board to communicate via Modbus protocol, acting as a master, slave or both. Supports network transport (Modbus TCP) and Serial line/RS-485 (Modbus RTU). Supports Modbus TCP Security for ESP8266/ESP32.
Other
534 stars 188 forks source link

Callback function within a class. #265

Closed kogdrix closed 1 year ago

kogdrix commented 1 year ago

I 've tried to create a class, and use a function within as callback for a basic read/write cb. Is it possible to give the class obj as param for the read/write operations? Or any other solution?

mCU is ESP32.

The scenario is: I have 15 nodes, and i want to managing them, i thought its an easier way to do that if i handle them as objects.

Something like this is I try to achieve: bool discoverCallback(Modbus::ResultCode event, uint16t transactionId, void data, Node node);
// then in the function, node_->setDiscovered();

class Manager {
// managing nodes etc.
}

class Node {
 public:
   void Discover();
   void setDiscovered();
   Node();
 private:   
   ModbusRTU *mbRtu;
   uint8_t nodeId;
   uint16_t nodeIdVerify[1];
   //bool discoverCallback(Modbus::ResultCode event, uint16_t transactionId, void* data);  // this doesn't work :/
   bool isAvailable;
   bool isOccupied;
   bool isDiscovered;
}

bool Node::Discover()
{        
    if (!this->isDiscovered){
      Serial.printf_P("discovering: %d\n", this->nodeId);     
      this->mbRtu->readHreg(nodeId, 1, nodeIdVerify, 1, discoverCallback);      
      this->isDiscovered = true;
    } 
    return true;
}

Sorry for my question, im not used to c++ :/

emelianov commented 1 year ago

Something like this should work:

class Node {
 public:
   bool Discover();
   //void setDiscovered();
   //Node();
 private:   
   ModbusRTU *mbRtu;
   uint8_t nodeId;
   uint16_t nodeIdVerify[1];
   bool discoverCallback(Modbus::ResultCode event, uint16_t transactionId, void* data);  // this doesn't work :/
   bool isAvailable;
   bool isOccupied;
   bool isDiscovered;
};

bool discoverCallback(Modbus::ResultCode event, uint16_t transactionId, void* data) {
  return true;
}

bool Node::Discover()
{        
  using namespace std::placeholders; // for _1,..
    if (!this->isDiscovered){
      Serial.printf_P("discovering: %d\n", this->nodeId);     
      this->mbRtu->readHreg(nodeId, 1, nodeIdVerify, 1, std::bind(&Node::discoverCallback, this, _1, _2, _3));      
      this->isDiscovered = true;
    } 
    return true;
}
kogdrix commented 1 year ago

Thank You, I 'll try.