WebSocketServer on ESP32 DevkitC V4 Issue - websocket

I'm developing a simple mobile robot controlled by a custom web application hosted on ESP32. The communication protocol that is used is WebSocket. I had a code that was working but after some break, I can't make it run properly again... most likely I changed something accidentally or I don't understand some code parts. The logs in SerialPort suggest that the program connects to the WiFi, it gets data (HTML files) from Flash memory and the server is started under some particular IP. However, when I try to access the server IP nothing is given in response. I pasted my .ino code down below, I can also add HTML and .js files if needed. The data folder is ofc uploaded to the flash memory. For now I just want to host that page on a server and access it, the code is not supposed to do anything else for now. I'm going crazy because of that issue. Does anyone see some mistake or misconception?
#include <Arduino.h>
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
#include <Arduino_JSON.h>
// Network credentials
const char *ssid = "mySSID";
const char *password = "myCredentials";
// Create AsyncWebServer object on port 80
AsyncWebServer server(80);
// Create a WebSocket object
AsyncWebSocket ws("/ws");
// Placeholder for messages from the clients
String message = "";
void initFS()
{
if (!SPIFFS.begin())
{
Serial.println("An error has occurred while mounting SPIFFS");
}
else
{
Serial.println("SPIFFS mounted successfully");
}
}
// Initialise WiFi
void initWiFi()
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
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;
message = (char *)data;
}
}
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()
{
Serial.println("I'm Inside!");
ws.onEvent(onEvent);
server.addHandler(&ws);
}
void setup()
{
Serial.begin(115200);
Serial.println("Initialising SPIFFS");
initFS();
Serial.println("Initialising WiFi");
initWiFi();
Serial.println("Initialising WebSocket");
initWebSocket();
// Web Server Root URL
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{ request->send(SPIFFS, "/index.html", "text/html"); });
server.serveStatic("/", SPIFFS, "/");
// Start server
server.begin();
Serial.println("Starting Server");
}
void loop()
{
ws.cleanupClients();
}
Update:
I created a different, very simple sketch just to have a look if it might work and it doesn't. It connects to the WiFi according to the logs but I'm getting timed out when I try to access the server IP address Down below is the code that I used for the second sketch:
#include <WiFi.h>
#include <WebServer.h>
//SSID and Password to the local WiFi
const char* ssid = "ssid";
const char* password = "password";
WebServer server(80);
String webpage = "<!DOCTYPE html><html lang='en'><head> <meta charset='UTF-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <title>Document</title></head><body> <h1> Test! </h1></body></html>";
//Function to initialise the connection with local WiFi
void InitWiFi()
{
WiFi.begin(ssid, password);
Serial.println("Trying to connect to the WiFi with SSID: " + String(ssid) + "..");
while(WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to the WiFi with the IP address: ");
Serial.println(WiFi.localIP());
}
void setup() {
Serial.begin(115200);
InitWiFi();
//Initialising WebServer
server.on("/", []() {
server.send(200, "text\html", webpage);
});
delay(1000);
server.begin();
Serial.println("Server started");
}
void loop() {
server.handleClient();
}

Related

Posting data from esp8266 to a webapi

I want to send data from my esp8266 to a webapi but it fails.
I tried this code to send my data like sensor status but it fails and returns error 400. I searched a lot about this problem and I tried so many things but it didn't work.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char *ssid = "VRU";
const char *password = "";
const char *host = "192.168.174.71";
WiFiClient wifiClient;
void setup() {
delay(1000);
Serial.begin(115200);
WiFi.mode(WIFI_OFF);
delay(1000);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
HTTPClient http;
http.begin(wifiClient,"http://192.168.174.71:100/api/StatusReport/AddStatus");
http.addHeader("Content-Type", "application/json");
int httpCode = http.POST("{\"status\":\"1\"}");
String payload = http.getString();
Serial.println(httpCode);
Serial.println(payload);
http.end();
delay(5000);
}
Here is my code. It connects to the wifi without any problem and when it wants to post the data it returns an error.
400
{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-862f434a8be85865c871ea45b89544d1-cea4232cafaa5cc1-00","errors":{"status":["The status field is required."]}}
And it's the error.
The api receives the data when I do it by myself but the esp can't send the data.
What should I do to prevent this error from happening. Is it from the api that can't receive data or from the esp?

ESP8266 not connecting to websocket server

I have created and deployed a websocket to the heroku. I am able to use the websocket on postman but I can't connect it with my node mcu. I could connect the node mcu to the wifi but not with the websocket.
I am not sure about the port number which should be used for begin() method for websocketsclient object.
Below is my code to connect with my websocket:
#include "ESP8266WiFi.h"
#include "WebSocketsClient.h"
// WiFi parameters to be configured
const char* ssid = "<wifi_ssid>"; // Write here your router's username
const char* password = "<password>"; // Write here your router's passward
int LED_STATUS = 0;
const char* host = "<project_name>.herokuapp.com";
const uint16_t port = 3000;
const char* url = "/";
WebSocketsClient webSocketsClient = WebSocketsClient();
void handleMessage(char * message){
Serial.println("message...");
Serial.println(message);
}
void webSocketCallback(WStype_t type, uint8_t * payload, size_t length){
toggleLED();
switch(type){
case WStype_DISCONNECTED:
offLED();
break;
case WStype_TEXT:
onLED();
handleMessage((char*) payload);
break;
case WStype_CONNECTED:
default:
onLED();
break;
}
}
void toggleLED(){
LED_STATUS = (LED_STATUS + 1)%2;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void offLED(){
LED_STATUS = 1;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void onLED(){
LED_STATUS = 0;
digitalWrite(LED_BUILTIN, LED_STATUS);
}
void setup(void)
{
Serial.begin(9600);
// Connect to WiFi
WiFi.begin(ssid, password);
//setting the led pin
pinMode(LED_BUILTIN, OUTPUT);
// while wifi not connected yet, print '.'
// then after it connected, get out of the loop
while (WiFi.status() != WL_CONNECTED) {
toggleLED();
delay(500);
Serial.print(".");
}
//WiFi connected, IP address
Serial.println("");
Serial.println("WiFi connected");
Serial.println(WiFi.localIP());
offLED();
//websocket connection
webSocketsClient.begin(host, port, url);
webSocketsClient.onEvent(webSocketCallback);
webSocketsClient.setReconnectInterval(5000);
}
void loop() {
// Nothing
webSocketsClient.loop();
}
Solutions(few mistakes in the code):
Since my websocket supports secured connection : wss, so instead of begin() need to use beginSSL()
since wss is used, port number for secured connections is 443

How to recieve a Direct Method on the ESP32 with azure-sdk-for-c-arduino

For a school project I am using IoT Hub to connect between different devices (ESP32), The intention is to use a web application to retrieve data from a device. I want to do this by using a Direct Method.
Now I have seen in the past some direct methods using python and how I can use this in Azure Functions but not yet on an ESP32. By the way, I am programming in C on the ESP32.
Does anyone have an example code for this? I am not finding really much info about direct methods in C with the library "azure-sdk-for-c-arduino".
Thanks in advance
My code at the moment (This is test code):
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/*
This is an Arduino-based Azure IoT Hub sample for ESPRESSIF ESP32 boards.
It uses our Azure Embedded SDK for C to help interact with Azure IoT.
For reference, please visit https://github.com/azure/azure-sdk-for-c.
To connect and work with Azure IoT Hub you need an MQTT client, connecting, subscribing
and publishing to specific topics to use the messaging features of the hub.
Our azure-sdk-for-c is an MQTT client support library, helping composing and parsing the
MQTT topic names and messages exchanged with the Azure IoT Hub.
This sample performs the following tasks:
- Synchronize the device clock with a NTP server;
- Initialize our "az_iot_hub_client" (struct for data, part of our azure-sdk-for-c);
- Initialize the MQTT client (here we use ESPRESSIF's esp_mqtt_client, which also handle the tcp connection and TLS);
- Connect the MQTT client (using server-certificate validation, SAS-tokens for client authentication);
- Periodically send telemetry data to the Azure IoT Hub.
To properly connect to your Azure IoT Hub, please fill the information in the `iot_configs.h` file.
*/
//Variabeles for drukknop
const int PushButton = 35;
//Variables for weight sensor;
double weight = 5.0;
// C99 libraries
#include <cstdlib>
#include <string.h>
#include <time.h>
// Libraries for MQTT client and WiFi connection
#include <WiFi.h>
#include <mqtt_client.h>
// Azure IoT SDK for C includes
#include <az_core.h>
#include <az_iot.h>
#include <azure_ca.h>
// Libraries for SendingJson
#include <ArduinoJson.h>
// Additional sample headers
#include "AzIoTSasToken.h"
#include "SerialLogger.h"
#include "iot_configs.h"
// When developing for your own Arduino-based platform,
// please follow the format '(ard;<platform>)'.
#define AZURE_SDK_CLIENT_USER_AGENT "c/" AZ_SDK_VERSION_STRING "(ard;esp32)"
// Utility macros and defines
#define sizeofarray(a) (sizeof(a) / sizeof(a[0]))
#define NTP_SERVERS "pool.ntp.org", "time.nist.gov"
#define MQTT_QOS1 1
#define DO_NOT_RETAIN_MSG 0
#define SAS_TOKEN_DURATION_IN_MINUTES 60
#define UNIX_TIME_NOV_13_2017 1510592825
#define PST_TIME_ZONE -8
#define PST_TIME_ZONE_DAYLIGHT_SAVINGS_DIFF 1
#define GMT_OFFSET_SECS (PST_TIME_ZONE * 3600)
#define GMT_OFFSET_SECS_DST ((PST_TIME_ZONE + PST_TIME_ZONE_DAYLIGHT_SAVINGS_DIFF) * 3600)
// Translate iot_configs.h defines into variables used by the sample
static const char* ssid = IOT_CONFIG_WIFI_SSID;
static const char* password = IOT_CONFIG_WIFI_PASSWORD;
static const char* host = IOT_CONFIG_IOTHUB_FQDN;
static const char* mqtt_broker_uri = "mqtts://" IOT_CONFIG_IOTHUB_FQDN;
static const char* device_id = IOT_CONFIG_DEVICE_ID;
static const int mqtt_port = AZ_IOT_DEFAULT_MQTT_CONNECT_PORT;
// Memory allocated for the sample's variables and structures.
static esp_mqtt_client_handle_t mqtt_client;
static az_iot_hub_client client;
static char mqtt_client_id[128];
static char mqtt_username[128];
static char mqtt_password[200];
static uint8_t sas_signature_buffer[256];
static unsigned long next_telemetry_send_time_ms = 0;
static char telemetry_topic[128];
static uint8_t telemetry_payload[100];
static uint32_t telemetry_send_count = 0;
#define INCOMING_DATA_BUFFER_SIZE 128
static char incoming_data[INCOMING_DATA_BUFFER_SIZE];
// Auxiliary functions
#ifndef IOT_CONFIG_USE_X509_CERT
static AzIoTSasToken sasToken(
&client,
AZ_SPAN_FROM_STR(IOT_CONFIG_DEVICE_KEY),
AZ_SPAN_FROM_BUFFER(sas_signature_buffer),
AZ_SPAN_FROM_BUFFER(mqtt_password));
#endif // IOT_CONFIG_USE_X509_CERT
static void connectToWiFi()
{
Logger.Info("Connecting to WIFI SSID " + String(ssid));
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Logger.Info("WiFi connected, IP address: " + WiFi.localIP().toString());
}
static void initializeTime()
{
Logger.Info("Setting time using SNTP");
configTime(GMT_OFFSET_SECS, GMT_OFFSET_SECS_DST, NTP_SERVERS);
time_t now = time(NULL);
while (now < UNIX_TIME_NOV_13_2017)
{
delay(500);
Serial.print(".");
now = time(nullptr);
}
Serial.println("");
Logger.Info("Time initialized!");
}
void receivedCallback(char* topic, byte* payload, unsigned int length)
{
Logger.Info("Received [");
Logger.Info(topic);
Logger.Info("]: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println("");
}
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event)
{
switch (event->event_id)
{
int i, r;
case MQTT_EVENT_ERROR:
Logger.Info("MQTT event MQTT_EVENT_ERROR");
break;
case MQTT_EVENT_CONNECTED:
Logger.Info("MQTT event MQTT_EVENT_CONNECTED");
r = esp_mqtt_client_subscribe(mqtt_client, AZ_IOT_HUB_CLIENT_C2D_SUBSCRIBE_TOPIC, 1);
if (r == -1)
{
Logger.Error("Could not subscribe for cloud-to-device messages.");
}
else
{
Logger.Info("Subscribed for cloud-to-device messages; message id:" + String(r));
}
break;
case MQTT_EVENT_DISCONNECTED:
Logger.Info("MQTT event MQTT_EVENT_DISCONNECTED");
break;
case MQTT_EVENT_SUBSCRIBED:
Logger.Info("MQTT event MQTT_EVENT_SUBSCRIBED");
break;
case MQTT_EVENT_UNSUBSCRIBED:
Logger.Info("MQTT event MQTT_EVENT_UNSUBSCRIBED");
break;
case MQTT_EVENT_PUBLISHED:
Logger.Info("MQTT event MQTT_EVENT_PUBLISHED");
break;
case MQTT_EVENT_DATA:
Logger.Info("MQTT event MQTT_EVENT_DATA");
for (i = 0; i < (INCOMING_DATA_BUFFER_SIZE - 1) && i < event->topic_len; i++)
{
incoming_data[i] = event->topic[i];
}
incoming_data[i] = '\0';
Logger.Info("Topic: " + String(incoming_data));
for (i = 0; i < (INCOMING_DATA_BUFFER_SIZE - 1) && i < event->data_len; i++)
{
incoming_data[i] = event->data[i];
}
incoming_data[i] = '\0';
if (String(incoming_data) == "GETWEIGHT")
{
Logger.Info("Send Data To The Cloud ");
sendTelemetry();
}
else
{
Logger.Info("Data: " + String(incoming_data));
}
break;
case MQTT_EVENT_BEFORE_CONNECT:
Logger.Info("MQTT event MQTT_EVENT_BEFORE_CONNECT");
break;
default:
Logger.Error("MQTT event UNKNOWN");
break;
}
return ESP_OK;
}
static void initializeIoTHubClient()
{
az_iot_hub_client_options options = az_iot_hub_client_options_default();
options.user_agent = AZ_SPAN_FROM_STR(AZURE_SDK_CLIENT_USER_AGENT);
if (az_result_failed(az_iot_hub_client_init(
&client,
az_span_create((uint8_t*)host, strlen(host)),
az_span_create((uint8_t*)device_id, strlen(device_id)),
&options)))
{
Logger.Error("Failed initializing Azure IoT Hub client");
return;
}
size_t client_id_length;
if (az_result_failed(az_iot_hub_client_get_client_id(
&client, mqtt_client_id, sizeof(mqtt_client_id) - 1, &client_id_length)))
{
Logger.Error("Failed getting client id");
return;
}
if (az_result_failed(az_iot_hub_client_get_user_name(
&client, mqtt_username, sizeofarray(mqtt_username), NULL)))
{
Logger.Error("Failed to get MQTT clientId, return code");
return;
}
Logger.Info("Client ID: " + String(mqtt_client_id));
Logger.Info("Username: " + String(mqtt_username));
}
static int initializeMqttClient()
{
#ifndef IOT_CONFIG_USE_X509_CERT
if (sasToken.Generate(SAS_TOKEN_DURATION_IN_MINUTES) != 0)
{
Logger.Error("Failed generating SAS token");
return 1;
}
#endif
esp_mqtt_client_config_t mqtt_config;
memset(&mqtt_config, 0, sizeof(mqtt_config));
mqtt_config.uri = mqtt_broker_uri;
mqtt_config.port = mqtt_port;
mqtt_config.client_id = mqtt_client_id;
mqtt_config.username = mqtt_username;
#ifdef IOT_CONFIG_USE_X509_CERT
Logger.Info("MQTT client using X509 Certificate authentication");
mqtt_config.client_cert_pem = IOT_CONFIG_DEVICE_CERT;
mqtt_config.client_key_pem = IOT_CONFIG_DEVICE_CERT_PRIVATE_KEY;
#else // Using SAS key
mqtt_config.password = (const char*)az_span_ptr(sasToken.Get());
#endif
mqtt_config.keepalive = 30;
mqtt_config.disable_clean_session = 0;
mqtt_config.disable_auto_reconnect = false;
mqtt_config.event_handle = mqtt_event_handler;
mqtt_config.user_context = NULL;
mqtt_config.cert_pem = (const char*)ca_pem;
mqtt_client = esp_mqtt_client_init(&mqtt_config);
if (mqtt_client == NULL)
{
Logger.Error("Failed creating mqtt client");
return 1;
}
esp_err_t start_result = esp_mqtt_client_start(mqtt_client);
if (start_result != ESP_OK)
{
Logger.Error("Could not start mqtt client; error code:" + start_result);
return 1;
}
else
{
Logger.Info("MQTT client started");
return 0;
}
}
/*
#brief Gets the number of seconds since UNIX epoch until now.
#return uint32_t Number of seconds.
*/
static uint32_t getEpochTimeInSecs()
{
return (uint32_t)time(NULL);
}
static void establishConnection()
{
connectToWiFi();
initializeTime();
initializeIoTHubClient();
(void)initializeMqttClient();
}
static void getTelemetryPayload(az_span payload, az_span* out_payload)
{
az_span original_payload = payload;
payload = az_span_copy(
payload, AZ_SPAN_FROM_STR("{ \"deviceId\": "));
payload = az_span_copy(payload, AZ_SPAN_FROM_STR( IOT_CONFIG_DEVICE_ID ));
payload = az_span_copy(payload, AZ_SPAN_FROM_STR( "," ));
payload = az_span_copy(payload, AZ_SPAN_FROM_STR( "\" weight\": "));
(void)az_span_u32toa(payload, weight , &payload);
payload = az_span_copy(payload, AZ_SPAN_FROM_STR(" }"));
payload = az_span_copy_u8(payload, '\0');
*out_payload = az_span_slice(original_payload, 0, az_span_size(original_payload) - az_span_size(payload) - 1);
}
static void sendTelemetry()
{
az_span telemetry = AZ_SPAN_FROM_BUFFER(telemetry_payload);
Logger.Info("Sending telemetry ...");
// The topic could be obtained just once during setup,
// however if properties are used the topic need to be generated again to reflect the
// current values of the properties.
if (az_result_failed(az_iot_hub_client_telemetry_get_publish_topic(
&client, NULL, telemetry_topic, sizeof(telemetry_topic), NULL)))
{
Logger.Error("Failed az_iot_hub_client_telemetry_get_publish_topic");
return;
}
getTelemetryPayload(telemetry, &telemetry);
if (esp_mqtt_client_publish(
mqtt_client,
telemetry_topic,
(const char*)az_span_ptr(telemetry),
az_span_size(telemetry),
MQTT_QOS1,
DO_NOT_RETAIN_MSG)
== 0)
{
Logger.Error("Failed publishing");
}
else
{
Logger.Info("Message published successfully");
}
}
// Arduino setup and loop main functions.
void setup()
{
establishConnection();
pinMode(PushButton, INPUT);
}
void loop()
{
if (WiFi.status() != WL_CONNECTED)
{
connectToWiFi();
}
#ifndef IOT_CONFIG_USE_X509_CERT
else if (sasToken.IsExpired())
{
Logger.Info("SAS token expired; reconnecting with a new one.");
(void)esp_mqtt_client_destroy(mqtt_client);
initializeMqttClient();
}
#endif
int Push_button_state = digitalRead(PushButton);
// if condition checks if push button is pressed
if ( Push_button_state == HIGH )
{
Serial.println("De Button Is ingedrukt");
sendTelemetry();
delay(500);
}
}
The idea is that when I send a Direct Method "GETWEIGHT" I get a json value back.
In your initializeMqttClient method, you can add the following line.
mqtt_client.setCallback(receivedCallback);
Your receivedCallback method can have the following definition (code from a Microsoft sample)
void receivedCallback(char* topic, byte* payload, unsigned int length)
{
Logger.Info("Received [");
Logger.Info(topic);
Logger.Info("]: ");
for (int i = 0; i < length; i++)
{
Serial.print((char)payload[i]);
}
Serial.println("");
}
You mentioned you want to retrieve data from the device, so you probably want to respond to the message. This is done by sending a message on the right topic. You need to include the status (for instance a 200 indicating 'OK') and the ID of the direct method. This id is included when you receive the direct method. For instance, if you receive a direct method with ID 42, you can respond to it by publishing:
void RespondToDirectMethod()
{
mqtt_client.publish("$iothub/methods/res/200/?$rid=42", "", false);
}

MQTT Websocket Arduino Uno with SIM7600

I'm created a program to connect an Arduino Uno to a MQTT broker.
With the code that you can see below, I can connect to the broker, for testing I use HiveMQ with a plain TCP connection, everything go more or less well.
But for the final broker I'm going to use Websockets secure (wss) and I cant find how to do it.
I read that "I should wrap the client with the websocket", like is made here, the problem is that all the libraries I found use WiFiClientSecure.h
Do you know any way to do this? Any library or example to use a GSM board to connect using websocket to MQTT?
//DEFINITION
#define TINY_GSM_MODEM_SIM7600 //have to be before the include
#define Terminal Serial
#define SIM7600RX_PIN 2
#define SIM7600TX_PIN 3
#define SIM7600PWR_PIN 5
//GPRS credentials
const char apn[] = "";
const char gprsUser[] = "";
const char gprsPass[] = "";
//MQTT
const char* broker = "broker.hivemq.com";
const char* topic = "/testPablo/init";
const char* topiclstWill = "/testPablo/last";
const int mqttPort = 1883;
uint32_t lastReconnectAttempt = 0;
//INCLUDE LIBRARIES
#include <SoftwareSerial.h>
#include <TinyGsmClient.h>
#include <PubSubClient.h>
//VARIABLE
SoftwareSerial SIM7600(SIM7600RX_PIN, SIM7600TX_PIN);
TinyGsm modem(SIM7600);
TinyGsmClient client(modem);
PubSubClient mqtt(client);
//Function
void activateSIM7600(){
Terminal.println("Starting 4G Module...");
pinMode(SIM7600PWR_PIN, OUTPUT);
digitalWrite(SIM7600PWR_PIN,HIGH);
delay(15000); //wait SIM7600 to start
Terminal.println("wait...");
}
bool connectNetwork(){
Terminal.print("Connecting to network...");
modem.gprsConnect(apn, gprsUser, gprsPass);
Terminal.print("Waiting for network...");
if (!modem.waitForNetwork()) {
Terminal.println(" fail");
delay(5000);
return false;
}
Terminal.println(" success");
if (modem.isNetworkConnected()) {
Terminal.println("Network connected");
}
}
void configureSIM7600(){
SIM7600.begin(115200);
modem.init();
String modemInfo = modem.getModemInfo();
Terminal.print("Modem Info: ");
Terminal.println(modemInfo);
connectNetwork();
}
void mqttCallback(char* topic, byte* payload, unsigned int len) {
Terminal.print("Message arrived [");
}
void configureMQTT(){
// MQTT Broker setup
mqtt.setServer(broker, 1883);
mqtt.setCallback(mqttCallback);
}
boolean mqttConnect() {
Terminal.print("Connecting to ");
Terminal.print(broker);
// Connect to MQTT Broker
boolean status = mqtt.connect("GsmClientTest");
//authenticate MQTT:
//boolean status = mqtt.connect("GsmClientName", "mqtt_user", "mqtt_pass");
if (status == false) {
Terminal.println(" fail");
return false;
}
Terminal.println(" success");
mqtt.publish(topic, "GsmClientTest started");
//mqtt.subscribe(topicLed);
return mqtt.connected();
}
void setup() {
Terminal.begin(115200);
delay(10);
activateSIM7600();
configureSIM7600();
configureMQTT();
Terminal.println("Finish configuration");
}
void loop() {
if (!mqtt.connected()) {
Terminal.println("=== MQTT NOT CONNECTED ===");
uint32_t t = millis(); // Reconnect every 10 seconds
if (t - lastReconnectAttempt > 10000L) {
lastReconnectAttempt = t;
if (mqttConnect()) {
lastReconnectAttempt = 0;
}
}
delay(100);
return;
}
mqtt.loop();
}
You want an Arduino to connect to a broker, in most cases this is done by using ports 1883 or 8883 (secured).
WebSockets are needed if you want to connect to a web client such as a browser and this is done in most cases over ports 8080, 8081 an alike.
If I've understood the README for the library you've linked to you need to use the TinyGsmClient instance instead of the WifiClientSecure
Something like:
TinyGsmClient client(modem);
WebSocketClient250 wsClient(client, host, port);
WebSocketStreamClient wsStreamClient(wsClient, path);
PubSubClient mqtt(wsStreamClient);
This should work for the unsecured version

nodeMCU connect refused with XMAPP localhost

My project is about using nodeMCU measure value from sensor DHT11 and sent value to database Mysql. I use xampp for server. I cannot sent value to database.
nodeMCU can read value and sent value.But HTTP GET is fail.And return connect refused. I think maybe have problems with port for listening.
this is my code
#include <Arduino.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include "DHT.h"
#define DHTPIN 2 // what digital pin the DHT22 is conected to
#define DHTTYPE DHT11 // there are multiple kinds of DHT sensors
DHT dht(DHTPIN, DHTTYPE);
ESP8266WiFiMulti WiFiMulti;
const char* ssid = "something";
const char* password = "something";
int EP =5;
void setup() {
Serial.begin(115200);
pinMode(EP, INPUT);
for (uint8_t t = 4; t > 0; t--) {
Serial.printf("[SETUP] WAIT %d...\n", t);
Serial.flush();
delay(1000);
}
WiFiMulti.addAP(ssid, password); // ssid , password
randomSeed(50);
}
int timeSinceLastRead = 0;
void loop() {
if ((WiFiMulti.run() == WL_CONNECTED)) {
HTTPClient http;
float temp = dht.readTemperature();
float humi = dht.readHumidity();
long meas =TP_init();
Serial.println(WiFi.localIP());
//int temp = random(25,35);
String url = "localhost:8012/add2.php?temp="+String(temp)+"&humi="+String(humi)+"&meas=0";
Serial.println(url);
http.begin(url); //HTTP
int httpCode = http.GET();
if (httpCode > 0) {
Serial.printf("[HTTP] GET... code: %d\n", httpCode);
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();
}
delay(3000);
}
long TP_init(){
delay(10);
long meas=pulseIn (EP, HIGH); //wait for the pin to get HIGH and returns measurement
return meas;
}
I changed Apache port from 80 to 8012
I use PHPMyadmin for store database . File php's name add2.php for insert value from sensor DHT11
enter image description here
This is result from serial port.
String url = "localhost should be replaced with String url = "<IP-address-of-your-webserver> as the webserver clearly isn't running on the ESP8266.

Resources