Created
September 5, 2015 08:00
-
-
Save Krifto/865456a1f9596c0878b3 to your computer and use it in GitHub Desktop.
MQTT (PubSubClient) over RF24Ethernet/RF24Gateway
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <RF24.h> | |
#include <SPI.h> | |
#include <RF24Mesh.h> | |
#include <RF24Network.h> | |
#include <RF24Ethernet.h> | |
#include <PubSubClient.h> | |
/*** Configure the radio CE & CS pins ***/ | |
RF24 radio(7, 8); | |
RF24Network network(radio); | |
RF24Mesh mesh(radio, network); | |
RF24EthernetClass RF24Ethernet(radio, network, mesh); | |
void callback(char* topic, byte* payload, unsigned int length) { | |
Serial.print("Message arrived ["); | |
Serial.print(topic); | |
Serial.print("] "); | |
for (int i = 0; i<length; i++) { | |
Serial.print((char)payload[i]); | |
} | |
Serial.println(); | |
} | |
EthernetClient ethClient; | |
PubSubClient psClient(ethClient); | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!psClient.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
if (psClient.connect("arduinoClient")) { | |
Serial.println("connected"); | |
// Once connected, publish an announcement... | |
psClient.publish("outTopic", "hello world"); | |
// ... and resubscribe | |
psClient.subscribe("inTopic"); | |
} | |
else { | |
Serial.print("failed, rc="); | |
Serial.println(psClient.state()); | |
} | |
} | |
} | |
void setup() { | |
Serial.begin(115200); | |
// printf_begin(); | |
Serial.println("Start"); | |
IPAddress gwIP(10, 10, 2, 2); | |
psClient.setServer(gwIP, 1883); | |
psClient.setCallback(callback); | |
// Set the IP address we'll be using. The last octet mast match the nodeID (9) | |
IPAddress myIP(10, 10, 2, 4); | |
Ethernet.begin(myIP); | |
mesh.begin(); | |
// If you'll be making outgoing connections from the Arduino to the rest of | |
// the world, you'll need a gateway set up. | |
Ethernet.set_gateway(gwIP); | |
} | |
void loop() { | |
if (!psClient.connected()) { | |
reconnect(); | |
} | |
psClient.loop(); | |
// We can do other things in the loop, but be aware that the loop will | |
// briefly pause while IP data is being processed. | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment