Compare commits
55 Commits
v2.1
...
revert-500
Author | SHA1 | Date | |
---|---|---|---|
3637cbec69 | |||
b1bdbb7aaf | |||
539838822c | |||
b5f90b679b | |||
4ecd32ec08 | |||
7517de7974 | |||
8154cbc09c | |||
0e8e3123cf | |||
9eff4b3308 | |||
a1cfd5af56 | |||
0e2d6c322b | |||
b2f3a6d2ec | |||
0c2d12d8b0 | |||
c87c9a47b3 | |||
3b3a8da8d2 | |||
54be6e87db | |||
f029640ee6 | |||
bb101c58e8 | |||
dddfffbe0c | |||
bef5814858 | |||
f46d0011ee | |||
10925659ef | |||
4c8ce14dad | |||
df4122466c | |||
d724864095 | |||
33170273a9 | |||
35ead348e3 | |||
341661671b | |||
4739ca0802 | |||
36bb1ffa6a | |||
83b69a766e | |||
baeb59e263 | |||
67eba6dad4 | |||
98a9c296f6 | |||
68400b7b6c | |||
21b75a2c4a | |||
830f34c7d0 | |||
0bb4efcea5 | |||
31521085ea | |||
8a1d7fb620 | |||
803f54b0bd | |||
6f97ea04f2 | |||
6bb06187b7 | |||
efebd2e5e4 | |||
5cdadf43da | |||
2f97e4a558 | |||
15a0e41c81 | |||
aa9afc7b44 | |||
461cbdb6e8 | |||
47a37a4663 | |||
efcf6dbf1e | |||
d5c13d578e | |||
b6f2cb29bc | |||
c1d327cac6 | |||
5ace47bc93 |
@ -1,3 +1,14 @@
|
|||||||
|
2.4
|
||||||
|
* Add MQTT_SOCKET_TIMEOUT to prevent it blocking indefinitely
|
||||||
|
whilst waiting for inbound data
|
||||||
|
* Fixed return code when publishing >256 bytes
|
||||||
|
|
||||||
|
2.3
|
||||||
|
* Add publish(topic,payload,retained) function
|
||||||
|
|
||||||
|
2.2
|
||||||
|
* Change code layout to match Arduino Library reqs
|
||||||
|
|
||||||
2.1
|
2.1
|
||||||
* Add MAX_TRANSFER_SIZE def to chunk messages if needed
|
* Add MAX_TRANSFER_SIZE def to chunk messages if needed
|
||||||
* Reject topic/payloads that exceed MQTT_MAX_PACKET_SIZE
|
* Reject topic/payloads that exceed MQTT_MAX_PACKET_SIZE
|
@ -8,7 +8,7 @@ a server that supports MQTT.
|
|||||||
The library comes with a number of example sketches. See File > Examples > PubSubClient
|
The library comes with a number of example sketches. See File > Examples > PubSubClient
|
||||||
within the Arduino application.
|
within the Arduino application.
|
||||||
|
|
||||||
Full API documentation is available here: http://knolleary.github.io/pubsubclient/
|
Full API documentation is available here: https://pubsubclient.knolleary.net
|
||||||
|
|
||||||
## Limitations
|
## Limitations
|
||||||
|
|
||||||
@ -33,7 +33,8 @@ boards and shields, including:
|
|||||||
be sure to do a `Bridge.begin()` first
|
be sure to do a `Bridge.begin()` first
|
||||||
- Arduino WiFi Shield - if you want to send packets > 90 bytes with this shield,
|
- Arduino WiFi Shield - if you want to send packets > 90 bytes with this shield,
|
||||||
enable the `MQTT_MAX_TRANSFER_SIZE` define in `PubSubClient.h`.
|
enable the `MQTT_MAX_TRANSFER_SIZE` define in `PubSubClient.h`.
|
||||||
- Sparkfun WiFly Shield – when used with [this library](https://github.com/dpslwk/WiFly)
|
- Sparkfun WiFly Shield – [library](https://github.com/dpslwk/WiFly)
|
||||||
|
- TI CC3000 WiFi - [library](https://github.com/sparkfun/SFE_CC3000_Library)
|
||||||
- Intel Galileo/Edison
|
- Intel Galileo/Edison
|
||||||
- ESP8266
|
- ESP8266
|
||||||
|
|
||||||
|
132
examples/mqtt_esp8266/mqtt_esp8266.ino
Normal file
132
examples/mqtt_esp8266/mqtt_esp8266.ino
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
/*
|
||||||
|
Basic ESP8266 MQTT example
|
||||||
|
|
||||||
|
This sketch demonstrates the capabilities of the pubsub library in combination
|
||||||
|
with the ESP8266 board/library.
|
||||||
|
|
||||||
|
It connects to an MQTT server then:
|
||||||
|
- publishes "hello world" to the topic "outTopic" every two seconds
|
||||||
|
- subscribes to the topic "inTopic", printing out any messages
|
||||||
|
it receives. NB - it assumes the received payloads are strings not binary
|
||||||
|
- If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
|
||||||
|
else switch it off
|
||||||
|
|
||||||
|
It will reconnect to the server if the connection is lost using a blocking
|
||||||
|
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
|
||||||
|
achieve the same result without blocking the main loop.
|
||||||
|
|
||||||
|
To install the ESP8266 board, (using Arduino 1.6.4+):
|
||||||
|
- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
|
||||||
|
http://arduino.esp8266.com/stable/package_esp8266com_index.json
|
||||||
|
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
|
||||||
|
- Select your ESP8266 in "Tools -> Board"
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
#include <PubSubClient.h>
|
||||||
|
|
||||||
|
// Update these with values suitable for your network.
|
||||||
|
|
||||||
|
const char* ssid = "........";
|
||||||
|
const char* password = "........";
|
||||||
|
const char* mqtt_server = "broker.mqtt-dashboard.com";
|
||||||
|
|
||||||
|
WiFiClient espClient;
|
||||||
|
PubSubClient client(espClient);
|
||||||
|
long lastMsg = 0;
|
||||||
|
char msg[50];
|
||||||
|
int value = 0;
|
||||||
|
|
||||||
|
void setup_wifi() {
|
||||||
|
|
||||||
|
delay(10);
|
||||||
|
// We start by connecting to a WiFi network
|
||||||
|
Serial.println();
|
||||||
|
Serial.print("Connecting to ");
|
||||||
|
Serial.println(ssid);
|
||||||
|
|
||||||
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
|
delay(500);
|
||||||
|
Serial.print(".");
|
||||||
|
}
|
||||||
|
|
||||||
|
randomSeed(micros());
|
||||||
|
|
||||||
|
Serial.println("");
|
||||||
|
Serial.println("WiFi connected");
|
||||||
|
Serial.println("IP address: ");
|
||||||
|
Serial.println(WiFi.localIP());
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
// Switch on the LED if an 1 was received as first character
|
||||||
|
if ((char)payload[0] == '1') {
|
||||||
|
digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level
|
||||||
|
// but actually the LED is on; this is because
|
||||||
|
// it is active low on the ESP-01)
|
||||||
|
} else {
|
||||||
|
digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
void reconnect() {
|
||||||
|
// Loop until we're reconnected
|
||||||
|
while (!client.connected()) {
|
||||||
|
Serial.print("Attempting MQTT connection...");
|
||||||
|
// Create a random client ID
|
||||||
|
String clientId = "ESP8266Client-";
|
||||||
|
clientId += String(random(0xffff), HEX);
|
||||||
|
// Attempt to connect
|
||||||
|
if (client.connect(clientId.c_str())) {
|
||||||
|
Serial.println("connected");
|
||||||
|
// Once connected, publish an announcement...
|
||||||
|
client.publish("outTopic", "hello world");
|
||||||
|
// ... and resubscribe
|
||||||
|
client.subscribe("inTopic");
|
||||||
|
} else {
|
||||||
|
Serial.print("failed, rc=");
|
||||||
|
Serial.print(client.state());
|
||||||
|
Serial.println(" try again in 5 seconds");
|
||||||
|
// Wait 5 seconds before retrying
|
||||||
|
delay(5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
|
||||||
|
Serial.begin(115200);
|
||||||
|
setup_wifi();
|
||||||
|
client.setServer(mqtt_server, 1883);
|
||||||
|
client.setCallback(callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
|
||||||
|
if (!client.connected()) {
|
||||||
|
reconnect();
|
||||||
|
}
|
||||||
|
client.loop();
|
||||||
|
|
||||||
|
long now = millis();
|
||||||
|
if (now - lastMsg > 2000) {
|
||||||
|
lastMsg = now;
|
||||||
|
++value;
|
||||||
|
snprintf (msg, 50, "hello world #%ld", value);
|
||||||
|
Serial.print("Publish message: ");
|
||||||
|
Serial.println(msg);
|
||||||
|
client.publish("outTopic", msg);
|
||||||
|
}
|
||||||
|
}
|
179
examples/mqtt_large_message/mqtt_large_message.ino
Normal file
179
examples/mqtt_large_message/mqtt_large_message.ino
Normal file
@ -0,0 +1,179 @@
|
|||||||
|
/*
|
||||||
|
Long message ESP8266 MQTT example
|
||||||
|
|
||||||
|
This sketch demonstrates sending arbitrarily large messages in combination
|
||||||
|
with the ESP8266 board/library.
|
||||||
|
|
||||||
|
It connects to an MQTT server then:
|
||||||
|
- publishes "hello world" to the topic "outTopic"
|
||||||
|
- subscribes to the topic "greenBottles/#", printing out any messages
|
||||||
|
it receives. NB - it assumes the received payloads are strings not binary
|
||||||
|
- If the sub-topic is a number, it publishes a "greenBottles/lyrics" message
|
||||||
|
with a payload consisting of the lyrics to "10 green bottles", replacing
|
||||||
|
10 with the number given in the sub-topic.
|
||||||
|
|
||||||
|
It will reconnect to the server if the connection is lost using a blocking
|
||||||
|
reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
|
||||||
|
achieve the same result without blocking the main loop.
|
||||||
|
|
||||||
|
To install the ESP8266 board, (using Arduino 1.6.4+):
|
||||||
|
- Add the following 3rd party board manager under "File -> Preferences -> Additional Boards Manager URLs":
|
||||||
|
http://arduino.esp8266.com/stable/package_esp8266com_index.json
|
||||||
|
- Open the "Tools -> Board -> Board Manager" and click install for the ESP8266"
|
||||||
|
- Select your ESP8266 in "Tools -> Board"
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include <ESP8266WiFi.h>
|
||||||
|
#include <PubSubClient.h>
|
||||||
|
|
||||||
|
// Update these with values suitable for your network.
|
||||||
|
|
||||||
|
const char* ssid = "........";
|
||||||
|
const char* password = "........";
|
||||||
|
const char* mqtt_server = "broker.mqtt-dashboard.com";
|
||||||
|
|
||||||
|
WiFiClient espClient;
|
||||||
|
PubSubClient client(espClient);
|
||||||
|
long lastMsg = 0;
|
||||||
|
char msg[50];
|
||||||
|
int value = 0;
|
||||||
|
|
||||||
|
void setup_wifi() {
|
||||||
|
|
||||||
|
delay(10);
|
||||||
|
// We start by connecting to a WiFi network
|
||||||
|
Serial.println();
|
||||||
|
Serial.print("Connecting to ");
|
||||||
|
Serial.println(ssid);
|
||||||
|
|
||||||
|
WiFi.begin(ssid, password);
|
||||||
|
|
||||||
|
while (WiFi.status() != WL_CONNECTED) {
|
||||||
|
delay(500);
|
||||||
|
Serial.print(".");
|
||||||
|
}
|
||||||
|
|
||||||
|
randomSeed(micros());
|
||||||
|
|
||||||
|
Serial.println("");
|
||||||
|
Serial.println("WiFi connected");
|
||||||
|
Serial.println("IP address: ");
|
||||||
|
Serial.println(WiFi.localIP());
|
||||||
|
}
|
||||||
|
|
||||||
|
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();
|
||||||
|
|
||||||
|
// Find out how many bottles we should generate lyrics for
|
||||||
|
String topicStr(topic);
|
||||||
|
int bottleCount = 0; // assume no bottles unless we correctly parse a value from the topic
|
||||||
|
if (topicStr.indexOf('/') >= 0) {
|
||||||
|
// The topic includes a '/', we'll try to read the number of bottles from just after that
|
||||||
|
topicStr.remove(0, topicStr.indexOf('/')+1);
|
||||||
|
// Now see if there's a number of bottles after the '/'
|
||||||
|
bottleCount = topicStr.toInt();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bottleCount > 0) {
|
||||||
|
// Work out how big our resulting message will be
|
||||||
|
int msgLen = 0;
|
||||||
|
for (int i = bottleCount; i > 0; i--) {
|
||||||
|
String numBottles(i);
|
||||||
|
msgLen += 2*numBottles.length();
|
||||||
|
if (i == 1) {
|
||||||
|
msgLen += 2*String(" green bottle, standing on the wall\n").length();
|
||||||
|
} else {
|
||||||
|
msgLen += 2*String(" green bottles, standing on the wall\n").length();
|
||||||
|
}
|
||||||
|
msgLen += String("And if one green bottle should accidentally fall\nThere'll be ").length();
|
||||||
|
switch (i) {
|
||||||
|
case 1:
|
||||||
|
msgLen += String("no green bottles, standing on the wall\n\n").length();
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
msgLen += String("1 green bottle, standing on the wall\n\n").length();
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
numBottles = i-1;
|
||||||
|
msgLen += numBottles.length();
|
||||||
|
msgLen += String(" green bottles, standing on the wall\n\n").length();
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Now we can start to publish the message
|
||||||
|
client.beginPublish("greenBottles/lyrics", msgLen, false);
|
||||||
|
for (int i = bottleCount; i > 0; i--) {
|
||||||
|
for (int j = 0; j < 2; j++) {
|
||||||
|
client.print(i);
|
||||||
|
if (i == 1) {
|
||||||
|
client.print(" green bottle, standing on the wall\n");
|
||||||
|
} else {
|
||||||
|
client.print(" green bottles, standing on the wall\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
client.print("And if one green bottle should accidentally fall\nThere'll be ");
|
||||||
|
switch (i) {
|
||||||
|
case 1:
|
||||||
|
client.print("no green bottles, standing on the wall\n\n");
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
client.print("1 green bottle, standing on the wall\n\n");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
client.print(i-1);
|
||||||
|
client.print(" green bottles, standing on the wall\n\n");
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// Now we're done!
|
||||||
|
client.endPublish();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void reconnect() {
|
||||||
|
// Loop until we're reconnected
|
||||||
|
while (!client.connected()) {
|
||||||
|
Serial.print("Attempting MQTT connection...");
|
||||||
|
// Create a random client ID
|
||||||
|
String clientId = "ESP8266Client-";
|
||||||
|
clientId += String(random(0xffff), HEX);
|
||||||
|
// Attempt to connect
|
||||||
|
if (client.connect(clientId.c_str())) {
|
||||||
|
Serial.println("connected");
|
||||||
|
// Once connected, publish an announcement...
|
||||||
|
client.publish("outTopic", "hello world");
|
||||||
|
// ... and resubscribe
|
||||||
|
client.subscribe("greenBottles/#");
|
||||||
|
} else {
|
||||||
|
Serial.print("failed, rc=");
|
||||||
|
Serial.print(client.state());
|
||||||
|
Serial.println(" try again in 5 seconds");
|
||||||
|
// Wait 5 seconds before retrying
|
||||||
|
delay(5000);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
|
||||||
|
Serial.begin(115200);
|
||||||
|
setup_wifi();
|
||||||
|
client.setServer(mqtt_server, 1883);
|
||||||
|
client.setCallback(callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
|
||||||
|
if (!client.connected()) {
|
||||||
|
reconnect();
|
||||||
|
}
|
||||||
|
client.loop();
|
||||||
|
}
|
@ -16,6 +16,9 @@ connect KEYWORD2
|
|||||||
disconnect KEYWORD2
|
disconnect KEYWORD2
|
||||||
publish KEYWORD2
|
publish KEYWORD2
|
||||||
publish_P KEYWORD2
|
publish_P KEYWORD2
|
||||||
|
beginPublish KEYWORD2
|
||||||
|
endPublish KEYWORD2
|
||||||
|
write KEYWORD2
|
||||||
subscribe KEYWORD2
|
subscribe KEYWORD2
|
||||||
unsubscribe KEYWORD2
|
unsubscribe KEYWORD2
|
||||||
loop KEYWORD2
|
loop KEYWORD2
|
17
library.json
Normal file
17
library.json
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
{
|
||||||
|
"name": "PubSubClient",
|
||||||
|
"keywords": "ethernet, mqtt, m2m, iot",
|
||||||
|
"description": "A client library for MQTT messaging. MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison, ESP8266 and TI CC3000.",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/knolleary/pubsubclient.git"
|
||||||
|
},
|
||||||
|
"version": "2.6",
|
||||||
|
"exclude": "tests",
|
||||||
|
"examples": "examples/*/*.ino",
|
||||||
|
"frameworks": "arduino",
|
||||||
|
"platforms": [
|
||||||
|
"atmelavr",
|
||||||
|
"espressif"
|
||||||
|
]
|
||||||
|
}
|
@ -1,9 +1,9 @@
|
|||||||
name=PubSubClient
|
name=PubSubClient
|
||||||
version=2.1
|
version=2.6
|
||||||
author=Nick O'Leary <nick.oleary@gmail.com>
|
author=Nick O'Leary <nick.oleary@gmail.com>
|
||||||
maintainer=Nick O'Leary <nick.oleary@gmail.com>
|
maintainer=Nick O'Leary <nick.oleary@gmail.com>
|
||||||
sentence=A client library for MQTT messaging.
|
sentence=A client library for MQTT messaging.
|
||||||
paragraph=MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages from a remote server. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison and ESP8266.
|
paragraph=MQTT is a lightweight messaging protocol ideal for small devices. This library allows you to send and receive MQTT messages. It supports the latest MQTT 3.1.1 protocol and can be configured to use the older MQTT 3.1 if needed. It supports all Arduino Ethernet Client compatible hardware, including the Intel Galileo/Edison, ESP8266 and TI CC3000.
|
||||||
category=Communication
|
category=Communication
|
||||||
url=http://knolleary.github.io/pubsubclient/
|
url=http://pubsubclient.knolleary.net
|
||||||
architectures=*
|
architectures=*
|
@ -122,10 +122,10 @@ boolean PubSubClient::connect(const char *id, const char *user, const char *pass
|
|||||||
} else {
|
} else {
|
||||||
result = _client->connect(this->ip, this->port);
|
result = _client->connect(this->ip, this->port);
|
||||||
}
|
}
|
||||||
if (result) {
|
if (result == 1) {
|
||||||
nextMsgId = 1;
|
nextMsgId = 1;
|
||||||
// Leave room in the buffer for header and variable length field
|
// Leave room in the buffer for header and variable length field
|
||||||
uint16_t length = 5;
|
uint16_t length = MQTT_MAX_HEADER_SIZE;
|
||||||
unsigned int j;
|
unsigned int j;
|
||||||
|
|
||||||
#if MQTT_VERSION == MQTT_VERSION_3_1
|
#if MQTT_VERSION == MQTT_VERSION_3_1
|
||||||
@ -171,13 +171,13 @@ boolean PubSubClient::connect(const char *id, const char *user, const char *pass
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
write(MQTTCONNECT,buffer,length-5);
|
write(MQTTCONNECT,buffer,length-MQTT_MAX_HEADER_SIZE);
|
||||||
|
|
||||||
lastInActivity = lastOutActivity = millis();
|
lastInActivity = lastOutActivity = millis();
|
||||||
|
|
||||||
while (!_client->available()) {
|
while (!_client->available()) {
|
||||||
unsigned long t = millis();
|
unsigned long t = millis();
|
||||||
if (t-lastInActivity > MQTT_KEEPALIVE*1000UL) {
|
if (t-lastInActivity >= ((int32_t) MQTT_SOCKET_TIMEOUT*1000UL)) {
|
||||||
_state = MQTT_CONNECTION_TIMEOUT;
|
_state = MQTT_CONNECTION_TIMEOUT;
|
||||||
_client->stop();
|
_client->stop();
|
||||||
return false;
|
return false;
|
||||||
@ -205,14 +205,33 @@ boolean PubSubClient::connect(const char *id, const char *user, const char *pass
|
|||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t PubSubClient::readByte() {
|
// reads a byte into result
|
||||||
while(!_client->available()) {}
|
boolean PubSubClient::readByte(uint8_t * result) {
|
||||||
return _client->read();
|
uint32_t previousMillis = millis();
|
||||||
|
while(!_client->available()) {
|
||||||
|
uint32_t currentMillis = millis();
|
||||||
|
if(currentMillis - previousMillis >= ((int32_t) MQTT_SOCKET_TIMEOUT * 1000)){
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*result = _client->read();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// reads a byte into result[*index] and increments index
|
||||||
|
boolean PubSubClient::readByte(uint8_t * result, uint16_t * index){
|
||||||
|
uint16_t current_index = *index;
|
||||||
|
uint8_t * write_address = &(result[current_index]);
|
||||||
|
if(readByte(write_address)){
|
||||||
|
*index = current_index + 1;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
|
uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
|
||||||
uint16_t len = 0;
|
uint16_t len = 0;
|
||||||
buffer[len++] = readByte();
|
if(!readByte(buffer, &len)) return 0;
|
||||||
bool isPublish = (buffer[0]&0xF0) == MQTTPUBLISH;
|
bool isPublish = (buffer[0]&0xF0) == MQTTPUBLISH;
|
||||||
uint32_t multiplier = 1;
|
uint32_t multiplier = 1;
|
||||||
uint16_t length = 0;
|
uint16_t length = 0;
|
||||||
@ -221,7 +240,13 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
|
|||||||
uint8_t start = 0;
|
uint8_t start = 0;
|
||||||
|
|
||||||
do {
|
do {
|
||||||
digit = readByte();
|
if (len == 6) {
|
||||||
|
// Invalid remaining length encoding - kill the connection
|
||||||
|
_state = MQTT_DISCONNECTED;
|
||||||
|
_client->stop();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if(!readByte(&digit)) return 0;
|
||||||
buffer[len++] = digit;
|
buffer[len++] = digit;
|
||||||
length += (digit & 127) * multiplier;
|
length += (digit & 127) * multiplier;
|
||||||
multiplier *= 128;
|
multiplier *= 128;
|
||||||
@ -230,8 +255,8 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
|
|||||||
|
|
||||||
if (isPublish) {
|
if (isPublish) {
|
||||||
// Read in topic length to calculate bytes to skip over for Stream writing
|
// Read in topic length to calculate bytes to skip over for Stream writing
|
||||||
buffer[len++] = readByte();
|
if(!readByte(buffer, &len)) return 0;
|
||||||
buffer[len++] = readByte();
|
if(!readByte(buffer, &len)) return 0;
|
||||||
skip = (buffer[*lengthLength+1]<<8)+buffer[*lengthLength+2];
|
skip = (buffer[*lengthLength+1]<<8)+buffer[*lengthLength+2];
|
||||||
start = 2;
|
start = 2;
|
||||||
if (buffer[0]&MQTTQOS1) {
|
if (buffer[0]&MQTTQOS1) {
|
||||||
@ -241,7 +266,7 @@ uint16_t PubSubClient::readPacket(uint8_t* lengthLength) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (uint16_t i = start;i<length;i++) {
|
for (uint16_t i = start;i<length;i++) {
|
||||||
digit = readByte();
|
if(!readByte(&digit)) return 0;
|
||||||
if (this->stream) {
|
if (this->stream) {
|
||||||
if (isPublish && len-*lengthLength-2>skip) {
|
if (isPublish && len-*lengthLength-2>skip) {
|
||||||
this->stream->write(digit);
|
this->stream->write(digit);
|
||||||
@ -287,12 +312,10 @@ boolean PubSubClient::loop() {
|
|||||||
uint8_t type = buffer[0]&0xF0;
|
uint8_t type = buffer[0]&0xF0;
|
||||||
if (type == MQTTPUBLISH) {
|
if (type == MQTTPUBLISH) {
|
||||||
if (callback) {
|
if (callback) {
|
||||||
uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2];
|
uint16_t tl = (buffer[llen+1]<<8)+buffer[llen+2]; /* topic length in bytes */
|
||||||
char topic[tl+1];
|
memmove(buffer+llen+2,buffer+llen+3,tl); /* move topic inside buffer 1 byte to front */
|
||||||
for (uint16_t i=0;i<tl;i++) {
|
buffer[llen+2+tl] = 0; /* end the topic as a 'C' string with \x00 */
|
||||||
topic[i] = buffer[llen+3+i];
|
char *topic = (char*) buffer+llen+2;
|
||||||
}
|
|
||||||
topic[tl] = 0;
|
|
||||||
// msgId only present for QOS>0
|
// msgId only present for QOS>0
|
||||||
if ((buffer[0]&0x06) == MQTTQOS1) {
|
if ((buffer[0]&0x06) == MQTTQOS1) {
|
||||||
msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1];
|
msgId = (buffer[llen+3+tl]<<8)+buffer[llen+3+tl+1];
|
||||||
@ -318,6 +341,9 @@ boolean PubSubClient::loop() {
|
|||||||
} else if (type == MQTTPINGRESP) {
|
} else if (type == MQTTPINGRESP) {
|
||||||
pingOutstanding = false;
|
pingOutstanding = false;
|
||||||
}
|
}
|
||||||
|
} else if (!connected()) {
|
||||||
|
// readPacket has closed the connection
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
@ -329,18 +355,22 @@ boolean PubSubClient::publish(const char* topic, const char* payload) {
|
|||||||
return publish(topic,(const uint8_t*)payload,strlen(payload),false);
|
return publish(topic,(const uint8_t*)payload,strlen(payload),false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
boolean PubSubClient::publish(const char* topic, const char* payload, boolean retained) {
|
||||||
|
return publish(topic,(const uint8_t*)payload,strlen(payload),retained);
|
||||||
|
}
|
||||||
|
|
||||||
boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigned int plength) {
|
boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigned int plength) {
|
||||||
return publish(topic, payload, plength, false);
|
return publish(topic, payload, plength, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigned int plength, boolean retained) {
|
boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigned int plength, boolean retained) {
|
||||||
if (connected()) {
|
if (connected()) {
|
||||||
if (MQTT_MAX_PACKET_SIZE < 5 + 2+strlen(topic) + plength) {
|
if (MQTT_MAX_PACKET_SIZE < MQTT_MAX_HEADER_SIZE + 2+strlen(topic) + plength) {
|
||||||
// Too long
|
// Too long
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
// Leave room in the buffer for header and variable length field
|
// Leave room in the buffer for header and variable length field
|
||||||
uint16_t length = 5;
|
uint16_t length = MQTT_MAX_HEADER_SIZE;
|
||||||
length = writeString(topic,buffer,length);
|
length = writeString(topic,buffer,length);
|
||||||
uint16_t i;
|
uint16_t i;
|
||||||
for (i=0;i<plength;i++) {
|
for (i=0;i<plength;i++) {
|
||||||
@ -350,7 +380,7 @@ boolean PubSubClient::publish(const char* topic, const uint8_t* payload, unsigne
|
|||||||
if (retained) {
|
if (retained) {
|
||||||
header |= 1;
|
header |= 1;
|
||||||
}
|
}
|
||||||
return write(header,buffer,length-5);
|
return write(header,buffer,length-MQTT_MAX_HEADER_SIZE);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -400,12 +430,43 @@ boolean PubSubClient::publish_P(const char* topic, const uint8_t* payload, unsig
|
|||||||
return rc == tlen + 4 + plength;
|
return rc == tlen + 4 + plength;
|
||||||
}
|
}
|
||||||
|
|
||||||
boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
|
boolean PubSubClient::beginPublish(const char* topic, unsigned int plength, boolean retained) {
|
||||||
|
if (connected()) {
|
||||||
|
// Send the header and variable length field
|
||||||
|
uint16_t length = MQTT_MAX_HEADER_SIZE;
|
||||||
|
length = writeString(topic,buffer,length);
|
||||||
|
uint16_t i;
|
||||||
|
uint8_t header = MQTTPUBLISH;
|
||||||
|
if (retained) {
|
||||||
|
header |= 1;
|
||||||
|
}
|
||||||
|
size_t hlen = buildHeader(header, buffer, plength+length-MQTT_MAX_HEADER_SIZE);
|
||||||
|
uint16_t rc = _client->write(buffer+(MQTT_MAX_HEADER_SIZE-hlen),length-(MQTT_MAX_HEADER_SIZE-hlen));
|
||||||
|
lastOutActivity = millis();
|
||||||
|
return (rc == (length-(MQTT_MAX_HEADER_SIZE-hlen)));
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int PubSubClient::endPublish() {
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t PubSubClient::write(uint8_t data) {
|
||||||
|
lastOutActivity = millis();
|
||||||
|
return _client->write(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t PubSubClient::write(const uint8_t *buffer, size_t size) {
|
||||||
|
lastOutActivity = millis();
|
||||||
|
return _client->write(buffer,size);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t PubSubClient::buildHeader(uint8_t header, uint8_t* buf, uint16_t length) {
|
||||||
uint8_t lenBuf[4];
|
uint8_t lenBuf[4];
|
||||||
uint8_t llen = 0;
|
uint8_t llen = 0;
|
||||||
uint8_t digit;
|
uint8_t digit;
|
||||||
uint8_t pos = 0;
|
uint8_t pos = 0;
|
||||||
uint8_t rc;
|
|
||||||
uint16_t len = length;
|
uint16_t len = length;
|
||||||
do {
|
do {
|
||||||
digit = len % 128;
|
digit = len % 128;
|
||||||
@ -419,12 +480,18 @@ boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
|
|||||||
|
|
||||||
buf[4-llen] = header;
|
buf[4-llen] = header;
|
||||||
for (int i=0;i<llen;i++) {
|
for (int i=0;i<llen;i++) {
|
||||||
buf[5-llen+i] = lenBuf[i];
|
buf[MQTT_MAX_HEADER_SIZE-llen+i] = lenBuf[i];
|
||||||
|
}
|
||||||
|
return llen+1; // Full header size is variable length bit plus the 1-byte fixed header
|
||||||
}
|
}
|
||||||
|
|
||||||
|
boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
|
||||||
|
uint16_t rc;
|
||||||
|
uint8_t hlen = buildHeader(header, buf, length);
|
||||||
|
|
||||||
#ifdef MQTT_MAX_TRANSFER_SIZE
|
#ifdef MQTT_MAX_TRANSFER_SIZE
|
||||||
uint8_t* writeBuf = buf+(4-llen);
|
uint8_t* writeBuf = buf+(MQTT_MAX_HEADER_SIZE-hlen);
|
||||||
uint8_t bytesRemaining = length+1+llen;
|
uint16_t bytesRemaining = length+hlen; //Match the length type
|
||||||
uint8_t bytesToWrite;
|
uint8_t bytesToWrite;
|
||||||
boolean result = true;
|
boolean result = true;
|
||||||
while((bytesRemaining > 0) && result) {
|
while((bytesRemaining > 0) && result) {
|
||||||
@ -436,9 +503,9 @@ boolean PubSubClient::write(uint8_t header, uint8_t* buf, uint16_t length) {
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
#else
|
#else
|
||||||
rc = _client->write(buf+(4-llen),length+1+llen);
|
rc = _client->write(buf+(MQTT_MAX_HEADER_SIZE-hlen),length+hlen);
|
||||||
lastOutActivity = millis();
|
lastOutActivity = millis();
|
||||||
return (rc == 1+llen+length);
|
return (rc == hlen+length);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -447,7 +514,7 @@ boolean PubSubClient::subscribe(const char* topic) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
boolean PubSubClient::subscribe(const char* topic, uint8_t qos) {
|
boolean PubSubClient::subscribe(const char* topic, uint8_t qos) {
|
||||||
if (qos < 0 || qos > 1) {
|
if (qos > 1) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (MQTT_MAX_PACKET_SIZE < 9 + strlen(topic)) {
|
if (MQTT_MAX_PACKET_SIZE < 9 + strlen(topic)) {
|
||||||
@ -456,7 +523,7 @@ boolean PubSubClient::subscribe(const char* topic, uint8_t qos) {
|
|||||||
}
|
}
|
||||||
if (connected()) {
|
if (connected()) {
|
||||||
// Leave room in the buffer for header and variable length field
|
// Leave room in the buffer for header and variable length field
|
||||||
uint16_t length = 5;
|
uint16_t length = MQTT_MAX_HEADER_SIZE;
|
||||||
nextMsgId++;
|
nextMsgId++;
|
||||||
if (nextMsgId == 0) {
|
if (nextMsgId == 0) {
|
||||||
nextMsgId = 1;
|
nextMsgId = 1;
|
||||||
@ -465,7 +532,7 @@ boolean PubSubClient::subscribe(const char* topic, uint8_t qos) {
|
|||||||
buffer[length++] = (nextMsgId & 0xFF);
|
buffer[length++] = (nextMsgId & 0xFF);
|
||||||
length = writeString((char*)topic, buffer,length);
|
length = writeString((char*)topic, buffer,length);
|
||||||
buffer[length++] = qos;
|
buffer[length++] = qos;
|
||||||
return write(MQTTSUBSCRIBE|MQTTQOS1,buffer,length-5);
|
return write(MQTTSUBSCRIBE|MQTTQOS1,buffer,length-MQTT_MAX_HEADER_SIZE);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -476,7 +543,7 @@ boolean PubSubClient::unsubscribe(const char* topic) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (connected()) {
|
if (connected()) {
|
||||||
uint16_t length = 5;
|
uint16_t length = MQTT_MAX_HEADER_SIZE;
|
||||||
nextMsgId++;
|
nextMsgId++;
|
||||||
if (nextMsgId == 0) {
|
if (nextMsgId == 0) {
|
||||||
nextMsgId = 1;
|
nextMsgId = 1;
|
||||||
@ -484,7 +551,7 @@ boolean PubSubClient::unsubscribe(const char* topic) {
|
|||||||
buffer[length++] = (nextMsgId >> 8);
|
buffer[length++] = (nextMsgId >> 8);
|
||||||
buffer[length++] = (nextMsgId & 0xFF);
|
buffer[length++] = (nextMsgId & 0xFF);
|
||||||
length = writeString(topic, buffer,length);
|
length = writeString(topic, buffer,length);
|
||||||
return write(MQTTUNSUBSCRIBE|MQTTQOS1,buffer,length-5);
|
return write(MQTTUNSUBSCRIBE|MQTTQOS1,buffer,length-MQTT_MAX_HEADER_SIZE);
|
||||||
}
|
}
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@ -494,6 +561,7 @@ void PubSubClient::disconnect() {
|
|||||||
buffer[1] = 0;
|
buffer[1] = 0;
|
||||||
_client->write(buffer,2);
|
_client->write(buffer,2);
|
||||||
_state = MQTT_DISCONNECTED;
|
_state = MQTT_DISCONNECTED;
|
||||||
|
_client->flush();
|
||||||
_client->stop();
|
_client->stop();
|
||||||
lastInActivity = lastOutActivity = millis();
|
lastInActivity = lastOutActivity = millis();
|
||||||
}
|
}
|
||||||
@ -547,7 +615,7 @@ PubSubClient& PubSubClient::setServer(const char * domain, uint16_t port) {
|
|||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
PubSubClient& PubSubClient::setCallback(void(*callback)(char*,uint8_t*,unsigned int)){
|
PubSubClient& PubSubClient::setCallback(MQTT_CALLBACK_SIGNATURE) {
|
||||||
this->callback = callback;
|
this->callback = callback;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
@ -17,13 +17,24 @@
|
|||||||
|
|
||||||
// MQTT_VERSION : Pick the version
|
// MQTT_VERSION : Pick the version
|
||||||
//#define MQTT_VERSION MQTT_VERSION_3_1
|
//#define MQTT_VERSION MQTT_VERSION_3_1
|
||||||
|
#ifndef MQTT_VERSION
|
||||||
#define MQTT_VERSION MQTT_VERSION_3_1_1
|
#define MQTT_VERSION MQTT_VERSION_3_1_1
|
||||||
|
#endif
|
||||||
|
|
||||||
// MQTT_MAX_PACKET_SIZE : Maximum packet size
|
// MQTT_MAX_PACKET_SIZE : Maximum packet size
|
||||||
|
#ifndef MQTT_MAX_PACKET_SIZE
|
||||||
#define MQTT_MAX_PACKET_SIZE 128
|
#define MQTT_MAX_PACKET_SIZE 128
|
||||||
|
#endif
|
||||||
|
|
||||||
// MQTT_KEEPALIVE : keepAlive interval in Seconds
|
// MQTT_KEEPALIVE : keepAlive interval in Seconds
|
||||||
|
#ifndef MQTT_KEEPALIVE
|
||||||
#define MQTT_KEEPALIVE 15
|
#define MQTT_KEEPALIVE 15
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// MQTT_SOCKET_TIMEOUT: socket timeout interval in Seconds
|
||||||
|
#ifndef MQTT_SOCKET_TIMEOUT
|
||||||
|
#define MQTT_SOCKET_TIMEOUT 15
|
||||||
|
#endif
|
||||||
|
|
||||||
// MQTT_MAX_TRANSFER_SIZE : limit how much data is passed to the network client
|
// MQTT_MAX_TRANSFER_SIZE : limit how much data is passed to the network client
|
||||||
// in each write call. Needed for the Arduino Wifi Shield. Leave undefined to
|
// in each write call. Needed for the Arduino Wifi Shield. Leave undefined to
|
||||||
@ -62,9 +73,17 @@
|
|||||||
#define MQTTQOS1 (1 << 1)
|
#define MQTTQOS1 (1 << 1)
|
||||||
#define MQTTQOS2 (2 << 1)
|
#define MQTTQOS2 (2 << 1)
|
||||||
|
|
||||||
#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*,uint8_t*,unsigned int)
|
// Maximum size of fixed header and variable length size header
|
||||||
|
#define MQTT_MAX_HEADER_SIZE 5
|
||||||
|
|
||||||
class PubSubClient {
|
#ifdef ESP8266
|
||||||
|
#include <functional>
|
||||||
|
#define MQTT_CALLBACK_SIGNATURE std::function<void(char*, uint8_t*, unsigned int)> callback
|
||||||
|
#else
|
||||||
|
#define MQTT_CALLBACK_SIGNATURE void (*callback)(char*, uint8_t*, unsigned int)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
class PubSubClient : public Print {
|
||||||
private:
|
private:
|
||||||
Client* _client;
|
Client* _client;
|
||||||
uint8_t buffer[MQTT_MAX_PACKET_SIZE];
|
uint8_t buffer[MQTT_MAX_PACKET_SIZE];
|
||||||
@ -74,9 +93,15 @@ private:
|
|||||||
bool pingOutstanding;
|
bool pingOutstanding;
|
||||||
MQTT_CALLBACK_SIGNATURE;
|
MQTT_CALLBACK_SIGNATURE;
|
||||||
uint16_t readPacket(uint8_t*);
|
uint16_t readPacket(uint8_t*);
|
||||||
uint8_t readByte();
|
boolean readByte(uint8_t * result);
|
||||||
|
boolean readByte(uint8_t * result, uint16_t * index);
|
||||||
boolean write(uint8_t header, uint8_t* buf, uint16_t length);
|
boolean write(uint8_t header, uint8_t* buf, uint16_t length);
|
||||||
uint16_t writeString(const char* string, uint8_t* buf, uint16_t pos);
|
uint16_t writeString(const char* string, uint8_t* buf, uint16_t pos);
|
||||||
|
// Build up the header ready to send
|
||||||
|
// Returns the size of the header
|
||||||
|
// Note: the header is built at the end of the first MQTT_MAX_HEADER_SIZE bytes, so will start
|
||||||
|
// (MQTT_MAX_HEADER_SIZE - <returned size>) bytes into the buffer
|
||||||
|
size_t buildHeader(uint8_t header, uint8_t* buf, uint16_t length);
|
||||||
IPAddress ip;
|
IPAddress ip;
|
||||||
const char* domain;
|
const char* domain;
|
||||||
uint16_t port;
|
uint16_t port;
|
||||||
@ -111,9 +136,27 @@ public:
|
|||||||
boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
|
boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage);
|
||||||
void disconnect();
|
void disconnect();
|
||||||
boolean publish(const char* topic, const char* payload);
|
boolean publish(const char* topic, const char* payload);
|
||||||
|
boolean publish(const char* topic, const char* payload, boolean retained);
|
||||||
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
|
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength);
|
||||||
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
|
boolean publish(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
|
||||||
boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
|
boolean publish_P(const char* topic, const uint8_t * payload, unsigned int plength, boolean retained);
|
||||||
|
// Start to publish a message.
|
||||||
|
// This API:
|
||||||
|
// beginPublish(...)
|
||||||
|
// one or more calls to write(...)
|
||||||
|
// endPublish()
|
||||||
|
// Allows for arbitrarily large payloads to be sent without them having to be copied into
|
||||||
|
// a new buffer and held in memory at one time
|
||||||
|
// Returns 1 if the message was started successfully, 0 if there was an error
|
||||||
|
boolean beginPublish(const char* topic, unsigned int plength, boolean retained);
|
||||||
|
// Finish off this publish message (started with beginPublish)
|
||||||
|
// Returns 1 if the packet was sent successfully, 0 if there was an error
|
||||||
|
int endPublish();
|
||||||
|
// Write a single byte of payload (only to be used with beginPublish/endPublish)
|
||||||
|
virtual size_t write(uint8_t);
|
||||||
|
// Write size bytes from buffer into the payload (only to be used with beginPublish/endPublish)
|
||||||
|
// Returns the number of bytes written
|
||||||
|
virtual size_t write(const uint8_t *buffer, size_t size);
|
||||||
boolean subscribe(const char* topic);
|
boolean subscribe(const char* topic);
|
||||||
boolean subscribe(const char* topic, uint8_t qos);
|
boolean subscribe(const char* topic, uint8_t qos);
|
||||||
boolean unsubscribe(const char* topic);
|
boolean unsubscribe(const char* topic);
|
@ -4,9 +4,9 @@ TEST_SRC=$(wildcard ${SRC_PATH}/*_spec.cpp)
|
|||||||
TEST_BIN= $(TEST_SRC:${SRC_PATH}/%.cpp=${OUT_PATH}/%)
|
TEST_BIN= $(TEST_SRC:${SRC_PATH}/%.cpp=${OUT_PATH}/%)
|
||||||
VPATH=${SRC_PATH}
|
VPATH=${SRC_PATH}
|
||||||
SHIM_FILES=${SRC_PATH}/lib/*.cpp
|
SHIM_FILES=${SRC_PATH}/lib/*.cpp
|
||||||
PSC_FILE=../PubSubClient/src/PubSubClient.cpp
|
PSC_FILE=../src/PubSubClient.cpp
|
||||||
CC=g++
|
CC=g++
|
||||||
CFLAGS=-I${SRC_PATH}/lib -I../PubSubClient/src
|
CFLAGS=-I${SRC_PATH}/lib -I../src
|
||||||
|
|
||||||
all: $(TEST_BIN)
|
all: $(TEST_BIN)
|
||||||
|
|
||||||
|
@ -133,6 +133,23 @@ int test_connect_accepts_username_no_password() {
|
|||||||
|
|
||||||
END_IT
|
END_IT
|
||||||
}
|
}
|
||||||
|
int test_connect_accepts_username_blank_password() {
|
||||||
|
IT("accepts a username and blank password");
|
||||||
|
ShimClient shimClient;
|
||||||
|
shimClient.setAllowConnect(true);
|
||||||
|
|
||||||
|
byte connect[] = { 0x10,0x20,0x0,0x4,0x4d,0x51,0x54,0x54,0x4,0xc2,0x0,0xf,0x0,0xc,0x63,0x6c,0x69,0x65,0x6e,0x74,0x5f,0x74,0x65,0x73,0x74,0x31,0x0,0x4,0x75,0x73,0x65,0x72,0x0,0x0};
|
||||||
|
byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
|
||||||
|
shimClient.expect(connect,0x26);
|
||||||
|
shimClient.respond(connack,4);
|
||||||
|
|
||||||
|
PubSubClient client(server, 1883, callback, shimClient);
|
||||||
|
int rc = client.connect((char*)"client_test1",(char*)"user",(char*)"pass");
|
||||||
|
IS_TRUE(rc);
|
||||||
|
IS_FALSE(shimClient.error());
|
||||||
|
|
||||||
|
END_IT
|
||||||
|
}
|
||||||
|
|
||||||
int test_connect_ignores_password_no_username() {
|
int test_connect_ignores_password_no_username() {
|
||||||
IT("ignores a password but no username");
|
IT("ignores a password but no username");
|
||||||
|
@ -5,6 +5,7 @@
|
|||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include <math.h>
|
#include <math.h>
|
||||||
|
#include "Print.h"
|
||||||
|
|
||||||
|
|
||||||
extern "C"{
|
extern "C"{
|
||||||
|
@ -2,9 +2,13 @@
|
|||||||
#include "Arduino.h"
|
#include "Arduino.h"
|
||||||
|
|
||||||
Buffer::Buffer() {
|
Buffer::Buffer() {
|
||||||
|
this->pos = 0;
|
||||||
|
this->length = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
Buffer::Buffer(uint8_t* buf, size_t size) {
|
Buffer::Buffer(uint8_t* buf, size_t size) {
|
||||||
|
this->pos = 0;
|
||||||
|
this->length = 0;
|
||||||
this->add(buf,size);
|
this->add(buf,size);
|
||||||
}
|
}
|
||||||
bool Buffer::available() {
|
bool Buffer::available() {
|
||||||
|
28
tests/src/lib/Print.h
Normal file
28
tests/src/lib/Print.h
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
/*
|
||||||
|
Print.h - Base class that provides print() and println()
|
||||||
|
Copyright (c) 2008 David A. Mellis. All right reserved.
|
||||||
|
|
||||||
|
This library is free software; you can redistribute it and/or
|
||||||
|
modify it under the terms of the GNU Lesser General Public
|
||||||
|
License as published by the Free Software Foundation; either
|
||||||
|
version 2.1 of the License, or (at your option) any later version.
|
||||||
|
|
||||||
|
This library is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||||
|
Lesser General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Lesser General Public
|
||||||
|
License along with this library; if not, write to the Free Software
|
||||||
|
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef Print_h
|
||||||
|
#define Print_h
|
||||||
|
|
||||||
|
class Print {
|
||||||
|
public:
|
||||||
|
virtual size_t write(uint8_t) = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
#endif
|
@ -63,7 +63,7 @@ int test_publish_bytes() {
|
|||||||
|
|
||||||
|
|
||||||
int test_publish_retained() {
|
int test_publish_retained() {
|
||||||
IT("publishes retained");
|
IT("publishes retained - 1");
|
||||||
ShimClient shimClient;
|
ShimClient shimClient;
|
||||||
shimClient.setAllowConnect(true);
|
shimClient.setAllowConnect(true);
|
||||||
|
|
||||||
@ -88,6 +88,29 @@ int test_publish_retained() {
|
|||||||
END_IT
|
END_IT
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int test_publish_retained_2() {
|
||||||
|
IT("publishes retained - 2");
|
||||||
|
ShimClient shimClient;
|
||||||
|
shimClient.setAllowConnect(true);
|
||||||
|
|
||||||
|
byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
|
||||||
|
shimClient.respond(connack,4);
|
||||||
|
|
||||||
|
PubSubClient client(server, 1883, callback, shimClient);
|
||||||
|
int rc = client.connect((char*)"client_test1");
|
||||||
|
IS_TRUE(rc);
|
||||||
|
|
||||||
|
byte publish[] = {0x31,0xc,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,'A','B','C','D','E'};
|
||||||
|
shimClient.expect(publish,14);
|
||||||
|
|
||||||
|
rc = client.publish((char*)"topic",(char*)"ABCDE",true);
|
||||||
|
IS_TRUE(rc);
|
||||||
|
|
||||||
|
IS_FALSE(shimClient.error());
|
||||||
|
|
||||||
|
END_IT
|
||||||
|
}
|
||||||
|
|
||||||
int test_publish_not_connected() {
|
int test_publish_not_connected() {
|
||||||
IT("publish fails when not connected");
|
IT("publish fails when not connected");
|
||||||
ShimClient shimClient;
|
ShimClient shimClient;
|
||||||
@ -158,6 +181,7 @@ int main()
|
|||||||
test_publish();
|
test_publish();
|
||||||
test_publish_bytes();
|
test_publish_bytes();
|
||||||
test_publish_retained();
|
test_publish_retained();
|
||||||
|
test_publish_retained_2();
|
||||||
test_publish_not_connected();
|
test_publish_not_connected();
|
||||||
test_publish_too_long();
|
test_publish_too_long();
|
||||||
test_publish_P();
|
test_publish_P();
|
||||||
|
@ -160,6 +160,35 @@ int test_receive_oversized_message() {
|
|||||||
END_IT
|
END_IT
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int test_drop_invalid_remaining_length_message() {
|
||||||
|
IT("drops invalid remaining length message");
|
||||||
|
reset_callback();
|
||||||
|
|
||||||
|
ShimClient shimClient;
|
||||||
|
shimClient.setAllowConnect(true);
|
||||||
|
|
||||||
|
byte connack[] = { 0x20, 0x02, 0x00, 0x00 };
|
||||||
|
shimClient.respond(connack,4);
|
||||||
|
|
||||||
|
PubSubClient client(server, 1883, callback, shimClient);
|
||||||
|
int rc = client.connect((char*)"client_test1");
|
||||||
|
IS_TRUE(rc);
|
||||||
|
|
||||||
|
byte publish[] = {0x30,0x92,0x92,0x92,0x92,0x92,0x92,0x0,0x5,0x74,0x6f,0x70,0x69,0x63,0x70,0x61,0x79,0x6c,0x6f,0x61,0x64};
|
||||||
|
shimClient.respond(publish,21);
|
||||||
|
|
||||||
|
rc = client.loop();
|
||||||
|
|
||||||
|
IS_FALSE(rc);
|
||||||
|
|
||||||
|
IS_FALSE(callback_called);
|
||||||
|
|
||||||
|
IS_FALSE(shimClient.error());
|
||||||
|
|
||||||
|
END_IT
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
int test_receive_oversized_stream_message() {
|
int test_receive_oversized_stream_message() {
|
||||||
IT("drops an oversized message");
|
IT("drops an oversized message");
|
||||||
reset_callback();
|
reset_callback();
|
||||||
@ -241,6 +270,7 @@ int main()
|
|||||||
test_receive_callback();
|
test_receive_callback();
|
||||||
test_receive_stream();
|
test_receive_stream();
|
||||||
test_receive_max_sized_message();
|
test_receive_max_sized_message();
|
||||||
|
test_drop_invalid_remaining_length_message();
|
||||||
test_receive_oversized_message();
|
test_receive_oversized_message();
|
||||||
test_receive_oversized_stream_message();
|
test_receive_oversized_stream_message();
|
||||||
test_receive_qos1();
|
test_receive_qos1();
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
import unittest
|
import unittest
|
||||||
import settings
|
import settings
|
||||||
|
|
||||||
import time
|
import time
|
||||||
import mosquitto
|
import mosquitto
|
||||||
|
|
||||||
import serial
|
|
||||||
|
|
||||||
def on_message(mosq, obj, msg):
|
def on_message(mosq, obj, msg):
|
||||||
obj.message_queue.append(msg)
|
obj.message_queue.append(msg)
|
||||||
|
|
||||||
|
|
||||||
class mqtt_basic(unittest.TestCase):
|
class mqtt_basic(unittest.TestCase):
|
||||||
|
|
||||||
message_queue = []
|
message_queue = []
|
||||||
@ -38,6 +37,3 @@ class mqtt_basic(unittest.TestCase):
|
|||||||
self.assertEqual(msg.payload, "hello world")
|
self.assertEqual(msg.payload, "hello world")
|
||||||
self.assertEqual(msg.qos, 0, "message qos not 0")
|
self.assertEqual(msg.qos, 0, "message qos not 0")
|
||||||
self.assertEqual(msg.retain, False, "message retain flag incorrect")
|
self.assertEqual(msg.retain, False, "message retain flag incorrect")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,14 +1,13 @@
|
|||||||
import unittest
|
import unittest
|
||||||
import settings
|
import settings
|
||||||
|
|
||||||
import time
|
import time
|
||||||
import mosquitto
|
import mosquitto
|
||||||
|
|
||||||
import serial
|
|
||||||
|
|
||||||
def on_message(mosq, obj, msg):
|
def on_message(mosq, obj, msg):
|
||||||
obj.message_queue.append(msg)
|
obj.message_queue.append(msg)
|
||||||
|
|
||||||
|
|
||||||
class mqtt_publish_in_callback(unittest.TestCase):
|
class mqtt_publish_in_callback(unittest.TestCase):
|
||||||
|
|
||||||
message_queue = []
|
message_queue = []
|
||||||
@ -39,7 +38,6 @@ class mqtt_publish_in_callback(unittest.TestCase):
|
|||||||
self.assertEqual(msg.qos, 0, "message qos not 0")
|
self.assertEqual(msg.qos, 0, "message qos not 0")
|
||||||
self.assertEqual(msg.retain, False, "message retain flag incorrect")
|
self.assertEqual(msg.retain, False, "message retain flag incorrect")
|
||||||
|
|
||||||
|
|
||||||
def test_publish(self):
|
def test_publish(self):
|
||||||
self.assertEqual(len(self.message_queue), 0, "message queue not empty")
|
self.assertEqual(len(self.message_queue), 0, "message queue not empty")
|
||||||
payload = "abcdefghij"
|
payload = "abcdefghij"
|
||||||
@ -59,6 +57,3 @@ class mqtt_publish_in_callback(unittest.TestCase):
|
|||||||
self.assertEqual(msg.payload, payload)
|
self.assertEqual(msg.payload, payload)
|
||||||
self.assertEqual(msg.qos, 0, "message qos not 0")
|
self.assertEqual(msg.qos, 0, "message qos not 0")
|
||||||
self.assertEqual(msg.retain, False, "message retain flag incorrect")
|
self.assertEqual(msg.retain, False, "message retain flag incorrect")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@ -10,21 +10,22 @@ import re
|
|||||||
|
|
||||||
from testcases import settings
|
from testcases import settings
|
||||||
|
|
||||||
|
|
||||||
class Workspace(object):
|
class Workspace(object):
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.root_dir = os.getcwd()
|
self.root_dir = os.getcwd()
|
||||||
self.build_dir = os.path.join(self.root_dir,"tmpbin");
|
self.build_dir = os.path.join(self.root_dir, "tmpbin")
|
||||||
self.log_dir = os.path.join(self.root_dir,"logs");
|
self.log_dir = os.path.join(self.root_dir, "logs")
|
||||||
self.tests_dir = os.path.join(self.root_dir,"testcases");
|
self.tests_dir = os.path.join(self.root_dir, "testcases")
|
||||||
self.examples_dir = os.path.join(self.root_dir, "../PubSubClient/examples")
|
self.examples_dir = os.path.join(self.root_dir, "../PubSubClient/examples")
|
||||||
self.examples = []
|
self.examples = []
|
||||||
self.tests = []
|
self.tests = []
|
||||||
if not os.path.isdir("../PubSubClient"):
|
if not os.path.isdir("../PubSubClient"):
|
||||||
raise Exception("Cannot find PubSubClient library")
|
raise Exception("Cannot find PubSubClient library")
|
||||||
try:
|
try:
|
||||||
import ino
|
return __import__('ino')
|
||||||
except:
|
except ImportError:
|
||||||
raise Exception("ino tool not installed")
|
raise Exception("ino tool not installed")
|
||||||
|
|
||||||
def init(self):
|
def init(self):
|
||||||
@ -57,6 +58,7 @@ class Workspace(object):
|
|||||||
def clean(self):
|
def clean(self):
|
||||||
shutil.rmtree(self.build_dir)
|
shutil.rmtree(self.build_dir)
|
||||||
|
|
||||||
|
|
||||||
class Sketch(object):
|
class Sketch(object):
|
||||||
def __init__(self, wksp, fn):
|
def __init__(self, wksp, fn):
|
||||||
self.w = wksp
|
self.w = wksp
|
||||||
@ -100,7 +102,7 @@ class Sketch(object):
|
|||||||
sys.stdout.write("\n")
|
sys.stdout.write("\n")
|
||||||
with open(self.build_err_log) as f:
|
with open(self.build_err_log) as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
print " ",line,
|
print(" " + line)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def upload(self):
|
def upload(self):
|
||||||
@ -118,10 +120,9 @@ class Sketch(object):
|
|||||||
sys.stdout.write("\n")
|
sys.stdout.write("\n")
|
||||||
with open(self.build_upload_log) as f:
|
with open(self.build_upload_log) as f:
|
||||||
for line in f:
|
for line in f:
|
||||||
print " ",line,
|
print(" " + line)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
def test(self):
|
def test(self):
|
||||||
# import the matching test case, if it exists
|
# import the matching test case, if it exists
|
||||||
try:
|
try:
|
||||||
@ -146,19 +147,20 @@ class Sketch(object):
|
|||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
for t in tests:
|
for t in tests:
|
||||||
t.run(result)
|
t.run(result)
|
||||||
print "%d/%d"%(result.testsRun-len(result.failures)-len(result.errors),result.testsRun)
|
print(str(result.testsRun - len(result.failures) - len(result.errors)) + "/" + str(result.testsRun))
|
||||||
if not result.wasSuccessful():
|
if not result.wasSuccessful():
|
||||||
if len(result.failures) > 0:
|
if len(result.failures) > 0:
|
||||||
for f in result.failures:
|
for f in result.failures:
|
||||||
print "-- %s"%(str(f[0]),)
|
print("-- " + str(f[0]))
|
||||||
print f[1]
|
print(f[1])
|
||||||
if len(result.errors) > 0:
|
if len(result.errors) > 0:
|
||||||
print " Errors:"
|
print(" Errors:")
|
||||||
for f in result.errors:
|
for f in result.errors:
|
||||||
print "-- %s"%(str(f[0]),)
|
print("-- " + str(f[0]))
|
||||||
print f[1]
|
print(f[1])
|
||||||
c.tearDownClass()
|
c.tearDownClass()
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
run_tests = True
|
run_tests = True
|
||||||
|
|
||||||
@ -166,13 +168,13 @@ if __name__ == '__main__':
|
|||||||
w.init()
|
w.init()
|
||||||
|
|
||||||
for e in w.examples:
|
for e in w.examples:
|
||||||
print "--------------------------------------"
|
print("--------------------------------------")
|
||||||
print "[%s]"%(e.basename,)
|
print("[" + e.basename + "]")
|
||||||
if e.build() and run_tests:
|
if e.build() and run_tests:
|
||||||
e.test()
|
e.test()
|
||||||
for e in w.tests:
|
for e in w.tests:
|
||||||
print "--------------------------------------"
|
print("--------------------------------------")
|
||||||
print "[%s]"%(e.basename,)
|
print("[" + e.basename + "]")
|
||||||
if e.build() and run_tests:
|
if e.build() and run_tests:
|
||||||
e.test()
|
e.test()
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user