├── .gitignore ├── LICENSE ├── README.md ├── examples ├── attr_req.py ├── attr_subs.py ├── auth_basic.py ├── auth_token.py ├── freemem.py └── rpc_request.py ├── package.json ├── package.sh ├── sdist_upip.py ├── setup.py └── uthingsboard ├── __init__.py └── client.py /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /dist/ 3 | /thingsboard_micropython.egg-info/ 4 | /venv/ 5 | /__pycache__/ 6 | *code-workspace 7 | MANIFEST -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ThingsBoard MQTT MicroPython client 2 | 3 | This project is a MicroPython library that provides an client for the [Device](https://thingsboard.io/docs/reference/mqtt-api/) API of [ThingsBoard](https://thingsboard.io/) open-source IoT Platform. 4 | 5 | The library consists of a thin wrapper around the MicroPython MQTT module, [umqtt.robust](https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.robust/umqtt/robust.py). 6 | 7 | ## Installation 8 | 9 | To install using pip: 10 | 11 | ```python 12 | import upip 13 | upip.install('thingsboard-micropython') 14 | ``` 15 | 16 | ## Getting Started 17 | 18 | Client initialization and telemetry publishing: 19 | 20 | ```python 21 | from uthingsboard.client import TBDeviceMqttClient 22 | 23 | # See examples for more authentication options 24 | client = TBDeviceMqttClient('demo.thingsboard.io', access_token='test01') 25 | 26 | # Connecting to ThingsBoard 27 | client.connect() 28 | 29 | # Sending telemetry 30 | telemetry = {'temperature': 41.9, 'enabled': False} 31 | client.send_telemetry(telemetry) 32 | 33 | # Checking for incoming subscriptions or RPC call requests (non-blocking) 34 | client.check_msg() 35 | 36 | # Disconnecting from ThingsBoard 37 | client.disconnect() 38 | ``` 39 | 40 | ## Examples 41 | 42 | More examples can be found in [examples](https://github.com/coredumplabs/thingsboard-micropython/tree/main/examples) directory. 43 | 44 | ## Support 45 | 46 | - SSL and QoS (0 or 1) as supported by the backend MQTT library, [umqtt.robust](https://github.com/micropython/micropython-lib/blob/master/micropython/umqtt.robust/umqtt/robust.py). 47 | - All [Device](https://thingsboard.io/docs/reference/mqtt-api/) API's, except Provisioning. 48 | - Tested only on ESP32 board running MicroPython v1.16 generic. 49 | 50 | ## Acknowledgment 51 | 52 | This library is an adapted version of the official [ThingsBoard client SDK for Python](https://github.com/thingsboard/thingsboard-python-client-sdk), 53 | to run in MicroPython. 54 | 55 | ## License 56 | 57 | This project is released under [Apache 2.0 License](https://github.com/coredumplabs/thingsboard-micropython/tree/main/LICENSE). 58 | -------------------------------------------------------------------------------- /examples/attr_req.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | from uthingsboard.client import TBDeviceMqttClient 6 | 7 | 8 | def on_attributes_change(data): 9 | print(data) 10 | 11 | 12 | def main(): 13 | client = TBDeviceMqttClient('127.0.0.1', access_token='test01') 14 | client.connect() 15 | 16 | # request attributes, wait for reply and process it in the callback 17 | client.request_attributes(client_keys=['myAttr1'], 18 | shared_keys=['myAttr2', 'myAttr3'], 19 | callback=on_attributes_change) 20 | client.wait_msg() 21 | 22 | client.disconnect() 23 | 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /examples/attr_subs.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | from uthingsboard.client import TBDeviceMqttClient 6 | 7 | 8 | def callback(data): 9 | print(data) 10 | 11 | 12 | def main(): 13 | client = TBDeviceMqttClient('127.0.0.1', access_token='test01') 14 | client.connect() 15 | 16 | sub_id_1 = client.subscribe_to_attribute('uploadFrequency', callback) 17 | sub_id_2 = client.subscribe_to_all_attributes(callback) 18 | 19 | client.unsubscribe_from_attribute(sub_id_1) 20 | client.unsubscribe_from_attribute(sub_id_2) 21 | 22 | client.disconnect() 23 | 24 | 25 | if __name__ == '__main__': 26 | main() 27 | -------------------------------------------------------------------------------- /examples/auth_basic.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | from uthingsboard.client import TBDeviceMqttClient 6 | 7 | 8 | def main(): 9 | # Basic auth with user and password 10 | credentials = {'user': 'myuser', 'password': 'mypassword'} 11 | 12 | # Basic auth with user only 13 | # credentials = {'user': 'myuser'} 14 | 15 | # Basic auth with Client ID only 16 | # credentials = {'client_id': 'myclient'} 17 | 18 | # Basic auth with all fields: 19 | # credentials = {'user': 'myuser', 'password': 'mypassword', 20 | # 'client_id': 'myclient'} 21 | 22 | client = TBDeviceMqttClient('127.0.0.1', basic_auth=credentials) 23 | client.connect() 24 | client.disconnect() 25 | 26 | 27 | if __name__ == '__main__': 28 | main() 29 | -------------------------------------------------------------------------------- /examples/auth_token.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | from uthingsboard.client import TBDeviceMqttClient 6 | 7 | 8 | def main(): 9 | client = TBDeviceMqttClient('127.0.0.1', access_token='test01') 10 | client.connect() 11 | client.disconnect() 12 | 13 | 14 | if __name__ == '__main__': 15 | main() 16 | -------------------------------------------------------------------------------- /examples/freemem.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | import gc 6 | import time 7 | 8 | from uthingsboard.client import TBDeviceMqttClient 9 | 10 | 11 | telemetry_interval = 5 12 | client = TBDeviceMqttClient('127.0.0.1', access_token='test01') 13 | 14 | 15 | # this callback changes global variable defining how often telemetry is sent 16 | def on_telemetry_interval_change(value): 17 | global telemetry_interval 18 | if 'telemetryInterval' in value: 19 | telemetry_interval = int(value['telemetryInterval']) 20 | elif 'shared' in value and 'telemetryInterval' in value['shared']: 21 | telemetry_interval = int(value['shared']['telemetryInterval']) 22 | 23 | 24 | # this callback handles RPC requests from server 25 | def handle_rpc_request(request_id, method, params): 26 | print('Request ID {req}: {method}({params})'.format(req=request_id, 27 | method=method, 28 | params=params)) 29 | if method == 'getFreeMemory': 30 | client.send_rpc_reply(request_id, {'memFree': gc.mem_free()}) 31 | 32 | 33 | def main(): 34 | client.set_server_side_rpc_request_handler(handle_rpc_request) 35 | client.connect() 36 | 37 | # subscribe to future changes of upload frequency 38 | client.subscribe_to_attribute('telemetryInterval', 39 | on_telemetry_interval_change) 40 | 41 | # fetch the latest setting for upload frequency configured on the server 42 | client.request_attributes(shared_keys=['telemetryInterval'], 43 | callback=on_telemetry_interval_change) 44 | 45 | while True: 46 | client.send_telemetry({'getFreeMemory': gc.mem_free()}) 47 | client.check_msg() 48 | time.sleep(telemetry_interval) 49 | 50 | 51 | if __name__ == '__main__': 52 | main() 53 | -------------------------------------------------------------------------------- /examples/rpc_request.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | from uthingsboard.client import TBDeviceMqttClient 6 | 7 | 8 | def callback(resp_id, data): 9 | print('Response {id}: {data})'.format(id=resp_id, data=data)) 10 | 11 | 12 | def main(): 13 | client = TBDeviceMqttClient('127.0.0.1', access_token='test01') 14 | client.connect() 15 | 16 | # call "getTime" on server and receive result, then process it on callback 17 | client.send_rpc_call('getTime', {}, callback) 18 | client.wait_msg() 19 | 20 | client.disconnect() 21 | 22 | 23 | if __name__ == '__main__': 24 | main() 25 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "urls": [ 3 | [ 4 | "uthingsboard/__init__.py", 5 | "github:manuargue/thingsboard-micropython/uthingsboard/__init__.py" 6 | ], 7 | [ 8 | "uthingsboard/client.py", 9 | "github:manuargue/thingsboard-micropython/uthingsboard/client.py" 10 | ] 11 | ], 12 | "deps": [ 13 | ], 14 | "version": "0.2.0" 15 | } -------------------------------------------------------------------------------- /package.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/bash 2 | # Copyright 2021 Coredump Labs 3 | # 4 | # SPDX-License-Identifier: Apache-2.0 5 | 6 | set -e 7 | 8 | upload=n 9 | clean=n 10 | build=n 11 | 12 | usage() { 13 | echo "usage: PYPI_CREDENTIALS=user:password ./package.sh [--upload] [--clean] [--build]" 14 | } 15 | 16 | if [[ "$@" -eq 0 ]]; then 17 | usage 18 | exit 1 19 | fi 20 | 21 | for i in "$@"; do 22 | case $i in 23 | --upload|-u) 24 | upload=y 25 | ;; 26 | --clean|-c) 27 | clean=y 28 | ;; 29 | --build|-b) 30 | build=y 31 | ;; 32 | *) 33 | usage 34 | exit 1 35 | ;; 36 | esac 37 | shift 38 | done 39 | 40 | if [ "$clean" == "y" ]; then 41 | rm -rf dist/ thingsboard_micropython.egg-info/ __pycache__/ MANIFEST 42 | fi 43 | 44 | if [ "$build" == "y" ]; then 45 | python3 setup.py sdist 46 | twine check dist/thingsboard-micropython-*.tar.gz 47 | fi 48 | 49 | if [ "$upload" == "y" ]; then 50 | user="${PYPI_CREDENTIALS/:*}" 51 | password="${PYPI_CREDENTIALS#*:}" 52 | twine upload dist/thingsboard-micropython-*.tar.gz -u "$user" -p "$password" 53 | fi 54 | -------------------------------------------------------------------------------- /sdist_upip.py: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2016-2019 Paul Sokolovsky 2 | # Licence: MIT 3 | # 4 | # This module overrides distutils (also compatible with setuptools) "sdist" 5 | # command to perform pre- and post-processing as required for Pycopy's 6 | # upip package manager. 7 | # 8 | # Preprocessing steps: 9 | # * Creation of Python resource module (R.py) from each top-level package's 10 | # resources. 11 | # Postprocessing steps: 12 | # * Removing metadata files not used by upip (this includes setup.py) 13 | # * Recompressing gzip archive with 4K dictionary size so it can be 14 | # installed even on low-heap targets. 15 | # 16 | # This module is part of Pycopy https://github.com/pfalcon/pycopy 17 | # and pycopy-lib https://github.com/pfalcon/pycopy-lib, projects to 18 | # create a (very) lightweight full-stack Python distribution. 19 | # 20 | # This file is not part delivered as part of thingsboard-micropython project 21 | # and is only used for generating the library distributable. 22 | 23 | import sys 24 | import os 25 | import zlib 26 | from subprocess import Popen, PIPE 27 | import glob 28 | import tarfile 29 | import re 30 | import io 31 | 32 | from distutils.filelist import FileList 33 | from setuptools.command.sdist import sdist as _sdist 34 | 35 | 36 | def gzip_4k(inf, fname): 37 | comp = zlib.compressobj(level=9, wbits=16 + 12) 38 | with open(fname + ".out", "wb") as outf: 39 | while 1: 40 | data = inf.read(1024) 41 | if not data: 42 | break 43 | outf.write(comp.compress(data)) 44 | outf.write(comp.flush()) 45 | os.rename(fname, fname + ".orig") 46 | os.rename(fname + ".out", fname) 47 | 48 | 49 | FILTERS = [ 50 | # include, exclude, repeat 51 | (r".+\.egg-info/(PKG-INFO|requires\.txt)", r"setup.py$"), 52 | (r".+\.py$", r"[^/]+$"), 53 | (None, r".+\.egg-info/.+"), 54 | ] 55 | 56 | 57 | outbuf = io.BytesIO() 58 | 59 | def filter_tar(name): 60 | fin = tarfile.open(name, "r:gz") 61 | fout = tarfile.open(fileobj=outbuf, mode="w") 62 | for info in fin: 63 | # print(info) 64 | if not "/" in info.name: 65 | continue 66 | fname = info.name.split("/", 1)[1] 67 | include = None 68 | 69 | for inc_re, exc_re in FILTERS: 70 | if include is None and inc_re: 71 | if re.match(inc_re, fname): 72 | include = True 73 | 74 | if include is None and exc_re: 75 | if re.match(exc_re, fname): 76 | include = False 77 | 78 | if include is None: 79 | include = True 80 | 81 | if include: 82 | print("including:", fname) 83 | else: 84 | print("excluding:", fname) 85 | continue 86 | 87 | farch = fin.extractfile(info) 88 | fout.addfile(info, farch) 89 | fout.close() 90 | fin.close() 91 | 92 | 93 | def make_resource_module(manifest_files): 94 | resources = [] 95 | # Any non-python file included in manifest is resource 96 | for fname in manifest_files: 97 | ext = fname.rsplit(".", 1) 98 | if len(ext) > 1: 99 | ext = ext[1] 100 | else: 101 | ext = "" 102 | if ext != "py": 103 | resources.append(fname) 104 | 105 | if resources: 106 | print("creating resource module R.py") 107 | resources.sort() 108 | last_pkg = None 109 | r_file = None 110 | for fname in resources: 111 | try: 112 | pkg, res_name = fname.split("/", 1) 113 | except ValueError: 114 | print("not treating %s as a resource" % fname) 115 | continue 116 | if last_pkg != pkg: 117 | last_pkg = pkg 118 | if r_file: 119 | r_file.write("}\n") 120 | r_file.close() 121 | r_file = open(pkg + "/R.py", "w") 122 | r_file.write("R = {\n") 123 | 124 | with open(fname, "rb") as f: 125 | r_file.write("%r: %r,\n" % (res_name, f.read())) 126 | 127 | if r_file: 128 | r_file.write("}\n") 129 | r_file.close() 130 | 131 | 132 | class sdist(_sdist): 133 | 134 | def run(self): 135 | self.filelist = FileList() 136 | self.get_file_list() 137 | make_resource_module(self.filelist.files) 138 | 139 | r = super().run() 140 | 141 | assert len(self.archive_files) == 1 142 | print("filtering files and recompressing with 4K dictionary") 143 | filter_tar(self.archive_files[0]) 144 | outbuf.seek(0) 145 | gzip_4k(outbuf, self.archive_files[0]) 146 | 147 | return r 148 | 149 | 150 | # For testing only 151 | if __name__ == "__main__": 152 | filter_tar(sys.argv[1]) 153 | outbuf.seek(0) 154 | gzip_4k(outbuf, sys.argv[1]) 155 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | import pathlib 6 | import sdist_upip 7 | from setuptools import setup 8 | 9 | 10 | HERE = pathlib.Path(__file__).parent 11 | README = (HERE / 'README.md').read_text() 12 | 13 | VERSION = '0.2.0' 14 | 15 | setup( 16 | name='thingsboard-micropython', 17 | version=VERSION, 18 | description='ThingsBoard MQTT MicroPython client', 19 | long_description=README, 20 | long_description_content_type='text/markdown', 21 | url='https://github.com/coredumplabs/thingsboard-micropython', 22 | license='Apache Software License (Apache Software License 2.0)', 23 | author='Coredump Labs', 24 | author_email='info@coredumplabs.com', 25 | classifiers=[ 26 | 'License :: OSI Approved :: Apache Software License', 27 | 'Programming Language :: Python :: Implementation :: MicroPython', 28 | ], 29 | packages=['uthingsboard'], 30 | cmdclass={'sdist': sdist_upip.sdist}, 31 | download_url=f'https://github.com/coredumplabs/thingsboard-micropython/releases/tag/v{VERSION}' 32 | ) 33 | -------------------------------------------------------------------------------- /uthingsboard/__init__.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | __name__ = 'uthingsboard' 6 | __version__ = '0.2.0' 7 | -------------------------------------------------------------------------------- /uthingsboard/client.py: -------------------------------------------------------------------------------- 1 | # Copyright 2021 Coredump Labs 2 | # 3 | # SPDX-License-Identifier: Apache-2.0 4 | 5 | import json 6 | import sys 7 | 8 | from umqtt.robust import MQTTClient 9 | 10 | 11 | RPC_RESPONSE_TOPIC = 'v1/devices/me/rpc/response/' 12 | RPC_REQUEST_TOPIC = 'v1/devices/me/rpc/request/' 13 | ATTRIBUTES_TOPIC = 'v1/devices/me/attributes' 14 | ATTRIBUTES_TOPIC_REQUEST = 'v1/devices/me/attributes/request/' 15 | ATTRIBUTES_TOPIC_RESPONSE = 'v1/devices/me/attributes/response/' 16 | TELEMETRY_TOPIC = 'v1/devices/me/telemetry' 17 | CLAIMING_TOPIC = 'v1/devices/me/claim' 18 | PROVISION_TOPIC_REQUEST = '/provision/request' 19 | PROVISION_TOPIC_RESPONSE = '/provision/response' 20 | 21 | 22 | class TBQoSException(Exception): 23 | pass 24 | 25 | 26 | class TBAuthException(Exception): 27 | pass 28 | 29 | 30 | def validate_qos(qos): 31 | if qos not in (0, 1): 32 | raise TBQoSException('Quality of service (qos) value must be 0 or 1') 33 | 34 | 35 | class TBDeviceMqttClient: 36 | 37 | DEBUG = False 38 | 39 | def __init__(self, host, port=1883, access_token=None, basic_auth=None, 40 | keepalive=0, ssl_params=None, qos=0): 41 | validate_qos(qos) 42 | 43 | # validate authentication 44 | if access_token and basic_auth: 45 | raise TBAuthException('Only one auth method must be provided') 46 | elif access_token: 47 | user = access_token 48 | password = client_id = '' 49 | elif basic_auth: 50 | valid_keys = ('user', 'password', 'client_id') 51 | if not all(k in valid_keys for k in basic_auth.keys()): 52 | raise TBAuthException('valid keys are {}'.format(valid_keys)) 53 | elif basic_auth.get('password') and not basic_auth.get('user'): 54 | raise TBAuthException('user must be provided') 55 | elif not basic_auth.get('user') and not basic_auth.get('client_id'): 56 | raise TBAuthException('client_id or user must be provided') 57 | user = basic_auth.get('user', '') 58 | password = basic_auth.get('password', '') 59 | client_id = basic_auth.get('client_id', '') 60 | else: 61 | raise TBAuthException('At least one auth method must be provided') 62 | 63 | ssl_params = ssl_params if ssl_params else {} 64 | self._client = MQTTClient(client_id, host, port=port, user=user, 65 | password=password, keepalive=keepalive, 66 | ssl=bool(ssl_params), ssl_params=ssl_params) 67 | 68 | self._qos = qos 69 | self._is_connected = False 70 | self._attr_request_dict = {} 71 | self._device_on_server_side_rpc_response = None 72 | self._device_max_sub_id = 0 73 | self._device_client_rpc_number = 0 74 | self._device_sub_dict = {} 75 | self._device_client_rpc_dict = {} 76 | self._attr_request_number = 0 77 | self._client.set_callback(self._on_message) 78 | 79 | def is_connected(self): 80 | return self._is_connected 81 | 82 | def connect(self): 83 | if self._is_connected: 84 | return 0 85 | 86 | ret = self._client.connect() 87 | if ret == 0: 88 | self._log('Connected to ThingsBoard') 89 | self._is_connected = True 90 | self._log('Subscribing to attributes and RPC topics') 91 | self._client.subscribe(ATTRIBUTES_TOPIC, qos=self._qos) 92 | self._client.subscribe(ATTRIBUTES_TOPIC + '/response/+', 93 | qos=self._qos) 94 | self._client.subscribe(RPC_REQUEST_TOPIC + '+', qos=self._qos) 95 | self._client.subscribe(RPC_RESPONSE_TOPIC + '+', qos=self._qos) 96 | return ret 97 | 98 | def reconnect(self): 99 | self._log('Reconnecting to ThingsBoard') 100 | return self._client.reconnect() 101 | 102 | def disconnect(self): 103 | if self._is_connected: 104 | self._log('Disconnecting from ThingsBoard') 105 | self._client.disconnect() 106 | self._is_connected = False 107 | 108 | def wait_msg(self): 109 | return self._client.wait_msg() 110 | 111 | def check_msg(self): 112 | return self._client.check_msg() 113 | 114 | def claim(self, secret_key, duration=30000): 115 | claiming_request = { 116 | 'secretKey': secret_key, 117 | 'durationMs': duration 118 | } 119 | self._client.publish(CLAIMING_TOPIC, json.dumps( 120 | claiming_request), qos=self._qos) 121 | 122 | def send_rpc_reply(self, req_id, resp, qos=0): 123 | validate_qos(qos) 124 | self._client.publish(RPC_RESPONSE_TOPIC + req_id, resp, qos=qos) 125 | 126 | def send_rpc_call(self, method, params, callback): 127 | self._device_client_rpc_number += 1 128 | self._device_client_rpc_dict.update( 129 | {self._device_client_rpc_number: callback}) 130 | rpc_request_id = self._device_client_rpc_number 131 | payload = {'method': method, 'params': params} 132 | self._client.publish(RPC_REQUEST_TOPIC + str(rpc_request_id), 133 | json.dumps(payload), 134 | qos=self._qos) 135 | 136 | def set_server_side_rpc_request_handler(self, handler): 137 | # handler signature is callback(req_id, method, params) 138 | self._device_on_server_side_rpc_response = handler 139 | 140 | def publish_data(self, topic, data, qos=0): 141 | validate_qos(qos) 142 | self._client.publish(topic, json.dumps(data), qos=qos) 143 | 144 | def send_telemetry(self, telemetry, qos=0): 145 | if not isinstance(telemetry, list): 146 | telemetry = [telemetry] 147 | return self.publish_data(TELEMETRY_TOPIC, telemetry, qos=qos) 148 | 149 | def send_attributes(self, attributes, qos=0): 150 | # attributes is a string or a list of strings 151 | return self.publish_data(ATTRIBUTES_TOPIC, attributes, qos=qos) 152 | 153 | def unsubscribe_from_attribute(self, subscription_id): 154 | for attribute in self._device_sub_dict: 155 | if self._device_sub_dict[attribute].get(subscription_id): 156 | del self._device_sub_dict[attribute][subscription_id] 157 | self._log('Unsubscribed from %s, subscription id %i', 158 | attribute, subscription_id) 159 | if subscription_id == '*': 160 | self._device_sub_dict = {} 161 | self._device_sub_dict = dict( 162 | (k, v) for k, v in self._device_sub_dict.items() if v) 163 | 164 | def subscribe_to_all_attributes(self, callback): 165 | # callback signature is callback(attributes) 166 | return self.subscribe_to_attribute('*', callback) 167 | 168 | def subscribe_to_attribute(self, key, callback): 169 | # callback signature is callback(attributes) 170 | self._device_max_sub_id += 1 171 | if key not in self._device_sub_dict: 172 | self._device_sub_dict.update( 173 | {key: {self._device_max_sub_id: callback}}) 174 | else: 175 | self._device_sub_dict[key].update( 176 | {self._device_max_sub_id: callback}) 177 | self._log('Subscribed to %s with id %i', key, self._device_max_sub_id) 178 | return self._device_max_sub_id 179 | 180 | def request_attributes(self, client_keys=None, shared_keys=None, 181 | callback=None): 182 | # callback signature is callback(resp_id, attributes) 183 | if client_keys is None and shared_keys is None: 184 | self._log('There are no keys to request') 185 | return False 186 | 187 | msg = {} 188 | if client_keys: 189 | msg.update({'clientKeys': ','.join(client_keys)}) 190 | if shared_keys: 191 | msg.update({'sharedKeys': ','.join(shared_keys)}) 192 | 193 | req_id = self._add_attr_request_callback(callback) 194 | self._client.publish(ATTRIBUTES_TOPIC_REQUEST + str(req_id), 195 | json.dumps(msg), 196 | qos=self._qos) 197 | return True 198 | 199 | def _add_attr_request_callback(self, callback): 200 | self._attr_request_number += 1 201 | self._attr_request_dict.update({self._attr_request_number: callback}) 202 | return self._attr_request_number 203 | 204 | def _on_message(self, topic, msg): 205 | topic = topic.decode('utf-8') 206 | payload = json.loads(msg.decode('utf-8')) 207 | self._log('Rx on {}: {}'.format(topic, payload)) 208 | self._on_decoded_message(topic, payload) 209 | 210 | def _on_decoded_message(self, topic, payload): 211 | if topic.startswith(RPC_REQUEST_TOPIC): 212 | req_id = topic[len(RPC_REQUEST_TOPIC):] 213 | if self._device_on_server_side_rpc_response: 214 | method = payload.get('method') 215 | params = payload.get('params') 216 | self._device_on_server_side_rpc_response(req_id, method, 217 | params) 218 | elif topic.startswith(RPC_RESPONSE_TOPIC): 219 | resp_id = int(topic[len(RPC_RESPONSE_TOPIC):]) 220 | callback = self._device_client_rpc_dict.pop(resp_id) 221 | if callback: 222 | callback(resp_id, payload) 223 | elif topic == ATTRIBUTES_TOPIC: 224 | callbacks = [] 225 | # callbacks for everything 226 | if self._device_sub_dict.get('*'): 227 | for subscription_id in self._device_sub_dict['*']: 228 | callbacks.append( 229 | self._device_sub_dict['*'][subscription_id]) 230 | # specific callback, iterate through message 231 | for key in payload.keys(): 232 | # find key in our dict 233 | if self._device_sub_dict.get(key): 234 | for subscription in self._device_sub_dict[key]: 235 | callbacks.append( 236 | self._device_sub_dict[key][subscription]) 237 | for cb in callbacks: 238 | cb(payload) 239 | elif topic.startswith(ATTRIBUTES_TOPIC_RESPONSE): 240 | resp_id = int(topic[len(ATTRIBUTES_TOPIC + '/response/'):]) 241 | callback = self._attr_request_dict.pop(resp_id) 242 | if callback: 243 | callback(payload) 244 | 245 | def _log(self, msg, *args): 246 | if self.DEBUG: 247 | stream = sys.stderr.write('%s:%s:' % (self.__name__)) 248 | if not args: 249 | print(msg, file=stream) 250 | else: 251 | print(msg % args, file=stream) 252 | --------------------------------------------------------------------------------