Hi all,
Very new to Blynk but so far getting great results. I have an existing Arduino project on ESP8266 that is already running a webserver with websocket interface for remote control. It has a good captive portal and has been very reliable to date.
Taking code from the Arduino Example:
Blynk → Boards_With_HTTP_Api → ESP8266_ESP32
I was able to merge the httpRequest function into my code and it runs successfully. Not much to note in the Serial output other than the connection to the Blynk Server was successful.
The value I am sending “Hello” updates to the Blynk. I can also replace my “Hello” string with a int counter which updates every second to blynk. The one annoyance is that even during successful communication Blynk shows my device is “Offline”.
Is there a way to alert the Blynk Server that I am actually online? For instance a seperate sync command, or sending data faster?
My simplified code is below:
#include <ESP8266WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ESPAsyncWiFiManager.h>
#include <ESPAsyncTCP.h>
#include "index.h"
/* Fill in information from Blynk Device Info here */
#define BLYNK_TEMPLATE_ID "*********"
#define BLYNK_TEMPLATE_NAME "*********"
#define BLYNK_AUTH_TOKEN "*********"
// Blynk cloud server
const char* host = "blynk.cloud";
unsigned int port = 80;
WiFiClient client;
AsyncWebServer server(80);
DNSServer dns;
AsyncWebSocket ws("/ws");
void notifyClients(String textMsg) {
ws.textAll(textMsg);
}
void handleWebSocketMessage(void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT) {
data[len] = 0;
if (strcmp((char*)data, "toggle") == 0) {
ledState = !ledState;
}
}
}
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(arg, data, len);
break;
case WS_EVT_PONG:
case WS_EVT_ERROR:
break;
}
}
void initWebSocket() {
ws.onEvent(onEvent);
server.addHandler(&ws);
}
void setup(){
Serial.begin(9600);
AsyncWiFiManager wifiManager(&server,&dns);
wifiManager.autoConnect("********");
Serial.println("Connected!");
Serial.println(WiFi.localIP());
initWebSocket();
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html);
});
// Start server
server.begin();
}
void loop() {
String message = "Hello";
ws.cleanupClients();
delay(1000);
httpRequest("GET", String("/external/api/update?token=") + BLYNK_AUTH_TOKEN + "&pin=V0&value=" + message, "", response);
}
//////////////////////////////////////////////////BLYNK FUNCTION FROM HTTP API EXAMPLE
bool httpRequest(const String& method,
const String& url,
const String& request,
String& response)
{
Serial.print(F("Connecting to "));
Serial.print(host);
Serial.print(":");
Serial.print(port);
Serial.print("... ");
if (client.connect(host, port)) {
Serial.println("OK");
} else {
Serial.println("failed");
return false;
}
Serial.print(method); Serial.print(" "); Serial.println(url);
client.print(method); client.print(" ");
client.print(url); client.println(F(" HTTP/1.1"));
client.print(F("Host: ")); client.println(host);
client.println(F("Connection: close"));
if (request.length()) {
client.println(F("Content-Type: application/json"));
client.print(F("Content-Length: ")); client.println(request.length());
client.println();
client.print(request);
} else {
client.println();
}
//Serial.println("Waiting response");
int timeout = millis() + 5000;
while (client.available() == 0) {
if (timeout - millis() < 0) {
Serial.println(">>> Client Timeout !");
client.stop();
return false;
}
}
//Serial.println("Reading response");
int contentLength = -1;
while (client.available()) {
String line = client.readStringUntil('\n');
line.trim();
line.toLowerCase();
if (line.startsWith("content-length:")) {
contentLength = line.substring(line.lastIndexOf(':') + 1).toInt();
} else if (line.length() == 0) {
break;
}
}
//Serial.println("Reading response body");
response = "";
response.reserve(contentLength + 1);
while (response.length() < contentLength) {
if (client.available()) {
char c = client.read();
response += c;
} else if (!client.connected()) {
break;
}
}
client.stop();
return true;
}