Skip to content

Instantly share code, notes, and snippets.

@mtzfactory
Created February 20, 2017 18:58
Show Gist options
  • Save mtzfactory/decc1fa356a6ae1da4e109f9e0b78926 to your computer and use it in GitHub Desktop.
Save mtzfactory/decc1fa356a6ae1da4e109f9e0b78926 to your computer and use it in GitHub Desktop.
configNetwork_Mqtt
#include <user_config.h>
#include <SmingCore/SmingCore.h>
#include <AppSettings.h>
#include "mqtt_func.h"
// MQTT
//
Timer procTimer;
// CONFIG SERVER
//
HttpServer server;
FTPServer ftp;
BssList networks;
String network, password;
Timer connectionTimer;
void onIndex(HttpRequest &request, HttpResponse &response)
{
TemplateFileStream *tmpl = new TemplateFileStream("index.html");
auto &vars = tmpl->variables();
response.sendTemplate(tmpl); // will be automatically deleted
}
void onIpConfig(HttpRequest &request, HttpResponse &response)
{
if (request.getRequestMethod() == RequestMethod::POST)
{
AppSettings.dhcp = request.getPostParameter("dhcp") == "1";
AppSettings.ip = request.getPostParameter("ip");
AppSettings.netmask = request.getPostParameter("netmask");
AppSettings.gateway = request.getPostParameter("gateway");
debugf("Updating IP settings: %d", AppSettings.ip.isNull());
AppSettings.save();
}
TemplateFileStream *tmpl = new TemplateFileStream("settings.html");
auto &vars = tmpl->variables();
bool dhcp = WifiStation.isEnabledDHCP();
vars["dhcpon"] = dhcp ? "checked='checked'" : "";
vars["dhcpoff"] = !dhcp ? "checked='checked'" : "";
if (!WifiStation.getIP().isNull())
{
vars["ip"] = WifiStation.getIP().toString();
vars["netmask"] = WifiStation.getNetworkMask().toString();
vars["gateway"] = WifiStation.getNetworkGateway().toString();
}
else
{
vars["ip"] = "192.168.1.77";
vars["netmask"] = "255.255.255.0";
vars["gateway"] = "192.168.1.1";
}
response.sendTemplate(tmpl); // will be automatically deleted
}
void onFile(HttpRequest &request, HttpResponse &response)
{
String file = request.getPath();
if (file[0] == '/')
file = file.substring(1);
if (file[0] == '.')
response.forbidden();
else
{
response.setCache(86400, true); // It's important to use cache for better performance.
response.sendFile(file);
}
}
void onAjaxNetworkList(HttpRequest &request, HttpResponse &response)
{
JsonObjectStream* stream = new JsonObjectStream();
JsonObject& json = stream->getRoot();
json["status"] = (bool)true;
bool connected = WifiStation.isConnected();
json["connected"] = connected;
if (connected)
{
// Copy full string to JSON buffer memory
json["network"]= WifiStation.getSSID();
}
JsonArray& netlist = json.createNestedArray("available");
for (int i = 0; i < networks.count(); i++)
{
if (networks[i].hidden) continue;
JsonObject &item = netlist.createNestedObject();
item["id"] = (int)networks[i].getHashId();
// Copy full string to JSON buffer memory
item["title"] = networks[i].ssid;
item["signal"] = networks[i].rssi;
item["encryption"] = networks[i].getAuthorizationMethodName();
}
response.setAllowCrossDomainOrigin("*");
response.sendJsonObject(stream);
}
// Will be called when WiFi station was connected to AP
void connectOk()
{
Serial.printf(">> Conectado a la red %s.\r\n", WifiStation.getSSID().c_str());
startMqttClient(); // Run MQTT client
//procTimer.initializeMs(15 * 1000, publishMessage).start(); // Start publishing loop
}
// Will be called when WiFi station timeout was reached
void connectFail()
{
Serial.printf(">> Sin conexion a la red %s.\r\n", WifiStation.getSSID().c_str());
//WifiStation.enable(false);
//WifiAccessPoint.enable(true); // Start AP for configuration
//WifiAccessPoint.config("Sming Configuration", "", AUTH_OPEN);
}
void makeStaConnection()
{
WifiAccessPoint.enable(false);
WifiStation.enable(true);
WifiStation.config(network, password);
AppSettings.ssid = network;
AppSettings.password = password;
AppSettings.save();
network = ""; // task completed
WifiStation.waitConnection(connectOk, 20, connectFail);
}
void onAjaxConnect(HttpRequest &request, HttpResponse &response)
{
JsonObjectStream* stream = new JsonObjectStream();
JsonObject& json = stream->getRoot();
String curNet = request.getPostParameter("network");
String curPass = request.getPostParameter("password");
bool updating = curNet.length() > 0 && (WifiStation.getSSID() != curNet || WifiStation.getPassword() != curPass);
bool connectingNow = WifiStation.getConnectionStatus() == eSCS_Connecting || network.length() > 0;
if (updating && connectingNow)
{
debugf("wrong action: %s %s, (updating: %d, connectingNow: %d)", network.c_str(), password.c_str(), updating, connectingNow);
json["status"] = (bool)false;
json["connected"] = (bool)false;
}
else
{
json["status"] = (bool)true;
if (updating)
{
network = curNet;
password = curPass;
debugf("CONNECT TO: %s %s", network.c_str(), password.c_str());
json["connected"] = false;
connectionTimer.initializeMs(1200, makeStaConnection).startOnce();
}
else
{
json["connected"] = WifiStation.isConnected();
debugf("Network already selected. Current status: %s", WifiStation.getConnectionStatusName());
}
}
if (!updating && !connectingNow && WifiStation.isConnectionFailed())
json["error"] = WifiStation.getConnectionStatusName();
response.setAllowCrossDomainOrigin("*");
response.sendJsonObject(stream);
}
void startWebServer()
{
server.listen(80);
server.addPath("/", onIndex);
server.addPath("/ipconfig", onIpConfig);
server.addPath("/ajax/get-networks", onAjaxNetworkList);
server.addPath("/ajax/connect", onAjaxConnect);
server.setDefaultHandler(onFile);
}
void networkScanCompleted(bool succeeded, BssList list)
{
if (succeeded)
{
for (int i = 0; i < list.count(); i++)
if (!list[i].hidden && list[i].ssid.length() > 0)
networks.add(list[i]);
}
networks.sort([](const BssInfo& a, const BssInfo& b){ return b.rssi - a.rssi; } );
}
void init()
{
spiffs_mount(); // Mount file system, in order to work with files
Serial.begin(SERIAL_BAUD_RATE); // 115200 by default
Serial.systemDebugOutput(true); // Enable debug output to serial
AppSettings.load();
WifiAccessPoint.enable(false);
WifiStation.enable(true);
if (AppSettings.exist())
{
WifiStation.config(AppSettings.ssid, AppSettings.password);
if (!AppSettings.dhcp && !AppSettings.ip.isNull())
WifiStation.setIP(AppSettings.ip, AppSettings.netmask, AppSettings.gateway);
}
WifiStation.startScan(networkScanCompleted);
// Start AP for configuration
WifiStation.disconnect();
WifiAccessPoint.enable(true);
WifiStation.connect();
WifiAccessPoint.config("Sming Configuration", "", AUTH_OPEN);
// Run WEB server on system ready
System.onReady(startWebServer);
}
#include <user_config.h>
#include <SmingCore/SmingCore.h>
#include <AppSettings.h>
#include "mqtt_func.h"
MqttClient *mqttc;
// For quick check you can use: http://www.hivemq.com/demos/websocket-client/ (Connection= test.mosquitto.org:8080)
// Publish our message
void publishMessage()
{
if (mqttc->getConnectionState() != eTCS_Connected)
startMqttClient(); // Auto reconnect
//String meas = readBarometer();
//Serial.printf(">> Publicando mensaje en 'mtz/sensors/%s': %s.\r\n", WifiStation.getHostname().c_str(), meas.c_str());
//mqtt.publish("mtz/sensors/" + sensorname, meas.c_str()); // or publishWithQoS
//blink();
mqttc->publish("mtz/sensors/s123", "bli bli"); // or publishWithQoS
}
// Check for MQTT Disconnection. Called whenever MQTT connection is failed.
void onMqttDisconnect(TcpClient& client, bool flag)
{
if (flag == true)
Serial.println(">> MQTT Broker desconectado!!");
else
Serial.println(">> MQTT Broker inalcanzable!!");
// Restart connection attempt after few seconds
procTimer.initializeMs(2 * 1000, startMqttClient).start(); // every 2 seconds
}
// Callback for messages, arrived from MQTT server
void onMqttMessageReceived(String topic, String message)
{
Serial.print(topic);
Serial.print(":\r\n\t"); // Pretify alignment for printing
Serial.println(message);
}
// Run MQTT client
void startMqttClient()
{
procTimer.stop();
mqttc = new MqttClient(MQTT_HOST, MQTT_PORT, onMqttMessageReceived);
if(!mqttc->setWill("last/will","The connection from this device is lost:(", 1, true)) {
Serial.println("Unable to set the last will and testament. Most probably there is not enough memory on the device."); //debugf
}
//mqtt.connect(sensorname, MQTT_USERNAME, MQTT_PWD);
mqttc->connect("mtz-sensor", MQTT_USERNAME, MQTT_PWD);
mqttc->setCompleteDelegate(onMqttDisconnect); // Assign a disconnect callback function
//mqtt.subscribe("mtz/" + sensorname + "/#");
mqttc->subscribe("mtz/cfg/s123/#");
}
/*
* mqtt.h
*
* Created on: Feb 20, 2017
* Author: mtz
*/
#ifndef INCLUDE_MQTT_FUNC_H_
#define INCLUDE_MQTT_FUNC_H_
// MQTT
//
// MQTT username and password
#ifndef MQTT_USERNAME
#define MQTT_USERNAME ""
#define MQTT_PWD ""
#endif
// MQTT host and port
#ifndef MQTT_HOST // mosquitto_sub -h broker.hivemq.com -t "mtz/sensors/#" -v
#define MQTT_HOST "broker.hivemq.com" //"test.mosquitto.org"
#define MQTT_PORT 1883
#endif
// Forward declarations
void publishMessage();
void startMqttClient();
void onMqttMessageReceived(String topic, String message);
extern Timer procTimer;
#endif /* INCLUDE_MQTT_FUNC_H_ */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment