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

问题描述 投票:0回答:1

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

apiClient = ApiClient(myUrl);
apiClient.sendValue(key, value);

除了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函数通常需要两个参数,但为什么这在示例代码中起作用?我该如何解决?

这是我到目前为止:

main.cpp中



#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);
}

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

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

先感谢您

c++ arduino esp32
1个回答
0
投票

我看了一下qazxsw poi linkedin OP的问题。

相关部分是

example

因此void setup(){ // contents skipped WiFi.onEvent(WiFiEvent); // contents skipped } 是一个自由函数,定义如上:

WiFiEvent

OP希望将此事件处理程序重构为他的void WiFiEvent(WiFiEvent_t event, system_event_info_t info){ switch(event){ // some cases to handle various events default: break; } }

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: }; 因此而成为成员函数,并且OP得到了报告的错误

WiFiEvent()

出于好奇,我在github项目中挖掘了一点,最后找到了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 的声明 - 它继承自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 }; 声明,因此每个参数的第二个参数都有一个默认参数。 (因此,在示例中只有一个参数的调用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); s的含义:

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

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

支持onEvent()非常好,因为它接受任何可调用匹配签名的东西:

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

因此,要使std::function兼容,有两种选择:

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

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

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

ApiClient::ApiClient()

这有效地注册了一个带有接受签名的仿函数,该签名捕获//ERROR: wifi.onEvent(WiFiEvent); //Instead: wifi.onEvent( [this](WiFiEvent_t event, system_event_info_t info) { this->WiFiEvent(event, info); }); this,以便可以完成对实例的成员函数的有效调用。 lambda的返回类型被隐式声明为ApiClient,因为lambda体中没有void

最后,我想提一下,在lambdas中捕获是必须要仔细完成的事情。如果returnwifi(即this的实例)更长,那么它可以在没有有效的ApiClient指针的情况下调用ApiClient::WiFiEvent()

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

© www.soinside.com 2019 - 2024. All rights reserved.