├── .gitignore ├── LICENSE ├── README.md ├── examples ├── publish │ └── publish.ino ├── publishNonBlocking │ └── publishNonBlocking.ino ├── subscribe │ └── subscribe.ino └── subscribe_and_publish │ └── subscribe_and_publish.ino ├── keywords.txt ├── library.properties └── src ├── UbidotsESPMQTT.cpp └── UbidotsESPMQTT.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Object files 2 | *.o 3 | *.ko 4 | *.obj 5 | *.elf 6 | 7 | # Precompiled Headers 8 | *.gch 9 | *.pch 10 | 11 | # Libraries 12 | *.lib 13 | *.a 14 | *.la 15 | *.lo 16 | 17 | # Shared objects (inc. Windows DLLs) 18 | *.dll 19 | *.so 20 | *.so.* 21 | *.dylib 22 | 23 | # Executables 24 | *.exe 25 | *.out 26 | *.app 27 | *.i*86 28 | *.x86_64 29 | *.hex 30 | 31 | # Debug files 32 | *.dSYM/ 33 | *.su 34 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Ubidots 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ubidots-mqtt-esp 2 | 3 | MQTT library for connecting to Ubidots using MQTT protocol and an ESP8266 chip. 4 | 5 | ## Setup 6 | 7 | 1. Go to the Arduino IDE, click on Files -> Preferences and enter http://arduino.esp8266.com/stable/package_esp8266com_index.json into Additional Board Manager URLs field. You can add multiple URLs, separating them with commas 8 | 2. Open Boards Manager from Tools -> Board menu and install esp8266 platform (and don’t forget to select your ESP8266 board from Tools > Board menu after installation) 9 | 3. Download this library as .zip 10 | 4. Now, click on Sketch -> Include Library -> Add .ZIP Library 11 | 5. Select the .ZIP file that you have just downloaded and then “Accept” or “Choose” 12 | 6. Go to Sketch/Program -> Include Library -> Library Manager and install the PubSubClient library 13 | 7. Close the Arduino IDE and open it again. 14 | 8. If you are using windows, please install the appropiate driver for your ESP board (CH340G if you are using a LoLin board or CP2102 if you are using an AMICA board) 15 | 16 | # Documentation 17 | 18 | ## Constructor 19 | 20 | ### Ubidots 21 | 22 | `Ubidots(char* token)` 23 | `Ubidots(char* token, char* clientName)` 24 | Creates an Ubidots instance, you must setup as input your Ubidots TOKEN, the MQTT client name is optional and must be unique so we recommend you to insert random ASCII characters if you decide to use it, if you don't pass the clientName as parameter to the constructor the library will try to get the MAC of the device as default client name. 25 | 26 | - @token, [Required]. Your Ubidots unique account [TOKEN](http://help.ubidots.com/user-guides/find-your-token-from-your-ubidots-account). 27 | - @clientName, [Optional] [default] = device unique MAC address. The MQTT unique client id to be identified by the broker. 28 | ## Methods 29 | 30 | ### Ubidots 31 | 32 | `add(char* variableLabel, float value, char *context, char *timestamp)` 33 | Add a variable with a value, context and timestamp to be sent to a certain data source, once you use add() you can publish your variable using the ubidotsPublish() method. You can add 5 variables maximum before of publish them. 34 | **Important:** As this library depends on a Pubsubclient client, the max length of the JSON dictionary to send by default is 128 bytes, if you want to publish more than 3 variables and they have context or long names you should set at PubSubclient.h the MQTT_MAX_PACKET_SIZE to 512, you can see on your serial console the dictionary to POST if you call the ```setDebug(bool debug)``` method and pass a true value to it. For more information, refer to the PubSubclient official library: https://github.com/knolleary/pubsubclient 35 | 36 | - @variable_label, [Required]. The label of the variable where the dot will be stored. 37 | - @value, [Required]. The value of the dot. 38 | - @context, [Optional]. The dot's context. 39 | - @timestamp, [Optional]. The dot's timestamp in milliseconds. 40 | 41 | `begin(void (*callback)(char*,uint8_t*,unsigned int))` 42 | Sets the callback function for subscribed topics 43 | 44 | - @callback [Mandatory] Pointer to the callback function that will process the incoming data 45 | 46 | `connected()` 47 | Returns True if the device is connected to the MQTT broker 48 | 49 | `loop()` 50 | Infinite loop for MQTT connection, insert it at the end of your routine 51 | 52 | `reconnect()` 53 | For trying to make a reconnection every 5 seconds if the connection is lost. 54 | 55 | `ubidotsSetBroker(char* broker)` 56 | Sets the broker properly for publish and subscribe to Ubidots accounts. If your account if a business one, set "business.api.ubidots.com" or the endpoint provided by Ubidots as your broker, see examples for more information. 57 | By default, broker will be set to publish and subscribe to free educational version accounts with broker "things.ubidots.com". 58 | 59 | - @broker, [Optional] [default] = `industrial.api.ubidots.com`. The server to send data url. 60 | 61 | `setDebug(bool debug)` 62 | Make available debug messages through the serial port. 63 | 64 | `ubidotsPublish(char *deviceLabel)` 65 | Publishes the variables added to the specified device label. 66 | - @deviceLabel [Mandatory] Device label that stores the the values to be ingested 67 | 68 | `ubidotsSubscribe(char* deviceLabel, char* variableLabel)` 69 | Subscribe to the specified device label and variable label of your Ubidots account. 70 | 71 | - @deviceLabel [Mandatory] Device label that stores the variable to retrieve values from 72 | - @variableLabel [Mandatory] Variable label to retrieve values from 73 | 74 | `bool connect(const char* clientName, const char* username, const char* password)` 75 | Connects to the broker using a custom client name, username and password 76 | 77 | - @clientName, [Optional] [default] = device unique MAC address. The MQTT unique client id to be identified by the broker. 78 | - @username, [optional] [default] = Ubidots account token used in the constructor. The username to be identified by the broker 79 | - @password, [optional] [default] = Ubidots account token used in the constructor. The password to be identified by the broker 80 | 81 | `void wifiConnection(char* ssid, char* pass)` 82 | Connects to an available WiFi network using WAP2. 83 | 84 | - @ssid [Mandatory] SSID of the network to connect to 85 | - @pass [Mandatory] WiFi network password 86 | 87 | `void disconnect()` 88 | Disconnects gracefully from the broker, closing the socket 89 | 90 | 91 | # Examples 92 | 93 | Please refer to examples folder. 94 | -------------------------------------------------------------------------------- /examples/publish/publish.ino: -------------------------------------------------------------------------------- 1 | /****************************************** 2 | * 3 | * This example works for both Industrial and STEM users. 4 | * If you are using the old educational platform, 5 | * please consider to migrate your account to a STEM plan 6 | * 7 | * Developed by Jose Garcia, https://github.com/jotathebest/ 8 | * 9 | * ****************************************/ 10 | 11 | /**************************************** 12 | * Include Libraries 13 | ****************************************/ 14 | #include "UbidotsESPMQTT.h" 15 | 16 | /**************************************** 17 | * Define Constants 18 | ****************************************/ 19 | #define TOKEN "....." // Your Ubidots TOKEN 20 | #define WIFINAME "....." // Your SSID 21 | #define WIFIPASS "....." // Your Wifi Pass 22 | 23 | Ubidots client(TOKEN); 24 | 25 | /**************************************** 26 | * Auxiliar Functions 27 | ****************************************/ 28 | 29 | void callback(char* topic, byte* payload, unsigned int length) { 30 | Serial.print("Message arrived ["); 31 | Serial.print(topic); 32 | Serial.print("] "); 33 | for (int i = 0; i < length; i++) { 34 | Serial.print((char)payload[i]); 35 | } 36 | Serial.println(); 37 | } 38 | 39 | /**************************************** 40 | * Main Functions 41 | ****************************************/ 42 | 43 | void setup() { 44 | // put your setup code here, to run once: 45 | Serial.begin(115200); 46 | client.setDebug(true); // Pass a true or false bool value to activate debug messages 47 | client.wifiConnection(WIFINAME, WIFIPASS); 48 | client.begin(callback); 49 | } 50 | 51 | void loop() { 52 | // put your main code here, to run repeatedly: 53 | if (!client.connected()) { 54 | client.reconnect(); 55 | } 56 | 57 | // Publish values to 2 different data sources 58 | 59 | client.add("stuff", 10.2); // Insert your variable Labels and the value to be sent 60 | client.ubidotsPublish("source1"); 61 | client.add("stuff", 10.2); 62 | client.add("more-stuff", 120.2); 63 | client.ubidotsPublish("source2"); 64 | client.loop(); 65 | delay(5000); 66 | } 67 | -------------------------------------------------------------------------------- /examples/publishNonBlocking/publishNonBlocking.ino: -------------------------------------------------------------------------------- 1 | /****************************************** 2 | * 3 | * This example works for both Industrial and STEM users. 4 | * If you are using the old educational platform, 5 | * please consider to migrate your account to a STEM plan 6 | * 7 | * Developed by Jose Garcia, https://github.com/jotathebest/ 8 | * 9 | * ****************************************/ 10 | 11 | /**************************************** 12 | * Include Libraries 13 | ****************************************/ 14 | #include "UbidotsESPMQTT.h" 15 | 16 | /**************************************** 17 | * Define Constants 18 | ****************************************/ 19 | #define TOKEN "...." // Your Ubidots TOKEN 20 | #define WIFINAME "...." // Your SSID 21 | #define WIFIPASS "...." // Your Wifi Pass 22 | 23 | Ubidots client(TOKEN); 24 | 25 | /**************************************** 26 | * Auxiliar Functions 27 | ****************************************/ 28 | 29 | void callback(char* topic, byte* payload, unsigned int length) { 30 | Serial.print("Message arrived ["); 31 | Serial.print(topic); 32 | Serial.print("] "); 33 | for (int i = 0; i < length; i++) { 34 | Serial.print((char)payload[i]); 35 | } 36 | Serial.println(); 37 | } 38 | 39 | /**************************************** 40 | * Auxiliar variables 41 | ****************************************/ 42 | 43 | bool connected = false; 44 | 45 | /**************************************** 46 | * Main Functions 47 | ****************************************/ 48 | 49 | void setup() { 50 | // put your setup code here, to run once: 51 | Serial.begin(115200); 52 | client.setDebug(true); // Pass a true or false bool value to activate debug messages 53 | client.wifiConnection(WIFINAME, WIFIPASS); 54 | client.begin(callback); 55 | } 56 | 57 | void loop() { 58 | // put your main code here, to run repeatedly: 59 | connected = client.connected(); 60 | if (!connected) { 61 | Serial.println("Not connected, attempting to connect ..."); 62 | connected = client.connect(); 63 | } 64 | 65 | // Publish values to 2 different data sources 66 | 67 | if (connected) { 68 | client.add("stuff", 10.2); // Insert your variable Labels and the value to be sent 69 | client.ubidotsPublish("source1"); 70 | client.add("stuff", 10.2); 71 | client.add("more-stuff", 120.2); 72 | client.ubidotsPublish("source2"); 73 | client.loop(); 74 | } 75 | delay(5000); 76 | } 77 | -------------------------------------------------------------------------------- /examples/subscribe/subscribe.ino: -------------------------------------------------------------------------------- 1 | /****************************************** 2 | * 3 | * This example works for both Industrial and STEM users. 4 | * If you are using the old educational platform, 5 | * please consider to migrate your account to a STEM plan 6 | * 7 | * Developed by Jose Garcia, https://github.com/jotathebest/ 8 | * 9 | * ****************************************/ 10 | 11 | /**************************************** 12 | * Include Libraries 13 | ****************************************/ 14 | #include "UbidotsESPMQTT.h" 15 | 16 | /**************************************** 17 | * Define Constants 18 | ****************************************/ 19 | #define TOKEN "....." // Your Ubidots TOKEN 20 | #define WIFINAME "....." // Your SSID 21 | #define WIFIPASS "....." // Your Wifi Pass 22 | 23 | Ubidots client(TOKEN); 24 | 25 | /**************************************** 26 | * Auxiliar Functions 27 | ****************************************/ 28 | 29 | void callback(char* topic, byte* payload, unsigned int length) { 30 | Serial.print("Message arrived ["); 31 | Serial.print(topic); 32 | Serial.print("] "); 33 | for (int i = 0; i < length; i++) { 34 | Serial.print((char)payload[i]); 35 | } 36 | Serial.println(); 37 | } 38 | 39 | /**************************************** 40 | * Main Functions 41 | ****************************************/ 42 | 43 | void setup() { 44 | // put your setup code here, to run once: 45 | Serial.begin(115200); 46 | client.setDebug(true); // Pass a true or false bool value to activate debug messages 47 | client.wifiConnection(WIFINAME, WIFIPASS); 48 | client.begin(callback); 49 | client.ubidotsSubscribe("esp8266", "temperature"); // Insert the dataSource and Variable's Labels 50 | } 51 | 52 | void loop() { 53 | // put your main code here, to run repeatedly: 54 | if (!client.connected()) { 55 | client.reconnect(); 56 | client.ubidotsSubscribe("esp8266", "temperature"); // Insert the dataSource and Variable's Labels 57 | } 58 | client.loop(); 59 | delay(5000); 60 | } 61 | -------------------------------------------------------------------------------- /examples/subscribe_and_publish/subscribe_and_publish.ino: -------------------------------------------------------------------------------- 1 | /****************************************** 2 | * 3 | * This example works for both Industrial and STEM users. 4 | * If you are using the old educational platform, 5 | * please consider to migrate your account to a STEM plan 6 | * 7 | * Developed by Jose Garcia, https://github.com/jotathebest/ 8 | * 9 | * ****************************************/ 10 | 11 | /**************************************** 12 | * Include Libraries 13 | ****************************************/ 14 | #include "UbidotsESPMQTT.h" 15 | 16 | /**************************************** 17 | * Define Constants 18 | ****************************************/ 19 | #define TOKEN "....." // Your Ubidots TOKEN 20 | #define WIFINAME "....." // Your SSID 21 | #define WIFIPASS "....." // Your Wifi Pass 22 | 23 | Ubidots client(TOKEN); 24 | 25 | /**************************************** 26 | * Auxiliar Functions 27 | ****************************************/ 28 | 29 | void callback(char* topic, byte* payload, unsigned int length) { 30 | Serial.print("Message arrived ["); 31 | Serial.print(topic); 32 | Serial.print("] "); 33 | for (int i = 0; i < length; i++) { 34 | Serial.print((char)payload[i]); 35 | } 36 | if ((char)payload[0] == '1') { 37 | digitalWrite(16, HIGH); 38 | } else { 39 | digitalWrite(16, LOW); 40 | } 41 | Serial.println(); 42 | } 43 | 44 | /**************************************** 45 | * Main Functions 46 | ****************************************/ 47 | 48 | void setup() { 49 | // put your setup code here, to run once: 50 | Serial.begin(115200); 51 | client.setDebug(true); // Pass a true or false bool value to activate debug messages 52 | client.wifiConnection(WIFINAME, WIFIPASS); 53 | client.begin(callback); 54 | pinMode(16, OUTPUT); 55 | client.ubidotsSubscribe("esp8266", "temperature"); // Insert the dataSource and Variable's Labels 56 | } 57 | 58 | void loop() { 59 | // put your main code here, to run repeatedly: 60 | if (!client.connected()) { 61 | client.reconnect(); 62 | client.ubidotsSubscribe("esp8266", "temperature"); // Insert the dataSource and Variable's Labels 63 | } 64 | client.add("stuff", 10); 65 | client.ubidotsPublish("source1"); 66 | client.loop(); 67 | delay(5000); 68 | } 69 | -------------------------------------------------------------------------------- /keywords.txt: -------------------------------------------------------------------------------- 1 | ####################################### 2 | # Syntax Coloring Map For ExampleLibrary 3 | ####################################### 4 | 5 | ####################################### 6 | # Datatypes (KEYWORD1) 7 | ####################################### 8 | 9 | ####################################### 10 | # Methods and Functions (KEYWORD2) 11 | ####################################### 12 | 13 | add KEYWORD2 14 | begin KEYWORD2 15 | connected KEYWORD2 16 | loop KEYWORD2 17 | ubidotsPublish KEYWORD2 18 | ubidotsSubscribe KEYWORD2 19 | ubidotsSetBroker KEYWORD2 20 | reconnect KEYWORD2 21 | setDebug KEYWORD2 22 | wifiConnection KEYWORD2 23 | connect KEYWORD2 24 | disconnect KEYWORD2 25 | 26 | ####################################### 27 | # Instances (KEYWORD2) 28 | ####################################### 29 | 30 | ####################################### 31 | # Constants (LITERAL1) 32 | ####################################### 33 | -------------------------------------------------------------------------------- /library.properties: -------------------------------------------------------------------------------- 1 | name=Ubidots MQTT for ESP8266 2 | version=1.2 3 | author=Jose García , Mateo Velez 4 | maintainer=Jose García 5 | sentence=Library for sending data to the Ubidots cloud using ESP8266 based systems 6 | paragraph=Library for sending data to the Ubidots cloud using ESP8266 based systems 7 | category=Other 8 | url=https://github.com/ubidots/ubidots-mqtt-esp 9 | architectures=* 10 | depends=PubSubClient 11 | -------------------------------------------------------------------------------- /src/UbidotsESPMQTT.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2021 Ubidots. 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | The above copyright notice and this permission notice shall be 11 | included in all copies or substantial portions of the Software. 12 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 13 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 14 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 15 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 16 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 17 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 18 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 19 | Created by: Jose Garcia 20 | */ 21 | 22 | /************************************************************************** 23 | * Overloaded constructors 24 | ***************************************************************************/ 25 | 26 | #include "UbidotsESPMQTT.h" 27 | 28 | Ubidots::Ubidots(char* token) { 29 | String _deviceMac = WiFi.macAddress(); 30 | _clientName = new char[_deviceMac.length() + 1]; 31 | strcpy(_clientName, _deviceMac.c_str()); 32 | initialize(token, _clientName); 33 | } 34 | 35 | Ubidots::Ubidots(char* token, char* clientName) { initialize(token, clientName); } 36 | 37 | /*************************************************************************** 38 | FUNCTIONS TO SEND/RETRIEVE DATA 39 | ***************************************************************************/ 40 | 41 | bool Ubidots::ubidotsSubscribe(char* deviceLabel, char* variableLabel) { 42 | char topic[150]; 43 | sprintf(topic, "%s%s/%s/lv", FIRST_PART_TOPIC, deviceLabel, variableLabel); 44 | if (!_client.connected()) { 45 | reconnect(); 46 | } 47 | if (_debug) { 48 | Serial.println("Subscribed to: "); 49 | Serial.println(topic); 50 | } 51 | return _client.subscribe(topic); 52 | } 53 | 54 | bool Ubidots::ubidotsPublish(char* deviceLabel) { 55 | char topic[150]; 56 | char payload[500]; 57 | String str; 58 | sprintf(topic, "%s%s", FIRST_PART_TOPIC, deviceLabel); 59 | sprintf(payload, "{"); 60 | for (int i = 0; i <= currentValue;) { 61 | str = String((val + i)->_value, 2); 62 | sprintf(payload, "%s\"%s\": [{\"value\": %s", payload, (val + i)->_variableLabel, str.c_str()); 63 | if ((val + i)->_timestamp != "NULL") { 64 | sprintf(payload, "%s, \"timestamp\": %s", payload, (val + i)->_timestamp); 65 | } 66 | if ((val + i)->_context != "NULL") { 67 | sprintf(payload, "%s, \"context\": {%s}", payload, (val + i)->_context); 68 | } 69 | i++; 70 | if (i >= currentValue) { 71 | sprintf(payload, "%s}]}", payload); 72 | break; 73 | } else { 74 | sprintf(payload, "%s}], ", payload); 75 | } 76 | } 77 | if (_debug) { 78 | Serial.println("publishing to TOPIC: "); 79 | Serial.println(topic); 80 | Serial.print("JSON dict: "); 81 | Serial.println(payload); 82 | } 83 | currentValue = 0; 84 | return _client.publish(topic, payload, 512); 85 | } 86 | 87 | /*************************************************************************** 88 | FUNCTIONS TO MANAGE SOCKET CONNECTION 89 | ***************************************************************************/ 90 | 91 | /** 92 | * Overloaded connect() methods. 93 | * Connects to the broker using a custom username and password 94 | * @arg clientName [Optional] Unique MQTT client id 95 | * @arg username [Mandatory] MQTT username to be identified by the broker 96 | * @arg password [Mandatory] MQTT password to be identified by the broker 97 | */ 98 | bool Ubidots::connect() { return connect(_clientName, _token, _token); } 99 | bool Ubidots::connect(const char* username, const char* password) { return connect(_clientName, username, password); } 100 | bool Ubidots::connect(const char* clientName, const char* username, const char* password) { 101 | bool result = _client.connect(clientName, username, password); 102 | if (_debug) { 103 | Serial.println("attempting to connect"); 104 | if (!result) { 105 | Serial.print("failed, rc="); 106 | Serial.print(_client.state()); 107 | } 108 | } 109 | return result; 110 | } 111 | 112 | bool Ubidots::connected() { return _client.connected(); } 113 | 114 | /** 115 | * Maintains the socket connection and sends periodically the keep alive command 116 | */ 117 | 118 | bool Ubidots::loop() { 119 | if (!_client.connected()) { 120 | reconnect(); 121 | } 122 | return _client.loop(); 123 | } 124 | 125 | /** 126 | * Disconnects gracefully from the broker, closing the socket 127 | */ 128 | void Ubidots::disconnect() { _client.disconnect(); }; 129 | 130 | /*************************************************************************** 131 | AUXILIAR FUNCTIONS 132 | ***************************************************************************/ 133 | 134 | /** 135 | * Add a value of variable to save 136 | * @arg variable_label [Mandatory] variable label where the dot will be stored 137 | * @arg value [Mandatory] Dot value 138 | * @arg context [optional] Dot context to store. Default NULL 139 | * @arg dot_timestamp_seconds [optional] Dot timestamp in seconds, usefull for 140 | * datalogger. Default NULL 141 | */ 142 | 143 | bool Ubidots::add(char* variableLabel, float value) { return add(variableLabel, value, "NULL", "NULL"); } 144 | 145 | bool Ubidots::add(char* variableLabel, float value, char* context) { 146 | return add(variableLabel, value, context, "NULL"); 147 | } 148 | 149 | bool Ubidots::add(char* variableLabel, float value, char* context, char* timestamp) { 150 | (val + currentValue)->_variableLabel = variableLabel; 151 | (val + currentValue)->_value = value; 152 | (val + currentValue)->_context = context; 153 | (val + currentValue)->_timestamp = timestamp; 154 | currentValue++; 155 | if (currentValue > MAX_VALUES) { 156 | Serial.println(F("You are sending more than the maximum of consecutive variables")); 157 | currentValue = MAX_VALUES; 158 | } 159 | return true; 160 | } 161 | 162 | void Ubidots::begin(void (*callback)(char*, uint8_t*, unsigned int)) { 163 | this->callback = callback; 164 | Serial.println("Client name is: "); 165 | Serial.println(_clientName); 166 | if (strcmp(_clientName, "00:00:00:00:00:00") == 0) { 167 | String _deviceMac = WiFi.macAddress(); 168 | strcpy(_clientName, _deviceMac.c_str()); 169 | Serial.println("Empty client name, using device MAC as client name"); 170 | } 171 | _client.setServer(_server, MQTT_PORT); 172 | _client.setCallback(callback); 173 | } 174 | 175 | void Ubidots::initialize(char* token, char* clientName) { 176 | _server = SERVER; 177 | _token = token; 178 | currentValue = 0; 179 | val = (Value*)malloc(MAX_VALUES * sizeof(Value)); 180 | _clientName = clientName; 181 | } 182 | 183 | void Ubidots::reconnect() { 184 | while (!_client.connected()) { 185 | Serial.print("Attempting MQTT connection..."); 186 | if (_client.connect(_clientName, _token, NULL)) { 187 | Serial.println("connected"); 188 | break; 189 | } else { 190 | Serial.print("failed, rc="); 191 | Serial.print(_client.state()); 192 | Serial.println(" try again in 3 seconds"); 193 | delay(3000); 194 | } 195 | } 196 | } 197 | 198 | void Ubidots::setDebug(bool debug) { _debug = debug; } 199 | 200 | void Ubidots::ubidotsSetBroker(char* broker) { 201 | if (_debug) { 202 | Serial.println("Broker set for Business Account"); 203 | } 204 | _server = broker; 205 | } 206 | 207 | bool Ubidots::wifiConnection(char* ssid, char* pass) { 208 | WiFi.begin(ssid, pass); 209 | while (WiFi.status() != WL_CONNECTED) { 210 | delay(500); 211 | Serial.print("."); 212 | } 213 | Serial.println(F("WiFi connected")); 214 | Serial.println(F("IP address: ")); 215 | Serial.println(WiFi.localIP()); 216 | return true; 217 | } 218 | -------------------------------------------------------------------------------- /src/UbidotsESPMQTT.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (c) 2016 Ubidots. 3 | 4 | Permission is hereby granted, free of charge, to any person obtaining 5 | a copy of this software and associated documentation files (the 6 | "Software"), to deal in the Software without restriction, including 7 | without limitation the rights to use, copy, modify, merge, publish, 8 | distribute, sublicense, and/or sell copies of the Software, and to 9 | permit persons to whom the Software is furnished to do so, subject to 10 | the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 17 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 19 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 20 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 21 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 22 | 23 | Original Maker: Mateo Velez - Metavix for Ubidots Inc 24 | Modified by: Jose Garcia 25 | 26 | */ 27 | 28 | #ifndef UbidotsESPMQTT_H 29 | #define UbidotsESPMQTT_H 30 | #include 31 | 32 | #include "PubSubClient.h" 33 | #include "string.h" 34 | 35 | #define MQTT_PORT 1883 36 | #define SERVER "industrial.api.ubidots.com" 37 | #define MAX_VALUES 5 38 | #define FIRST_PART_TOPIC "/v1.6/devices/" 39 | #define DEFAULT_DEVICE_LABEL "ESP8266" 40 | 41 | #define META_DEBUG Serial 42 | 43 | typedef struct Value { 44 | char* _variableLabel; 45 | float _value; 46 | char* _context; 47 | char* _timestamp; 48 | } Value; 49 | 50 | class Ubidots { 51 | private: 52 | void (*callback)(char*, uint8_t*, unsigned int); 53 | void initialize(char* token, char* clientName); 54 | WiFiClient espClient; 55 | PubSubClient _client = PubSubClient(espClient); 56 | char* _clientName; 57 | bool _debug = false; 58 | uint8_t currentValue; 59 | char* _password; 60 | char* _server; 61 | char* _ssid; 62 | char* _token; 63 | Value* val; 64 | 65 | public: 66 | Ubidots(char* token); 67 | Ubidots(char* token, char* clientName); 68 | bool add(char* variableLabel, float value); 69 | bool add(char* variableLabel, float value, char* context); 70 | bool add(char* variableLabel, float value, char* context, char* timestamp); 71 | void begin(void (*callback)(char*, uint8_t*, unsigned int)); 72 | bool connected(); 73 | bool connect(); 74 | bool connect(const char* username, const char* password); 75 | bool connect(const char* clientName, const char* username, const char* password); 76 | void disconnect(); 77 | bool loop(); 78 | bool ubidotsSubscribe(char* deviceLabel, char* variableLabel); 79 | bool ubidotsPublish(char* deviceLabel); 80 | void ubidotsSetBroker(char* broker); 81 | void reconnect(); 82 | void setDebug(bool debug); 83 | bool wifiConnection(char* ssid, char* pass); 84 | }; 85 | 86 | #endif 87 | --------------------------------------------------------------------------------