#include <SPI.h>
#include <RF24.h>
#include <RF24Network.h>
#include <RF24Mesh.h>
#include <MQTT.h>
RF24 radio(7, 8);
RF24Network network(radio);
RF24Mesh mesh(radio, network);
IPAddress ip(10, 10, 2, 4);
IPAddress gateway(10, 10, 2, 2);
IPAddress server(10, 10, 2, 2);
char clientID[] = { "arduinoClient " };
void messageReceived(String& topic, String& payload) {
Serial.println("incoming: ");
Serial.print(topic);
Serial.print(" - ");
Serial.println(payload);
}
MQTTClient client;
void connect() {
Serial.print("connecting...");
uint32_t clTimeout = millis() + 5001;
while (!client.connect(clientID)) {
Serial.print(".");
if (millis() > clTimeout) {
mesh.renewAddress();
Serial.println();
return;
}
uint32_t timer = millis() + 1000;
while (millis() < timer) {
}
}
Serial.println("\nconnected!");
client.publish("outTopic", "hello world");
client.subscribe("inTopic", 2);
}
void setup() {
Serial.begin(115200);
if (mesh.begin()) {
Serial.println(" OK");
} else {
Serial.println(" Failed");
}
char str[4];
itoa(ip[3], str, 10);
memcpy(&clientID[13], &str, strlen(str));
Serial.println(clientID);
client.begin(server, ethClient);
client.onMessage(messageReceived);
}
uint32_t mesh_timer = 0;
uint32_t pub_timer = 0;
void loop() {
if (millis() - mesh_timer > 30000) {
mesh_timer = millis();
if (!mesh.checkConnection()) {
if (mesh.renewAddress() == MESH_DEFAULT_ADDRESS) {
mesh.begin();
}
}
Serial.println();
}
if (!client.connected()) {
connect();
}
client.loop();
if (client.connected() && millis() - pub_timer > 3000) {
pub_timer = millis();
char str[4];
itoa(ip[3], str, 10);
char str1[] = "Node \r\n";
memcpy(&str1[5], &str, strlen(str));
client.publish("outTopic", str1);
}
}
RF24EthernetClass RF24Ethernet