Allow any instance of Client to be passed in.

Added new example for publishing in callback.
This commit is contained in:
Nicholas O'Leary
2012-09-13 22:35:48 +01:00
parent 2d43044338
commit a971ed4a2c
6 changed files with 109 additions and 45 deletions

View File

@ -1,7 +1,8 @@
/*
Basic MQTT example
Basic MQTT example with Authentication
- connects to an MQTT server
- connects to an MQTT server, providing username
and password
- publishes "hello world" to the topic "outTopic"
- subscribes to the topic "inTopic"
*/
@ -19,7 +20,8 @@ void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
PubSubClient client(server, 1883, callback);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{

View File

@ -19,7 +19,8 @@ void callback(char* topic, byte* payload, unsigned int length) {
// handle message arrived
}
PubSubClient client(server, 1883, callback);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
void setup()
{

View File

@ -0,0 +1,51 @@
/*
Publishing in the callback
- connects to an MQTT server
- subscribes to the topic "inTopic"
- when a message is received, republishes it to "outTopic"
This example shows how to publish messages within the
callback function. The callback function header needs to
be declared before the PubSubClient constructor and the
actual callback defined afterwards.
This ensures the client reference in the callback function
is valid.
*/
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
byte server[] = { 172, 16, 0, 2 };
byte ip[] = { 172, 16, 0, 100 };
// Callback function header
void callback(char* topic, byte* payload, unsigned int length);
EthernetClient ethClient;
PubSubClient client(server, 1883, callback, ethClient);
// Callback function
void callback(char* topic, byte* payload, unsigned int length) {
client.publish("outTopic", payload, length);
}
void setup()
{
Ethernet.begin(mac, ip);
if (client.connect("arduinoClient")) {
client.publish("outTopic","hello world");
client.subscribe("inTopic");
}
}
void loop()
{
client.loop();
}