#inheritance #arduino #httpclient #libraries #arduino-uno-wifi
#наследование #arduino #httpclient #библиотеки #arduino-uno-wifi
Вопрос:
Я использовал некоторый пример кода для создания рабочего эскиза HttpClient, отправляющего JSON из Uno rv2 в C # api. Все хорошо.
Далее я планировал добавить это в эскиз, чтобы отправить тот же JSON с помощью Sparkfun weather shield. Я подумал, что для очистки кода shield я бы создал пользовательскую библиотеку, наследующую HttpClient, и просто передал учетные данные WiFiClient, ServerName, port и wifi в конструкторе.
Я не делал много C, C в течение 20 с лишним лет. Возможно ли то, что я пытаюсь сделать? Или я просто очень заржавел и еще не понял этого. (Вероятно, следовало выбрать что-то более простое для моей первой попытки в пользовательской библиотеке)
Если это возможно, я предполагаю, что я испортил конструкторы и перепробовал множество вариантов темы безрезультатно.
Цените любую информацию.
ОБНОВЛЕНИЕ: итак, я внес некоторые изменения, но я все еще получаю ошибки компиляции, мне сказали добавить виртуальные методы унаследованного класса (HttpClient), что я и сделал, но у меня все еще возникают проблемы с компиляцией. Ошибки прилагаются.
Вот мой заголовок.
#ifndef SPARKFUN_WIFI
#define SPARKFUN_WIFI
#include <ArduinoJson.h>
#include <b64.h>
#include <HttpClient.h>
#include <URLEncoder.h>
#include <WebSocketClient.h>
#include <WiFiNINA.h>
#include "arduino.h"
#include <ArduinoHttpClient.h>
class SparkfunWifi : public HttpClient {
public:
// Contructor
/** Connect to the server and start to send a GET request.
@param serverName The server name to conect to.
@param port The port number.
@param ssid The network ssid.
@param pass The network password.
*/
SparkfunWifi(Clientamp; client, char* serverName, char* port, char* ssid, char* pass);
// Methods
/** Connect to the server and start to send a GET request.
@return true if connection successful
*/
bool connectWifi();
/** Sends HTTP weather POST to weather.api.
@return 200 if successful response from api.
*/
int sendWeather();
virtual bool endOfStream() { return endOfBodyReached(); };
virtual bool completed() { return endOfBodyReached(); };
// Inherited from HttpClient which inherited them from Print
// Note: 1st call to these indicates the user is sending the body, so if need
// Note: be we should finish the header first
virtual size_t write(uint8_t aByte) { if (iState < eRequestSent) { finishHeaders(); }; return iClient-> write(aByte); };
virtual size_t write(const uint8_t *aBuffer, size_t aSize) { if (iState < eRequestSent) { finishHeaders(); }; return iClient->write(aBuffer, aSize); };
// Inherited from Stream
virtual int available();
/** Read the next byte from the server.
@return Byte read or -1 if there are no bytes available.
*/
virtual int read();
virtual int read(uint8_t *buf, size_t size);
virtual int peek() { return iClient->peek(); };
virtual void flush() { iClient->flush(); };
// Inherited from Client
virtual int connect(IPAddress ip, uint16_t port) { return iClient->connect(ip, port); };
virtual int connect(const char *host, uint16_t port) { return iClient->connect(host, port); };
virtual void stop();
virtual uint8_t connected() { return iClient->connected(); };
virtual operator bool() { return bool(iClient); };
virtual uint32_t httpResponseTimeout() { return iHttpResponseTimeout; };
virtual void setHttpResponseTimeout(uint32_t timeout) { iHttpResponseTimeout = timeout; };
private:
int _serverName;
int _status;
char* _ssid;
char* _pass;
};
#endif
И .cpp
// inlcludes
#include "arduino.h"
#include "SparkfunWifi.h"
// constructor
SparkfunWifi::SparkfunWifi(Clientamp; client, char* serverName, int port, char* ssid, char* pass)
: client(client), serverName(serverName), serverAddress(), serverPort(port),
iConnectionClose(true), iSendDefaultRequestHeaders(true)
{
_ssid = ssid;
_pass = pass;
_status != WL_CONNECTED;
}
bool SparkfunWifi::connectWifi(){
Serial.begin(9600);
int times = 1;
while (_status != WL_CONNECTED) {
times ;
if (times <= 5){
// attempt to connect 5 times
Serial.println("Attempting to connect to Network named: ");
Serial.println(_ssid); // print the network name (SSID);
Serial.println("Attempt:"); // print the network name (SSID);
Serial.println(times); // print the network name (SSID);
// Connect to WPA/WPA2 network:
_status = WiFi.begin(_ssid, _pass);
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
return true;
}
else
{
Serial.print("Could not connect on 5th attempt to: ");
Serial.println(_ssid); // print the network name (SSID);
return false;
}
}
}
int SparkfunWifi::sendWeather() {
Serial.println("making POST request to " _serverName);
client.beginRequest();
StaticJsonDocument<500> doc; // create a JSON document
doc["temp"] = "33.2"; // add the temperature elememnt and value
doc["humidity"] = "95.2"; // add the humidity elememnt and value
client.post("/addWeather"); // call the weather api post operation
client.sendHeader("Content-Type", "application/json"); // send content type and legnth headers
client.sendHeader("Content-Length", measureJsonPretty(doc));
client.beginBody(); // send the JSON
serializeJsonPretty(doc, Serial);
serializeJsonPretty(doc, client);
client.endRequest(); // end http request
// read the status code and body of the response
int statusCode = client.responseStatusCode();
String response = client.responseBody();
return statusCode;
}
Наконец, мой sketch .ino
// inlcludes
#include "arduino_secrets.h"
#include "SparkfunWifi.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
/////// Wifi Settings ///////
char* ssid = SECRET_SSID;
char* pass = SECRET_PASS;
char serverName[] = "dionysus"; // server address
int port = 5000; // port number
WiFiClient wifi;
SparkfunWifi client(wifi, serverName, port, ssid, pass);
void setup() {
client.connectWifi();
}
void loop() {
Serial.println("Send weather...");
client.sendWeather();
Serial.println("Wait five seconds");
delay(5000);
}
Вот вывод ошибки
SparkfunWifi.cpp:6:1: error: prototype for 'SparkfunWifi::SparkfunWifi(arduino::Clientamp;, char*, int, char*, char*)' does not match any in class 'SparkfunWifi'
SparkfunWifi::SparkfunWifi(Clientamp; client, char* serverName, int port, char* ssid, char* pass)
^~~~~~~~~~~~
In file included from sketchSparkfunWifi.cpp:3:0:
SparkfunWifi.h:13:7: error: candidates are: SparkfunWifi::SparkfunWifi(SparkfunWifiamp;amp;)
class SparkfunWifi : public HttpClient {
^~~~~~~~~~~~
SparkfunWifi.h:13:7: error: SparkfunWifi::SparkfunWifi(const SparkfunWifiamp;)
SparkfunWifi.h:24:5: error: SparkfunWifi::SparkfunWifi(arduino::Clientamp;, char*, char*, char*, char*)
SparkfunWifi(Clientamp; client, char* serverName, char* port, char* ssid, char* pass);
^~~~~~~~~~~~
sketchSparkfunWifi.cpp: In member function 'int SparkfunWifi::sendWeather()':
SparkfunWifi.cpp:48:5: error: 'client' was not declared in this scope
client.beginRequest();
^~~~~~
sketchSparkfunWifi.cpp:48:5: note: suggested alternative: 'Client'
client.beginRequest();
^~~~~~
Client
exit status 1
[Error] Exit with code=1
Комментарии:
1. очень ржавый. в .h у вас есть const char* для порта в параметрах конструктора. и C чувствителен к регистру, поэтому iclient не является IClient. в cpp в конструкторе
iServerName(aServerName)
, что такое иМя_серВера?2. у вас все еще есть in .h
const char*
для порта в параметрах конструктора?
Ответ №1:
Мне удалось заставить это работать со следующим…
.h
#ifndef SPARKFUN_WIFI
#define SPARKFUN_WIFI
#include "arduino.h"
#include "ArduinoJson.h"
#include "HttpClient.h"
#include "ArduinoHttpClient.h"
#include "WiFiNINA.h"
#include "WeatherData.h"
class SparkfunWifi : public HttpClient {
public:
// Contructor
/** Create a new Sparkwifi class inheriting HttpClient.
@param wifi The wifi client.
@param port The port number.
@param ssid The network ssid.
@param pass The network password.
*/
SparkfunWifi(Clientamp; wifi, Stringamp; serverName, uint16_t port, char* ssid, char* pass);
// Methods
/** Connect to the server and start to send a GET request.
@return true if connection successful
*/
bool connectWifi();
/** Sends HTTP weather POST to weather.api.
@return 200 if successful response from api.
*/
int sendWeather(WeatherData weatherData);
private:
int _status;
char* _ssid;
char* _pass;
String _serverName;
};
#endif
`
.cpp
` // inlcludes #включить «arduino.h» #включить «SparkfunWifi.h» #включить «WeatherData.h»
// constructor
SparkfunWifi::SparkfunWifi(Clientamp; wifi, Stringamp; serverName, uint16_t port, char*
ssid, char* pass)
: (wifi, serverName, port)
{
_ssid = ssid;
_pass = pass;
_status != WL_CONNECTED;
_serverName = serverName;
}
bool SparkfunWifi::connectWifi(){
Serial.begin(9600);
int times = 1;
while (_status != WL_CONNECTED) {
times ;
if (times <= 5){
// attempt to connect 5 times
Serial.println("Attempting to connect to Network named: ");
Serial.println(_ssid); // print the network name (SSID);
Serial.println("Attempt:"); // print the network name (SSID);
Serial.println(times); // print the network name (SSID);
// Connect to WPA/WPA2 network:
_status = WiFi.begin(_ssid, _pass);
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
return true;
}
else
{
Serial.print("Could not connect on 5th attempt to: ");
Serial.println(_ssid); // print the network name (SSID);
return false;
}
}
}
int SparkfunWifi::sendWeather(WeatherData weatherData) {
beginRequest();
DynamicJsonDocument doc(500);
doc["temp"] = weatherData.getTemp();
doc["humidity"] = weatherData.getHumidity();
doc["windDir"] = weatherData.getWindDir();
doc["windSpeed"] = weatherData.getWindSpeed();
doc["windGust"] = weatherData.getWindGust();
doc["windGustDir"] = weatherData.getWindGustDir();
doc["windSpeedAvg2m"] = weatherData.getWindSpeedAvg2m();
doc["windDirAvg2m"] = weatherData.getWindDirAvg2m();
doc["windGustAvg10m"] = weatherData.getWindGustAvg10m();
doc["windGustDirAvg10m"] = weatherData.getWindGustDirAvg10m();
doc["dailyRain"] = weatherData.getDailyRain();
doc["pressure"] = weatherData.getPressure();
doc["batteryLevel"] = weatherData.getBatteryLevel();
doc["lightLevel"] = weatherData.getLightLevel();
post("/addWeather");
sendHeader("Content-Type", "application/json");
sendHeader("Content-Length", measureJsonPretty(doc));
beginBody(); // send the JSON
serializeJsonPretty(doc, Serial);
serializeJsonPretty(doc, (*iClient));
endRequest(); // end http request
// read the status code
int statusCode = responseStatusCode();
Serial.println(statusCode);
return statusCode;
}
`