I have a web server running on the esp8266.
The code is here:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266mDNS.h>
#include <ESP8266WebServer.h>
#include "index.h"
#include "login.h"
ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
ESP8266WebServer server(80); // Create a webserver object that listens for HTTP request on port 80
void handleRoot(); // function prototypes for HTTP handlers
void handleLogin();
void handleNotFound();
void setup(void){
Serial.begin(115200); // Start the Serial communication to send messages to the computer
delay(100);
wifiMulti.addAP("DIGISOL", "edot2017"); // add Wi-Fi networks you want to connect to
Serial.println("Connecting ...");
while (wifiMulti.run() != WL_CONNECTED) { // Wait for the Wi-Fi to connect: scan for Wi-Fi networks, and connect to the strongest of the networks above
delay(250);
Serial.print('.');
}
Serial.println('\n');
Serial.print("Connected to ");
Serial.println(WiFi.SSID()); // Tell us what network we're connected to
Serial.print("IP address:\t");
Serial.println(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
server.on("/", HTTP_GET, handleRoot); // Call the 'handleRoot' function when a client requests URI "/"
server.on("/login", HTTP_POST, handleLogin); // Call the 'handleLogin' function when a POST request is made to URI "/login"
server.on("/back",HTTP_POST,handleRoot);
server.onNotFound(handleNotFound); // When a client requests an unknown URI (i.e. something other than "/"), call function "handleNotFound"
server.begin(); // Actually start the server
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient(); // Listen for HTTP requests from clients
}
void handleRoot() { // When URI / is requested, send a web page
String indexPage = MAIN_page;
server.send(200, "text/html",indexPage);
}
void handleLogin() { // If a POST request is made to URI /login
String message = "";
if( ! server.hasArg("data") || server.arg("data") == NULL ){ // If the POST request doesn't have username and password data
server.send(400, "text/plain", "400: Invalid Request"); // The request is invalid, so send HTTP status 400
return;
}
else
{
message += server.arg("data"); //Get the name of the parameter
Serial.println(message);
String loginpage = LOGIN_PAGE;
server.send(200, "text/html",loginpage);
}
}
void handleNotFound(){
server.send(404, "text/plain", "404: Not found"); // Send HTTP status 404 (Not Found) when there's no handler for the URI in the request
}
Then I have a sketch to display a message on to the ledp10 display which is working fine.
ledp10 display message code:
#include <SPI.h>
#include <DMD2.h>
#include <fonts/SystemFont5x7.h>
#include <fonts/Arial14.h>
#include <fonts/Droid_Sans_24.h>
#include <fonts/Droid_Sans_16.h>
// Set Width to the number of displays wide you have
const int WIDTH = 1;
const int COUNTDOWN_FROM = 0;
int counter = COUNTDOWN_FROM;
// You can change to a smaller font (two lines) by commenting this line,
// and uncommenting the line after it:
const uint8_t *FONT = SystemFont5x7;
const uint8_t *FONT2 = SystemFont5x7;
const char *MESSAGE = "GOA";
SoftDMD dmd(WIDTH,1); // DMD controls the entire display
DMD_TextBox box(dmd, 0, 1);
DMD_TextBox box1(dmd,11,1); // "box" provides a text box to automatically write to/scroll the display
// the setup routine runs once when you press reset:
void setup() {
Serial.begin(9600);
dmd.setBrightness(255);
//dmd.selectFont(FONT);
dmd.begin();
}
// the loop routine runs over and over again forever:
void loop() {
dmd.selectFont(FONT);
box.print(counter);
dmd.selectFont(FONT2);
const char *next = MESSAGE;
while(*next) {
Serial.print(*next);
box1.print(*next);
delay(500);
next++;
}
box.println(F(""));
counter++;
if(counter == 60) {
dmd.clearScreen();
counter = 0;
}
}
Now I need to communicate between the esp8266 and atmega328p. I.e the message sent on the web page needs to be displayed on to the ledp10 display.
How should I do it?
Please help only in serial communication between esp8266 and atmega328p.
modify the lcd Atmega sketch to receive a text from Serial Monitor.
Then connect the esp8266 to Serial of Atmega and the Atmega sketch will receive the text you print to Serial in the esp sketch
Related
I need help with how i can send a tcp message using the ESPAsyncTCP library. The reason i have decided to use ESPAsyncTCP is that it is the only way i have gotten TCP server to work on my ESP8266 and not refuse the connection, but the example code confuses me a little since i dont know how the arrow/pointer operator work.
The code i have included below is the example code from the library, i have modified it to connect to a WiFi instead of being an access point, it works like it should but i dont understand how i can get this to send a message from the loop.
I have seen that it uses client->add() to add the message to a buffer and then sending it with client->send().
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <vector>
#include "config.h"
static std::vector<AsyncClient*> clients; // a list to hold all clients
/* clients events */
static void handleError(void* arg, AsyncClient* client, int8_t error) {
Serial.printf("\n connection error %s from client %s \n", client->errorToString(error), client->remoteIP().toString().c_str());
}
static void handleData(void* arg, AsyncClient* client, void *data, size_t len) {
Serial.printf("\n data received from client %s \n", client->remoteIP().toString().c_str());
Serial.write((uint8_t*)data, len);
// reply to client
// ----- This is where the example code from the library sends a reply and is what i would like to understand how to do from the loop ------
if (client->space() > 32 && client->canSend()) {
char reply[32];
sprintf(reply, "this is from %s", SERVER_HOST_NAME);
client->add(reply, strlen(reply));
client->send();
}
}
static void handleDisconnect(void* arg, AsyncClient* client) {
Serial.printf("\n client %s disconnected \n", client->remoteIP().toString().c_str());
}
static void handleTimeOut(void* arg, AsyncClient* client, uint32_t time) {
Serial.printf("\n client ACK timeout ip: %s \n", client->remoteIP().toString().c_str());
}
/* server events */
static void handleNewClient(void* arg, AsyncClient* client) {
Serial.printf("\n new client has been connected to server, ip: %s", client->remoteIP().toString().c_str());
// add to list
clients.push_back(client);
// register events
client->onData(&handleData, NULL);
client->onError(&handleError, NULL);
client->onDisconnect(&handleDisconnect, NULL);
client->onTimeout(&handleTimeOut, NULL);
}
void setup() {
Serial.begin(9600);
delay(20);
// connect to wifi
WiFi.begin(SSID, PASSWORD);
Serial.println("Connecting to WiFi..");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to the WiFi network");
Serial.println(WiFi.localIP());
AsyncServer* server = new AsyncServer(TCP_PORT); // start listening on tcp port 7050
server->onClient(&handleNewClient, server);
server->begin();
}
void loop() {}
I have a program trying to connect to a Bluetooth device and then sending an ack over a server (the server is private so I just used some pseudonym).
The first ACK on setup, goes through with 204 http return code which is fine, then it searches for a device, and whether it finds one or not it gives an error code of -1, then further on it gives 204 as well.
Here is the code that I have: (I have another project so this is just stripped down version trying things). This is also largely based form the Bluetooth client connect example on the esp32.
Code:
#include "BLEDevice.h"
#include "esp_bt.h"
#include "WiFi.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Arduino_JSON.h>
//WiFi variables
//HTTPClient http;
const char* ssid = "SSID";
const char* password = "Password";
char* serverName = "ServerName";
char* serverQR = "ServerName1";
String serverPath;
String httpRequestData;
bool wifiOn = 0;
bool wifiAck = 0;
int Connection = 0;
int httpResponseCode;
String Data = "";
String externalID = "";
bool answer = "false";
String payload = "{}";
BLEScan* pBLEScan;
// The remote service we wish to connect to.
static BLEUUID serviceUUID("0000fff0-0000-1000-8000-00805f9b34fb");
// The characteristic of the remote service we are interested in.
static BLEUUID charUUID("0000fff1-0000-1000-8000-00805f9b34fb");
static boolean doConnect = false; //should esp connect to ble device
static boolean connected = false; // is esp connected to a ble device
static boolean doScan = false; //should esp scan for ble devices
static BLERemoteCharacteristic* pRemoteCharacteristic; //init remote characterestic
static BLEAdvertisedDevice* myDevice; //init device found
static void notifyCallback( //beginning of functions, parameters follow
BLERemoteCharacteristic* pBLERemoteCharacteristic, //this is the device characterisitc value
uint8_t* pData, //data it received
size_t length,//length of data received
bool isNotify) {
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.println(length);
Serial.print("data: ");
Serial.println((char*)pData);
esp_bt_controller_deinit();
esp_bt_controller_disable();
}
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {//when connecting
connected = true;
Serial.println("onConnect");
}
void onDisconnect(BLEClient* pclient) {//when disconnecting
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {//connect to ble device
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();//create esp as a client
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());//set the function of client callbacks
// Connect to the remove BLE server.
pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be
recognized type of peer device address (public or private)
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);//can we connect to ble device
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
// Obtain a reference to the characteristic in the service of the remote BLE server.
pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID);//does the ble device have the
characteristic function we want?
if (pRemoteCharacteristic == nullptr) {
Serial.print("Failed to find our characteristic UUID: ");
Serial.println(charUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our characteristic");
// Read the value of the characteristic.
if (pRemoteCharacteristic->canRead()) {
std::string value = pRemoteCharacteristic->readValue();
Serial.print("The characteristic value was: ");
Serial.println(value.c_str());
}
if (pRemoteCharacteristic->canNotify()) //if ble server transmits data do a callback
pRemoteCharacteristic->registerForNotify(notifyCallback);
connected = true;
return true;
}
/**
Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {//When a scan is activated
/**
Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {//when a ble device is found
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);//ble server connected
doConnect = true;//has to connect
doScan = true;//has to scan
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
//WiFi setup
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting to WiFi...");
delay(1000);
}//end while
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
serverPath = serverName;
if (WiFi.status() == WL_CONNECTED) {
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Data to send with HTTP POST
JSONVar json_test;
json_test["id"] = WiFi.macAddress();
httpRequestData = JSON.stringify(json_test);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
httpResponseCode = http.POST(httpRequestData);
payload = " {}";
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println("This is the response code");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
WiFi.disconnect(true);
delay(1); // disable WIFI altogether
WiFi.mode(WIFI_OFF);
delay(1);
} else
{
Serial.println("WiFi disconnected");
}
} // End of setup.
// This is the Arduino main loop function.
void loop() {
esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT();
esp_bt_controller_init(&bt_cfg);
esp_bt_controller_enable(ESP_BT_MODE_BLE);
if (!connected)
{
Serial.println("Initialising");
pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setActiveScan(true);
Serial.println("Scan starting");
pBLEScan->start(30, false);
Serial.println("Scan ended");
}
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {//if ble server was found connect to it
if (connectToServer()) {
Serial.println("We are now connected to the BLE Server.");
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
esp_bt_controller_deinit();
esp_bt_controller_disable();
//WiFi setup
Serial.println();
Serial.printf("Connecting to %s\n", ssid);
WiFi.begin(ssid, password);
//WiFi.config(staticIP, gateway, subnet);
while (WiFi.status() != WL_CONNECTED)
{
Serial.println("Connecting to WiFi...");
delay(1000);
}//end while
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
HTTPClient http;
serverPath = serverName;
if (WiFi.status() == WL_CONNECTED) {
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// Data to send with HTTP POST
JSONVar json_test;
json_test["id"] = WiFi.macAddress();
httpRequestData = JSON.stringify(json_test);
// If you need an HTTP request with a content type: application/json, use the following:
http.addHeader("Content-Type", "application/json");
httpResponseCode = http.POST(httpRequestData);
if (httpResponseCode > 0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
Serial.println("This is the loop");
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
Serial.println("This is the loop");
}
// Free resources
http.end();
WiFi.disconnect(true);
delay(1); // disable WIFI altogether
WiFi.mode(WIFI_OFF);
delay(1);
} else
{
Serial.println("WiFi disconnected");
}
delay(1000); // Delay a second between loops.
} // End of loop
The output of the code is:
Starting Arduino BLE Client application...
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the response code IS this done? Initialising Scan starting BLE Advertised Device found: Name: , Address: address, manufacturer data:random stuff Scan ended Forming a connection to addresss
- Created client onConnect
- Connected to server
- Found our service
- Found our characteristic We are now connected to the BLE Server.
Connecting to SSID Connecting to WiFi... Connected, IP address: IP Error code: -1 This is the loop
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the loop
Connecting to SSID Connecting to WiFi... Connected, IP address: IP HTTP Response code: 204 This is the loop
My question basically is does anyone know what an erro0 rcode if -1 is? On my main project I am unable to send a get request after scanning for a ble device even if I disabl the controller.
To answer your question about error code -1:
It means that a connection was not successful according to this example from the HTTPClient repository.
Your log shows that you are able to connect to your server and afterwards to your BLE peripheral. But it seems like you never disconnect from the peripheral and continue to block the other wifi connections. Have a look at this for further ideas on using BLE and WiFi together.
error project
Guru Meditation Error in project
Core 0 panic'ed (LoadProhibited). Exception was unhandled.
I have project using pulsesensor with ESP32, Data from ESP32 is saved in database.
I tried many times but could not
help me
#include <ssl_client.h>
#include <WiFiClientSecure.h>
#include <WiFi.h>
#include <SPI.h>
#include <WiFiClient.h>
#include <HTTPClient.h>
#define USE_SERIAL Serial
/* Konfigurasi pada SSID dan Password Wifi */
const char* ssid = "berdikari";
const char* password = "alfian24";
/* Konfigurasi koneksi ke server */
char server[] = "192.168.43.108"; // Ganti dengan IP Address komputer aplikasi
int port = 81;
/*konfigurasi*/
int PulseSensorPurplePin = 34; // Pulse Sensor PURPLE WIRE connected to ANALOG PIN 0
int LED21 = 21; // The on-board Arduion LED
int Signal; // holds the incoming raw data. Signal value can range from 0-102
float pulse=0;
WiFiClient client;
void setup() {
USE_SERIAL.begin(115200); // Baudrate/kec. komunikasi pengiriman data ke serial terminal
delay(10);
Serial.println('\n');
WiFi.begin(ssid, password);
USE_SERIAL.print("Terhubung ke ");
USE_SERIAL.print(ssid);
// WiFi.config(local_IP, gateway, subnet, dns);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
USE_SERIAL.print('.');
}
USE_SERIAL.print('\n');
USE_SERIAL.println("Identitas ESP-32");
USE_SERIAL.print("IP Address:\t");
USE_SERIAL.println(WiFi.localIP()); // IP Address ESP-32
USE_SERIAL.print('\n');
USE_SERIAL.println("Identitas Web Server");
USE_SERIAL.println("IP Address:");
USE_SERIAL.print(server);
USE_SERIAL.print("\tport:\t");
USE_SERIAL.print(port);
}
void loop() {
Signal = analogRead(PulseSensorPurplePin); // Read the PulseSensor’s value.
// Send the Signal value to Serial Plotter.
delay(1000);
pulse = Signal;
USE_SERIAL.println(pulse);
if(WiFi.status() == WL_CONNECTED){
//URL target untuk menyimpan data sensor Pulse ke database
String url = "http://192.168.43.108:81/";
url += "sistem_monitoring/Monitoring/simpan/";
url += String(pulse);
HTTPClient http;
USE_SERIAL.print("[HTTP] begin...\n");
http.begin(url);
USE_SERIAL.print("[HTTP] GET...\n");
int httpCode = http.GET();
if(httpCode > 0) {
USE_SERIAL.printf("[HTTP] GET... code: %d\n",
httpCode);
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n",
http.errorToString(httpCode).c_str());
}
http.end();
}
}
please help me.
What should I do??
I've seen this question asked a few times but never got a good answer.
This is my first post so tell me where I go wrong.
Here is my setup.
I have a sensor connected via SCL and STA to a ESP8266 developer kit.
My language is arduino. This works, I can get it to put out the temperature and humidity into the serial monitor. I also have a raspberry pi (3?) that currently works as a wifi router. I used hostapd to do this. I have also signed up for amazon AWS, and have AWSIoT connected with the pi, which i have mosquitto running as the broker. My goal is to be able to leave the pi and esp with sensor in a location, pi connected with ethernet, and have the temperature and humidity come to kibana browser and I be able to see the data.
Here is my problem. mosquitto works with the mosquitto_sub and mosquitto_pub client. However, my arduino code cannot connect. I suspected that this was a problem with the IP address, so I consulted the internet, and got many test sites, but none told me where to find the IP to put as the mqtt broker server. I have included my code, and I live in japan, so don`t be frightened by the time settings. As you can see, I have been trying many different things that maybe could work :/.
#include "SparkFun_Si7021_Breakout_Library.h"
#include <Wire.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <time.h>
#include <WiFiUdp.h>
float humidity = 0;
float tempf = 0;
const char* SSID = "ssid";
const char* PASSWORD = "password";
const int MQTTPORT = 1883;
I tried many different ips here, but none of them worked.
(Using the const char* format below)(The reason I exclude them is for security(right?))
//const char* MQTTSERVER = "mosquitto.service";
//const char* MQTTSERVER = "systemctl";
//const char* MQTTSERVER = "bridgeawsiot2";
const char* MQTTINITTOPIC = "/dev/init/msg/";
const char* MQTTSNTOPIC = "/ras-xdv2/Si7021";
const char* MQTTINITTOPICMSG = "{\"dev\"=\"Si7021\",\"msg\"=\"init\"}";
// APRIME
WiFiUDP ntpUDP;
const char* NTPSERVER = "ntp.nict.jp";
const int NTPTIMEOFFSET = 9 * 60 * 60;
WiFiClient espClient;
PubSubClient client(espClient);
//Create Instance of HTU21D or SI7021 temp and humidity sensor and MPL3115A2 barrometric sensor
Weather sensor;
//---------------------------------------------------------------
void setup_wifi() {
delay(10);
Serial.print("WiFi CONNECTION...");
Serial.println(SSID);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print("Waiting...");
}
randomSeed(micros());
Serial.println(" ");
Serial.println("WiFi connected");
Serial.println("ESP8266 ip:");
Serial.println(WiFi.localIP());
}
//---------------------------------------------------------------
void mqttConnect() {
// client.setServer(MQTTSERVER, MQTTPORT);
while (!client.connected()) {
Serial.print("MQTT communications need more time...");
String clientId = "ESP8266-";
clientId += String(random(0xffff));
delay(3000);
if (client.connect(clientId.c_str())) {
Serial.println("MQTT communications online!");
client.publish(MQTTINITTOPIC, MQTTINITTOPICMSG);
} else {
Serial.print("MQTT communications unavailible, rc=");
Serial.print(client.state());
delay(2000);
Serial.println("Attempting connection in t-2 Seconds...");
delay(2000);
}
}
}
//---------------------------------------------------------------
void setup()
{
Serial.begin(115200);
sensor.begin();
setup_wifi();
client.setServer(MQTTSERVER, MQTTPORT);
delay(5000);
/*if (!sensor.begin()) {
Serial.print("sensor ded :(");
while (1);
}*/
configTime( NTPTIMEOFFSET, 0, NTPSERVER );
}
//---------------------------------------------------------------
void loop()
{
time_t t = time(NULL);
struct tm *tm;
tm = localtime(&t);
char dt[25];
sprintf(dt, "%04d-%02d-%02dT%02d:%02d:%02d+09:00", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);
Serial.printf(dt);
if(!client.connected()){
mqttConnect();
} else {
client.loop();
}
char pub_json[100];
//Get readings from all sensors
getWeather();
printInfo();
delay(10000);
char tempfbuf[4];
char humiditybuf[4];
sprintf(pub_json,"{\"Temperature\":%s,\"Humidity\": %s, \"#timestamp\": %s}]}",dtostrf(tempf, 4, 2, tempfbuf), dtostrf(humidity, 4, 2, humiditybuf), dt);
client.publish(MQTTSNTOPIC, pub_json);
Serial.println("TEMPERATURE BEING PUBLISHED...");
Serial.println(pub_json);
delay(60000 * 10);
}
//---------------------------------------------------------------
void getWeather()
{
// Measure Relative Humidity from the HTU21D or Si7021
humidity = sensor.getRH();
// Measure Temperature from the HTU21D or Si7021
tempf = sensor.getTemp();
// Temperature is measured every time RH is requested.
// It is faster, therefore, to read it from previous RH
// measurement with getTemp() instead with readTemp()
}
//---------------------------------------------------------------
void printInfo()
{
//This function prints the weather data out to the default Serial Port
Serial.print("Temp:");
Serial.print(tempf);
Serial.print("F, ");
Serial.print("Humidity:");
Serial.print(humidity);
Serial.println("%");
}
The mosquitto.conf file was nonexistant when I first downloaded mosquitto, so I created it and used this:
Please tell me if I posted sensitive information: I am new to this :)
c4message_size_limit 0
clientid bridgeawsiot2
persistence true
persistence_file mosquitto.db
persistence_location /var/mosquitto/
log_type all
connection_messages true
log_timestamp true
allow_anonymous true
password_file /etc/mosquitto/conf.d/users
allow_anonymous true
listener 9001 127.0.0.1
protocol websockets
connection_messages true
log_timestamp true
listener 1883
connection <awsiot>
address yl42kju76zjjodsbm6nfl4yycq.ap-northeast-1.es.amazonaws.com:8883
topic /esp8266/Si7021/slack out 1
cleansession true
notifications false
start_type automatic
bridge_cafile /etc/mosquitto/certs/root-CA.crt
bridge_certfile /etc/mosquitto/certs/RAS-XD.cert.pem
bridge_keyfile /etc/mosquitto/certs/RAS-XD.private.key
Maybe the problem is the websockets thing?
Any help is appreciated!
Literally any :)
I am doing some pretty good work with the esp8266 and mqtt using arduino IDE. I have mine logging on to my own mqtt broker I set up in a centos 7 box with encryption using x509 certs.
I use mosquitto-auth-plug to manage user access with a mysql database set up on the same machine
when you think about it the operating system is free, mosquitto broker is free, and mysql server is free.
the only expense to having your own setup is a fixed IP and fast enough connection. Which you could set up pretty cheap in a virtual machine on azure.
Anyhow when I first started a friend (the guy who sold me my first nodemcu .9 board). Hooked me up with this script and I have been able to get it all done using this as my example.
the part I liked was if you monitored your mqtt from a client like mqtt box or others. When the chip first starts it sends payload "Start" to topic "device_name/status". This way you can always tell when it's online.
I copied the notes he gave me they are located below.
good luck
/*
* Skeleton for ESPP based sensors.
* Supports:
* - OTA fw update via HTTP
* http://ipaddr/update
* - REST access
* http://ipaddr:8080/<id>
* - MQTT publish and subscribe
*/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <aREST.h>
// Define device name
const char* device_name = "myHostName";
const char* ssid = "WiFiSSID";
const char* password = "wiFiPassword";
const char* mqtt_server = "mqtt_hostname.example.com";
char host[14];
int rest_test = 7467;
/* WiFi Client */
WiFiClient espClient;
/* MQTT Client */
PubSubClient client(espClient);
/* HTTP client, for remote updates */
ESP8266WebServer httpServer(80);
ESP8266HTTPUpdateServer httpUpdater;
/* Rest server */
aREST rest = aREST();
WiFiServer restServer(8080);
void setup() {
char topic[80];
Serial.begin(115200);
/* Start WiFi */
setup_wifi();
/* Setup MQTT client */
client.setServer(mqtt_server, 1883);
client.setCallback(mqtt_callback);
/* Start the HTTP update server */
MDNS.begin(host);
httpUpdater.setup(&httpServer);
httpServer.begin();
MDNS.addService("http", "tcp", 80);
/* Set REST variables */
rest.set_id("1");
rest.set_name(host);
rest.variable("test", &rest_test);
/*
rest.variable("temperature", &temp);
rest.variable("distance", &dist);
rest.variable("reset_count", &reset_count);
rest.set_id("1");
rest.set_name("esp8266");
*/
restServer.begin();
/* Connect to the MQTT broker */
reconnect();
client.subscribe("network/broadcast");
sprintf(topic, "network/%s", device_name);
client.subscribe(topic);
sprintf(topic, "%s/status", device_name);
client.publish(topic, "start");
Serial.print("Node ");
Serial.print(device_name);
Serial.println(" started.");
Serial.print("Hostname ");
Serial.println(host);
Serial.print("IP Address ");
Serial.println(WiFi.localIP());
}
void setup_wifi() {
uint8_t mac[6];
delay(10);
WiFi.begin(ssid, password);
WiFi.macAddress(mac);
sprintf(host, "esp-%02x%02x%02x", mac[3], mac[4], mac[5]);
WiFi.hostname(host);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
}
/* Handle incoming MQTT messages */
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
char payloadStr[80];
if (length > 79) {
length = 79;
}
memcpy(payloadStr, payload, length);
payloadStr[length] = '\0';
if (strcmp(payloadStr, "discover") == 0) {
delay(random(10, 1000));
client.publish("network/presence", device_name);
}
if (strcmp(payloadStr, "refresh") == 0) {
/* Publish all sensor data */
}
}
/* Connect (or re-connect) to the MQTT broker */
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
// Attempt to connect
/* TODO: Create this based on the MAC address */
if (client.connect(host)) {
} else {
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
WiFiClient restClient;
/* Check MQTT connection, reconnect if needed */
if (!client.connected()) {
reconnect();
}
/* Process MQTT tasks */
client.loop();
/* Process HTTP FW update requests */
httpServer.handleClient();
/* Process REST requests */
restClient = restServer.available();
if (restClient) {
while (!restClient.available()) {
delay(1);
}
rest.handle(restClient);
}
/* Insert normal sensor code here. */
/* Publish results with client.publish(topic, value); */
}
My code sets up it's own device name, subscribes to the MQTT topics "network/broadcast", "network/(device name)".
When it starts it sends "(device_name)/status" with a payload of "start".
When it gets a "network/broadcast" with a payload of "discover" it replies by publishing a "network/presence" and its name.
Basically, you sent MQTT events with client.publish(topic, payload).
You subscribe to events with client.subscribe(topic).
When an event is received that matches your subscription it will call mqtt_callback and give it the topic, the payload, and the length.
Hope that helps.
I'm using NodeMCU v3, and can already send some information on its server.
But how can I receive some information from other web pages, let say for beginning, a plain text?
You need a HttpClient to communicate with a web server.
Good way to start is to use the HttpClient sample -> ReuseConnection.
This will allow you to make more requests than one.
You can see in Serial Monitor in Arduino IDE to see the response from the request.
Sample code:
Note: replace " http://:/someroute " with the desired http page you want to get.
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#define USE_SERIAL Serial
ESP8266WiFiMulti WiFiMulti;
HTTPClient http;
void setup() {
USE_SERIAL.begin(115200);
// USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFiMulti.addAP("SSID", "PASSWORD");
// allow reuse (if server supports it)
http.setReuse(true);
}
void loop() {
// wait for WiFi connection
if((WiFiMulti.run() == WL_CONNECTED)) {
http.begin("http://<IP>:<Port>/someroute");
int httpCode = http.GET();
if(httpCode > 0) {
USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
String payload = http.getString();
USE_SERIAL.println(payload);
}
} else {
USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
}
delay(3000);
}