Coder Social home page Coder Social logo

knolleary / pubsubclient Goto Github PK

View Code? Open in Web Editor NEW
3.7K 209.0 1.5K 313 KB

A client library for the Arduino Ethernet Shield that provides support for MQTT.

Home Page: http://pubsubclient.knolleary.net/

License: MIT License

C++ 87.98% C 1.11% Python 10.35% Makefile 0.57%

pubsubclient's Introduction

Arduino Client for MQTT

This library provides a client for doing simple publish/subscribe messaging with a server that supports MQTT.

Examples

The library comes with a number of example sketches. See File > Examples > PubSubClient within the Arduino application.

Full API documentation is available here: https://pubsubclient.knolleary.net

Limitations

  • It can only publish QoS 0 messages. It can subscribe at QoS 0 or QoS 1.
  • The maximum message size, including header, is 256 bytes by default. This is configurable via MQTT_MAX_PACKET_SIZE in PubSubClient.h or can be changed by calling PubSubClient::setBufferSize(size).
  • The keepalive interval is set to 15 seconds by default. This is configurable via MQTT_KEEPALIVE in PubSubClient.h or can be changed by calling PubSubClient::setKeepAlive(keepAlive).
  • The client uses MQTT 3.1.1 by default. It can be changed to use MQTT 3.1 by changing value of MQTT_VERSION in PubSubClient.h.

Compatible Hardware

The library uses the Arduino Ethernet Client api for interacting with the underlying network hardware. This means it Just Works with a growing number of boards and shields, including:

  • Arduino Ethernet
  • Arduino Ethernet Shield
  • Arduino YUN – use the included YunClient in place of EthernetClient, and be sure to do a Bridge.begin() first
  • Arduino WiFi Shield - if you want to send packets > 90 bytes with this shield, enable the MQTT_MAX_TRANSFER_SIZE define in PubSubClient.h.
  • Sparkfun WiFly Shield – library
  • TI CC3000 WiFi - library
  • Intel Galileo/Edison
  • ESP8266
  • ESP32

The library cannot currently be used with hardware based on the ENC28J60 chip – such as the Nanode or the Nuelectronics Ethernet Shield. For those, there is an alternative library available.

License

This code is released under the MIT License.

pubsubclient's People

Contributors

abderraouf-adjal avatar apicquot avatar brandon2255p avatar czaraugust avatar e-lin avatar edwin-oetelaar avatar elvistheking avatar ennui2342 avatar eykamp avatar folkertvanheusden avatar igrr avatar ivankravets avatar kevinresol avatar knolleary avatar leojz avatar lexszero avatar marcelrv avatar maxim-kukushkin avatar mcollina avatar mrdunk avatar nickdex avatar pauloacmartinez avatar phirephly avatar rotzbua avatar skorokithakis avatar tobyjaffey avatar trygvis avatar turgu1 avatar vicatcu avatar wilhall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pubsubclient's Issues

Library doesn't compile for ESP8266

Hello knolleary,

I'm referring to my pull request on this topic.

I think that its, of course, better to check if PROGMEM is defined, instead of just checking if you are on that one platform, like the ESP8266.

The problem is: It doesn't work. PROGMEM seems to be still defined on an ESP8266. Your library would only compile, if I insert #undef PROGMEM in both the header and cpp-files.

Maybe, you could combine the two?

Thanks, l-sch.

What about Zigbee?

Have you considered support for a Zigbee messaging transport for MQTT? This would be assuming a 6lowpan implementation in the mix (I imagine) - I haven't really done the homework, but can see a MQTT-based BUS (maybe even with Mule) as a very useful application platform, especially if you can connect anything with an arduino and a zigbee radio on it to the bus for events and commands.

Thanks,
Karl Miller

Disconnect condition in Examples

The examples are very simple and basic, no doubt by design, however the example code can lead to a situation where the connection drops and is not handled.

I had a project where the remote sensor that was publishing a value to an MQTT server worked fine on the bench, but at it's remote location, it was failing at seemingly random intervals, but usually within 24 hours of a reset. This morning it failed within 15 minutes of a reset, so I knew something was wrong with the code. The remote location is across a, somewhat unreliable at times, WiFi bridged connection. (yep, need to fix that too... :-) )

As the example code stands, if the Arduino misses a PING packet exchange, it will disconnect. In the example code, this disconnect is permanent. This can happen on unreliable links (WiFi) or if the publisher is unable to communicate with the server for whatever reason (ISP outage). The symptom is that all other code on the Arduino continues to operate normally, with the exception of the MQTT client functionality.

The good news is that the functionality is already in the library, it's just not shown in the examples. Simply check the result of the client.loop() statement in the main loop and act upon it.

FALSE == we're disconnected so it's time to try reconnecting
TRUE == all is good.

In the examples, replace:

client.loop()

with

if(!client.loop()) client.connect("arduinoPublisher");

or, if want to check the client.connect() as well, use something like this:

  if (!client.loop()) {
    Serial.print("Client disconnected...");
    if (client.connect("arduinoPublisher")) {
      Serial.println("reconnected.");
    } else {
      Serial.println("failed.");
    }
  } 

I don't expect an update the library for this, but I did want to document this here on GitHub so that it might be useful to future users of your excellent library. Thanks Nick!!

Large payloads with Arduino Wifi Shield does not work

I ran into the problem that messages I published via PubSubClient using an Arduino Mega and an Arduino Wifi Shield which are large than about 80 octets did not appear at the broker. I found by googling that it is not possible to send more than 90 octets using the Wifi Shield and the related library at once: http://mssystems.emscom.net/helpdesk/knowledgebase.php?article=51
And that exactly what I experienced too: I increased the buffer size one by one and at 90 octets it stopped and the WiFi library lost the connection.

Furthermore I found that the WiFi library and the shield handles a stop() on a fresh client socket somewhat strange: The socket can not be open or will be closed immediately after opening. Since at least in my case I always give a fresh WiFiClient into the PubSubClient I removed the connected() call from the top of the connect method in PubSubClient.cpp.

Since PubSubClient works as it is with the Ethernet Shield I suppose a fix in the WiFi library would be a better idea but I put a workaround into PubSubClient.cpp. Here is my diff against release 1.9.1. Maybe - as long as the WiFi library is not fixed - this fix/workaround should depend on the actual type of Client but this distinction of cases is not included in the patch. Will free to use it if you like.

wn@baikonur:~/Documents/workspace/WiModbusGateway/MQTT$ diff PubSubClient.cpp ~/Downloads/pubsubclient-1.9.1/PubSubClient/PubSubClient.cpp 
42,43c42
< //   if (!connected()) {
<    if (true) {

---
>    if (!connected()) {
217d215
<       // Serial.print("pub len: "); Serial.println(length-5);
219,220d216
<    } else {
<      // Serial.println("connection lost");
290,308c286
< 
< //   Serial.print("write len: "); Serial.println(length+1+llen);
< //   size_t olen = length + 1 + llen;
< //   rc = _client->write(buf+(4-llen),length+1+llen);
< 
<    const size_t SEND_AT_ONCE = 64;
<    size_t remains = length + 1 + llen;
<    // Serial.print("write len: "); Serial.println(remains);
<    const uint8_t *writebuf = buf + (4 - llen);
<    bool result = true;
<    while ((remains > 0) && result) {
<      size_t actuallySendChars = (remains > SEND_AT_ONCE) ? SEND_AT_ONCE : remains;
<      // Serial.print("tbs: "); Serial.println(actuallySendChars);
<      size_t sentChars = _client->write(writebuf, actuallySendChars);
<      result = sentChars == actuallySendChars;
<      remains -= sentChars;
<      writebuf += sentChars;
<    }
< 

---
>    rc = _client->write(buf+(4-llen),length+1+llen);
311,312c289
< //   return (rc == 1+llen+length);
<    return result;

---
>    return (rc == 1+llen+length);
357,362c334
<    //Serial.print("rc: "); Serial.println(rc);
<    if (!rc) {
<      //Serial.println("would stop");
<      _client->stop();
<      // while (true);
<    }

---
>    if (!rc) _client->stop();
wn@baikonur:~/Documents/workspace/WiModbusGateway/MQTT$ 

Issue on Intel Galileo board

Hi Nick,
I have never used your library on Arduino but today I'm using it with an Intel Galileo board !
I have a question for you ...
The Arduino Ethernet and EthernetClient classes has some methods that receive in input an IPAddress instance but in your implementation you want a byte array for ip address.
On Intel Galileo board it seems not working : Ethernet.begin fails if I use a byte array for ip address but it works fine if I use IPAddress instance class. Do you have any idea ?

However, The library works fine but on Intel Galileo I removed "pgm_read_byte_near" in the publish method because we have a Quark x86 CPU and not an Atmel AVR.
I have to test better in the next few days !

Paolo.

mqtt_auth does not work

I am working on an Arduino UNO project which is required an authorized password based on OAuth 1.0 to connects to the cloud via MQTT. This is alike [Authorizing a request to Twitter API][1], and [Creating a signature][2]. The whole process of creating a signature, here I said, password, requires algorithms like encodeURL, base64encode, and hmac-sha1. After processing, there is a base64-encoded, HMAC-SHA1 signature for the password.

However, I filled(even tried hard code) the generated password and username to the function client.connect("arduinoClient", "username", "password") in the example mqtt_auth, the Arduino device cannot connect to the cloud.

I've tried mqtt_basic example and the device connects to test.mosquitto.org very well. I've also tried to write a JAVA program that using my username and generated password to connect to the cloud via MQTT, and the JAVA program connects to the cloud successfully. I am pretty sure the username and password that I filled into the example mqtt_auth are right.

The MQTT broker of the cloud is implemented based on RabbitMQ.
I am not sure if there is an obvious mistake I've made here?

[1] https://dev.twitter.com/oauth/overview/authorizing-requests
[2] https://dev.twitter.com/oauth/overview/creating-signatures

Connection Issue

I'm using the latest git pull of this library, with the only modification being that I changed instances of Ethernet to WiFly. I also tried it with https://github.com/dpslwk/pubsubclient

It connects successfully to my mosquitto server but then it starts having issues and cannot publish or subscribe:
Jul 25 22:02:46 localhost mosquitto[4096]: New connection from 50.74.0.42.
Jul 25 22:02:46 localhost mosquitto[4096]: New client connected from 50.74.0.42 as twiliopower.
Jul 25 22:02:46 localhost mosquitto[4096]: Sending CONNACK to twiliopower (0)
Jul 25 22:02:46 localhost mosquitto[4096]: Socket read error on client twiliopower, disconnecting.
Jul 25 22:02:55 localhost mosquitto[4096]: New connection from 50.74.0.42.
Jul 25 22:02:56 localhost mosquitto[4096]: Socket read error on client (null), disconnecting.
Jul 25 22:03:15 localhost mosquitto[4096]: New connection from 50.74.0.42.
Jul 25 22:03:16 localhost mosquitto[4096]: Socket read error on client (null), disconnecting.

Looks very similar to this bug: https://bugs.launchpad.net/mosquitto/+bug/528663

UIPEthernet with pubsubclient

Just like to know whether there is any support or way of using UIPEthernet instead of the standard Ethernet libraries as I am using a ENC28J60?

Add support for QOS1 sending

For some use cases such as a state transition, it is required to make sure message was delivered. I understand your concerns about local arduino memory, but how about an option?

subscribe does not receive any data

Hello, I am working with a local mosquitto instance and also with test.mosquitto.org, in both I can publish and it works, but I cannot get info when subscribing.

I publish to sensor/smoke topic, but when I want to subscribe to sensor/smoke topic it nevers receives anything. I tested with mosquitto_sub and paho-mqtt to check if subscriptions were right, and they receive.

// #include <aJSON.h>
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

byte mac[] = {0x90, 0xa2, 0xda, 0x0d, 0x2e, 0x8a};
byte mqttServer[] = {192,168,0,1};
unsigned int port = 1883;
byte ip[] = {10,42,0,69};


void callback(char* topic, byte* payload, unsigned int length) {
  // Use if subscription is done ;)
  Serial.println("GOT");
  Serial.println(topic);

}
EthernetClient ethClient;
// PubSubClient mqttClient(mqttServer, 1883, callback, ethClient);
PubSubClient mqttClient("test.mosquitto.org", 1883, callback, ethClient);

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip);
  delay(1000);

  Serial.println("[+] Network connection established.");

  if (mqttClient.connect("mqtt_1")) {
    Serial.println("  [+] MQTT connection established");
    Serial.println("Subscribing to: sensor/smoke");
    mqttClient.subscribe("sensor/smoke");
  } else {
    Serial.println("  [-] Cannot connect to MQTT server.");
    while(true);
  }
}
char buffer[3];
byte rnd;

void loop() {
  rnd = random(5, 20);
  sprintf(buffer, "%d", rnd);

  Serial.println("publishing:");
  Serial.println(rnd);
  mqttClient.publish("sensor/smoke", buffer);

  delay(3000);
}

Last Testament Published On Connect

Hey Hey.

Not sure if this has to do with your lib, but when connecting with a will to ActiveMQ 5.11, the last testament gets published by the broker upon connection.

/c

Using ESP8266 with an Arduino

Hello. I am trying to use the PubSubClient library but instead of using an Ethernet shield, I would like use an ESP8266 module. In the readme, it is stated to be compatible. Which library should be used for the ESP8266?

The sample found here: https://gist.github.com/igrr/7f7e7973366fc01d6393 seems to address that, but the library used (ESP8266WiFi found here: https://github.com/sandeepmistry/esp8266-Arduino/tree/master/esp8266com/esp8266/libraries/ESP8266WiFi) seems to be written for the ESP8266 as a standalone. The other library (ESP8266wifi found here: https://github.com/ekstrand/ESP8266wifi) is not compatible with the original Ethernet library, so it doesn't work.

publish fails when including retained parameter

Hi Nick,

Just started using your MQTT library with the ESP8266 and the Arduino IDE.

All works well when using the short form of publish, e.g.:
client.publish(topic, myIP);
where the 2 variables are both char (string arrays).

However, when I try to use the extended form so that I can include the retained parameter:
client.publish(topic, msg, 50, 1);
It fails with:

\sketches\libraries\pubsubclient\src/PubSubClient.h:115:12: error:   initializing argument 2 of 'boolean PubSubClient::publish(const char*, const uint8_t*, unsigned int, boolean)' [-fpermissive]
    boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
            ^
invalid conversion from 'char*' to 'const uint8_t* {aka const unsigned char*}' [-fpermissive]

So it appears the parameter 2 is defined differently? My C skills are totally naff I'm afraid so I can't work out whether this is deliberate (and if so why). If it is, I'm uncertain how to convert from the string array to the uint8_t format.

I'm also not sure why I need the length parameter just to set the retained flag?

Thanks for the library though, without it I'd still be struggling along with the NODEMCU firmware and LUA!

Question: How to change the port settings dynamically

Is there a way to set the port dynamically, meaning not directly at the initialization.
I am reading the server and the port int from eeprom, however then I'm no longer able to set the port settings. For the mqtt server it is still possible to change this later, but for the port not.

Is there another way other then introducing something like
void PubSubClient::setPort(uint16_t port) {
this->port = port;
}

Max topic length

Hi.
I've been playing around with MQTT on the Arduino. After figuring out the basics, I can't get subscriptions to long topics to work.
Is there a limit to the max. topic length implemented?
Subscriptions to topics with less then 23 characters seem to work fine.
Thanks in advance
David

Can I use pubsubclient at wizfi250(speedstudio) or Yun Shield?

I bought wizfi250(speedstudio). I was going to use the pubsubclient, but the fi250(libarary) had not client.h. In this situation can I use the pubsubclient at wizifi250?
And I am going to buy Yun Shield
(http://www.aliexpress.com/item/Linux-WiFi-Ethernet-USB-All-in-one-Shield-for-Arduino-Leonardo-UNO-Mega2560-Duemilanove/2011318517.html?s=p).
In this device, can I use pubsubclient? pls. help me.

(If you can't know what I say, give me the massage. My english is very poor.)

Character limit on payload

We are using a Arduino Uno board to communicate to a server via a MQTT message broker.
The board is connected to several sensors we are hoping to send multiple readings in one request.
Our request is being sent in JSON format and it's about 580 characters.
Unfortunately we are finding the device crashes when it tries to receive over 106 characters.
And simply cuts out most of the payload when we publish. We have increased the max packet size in the header file (no luck).

We are using the following client library to talk to the broker.

http://knolleary.net/arduino-client-for-mqtt/

I know that MQTT does not have a character limit this small.
Could it be that the library is setting a character limit?

Thanks in advance.

RF24(Network) library?

MQTT and this library seems to be perfect for sensor nodes based on Arduino Nano with RF24 nodes.
I'm currently using own code for this library: https://github.com/maniacbug/RF24Network but I'd like to switch it to MQTT and Raspberry as a broker.

Is it somehow possible to optimize 'messages' in pubsubclient, so they can (somehow) fit in the 24bytes maximum payload of library? (http://stackoverflow.com/questions/18170553/sending-a-char-array-using-rf24network-on-arduino - not mine thread tho)
The setup I'd like to use in my house looks like:
Raspberry (broker) - Arduino MEGA (with: ethernet and rf24 distributing packets) to Arduino NANO (nodes).
I'd like to get and send values of sensors/switches from "nodes" to Mega and report it to RPI.

type mismatch in write method

I increased MQTT_MAX_PACKET_SIZE to 1024 and got issues with large payloads. I found:

boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
   uint8_t lenBuf[4];
   uint8_t llen = 0;
   uint8_t digit;
   uint8_t pos = 0;
   uint8_t rc;
   uint8_t len = length;

lengthof type uint16_t is assigned to lenof type uint8_t. Is this a bug or a feature?
Changing the type of len to uint16_t solved at least forehand my problem. Or have I got a new problem now I haven't discovered so far?

Thanks and Cheers, Wolfgang

PubSubClient client(server, 1883, callback, ethClient); causes a debug error

Hi, when I debug any of the examples, the line "PubSubClient client(server, 1883, callback, ethClient);" gets highlighted and the error is as follows, any ideas?

Arduino: 1.5.4 (Windows 7), Board: "Arduino Yún"

mqtt_publish_in_callback:30: error: 'PubSubClient' does not name a type
mqtt_publish_in_callback.ino: In function 'void callback(char_, byte_, unsigned int)':
mqtt_publish_in_callback:42: error: 'client' was not declared in this scope
mqtt_publish_in_callback.ino: In function 'void setup()':
mqtt_publish_in_callback:51: error: 'client' was not declared in this scope
mqtt_publish_in_callback.ino: In function 'void loop()':
mqtt_publish_in_callback:59: error: 'client' was not declared in this scope

Inbound message size limitation on 1.91

The readpacket encodes the payload size into a buffer, but downstream code assumes that this is a single byte. I've changed the code to allow the payload size to be a uint64_t, as per the MQTT spec, and removed it from the buffer altogether.

Nick - I'm new to this process - should I pull the source from Github, add my changes, or do you want to look at the changes ?

When Arduino Publishes, Other mqtt clients keeps disconnecting

I have tried using couple of available mosquito brokers & I am getting the following problem:

Whenever Arduino publishes on some topic, my mqtt.io client get disconnected & hence I am not able to see the message published by Arduino. I have tried couple of available sandboxes based on mosquito broker but same problem.

Please help!!

Request: set hostname in connect method rather than constructor?

I've written some code which stores the DNS name in EEPROM, and then copies it from the EEPROM to RAM at runtime (so I don't have to recompile to change the hostname, just reflash the EEPROM). However the PubSubClient expects the hostname in the constructor, and I don't think (correct me if I am wrong) that arduino supports dynamic instantiation using new()?

Currently passing the constructor a pointer to the array that I fill in later from the EEPROM works, but only because the class just maintains a pointer to the array I've passed it; if it happened to make a copy of it internally my code wouldn't work. And relying on the internal implementation like this is horribly inelegant :)

Would it be possible to add a constructor variant which doesn't take the hostname and port as arguments, and then either provide a variant of the connect() method which takes those arguments, or alternatively a separate method to set them?

(I also store the ClientID in the EEPROM, but that is supplied to the connect() method and so doesn't suffer from the same issue).

Cheers

David

Do subscriptions expire?

Hi, I plug in the Arduino and everything works fine, it connects, subscribes (to Xively), executes the callback function, but after a few hours (of inactivity) it just dies and does not seem to execute the callback. I am subscribing using the standard: client.subscribe("/v2/feeds/FEEDID.csv"). Any idea?

callback not invoked when payload contains space(s)

I am sending MQTT messages via the paho python lib. The payload contains spaces (JSON string). When I send a string like "{"id": 4711}", the callback function is not invoked although the MQTT message is properly sent to the broker.

I have to remove the spaces in the payload (like: json.dumps(myDataStructure, separators=(',', ':'))) ) in order to invoke the callback function on the Arduino.

Connection timeout

Hi, Great work on the library but would it be possible to introduce a connection timeout in the connect function? It currently seems to take about 30(?) or so seconds to timeout the connection and since this is a blocking function it holds up any other code unless interrupts are in use (which i can't use in my current project).

mqtt publish in callback example not working with Mosquitto 3.1

Hi Nicholas.

Thank you for your work on this.

I'm using the pubsubclient 'mqtt publish in callback' example with Mosquitto 3.1 on a genuine Arduino Uno with Ethernet Shield.

I use IBM WMQTT client to publish to the inTopic for the Arduino to receive.

WMQTT is also subscribed to outTopic to check what Arduino publishes.

The Arduino does pick up messages from inTopic, but corrupts them before publishing them to outTopic.

eg This history listing from WMQTT when I publish a test message:

--> PUBLISH sent, TOPIC:inTopic, QoS:0, Retained:false
DATA:this is a test
--> PUBLISH received, TOPIC:outTopic, QoS:0, Retained:false
DATA:opicopicopicop

The published message is the same length as the received one, but always contains 'opic' repeated as shown.

I don't understand this well enough to debug it myself, but obviously it looks like part of the string 'Topic' is being read and being repeatedly inserted in the output string, overwriting the real message.

Is this something I'm doing wrong?

Does the example still work for you?

Cheers.

Incorrect output, length error when using a String object

I've got these objects defined in the prolog for my code:

/* DCF 77 signal and MQTT */

define DEBUG

String MQTTbuffer;
char MQTTtext[400];
boolean DCF77signal[62];

I then build the string to send to Mosquitto using this:

void displayTime() {

MQTTbuffer = "** ";
for (i = 0; i < 63; i++) {
MQTTbuffer += DCF77signal[i];
}
MQTTbuffer += " **\r\n";
MQTTbuffer +="TZ:";
MQTTbuffer +=BCDtoDecimal(17,2);
MQTTbuffer +="\tmm:";
MQTTbuffer +=BCDtoDecimal(21,7);
MQTTbuffer +="\thh:";
MQTTbuffer +=BCDtoDecimal(29,6);
MQTTbuffer +="\tday:";
MQTTbuffer +=BCDtoDecimal(36,6);
MQTTbuffer +="\tdw:";
MQTTbuffer +=BCDtoDecimal(42,3);
MQTTbuffer +="\tmth:";
MQTTbuffer +=BCDtoDecimal(45,5);
MQTTbuffer +="\tyy:";
MQTTbuffer +=BCDtoDecimal(50,8);
MQTTbuffer +="\tParity:";
MQTTbuffer +=BCDtoDecimal(60,3);
MQTTbuffer.toCharArray(MQTTtext,400);

if DEBUG

for (int i = 0; i < 400; i ++) {
Serial.print(MQTTtext[i],HEX);
}

endif

if (client.connect("arduinoClient")) {
client.publish("arduino/DCF77",MQTTtext);
client.disconnect();
}
if (client.connect("arduinoClient")) {
client.publish("arduino/DCF77","DONE");
client.disconnect();
}
}

That gets the following printed on the Serial console:

2A2A2030313030313130303031313130313030303130313031313030303131313030303030
3130303031303030303131313030303031303031303030303030303130202A2ADA545A3A
3196D6D3A3633968683A323096461793A34964773A3696D74683A31979793A399506172
6974793A32
000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

So as far as I can tell the char array MQTTtext has been built correctly (until someone proves otherwise).

But the send to Mosquitto is rejected with a length error.

Looking at a tcpdump (with Wireshark) I get the following:

CONNECT
00000000 10 .
00000001 1b .
00000002 00 06 4d 51 49 73 64 70 03 02 00 0f 00 0d 61 72 ..MQIsdp ......ar
00000012 64 75 69 6e 6f 43 6c 69 65 6e 74 duinoCli ent

CONNACK
00000000 20 02 00 00 ...

PUBLISH
0000001D 30 0
0000001E 83 .
0000001F 00 0d 61 72 64 75 69 6e 6f 2f 44 43 46 37 37 2a ..arduin o/DCF77*
0000002F 2a 20 30 30 30 30 30 30 30 30 30 30 30 30 30 30 * 000000 00000000
0000003F 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 00000000 00000000
0000004F 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 00000000 00000000
0000005F 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 30 00000000 00000000
0000006F 30 20 2a 2a 0d 0a 54 5a 3a 30 09 6d 6d 3a 30 09 0 **..TZ :0.mm:0.
0000007F 68 68 3a 30 09 64 61 79 3a 30 09 64 77 3a 30 09 hh:0.day :0.dw:0.
0000008F 6d 74 68 3a 30 09 79 79 3a 30 09 50 61 72 69 74 mth:0.yy :0.Parit
0000009F 79 3a 30 y:0

DISCONNECT
000000A2 e0 .
000000A3 00 .

That x'E000' on the tail end of TCP stream is from the DISCONNECT, if I remove the client.disconnect() call it makes no difference. I still don't get my message delivered.

Use a variable in client.publish

Hi Nick ... great library! I have a Q.

How would I publish the value of a variable in e.g. client.publish("MIDJ/Temp","temperature");

I want to publish the value of the variable "temperature" not the string "temperature" if you know what I mean?

Thanks a stack!

void loop(){
float temperature = getTemp();
Serial.println(temperature);
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("Temp: ");
lcd.print(temperature);
lcd.print((char)223);
client.publish("MIDJ/Temp","temperature");
delay(5000); //read temp every 5 seconds
client.loop();

Allow class-based callback function

Enable the callback function to be a class member. The following is not currently possible, but desirable:

class MyMqttWrapperClass {
   byte server[] = { 10, 1, 1, 1 };
   PubSubClient *mqttclient;
   void mycallback(char* topic, byte* payload, unsigned int length) {
      //do something here
   }
   void init() {
      mqttlclient=new PubSubClient(server, 1883, this->mycallback, ethClient);
   }
}

Rapid Messages will Crash the Client?

Hi! First of all, kudos on your great work.

I've been using your library to subscribe to an MQTT topic, and then relay the message to another Arduino "field unit" via RF links using RadioHead. Here's the sketch if you'd like to take look at it:

https://github.com/kerti/catleya-arduino/blob/master/baseStation/baseStation.ino

I use openHAB to publish messages to MQTT based on what switch I press on my handset. So, all goes well when I test one switch and just leave it alone. But when I mash on the controls and make openHAB spit out a bunch of messages rapidly, eventually the Arduino just goes silent, and I presume it's crashed.

I don't know what happened, maybe you could check it out and see if I crashed the client?

pubsubclient dependencies

Hi,
When we tried to compile pubsubclient code, we noticed it depends on WMConstants.h and client.h. Can you tell us which libraries we need to download to compile pubsubclient source code?

Thanks,

Venky

Odd behaviour when publishing to multiple topics

Hi again. I'm hoping this is just a matter of my code being wrong but I have gone over it and over it and i can not see where the problem might be so i'm wondering if there might be something astray in the library.

I have a shield that has 6 buttons and 6 leds. Each press of a button toggles the corresponding led and publishes this to 'led/[led number]/[0|1]' This is working fine as much that i can press any button and the corresponding led comes on and the value is published UNTIL i have more than one in the ON state and then the library seems to think it is no longer connected to the broker and goes into a connect loop yet the broker does not seem to show the connection was dropped, nor does it see the attempts to reconnect.

The value of the second led does get published.

This is the cut down version of the sketch i am using to replicate the problem - Can you see any reason for this behavior?


# include 
# include 
# include 

// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network.
// gateway and subnet are optional:
byte mac[] = { 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 };
IPAddress ip;
IPAddress MQTT_Server;
byte server[] = { 192, 168, 0, 1 };

// constants won't change. They're used here to 
// set pin numbers:
int buttonPin[] = {4, 5, 6, 7, 8, 9};     // the number of the pushbutton pin
int ledPin[] =  {14, 15, 16, 17, 18, 19};      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status
byte ledState[] = {0,0,0,0,0,0};         // variable for storing the led state

EthernetClient ethClient;
PubSubClient MQTTClient(server, 1883, callback, ethClient);

long previousMillis = 0;     // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 500;           // interval at which to blink (milliseconds)

void setup() {
  for( byte i = 0; i < 6; i++) {
  // initialize the LED pin as an output:
  pinMode(ledPin[i], OUTPUT);  
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin[i], INPUT);  
  // Turn it off
  digitalWrite(ledPin[i], ledState[i]); 
  }

  // open the serial port
  Serial.begin(9600);

  digitalWrite(13, HIGH);  
  // start the Ethernet connection:
  delay(500);
  digitalWrite(13, LOW);  

  Serial.println("Trying to get an IP address using DHCP");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    return;
  } 

  char startTime[40] = "";

  char s1[20];
  itoa(millis(), s1, 10);

  strcat(startTime, "started ");
  strcat(startTime, s1);

  MQTTClient.publish("foo", startTime);

  digitalWrite(13, HIGH);  
}

void loop() {

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    previousMillis = currentMillis;

```
for(  int i = 0; i < 6; i++) {
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin[i]);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {  
    // turn LED on: 
    if (ledState[i] == HIGH) {   
      ledState[i] = LOW;
    } 
    else {
      ledState[i] = HIGH;
    }
    digitalWrite(ledPin[i], ledState[i]);
    publishLedState(i, ledState[i]);
    }
}
```

  }
  mqttConnect(); 
  MQTTClient.loop();
}

void publishLedState(int ledNo, char ledToState) {
  char s[10];
  char t[1];
  itoa(ledToState, s, 10);
  itoa(ledNo, t, 10);
  char publishString[6] = "led/";
  publishString[4] = t[0];
  Serial.print(publishString);
  Serial.print("/");
  Serial.println(s);
  MQTTClient.publish(publishString, s);
}

void mqttConnect() {
  if (!MQTTClient.connected()) {
    Serial.println("Connecting to broker");
    if (MQTTClient.connect("arduino")){
    }else{
      Serial.println("Failed to connect!");
    }
  }
}

void callback(char\* topic, byte\* payload,unsigned int length) {
  Serial.print("Received topic update: ");
  Serial.println(topic);
  int i = topic[4];
  int newState = atoi((char \* ) payload);
  byte rv;
  Serial.println(newState);
  if (newState > 0) {
    rv = HIGH;
  } else {
    rv = LOW;
  }
  digitalWrite(ledPin[i], rv);
}

Connections don't live past the Keepalive time

It seems that with the Jan 26 change on the PubSubClient.cpp file, the client completely halts when it hits the configured Keepalive time. The arduino actually stops executing code added to the Loop().

Going back to the previous commit on that file, everything seems to work fine.

5 sec delay in the loop() function

Hello,
I'm using this great library on Intel Galileo board with some little changes as reported in another issue.
I see that there is a 5 sec delay inside client.loop() function when the client doesn't receive any data. Why ?
In this way if I use client.loop() as first statement in the loop() sketch function, the subsequent instruction are always executed with a 5 sec delay.

Paolo.

doesn't seem to work with 1.0 beta4

when compiling a sketch I get the following errors. My C++-fu is insufficient to figure this one out :)

Cheers,

David

In file included from MQTTBridge2.cpp:26:
/home/davidm/sketchbook/libraries/PubSubClient/PubSubClient.h:36: error: cannot declare field ‘PubSubClient::client’ to be of abstract type ‘Client’
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:7: note: because the following virtual functions are pure within ‘Client’:
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:12: note: virtual size_t Client::write(uint8_t)
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:13: note: virtual size_t Client::write(const uint8_t
, size_t)
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:14: note: virtual int Client::available()
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:15: note: virtual int Client::read()
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:17: note: virtual int Client::peek()
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:18: note: virtual void Client::flush()
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:10: note: virtual int Client::connect(IPAddress, uint16_t)
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:11: note: virtual int Client::connect(const char_, uint16_t)
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:16: note: virtual int Client::read(uint8_t*, size_t)
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:19: note: virtual void Client::stop()
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:20: note: virtual uint8_t Client::connected()
/u5/home/davidm/arduino-1.0-beta4/hardware/arduino/cores/arduino/Client.h:21: note: virtual Client::operator bool()

Problems with subscribe.

hello, I am having some problems with the subscribe method, it doesn't trigger the callback when i send messages to that topic, the basic code does the publish correctly, but the subscribe has that problem, am I doing something wrong? I am using arduino 1.0.5 with mosquitto 1.1.2.

thanks

Cannot get Arduino to connect to Raspberry Pi MQTT broker

I am having a problem connecting my Arduino to a Raspberry Pi 2 MQTT broker using the MQTTbasic.ino example. I have changed the MAC address to that on my Arduino Ethernet Shield, input an IP address that is consistent with what the shield has been assigned from my router (192.168.1.67) and changed the server address to that of my Pi2 (192.168.1.87). The serial monitor just says "attempting MQTT connection.... failed rc=-4 try again in 5 seconds" and sticks in an infinite loop. I have verified that my MQTT broker works, as I can connect to it on my PC and send messages using M2MqttSpy via port 1883. I also know that my Arduino system is functional because I can load the example Ethernet server and connect to it using my web browser on port 80.

Please help, as I am at my wits end here. I am trying to construct the Uber Home Automation system with OpenHab, and the MQTT client sketch there didn't connect either, so I tried to diagnose the problem with a basic sketch here and have the same issue.

Many thanks,

-Mark

Update mqtt_basic to include Serial debugging

mqtt_basic is a simple sanity check sketch. Pretty much every time I use it to help debug something, I end up added Serial debug statements. It would probably be helpful to have the default example sketch have them in out of the box.

Hang using arduino nano with UIP driver

Hello I am using pubsubclient with arduino nano and UIP driver for ENC28J60 ethernet https://github.com/ntruchsess/arduino_uip. But I have notice that sometimes it will publish data and sometimes it does not. If i put this PubSubClient client(server, 1883, callback, ethClient); in my code sometimes the device get an IP and sometimes does not. Have any body here tried used this in arduino NANO and ENC28J60?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.