Commit e58d05b9 authored by Jerome Courat's avatar Jerome Courat

Initial commit of library

parents
# DD WiFi MQTT Library
## build directives
When you use this library, you'll need to add those two lines in the platformio.ini file :
```
board_build.filesystem = littlefs
lib_ldf_mode = deep+
```
First line indicates that LittleFS needs to be used instead of SPIFFS for filesystem,
second one indicates that library dependencies need to be deeply fetched.
\ No newline at end of file
#include <Arduino.h>
#include "mqtt.h"
#include "wifi_settings.h"
WifiConfiguration wifi_settings;
MQTTConfiguration mqtt_settings;
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
}
void loop() {
}
\ No newline at end of file
#ifndef _MQTT_H__
#define _MQTT_H__
#include <PubSubClient.h>
#include "mqtt_settings.h"
void setup_mqtt(PubSubClient& pClient, MQTT_CALLBACK_SIGNATURE);
boolean publish_mqtt(PubSubClient& client, const char* topic, const char* payload);
boolean publish_mqtt(PubSubClient& client, const char* topic, const char* payload, bool retain);
void reconnect(PubSubClient& pClient);
#endif
\ No newline at end of file
#ifndef _MQTT_SETTINGS_H__
#define _MQTT_SETTINGS_H__
#include <ArduinoJson.h>
#include <FS.h>
#include <ESP8266WiFi.h>
struct MQTTConfiguration {
bool active;
String server;
int port;
String wifi_ap_ssid;
String client_id;
String client_username;
String client_password;
String temperature_topic;
String humidity_topic;
String pressure_topic;
String voltage_topic;
String command_topic;
String signal_topic;
};
extern MQTTConfiguration mqtt_settings;
boolean readMQTTSettings();
boolean writeMQTTSettings();
#endif
\ No newline at end of file
#ifndef _WIFI_H__
#define _WIFI_H__
#include "wifi_settings.h"
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
void setup_wifi();
#endif
\ No newline at end of file
#ifndef _WIFI_SETTINGS_H__
#define _WIFI_SETTINGS_H__
#include <ArduinoJson.h>
#include <FS.h>
struct WifiConfiguration {
String wifi_name;
boolean wifi_ap_active;
String wifi_ap_ssid;
String wifi_ap_pwd;
boolean wifi_sta_active;
String wifi_sta_ssid;
String wifi_sta_pwd;
};
extern WifiConfiguration wifi_settings;
boolean readWifiSettings();
boolean writeWifiSettings();
#endif
\ No newline at end of file
{
"name": "DDWifiMqtt",
"version": "1.0.0",
"description": "a simple library wrapping common steps in wifi connection and mqtt actions (connect, publish, subscribe).",
"keywords": "happy",
"repository": {
"type": "git",
"url": "https://gitlab.ntic-et-tac.info/iot/dd-wifi-mqtt.git"
},
"authors": [
{
"name": "Jérôme Courat",
"email": "jerome@courat.fr",
"url": "https://www.courat.fr/makerzblog/"
}
],
"dependencies": {
"knolleary/PubSubClient": "~2.8",
"bblanchon/ArduinoJson": "~6.12.0"
}
}
\ No newline at end of file
#include "mqtt.h"
void setup_mqtt(PubSubClient& pClient, MQTT_CALLBACK_SIGNATURE) {
if (readMQTTSettings() && mqtt_settings.active) {
Serial.println("Setting up MQTT");
pClient.setServer(mqtt_settings.server.c_str(), 1883);
pClient.setCallback(callback);
}
}
boolean publish_mqtt(PubSubClient& client, const char* topic, const char* payload) {
return publish_mqtt(client, topic, payload, true);
}
boolean publish_mqtt(PubSubClient& client, const char* topic, const char* payload, bool retain) {
boolean result = client.publish(topic, payload, retain);
client.loop();
return result;
}
void reconnect(PubSubClient& client) {
int i = 0;
// Loop until we're reconnected
while (!client.connected() && (i++ < 6)) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = mqtt_settings.client_id;
clientId += "-" + String(random(0xffff), HEX);
// Attempt to connect
if (client.connect(mqtt_settings.client_id.c_str(),
mqtt_settings.client_username.c_str(),
mqtt_settings.client_password.c_str())) {
Serial.println("connected");
// subscription
bool subSuccess = client.subscribe(mqtt_settings.command_topic.c_str());
if (subSuccess) {
Serial.println("-> subscription OK");
} else {
Serial.println("-> Subscription KO!!");
}
delay(250);
// subscription polling
client.loop();
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
\ No newline at end of file
#include "mqtt_settings.h"
#include "LittleFS.h"
String MQTT_CONFIG_FILE = "/mqtt.json";
boolean readMQTTSettings() {
LittleFS.begin();
File configFile = LittleFS.open(MQTT_CONFIG_FILE, "r");
if (!configFile) {
Serial.println("Failed to open config file");
LittleFS.end();
return false;
}
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
LittleFS.end();
return false;
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
// ArduinoJson 6 migration now...
StaticJsonDocument<384> doc;
auto error = deserializeJson(doc, buf.get());
if (error) {
Serial.println("Failed to parse config file");
LittleFS.end();
return false;
}
Serial.println("Loaded conf : ");
serializeJson(doc, Serial);
Serial.println("");
mqtt_settings.active = doc["mqtt"]["active"].as<bool>();
mqtt_settings.server = doc["mqtt"]["host"].as<String>();
mqtt_settings.port = doc["mqtt"]["port"].as<int>();
mqtt_settings.command_topic = doc["mqtt"]["topics"]["command"].as<String>();
mqtt_settings.temperature_topic = doc["mqtt"]["topics"]["temperature"].as<String>();
mqtt_settings.humidity_topic = doc["mqtt"]["topics"]["humidity"].as<String>();
mqtt_settings.pressure_topic = doc["mqtt"]["topics"]["pressure"].as<String>();
mqtt_settings.voltage_topic = doc["mqtt"]["topics"]["voltage"].as<String>();
mqtt_settings.signal_topic = doc["mqtt"]["topics"]["signal"].as<String>();
mqtt_settings.client_id = doc["mqtt"]["client"]["id"].as<String>();
mqtt_settings.client_username =
doc["mqtt"]["client"]["username"].as<String>();
mqtt_settings.client_password =
doc["mqtt"]["client"]["password"].as<String>();
Serial.println("End of MQTT Config");
LittleFS.end();
return true;
}
boolean writeMQTTSettings() { return false; }
\ No newline at end of file
/************************************************
* This example file still needs to be reviewed.
* not yet verified that it still compiles,
* but the idea is there...
************************************************/
#include "wifi.h"
extern WifiConfiguration wifi_settings;
void setup_wifi() {
if (readWifiSettings()) {
Serial.println("Wifi settings...");
Serial.print("AP?");
Serial.println(wifi_settings.wifi_ap_active);
if (wifi_settings.wifi_ap_active == true) {
Serial.print("Setting up Soft AP: ");
Serial.println(wifi_settings.wifi_ap_ssid);
IPAddress myIP = WiFi.softAP(wifi_settings.wifi_ap_ssid.c_str(),
wifi_settings.wifi_ap_pwd.c_str());
Serial.print("IP Address: ");
Serial.println(myIP);
}
Serial.print("STA?");
Serial.println(wifi_settings.wifi_sta_active);
if (wifi_settings.wifi_sta_active == true) {
Serial.print("Connecting to AP: ");
Serial.println(wifi_settings.wifi_sta_ssid);
if (WiFi.begin(wifi_settings.wifi_sta_ssid.c_str(),
wifi_settings.wifi_sta_pwd.c_str()) !=
WL_CONNECTED) {
Serial.println("Connected to Wifi :)");
Serial.println(WiFi.localIP());
} else {
Serial.println("Connection to wifi failed.");
}
randomSeed(micros());
delay(500);
Serial.println(WiFi.localIP());
}
} else {
Serial.println("Could not read settings");
}
MDNS.begin(wifi_settings.wifi_name.c_str());
}
\ No newline at end of file
#include <wifi_settings.h>
#include "LittleFS.h"
String WIFI_CONFIG_FILE = "/wifi.json";
boolean readWifiSettings() {
LittleFS.begin();
File configFile = LittleFS.open(WIFI_CONFIG_FILE, "r");
if (!configFile) {
Serial.println("Failed to open config file");
LittleFS.end();
return false;
}
size_t size = configFile.size();
if (size > 1024) {
Serial.println("Config file size is too large");
LittleFS.end();
return false;
}
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
// We don't use String here because ArduinoJson library requires the input
// buffer to be mutable. If you don't use ArduinoJson, you may as well
// use configFile.readString instead.
configFile.readBytes(buf.get(), size);
// ArduinoJson 6 migration now...
StaticJsonDocument<200> doc;
auto error = deserializeJson(doc, buf.get());
if (error) {
Serial.println("Failed to parse config file");
LittleFS.end();
return false;
}
Serial.println("Loaded conf : ");
serializeJson(doc, Serial);
Serial.println("");
wifi_settings.wifi_name = doc["wifi"]["name"].as<String>();
wifi_settings.wifi_ap_active = doc["wifi"]["ap"]["enabled"].as<boolean>();
wifi_settings.wifi_ap_ssid = doc["wifi"]["ap"]["ssid"].as<String>();
wifi_settings.wifi_ap_pwd = doc["wifi"]["ap"]["password"].as<String>();
wifi_settings.wifi_sta_active = doc["wifi"]["sta"]["enabled"].as<boolean>();
wifi_settings.wifi_sta_ssid = doc["wifi"]["sta"]["ssid"].as<String>();
wifi_settings.wifi_sta_pwd = doc["wifi"]["sta"]["password"].as<String>();
Serial.println("End of Wifi Config");
LittleFS.end();
return true;
}
boolean writeWifiSettings() {
return false;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment