#!/usr/bin/env python3 # ------------------------------------ UPSCALE MQTT ------------------------------------ # ------------ UP-SCALES.COM ROOM VALUES FOR THE SCALE OVER MQTT (PYTHON PUBLISHER) ----- # -------------------------------------------------------------------------------------- # YOUR UP↑SCALE SCALE READS ROOM VALUES (TEMPERATURE, HUMIDITY, AIR PRESSURE, TWO OF YOUR # OWN) FROM A TOPIC OF YOUR MQTT BROKER - THIS SCRIPT PUBLISHES THEM THERE: FROM YOUR OWN # SENSOR, A FILE, A WEB ADDRESS, OR BY HAND. PYTHON STANDARD LIBRARY ONLY. # (Home Assistant, Node-RED, Zigbee2MQTT, Tasmota ... can publish the same - see the # topics and payloads below and upscale-home-assistant.yaml next to this file.) # -------------------------------------------------------------------------------------- # ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # -------------------------------------------------------------------------------------- # SENSORS OF THE SCALE: https://up-scales.com/manual.html#WiFiSensors # ALL EXAMPLES FOR YOUR IT: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#examples # -------------------------------------------------------------------------------------- # (C) Johann Anderson, 2025-2026 http://farm23.es # -------------------------------------------------------------------------------------- # MIT License - Copyright (c) 2025-2026 Johann Anderson # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to the following # conditions: The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR # PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE # FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # -------------------------------------------------------------------------------------- # # -------------------------------------------------------------------------------------- # 1st: The scale (in the app, ENTERPRISE, the scale in your WiFi network): # -------------------------------------------------------------------------------------- # # LINK -> 🌡 Sensors of the scale: # Broker: mqtt://:1883 (or mqtts://:8883 with TLS), user + password if # your broker wants them. The scale only SUBSCRIBES (it reads), QoS 0. # Source 1..4, kind MQTT: the topic, e.g. "lab/room" (+ and # allowed: "lab/+/env"), # the values you want (temperature, humidity, pressure, value 4, value 5), how # long a value counts, and the JSON path of each value. # # -------------------------------------------------------------------------------------- # Topics and payloads the scale takes: # -------------------------------------------------------------------------------------- # # A JSON payload, each value at its JSON path (keys and positions with dots; empty path # = the default names below; a number in quotes counts too): # lab/room {"temperature":21.4,"humidity":45.2,"pressure":1013.2} # lab/room {"tmp":{"tC":21.4},"hum":{"value":45}} paths tmp.tC, hum.value # zigbee2mqtt/room-sensor {"temperature":21.4,"humidity":45,"battery":97} # A plain number = the FIRST ticked value of the source: # lab/room/temperature 21.4 (a source with only "temperature" ticked) # Values outside -40..125 °C, 0..100 % RH, 300..1200 hPa are dropped. # One topic per source; a retained message is read at once when the scale connects. # # -------------------------------------------------------------------------------------- # 2nd: This script: # -------------------------------------------------------------------------------------- # # python3 upscale-mqtt-publish.py --broker 192.168.1.10 --topic lab/room \ # --json '{"temperature":21.4,"humidity":45.2,"pressure":1013.2}' # python3 upscale-mqtt-publish.py --broker 192.168.1.10 --topic lab/room/temperature --value 21.4 # python3 upscale-mqtt-publish.py ... --every 60 --read-file /run/room.json # (sends the file every 60 s - your sensor writes it) # options: --port 1883 --user U --password P --retain --client-id NAME # # MQTT 3.1.1, plain TCP, QoS 0 - written by hand (CONNECT, PUBLISH, DISCONNECT), so it # runs everywhere Python runs. For TLS (mqtts, port 8883) wrap the socket with the # module ssl (see connect() below) - or use the client of your choice. # -------------------------------------------------------------------------------------- import argparse, json, socket, ssl, struct, sys, time def enc_len(n): out = bytearray() while True: b = n % 128 n //= 128 out.append(b | (0x80 if n else 0)) if not n: return bytes(out) def mqtt_str(s): b = s.encode('utf-8') return struct.pack('>H', len(b)) + b def connect(host, port, client_id, user=None, password=None, use_tls=False, keepalive=60): """A connected MQTT 3.1.1 session (socket) - CONNACK checked.""" s = socket.create_connection((host, port), timeout=10) if use_tls: s = ssl.create_default_context().wrap_socket(s, server_hostname=host) flags = 0x02 | (0x80 if user else 0) | (0x40 if password else 0) # clean session, user, password body = mqtt_str('MQTT') + bytes([4, flags]) + struct.pack('>H', keepalive) + mqtt_str(client_id) if user: body += mqtt_str(user) if password: body += mqtt_str(password) s.sendall(bytes([0x10]) + enc_len(len(body)) + body) ack = s.recv(4) if len(ack) < 4 or ack[0] != 0x20: raise OSError('no CONNACK from the broker') if ack[3] != 0: raise OSError('the broker refused the connection (code %d: 4/5 = user or password)' % ack[3]) return s def publish(s, topic, payload, retain=False): """PUBLISH QoS 0 (no answer from the broker).""" body = mqtt_str(topic) + payload s.sendall(bytes([0x30 | (1 if retain else 0)]) + enc_len(len(body)) + body) def disconnect(s): try: s.sendall(bytes([0xE0, 0])) s.close() except OSError: pass def payload_now(a): """What to send now: --json, --value, or the content of --read-file (your sensor writes it).""" if a.read_file: with open(a.read_file, 'rb') as f: return f.read().strip() if a.value is not None: return ('%g' % a.value).encode() json.loads(a.json) # (a typo in the JSON shows here, not on the scale) return a.json.encode('utf-8') def main(): ap = argparse.ArgumentParser(description='Publish room values for UP-SCALE scales over MQTT') ap.add_argument('--broker', required=True) ap.add_argument('--port', type=int, default=0, help='default 1883 (8883 with --tls)') ap.add_argument('--topic', required=True) ap.add_argument('--json', default='{"temperature":21.4,"humidity":45.2,"pressure":1013.2}') ap.add_argument('--value', type=float, help='a plain number instead of JSON') ap.add_argument('--read-file', help='send the content of this file (JSON or a number)') ap.add_argument('--every', type=float, default=0, help='send again every N seconds (0: once)') ap.add_argument('--retain', action='store_true', help='the broker keeps the last value for the next subscriber') ap.add_argument('--user') ap.add_argument('--password') ap.add_argument('--tls', action='store_true') ap.add_argument('--client-id', default='upscale-room-%d' % (int(time.time()) % 100000)) a = ap.parse_args() port = a.port or (8883 if a.tls else 1883) s = None try: while True: try: if s is None: s = connect(a.broker, port, a.client_id, a.user, a.password, a.tls) p = payload_now(a) publish(s, a.topic, p, a.retain) print('%s %s %s' % (time.strftime('%H:%M:%S'), a.topic, p.decode('utf-8', 'replace')), flush=True) except (OSError, ValueError) as e: print('%s not sent: %s' % (time.strftime('%H:%M:%S'), e), file=sys.stderr, flush=True) if s: disconnect(s) s = None if not a.every: break # (QoS 0 and a keep-alive of 60 s: a PINGREQ when sending less often than that) slept = 0.0 while slept < a.every: step = min(30.0, a.every - slept) time.sleep(step) slept += step if s and slept < a.every: try: s.sendall(bytes([0xC0, 0])) s.settimeout(5) s.recv(2) except OSError: disconnect(s) s = None except KeyboardInterrupt: pass if s: disconnect(s) if __name__ == '__main__': main()