GithubHelp home page GithubHelp logo

arduino's Introduction

PubNub Arduino Library

Build Status

This library allows your sketches to communicate with the PubNub cloud message passing system using any network hardware (chip/shield) that has a class compatible with Arduino de facto standard Client. Your application can receive (subscribe to) and send (publish) messages.

Copy-and-Paste-Ready Code!

See how easy it is to Publish and Subscribe!

Synopsis

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

    /* If you use some other HW, you need to do some other
       initialization of it here... */
    Ethernet.begin(mac);

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */
    Ethernet.maintain();

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`. 
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Upgrading from version 2

The publish() method now returns PubNub's "own" Client compatible class (that is, pointer to an object of said class). It used to return a pointer to the network client class used. In most cases, your sketch will continue to work, only in some special cases (like ESP32), where the implementation of the client class is not actually conforming to the "contract" of the Cient interface, will you need to update to make things work.

BTW, if you used auto instead of naming the class, there will be no need to update.

Same goes for history(), it now returns PubNub's own Client.

But, subscribe() does not need any update, it still returns PubSubClient*.

It is now recommended to use the higher level interface for parsing the response returned from PubNub, which is introduced in version 3.0.0. It is much easier to use. You can still use the "low level" interface, that is, the (only) one that was available in previous versions. So, while no upgrade is required, you will probably benefit from upgrading, in most cases.

Library Reference

bool PubNub.begin(char *publish_key, char *subscribe_key, char *origin)

To start using PubNub, use PubNub.begin(). This should be called after initializing your network hardware (like Ethernet.begin()).

Note that the string parameters are not copied; do not overwrite or free the memory where you stored the keys! (If you are passing string literals, don't worry about it.) Note that you should run only one of publish, subscribe and history requests each at once.

The origin parameter is optional, defaulting to "pubsub.pubnub.com".

PubNonSubClient *publish(char *channel, char *message, int timeout)

Send a message (assumed to be well-formed JSON) to a given channel.

Returns NULL in case of error, otherwise a pointer to an instance of Client-compatible class that you can use to read the response to the publish command. If you don't care about the response, call client->stop() right away.

Since v2.1.0, if Pubnub responds with a HTTP status code indicating a failure, this will not return NULL. Of course, NULL will still be returned for other errors, mostly networking errors like DNS failure, connection failure, etc. If you care, you should check the HTTP status code class, like:

if (PubNub.get_last_http_status_code_class() != PubNub::http_scc_success) {
    Serial.print("Got HTTP status code error from PubNub, class: ");
    Serial.print((int)PubNub.get_last_http_status_code_class(), DEC);
}

The timeout parameter is optional, with a sensible default. See also a note about timeouts below.

To avoid parsing the response, you should use PublishCracker "on" the result of this member function.

PubSubClient *subscribe(char *channel, int timeout)

Listen for a message on a given channel. The function will block and return when message(s) arrive(s) (or timeout expires). NULL is returned in case of error. The return type is PubSubClient, which is Client compatible, but it also provides an extra convenience method wait_for_data() that allows you to wait for more data with sensible timeout.

Typically, you will run this function from loop() function to keep listening for messages indefinitely.

As a reply, if all goes well, you will get a JSON array with messages, e.g.:

    ["msg1",{msg2:"x"}]

and so on. Empty reply ([]) is also normal and your code must be able to handle that - it means no messages were pulished during a time(out) set on the PubNub side. Note that the reply specifically does not include the time token present in the raw reply from PubNub; it is filtered out by PubSubClient.

The timeout parameter is optional, with a sensible default. See also a note about timeouts below.

To avoid parsing the response, you should use SubscribeCracker "on" the result of this member function.

PubNonSubClient *history(char *channel, int limit, int timeout)

Receive list of the last messages published on the given channel. The limit argument is optional and defaults to 10. Keep in mind that PubNub network has its own limit, which was 100 at the time of this writing. Thus, even if you set limit to something higher than that (say 1000) you will not actually get that many messages.

The timeout parameter is optional, with sensible default. See also a note about timeouts below.

Message crackers

These are used to interpret/parse the response from Pubnub, so that you don't have to. Their interface is much easier to use than the "low level" (essentially Client) interface. This parsing is minimal and non-validating, mostly to "tell elements of the response apart", thus they are named "message crackers" (and not "parsers" or "interpreters"), which might make for an interesting piece of nostalgia to users familiar w/WinAPI.

Each API (publish, subscribe...) has its own class, because the format of the PubNub response is different. But, for some groups of classes (APIs), the user interface is essentially the same.

PublishCracker

Just declare an object, call read_and_parse() on it and then use the "getters" to see the parts of the message:

  • outcome(): to see if the publish succeeded or not. For logging, use to_str() to get a string "representation" of the outcome.
  • description(): to get the description of the outcome as returned, in the response, by PubNub
  • timestamp(): to get the string of the timestamp (token) of the moment the publish was executed, as returned by PubNub. In general, this is seldom interesting.
  • state() to see if parsing is complete (done). For logging, use to_str() to get a string "representation" of the state.

If you want more control, you can read the response characters yourself and use handle() to pass them to the parser/cracker, (instead of using read_and_parse()).

SubscribeCracker

Declare an object passing the PubSubClient you got from subscribe(). Then, until parsing is finished(), call get() to obtain the next message in the PubNub response. Keep in mind that one subscribe can yield more than one message in the response, as more than one message might have been published on the channel(s) you are subscribing to between two calls to subscribe().

If you want more control, you can read the characters of the response yourself and use handle() to pass them to the parser/cracker, (instead of using get()).

To read the timetoken that was returned in the PubNub response, use PubNub::server_timetoken(), as the timetoken is filtered by PubSubClient.

HistoryCracker

The usage is essentially the same as SubscribeCracker.

Debug logging

To enable debugg logging to the Arduino console, add

#define PUBNUB_DEBUG

before #include <PubNub.h>

Installation

Since version 1.1.1, Pubnub SDK is part of the Arduino Library Manager and you can use it directly from Arduino IDE (v 1.6.8 or newer).

But, sometimes Arduino online repository for its Library manager takes time to update to new releases of Pubnub SDK, so, you might want to install it manually. To do so, download a release from Arduino SDK on Github and move the contents to your Arduino libraries directory (on Linux, default would be: ~/sketchbook/libraries/PubNub/) and restart your Arduino IDE. Try out the examples!

Keep in mind that if you both install the library via Arduino Library Manager and manually, and the versions mismatch, Arduino IDE will issue warnings like:

Invalid version found: x.y.z

Where x.y.z would be the version ID of the manually installed library. This is just a warning, the build and upload process is not impacted by this.

Supported Hardware

In general, the most widely available Arduino boards and shields are supported and tested. Any Arduino board that has networking hardware that supports a Client compatible class should work. In most cases, they are actually derived from Client, but there are some subtle differences in the base Client as implemented in various libraries.

Since version 3.3, several boards are automatically detected and you don't need to do anything special to use PubNub library on them. For others, you'll have to #define the Pubnub_BASE_CLIENT to the class that you use for networking on your board/shield that has the Client compatible interface before you #include <PubNub.h>.

The Arduino ecosystem features a multitude of platforms that have significant differences regarding their hardware capabilities. Keeping up with all of them is next to impossible.

If you find some Arduino board/shield that does provide an Client compatbile class and it doesn't work with Pubnub library, let us know and we'll make it work. In general, this means that it is not really compatible. Such was the case with ESP32 library.

Also, if you have some Arduino board/shield that doesn't provide an Client compatible class and you want to use Pubnub with it, please let us know.

Arduino Ethernet Shield

For this to work, all you need to do is to include the Ethernet Shield Arduino library and start your sketch with:

#include <EthernetClient>
#include <PubNub.h>

As EthernetClient is the default Pubnub_BASE_CLIENT.

Of course, you also need to initialize the shield and do any maintenance (like DHCP lease).

WiFi (Shield) Support

Whether you are using the older WiFi shield or the Arduino WiFi Shield 101, you will be using the WiFiClient class. Keep in mind that the WiFi101 library is used with other shields/boards (Arduino MKR1000, Adafruit Feather M0 WINC1500...) and that WiFiClient is the name of the client class for most Wifi hardware even if it uses another library.

So, for any WiFi101 compatible hardware, you would:

#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

Of course, please keep in mind that you need to initialize your WiFi hardware, connect to a WiFi network and possibly do some maintenance, which is hardware specific. But, Pubnub SDK has nothing to do with that, it expects a working network. We provide examples for some HW.

ESP8266 and ESP32

ESP8266 and ESP32 are recognized since version 3.3 so can just:

#include <PubNub.h>

It will include ESP8266WiFi.h or WiFi.h (for ESP32) automatically.

In some (older) versions of ESP8266 support for Arduino, some of the (de-facto) standard library functions were missing. To use our own implementation of them, #define a macro constant before you include PubNub.h, like this:

#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP
#include <PubNub.h>

Notes

  • If you #include <PubNub.h>, it will define the global PubNub object in your code. Thus, you can't #include <Pubnub.h> in two or more different files in you project, but only in one file. In all other source files (if you have them) #include <PubNubDefs.h>, which doesn't define the global PubNub object. This shouldn't be much of an inconvenience, as most Arduino projects have only one file - the sketch itself.

  • We don't provide any SSL/TLS support, because of modest resource of most Arduino compatible boards. But, some shields/boards have SSL ("Secure") clients and you may succeed in using them instead of the non-secure clients (WiFiClientSecure instead of WiFiClient). But don't forget to PubNub.set_port(PubNub.tls_port).

  • We re-resolve the origin server IP address before each request. This means some slow-down for intensive communication, but we rather expect light traffic and very long-running sketches (days, months), where refreshing the IP address is quite desirable.

  • We let the users read replies at their leisure instead of returning an already preloaded string so that (a) they can do that in loop() code while taking care of other things as well (b) we don't waste precious RAM by pre-allocating buffers that are never needed.

  • The optional timeout parameter allows you to specify a timeout period after which the subscribe call shall be cancelled. Note that this timeout is applied only for reading response, not for connecting or sending data; use retransmission parameters of the network library to tune this. As a rule of thumb, timeout smaller than 30 seconds may still block longer with flaky network.

  • In general, there may be many issues with different shields and Arduino-compatible boards. A common issue is a firmware bug. Please look to the available info on your shield and board for troubleshooting.

arduino's People

Contributors

girliemac avatar maxpresman avatar pasky avatar per1234 avatar robertinant avatar stephenlb avatar sveljko avatar vveljko 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

arduino's Issues

publishing error on PubNubWifi101.ino using MKR1000 board

Hi

as per title, I'm using MKR1000 board, i can verify and upload the sketch but on serial monitor it pop up publishing error. below is the sketch

#include <SPI.h>
#include <WiFi101.h>
#define PubNub_BASE_CLIENT WiFiClient
#include <PubNub.h>

static char ssid[] = ""; // your network SSID (name)
static char pass[] = "
"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status

const static char pubkey[] = "pub-c-b5092f02-f467-4795-b5ba-97286b6cb961"; //PubNub wifi101 Dev
const static char subkey[] = "sub-c-b60400ce-23f6-11e7-bd07-02ee2ddab7fe";
const static char channel[] = "hello_world";

void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Serial set up");

// attempt to connect using WPA2 encryption:
Serial.println("Attempting to connect to WPA network...");
status = WiFi.begin(ssid, pass);

// if you're not connected, stop here:
if ( status != WL_CONNECTED) {
Serial.println("Couldn't get a wifi connection");
while (true);
} else {
Serial.print("WiFi connecting to SSID: ");
Serial.println(ssid);

PubNub.begin(pubkey, subkey);
Serial.println("PubNub set up");

}
}

void loop() {

/* Publish */

WiFiClient *client;

char msg[] = ""running"";

client = PubNub.publish(channel, msg);

if (!client) {
Serial.println("publishing error");
delay(1000);
return;
}
client->stop();
}

Change request for Pubnub.h to match Adafruit Feather M0

I'm glad to see that you have posted a library modficiation for the Adafruit Feather M0. It's important to note that Adafruit publishes their own Wifi101 equivalent library called Adafruit_WINC1500.h
Fortunately this takes care of all the pin differences and more. Seeing that I am successfully using the Adafruit library already, it gets messy with mismatching later because the Wifi101.h libarary is called in the pubnub.cpp file.

That said, I cannot even get Arduino 1.6.8 to even compile the basic example files. Getting declaration errors relative to WiFi and WiFiClient. Could there be an issue with Arduino IDE versioning requirements?

Regarding SSL Support: The comments below are copied from PubNub.h.
However the Adafruit Feather M0 WINC1500 does support SSL. How do we resolve this?

/* Some notes:
 *
 * (i) There is no SSL support on Arduino, it is unfeasible with
 * Arduino Uno or even Arduino Mega's computing power and memory limits.
 * All the traffic goes on the wire unencrypted and unsigned. 

Can this be better annotated to show exactly which lines needed to be modified? Or better yet create a library that is default for wifi with reference to Adafruit_WINC1500.h , instead of asking the user to change all the ethernet defaults? Less obstacles means easier adoption of PubNub. Hopefully you can help. Thanks

It's just not working.

I am trying to make it work to wait for message and every some time to go and send a message

It's waiting and after is not coming out properly and unable to wait again for the messages

The support told me that they are not dealing with it since 2019. Really disappointed.

Support for own instantiated client or possibility to execute client method before publish

Hello, I started using PubNub for my new arduino (on ESP8266) but I want to publish messages by GPRS with SIM800 module. I'm using TinyGSM lib for other things like reading/sending sms'es etc.

TinyGSM provides TinyGsmClient class that can be used as PubNub_BASE_CLIENT but there is small problem. TinyGsmClient class require existing TinyGsm passed into constructor or as parameter of init method (if used prameterless constructor). PubNub_BASE_CLIENT is instantiated inside PubNub class and I have no possibility to pass constructor paramters or execute init method before publish.

Will it be possible to do something on PubNub_BASE_CLIENT before publish? Or better provide own instance of PubNub_BASE_CLIENT.

Now I have workaround for this by publish messages using PubNub http api with this example:
https://github.com/vshymanskyy/TinyGSM/blob/master/examples/HttpClient/HttpClient.ino

Set device publisher name

Hey,
I tried setting up an arduino which publishes some messages to an node js server, but I cannot get an publisher name out of it. I searched the docs and found nothing really useful. I set an uuid before the PubNub begin with ( PubNub.set_uuid(uuid); ), but it had no effect. The Application just returns an undefined. How can I set this up?

Thanks for help

Typo in header file about enabling WiFi

I tried to push the fix myself, but I guess I don't have the permissions. Anyways, it should read like the following:

/* By default, the PubNub library is built to work with the Ethernet
 * shield. WiFi shield support can be enabled by commenting out the
 * following line and uncommenting the line after that. Refer
 * to the PubNubJsonWifi sketch for a complete example. */

Not obvious how to set up 2 authorisaton keys for 2 channels within 1 client

I might have misunderstood how things work, so apologies if that's the case.

I am using the Pubnub's Debug Console as my guide. Here I can set up individual authorisation keys for different channels.

Within the Arduino library code there is set_auth(const char* auth) { d_auth = auth; }

but this sets up an authorization key/token for a PubNub client.

How can the code/library be changed so that a separate auth key can be used for publish and subscribe.

Sample Sketch doesn't compile due to code error

The latest sample sketch doesn't compile due to a number of issues. The first issue is in line 17 of the PubNubWifi101 sketch -
#define Pubnub_BASE_CLIENT WiFiClient
In <PubNub.h>, it is expecting the #define to be
#define PubNub_BASE_CLIENT EthernetClient
-- note that Pubnub and PubNub have different cases.

There are other errors too, and tons of warnings.
I have tried the other examples, none of them compile. There are undefined references to various string compare functions.

I'm using Arduino 1.6.13 on Ubuntu 14.04. The PubNub libraries and sample sketches were obtained today from GitHub.

On publish using ESP86, board crashes

As I mentioned in the ticket #15 the addition of the provided code to PubNubDefs.h and I see my messages get published once. Thanks! However, upon publishing, the Adafruit Feather ESP8266 seems to be crashing. As soon as it publishes, i see the message come in on the pubnub dashboard I see an Exception(3) in the serial port of the Arduino IDE. The full error output from the serial is below. Any ideas as to what might be causing the issue? Or a potential area that might be causing the problem?

The code I added to PubNubDefs.h was placed at the end of the script after the #endif on line # 692

The message I'm posting is: "{num:1, txt:'Yo!'}"

Beginning of loop...
Exception (3):
epc1=0x40201e66 epc2=0x00000000 epc3=0x00000000 excvaddr=0x4023004c depc=0x00000000

ctx: cont 
sp: 3ffef3c0 end: 3ffef720 offset: 01a0

\>>>stack>>>
3ffef560:  40105244 0055ec10 00005419 40201e29  
3ffef570:  65746144 6f4d203a 33202c6e 614a2030  
3ffef580:  3032206e 30203731 36333a32 3ffee700  
3ffef590:  00000000 00001388 00000044 00000036  
3ffef5a0:  0000001c 00000004 3fff0bfc 40202e7a  
3ffef5b0:  00000000 3ffee554 3ffee568 3ffef634  
3ffef5c0:  00000000 3ffee554 3ffee568 402024a8  
3ffef5d0:  00463625 00000006 3ffef6e8 40203671  
3ffef5e0:  00005419 3ffe85af 3ffef620 0000001e  
3ffef5f0:  3ffef634 3ffee550 3ffef6e8 402036bc  
3ffef600:  3ffe8565 000001f4 3ffee6c0 3ffee6ec  
3ffef610:  000000c8 3ffee550 3ffee6c0 4020257b  
3ffef620:  756e7b22 2c313a6d 74787420 6f59273a  
3ffef630:  227d2721 fee4f000 fe83543f 3430313f  
3ffef640:  fee4c400 202b2d3f fe84c540 0000003f  
3ffef650:  00000009 4affffff 77616853 00302e32  
3ffef660:  feefeffe feefeffe feefeffe 3ffef6f0  
3ffef670:  3ffee6c0 00000009 00000003 40203456  
3ffef680:  00216b72 00000001 3ffe8489 40203ba0  
3ffef690:  00000000 0000000c 3ffe84d4 3ffee6ec  
3ffef6a0:  3ffe86df 0000000d 3ffee6c0 40203339  
3ffef6b0:  3ffe8488 3ffee5d0 3ffee6c0 40203339  
3ffef6c0:  3ffe84c8 3ffee5d0 3ffee6c0 40203364  
3ffef6d0:  680010ac 00ffffff 3ffee6c0 40203388  
3ffef6e0:  3ffe8350 3ffee5d0 3fff0d2c 0000001f  
3ffef6f0:  00000014 680010ac feefeffe feefeffe  
3ffef700:  3fffdad0 00000000 3ffee6e4 4020385c  
3ffef710:  feefeffe feefeffe 3ffee700 40100718  
<<<stack<<<

 ets Jan  8 2013,rst cause:2, boot mode:(1,6)


 ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset

Thanks,

Arduino Yun

Hi
How I can use this library with Arduino Yùn board, do you hav an example?
Thanks
Luigi

Support for ESP8266

It would be fantastic if this library was supported on the ESP8266 microcontroller. The ESP8266 Arduino environment provides a WiFiClient that is derived from the Arduino's Client class so it shouldn't be a huge effort to support it.

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.