├── .buildpath ├── .gitignore ├── .project ├── CONTRIBUTING.md ├── README.md ├── about.html ├── edl-v10 ├── epl-v10 ├── example ├── example_00.lua ├── example_01.lua ├── example_02.lua ├── mqtt_publish.lua ├── mqtt_subscribe.lua └── mqtt_test.lua ├── notice.html ├── paho ├── mqtt.lua └── utility.lua └── rocks └── paho-mqtt-0.3.0-1.rockspec /.buildpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.rock 2 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | org.eclipse.paho.mqtt.lua 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.dltk.core.scriptbuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.ldt.nature 16 | 17 | 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing to Paho 2 | ==================== 3 | 4 | Thanks for your interest in this project. 5 | 6 | Project description: 7 | -------------------- 8 | 9 | The Paho project has been created to provide scalable open-source implementations of open and standard messaging protocols aimed at new, existing, and emerging applications for Machine-to-Machine (M2M) and Internet of Things (IoT). 10 | Paho reflects the inherent physical and cost constraints of device connectivity. Its objectives include effective levels of decoupling between devices and applications, designed to keep markets open and encourage the rapid growth of scalable Web and Enterprise middleware and applications. Paho is being kicked off with MQTT publish/subscribe client implementations for use on embedded platforms, along with corresponding server support as determined by the community. 11 | 12 | - https://projects.eclipse.org/projects/technology.paho 13 | 14 | Developer resources: 15 | -------------------- 16 | 17 | Information regarding source code management, builds, coding standards, and more. 18 | 19 | - https://projects.eclipse.org/projects/technology.paho/developer 20 | 21 | Contributor License Agreement: 22 | ------------------------------ 23 | 24 | Before your contribution can be accepted by the project, you need to create and electronically sign the Eclipse Foundation Contributor License Agreement (CLA). 25 | 26 | - http://www.eclipse.org/legal/CLA.php 27 | 28 | Contact: 29 | -------- 30 | 31 | Contact the project developers via the project's "dev" list. 32 | 33 | - https://dev.eclipse.org/mailman/listinfo/paho-dev 34 | 35 | Search for bugs: 36 | ---------------- 37 | 38 | This project uses Bugzilla to track ongoing development and issues. 39 | 40 | - https://bugs.eclipse.org/bugs/buglist.cgi?product=Paho 41 | 42 | Create a new bug: 43 | ----------------- 44 | 45 | Be sure to search for existing bugs before you create another one. Remember that contributions are always welcome! 46 | 47 | - https://bugs.eclipse.org/bugs/enter_bug.cgi?product=Paho 48 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MQTT-v3.1.1 client library in Lua 2 | ------- 3 | 4 | This project is a fork of 5 | [Eclipse Paho project](http://eclipse.org/paho) Lua library. 6 | 7 | This README file is outdated for this project and will be updated soon. 8 | 9 | Contents 10 | -------- 11 | - [Introduction](#introduction) 12 | - [Protocol implementation and restrictions](#restrictions) 13 | - [Download](#download) 14 | - [Feedback and issues](#feedback) 15 | - [Installation](#installation) 16 | - [Usage](#usage) 17 | - [Example code](#example) 18 | - [Library API](#api) 19 | - [Known problems](#problems) 20 | 21 | 22 | Introduction 23 | ------------ 24 | This project provides a partial client-side implementation of the [MQTT protocol](http://mqtt.org), 25 | plus command-line utilities for publishing and subscribing to MQTT topics. Typically, one or more MQTT servers (brokers), such as 26 | [mosquitto](http://mosquitto.org) will be running on host systems, with which the Lua MQTT client can interact. 27 | 28 | MQTT stands for "Message Queue Telemetry Transport", a protocol authored by 29 | [Dr. Andy Stanford-Clark](http://wikipedia.org/wiki/Andy_Stanford-Clark) 30 | and Arlen Nipper. The protocol is a message-based, publish/subscribe transport layer, which is optimized 31 | for simple telemetry applications running on devices such as Sierra Wireless LS300 Gateway, micro-controllers 32 | such as [Arduino](http://arduino.cc), [mbed](http:mbed.org) and the likes, over possibly low-bandwidth connections. 33 | 34 | This library partially (for now) implements 35 | [MQTT protocol specification v3.1.1](http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.pdf). 36 | The intention is to implement full specification in the near future as much as possible within the constraints of Lua langulage and embedded platforms. 37 | 38 | A good use-case for this library is running on constrained systems, such as [OpenWRT](http://openwrt.org), 39 | and acting as a gateway between non-MQTT clients and MQTT servers. An advantage of using Lua is that only a text editor is required for rapid 40 | development of simple MQTT client applications on platforms such as OpenWRT. 41 | 42 | [MQTT libraries exist](http://mqtt.org/software) for most popular programming languages, so you can utilize MQTT 43 | on whatever server or device that you require. 44 | 45 | Protocol implementation and restrictions 46 | ---------------------------------------- 47 | - Always assumes MQTT connection "clean session" enabled. 48 | - Only supports QOS (Quality Of Service) level 0. 49 | - Packet size of up to maximum specified in [MQTT-v.3.1.1] (2.2.3) 50 | - Publish message doesn't support "message identifier". 51 | - Subscribe acknowledgement messages don't check granted QOS level. 52 | - Outstanding subscribe acknowledgement messages aren't escalated. 53 | - Works on the Sony PlayStation Portable, using 54 | [Lua Player HM](http://en.wikipedia.org/wiki/Lua_Player_HM). 55 | 56 | The Lua MQTT client library also runs (unmodified) on a Sony PlayStation Portable using the 57 | [Lua Player HM](http://en.wikipedia.org/wiki/Lua_Player_HM) _(which requires your PSP to be able to run unsigned executables)._ 58 | 59 | Modules implemented in target platform affects how the library will be used. It may not be possible to add some modules to closed systems. 60 | For example, Sierra Wireless Airlink LS300 3G gateway. 61 | 62 | Installation 63 | ------------ 64 | 65 | Prerequisites ... 66 | 67 | - Install [Lua programming language](http://www.lua.org/download.html) 68 | - Install [LuaRocks package manager](http://luarocks.org/en/Download) 69 | - Install [LuaSocket](http://w3.impa.br/~diego/software/luasocket) 70 | - Install [PenLight](https://github.com/stevedonovan/Penlight) (For running example command line code) 71 | 72 | On Linux, Lua and LuaRocks can be installed via your Linux distribution 73 | package manager. 74 | On Mac OS X, Lua and LuaRocks can be installed via Darwin ports. 75 | 76 | After that, LuaSocket and PenLight can be installed via LuaRocks. 77 | 78 | Usage 79 | ----- 80 | The Lua MQTT client library comes with three command line utilites, 81 | which are useful for testing the library and acting as example code. 82 | These utilities require that Lua Penlight has been installed. 83 | 84 | #### mqtt_test: Test publish and receive messages on different topics 85 | 86 | This command periodically publishes a message on topic "test/1" and 87 | subscribes to the topic "test/2". The command exits when the message 88 | "quit" is published on topic "test/2". 89 | 90 | cd $(LUA_MQTT_LIB) // where Lua MQTT library is installed 91 | example/mqtt_test -d localhost // Assume MQTT server is on "localhost" 92 | 93 | -d,--debug Verbose console logging 94 | -i,--id (default MQTT test) MQTT client identifier 95 | -p,--port (default 1883) MQTT server port number 96 | (default localhost) MQTT server hostname 97 | 98 | #### mqtt_publish: Publish a single retained message to a specified topic 99 | 100 | This command publishes a single retained message and then exits. Subscribe to topic from another Mqtt client to watch 101 | the numbers go up. The last message is retained, replacing the one before it. 102 | You would see that last message if you unsubscribe and resubscribe, even if the mqtt_test is no longer running. 103 | 104 | example/mqtt_publish -d -r -t test/1 -m "Test message" 105 | 106 | Only the _--topic_ and _--message_ parameters are required. 107 | 108 | -d,--debug Verbose console logging 109 | -H,--host (default localhost) MQTT server hostname 110 | -i,--id (default MQTT client) MQTT client identifier 111 | -m,--message (string) Message to be published 112 | -p,--port (default 1883) MQTT server port number 113 | -t,--topic (string) Topic on which to publish 114 | -r,--retain Retain the message 115 | -w,--will_message Last will and testament message 116 | -w,--will_qos (default 0) Last will and testament QOS 117 | -w,--will_retain (default 0) Last will and testament retention 118 | -w,--will_topic Last will and testament topic 119 | 120 | #### mqtt_subscribe: Subscribe to a topic 121 | 122 | This command subscribes to a topic and listens indefinitely for messages. 123 | Use ^C (or similar) to stop execution. 124 | 125 | example/mqtt_subscribe -d -t test/1 126 | 127 | Only the _--topic_ parameter is required. 128 | 129 | -d,--debug Verbose console logging 130 | -H,--host (default localhost) MQTT server hostname 131 | -i,--id (default MQTT client) MQTT client identifier 132 | -k,--keepalive (default 60) Send MQTT PING period (seconds) 133 | -p,--port (default 1883) MQTT server port number 134 | -t,--topic (string) Subscription topic 135 | -w,--will_message Last will and testament message 136 | -w,--will_qos (default 0) Last will and testament QOS 137 | -w,--will_retain (default 0) Last will and testament retention 138 | -w,--will_topic Last will and testament topic 139 | 140 | 141 | Example code 142 | ------------ 143 | The complete functioning code can be viewed here ... 144 | [mqtt_lua/example/mqtt_test.lua](https://github.com/iotrac/mqtt-lua/blob/master/example/mqtt_test.lua) 145 | 146 | local running = true 147 | local counter = 0 148 | 149 | -- Define a function which is called by mqtt_client:handler(), 150 | -- whenever messages are received on the subscribed topics 151 | function callback( 152 | topic, -- string 153 | payload) -- string 154 | 155 | print("mqtt_test:callback(): " .. topic .. ": " .. payload) 156 | 157 | if payload == "quit" then running = false end 158 | end 159 | 160 | local args = lapp [[ 161 | Test Lua MQTT client library 162 | -d,--debug Verbose console logging 163 | -i,--id (default mqtt_test) MQTT client identifier 164 | -p,--port (default 1883) MQTT server port number 165 | -s,--topic_s (default test/2) Subscribe topic 166 | -t,--topic_p (default test/1) Publish topic 167 | (default localhost) MQTT server hostname 168 | ]] 169 | 170 | if (args.debug) then MQTT.Utility.set_debug(true) end 171 | 172 | local error_message = nil 173 | 174 | local mqtt_client = MQTT.client.create(args.host, args.port, callback) 175 | 176 | mqtt_client.auth(mqtt_client, "user", "passwd") 177 | error_message = mqtt_client:connect("mqtt-test") 178 | if error_message ~= nil then error(error_message) end 179 | 180 | error_message = mqtt_client:handler() 181 | 182 | mqtt_client:publish(args.topic_p, "*** Lua test start ***") 183 | mqtt_client:subscribe({ args.topic_s }) 184 | 185 | while (error_message == nil and running) do 186 | error_message = mqtt_client:handler() 187 | 188 | if (error_message == nil) then 189 | mqtt_client:publish(args.topic_p, "*** Lua test message: "..counter, true) 190 | 191 | counter = counter + 1 192 | socket.sleep(1.0) -- seconds 193 | end 194 | end 195 | 196 | -- An error happened or running == false due to a message to topic "test/2" with payload "quit" 197 | if (error_message == nil) then 198 | mqtt_client:unsubscribe({ args.topic_s }) 199 | mqtt_client:destroy() 200 | else 201 | print(error_message) 202 | end 203 | 204 | There are also a number of Lua MQTT client examples in the _example/_ directory. 205 | They can be run from the parent directory, as follow ... 206 | 207 | cd mqtt_client 208 | example/example_00.lua 209 | 210 | 211 | MQTT client Library API 212 | ----------------------- 213 | Once the MQTT client library has been included (via _require_), one or more 214 | MQTT server connections can be created. Using a server connection, the client 215 | may then publish messages directly on a specified topic. Or, subscribe to one 216 | or more topics, where received messages are passed to a callback function 217 | (defined when creating an MQTT client instance). Finally, the client can 218 | unsubscribe from one or more topics and disconnect from the MQTT server. 219 | 220 | Use the Lua _require_ statement to load the MQTT client library ... 221 | 222 | local MQTT = require 'paho.mqtt' 223 | 224 | #### MQTT.Utility.set_debug(): Library debug console logging 225 | 226 | The following statement enables debug console logging for diagnosis. 227 | 228 | MQTT.Utility.set_debug(true) 229 | 230 | #### MQTT.client.create(): Create an MQTT client instance 231 | 232 | Create an MQTT client that will be connected to the specified host. 233 | 234 | mqtt_client = MQTT.client.create(hostname, port, callback) 235 | 236 | The _hostname_ must be provided, but both the _port_ and _callback function_ 237 | parameters are optional. This function returns an MQTT client instance 238 | that must be used for all subsequent MQTT operations for that server connection. 239 | 240 | hostname string: Host name or address of the MQTT broker 241 | port integer: Port number of the MQTT broker (default: 1883) 242 | callback function: Invoked when subscribed topic messages received 243 | 244 | The _callback function_ is defined as follows ... 245 | 246 | function callback(topic, payload) 247 | -- application specific code 248 | end 249 | 250 | topic -- string: Topic for the received message 251 | payload -- string: Message data 252 | 253 | #### MQTT.client:destroy(): Destroy an MQTT client instance 254 | 255 | When finished with a server connection, this statement cleans-up all resources 256 | allocated by the client. 257 | 258 | mqtt_client:destroy() 259 | 260 | #### MQTT.client:connect(): Make a connection to an MQTT server 261 | 262 | Before messages can be transmitted, the MQTT client must connect to the server. 263 | 264 | mqtt_client:connect(identifier) 265 | 266 | Each individual client connection must use a unique identifier. 267 | Only the _identifier_ parameter is required, the remaining parameters 268 | are optional. 269 | 270 | mqtt_client:connect(identifier, will_topic, will_qos, will_retain, will_message) 271 | 272 | MQTT also provides a "last will and testament" for clients, which is a message 273 | automatically sent by the server on behalf of the client, should the connection 274 | fail. 275 | 276 | identifier -- string: MQTT client identifier (maximum 23 characters) 277 | will_topic -- string: Last will and testament topic 278 | will_qos -- byte: Last will and testament Quality Of Service 279 | will_retain -- byte: Last will and testament retention status 280 | will_message -- string: Last will and testament message 281 | 282 | #### MQTT.client:disconnect(): Transmit MQTT Disconnect message 283 | 284 | Transmit an MQTT disconnect message to the server. 285 | 286 | mqtt_client:disconnect() 287 | 288 | #### MQTT.client:publish(): Transmit MQTT publish message 289 | 290 | Transmit a message on a specified topic. 291 | 292 | mqtt_client:publish(topic, payload, retain) 293 | 294 | topic -- string: Topic for the published message 295 | payload -- string: Message data 296 | retain -- boolean: Whether to request the broker to retain this message 297 | 298 | #### MQTT.client:subscribe(): Transmit MQTT Subscribe message 299 | 300 | Subscribe to one or more topics. Whenever a message is published to one of 301 | those topics, the callback function (defined above) will be invoked. 302 | 303 | mqtt_client:subscribe(topics) 304 | 305 | topics -- table of strings, e.g. { "topic1", "topic2" } 306 | 307 | #### MQTT.client:handler(): Handle received messages, maintain keep-alive messages 308 | 309 | The _handler()_ function must be called periodically to service incoming 310 | messages and to ensure that keep-alive messages (PING) are being sent 311 | when required. 312 | 313 | The default _KEEP\_ALIVE\_TIME_ is 60 seconds, therefore _handler()_ must be 314 | invoked more often than once per minute. 315 | 316 | Should any messages be received on the subscribed topics, then _handler()_ 317 | will invoke the callback function (defined above). 318 | 319 | mqtt_client:handler() 320 | 321 | #### MQTT.client:unsubscribe(): Transmit MQTT Unsubscribe message 322 | 323 | Unsubscribe from one or more topics, so that messages published to those 324 | topics are no longer received. 325 | 326 | topics -- table of strings, e.g. { "topic1", "topic2" } 327 | 328 | Known problems 329 | -------------- 330 | 331 | - Occasional "MQTT.client:handler(): Message length mismatch" errors, 332 | particularly when subscribed topics are transmitting many messages. 333 | 334 | - Not really a problem, but if you find that the MQTT socket connection is 335 | being closed for no apparent reason, particularly for subscribers ... 336 | then check that all MQTT clients are using a unique client identifier. 337 | -------------------------------------------------------------------------------- /about.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | About 5 | 6 | 7 |

About This Content

8 | 9 |

December 9, 2013

10 |

License

11 | 12 |

The Eclipse Foundation makes available all content in this plug-in ("Content"). Unless otherwise 13 | indicated below, the Content is provided to you under the terms and conditions of the 14 | Eclipse Public License Version 1.0 ("EPL") and Eclipse Distribution License Version 1.0 ("EDL"). 15 | A copy of the EPL is available at 16 | http://www.eclipse.org/legal/epl-v10.html 17 | and a copy of the EDL is available at 18 | http://www.eclipse.org/org/documents/edl-v10.php. 19 | For purposes of the EPL, "Program" will mean the Content.

20 | 21 |

If you did not receive this Content directly from the Eclipse Foundation, the Content is 22 | being redistributed by another party ("Redistributor") and different terms and conditions may 23 | apply to your use of any object code in the Content. Check the Redistributor's license that was 24 | provided with the Content. If no such license exists, contact the Redistributor. Unless otherwise 25 | indicated below, the terms and conditions of the EPL still apply to any source code in the Content 26 | and such source code may be obtained at http://www.eclipse.org.

27 | 28 | 29 | -------------------------------------------------------------------------------- /edl-v10: -------------------------------------------------------------------------------- 1 | 2 | Eclipse Distribution License - v 1.0 3 | 4 | Copyright (c) 2007, Eclipse Foundation, Inc. and its licensors. 5 | 6 | All rights reserved. 7 | 8 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 9 | 10 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 11 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 12 | Neither the name of the Eclipse Foundation, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 13 | 14 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 15 | 16 | -------------------------------------------------------------------------------- /epl-v10: -------------------------------------------------------------------------------- 1 | Eclipse Public License - v 1.0 2 | 3 | THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. 4 | 5 | 1. DEFINITIONS 6 | 7 | "Contribution" means: 8 | 9 | a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and 10 | b) in the case of each subsequent Contributor: 11 | i) changes to the Program, and 12 | ii) additions to the Program; 13 | where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. 14 | "Contributor" means any person or entity that distributes the Program. 15 | 16 | "Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. 17 | 18 | "Program" means the Contributions distributed in accordance with this Agreement. 19 | 20 | "Recipient" means anyone who receives the Program under this Agreement, including all Contributors. 21 | 22 | 2. GRANT OF RIGHTS 23 | 24 | a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. 25 | b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. 26 | c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. 27 | d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. 28 | 3. REQUIREMENTS 29 | 30 | A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: 31 | 32 | a) it complies with the terms and conditions of this Agreement; and 33 | b) its license agreement: 34 | i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; 35 | ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; 36 | iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and 37 | iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. 38 | When the Program is made available in source code form: 39 | 40 | a) it must be made available under this Agreement; and 41 | b) a copy of this Agreement must be included with each copy of the Program. 42 | Contributors may not remove or alter any copyright notices contained within the Program. 43 | 44 | Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. 45 | 46 | 4. COMMERCIAL DISTRIBUTION 47 | 48 | Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. 49 | 50 | For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. 51 | 52 | 5. NO WARRANTY 53 | 54 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. 55 | 56 | 6. DISCLAIMER OF LIABILITY 57 | 58 | EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 59 | 60 | 7. GENERAL 61 | 62 | If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. 63 | 64 | If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. 65 | 66 | All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. 67 | 68 | Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. 69 | 70 | This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. 71 | -------------------------------------------------------------------------------- /example/example_00.lua: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/lua 2 | -- 3 | -- example_00.lua 4 | -- ~~~~~~~~~~~~~~ 5 | -- Version: 0.2 2012-06-01 6 | -- ------------------------------------------------------------------------- -- 7 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 8 | -- All rights reserved. This program and the accompanying materials 9 | -- are made available under the terms of the Eclipse Public License v1.0 10 | -- which accompanies this distribution, and is available at 11 | -- http://www.eclipse.org/legal/epl-v10.html 12 | -- 13 | -- Contributors: 14 | -- Andy Gelme - Initial implementation 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Description 18 | -- ~~~~~~~~~~~ 19 | -- Subscribe to a topic and publish all received messages on another topic. 20 | -- 21 | -- ToDo 22 | -- ~~~~ 23 | -- - On failure, automatically reconnect to MQTT server. 24 | -- - Error handling: MQTT.client.connect() 25 | -- - Error handling: MQTT.client.destroy() 26 | -- - Error handling: MQTT.client.disconnect() 27 | -- - Error handling: MQTT.client.handler() 28 | -- - Error handling: MQTT.client.publish() 29 | -- - Error handling: MQTT.client.subscribe() 30 | -- - Error handling: MQTT.client.unsubscribe() 31 | -- ------------------------------------------------------------------------- -- 32 | 33 | package.path = package.path .. ";../paho/?.lua;paho/?.lua" 34 | 35 | local MQTT = require "mqtt" 36 | local socket = require "socket" 37 | local lapp = require("pl.lapp") 38 | 39 | -- ------------------------------------------------------------------------- -- 40 | function is_openwrt() 41 | return(os.getenv("USER") == "root") -- Assume logged in as "root" on OpenWRT 42 | end 43 | -- if (not is_openwrt()) then require("luarocks.require") end 44 | -- ------------------------------------------------------------------------- -- 45 | 46 | local mqtt_client 47 | local error_message = nil 48 | 49 | function callback( 50 | topic, -- string 51 | message) -- string 52 | 53 | print("Topic: " .. topic .. ", message: '" .. message .. "'") 54 | 55 | mqtt_client:publish(args.topic_p, message) 56 | end 57 | 58 | print("\n--- example_00 v0.4-SNAPSHOT ---\n") 59 | 60 | args = lapp [[ 61 | Subscribe to topic_s and publish all messages on topic_p 62 | -H,--host (default localhost) MQTT server hostname 63 | -i,--id (default example_00) MQTT client identifier 64 | -p,--port (default 1883) MQTT server port number 65 | -s,--topic_s (default test/1) Subscribe topic 66 | -t,--topic_p (default test/2) Publish topic 67 | ]] 68 | 69 | 70 | mqtt_client = MQTT.client.create(args.host, args.port, callback) 71 | 72 | error_message = mqtt_client:connect(args.id) 73 | if error_message ~= nil then error(error_message) end 74 | 75 | mqtt_client:subscribe({ args.topic_s }) 76 | 77 | while (error_message == nil) do 78 | error_message = mqtt_client:handler() 79 | socket.sleep(1.0) -- seconds 80 | end 81 | 82 | if (error_message == nil) then 83 | mqtt_client:unsubscribe({ args.topic_s }) 84 | mqtt_client:destroy() 85 | else 86 | print(error_message) 87 | end 88 | 89 | -- ------------------------------------------------------------------------- -- 90 | -------------------------------------------------------------------------------- /example/example_01.lua: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/lua 2 | -- 3 | -- example_01.lua 4 | -- ~~~~~~~~~~~~~~ 5 | -- Version: 0.2 2012-06-01 6 | -- ------------------------------------------------------------------------- -- 7 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 8 | -- All rights reserved. This program and the accompanying materials 9 | -- are made available under the terms of the Eclipse Public License v1.0 10 | -- which accompanies this distribution, and is available at 11 | -- http://www.eclipse.org/legal/epl-v10.html 12 | -- 13 | -- Contributors: 14 | -- Andy Gelme - Initial implementation 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Description 18 | -- ~~~~~~~~~~~ 19 | -- Subscribe to a topic on one MQTT server and publish all received messages 20 | -- to a topic on another MQTT server. 21 | -- 22 | -- ToDo 23 | -- ~~~~ 24 | -- - On failure, automatically reconnect to MQTT server(s). 25 | -- ------------------------------------------------------------------------- -- 26 | 27 | package.path = package.path .. ";../paho/?.lua;paho/?.lua" 28 | 29 | local MQTT = require "mqtt" 30 | local socket = require "socket" 31 | local lapp = require("pl.lapp") 32 | 33 | function is_openwrt() 34 | return(os.getenv("USER") == "root") -- Assume logged in as "root" on OpenWRT 35 | end 36 | -- if (not is_openwrt()) then require("luarocks.require") end 37 | -- ------------------------------------------------------------------------- -- 38 | 39 | print("\n--- example_01 v0.4-SNAPSHOT ---\n") 40 | 41 | args = lapp [[ 42 | Subscribe to topic_s and publish all messages on topic_p 43 | -g,--host_s (default localhost) Subscribe MQTT server hostname 44 | -H,--host_p (default iot.eclipse.org) Publish MQTT server hostname 45 | -i,--id (default example_01) MQTT client identifier 46 | -p,--port_s (default 1883) Subscribe MQTT server port number 47 | -q,--port_p (default 1883) Publish MQTT server port number 48 | -s,--topic_s (default test/1) Subscribe topic 49 | -t,--topic_p (default test/2) Publish topic 50 | ]] 51 | 52 | local error_message1 = nil 53 | local error_message2 = nil 54 | 55 | local mqtt_client1 56 | local mqtt_client2 57 | 58 | function callback( 59 | topic, -- string 60 | message) -- string 61 | 62 | print("Topic: " .. topic .. ", message: '" .. message .. "'") 63 | 64 | mqtt_client2:publish(args.topic_p, message) 65 | end 66 | 67 | mqtt_client1 = MQTT.client.create(args.host_s, args.port_s, callback) 68 | mqtt_client2 = MQTT.client.create(args.host_p, args.port_p) 69 | 70 | error_message1 = mqtt_client1:connect(args.id .. "-a") 71 | if error_message1 ~= nil then error(error_message1) end 72 | 73 | error_message2 = mqtt_client2:connect(args.id .. "-b") 74 | if error_message2 ~= nil then error(error_message2) end 75 | 76 | mqtt_client1:subscribe({ args.topic_s }) 77 | 78 | while (error_message1 == nil and error_message2 == nil) do 79 | error_message1 = mqtt_client1:handler() 80 | error_message2 = mqtt_client2:handler() 81 | socket.sleep(2.0) -- seconds 82 | end 83 | 84 | if (error_message1 == nil) then 85 | mqtt_client1:unsubscribe({ args.topic_s }) 86 | mqtt_client1:destroy() 87 | else 88 | print(error_message1) 89 | end 90 | 91 | if (error_message2 == nil) then 92 | mqtt_client2:destroy() 93 | else 94 | print(error_message2) 95 | end 96 | 97 | 98 | -------------------------------------------------------------------------------- /example/example_02.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/lua 2 | -- 3 | -- example_02.lua 4 | -- ~~~~~~~~~~~~~~ 5 | -- Version: 0.2 2012-06-01 6 | -- ------------------------------------------------------------------------- -- 7 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 8 | -- All rights reserved. This program and the accompanying materials 9 | -- are made available under the terms of the Eclipse Public License v1.0 10 | -- which accompanies this distribution, and is available at 11 | -- http://www.eclipse.org/legal/epl-v10.html 12 | -- 13 | -- Contributors: 14 | -- Andy Gelme - Initial implementation 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Description 18 | -- ~~~~~~~~~~~ 19 | -- Publish a sequence of messages to a specified topic. 20 | -- Used to control some coloured RGB LEDs. 21 | -- 22 | -- ToDo 23 | -- ~~~~ 24 | -- - On failure, automatically reconnect to MQTT server. 25 | -- ------------------------------------------------------------------------- -- 26 | package.path = package.path .. ";../paho/?.lua;paho/?.lua" 27 | 28 | local MQTT = require "mqtt" 29 | local socket = require "socket" 30 | local lapp = require("pl.lapp") 31 | 32 | function is_openwrt() 33 | return(os.getenv("USER") == "root") -- Assume logged in as "root" on OpenWRT 34 | end 35 | -- if (not is_openwrt()) then require("luarocks.require") end 36 | -- ------------------------------------------------------------------------- -- 37 | 38 | print("\n--- example_02 v0.4-SNAPSHOT ---\n") 39 | 40 | local args = lapp [[ 41 | Subscribe to topic1 and publish all messages on topic2 42 | -H,--host (default localhost) MQTT server hostname 43 | -i,--id (default example_02) MQTT client identifier 44 | -p,--port (default 1883) MQTT server port number 45 | -s,--sleep (default 3.0) Sleep time between commands 46 | -t,--topic (default test/ex3) Topic on which to publish 47 | ]] 48 | 49 | 50 | local error_message = nil 51 | local index = 1 52 | local messages = { "c010000", "c000100", "c000001" } 53 | local mqtt_client = MQTT.client.create(args.host, args.port) 54 | 55 | error_message = mqtt_client:connect(args.id) 56 | if error_message ~= nil then error(error_message) end 57 | 58 | while (error_message == nil) do 59 | mqtt_client:publish(args.topic, messages[index]); 60 | 61 | index = index + 1 62 | if (index > #messages) then index = 1 end 63 | 64 | socket.sleep(args.sleep) -- seconds 65 | error_message = mqtt_client:handler() 66 | end 67 | 68 | if (error_message == nil) then 69 | mqtt_client:destroy() 70 | else 71 | print(error_message) 72 | end 73 | -------------------------------------------------------------------------------- /example/mqtt_publish.lua: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/lua 2 | -- 3 | -- mqtt_publish.lua 4 | -- ~~~~~~~~~~~~~~~~ 5 | -- Version: 0.2 2012-06-01 6 | -- ------------------------------------------------------------------------- -- 7 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 8 | -- All rights reserved. This program and the accompanying materials 9 | -- are made available under the terms of the Eclipse Public License v1.0 10 | -- which accompanies this distribution, and is available at 11 | -- http://www.eclipse.org/legal/epl-v10.html 12 | -- 13 | -- Contributors: 14 | -- Andy Gelme - Initial implementation 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Description 18 | -- ~~~~~~~~~~~ 19 | -- Publish an MQTT message on the specified topic with an optional last will. 20 | -- 21 | -- References 22 | -- ~~~~~~~~~~ 23 | -- Lapp Framework: Lua command line parsing 24 | -- http://lua-users.org/wiki/LappFramework 25 | -- 26 | -- ToDo 27 | -- ~~~~ 28 | -- None, yet. 29 | -- ------------------------------------------------------------------------- -- 30 | package.path = package.path .. ";../paho/?.lua;paho/?.lua" 31 | 32 | local MQTT = require "mqtt" 33 | local socket = require "socket" 34 | local lapp = require("pl.lapp") 35 | 36 | function is_openwrt() 37 | return(os.getenv("USER") == "root") -- Assume logged in as "root" on OpenWRT 38 | end 39 | -- if (not is_openwrt()) then require("luarocks.require") end 40 | -- ------------------------------------------------------------------------- -- 41 | 42 | print("\n--- mqtt_publish v0.4-SNAPSHOT ---\n") 43 | 44 | 45 | local args = lapp [[ 46 | Publish a message to a specified MQTT topic 47 | -d,--debug Verbose console logging 48 | -H,--host (default localhost) MQTT server hostname 49 | -i,--id (default mqtt_pub) MQTT client identifier 50 | -m,--message (string) Message to be published 51 | -p,--port (default 1883) MQTT server port number 52 | -t,--topic (string) Topic on which to publish. 53 | -r,--retain Retain the message 54 | -w,--will_message (default .) Last will and testament message 55 | -w,--will_qos (default 0) Last will and testament QOS 56 | -w,--will_retain (default 0) Last will and testament retention 57 | -w,--will_topic (default .) Last will and testament topic 58 | ]] 59 | 60 | local retain = false 61 | local error_message=nil 62 | 63 | if (args.debug) then MQTT.Utility.set_debug(true) end 64 | if args.retain then retain=true end 65 | 66 | local mqtt_client = MQTT.client.create(args.host, args.port) 67 | 68 | if (args.will_message == "." or args.will_topic == ".") then 69 | error_message = mqtt_client:connect(args.id) 70 | else 71 | error_message = mqtt_client:connect( 72 | args.id, args.will_topic, args.will_qos, args.will_retain, args.will_message 73 | ) 74 | end 75 | if error_message ~= nil then error(error_message) end 76 | 77 | mqtt_client:publish(args.topic, args.message, retain) 78 | 79 | mqtt_client:destroy() 80 | 81 | -------------------------------------------------------------------------------- /example/mqtt_subscribe.lua: -------------------------------------------------------------------------------- 1 | #!/usr/bin/lua 2 | -- 3 | -- mqtt_subscribe.lua 4 | -- ~~~~~~~~~~~~~~~~~~ 5 | -- Version: 0.2 2012-06-01 6 | -- ------------------------------------------------------------------------- -- 7 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 8 | -- All rights reserved. This program and the accompanying materials 9 | -- are made available under the terms of the Eclipse Public License v1.0 10 | -- which accompanies this distribution, and is available at 11 | -- http://www.eclipse.org/legal/epl-v10.html 12 | -- 13 | -- Contributors: 14 | -- Andy Gelme - Initial implementation 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Description 18 | -- ~~~~~~~~~~~ 19 | -- Subscribe to an MQTT topic and display any received messages. 20 | -- 21 | -- References 22 | -- ~~~~~~~~~~ 23 | -- Lapp Framework: Lua command line parsing 24 | -- http://lua-users.org/wiki/LappFramework 25 | -- 26 | -- ToDo 27 | -- ~~~~ 28 | -- None, yet. 29 | -- ------------------------------------------------------------------------- -- 30 | package.path = package.path .. ";../paho/?.lua;paho/?.lua" 31 | 32 | local MQTT = require "mqtt" 33 | local socket = require "socket" 34 | local lapp = require("pl.lapp") 35 | 36 | -- ------------------------------------------------------------------------- -- 37 | function is_openwrt() 38 | return(os.getenv("USER") == "root") -- Assume logged in as "root" on OpenWRT 39 | end 40 | -- if (not is_openwrt()) then require("luarocks.require") end 41 | -- ------------------------------------------------------------------------- -- 42 | 43 | function callback( 44 | topic, -- string 45 | message) -- string 46 | 47 | print("Topic: " .. topic .. ", message: '" .. message .. "'") 48 | end 49 | 50 | print("\n--- mqtt_subscribe v0.4-SNAPSHOT ---\n") 51 | 52 | local args = lapp [[ 53 | Subscribe to a specified MQTT topic 54 | -d,--debug Verbose console logging 55 | -H,--host (default localhost) MQTT server hostname 56 | -i,--id (default mqtt_sub) MQTT client identifier 57 | -k,--keepalive (default 60) Send MQTT PING period (seconds) 58 | -p,--port (default 1883) MQTT server port number 59 | -t,--topic (string) Subscription topic 60 | -w,--will_message (default .) Last will and testament message 61 | -w,--will_qos (default 0) Last will and testament QOS 62 | -w,--will_retain (default 0) Last will and testament retention 63 | -w,--will_topic (default .) Last will and testament topic 64 | ]] 65 | 66 | 67 | if (args.debug) then MQTT.Utility.set_debug(true) end 68 | 69 | if (args.keepalive) then MQTT.client.KEEP_ALIVE_TIME = args.keepalive end 70 | 71 | local mqtt_client = MQTT.client.create(args.host, args.port, callback) 72 | 73 | local error_message=nil 74 | 75 | if (args.will_message == "." or args.will_topic == ".") then 76 | error_message = mqtt_client:connect(args.id) 77 | else 78 | error_message = mqtt_client:connect( 79 | args.id, args.will_topic, args.will_qos, args.will_retain, args.will_message 80 | ) 81 | end 82 | if error_message ~= nil then error(error_message) end 83 | 84 | mqtt_client:subscribe({args.topic}) 85 | 86 | while (error_message == nil) do 87 | error_message = mqtt_client:handler() 88 | socket.sleep(1.0) -- seconds 89 | end 90 | 91 | if (error_message == nil) then 92 | mqtt_client:unsubscribe({args.topic}) 93 | mqtt_client:destroy() 94 | else 95 | print(error_message) 96 | end 97 | 98 | -- ------------------------------------------------------------------------- -- 99 | -------------------------------------------------------------------------------- /example/mqtt_test.lua: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/lua 2 | -- 3 | -- mqtt_test.lua 4 | -- ~~~~~~~~~~~~~ 5 | -- Version: 0.4-SNAPSHOT 6 | -- ------------------------------------------------------------------------- -- 7 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 8 | -- All rights reserved. This program and the accompanying materials 9 | -- are made available under the terms of the Eclipse Public License v1.0 10 | -- which accompanies this distribution, and is available at 11 | -- http://www.eclipse.org/legal/epl-v10.html 12 | -- 13 | -- Contributors: 14 | -- Andy Gelme - Initial implementation 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Description 18 | -- ~~~~~~~~~~~ 19 | -- Repetitively publishes MQTT messages on the topic_p, 20 | -- until the "quit" message is received on the topic_s. 21 | -- 22 | -- References 23 | -- ~~~~~~~~~~ 24 | -- Lapp Framework: Lua command line parsing 25 | -- http://lua-users.org/wiki/LappFramework 26 | -- 27 | -- ToDo 28 | -- ~~~~ 29 | -- - On failure, automatically reconnect to MQTT server. 30 | -- ------------------------------------------------------------------------- -- 31 | 32 | package.path = package.path .. ";../paho/?.lua;paho/?.lua" 33 | 34 | local MQTT = require "mqtt" 35 | local socket = require "socket" 36 | local lapp = require("pl.lapp") 37 | local version = "0.4-SNAPSHOT" 38 | 39 | -- ------------------------------------------------------------------------- -- 40 | function is_openwrt() 41 | return(os.getenv("USER") == "root") -- Assume logged in as "root" on OpenWRT 42 | end 43 | -- if (not is_openwrt()) then require("luarocks.require") end 44 | -- ------------------------------------------------------------------------- -- 45 | 46 | print("\n--- mqtt_test (v." .. version .. ") ---\n") 47 | 48 | local running = true 49 | local counter = 0 50 | 51 | -- Define a function which is called by mqtt_client:handler(), 52 | -- whenever messages are received on the subscribed topics 53 | function callback( 54 | topic, -- string 55 | payload) -- string 56 | 57 | print("mqtt_test:callback(): " .. topic .. ":" .. payload) 58 | 59 | if payload == "quit" then running = false end 60 | end 61 | 62 | local args = lapp [[ 63 | Test Lua MQTT client library 64 | -d,--debug Verbose console logging 65 | -i,--id (default mqtt_test) MQTT client identifier 66 | -p,--port (default 1883) MQTT server port number 67 | -s,--topic_s (default test/2) Subscribe topic 68 | -t,--topic_p (default test/1) Publish topic 69 | (default localhost) MQTT server hostname 70 | ]] 71 | 72 | if (args.debug) then MQTT.Utility.set_debug(true) end 73 | 74 | local error_message = nil 75 | 76 | local mqtt_client = MQTT.client.create(args.host, args.port, callback) 77 | 78 | mqtt_client.auth(mqtt_client, "user", "passwd") 79 | error_message = mqtt_client:connect("mqtt-test") 80 | if error_message ~= nil then error(error_message) end 81 | 82 | error_message = mqtt_client:handler() 83 | 84 | mqtt_client:publish(args.topic_p, "*** Lua test start ***") 85 | mqtt_client:subscribe({ args.topic_s }) 86 | 87 | while (error_message == nil and running) do 88 | error_message = mqtt_client:handler() 89 | 90 | if (error_message == nil) then 91 | mqtt_client:publish(args.topic_p, "*** Lua test message: "..counter, true) 92 | 93 | counter = counter + 1 94 | socket.sleep(1.0) -- seconds 95 | end 96 | end 97 | 98 | if (error_message == nil) then 99 | -- running == false, due to a message to topic "test/2" with payload "quit" 100 | mqtt_client:unsubscribe({ args.topic_s }) 101 | mqtt_client:destroy() 102 | else 103 | -- An error occurred 104 | print(error_message) 105 | end 106 | 107 | -- ------------------------------------------------------------------------- -- 108 | -------------------------------------------------------------------------------- /notice.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Eclipse Foundation Software User Agreement 7 | 8 | 9 | 10 |

Eclipse Foundation Software User Agreement

11 |

February 1, 2011

12 | 13 |

Usage Of Content

14 | 15 |

THE ECLIPSE FOUNDATION MAKES AVAILABLE SOFTWARE, DOCUMENTATION, INFORMATION AND/OR OTHER MATERIALS FOR OPEN SOURCE PROJECTS 16 | (COLLECTIVELY "CONTENT"). USE OF THE CONTENT IS GOVERNED BY THE TERMS AND CONDITIONS OF THIS AGREEMENT AND/OR THE TERMS AND 17 | CONDITIONS OF LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW. BY USING THE CONTENT, YOU AGREE THAT YOUR USE 18 | OF THE CONTENT IS GOVERNED BY THIS AGREEMENT AND/OR THE TERMS AND CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR 19 | NOTICES INDICATED OR REFERENCED BELOW. IF YOU DO NOT AGREE TO THE TERMS AND CONDITIONS OF THIS AGREEMENT AND THE TERMS AND 20 | CONDITIONS OF ANY APPLICABLE LICENSE AGREEMENTS OR NOTICES INDICATED OR REFERENCED BELOW, THEN YOU MAY NOT USE THE CONTENT.

21 | 22 |

Applicable Licenses

23 | 24 |

Unless otherwise indicated, all Content made available by the Eclipse Foundation is provided to you under the terms and conditions of the Eclipse Public License Version 1.0 25 | ("EPL"). A copy of the EPL is provided with this Content and is also available at http://www.eclipse.org/legal/epl-v10.html. 26 | For purposes of the EPL, "Program" will mean the Content.

27 | 28 |

Content includes, but is not limited to, source code, object code, documentation and other files maintained in the Eclipse Foundation source code 29 | repository ("Repository") in software modules ("Modules") and made available as downloadable archives ("Downloads").

30 | 31 |
    32 |
  • Content may be structured and packaged into modules to facilitate delivering, extending, and upgrading the Content. Typical modules may include plug-ins ("Plug-ins"), plug-in fragments ("Fragments"), and features ("Features").
  • 33 |
  • Each Plug-in or Fragment may be packaged as a sub-directory or JAR (Java™ ARchive) in a directory named "plugins".
  • 34 |
  • A Feature is a bundle of one or more Plug-ins and/or Fragments and associated material. Each Feature may be packaged as a sub-directory in a directory named "features". Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of the Plug-ins 35 | and/or Fragments associated with that Feature.
  • 36 |
  • Features may also include other Features ("Included Features"). Within a Feature, files named "feature.xml" may contain a list of the names and version numbers of Included Features.
  • 37 |
38 | 39 |

The terms and conditions governing Plug-ins and Fragments should be contained in files named "about.html" ("Abouts"). The terms and conditions governing Features and 40 | Included Features should be contained in files named "license.html" ("Feature Licenses"). Abouts and Feature Licenses may be located in any directory of a Download or Module 41 | including, but not limited to the following locations:

42 | 43 |
    44 |
  • The top-level (root) directory
  • 45 |
  • Plug-in and Fragment directories
  • 46 |
  • Inside Plug-ins and Fragments packaged as JARs
  • 47 |
  • Sub-directories of the directory named "src" of certain Plug-ins
  • 48 |
  • Feature directories
  • 49 |
50 | 51 |

Note: if a Feature made available by the Eclipse Foundation is installed using the Provisioning Technology (as defined below), you must agree to a license ("Feature Update License") during the 52 | installation process. If the Feature contains Included Features, the Feature Update License should either provide you with the terms and conditions governing the Included Features or 53 | inform you where you can locate them. Feature Update Licenses may be found in the "license" property of files named "feature.properties" found within a Feature. 54 | Such Abouts, Feature Licenses, and Feature Update Licenses contain the terms and conditions (or references to such terms and conditions) that govern your use of the associated Content in 55 | that directory.

56 | 57 |

THE ABOUTS, FEATURE LICENSES, AND FEATURE UPDATE LICENSES MAY REFER TO THE EPL OR OTHER LICENSE AGREEMENTS, NOTICES OR TERMS AND CONDITIONS. SOME OF THESE 58 | OTHER LICENSE AGREEMENTS MAY INCLUDE (BUT ARE NOT LIMITED TO):

59 | 60 | 68 | 69 |

IT IS YOUR OBLIGATION TO READ AND ACCEPT ALL SUCH TERMS AND CONDITIONS PRIOR TO USE OF THE CONTENT. If no About, Feature License, or Feature Update License is provided, please 70 | contact the Eclipse Foundation to determine what terms and conditions govern that particular Content.

71 | 72 | 73 |

Use of Provisioning Technology

74 | 75 |

The Eclipse Foundation makes available provisioning software, examples of which include, but are not limited to, p2 and the Eclipse 76 | Update Manager ("Provisioning Technology") for the purpose of allowing users to install software, documentation, information and/or 77 | other materials (collectively "Installable Software"). This capability is provided with the intent of allowing such users to 78 | install, extend and update Eclipse-based products. Information about packaging Installable Software is available at http://eclipse.org/equinox/p2/repository_packaging.html 80 | ("Specification").

81 | 82 |

You may use Provisioning Technology to allow other parties to install Installable Software. You shall be responsible for enabling the 83 | applicable license agreements relating to the Installable Software to be presented to, and accepted by, the users of the Provisioning Technology 84 | in accordance with the Specification. By using Provisioning Technology in such a manner and making it available in accordance with the 85 | Specification, you further acknowledge your agreement to, and the acquisition of all necessary rights to permit the following:

86 | 87 |
    88 |
  1. A series of actions may occur ("Provisioning Process") in which a user may execute the Provisioning Technology 89 | on a machine ("Target Machine") with the intent of installing, extending or updating the functionality of an Eclipse-based 90 | product.
  2. 91 |
  3. During the Provisioning Process, the Provisioning Technology may cause third party Installable Software or a portion thereof to be 92 | accessed and copied to the Target Machine.
  4. 93 |
  5. Pursuant to the Specification, you will provide to the user the terms and conditions that govern the use of the Installable 94 | Software ("Installable Software Agreement") and such Installable Software Agreement shall be accessed from the Target 95 | Machine in accordance with the Specification. Such Installable Software Agreement must inform the user of the terms and conditions that govern 96 | the Installable Software and must solicit acceptance by the end user in the manner prescribed in such Installable Software Agreement. Upon such 97 | indication of agreement by the user, the provisioning Technology will complete installation of the Installable Software.
  6. 98 |
99 | 100 |

Cryptography

101 | 102 |

Content may contain encryption software. The country in which you are currently may have restrictions on the import, possession, and use, and/or re-export to 103 | another country, of encryption software. BEFORE using any encryption software, please check the country's laws, regulations and policies concerning the import, 104 | possession, or use, and re-export of encryption software, to see if this is permitted.

105 | 106 |

Java and all Java-based trademarks are trademarks of Oracle Corporation in the United States, other countries, or both.

107 | 108 | 109 | -------------------------------------------------------------------------------- /paho/mqtt.lua: -------------------------------------------------------------------------------- 1 | --- 2 | -- @module mqtt_library 3 | -- ~~~~~~~~~~~~~~~~ 4 | -- Version: 0.4-SNAPSHOT 5 | -- -------------------------------------------------------------------------- -- 6 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 7 | -- All rights reserved. This program and the accompanying materials 8 | -- are made available under the terms of the Eclipse Public License v1.0 9 | -- which accompanies this distribution, and is available at 10 | -- http://www.eclipse.org/legal/epl-v10.html 11 | -- 12 | -- Contributors: 13 | -- Andy Gelme - Initial API and implementation 14 | -- Kevin KIN-FOO - Authentication and rockspec 15 | -- -------------------------------------------------------------------------- -- 16 | -- 17 | -- Documentation 18 | -- ~~~~~~~~~~~~~ 19 | -- Paho MQTT Lua website 20 | -- http://eclipse.org/paho/ 21 | -- 22 | -- References 23 | -- ~~~~~~~~~~ 24 | -- MQTT Community 25 | -- http://mqtt.org 26 | 27 | -- MQTT protocol specification v3.1.1 28 | -- http://mqtt.org/documentation 29 | -- http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.pdf 30 | -- 31 | -- Notes 32 | -- ~~~~~ 33 | -- - Always assumes MQTT connection "clean session" enabled. 34 | -- - Only supports QOS level 0. 35 | -- - Publish message doesn't support "message identifier". 36 | -- - Subscribe acknowledgement messages don't check granted QOS level. 37 | -- - Outstanding subscribe acknowledgement messages aren't escalated. 38 | -- 39 | -- ToDo 40 | -- ~~~~ 41 | -- * Consider when payload needs to be an array of bytes (not characters). 42 | -- * Maintain both "last_activity_out" and "last_activity_in". 43 | -- * - http://mqtt.org/wiki/doku.php/keepalive_for_the_client 44 | -- * Update "last_activity_in" when messages are received. 45 | -- * When a PINGREQ is sent, must check for a PINGRESP, within KEEP_ALIVE_TIME.. 46 | -- * Otherwise, fail the connection. 47 | -- * When connecting, wait for CONNACK, until KEEP_ALIVE_TIME, before failing. 48 | -- This fixed by: https://github.com/iotrac/mqtt-lua/commit/3c8776bb8b67e23fff8d3fd2908145ccb8afdfa2 49 | -- After CONNECT msg, wait for CONNACK until CONNACK_WAIT_TIMEOUT. KEEP_ALIVE_TIME is too long. 50 | -- 51 | -- * Review all public APIs for asynchronous callback behaviour. 52 | -- * Implement parse PUBACK message. -- This should be: Implement QoS level 1. 53 | 54 | -- * Handle failed subscriptions, i.e no subscription acknowledgement received. 55 | 56 | -- MQTT.client:handler(): Message length mismatch 57 | -- - On socket error, optionally try reconnection to MQTT server. 58 | -- - Consider use of assert() and pcall() ? 59 | -- - Only expose public API functions, don't expose internal API functions. 60 | -- - Refactor "if self.connected()" to "self.checkConnected(error_message)". 61 | -- - Maintain and publish messaging statistics. 62 | -- - Memory heap/stack monitoring. 63 | -- - When debugging, why isn't mosquitto sending back CONNACK error code ? 64 | -- Fixed by: https://github.com/iotrac/mqtt-lua/issues/3 65 | -- 66 | -- - Implement asynchronous state machine, rather than single-thread waiting. 67 | -- - Consider using Copas http://keplerproject.github.com/copas/manual.html 68 | -- ------------------------------------------------------------------------- -- 69 | 70 | function isPsp() return(Socket ~= nil) end 71 | 72 | local socket = require("socket") 73 | -- require("io") 74 | -- require("ltn12") 75 | -- require("ssl") 76 | 77 | local version = "0.4-SNAPSHOT" 78 | 79 | local MQTT = {} 80 | 81 | local pathOfThisFile = ... 82 | local folderOfThisFile = (...):match("(.-)[^%.]+$") 83 | -- Thanks to http://stackoverflow.com/questions/9145432/load-lua-files-by-relative-path 84 | 85 | --- 86 | -- @field [parent = #mqtt_library] utility#utility Utility 87 | -- 88 | MQTT.Utility = require(folderOfThisFile .. 'utility') 89 | 90 | 91 | --- 92 | -- @field [parent = #mqtt_library] #number VERSION 93 | -- 94 | MQTT.VERSION = 0x04 95 | 96 | --- 97 | -- @field [parent = #mqtt_library] #boolean ERROR_TERMINATE 98 | -- 99 | MQTT.ERROR_TERMINATE = false -- Message handler errors terminate process ? 100 | 101 | --- 102 | -- @field [parent = #mqtt_library] #string DEFAULT_BROKER_HOSTNAME 103 | -- 104 | MQTT.DEFAULT_BROKER_HOSTNAME = "iot.eclipse.org" 105 | 106 | --- 107 | -- An MQTT client 108 | -- @type client 109 | 110 | --- 111 | -- @field [parent = #mqtt_library] #client client 112 | -- 113 | MQTT.client = {} 114 | 115 | MQTT.client.__index = MQTT.client 116 | 117 | --- 118 | -- @field [parent = #client] #number DEFAULT_PORT 119 | -- 120 | MQTT.client.DEFAULT_PORT = 1883 121 | 122 | --- 123 | -- @field [parent = #client] #number KEEP_ALIVE_TIME 124 | -- 125 | MQTT.client.KEEP_ALIVE_TIME = 60 -- seconds (maximum is 65535) 126 | MQTT.client.CONNACK_WAIT_TIMEOUT = 3 -- seconds [MQTT-3.2: "Reasonable" time] 127 | MQTT.client.CLIENT_SOCKET_TIMEOUT = 0.01 128 | --- 129 | -- @field [parent = #client] #number MAX_PAYLOAD_LENGTH 130 | -- 131 | MQTT.client.MAX_PAYLOAD_LENGTH = 268435455 -- bytes 132 | 133 | -- MQTT 3.1.1 Specification: Section 2.2.1: Fixed header control packet types 134 | --- 135 | -- @field [parent = #mqtt_library] message 136 | -- 137 | MQTT.RESERVED_00 = 0x00 -- Forbidden 138 | MQTT.CONNECT = 0x01 139 | MQTT.CONNACK = 0x02 140 | MQTT.PUBLISH = 0x03 141 | MQTT.PUBACK = 0x04 142 | MQTT.PUBREC = 0x05 143 | MQTT.PUBREL = 0x06 144 | MQTT.PUBCOMP = 0x07 145 | MQTT.SUBSCRIBE = 0x08 146 | MQTT.SUBACK = 0x09 147 | MQTT.UNSUBSCRIBE = 0x0A 148 | MQTT.UNSUBACK = 0x0B 149 | MQTT.PINGREQ = 0x0C 150 | MQTT.PINGRESP = 0x0D 151 | MQTT.DISCONNECT = 0x0E 152 | MQTT.RESERVED_FF = 0xFF --Forbidden 153 | 154 | -- MQTT 3.1.1 Specification: Section 3.2: CONNACK return error messages. 155 | -- CONNACK return code 0x0 -> Connection Accepted. Others are errors. 156 | MQTT.error_message = {} 157 | MQTT.error_message.CONNACK = { -- CONNACK return code used as the index 158 | "Connection refused, unacceptable protocol version", -- 0x01 159 | "Connection refused, identifer rejected", -- 0x02 160 | "Connection refused, server unavailable", -- 0x03 161 | "Connection refused, bad user name or password", -- 0x04 162 | "Connection refused, client is not authorized to connect" -- 0x05 163 | -- 6-255: Reserved for future use 164 | } 165 | 166 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 167 | -- Create an MQTT client instance 168 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 169 | --- 170 | -- Create an MQTT client instance. 171 | -- @param #string hostname Host name or address of the MQTT broker 172 | -- @param #number port Port number of the MQTT broker (default: 1883) 173 | -- @param #function callback Invoked when subscribed topic messages received 174 | -- @function [parent = #client] create 175 | -- @return #client created client 176 | -- 177 | function MQTT.client.create( -- Public API 178 | hostname, -- string: Host name or address of the MQTT broker 179 | port, -- integer: Port number of the MQTT broker (default: 1883) 180 | callback) -- function: Invoked when subscribed topic messages received 181 | -- return: mqtt_client table 182 | 183 | local mqtt_client = {} 184 | 185 | setmetatable(mqtt_client, MQTT.client) 186 | 187 | mqtt_client.callback = callback -- function(topic, payload) 188 | mqtt_client.hostname = hostname or MQTT.DEFAULT_BROKER_HOSTNAME 189 | mqtt_client.port = port or MQTT.client.DEFAULT_PORT 190 | 191 | mqtt_client.connected = false 192 | mqtt_client.destroyed = false 193 | mqtt_client.last_activity = 0 194 | mqtt_client.message_id = 0 195 | mqtt_client.outstanding = {} 196 | mqtt_client.socket_client = nil 197 | 198 | return(mqtt_client) 199 | end 200 | 201 | -------------------------------------------------------------------------------- 202 | -- Specify username and password before #client.connect 203 | -- 204 | -- It is possible to have empty username and passwords per [MQTT-3.1.3.4] 205 | -- 206 | -- If called with empty _username_ or _password_, username and password flags will be set and: 207 | -- If username is empty, 0 length UTF-8 encoded string will be added to payload. 208 | -- If password is empty, 2 bytes for length + 0 length binary password(emtpy) 209 | -- will be added added to payload. [MQTT-3.1.3.5] 210 | -- 211 | -- What will happen when username="" and password="abc" is: 212 | -- 1. username & password flags will be set 213 | -- 2. username will be encoded as only two bytes of length 0 as per [MQTT 1.5.3] 214 | -- 3. password bytes will contain '0,3,97,98,99' 215 | -- 216 | -- Remains to be seen if this behaviour will be accepted by brokers. 217 | -- 218 | -- Usage example: 219 | -- local mqtt_client = MQTT.client.create(args.host, args.port, callback) 220 | -- mqtt_client.auth(mqtt_client, , ) 221 | -- 222 | -- @function [parent = #client] auth 223 | -- @param self 224 | -- @param #string username Name of the user who is connecting. 225 | -- @param #string password Password for the connecting user. 226 | function MQTT.client.auth(self, username, password) 227 | -- When no string is provided, remember current call to set flags 228 | self.username = username or true 229 | self.password = password or true 230 | end 231 | 232 | -------------------------------------------------------------------------------- 233 | -- Transmit a CONNECT Packet to MQTT broker. 234 | -- MQTT 3.1.1 - 3.1: CONNECT 235 | -- @param self 236 | -- @param #string identifier MQTT client identifier (maximum 23 characters) 237 | -- @param #string will_topic Last will and testament topic 238 | -- @param #string will_qos Last will and testament Quality Of Service 239 | -- @param #string will_retain Last will and testament retention status 240 | -- @param #string will_message Last will and testament message 241 | -- @function [parent = #client] connect 242 | -- 243 | function MQTT.client:connect( -- Public API 244 | identifier, -- string: MQTT client identifier (maximum 23 characters) 245 | will_topic, -- string: Last will and testament topic 246 | will_qos, -- byte: Last will and testament Quality Of Service 247 | will_retain, -- byte: Last will and testament retention status 248 | will_message) -- string: Last will and testament message 249 | -- return: nil or error message 250 | 251 | if (self.connected) then 252 | -- TODO: Should this be an idempotent operation ? 253 | return("MQTT.client:connect(): Already connected") 254 | end 255 | 256 | MQTT.Utility.debug("MQTT.client:connect(): " .. identifier) 257 | 258 | self.socket_client = socket.connect(self.hostname, self.port) 259 | 260 | if (self.socket_client == nil) then 261 | MQTT.Utility.debug("MQTT.client:connect(): Couldn't open MQTT broker connection") 262 | return("MQTT.client:connect(): Couldn't open MQTT broker connection") 263 | end 264 | 265 | -- Set a timeout value for subsequent operations 266 | MQTT.Utility.socket_wait_connected(self.socket_client, MQTT.client.CLIENT_SOCKET_TIMEOUT) 267 | 268 | -- Not yet connected. Only after CONNACK is received without errors. 269 | self.connected = false 270 | 271 | -- Construct CONNECT variable header fields (bytes 1 through 7) 272 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 273 | local payload 274 | payload = MQTT.client.encode_utf8("MQTT") -- For v.3.1.1 275 | payload = payload .. string.char(MQTT.VERSION) -- Protocol level (3.1.2.2) 276 | 277 | -- Connect flags (byte 8) 278 | -- ~~~~~~~~~~~~~ 279 | -- bit 7: Username flag = 0 280 | -- bit 6: Password flag = 0 281 | -- bit 5: Will retain = 0 282 | -- bits 4,3: Will QOS = 00 283 | -- bit 2: Will flag = 0 284 | -- bit 1: Clean session = 1 --TODO: Add ability to use existing sessions. 285 | -- bit 0: Unused = 0 286 | 287 | local username = self.username and 0x80 or 0 288 | 289 | -- If the User Name Flag is set to 0, the Password Flag MUST be set to 0 [MQTT-3.1.2.9] 290 | local password = self.username and self.password and 0x40 or 0 291 | 292 | local flags = username + password 293 | 294 | if (will_topic == nil) then 295 | -- Clean session, no last will 296 | flags = flags + 0x02 297 | else 298 | flags = flags + MQTT.Utility.shift_left(will_retain, 5) 299 | flags = flags + MQTT.Utility.shift_left(will_qos, 3) 300 | -- Last will and clean session 301 | flags = flags + 0x04 + 0x02 302 | end 303 | payload = payload .. string.char(flags) 304 | 305 | -- Keep alive timer (bytes 9 LSB and 10 MSB, unit is seconds) 306 | -- ~~~~~~~~~~~~~~~~~ 307 | payload = payload .. string.char(math.floor(MQTT.client.KEEP_ALIVE_TIME / 256)) 308 | payload = payload .. string.char(MQTT.client.KEEP_ALIVE_TIME % 256) 309 | 310 | -- Client identifier 311 | -- ~~~~~~~~~~~~~~~~~ 312 | payload = payload .. MQTT.client.encode_utf8(identifier) 313 | 314 | -- Last will and testament 315 | -- ~~~~~~~~~~~~~~~~~~~~~~~ 316 | if (will_topic ~= nil) then 317 | payload = payload .. MQTT.client.encode_utf8(will_topic) 318 | payload = payload .. MQTT.client.encode_utf8(will_message) 319 | end 320 | 321 | -- Username and password 322 | -- ~~~~~~~~~~~~~~~~~~~~~ 323 | if type(self.username) == 'string' then 324 | payload = payload .. MQTT.client.encode_utf8(self.username) 325 | 326 | -- if no username, there can be no password. Empty string as username is OK. :-( 327 | if type(self.password) == 'string' then 328 | payload = payload .. MQTT.client.encode_utf8(self.password) 329 | end 330 | end 331 | 332 | -- Send CONNECT message 333 | local send_connect_result = self:message_write(MQTT.CONNECT, payload) 334 | if(send_connect_result ~= nil) then 335 | return("MQTT.client:connect(): Could not send CONNECT request: ".. send_result) 336 | end 337 | 338 | -- Now waiting for CONNACK message from the broker. 339 | -- Only after receiving a valid CONNACK message, self.connected will be true. 340 | local connack_result = self:wait_for_connack(MQTT.client.CONNACK_WAIT_TIMEOUT) 341 | if (connack_result == nil) then 342 | self.connected = true 343 | MQTT.Utility.debug("MQTT.client:connect() - Successful") 344 | else -- Deal with error here. 345 | MQTT.Utility.debug("MQTT.client:connect() - ".. connack_result) 346 | self:destroy() 347 | end 348 | 349 | return(connack_result) 350 | end 351 | 352 | ------------------------------------------------- 353 | -- Wait for CONNACK response from broker after a CONNECT request is sent. 354 | -- This should be the first message received from the broker. 355 | -- 356 | -- @param timeout maximum time to wait for a CONNACK response as per [MQTT-3.2] 357 | -- -- @function [parent = #client] wait_for_connack 358 | -- 359 | function MQTT.client:wait_for_connack( -- Internal API 360 | timeout) 361 | -- return: nil or error message 362 | 363 | local connack_received = false 364 | local error_message = nil 365 | 366 | local socket_ready = MQTT.Utility.socket_ready(self.socket_client, timeout) 367 | 368 | if (not socket_ready) then 369 | -- After seconds, assume CONNACK msg is not coming and give up. 370 | error_message = "Socket is not ready" 371 | else 372 | error_message, buffer = MQTT.Utility.socket_receive(self.socket_client) 373 | if (error_message == nil) then 374 | if (buffer ~= nil and #buffer > 0) then 375 | local message_type_flags = string.byte(buffer, 1) 376 | local message_type = MQTT.Utility.shift_right(message_type_flags, 4) 377 | 378 | if(message_type == MQTT.CONNACK) then 379 | -- Verify no CONNACK error is returned from broker 380 | local remaining_length = string.byte(buffer, 2) 381 | assert(remaining_length==2, "CONNACK:remaining_length must be 2!. It was: "..remaining_length ) 382 | 383 | -- local byte3 = string.byte(buffer, 3) -- Only SP bit is relevant 384 | 385 | local connect_return_code = string.byte(buffer, 4) 386 | if (connect_return_code ~= 0) then 387 | error_message = MQTT.error_message.CONNACK[connect_return_code] 388 | MQTT.Utility.debug("MQTT.client:wait_for_connack() - "..error_message) 389 | end 390 | else -- message_type != CONNACK 391 | -- We must have gotten a CONNACK and nothing ese at this point 392 | error_message = "Unexpected message type while waiting for CONNACK" 393 | end 394 | end 395 | end 396 | end 397 | 398 | return error_message 399 | end 400 | 401 | --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 402 | -- Destroy an MQTT client instance. 403 | -- @param self 404 | -- @function [parent = #client] destroy 405 | -- 406 | function MQTT.client:destroy() -- Public API 407 | MQTT.Utility.debug("MQTT.client:destroy()") 408 | 409 | if (self.destroyed == false) then 410 | self.destroyed = true -- Avoid recursion when message_write() fails 411 | 412 | if (self.connected) then self:disconnect() end 413 | 414 | --self.callback = nil 415 | self.outstanding = nil 416 | end 417 | end 418 | 419 | --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 420 | -- Transmit MQTT Disconnect message. 421 | -- MQTT 3.1 Specification: Section 3.14: Disconnect notification 422 | -- bytes 1,2: Fixed message header, see MQTT.client:message_write() 423 | -- @param self 424 | -- @function [parent = #client] disconnect 425 | -- 426 | function MQTT.client:disconnect() -- Public API 427 | MQTT.Utility.debug("MQTT.client:disconnect()") 428 | 429 | if (self.connected) then 430 | self:message_write(MQTT.DISCONNECT, nil) 431 | self.socket_client:close() 432 | self.connected = false 433 | else 434 | error("MQTT.client:disconnect(): Already disconnected") 435 | end 436 | end 437 | 438 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 439 | -- Encode a message string using UTF-8 (for variable header) 440 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 441 | -- MQTT 3.1.1 Specification: Section 1.5.3: UTF-8 Encoded strings. 442 | -- Unless stated otherwise UTF-8 encoded strings can have any length in the range 0 to 65535 bytes 443 | -- 444 | -- byte 1: String length MSB 445 | -- byte 2: String length LSB 446 | -- bytes 3-n: String encoded as UTF-8, if length > 0 447 | 448 | function MQTT.client.encode_utf8(input) 449 | 450 | local output 451 | output = string.char(math.floor(#input / 256)) 452 | output = output .. string.char(#input % 256) 453 | output = output .. input 454 | 455 | return(output) 456 | end 457 | 458 | --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 459 | -- Handle received messages and maintain keep-alive PING messages. 460 | -- This function must be invoked periodically (more often than the 461 | -- `MQTT.client.KEEP_ALIVE_TIME`) which maintains the connection and 462 | -- services the incoming subscribed topic messages 463 | -- @param self 464 | -- @function [parent = #client] handler 465 | -- 466 | function MQTT.client:handler() 467 | 468 | if (self.connected == false) then 469 | error("MQTT.client:handler(): Not connected") 470 | end 471 | 472 | MQTT.Utility.debug("MQTT.client:handler()") 473 | 474 | -- Transmit MQTT PING message 475 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~ 476 | -- MQTT 3.1.1 Specification: Section 3.12: PING request 477 | -- 478 | -- bytes 1,2: Fixed message header, see MQTT.client:message_write() 479 | 480 | local activity_timeout = self.last_activity + MQTT.client.KEEP_ALIVE_TIME 481 | 482 | if (MQTT.Utility.get_time() > activity_timeout) then 483 | MQTT.Utility.debug("MQTT.client:handler(): PINGREQ") 484 | 485 | self:message_write(MQTT.PINGREQ, nil) 486 | end 487 | 488 | -- Check for available client socket data 489 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 490 | local ready = MQTT.Utility.socket_ready(self.socket_client) 491 | if (ready) then 492 | local error_message, buffer = MQTT.Utility.socket_receive(self.socket_client) 493 | 494 | if (error_message ~= nil) then 495 | self:destroy() 496 | error_message = "socket_client:receive(): " .. error_message 497 | MQTT.Utility.debug(error_message) 498 | return(error_message) 499 | end 500 | 501 | if (buffer ~= nil and #buffer > 0) then 502 | local index = 1 503 | 504 | -- Parse individual messages (each must be at least 2 bytes long) 505 | -- Decode "remaining length" [MQTT-v3.1.1] (2.2.3) - Pages 18,19 506 | while (index < #buffer) do 507 | local message_type_flags = string.byte(buffer, index) 508 | local multiplier = 1 509 | local value = 0 510 | 511 | repeat 512 | index = index + 1 513 | local encodedByte = string.byte(buffer, index) -- 'next byte from stream' 514 | value = value + ((encodedByte % 128) * multiplier) -- (encodedByte & 127) * multiplier 515 | multiplier = multiplier * 128 516 | until encodedByte < 128 -- check continuation bit 517 | -- here 'value' contains remaining_length 518 | 519 | local message = string.sub(buffer, index + 1, index + value) 520 | if (#message == value) then 521 | self:parse_message(message_type_flags, value, message) 522 | else 523 | MQTT.Utility.debug( 524 | "MQTT.client:handler(): Incorrect remaining length: " .. 525 | value .. " ~= message length: " .. #message 526 | ) 527 | end 528 | 529 | index = index + value + 1 530 | end 531 | 532 | -- Check for any left over bytes, i.e. partial message received 533 | 534 | if (index ~= (#buffer + 1)) then 535 | local error_message = 536 | "MQTT.client:handler(): Partial message received" .. 537 | index .. " ~= " .. (#buffer + 1) 538 | 539 | if (MQTT.ERROR_TERMINATE) then -- TODO: Refactor duplicate code 540 | self:destroy() 541 | error(error_message) 542 | else 543 | MQTT.Utility.debug(error_message) 544 | end 545 | end 546 | end 547 | end 548 | 549 | return(nil) 550 | end 551 | 552 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 553 | -- Transmit an MQTT message 554 | -- ~~~~~~~~~~~~~~~~~~~~~~~~ 555 | -- MQTT 3.1 Specification: Section 2.1: Fixed header 556 | -- 557 | -- byte 1: Message type and flags (DUP, QOS level, and Retain) fields 558 | -- bytes 2-5: Remaining length field (between one and four bytes long) 559 | -- bytes m- : Optional variable header and payload 560 | 561 | function MQTT.client:message_write( -- Internal API 562 | message_type, -- enumeration 563 | payload, 564 | retain) -- string 565 | -- return: nil or error message 566 | 567 | -- TODO: Complete implementation of fixed header byte 1 568 | 569 | local message = string.char(MQTT.Utility.shift_left(message_type, 4)) 570 | 571 | -- [MQTT-v3.1.1](2.2.2) Fixed header flags: 572 | -- Fixed header Byte 1 must be 0x82 for SUBSCRIBE and 0xA2 for UNSUBSCRIBE 573 | -- Also 0x62 for PUBREL for when we support it. 574 | if( message_type == MQTT.SUBSCRIBE or 575 | message_type == MQTT.UNSUBSCRIBE or 576 | message_type == MQTT.PUBREL ) then 577 | message = string.char( MQTT.Utility.shift_left(message_type, 4) + 2) 578 | end 579 | 580 | if(message_type == MQTT.PUBLISH and retain == true) then 581 | message = string.char( MQTT.Utility.shift_left(message_type, 4) + 1) 582 | end 583 | 584 | if (payload == nil) then 585 | message = message .. string.char(0) -- Zero length, no payload 586 | else 587 | if (#payload > MQTT.client.MAX_PAYLOAD_LENGTH) then 588 | return( 589 | "MQTT.client:message_write(): Payload length = " .. #payload .. 590 | " exceeds maximum of " .. MQTT.client.MAX_PAYLOAD_LENGTH 591 | ) 592 | end 593 | 594 | -- Encode "remaining length" [MQTT-v3.1.1] Section. (2.2.3 pages 18,19) 595 | local encoded_rl_buf="" 596 | local x = #payload 597 | repeat 598 | local encoded_byte = x % 128 -- modulo in lua: a % b == a - math.floor(a / b ) * b 599 | x = math.floor(x / 128) -- integer division :-( 600 | if (x > 0) then 601 | encoded_byte = encoded_byte + 128 -- encodedByte OR 128 602 | end 603 | encoded_rl_buf = encoded_rl_buf .. string.char(encoded_byte) -- 'output' encodedByte 604 | until x <= 0 -- while ( x > 0 ) 605 | 606 | message = message .. encoded_rl_buf .. payload 607 | end 608 | 609 | local status, error_message = self.socket_client:send(message) 610 | 611 | if (status == nil) then 612 | self:destroy() 613 | return("MQTT.client:message_write(): " .. error_message) 614 | end 615 | 616 | self.last_activity = MQTT.Utility.get_time() 617 | return(nil) 618 | end 619 | 620 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 621 | -- Parse MQTT message 622 | -- ~~~~~~~~~~~~~~~~~~ 623 | -- MQTT 3.1 Specification: Section 2.1: Fixed header 624 | -- 625 | -- byte 1: Message type and flags (DUP, QOS level, and Retain) fields 626 | -- bytes 2-5: Remaining length field (between one and four bytes long) 627 | -- bytes m- : Optional variable header and payload 628 | -- 629 | -- The message type/flags and remaining length are already parsed and 630 | -- removed from the message by the time this function is invoked. 631 | -- Leaving just the optional variable header and payload. 632 | 633 | function MQTT.client:parse_message( -- Internal API 634 | message_type_flags, -- byte 635 | remaining_length, -- integer 636 | message) -- string: Optional variable header and payload 637 | 638 | local message_type = MQTT.Utility.shift_right(message_type_flags, 4) 639 | 640 | -- TODO: MQTT.TYPE table should include "parser handler" function. 641 | -- This would nicely collapse the if .. then .. elseif .. end. 642 | 643 | -- 644 | if (message_type == MQTT.CONNACK) then 645 | self:parse_message_connack(message_type_flags, remaining_length, message) 646 | 647 | elseif (message_type == MQTT.PUBLISH) then 648 | self:parse_message_publish(message_type_flags, remaining_length, message) 649 | 650 | elseif (message_type == MQTT.PUBACK) then 651 | print("MQTT.client:parse_message(): PUBACK -- UNIMPLEMENTED --") -- TODO 652 | 653 | elseif (message_type == MQTT.SUBACK) then 654 | self:parse_message_suback(message_type_flags, remaining_length, message) 655 | 656 | elseif (message_type == MQTT.UNSUBACK) then 657 | self:parse_message_unsuback(message_type_flags, remaining_length, message) 658 | 659 | elseif (message_type == MQTT.PINGREQ) then 660 | self:ping_response() 661 | 662 | elseif (message_type == MQTT.PINGRESP) then 663 | self:parse_message_pingresp(message_type_flags, remaining_length, message) 664 | 665 | else 666 | local error_message = 667 | "MQTT.client:parse_message(): Unknown message type: " .. message_type 668 | 669 | if (MQTT.ERROR_TERMINATE) then -- TODO: Refactor duplicate code 670 | self:destroy() 671 | error(error_message) 672 | else 673 | MQTT.Utility.debug(error_message) 674 | end 675 | end 676 | end 677 | 678 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 679 | -- Parse MQTT CONNACK message 680 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~ 681 | -- MQTT 3.1 Specification: Section 3.2: CONNACK Acknowledge connection 682 | -- 683 | -- byte 1: Reserved value 684 | -- byte 2: Connect return code, see MQTT.CONNACK.error_message[] 685 | 686 | function MQTT.client:parse_message_connack( -- Internal API 687 | message_type_flags, -- byte 688 | remaining_length, -- integer 689 | message) -- string 690 | 691 | local me = "MQTT.client:parse_message_connack()" 692 | MQTT.Utility.debug(me) 693 | 694 | if (remaining_length ~= 2) then 695 | error(me .. ": Invalid remaining length") 696 | end 697 | 698 | local return_code = string.byte(message, 2) 699 | 700 | if (return_code ~= 0) then 701 | local error_message = "Unknown return code" 702 | --local max_error = table.getn(MQTT.CONNACK.error_message) :HKN 703 | local max_error = #MQTT.error_message.CONNACK 704 | 705 | if (return_code <= max_error) then 706 | error_message = MQTT.error_message.CONNACK[return_code] 707 | end 708 | 709 | error(me .. ": CONNECT failed: " .. error_message) 710 | end 711 | end 712 | 713 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 714 | -- Parse MQTT PINGRESP message 715 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 716 | -- MQTT 3.1 Specification: Section 3.13: PING response 717 | 718 | function MQTT.client:parse_message_pingresp( -- Internal API 719 | message_type_flags, -- byte 720 | remaining_length, -- integer 721 | message) -- string 722 | 723 | local me = "MQTT.client:parse_message_pingresp()" 724 | MQTT.Utility.debug(me) 725 | 726 | if (remaining_length ~= 0) then 727 | error(me .. ": Invalid remaining length") 728 | end 729 | 730 | -- ToDo: self.ping_response_outstanding = false 731 | end 732 | 733 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 734 | -- Parse MQTT PUBLISH message 735 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~ 736 | -- MQTT 3.1 Specification: Section 3.3: Publish message 737 | -- 738 | -- Variable header .. 739 | -- bytes 1- : Topic name and optional Message Identifier (if QOS > 0) 740 | -- bytes m- : Payload 741 | 742 | function MQTT.client:parse_message_publish( -- Internal API 743 | message_type_flags, -- byte 744 | remaining_length, -- integer 745 | message) -- string 746 | 747 | local me = "MQTT.client:parse_message_publish()" 748 | MQTT.Utility.debug(me) 749 | 750 | if (self.callback ~= nil) then 751 | if (remaining_length < 3) then 752 | error(me .. ": Invalid remaining length: " .. remaining_length) 753 | end 754 | 755 | local topic_length = string.byte(message, 1) * 256 756 | topic_length = topic_length + string.byte(message, 2) 757 | local topic = string.sub(message, 3, topic_length + 2) 758 | local index = topic_length + 3 759 | 760 | -- Handle optional Message Identifier, for QOS levels 1 and 2 761 | -- TODO: Enable Subscribe with QOS and deal with PUBACK, etc. 762 | 763 | local qos = MQTT.Utility.shift_right(message_type_flags, 1) % 3 764 | 765 | if (qos > 0) then 766 | local message_id = string.byte(message, index) * 256 767 | message_id = message_id + string.byte(message, index + 1) 768 | index = index + 2 769 | end 770 | 771 | local payload_length = remaining_length - index + 1 772 | local payload = string.sub(message, index, index + payload_length - 1) 773 | 774 | self.callback(topic, payload) 775 | end 776 | end 777 | 778 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 779 | -- Parse MQTT SUBACK message 780 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~ 781 | -- MQTT 3.1 Specification: Section 3.9: SUBACK Subscription acknowledgement 782 | -- 783 | -- bytes 1,2: Message Identifier 784 | -- bytes 3- : List of granted QOS for each subscribed topic 785 | 786 | function MQTT.client:parse_message_suback( -- Internal API 787 | message_type_flags, -- byte 788 | remaining_length, -- integer 789 | message) -- string 790 | 791 | 792 | local me = "MQTT.client:parse_message_suback()" 793 | MQTT.Utility.debug(me) 794 | 795 | if (remaining_length < 3) then 796 | error(me .. ": Invalid remaining length: " .. remaining_length) 797 | end 798 | 799 | local message_id = string.byte(message, 1) * 256 + string.byte(message, 2) 800 | local outstanding = self.outstanding[message_id] 801 | 802 | if (outstanding == nil) then 803 | error(me .. ": No outstanding message: " .. message_id) 804 | end 805 | 806 | self.outstanding[message_id] = nil 807 | 808 | if (outstanding[1] ~= "subscribe") then 809 | error(me .. ": Outstanding message wasn't SUBSCRIBE") 810 | end 811 | 812 | --local topic_count = table.getn(outstanding[2]) 813 | local topic_count = #outstanding[2] 814 | 815 | if (topic_count ~= remaining_length - 2) then 816 | error(me .. ": Didn't received expected number of topics: " .. topic_count) 817 | end 818 | end 819 | 820 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 821 | -- Parse MQTT UNSUBACK message 822 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ 823 | -- MQTT 3.1 Specification: Section 3.11: UNSUBACK Unsubscription acknowledgement 824 | -- 825 | -- bytes 1,2: Message Identifier 826 | 827 | function MQTT.client:parse_message_unsuback( -- Internal API 828 | message_type_flags, -- byte 829 | remaining_length, -- integer 830 | message) -- string 831 | 832 | local me = "MQTT.client:parse_message_unsuback()" 833 | MQTT.Utility.debug(me) 834 | 835 | if (remaining_length ~= 2) then 836 | error(me .. ": Invalid remaining length") 837 | end 838 | 839 | local message_id = string.byte(message, 1) * 256 + string.byte(message, 2) 840 | 841 | local outstanding = self.outstanding[message_id] 842 | 843 | if (outstanding == nil) then 844 | error(me .. ": No outstanding message: " .. message_id) 845 | end 846 | 847 | self.outstanding[message_id] = nil 848 | 849 | if (outstanding[1] ~= "unsubscribe") then 850 | error(me .. ": Outstanding message wasn't UNSUBSCRIBE") 851 | end 852 | end 853 | 854 | -- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 855 | -- Transmit MQTT Ping response message 856 | -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 857 | -- MQTT 3.1 Specification: Section 3.13: PING response 858 | 859 | function MQTT.client:ping_response() -- Internal API 860 | MQTT.Utility.debug("MQTT.client:ping_response()") 861 | 862 | if (self.connected == false) then 863 | error("MQTT.client:ping_response(): Not connected") 864 | end 865 | 866 | self:message_write(MQTT.PINGRESP, nil) 867 | end 868 | 869 | --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 870 | -- Transmit MQTT Publish message. 871 | -- MQTT 3.1.1 Specification: Section 3.3: Publish message 872 | -- 873 | -- * bytes 1,2: Fixed message header, see MQTT.client:message_write() 874 | -- Variable header .. 875 | -- * bytes 3- : Topic name and optional Message Identifier (if QOS > 0) 876 | -- * bytes m- : Payload 877 | -- @param self 878 | -- @param #string topic 879 | -- @param #string payload 880 | -- @param #boolean retain publish this message with retain flag set 881 | -- @function [parent = #client] publish 882 | -- 883 | function MQTT.client:publish( -- Public API 884 | topic, 885 | payload, -- string 886 | retain) -- boolean 887 | 888 | if (self.connected == false) then 889 | error("MQTT.client:publish(): Not connected") 890 | end 891 | 892 | MQTT.Utility.debug("MQTT.client:publish(): " .. topic) 893 | 894 | local message = MQTT.client.encode_utf8(topic) .. payload 895 | 896 | self:message_write(MQTT.PUBLISH, message, retain) 897 | end 898 | 899 | --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 900 | -- Transmit MQTT Subscribe message. 901 | -- MQTT 3.1 Specification: Section 3.8: Subscribe to named topics 902 | -- 903 | -- * bytes 1,2: Fixed message header, see MQTT.client:message_write() 904 | -- Variable header .. 905 | -- * bytes 3,4: Message Identifier 906 | -- * bytes 5- : List of topic names and their QOS level 907 | -- @param self 908 | -- @param #string topics table of strings 909 | -- @function [parent = #client] subscribe 910 | -- 911 | function MQTT.client:subscribe( -- Public API 912 | topics) -- table of strings 913 | 914 | if (self.connected == false) then 915 | error("MQTT.client:subscribe(): Not connected") 916 | end 917 | 918 | self.message_id = self.message_id + 1 919 | 920 | local message 921 | message = string.char(math.floor(self.message_id / 256)) 922 | message = message .. string.char(self.message_id % 256) 923 | 924 | for index, topic in ipairs(topics) do 925 | MQTT.Utility.debug("MQTT.client:subscribe(): " .. topic) 926 | message = message .. MQTT.client.encode_utf8(topic) 927 | message = message .. string.char(0) -- QOS level 0 928 | end 929 | self:message_write(MQTT.SUBSCRIBE, message) 930 | 931 | self.outstanding[self.message_id] = { "subscribe", topics } 932 | end 933 | 934 | --- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -- 935 | -- Transmit MQTT Unsubscribe message 936 | -- MQTT 3.1 Specification: Section 3.10: Unsubscribe from named topics 937 | -- 938 | -- * bytes 1,2: Fixed message header, see MQTT.client:message_write() 939 | -- Variable header .. 940 | -- * bytes 3,4: Message Identifier 941 | -- * bytes 5- : List of topic names 942 | -- @param self 943 | -- @param #string topics table of strings 944 | -- @function [parent = #client] unsubscribe 945 | -- 946 | function MQTT.client:unsubscribe( -- Public API 947 | topics) -- table of strings 948 | 949 | if (self.connected == false) then 950 | error("MQTT.client:unsubscribe(): Not connected") 951 | end 952 | 953 | self.message_id = self.message_id + 1 954 | 955 | local message 956 | message = string.char(math.floor(self.message_id / 256)) 957 | message = message .. string.char(self.message_id % 256) 958 | 959 | for index, topic in ipairs(topics) do 960 | MQTT.Utility.debug("MQTT.client:unsubscribe(): " .. topic) 961 | message = message .. MQTT.client.encode_utf8(topic) 962 | end 963 | 964 | self:message_write(MQTT.UNSUBSCRIBE, message) 965 | 966 | self.outstanding[self.message_id] = { "unsubscribe", topics } 967 | end 968 | 969 | return(MQTT) 970 | -------------------------------------------------------------------------------- /paho/utility.lua: -------------------------------------------------------------------------------- 1 | --- 2 | -- @module Utility 3 | -- ~~~~~~~~~~~ 4 | -- Version: 0.3 2014-10-06 5 | -- -------------------------------------------------------------------------- -- 6 | -- Copyright (c) 2011-2012 Geekscape Pty. Ltd. 7 | -- All rights reserved. This program and the accompanying materials 8 | -- are made available under the terms of the Eclipse Public License v1.0 9 | -- which accompanies this distribution, and is available at 10 | -- http://www.eclipse.org/legal/epl-v10.html 11 | -- 12 | -- Contributors: 13 | -- Andy Gelme - Initial API and implementation 14 | -- -------------------------------------------------------------------------- -- 15 | -- 16 | -- Notes 17 | -- ~~~~~ 18 | -- - Works on the Sony PlayStation Portable (aka Sony PSP) ... 19 | -- See http://en.wikipedia.org/wiki/Lua_Player_HM 20 | -- 21 | -- ToDo 22 | -- ~~~~ 23 | -- - shift_left() should mask bits past the 8, 16, 32 and 64-bit boundaries. -- TODO: What does this mean? 24 | -- ------------------------------------------------------------------------- -- 25 | local socket = require("socket") 26 | 27 | local function isPsp() return(Socket ~= nil) end 28 | 29 | if (isPsp()) then socket = Socket end -- Compatibility ! 30 | 31 | -- ------------------------------------------------------------------------- -- 32 | 33 | local debug_flag = true 34 | 35 | local function set_debug(value) debug_flag = value end 36 | 37 | local function debug(message) 38 | if (debug_flag) then print(message) end 39 | end 40 | 41 | -- ------------------------------------------------------------------------- -- 42 | 43 | local function dump_string(value) 44 | local index 45 | 46 | for index = 1, string.len(value) do 47 | print(string.format("%d: %02x", index, string.byte(value, index))) 48 | end 49 | end 50 | 51 | -- ------------------------------------------------------------------------- -- 52 | 53 | local timer 54 | 55 | if (isPsp()) then 56 | timer = Timer.new() 57 | timer:start() 58 | end 59 | 60 | local function get_time() 61 | if (isPsp()) then 62 | return(timer:time() / 1000) 63 | else 64 | return(socket.gettime()) 65 | end 66 | end 67 | 68 | local function expired(last_time, duration, type) 69 | local time_expired = get_time() >= (last_time + duration) 70 | 71 | if (time_expired) then debug("Event: " .. type) end 72 | return(time_expired) 73 | end 74 | 75 | -- ------------------------------------------------------------------------- -- 76 | 77 | local function shift_left(value, shift) 78 | return(value * 2 ^ shift) 79 | end 80 | 81 | local function shift_right(value, shift) 82 | return(math.floor(value / 2 ^ shift)) 83 | end 84 | 85 | -- ------------------------------------------------------------------------- -- 86 | 87 | local function socket_ready(socket_client, timeout) 88 | local ready, read_sockets, write_sockets, error_state = true, nil, nil, nil 89 | 90 | local stimeout = timeout or 0.001 91 | if (not isPsp()) then 92 | read_sockets, write_sockets, error_state = 93 | socket.select({socket_client}, nil, stimeout) 94 | 95 | if (#read_sockets == 0) then ready = false end 96 | end 97 | 98 | return(ready) 99 | end 100 | 101 | local function socket_receive(socket_client, byte_count) 102 | local response, error_message, partial_buffer = nil, nil, nil 103 | local result_buffer = nil 104 | 105 | if (isPsp()) then 106 | byte_count = byte_count or 128 -- default 107 | buffer = socket_client:recv(byte_count) 108 | else 109 | response, error_message, partial_buffer = socket_client:receive("*a") 110 | 111 | if response == nil then --either error or partial response 112 | -- error_message-> "closed" | "timeout" 113 | if error_message == "timeout" then error_message = nil end 114 | result_buffer = partial_buffer 115 | else 116 | result_buffer = response 117 | end 118 | end 119 | -- error_message -> nil | "closed" 120 | return(error_message), (result_buffer) 121 | end 122 | 123 | 124 | --[[ 125 | TODO: Write doc for what this is for. Seems to be doing conflicting things 126 | for psp it is just spinning. 127 | Also socket does not have isConnected() function from the docs. Maybe there is for psp 128 | --]] 129 | local function socket_wait_connected(socket_client, timeout) 130 | if (isPsp()) then 131 | while (socket_client:isConnected() == false) do 132 | System.sleep(100) 133 | end 134 | else 135 | socket_client:settimeout(timeout or 0.01) -- So that socket.recieve doesn't block 136 | end 137 | end 138 | 139 | -- ------------------------------------------------------------------------- -- 140 | 141 | local function table_to_string(table) 142 | local result = '' 143 | 144 | if (type(table) == 'table') then 145 | result = '{ ' 146 | 147 | for index = 1, #table do 148 | result = result .. table_to_string(table[index]) 149 | if (index ~= #table) then 150 | result = result .. ', ' 151 | end 152 | end 153 | 154 | result = result .. ' }' 155 | else 156 | result = tostring(table) 157 | end 158 | 159 | return(result) 160 | end 161 | 162 | -- ------------------------------------------------------------------------- -- 163 | -- Define Utility "module" 164 | -- ~~~~~~~~~~~~~~~~~~~~~~~ 165 | 166 | local Utility = {} 167 | 168 | --- 169 | -- @function [parent = #utility] isPsp 170 | -- 171 | Utility.isPsp = isPsp 172 | 173 | --- 174 | -- @param #boolean flag 175 | -- @function [parent = #utility] set_debug 176 | -- 177 | Utility.set_debug = set_debug 178 | 179 | --- 180 | -- @param #string message 181 | -- @function [parent = #utility] debug 182 | -- 183 | Utility.debug = debug 184 | 185 | --- 186 | -- @param #string value 187 | -- @function [parent = #utility] dump_string 188 | -- 189 | 190 | Utility.dump_string = dump_string 191 | 192 | --- 193 | -- @function [parent = #utility] get_time 194 | -- @return #number 195 | -- 196 | Utility.get_time = get_time 197 | 198 | --- 199 | -- @param #number last_time 200 | -- @param #number duration 201 | -- @param #string type 202 | -- @function [parent = #utility] expired 203 | -- @return #number 204 | -- 205 | Utility.expired = expired 206 | 207 | --- 208 | -- @param #number value 209 | -- @param #number shift 210 | -- @function [parent = #utility] shift_left 211 | -- @return #number 212 | -- 213 | Utility.shift_left = shift_left 214 | 215 | --- 216 | -- @param #number value 217 | -- @param #number shift 218 | -- @function [parent = #utility] shift_left 219 | -- @return #number 220 | -- 221 | Utility.shift_right = shift_right 222 | 223 | --- 224 | -- @param socket_client 225 | -- @function [parent = #utility] socket_ready 226 | -- @return #boolean 227 | -- 228 | Utility.socket_ready = socket_ready 229 | 230 | --- 231 | -- @param socket_client 232 | -- @param #number byte_count 233 | -- @function [parent = #utility] socket_receive 234 | -- @return #string,#string 235 | -- 236 | Utility.socket_receive = socket_receive 237 | 238 | --- 239 | -- @param socket_client 240 | -- @function [parent = #utility] socket_wait_connected 241 | -- 242 | Utility.socket_wait_connected = socket_wait_connected 243 | 244 | --- 245 | -- @param #table table 246 | -- @function [parent = #utility] table_to_string 247 | -- @return #string 248 | -- 249 | Utility.table_to_string = table_to_string 250 | 251 | -- For ... Utility = require 'paho.utility' 252 | 253 | return(Utility) 254 | 255 | -- ------------------------------------------------------------------------- -- 256 | -------------------------------------------------------------------------------- /rocks/paho-mqtt-0.3.0-1.rockspec: -------------------------------------------------------------------------------- 1 | package = 'paho-mqtt' 2 | version = '0.3.0-1' 3 | source = { 4 | url = 'git://git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.lua.git', 5 | tag = 'v0.3.0-1', 6 | } 7 | 8 | description = { 9 | summary = 'Client-side implementation of MQTT', 10 | detailed = [[Implements the client-side subset of the MQTT protocol 11 | specification 3.1, plus command-line utilities for publishing and 12 | subscribing to MQTT topics. Typically, one or more MQTT servers, 13 | such as mosquitto or rsmb will be running on host systems, with 14 | which the Lua MQTT client can interact.]], 15 | license = 'EPL', 16 | homepage = 'https://www.eclipse.org/paho/', 17 | maintainer = 'Kevin KIN-FOO ', 18 | } 19 | 20 | dependencies = { 21 | 'lua ~> 5.1', 22 | 'luafilesystem ~> 1.6', 23 | 'luasocket ~> 3.0', 24 | 'penlight ~> 1.3', 25 | } 26 | 27 | build = { 28 | type = 'builtin', 29 | modules = { 30 | ['paho.mqtt'] = 'paho/mqtt.lua', 31 | ['paho.utility'] = 'paho/utility.lua', 32 | }, 33 | install = { 34 | bin = { 35 | mqtt_publish = 'paho/example/mqtt_publish.lua', 36 | mqtt_subscribe = 'paho/example/mqtt_subscribe.lua', 37 | } 38 | } 39 | } 40 | --------------------------------------------------------------------------------