source: rtos_arduino/trunk/arduino_lib/libraries/pubsubclient-2.6/examples/mqtt_publish_in_callback/mqtt_publish_in_callback.ino@ 209

Last change on this file since 209 was 209, checked in by ertl-honda, 8 years ago

BlueMix用のフィアルを追加

File size: 1.5 KB
Line 
1/*
2 Publishing in the callback
3
4 - connects to an MQTT server
5 - subscribes to the topic "inTopic"
6 - when a message is received, republishes it to "outTopic"
7
8 This example shows how to publish messages within the
9 callback function. The callback function header needs to
10 be declared before the PubSubClient constructor and the
11 actual callback defined afterwards.
12 This ensures the client reference in the callback function
13 is valid.
14
15*/
16
17#include <SPI.h>
18#include <Ethernet.h>
19#include <PubSubClient.h>
20
21// Update these with values suitable for your network.
22byte mac[] = { 0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
23IPAddress ip(172, 16, 0, 100);
24IPAddress server(172, 16, 0, 2);
25
26// Callback function header
27void callback(char* topic, byte* payload, unsigned int length);
28
29EthernetClient ethClient;
30PubSubClient client(server, 1883, callback, ethClient);
31
32// Callback function
33void callback(char* topic, byte* payload, unsigned int length) {
34 // In order to republish this payload, a copy must be made
35 // as the orignal payload buffer will be overwritten whilst
36 // constructing the PUBLISH packet.
37
38 // Allocate the correct amount of memory for the payload copy
39 byte* p = (byte*)malloc(length);
40 // Copy the payload to the new buffer
41 memcpy(p,payload,length);
42 client.publish("outTopic", p, length);
43 // Free the memory
44 free(p);
45}
46
47void setup()
48{
49
50 Ethernet.begin(mac, ip);
51 if (client.connect("arduinoClient")) {
52 client.publish("outTopic","hello world");
53 client.subscribe("inTopic");
54 }
55}
56
57void loop()
58{
59 client.loop();
60}
Note: See TracBrowser for help on using the repository browser.