将示例代码重构为类不会引发重载函数的实例

Jan*_*Jan 3 c++ arduino esp32

我是 CPP 的新手,并尝试将此示例代码https://github.com/espressif/arduino-esp32/blob/master/libraries/WiFi/examples/WPS/WPS.ino “重构”为名为ApiClient`的类。然后我希望能够做这样的事情:

apiClient = ApiClient(myUrl);
apiClient.sendValue(key, value);
Run Code Online (Sandbox Code Playgroud)

除了函数调用之外,所有内容都会编译wifi.onEvent(WiFiEvent);。当我将整个示例代码复制粘贴到我的main.cpp文件中时,该示例正在运行。当我使用“重构”方法时,他们wifi.onEvent(WifiEvent)会抱怨。

确切的错误信息:

no instance of overloaded function "WiFiClass::onEvent" matches the argument list -- argument types are: (void (system_event_id_t event, system_event_info_t info)) -- object type is: WiFiClass

我知道该onEvent函数通常需要两个参数,但为什么这在示例代码中有效?我该如何解决这个问题?

这是我到目前为止所拥有的:

主程序



#include "WiFi.h"
#include <esp_wps.h>
#include <Hythe22.h>
#include <ApiClient.h>

#define DHTPIN 14
// ?accessKey=ist_NJu3tjPIBCYeJd6DGGBxzq14LvungHoK&bucketKey=B37GHBNK5HL3
#define API_URL "https://groker.init.st/api/events";

Hythe22 dht(DHTPIN);
ApiClient apiClient;
uint64_t chipid;
#define ESP_DEVICE_NAME String(chipid)


void setup()
{
  String apiUrl = "https://myApi.Endpoint.com/event";
  Serial.begin(115200);
  delay(100);
  Serial.println();
}

void loop()
{

  String temp = String(dht.temperature);
  Serial.println("TEMP:" + temp);
  apiClient.sendValue("temperature", temp);

  String hum = String(dht.humidity);
  Serial.println("HUM:" + hum);
  apiClient.sendValue("humidity", hum);
}

Run Code Online (Sandbox Code Playgroud)

APIClient.h

/*
===========================================================
*/

#ifndef WebClient_h
#define WebClient_h

#include <Arduino.h>
#include <WiFi.h>
#include "esp_wps.h"
#include <HTTPClient.h>

class ApiClient
{
  public:
    ApiClient(String apiUrl);
    void sendValue(String key, String value);
    void wpsInitConfig();
    void WiFiEvent(WiFiEvent_t event, system_event_info_t info);
    String wpspin2string(uint8_t a[]);
    String requestUrl;
    String _apiUrl;
    int chipid;

  private:
};

#endif
Run Code Online (Sandbox Code Playgroud)

ApiClient.cpp


/*
===========================================================
*/

#include <Arduino.h>
#include <ApiClient.h>
#include <WiFi.h>
#include <esp_wps.h>
#include <HTTPClient.h>

int chipid;

#define ESP_WPS_MODE WPS_TYPE_PBC
#define ESP_MANUFACTURER "ESPRESSIF"
#define ESP_MODEL_NUMBER "ESP32"
#define ESP_MODEL_NAME "ESPRESSIF IOT"
#define ESP_DEVICE_NAME "ESP STATION"

String _apiUrl;
HTTPClient http;
String requestUrl;
WiFiClass wifi;

static esp_wps_config_t config;

ApiClient::ApiClient(String apiUrl)
{
    Serial.begin(115200);
    delay(10);

    Serial.println();

    wifi.onEvent(WiFiEvent);
    wifi.mode(WIFI_MODE_STA);

    Serial.println("Starting WPS");

    wpsInitConfig();
    esp_wifi_wps_enable(&config);
    esp_wifi_wps_start(0);
}

void sendValue(String key, String value)
{
    HTTPClient http;
    Serial.println("key:" + key);
    Serial.println("value:" + value);
    requestUrl = _apiUrl + "?" + key + "=" + value;
    // Serial.println(apiUrl);
    http.begin(requestUrl);

    int httpCode = http.GET();

    if (httpCode > 0)
    {
        Serial.printf("[HTTP] GET... code: %d\n", httpCode);
        //file found at server --> on unsucessful connection code will be -1
        if (httpCode == HTTP_CODE_OK)
        {
            String payload = http.getString();
            Serial.println(payload);
        }
    }
    else
    {
        Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
    }
    http.end();
}

void ApiClient::wpsInitConfig()
{
    config.crypto_funcs = &g_wifi_default_wps_crypto_funcs;
    config.wps_type = ESP_WPS_MODE;
    strcpy(config.factory_info.manufacturer, ESP_MANUFACTURER);
    strcpy(config.factory_info.model_number, ESP_MODEL_NUMBER);
    strcpy(config.factory_info.model_name, ESP_MODEL_NAME);
    strcpy(config.factory_info.device_name, ESP_DEVICE_NAME);
}

String wpspin2string(uint8_t a[])
{
    char wps_pin[9];
    for (int i = 0; i < 8; i++)
    {
        wps_pin[i] = a[i];
    }
    wps_pin[8] = '\0';
    return (String)wps_pin;
}

void WiFiEvent(WiFiEvent_t event, system_event_info_t info){
  switch(event){
    case SYSTEM_EVENT_STA_START:
      Serial.println("Station Mode Started");
      break;
    case SYSTEM_EVENT_STA_GOT_IP:
      Serial.println("Connected to :" + String(WiFi.SSID()));
      Serial.print("Got IP: ");
      Serial.println(WiFi.localIP());
      break;
    case SYSTEM_EVENT_STA_DISCONNECTED:
      Serial.println("Disconnected from station, attempting reconnection");
      WiFi.reconnect();
      break;
    case SYSTEM_EVENT_STA_WPS_ER_SUCCESS:
      Serial.println("WPS Successfull, stopping WPS and connecting to: " + String(WiFi.SSID()));
      esp_wifi_wps_disable();
      delay(10);
      WiFi.begin();
      break;
    case SYSTEM_EVENT_STA_WPS_ER_FAILED:
      Serial.println("WPS Failed, retrying");
      esp_wifi_wps_disable();
      esp_wifi_wps_enable(&config);
      esp_wifi_wps_start(0);
      break;
    case SYSTEM_EVENT_STA_WPS_ER_TIMEOUT:
      Serial.println("WPS Timedout, retrying");
      esp_wifi_wps_disable();
      esp_wifi_wps_enable(&config);
      esp_wifi_wps_start(0);
      break;
    case SYSTEM_EVENT_STA_WPS_ER_PIN:
      Serial.println("WPS_PIN = " + wpspin2string(info.sta_er_pin.pin_code));
      break;
    default:
      break;
  }
}

Run Code Online (Sandbox Code Playgroud)

先感谢您

Sch*_*eff 6

我查看了OP问题中链接的示例。

相关部分是

void setup(){
  // contents skipped
  WiFi.onEvent(WiFiEvent);
  // contents skipped
}
Run Code Online (Sandbox Code Playgroud)

因此WiFiEvent上面定义了一个自由函数:

void WiFiEvent(WiFiEvent_t event, system_event_info_t info){
  switch(event){
    // some cases to handle various events
    default:
      break;
  }
}
Run Code Online (Sandbox Code Playgroud)

OP 希望将此事件处理程序重构为他的class ApiClient

class ApiClient
{
  public:
    ApiClient(String apiUrl);
    void sendValue(String key, String value);
    void wpsInitConfig();
    void WiFiEvent(WiFiEvent_t event, system_event_info_t info);
    String wpspin2string(uint8_t a[]);
    String requestUrl;
    String _apiUrl;
    int chipid;

  private:
};
Run Code Online (Sandbox Code Playgroud)

本质区别在于,因此WiFiEvent()成为成员函数,OP得到了报错

void setup(){
  // contents skipped
  WiFi.onEvent(WiFiEvent);
  // contents skipped
}
Run Code Online (Sandbox Code Playgroud)

出于好奇,我在 github 项目中进行了一些挖掘,终于找到了声明WiFiClass::onEvent()– 它继承自class WiFiGenericClass

class WiFiGenericClass
{
  public:
    WiFiGenericClass();

    wifi_event_id_t onEvent(WiFiEventCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX);
    wifi_event_id_t onEvent(WiFiEventFuncCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX);
    wifi_event_id_t onEvent(WiFiEventSysCb cbEvent, system_event_id_t event = SYSTEM_EVENT_MAX);
    // a lot more - skipped
};
Run Code Online (Sandbox Code Playgroud)

因此,实际上存在三个onEvent()带有两个参数的声明,因此每个的第二参数都有一个默认参数。WiFi.onEvent(WiFiEvent);(因此,示例中只有一个参数的调用是可以的。)

为了完全解决这个问题,我查找了WiFiEventCbWiFiEventFuncCb、 ,并WiFiEventSysCb在上面的同一头文件中找到了它们class WiFiGenericClass

typedef void (*WiFiEventCb)(system_event_id_t event);
typedef std::function<void(system_event_id_t event, system_event_info_t info)> WiFiEventFuncCb;
typedef void (*WiFiEventSysCb)(system_event_t *event);
Run Code Online (Sandbox Code Playgroud)

这就是三个typedefs 的意思:

  1. WiFiEventCb... 指向一个(自由)函数的函数指针,该函数返回void并具有一个类型的参数system_event_id_t
  2. WiFiEventFuncCb...std::function任何返回的对象void并具有两个类型system_event_id_t和的参数system_event_info_t
  3. WiFiEventSysCb... 指向一个(自由)函数的函数指针,该函数返回void并具有一个类型为 的参数system_event_id_t*

显然,该示例使用了第二个,因为 onEvent()它是唯一一个接受具有两个参数的函数。

对 的支持std::function非常好,因为它接受任何具有匹配签名的可调用内容:

  • 免费功能,
  • 函子,
  • lambda(实际上只不过是前者之一)。

因此,为了兼容ApiClient::WiFiEvent(),有两种选择:

  1. 声明ApiClient::WiFiEvent()为静态成员函数
  2. ApiClient::WiFiEvent()与调用它的实例绑定。

ApiClient::WiFiEvent()第一个选项限制了成员函数的可用性,static因为在没有 resp 实例的情况下调用成员函数。班级。缺点——成员函数中没有可用的实例(即禁止显式或隐式访问this),这可能是可接受的,也可能是不可接受的。

通过使用lambda作为适配器可以轻松实现第二个选项。为此,ApiClient::ApiClient()必须更改事件处理程序注册:

//ERROR: wifi.onEvent(WiFiEvent);
//Instead:
wifi.onEvent(
  [this](WiFiEvent_t event, system_event_info_t info) {
    this->WiFiEvent(event, info);
  });
Run Code Online (Sandbox Code Playgroud)

这有效地注册了一个具有接受的签名的仿函数,该签名捕获thisApiClient,以便可以对实例的成员函数进行有效的调用。lambda 的返回类型是隐式声明的,因为lambda 主体中void没有返回类型。return

最后,我想提一下,在 lambda 中进行捕获是必须小心完成的事情。如果wifi过期this(即 的实例ApiClient),那么它可能会ApiClient::WiFiEvent()在没有有效this指针的情况下调用。

为了使其“防弹”, 的析构函数ApiClient可以removeEvent()使用wifi_event_id_t所返回的进行调用onEvent()ApiClient(为此目的应将其存储在其中。)