#!/usr/bin/env python3 # ------------------------------------ UPSCALE API ------------------------------------- # ------------------ UP-SCALES.COM JSON API CLIENT OF THE SCALE (PYTHON) ---------------- # -------------------------------------------------------------------------------------- # A CLIENT FOR YOUR OWN PROGRAMS: IT ASKS AN UP↑SCALE SCALE IN YOUR WIFI NETWORK FOR ITS # WEIGHT, STATUS, SENSORS, THINGS AND RECORDS (ACTIVITY LOG, LEGAL MODE STORE, SALES) - # AND SENDS ACTIONS (TARE, ZERO, A LOG LINE). NO APP NEEDED. # -------------------------------------------------------------------------------------- # ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # -------------------------------------------------------------------------------------- # JSON API OF THE SCALE: https://up-scales.com/manual.html#WiFiApi # WEIGHT STREAMS FOR MACHINES: https://up-scales.com/manual.html#WiFiStreams # 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. # -------------------------------------------------------------------------------------- # # This script will: # Read GET /api/status (no secret) and pick the security mode of the scale: # 2 HMAC-signed: a one-time nonce, the signed request, the signed answer checked # 3 sealed envelope (AES-256-GCM): the request sealed, the answer opened # Ask for one thing (weight, status, sensors, things, activity, legal, sales, prints) or # send one action (tare, zero, log) - and print the answer as JSON. # Follow a record list: ask again with "since" = "next" and print every new event. # Push room values to a sensor source of the scale (POST /api/sensor, kind "push"). # # -------------------------------------------------------------------------------------- # 1st: What you need: # -------------------------------------------------------------------------------------- # # 1.) The scale in your WiFi network (WiFi session), ENTERPRISE, and in the app: # LINK -> πŸ”— Webhook & JSON API -> πŸ”Œ JSON API & weight streams -> JSON API ON. The API uses the # secret and the security mode of the box πŸ”— Webhook export (with "TLS" there the API # uses the HMAC rules: the scale has no certificate of its own). # Actions (tare, zero, log) also need "Remote actions" ON in the webhook box; they are # refused in LEGAL MODE, tare and zero only on the pages where TARE tares. # 2.) Python 3.8 or newer - the standard library is enough for mode 2 (HMAC). # Mode 3 (sealed envelope) needs the package "cryptography" for AES-GCM: # pip install cryptography (Debian / Ubuntu: apt install python3-cryptography) # 3.) Your settings (environment variables or the options below): # UPSCALE_HOST the address of the scale (shown on the scale and on its status page) # UPSCALE_KEY the secret of the webhook box # # python3 upscale-api.py --host 192.168.1.50 --key my-secret weight # python3 upscale-api.py status (env UPSCALE_HOST + UPSCALE_KEY set) # python3 upscale-api.py sensors # python3 upscale-api.py things --from 0 # python3 upscale-api.py activity --since 1200 --count 20 # python3 upscale-api.py legal --since 1 (232 / DIY with LEGAL MODE only) # python3 upscale-api.py sales --day 2026-11-27 # python3 upscale-api.py tare (an action: see 1.) # python3 upscale-api.py log --text "batch 42 started" # python3 upscale-api.py follow activity (every new entry, every 10 s) # python3 upscale-api.py public (status + a nonce + the plain weight) # python3 upscale-api.py push --source 1 --json '{"temperature":21.4,"humidity":45}' # (a sensor source of the kind "push" on # the scale; works also with the API off - # then add --security 2|3 and, sealed, # --device ) # # -------------------------------------------------------------------------------------- # How it works (to write it in another language): # -------------------------------------------------------------------------------------- # # GET /api/nonce -> {"nonce":"<16 hex>","n":,"valid_s":60}: one use each. # Mode 2: GET /api/? (or POST /api/do with {"do":"tare"}) with the headers # X-Upscale-Time: X-Upscale-Nonce: # X-Upscale-Signature: sha256=hex(HMAC-SHA256(secret, time "." nonce "." METHOD " " # PATH-WITH-QUERY "." body)) (body empty for a GET) # The answer carries X-Upscale-Time / -Nonce (yours) / -Signature over # (its time "." the nonce "." its body). # Mode 3: POST /api/ with {"schema":"upscale.sealed/1","n":,"ct":""}: # ct = AES-256-GCM(key = SHA-256(secret), nonce = (device ID XOR 0x0F, 6 bytes) + # n (6 bytes, little endian)) of ONE request object - {"get":"activity","since":5}, # {"do":"tare"} - followed by the 16-byte tag. The answer is sealed the same way with # the device ID XOR 0xF0 and the same n. The device ID: GET /api/status "device". # Records: {"ok":true,"type":"activity","from":N,"events":[...],"next":M,"more":true}: # ask again with since (sales: from) = next. Each event is the envelope of the # webhook export (activity / legal with "raw" and "chain" for the hash chain check). # Push: POST /api/sensor?source=<1-4> - secured the same way (mode 2: the body = your # JSON; mode 3: the sealed plain text = your JSON). The scale takes each value at the # JSON path of the source (empty = temperature, humidity, pressure, value4, value5). # 10 failed checks within a minute -> HTTP 429 for a minute. # -------------------------------------------------------------------------------------- import argparse, base64, hashlib, hmac, json, os, sys, time import urllib.error, urllib.request try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM except ImportError: AESGCM = None TIMEOUT = 8 class ApiError(Exception): pass def http(method, url, body=None, headers=None): """One HTTP request -> (status, headers, body bytes). Error statuses come back too.""" req = urllib.request.Request(url, data=body, method=method, headers=headers or {}) try: with urllib.request.urlopen(req, timeout=TIMEOUT) as r: return r.status, r.headers, r.read() except urllib.error.HTTPError as e: return e.code, e.headers, e.read() class Scale: def __init__(self, host, key, security=0, device=''): self.base = 'http://' + host self.key = key.encode('utf-8') self.status = None self.given = {'security': security, 'device': device} def public(self, what): """The public endpoints: status, nonce, weight (the weight only with "GET /api/weight without the secret" on).""" code, _, body = http('GET', self.base + '/api/' + what) if code != 200: raise ApiError('%s: HTTP %d %s' % (what, code, body.decode('utf-8', 'replace'))) return json.loads(body) def mode(self): if self.status is None: self.status = self.public('status') if not self.status.get('api'): raise ApiError('the JSON API of the scale is off (LINK -> πŸ”— Webhook & JSON API -> JSON API)') if not self.status.get('key'): raise ApiError('no secret on the scale (LINK -> πŸ”— Webhook & JSON API -> webhook box)') return self.status.get('security') def nonce(self): return self.public('nonce') def request(self, obj, path=None): """One request object ({"get": "weight"} / {"get": "activity", "since": 5} / {"do": "tare"}) -> (HTTP status, answer). path: POST this object as it is to that path (the push of sensor values: /api/sensor?source=1).""" if path is None: # the security of the scale: the public status says it (2 HMAC / 3 sealed) self.mode() elif self.status is None: # (the push works also with the API off - then /api/status is closed: --security / --device say it) try: self.status = self.public('status') except ApiError: if not self.given.get('security') or (self.given['security'] == 3 and not self.given.get('device')): raise ApiError('the JSON API is off: give --security 2|3 (and --device for 3) of the scale') self.status = self.given if self.status.get('security') == 3: return self.sealed(obj, path) return self.signed(obj, path) # ---------- mode 2: HMAC-signed ---------- def signed(self, obj, push=None): n = self.nonce()['nonce'] if push: method, path, body = 'POST', push, json.dumps(obj, separators=(',', ':')).encode() elif 'do' in obj: method, path, body = 'POST', '/api/do', json.dumps(obj, separators=(',', ':')).encode() else: q = '&'.join('%s=%s' % (k, v) for k, v in obj.items() if k != 'get') method, path, body = 'GET', '/api/' + obj['get'] + ('?' + q if q else ''), b'' t = str(int(time.time())) sig = hmac.new(self.key, (t + '.' + n + '.' + method + ' ' + path + '.').encode() + body, hashlib.sha256).hexdigest() headers = {'X-Upscale-Time': t, 'X-Upscale-Nonce': n, 'X-Upscale-Signature': 'sha256=' + sig} if body: headers['Content-Type'] = 'application/json' code, h, answer = http(method, self.base + path, body or None, headers) # the answer of a checked request is signed with the same nonce (refusals before the check are not) got = h.get('X-Upscale-Signature', '') if got: want = 'sha256=' + hmac.new(self.key, (h.get('X-Upscale-Time', '') + '.' + n + '.').encode() + answer, hashlib.sha256).hexdigest() if h.get('X-Upscale-Nonce') != n or not hmac.compare_digest(want, got): raise ApiError('the signature of the answer is wrong - not from the scale with this secret') elif code == 200: raise ApiError('an answer without signature') return code, json.loads(answer) # ---------- mode 3: sealed envelope ---------- def seal_nonce(self, x, n): dev = bytes(b ^ x for b in bytes.fromhex(self.status['device'])) return dev + n.to_bytes(6, 'little') def sealed(self, obj, push=None): if AESGCM is None: raise ApiError('the sealed mode needs the package "cryptography" (pip install cryptography)') n = self.nonce()['n'] aes = AESGCM(hashlib.sha256(self.key).digest()) ct = aes.encrypt(self.seal_nonce(0x0F, n), json.dumps(obj, separators=(',', ':')).encode(), None) body = json.dumps({'schema': 'upscale.sealed/1', 'n': n, 'ct': base64.b64encode(ct).decode()}).encode() path = push or '/api/' + ('do' if 'do' in obj else obj['get']) code, _, answer = http('POST', self.base + path, body, {'Content-Type': 'application/json'}) env = json.loads(answer) if env.get('schema') != 'upscale.sealed/1': # (a refusal before the check: plain JSON - wrong seal, used number, the brake) return code, env if env.get('n') != n: raise ApiError('the answer has another n') try: plain = aes.decrypt(self.seal_nonce(0xF0, n), base64.b64decode(env['ct']), None) except Exception: raise ApiError('the answer does not open - not from the scale with this secret') return code, json.loads(plain) def show(code, answer): print('HTTP %d' % code) print(json.dumps(answer, indent=2, ensure_ascii=False)) def main(): ap = argparse.ArgumentParser(description='JSON API client of an UP-SCALE scale') ap.add_argument('what', choices=['public', 'weight', 'status', 'sensors', 'things', 'activity', 'legal', 'sales', 'prints', 'tare', 'zero', 'log', 'follow', 'push']) ap.add_argument('list', nargs='?', choices=['activity', 'legal'], help='follow: the record list') ap.add_argument('--host', default=os.environ.get('UPSCALE_HOST', '')) ap.add_argument('--key', default=os.environ.get('UPSCALE_KEY', '')) ap.add_argument('--since', type=int) ap.add_argument('--count', type=int) ap.add_argument('--from', dest='frm', type=int) ap.add_argument('--day', help='sales: YYYY-MM-DD') ap.add_argument('--text', default='', help='log: the text (max. 64 characters)') ap.add_argument('--every', type=int, default=10, help='follow: seconds between two asks') ap.add_argument('--source', type=int, default=0, help='push: the sensor source 1-4 (0: the first one of the kind "push")') ap.add_argument('--json', default='', help='push: the values as JSON, e.g. {"temperature":21.4}') ap.add_argument('--security', type=int, choices=[2, 3], default=0, help='push with the API off: the security mode of the scale') ap.add_argument('--device', default='', help='push with the API off, sealed: the Device ID of the scale (12 hex)') a = ap.parse_args() if not a.host: sys.exit('the address of the scale: --host or UPSCALE_HOST') s = Scale(a.host, a.key, a.security, a.device) try: if a.what == 'public': for w in ('status', 'nonce', 'weight'): try: print(w, json.dumps(s.public(w), ensure_ascii=False)) except ApiError as e: print(e) return if not a.key: sys.exit('the secret of the webhook box: --key or UPSCALE_KEY') if a.what == 'push': path = '/api/sensor' + ('?source=%d' % a.source if a.source else '') return show(*s.request(json.loads(a.json or '{}'), path)) if a.what in ('tare', 'zero', 'log'): obj = {'do': a.what} if a.what == 'log': obj['text'] = a.text return show(*s.request(obj)) if a.what == 'follow': kind = a.list or 'activity' since = a.since if since is None: # (start at the end: the next number of the full status) code, st = s.request({'get': 'status'}) since = st.get(kind + '_next', 0) print('following %s from %d (Ctrl+C ends)' % (kind, since)) while True: code, ans = s.request({'get': kind, 'since': since, 'count': 50}) if code != 200: show(code, ans) return for ev in ans.get('events', []): print(json.dumps(ev, ensure_ascii=False)) since = ans.get('next', since) if not ans.get('more'): time.sleep(a.every) obj = {'get': a.what} for k, v in (('since', a.since), ('count', a.count), ('from', a.frm), ('day', a.day)): if v is not None: obj[k] = v show(*s.request(obj)) except ApiError as e: sys.exit(str(e)) except (OSError, ValueError) as e: sys.exit('no answer from the scale: %s' % e) except KeyboardInterrupt: pass if __name__ == '__main__': main()