Buonasera a tutti,
condivido il codice che uso come bridge per una rete mesh, come si potrebbe migliorare?
grazie a tutti per l'eventuale aiuto
//************************************************************
// this is a simple example that uses the painlessMesh library to
// connect to a another network and relay messages from a MQTT broker to the nodes of the mesh network.
// To send a message to a mesh node, you can publish it to "painlessMesh/to/12345678" where 12345678 equals the nodeId.
// To broadcast a message to all nodes in the mesh you can publish it to "painlessMesh/to/broadcast".
// When you publish "getNodes" to "painlessMesh/to/gateway" you receive the mesh topology as JSON
// Every message from the mesh which is send to the gateway node will be published to "painlessMesh/from/12345678" where 12345678
// is the nodeId from which the packet was send.
//************************************************************
unsigned long thisMillis = 0;
unsigned long lastMillis = 0;
unsigned long interval;//5 secondi
unsigned long now;
#include <Arduino.h>
//#include <painlessMesh.h>
#include "namedMesh.h"
#include <PubSubClient.h>
#include <WiFiClient.h>
#define MESH_PREFIX "whateverYouLike"
#define MESH_PASSWORD "somethingSneaky"
#define MESH_PORT 5555
#define STATION_SSID "linksys"
#define STATION_PASSWORD ""
#define HOSTNAME "MQTT_Bridge"
#define ROLE "mqttbridge"
#define VERSION "MQTTBRIDGE v1.0.14"
#define MESSAGE "mqttbridge "
// Prototypes
//void receivedCallback( const uint32_t &from, const String &msg );
void receivedCallback( const String &from, const String &msg );
void mqttCallback(char* topic, byte* payload, unsigned int length);
IPAddress getlocalIP();
IPAddress myIP(0,0,0,0);
IPAddress myAPIP(0,0,0,0);
//IPAddress mqttBroker(10, 42, 0, 1);
IPAddress mqttBroker(192, 168, 1, 60);
//painlessMesh mesh;
namedMesh mesh;
String msgg;
String nodeName = "bridgemqtt"; // Name needs to be unique
String myNetworkDetails;
WiFiClient wifiClient;
PubSubClient mqttClient(mqttBroker, 1883, mqttCallback, wifiClient);
void setup() {
Serial.begin(115200);
Serial.setDebugOutput(true);
//mesh.setDebugMsgTypes( ERROR | STARTUP | CONNECTION | DEBUG | MESH_STATUS | SYNC | COMMUNICATION | GENERAL | REMOTE ); // set before init() so that you can see startup messages
mesh.setDebugMsgTypes( ERROR | STARTUP );
// Channel set to 6. Make sure to use the same channel for your mesh and for you other
// network (STATION_SSID)
mesh.init( MESH_PREFIX, MESH_PASSWORD, MESH_PORT, WIFI_AP_STA, 11 );
mesh.initOTAReceive(ROLE);
mesh.setRoot(true);
mesh.setContainsRoot(true);
mesh.setName(nodeName);
mesh.onReceive(&receivedCallback);
mesh.stationManual(STATION_SSID, STATION_PASSWORD);
mesh.setHostname(HOSTNAME);
}
void update_status()
{
long uptime = millis() / 60000L;
char buf[16];
dtostrf(uptime,2,0, buf);
mqttClient.publish("home/bridge/uptime",buf);
String noded = String(mesh.getNodeId());
mqttClient.publish("home/bridge/nodeid",noded.c_str());
long fr=ESP.getFreeHeap();
dtostrf(fr,2,0, buf);
mqttClient.publish("home/bridge/freememory",buf);
myNetworkDetails = String(mesh.getNodeId()) + " ready! IP " + myIP.toString() + " wifi channel " + String(WiFi.channel()) + " Version " + String(VERSION);
mqttClient.publish("home/bridge/mynetwork",myNetworkDetails.c_str());
mqttClient.publish( "home/bridge/getrt", mesh.subConnectionJson(false).c_str());
}
void send_id()
{
msgg = "sendnodeid";
mesh.sendBroadcast(msgg);
}
void reconnect()
{
while (!mqttClient.connected())
{
Serial.println("Attempting MQTT connection...");
// Attemp to connect
if (mqttClient.connect("BridgeMqttMesh"))
{
Serial.println("Connected");
mqttClient.publish("home/bridge/start","Ready!");
mqttClient.subscribe("home/comand/#");
}
else
{
Serial.print("Failed, rc=");
Serial.print(mqttClient.state());
Serial.println(" try again in 2 seconds");
// Wait 2 seconds before retrying
delay(2000);
mesh.update();
mqttClient.loop();
}
}
}
void loop() {
mesh.update();
mqttClient.loop();
if(myIP != getlocalIP()){
myIP = getlocalIP();
Serial.println("My IP is " + myIP.toString());
}
if (!mqttClient.connected()) {
{reconnect();}
}
if((millis() - interval) > 100000) { //600000 - 10 min
update_status();
send_id();
interval=millis();
}
}
//void receivedCallback( String from, String &msg ) {
void receivedCallback( const String &from, const String &msg ) {
Serial.printf("bridge: Received from %s msg=%s\n", from.c_str(), msg.c_str());
char *primo;
char *secondo;
char msg_array[100];
msg.toCharArray(msg_array, 100);
primo=strtok(msg_array, "/");
secondo=strtok(NULL, "/");
String topic = "home/" + String(from.c_str() + String("/") + String(primo));
Serial.printf("bridge: Send server mqtt %s sec %s\n", topic.c_str(), secondo);
mqttClient.publish(topic.c_str(), secondo);
}
void mqttCallback(char* topic, uint8_t* payload, unsigned int length) {
char* cleanPayload = (char*)malloc(length+1);
memcpy(cleanPayload, payload, length);
cleanPayload[length] = '\0';
String msg = String(cleanPayload);
free(cleanPayload);
String targetStr = String(topic).substring(12);//5
mesh.sendSingle(targetStr, msg);
Serial.printf("bridge: Send target %s msg %s\n", targetStr, msg);
if(msg == "nodelist")
{
auto nodes = mesh.getNodeList(true);
String str;
for (auto &&id : nodes)
str += String(id) + String(" ");
mqttClient.publish("home/bridge/nodelist", str.c_str());
}
else if(msg == "getrt")
{
mqttClient.publish( "home/bridge/getrt", mesh.subConnectionJson(false).c_str());
}
// if(msg == "nodetree")
// {
// mqttClient.publish( "painlessMesh/from/nodetree", mesh.asNodeTree().c_str() );
// }
}
IPAddress getlocalIP() {
return IPAddress(mesh.getStationIP());
}