#!/usr/bin/env python3 # ------------------------------ UPSCALE TRACKING RECEIVER ------------------------------- # ------------- UP-SCALES.COM TRACKING MODE: LIVE CHART, STORAGE, CSV, E-MAIL ALARMS ------- # ---------------------------------------------------------------------------------------- # ONE PYTHON FILE FOR YOUR OWN SERVER: IT TAKES THE TRACKING RUNS OF YOUR UP↑SCALE SCALES, # KEEPS EVERY POINT, SHOWS A LIVE CHART, GIVES A CSV FOR THE EXPORT AND SENDS AN E-MAIL # AT EVERY ALARM. THE DATA COMES EITHER FROM THE SCALE ITSELF (ITS WEBHOOK EXPORT IN THE # WIFI NETWORK - NO APP NEEDED) OR FROM THE APP (LIMS / ELN FORWARDING - THE SCALE ON # BLUETOOTH OR USB, THE APP OPEN ON A PHONE, TABLET OR PC). # THE TWIN OF upscale-tracking-receiver.php: THE SAME DATA FOLDER, SO YOU CAN SWAP THEM. # ---------------------------------------------------------------------------------------- # ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # ---------------------------------------------------------------------------------------- # THE GUIDE TO THIS EXAMPLE: https://up-scales.com/hardware/tracking-live-chart-webhook.html # TRACKING MODE: https://up-scales.com/manual.html#TrackingMode # WEBHOOK EXPORT OF THE SCALE: https://up-scales.com/manual.html#WiFiWebhook # LIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding # 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: # Take the events "tracking" (start, stop, every alarm of a run) and "points" (the # recorded points) - and "weight" (the live weight: kept as a day run "live-..."). # Check every request with one of the three security modes of the scale: # 1 https + a token (Bearer, X-API-Key or ?token=) - also the mode of the app # 2 HMAC-signed (X-Upscale-Time / -Nonce / -Signature) - it signs its answer # 3 sealed envelope (AES-256-GCM) - it seals its answer and refuses a replayed n # Keep every run in its own folder: points.csv (= the export), alarms.jsonl, run.json. # Drop what comes twice (the scale sends a run again after a restart). # Check your own limits too (a weight below / above), and - with a cron job - send an # e-mail when a recording scale has gone silent. # Send an e-mail at every alarm (your SMTP server, or the mail server of this computer). # Show the live chart: ?view=chart&key= # Give the data as JSON: ?view=runs&key=... ?view=data&key=...&device=...&run=... # Give the CSV export: ?view=csv&key=...&device=...&run=... # Keep the events of other kinds (activity, sales, ...) as JSON lines in other/ - for # the records use upscale-receiver.py (hash chain, "stored", requests). # # ---------------------------------------------------------------------------------------- # 1st: What you need: # ---------------------------------------------------------------------------------------- # # 1.) Python 3.8 or newer - the standard library is enough for modes 1 and 2. # Mode 3 (sealed envelope) needs the package "cryptography" for AES-GCM: # pip install cryptography (Debian / Ubuntu: apt install python3-cryptography) # Without it, modes 1 and 2 work and every sealed request is refused (HTTP 500). # No database: the runs are plain files, so the example runs everywhere. # FOR REAL USE, CHANGE THE STORAGE TO A DATABASE: many scales, long runs at short # intervals and several people viewing at once are faster and safer in SQL. sqlite3 is # in the standard library: a table points(device, run_id, t, n, gross_g, net_g, # PRIMARY KEY(device, run_id, t)) - INSERT OR IGNORE then drops the doubled points. # Only the functions run_meta(), run_save(), run_add_points(), run_alarm() and the # views view_runs(), view_data(), view_csv() touch the run files - replace them. # 2.) A data folder this script may write to (see UPSCALE_DATA). It creates it if it can; # if it can not, every event is answered with 500 and what to do, and # ?view=setup&key= (or: python3 --setup) # shows what works: Python, cryptography, the folder, the e-mail settings. Usually it is: # mkdir upscale-tracking-data && chown upscale-tracking-data && chmod 770 upscale-tracking-data # ( = the user this script runs as - the setup page shows its name). # 3.) It serves on http://127.0.0.1:8090 (UPSCALE_BIND, UPSCALE_PORT). https for mode 1 and # for the app (browsers only post from the app to https): put it behind your web # server - nginx / Apache with https as a proxy to this port, e.g. in nginx: # location /upscale-tracking/ { proxy_pass http://127.0.0.1:8090/; proxy_set_header Host $host; # proxy_set_header X-Forwarded-Proto $scheme; } # or give it a certificate itself: UPSCALE_CERT=/path/cert.pem UPSCALE_KEY=/path/key.pem # Modes 2 and 3 also work on plain http in your own network (UPSCALE_BIND=0.0.0.0). # 4.) Your settings (environment variables, or change the defaults below): # UPSCALE_PORT the port (default 8090) # UPSCALE_BIND the address it listens on (default 127.0.0.1: only this computer, # e.g. your nginx / Apache; 0.0.0.0: every network) # UPSCALE_MODES the modes this receiver takes, e.g. "1,2,3" or "3" # UPSCALE_TOKENS mode 1: the token(s), comma separated # UPSCALE_SECRET modes 2 + 3: the secret you typed into the webhook card # UPSCALE_DATA the folder for the runs (default: upscale-tracking-data next to # this file - the same folder as the PHP twin) # UPSCALE_VIEW_KEY the key of the chart / data / CSV pages (a long random text) # UPSCALE_MAIL_TO who gets the alarm e-mails (comma separated; empty: no e-mails) # UPSCALE_MAIL_FROM the sender address (on most servers: an address of your domain) # UPSCALE_SMTP_HOST your SMTP server - with UPSCALE_SMTP_PORT (587 STARTTLS, 465 TLS), # UPSCALE_SMTP_USER, UPSCALE_SMTP_PASS and UPSCALE_SMTP_TLS # (starttls | ssl | none - default: ssl on port 465, else starttls). # Empty: the mail server of this computer (localhost:25, no login, # no TLS - e.g. postfix); if none answers, the e-mail is skipped # with a line in receiver.log. # UPSCALE_LIMIT_LOW your own limits in g (empty: off): an e-mail when a point is at or # UPSCALE_LIMIT_HIGH below LOW (at or above HIGH), again only after it was back inside # UPSCALE_SILENCE_MIN with the cron job: an e-mail when a recording run sent no point for # this many minutes (0: off) # # UPSCALE_SECRET=my-secret UPSCALE_TOKENS=my-token UPSCALE_VIEW_KEY=my-view-key python3 upscale-tracking-receiver.py # # (to keep it running: a systemd service, e.g. ExecStart=/usr/bin/python3 /path/to/upscale-tracking-receiver.py # with the settings as Environment= lines) # 5.) THE SCALE SENDS ITSELF (WiFi, PRO): in the app LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export: # the address of this receiver, the security mode + the secret, and tick "📈 Tracking: # start, end and every alarm" and "📈 Tracking: every new point". Start a run in the # TRACKING MODE - the app can be closed, the scale posts every point by itself. # THE APP SENDS (Bluetooth / USB, PRO): Settings -> 🔗 LIMS / ELN FORWARDING: the https # address of this receiver and a token (mode 1), tick the two tracking kinds. The app # sends while it is open and connected; the scale keeps recording when it is closed, # and the app sends the missing alarms and the newest point when it connects again. # 6.) The silence check (optional), a cron job every 5 minutes (as the same user and with # the same settings as the receiver): # 0-59/5 * * * * python3 /path/to/upscale-tracking-receiver.py --check # # ---------------------------------------------------------------------------------------- # What you get in the data folder: # ---------------------------------------------------------------------------------------- # # runs///points.csv number,epoch_s,time_utc,gross_g,net_g - one line # per point (gross: against the zero of the run, # net: like the display - the same until a tare) # runs///alarms.jsonl every alarm (of the scale and your own limits) # runs///run.json name, state, interval, target, last point ... # other/-.jsonl the events of other kinds, as they came # state/ seen event ids, the last n per scale (mode 3) # receiver.log refused requests, e-mail errors # # The run id is "-" (e.g. "7-1764316800"): the same from the # scale and from the app. A gap (the scale restarted) is a line with an empty weight. # ---------------------------------------------------------------------------------------- import base64, calendar, glob, hashlib, hmac, json, math, os, platform, re, smtplib, socket, ssl, sys, threading, time from email.utils import formatdate from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse, parse_qs, quote try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM except ImportError: AESGCM = None try: import fcntl except ImportError: fcntl = None try: import pwd except ImportError: pwd = None def env_int(name, default): try: return int(os.environ.get(name) or default) except ValueError: return default # ---------- your settings ---------- PORT = env_int('UPSCALE_PORT', 8090) BIND = os.environ.get('UPSCALE_BIND') or '127.0.0.1' CERT = os.environ.get('UPSCALE_CERT') or '' MODES = [int(m) for m in (os.environ.get('UPSCALE_MODES') or '1,2,3').split(',') if m.strip().isdigit()] TOKENS = [t.strip() for t in (os.environ.get('UPSCALE_TOKENS') or 'CHANGE-ME-TOKEN').split(',') if t.strip()] SECRET = os.environ.get('UPSCALE_SECRET') or 'CHANGE-ME-SECRET' DATA = (os.environ.get('UPSCALE_DATA') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upscale-tracking-data')).rstrip('/') VIEW_KEY = os.environ.get('UPSCALE_VIEW_KEY') or 'CHANGE-ME-VIEW-KEY' # the app's address (the offline app - the single file - sends the origin "null": add 'null' only if you use it) ORIGINS = ['https://up-scales.com'] MAX_BODY = 4 * 1024 * 1024 # e-mail MAIL_TO = os.environ.get('UPSCALE_MAIL_TO') or '' MAIL_FROM = os.environ.get('UPSCALE_MAIL_FROM') or 'scale@' + (re.sub(r'[^A-Za-z0-9.-]', '', socket.getfqdn()) or 'localhost') SMTP = {'host': os.environ.get('UPSCALE_SMTP_HOST') or '', 'port': env_int('UPSCALE_SMTP_PORT', 587), 'user': os.environ.get('UPSCALE_SMTP_USER') or '', 'pass': os.environ.get('UPSCALE_SMTP_PASS') or '', 'tls': (os.environ.get('UPSCALE_SMTP_TLS') or '').lower()} if SMTP['tls'] not in ('starttls', 'ssl', 'none'): SMTP['tls'] = 'ssl' if SMTP['port'] == 465 else 'starttls' # which events send an e-mail: the alarms of the scale, your own limits, the end of a run, a silent scale MAIL_KINDS = ['target', 'constant', 'jump', 'restart', 'peak', 'above', 'below', 'low', 'high', 'own_low', 'own_high', 'stop', 'silence'] # your own limits (g, '' = off), the weight they look at ('gross' = the real weight of the item, 'net' = like the display), hysteresis (g) LIMIT_LOW = os.environ.get('UPSCALE_LIMIT_LOW') or '' LIMIT_HIGH = os.environ.get('UPSCALE_LIMIT_HIGH') or '' LIMIT_WEIGHT = 'gross' LIMIT_HYST = 0.0 SILENCE_MIN = env_int('UPSCALE_SILENCE_MIN', 0) # the live weight (event "weight") as a run per day - False: dropped LIVE_RUNS = True def secret_for(device): """The secret of a scale (modes 2 + 3). Several scales with their own secrets: secrets = {'a1b2c3d4e5f6': 'secret of scale 1', '0a1b2c3d4e5f': 'secret of scale 2'} return secrets.get(device.lower(), '')""" return SECRET LOCK = threading.Lock() # one request at a time in the run files (with the file lock state/.lock: also against --check) REQ = threading.local() # per request: the e-mails to send after the answer, the address of the live chart # ---------- helpers ---------- def not_set(s): return s is None or s == '' or str(s).startswith('CHANGE-ME') def utc(fmt='%Y-%m-%dT%H:%M:%SZ', t=None): return time.strftime(fmt, time.gmtime(time.time() if t is None else t)) def log_line(text): try: with open(os.path.join(DATA, 'receiver.log'), 'a', encoding='utf-8') as f: f.write(utc() + ' ' + text + '\n') except OSError: pass NUMERIC = re.compile(r'\s*[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?\s*') def is_numeric(v): if isinstance(v, bool): return False if isinstance(v, (int, float)): return True return isinstance(v, str) and NUMERIC.fullmatch(v) is not None def num(v): """A number (float) or None.""" return float(v) if is_numeric(v) else None def to_int(v): """A whole number from anything (a text: its leading number, else 0).""" if isinstance(v, bool): return int(v) if isinstance(v, int): return v if isinstance(v, float): return int(v) if math.isfinite(v) else 0 if isinstance(v, str): m = NUMERIC.match(v) return int(float(m.group(0))) if m and m.group(0).strip() else 0 return 0 def num_text(v): """A float as text in the CSV: 100.0 -> "100", 99.5 -> "99.5" (14 significant digits).""" if not math.isfinite(v): return 'NAN' if v != v else ('INF' if v > 0 else '-INF') if v.is_integer() and abs(v) < 1e15: return str(int(v)) s = '%.14G' % v if 'E' in s: m, e = s.split('E') s = (m if '.' in m else m + '.0') + 'E' + ('+' if int(e) >= 0 else '-') + str(abs(int(e))) return s def to_text(v): if v is None or v is False: return '' if v is True: return '1' if isinstance(v, float): return num_text(v) return str(v) def empty(v): return v is None or v is False or v == '' or v == '0' or v == 0 or v == [] or v == {} def to_json(obj, pretty=False): """JSON like the PHP twin writes it: whole floats without ".0", no escaped slashes or unicode.""" def fix(v): if isinstance(v, float) and v.is_integer() and abs(v) < 1e15: return int(v) if isinstance(v, dict): return {k: fix(x) for k, x in v.items()} if isinstance(v, list): return [fix(x) for x in v] return v if pretty: return json.dumps(fix(obj), ensure_ascii=False, indent=4) return json.dumps(fix(obj), ensure_ascii=False, separators=(',', ':')) def json_file(path): try: with open(path, encoding='utf-8') as f: j = json.load(f) return j if isinstance(j, dict) else {} except (OSError, ValueError): return {} def json_save(path, data): try: with open(path + '.tmp', 'w', encoding='utf-8') as f: f.write(to_json(data, True)) os.replace(path + '.tmp', path) except OSError: raise RuntimeError('can not write ' + path + ' - see ?view=setup') def str_time(s): """Epoch seconds of an ISO 8601 time ("2026-11-28T10:00:00.000Z"; without a zone: UTC) - 0: none.""" m = re.fullmatch(r'\s*(\d{4})-(\d{2})-(\d{2})(?:[T ](\d{2}):(\d{2})(?::(\d{2})(?:[.,]\d+)?)?)?\s*(Z|[+-]\d{2}:?\d{2})?\s*', to_text(s), re.I) if not m: return 0 try: t = calendar.timegm(tuple(int(x or 0) for x in m.groups()[:6]) + (0, 0, 0)) except (ValueError, OverflowError): return 0 z = m.group(7) if z and z.upper() != 'Z': t -= (1 if z[0] == '+' else -1) * (int(z[1:3]) * 3600 + int(z[-2:]) * 60) return t # the user this script runs as (the owner the data folder needs) def py_user(): try: return pwd.getpwuid(os.geteuid()).pw_name except Exception: try: import getpass return getpass.getuser() except Exception: return 'the user of this script' def owner_of(path): try: uid = os.stat(path).st_uid except OSError: return '?' try: return pwd.getpwuid(uid).pw_name except Exception: return str(uid) def data_problem(): """Why the data folder can not be used ('' = it can): created if missing, then a test file written and removed.""" for sub in ('', '/runs', '/other', '/state', '/state/seen'): path = DATA + sub if not os.path.isdir(path): try: os.makedirs(path, 0o770, exist_ok=True) except OSError: pass if not os.path.isdir(path): parent = os.path.dirname(path) while not os.path.isdir(parent) and parent != os.path.dirname(parent): parent = os.path.dirname(parent) return ('can not create the folder ' + path + ' - the folder ' + parent + ' is not writable for ' + py_user() + '. Create it yourself and give it to that user: mkdir ' + path + ' && chown ' + py_user() + ' ' + path + ' && chmod 770 ' + path + ', or set UPSCALE_DATA to a folder that is writable.') test = os.path.join(path, '.write-test-%d' % os.getpid()) try: with open(test, 'w') as f: f.write('x') os.remove(test) except OSError: try: rights = '%04o' % (os.stat(path).st_mode & 0o7777) except OSError: rights = '?' return ('the folder ' + path + ' exists but ' + py_user() + ' can not write into it (owner: ' + owner_of(path) + ', rights: ' + rights + '). Fix: chown -R ' + py_user() + ' ' + DATA + ' && chmod -R u+rwX,g+rwX ' + DATA + ' (never 777 on a shared server).') return '' def data_dirs(cli=False): why = data_problem() if why: log_line('SETUP: ' + why) print('upscale-tracking-receiver: ' + why, file=sys.stderr, flush=True) if cli: sys.exit(1) # (500: the scale keeps its points and sends them again when the folder works) raise Refused(500, 'receiver not set up: the data folder is not writable - see ?view=setup', False) # (for the PHP twin in the same folder on Apache: the data is not served) if not os.path.isfile(os.path.join(DATA, '.htaccess')): with open(os.path.join(DATA, '.htaccess'), 'w') as f: f.write('Require all denied\n') class FileLock: """state/.lock - the receiver and the cron job (--check) do not write a run at the same time.""" def __enter__(self): self.f = open(os.path.join(DATA, 'state', '.lock'), 'a') if fcntl: fcntl.flock(self.f, fcntl.LOCK_EX) return self def __exit__(self, *a): if fcntl: fcntl.flock(self.f, fcntl.LOCK_UN) self.f.close() def setup_report(): """What works (?view=setup&key=..., python3 --setup).""" why = data_problem() tokens_set = any(not not_set(t) for t in TOKENS) if not MAIL_TO: mail = 'off (UPSCALE_MAIL_TO empty)' elif SMTP['host']: mail = 'SMTP %s:%d (%s)' % (SMTP['host'], SMTP['port'], SMTP['tls']) else: mail = 'localhost:25 without login (UPSCALE_SMTP_HOST empty) - skipped with a line in receiver.log if no mail server answers' return [ ('Python ' + platform.python_version(), 'ok' if sys.version_info >= (3, 8) else 'too old: Python 3.8 or newer'), ('runs as', py_user()), ('data folder ' + DATA, 'ok (created / writable)' if why == '' else why), ('listens on', '%s:%d' % (BIND, PORT) + (' (https: UPSCALE_CERT)' if CERT else ' (http - for mode 1 and the app: behind nginx / Apache with https)')), ('modes', ', '.join(map(str, MODES))), ('mode 1 token', ('set' if tokens_set else 'NOT SET (UPSCALE_TOKENS)') if 1 in MODES else 'mode 1 off'), ('modes 2 / 3 secret', ('NOT SET (UPSCALE_SECRET)' if not_set(SECRET) else 'set') if (2 in MODES or 3 in MODES) else 'off'), ('cryptography (mode 3)', 'ok' if AESGCM else ('MISSING - mode 3 will not work (pip install cryptography)' if 3 in MODES else 'missing (mode 3 off)')), ('view key', 'NOT SET (UPSCALE_VIEW_KEY)' if not_set(VIEW_KEY) else 'set'), ('e-mail', mail), ('silence check', 'after %d min (needs the cron job)' % SILENCE_MIN if SILENCE_MIN > 0 else 'off'), ] def setup_text(): return ''.join('%-36s %s\n' % row for row in setup_report()) def safe_device(d): d = to_text(d) return d.lower() if re.fullmatch(r'[0-9a-fA-F]{12}', d) else (re.sub(r'[^A-Za-z0-9_-]', '', d) or 'unknown') def safe_run(r): r = to_text(r) return r if re.fullmatch(r'\d{1,3}-\d{1,10}|live-\d{4}-\d{2}-\d{2}', r) else '' def run_dir(device, run): return DATA + '/runs/' + safe_device(device) + '/' + run def iso(t): f = math.floor(t) frac = t - f return utc('%Y-%m-%dT%H:%M:%S', f) + ('.%03d' % math.floor(frac * 1000 + 0.5) if frac > 0.0005 else '') + 'Z' # ---------- e-mail ---------- def mail_later(kind, subject, text): if not MAIL_TO or kind not in MAIL_KINDS: return if not hasattr(REQ, 'mails'): REQ.mails = [] REQ.mails.append((subject, text)) def mail_send_all(mails): for subject, text in mails: if not smtp_send(subject, text): log_line('e-mail not sent: ' + subject) def smtp_send(subject, text): """Your SMTP server: STARTTLS (587), TLS (465) or none, login when a user is set. No UPSCALE_SMTP_HOST: localhost:25.""" host, port, tls, user = SMTP['host'], SMTP['port'], SMTP['tls'], SMTP['user'] if not host: host, port, tls, user = 'localhost', 25, 'none', '' to = [t.strip() for t in MAIL_TO.split(',') if t.strip()] msg = ('From: ' + MAIL_FROM + '\r\nTo: ' + MAIL_TO + '\r\nSubject: =?UTF-8?B?' + base64.b64encode(subject.encode()).decode() + '?=\r\nDate: ' + formatdate(localtime=True) + '\r\nMIME-Version: 1.0\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 8bit\r\n\r\n' + text.replace('\r\n', '\n').replace('\n', '\r\n')).encode('utf-8') try: if tls == 'ssl': s = smtplib.SMTP_SSL(host, port, timeout=15, context=ssl.create_default_context()) else: s = smtplib.SMTP(host, port, timeout=15) try: s.ehlo() if tls == 'starttls': s.starttls(context=ssl.create_default_context()) s.ehlo() if user: s.login(user, SMTP['pass']) s.sendmail(MAIL_FROM, to, msg) finally: try: s.quit() except Exception: pass return True except (OSError, smtplib.SMTPException) as e: log_line('SMTP %s:%d: %s' % (host, port, e)) return False def alarm_mail(kind, meta, text, t, g): who = ((meta.get('scale') or '') + ' ' + ('- ' + meta['name'] if meta['name'] != '' else '')).strip() line = text + (': ' + num_text(round(g, 3)) + ' g' if g is not None else '') + ' at ' + iso(t or time.time()) + ' (UTC)' link = '' if getattr(REQ, 'link', ''): link = '\n\nLive chart: ' + REQ.link + '?view=chart&device=' + quote(meta['device'], safe='') + '&run=' + quote(meta['run_id'], safe='') mail_later(kind, 'UP↑SCALE ' + who + ': ' + text, line + '\n\nScale: ' + (meta.get('scale') or '') + ' (' + meta['device'] + ')\nRun: ' + meta['run_id'] + (' "' + meta['name'] + '"' if meta['name'] != '' else '') + '\nLast point: ' + (num_text(round(meta['last_g'], 3)) + ' g' if meta['last_g'] is not None else '-') + link + '\n') # ---------- the runs ---------- def run_meta(device, run): """run.json of a run (new: the defaults).""" m = json_file(run_dir(device, run) + '/run.json') meta = {'device': safe_device(device), 'run_id': run, 'run': None, 'name': '', 'scale': '', 'src': '', 'state': '', 'started': None, 'updated': None, 'interval_s': None, 'target_g': None, 'start_g': None, 'unit': 'g', 'points': 0, 'last_t': 0, 'last_g': None, 'last_n': 0, 'own': 0, 'silent': False, 'stopped': None} meta.update(m) return meta def run_folder(meta): d = run_dir(meta['device'], meta['run_id']) try: os.makedirs(d, 0o770, exist_ok=True) except OSError: raise RuntimeError('can not create ' + d + ' - see ?view=setup') return d def run_save(meta): d = run_folder(meta) meta['updated'] = int(time.time()) json_save(d + '/run.json', meta) def run_of(device, d, fallback_time): """The run id of an event: run_id (scale, app) - else the newest run with that number of this scale (app: before it knows the time of the run).""" rid = safe_run(d.get('run_id')) if rid: return rid no = to_int(d.get('run') if d.get('run') is not None else 0) best, best_updated = '', 0 for path in glob.glob(run_dir(device, '%d-*' % no)): if not os.path.isdir(path): continue u = json_file(path + '/run.json').get('updated') or 0 if u > best_updated and u > time.time() - 2 * 86400: best, best_updated = os.path.basename(path), u return best or '%d-%d' % (no, to_int(fallback_time)) def run_take_fields(meta, ev, d): """The fields every tracking event carries.""" if not empty(ev.get('scale')): meta['scale'] = to_text(ev['scale']) if d.get('name') is not None and d['name'] != '': meta['name'] = to_text(d['name']) if d.get('run') is not None: meta['run'] = to_int(d['run']) if d.get('state') is not None and d['state'] != '': meta['state'] = to_text(d['state']) for k in ('interval_s', 'target_g', 'start_g'): if k in d: meta[k] = num(d[k]) meta['src'] = 'scale' if ev.get('src') == 'scale' else 'app' m = re.search(r'-(\d{9,10})$', meta['run_id']) if meta['started'] is None and m: meta['started'] = int(m.group(1)) def run_add_points(meta, points): """New points ([number, epoch s, gross, net]) into points.csv - only newer than the last one (the scale sends a run again after a restart: those are dropped here); a point without a weight = a gap (empty).""" lines = '' meta['own'] = to_int(meta.get('own')) for p in points: if not isinstance(p, list) or len(p) < 3: continue t = num(p[1]) if t is None or t <= (meta['last_t'] or 0): continue gross = num(p[2]) net = num(p[3] if len(p) > 3 and p[3] is not None else p[2]) n = to_int(p[0]) lines += '%d,%s,%s,%s,%s\n' % (n, ('%.3f' % t).rstrip('0').rstrip('.'), iso(t), '' if gross is None else num_text(gross), '' if net is None else num_text(net)) meta['last_t'] = t meta['last_n'] = n meta['points'] = to_int(meta.get('points')) + 1 meta['silent'] = False if gross is None: continue meta['last_g'] = gross # your own limits g = net if LIMIT_WEIGHT == 'net' else gross if g is None: continue if not not_set(LIMIT_LOW) and is_numeric(LIMIT_LOW): if not meta['own'] & 1 and g <= float(LIMIT_LOW): meta['own'] |= 1 run_alarm(meta, 'own_low', 'below your limit of ' + LIMIT_LOW + ' g', n, t, g, 'receiver') elif meta['own'] & 1 and g > float(LIMIT_LOW) + LIMIT_HYST: meta['own'] &= ~1 if not not_set(LIMIT_HIGH) and is_numeric(LIMIT_HIGH): if not meta['own'] & 2 and g >= float(LIMIT_HIGH): meta['own'] |= 2 run_alarm(meta, 'own_high', 'above your limit of ' + LIMIT_HIGH + ' g', n, t, g, 'receiver') elif meta['own'] & 2 and g < float(LIMIT_HIGH) - LIMIT_HYST: meta['own'] &= ~2 if not lines: return path = run_folder(meta) + '/points.csv' head = '' if os.path.isfile(path) else 'number,epoch_s,time_utc,gross_g,net_g\n' try: with open(path, 'a', encoding='utf-8', newline='') as f: f.write(head + lines) except OSError: raise RuntimeError('could not store the points') def run_alarm(meta, kind, text, point, t, g, frm): d = run_folder(meta) line = to_json({'alarm': kind, 'text': text, 'point': point, 't': t, 'time_utc': iso(t) if t else None, 'g': g, 'from': frm}) with open(d + '/alarms.jsonl', 'a', encoding='utf-8') as f: f.write(line + '\n') alarm_mail(kind, meta, text, t, g) def take_event(ev): """One event (a dict) -> True: stored.""" typ = re.sub(r'[^a-z0-9_-]', '', to_text(ev.get('type')).lower()) or 'other' device = safe_device(ev.get('device') if ev.get('device') is not None else '') d = ev.get('data') if isinstance(ev.get('data'), dict) else {} now = int(time.time()) if typ == 'points': points = d.get('list') # (an app without "list": the newest point from the fields) if not isinstance(points, list): points = [[to_int(d.get('points') or 0), str_time(d.get('time')) or now, d.get('last_point_g')]] first = points[0][1] if points and isinstance(points[0], list) and len(points[0]) > 1 and is_numeric(points[0][1]) else now meta = run_meta(device, run_of(device, d, first)) run_take_fields(meta, ev, d) run_add_points(meta, points) run_save(meta) return True if typ == 'tracking': meta = run_meta(device, run_of(device, d, str_time(d.get('time')) or now)) run_take_fields(meta, ev, d) what = to_text(d.get('event')) if what == 'stop' and meta['stopped'] is None: meta['stopped'] = now meta['state'] = 'stopped' alarm_mail('stop', meta, 'run stopped' + (' after %d points' % to_int(d['points']) if d.get('points') is not None else ''), now, num(d.get('last_point_g'))) elif what == 'alarm': key = re.sub(r'[^a-z_]', '', to_text(d.get('alarm') if d.get('alarm') is not None else 'alarm')) t = num(d.get('alarm_time')) or (str_time(d.get('time')) or now) g = num(d['alarm_g']) if 'alarm_g' in d else num(d.get('last_point_g')) run_alarm(meta, key, to_text(d['text']) if d.get('text') is not None else key, d['alarm_point'] if d.get('alarm_point') is not None else d.get('points'), t, g, meta['src']) run_save(meta) return True if typ == 'weight': if not LIVE_RUNS: return True t = str_time(d.get('time')) or now day = utc('%Y-%m-%d', t) meta = run_meta(device, 'live-' + day) meta['name'] = 'live weight ' + day meta['state'] = 'live' meta['src'] = 'scale' if not empty(ev.get('scale')): meta['scale'] = to_text(ev['scale']) if meta['started'] is None: meta['started'] = int(t) # (several weights in one second: the time gets the milliseconds of receiving) if t <= (meta['last_t'] or 0): t = meta['last_t'] + 0.001 run_add_points(meta, [[to_int(meta['last_n']) + 1, t, d.get('grams'), d.get('grams')]]) run_save(meta) return True # other kinds: kept as they came try: with open(DATA + '/other/' + typ + '-' + utc('%Y-%m-%d') + '.jsonl', 'a', encoding='utf-8') as f: f.write(to_json(ev) + '\n') return True except OSError: return False # ---------- the silence check (cron: python3 upscale-tracking-receiver.py --check) ---------- def check(): if SILENCE_MIN <= 0: print('UPSCALE_SILENCE_MIN is 0: nothing to check') return 0 data_dirs(True) REQ.mails, REQ.link = [], '' with LOCK, FileLock(): for path in sorted(glob.glob(DATA + '/runs/*/*/run.json')): meta = run_meta(os.path.basename(os.path.dirname(os.path.dirname(path))), os.path.basename(os.path.dirname(path))) if meta['state'] != 'recording' or meta['silent'] or not meta['last_t']: continue # (a point is due every interval: silent = no point for the minutes you set, and at least 3 intervals) wait = max(SILENCE_MIN * 60, 3 * float(meta['interval_s'] or 0)) if time.time() - meta['last_t'] < wait: continue meta['silent'] = True now = int(time.time()) alarm_mail('silence', meta, 'no point for %d minutes' % round((now - meta['last_t']) / 60), now, meta['last_g']) run_save(meta) print('silent: ' + meta['device'] + ' ' + meta['run_id']) mail_send_all(REQ.mails) return 0 # ---------- the pages: chart, runs, data, CSV (with the view key) ---------- def view_runs(): out = [run_meta(os.path.basename(os.path.dirname(os.path.dirname(p))), os.path.basename(os.path.dirname(p))) for p in glob.glob(DATA + '/runs/*/*/run.json')] out.sort(key=lambda m: m.get('updated') or 0, reverse=True) return to_json(out).encode('utf-8') def view_csv(d): try: with open(d + '/points.csv', 'rb') as f: return f.read() except OSError: return b'number,epoch_s,time_utc,gross_g,net_g\n' def view_data(device, run, d, since): """Points newer than "since" (epoch s): [[t, gross, net], ...] - the first load: all (at most 20000: then every k-th).""" points = [] try: with open(d + '/points.csv', encoding='utf-8') as f: f.readline() for line in f: c = line.strip().split(',') if len(c) < 5 or (num(c[1]) or 0) <= since: continue points.append([num(c[1]) or 0.0, None if c[3] == '' else num(c[3]), None if c[4] == '' else num(c[4])]) except OSError: pass if len(points) > 20000: k = math.ceil(len(points) / 20000) last = points[-1] points = [p for i, p in enumerate(points) if i % k == 0 or p[1] is None] if points[-1] != last: points.append(last) alarms = [] try: with open(d + '/alarms.jsonl', encoding='utf-8') as f: for line in f: if line.strip(): try: a = json.loads(line) except ValueError: a = None if a: alarms.append(a) except OSError: pass return to_json({'run': run_meta(device, run), 'points': points, 'alarms': alarms}).encode('utf-8') class Refused(Exception): def __init__(self, code, text, log=True): Exception.__init__(self, text) self.code, self.text, self.log = code, text, log def seal_nonce(device, n, answer): """The 12-byte AES-GCM nonce: the 6 bytes of the Device ID (XOR 0xFF for the answer) + n as 6 bytes little-endian.""" d = bytearray(bytes.fromhex(device)) if answer: d = bytearray(b ^ 0xFF for b in d) return bytes(d) + n.to_bytes(6, 'little') class Handler(BaseHTTPRequestHandler): protocol_version = 'HTTP/1.1' def log_message(self, *a): pass def send(self, code, body=b'', headers=None, ctype='application/json'): self.send_response(code) # CORS: the app runs in the browser origin = self.headers.get('Origin', '') self.send_header('Access-Control-Allow-Origin', origin if origin in ORIGINS else ORIGINS[0]) self.send_header('Vary', 'Origin') self.send_header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS') self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization') self.send_header('Access-Control-Allow-Private-Network', 'true') for k, v in (headers or {}).items(): self.send_header(k, v) if code != 204: self.send_header('Content-Type', ctype) self.send_header('Content-Length', str(len(body))) self.end_headers() if body: self.wfile.write(body) def do_OPTIONS(self): self.send(204) def do_POST(self): self.handle_any('POST') def do_GET(self): self.handle_any('GET') def do_PUT(self): self.send(405) do_DELETE = do_PATCH = do_HEAD = do_PUT def handle_any(self, method): REQ.mails, REQ.link = [], '' try: code, body, headers, ctype = self.process(method) except Refused as e: if e.log: with LOCK: log_line('%d %s (%s)' % (e.code, e.text, self.client_address[0])) REQ.mails = [] code, body, headers, ctype = e.code, (json.dumps({'error': e.text}).encode() if e.text else b''), {}, 'application/json' except Exception as e: log_line('500 %r (%s)' % (e, self.client_address[0])) REQ.mails = [] code, body, headers, ctype = 500, b'', {}, 'application/json' self.send(code, body, headers, ctype) # the e-mails after the answer: the scale does not wait for your mail server if REQ.mails: mails, REQ.mails = REQ.mails, [] mail_send_all(mails) def process(self, method): u = urlparse(self.path) q = parse_qs(u.query, keep_blank_values=True) qget = lambda k: (q.get(k) or [''])[0] hdr = lambda k: self.headers.get(k, '') if method == 'GET' and 'view' in q: return self.view(q, qget, hdr) # ---------- an event of the scale or of the app ---------- is_poll = method == 'GET' if is_poll and qget('poll') != '1': raise Refused(405, '', False) length = to_int(self.headers.get('Content-Length') or 0) if length > MAX_BODY: raise Refused(413, 'too large', False) raw = self.rfile.read(length) if length > 0 and not is_poll else b'' try: body = None if is_poll else json.loads(raw.decode('utf-8')) except (ValueError, UnicodeDecodeError): body = None # which mode: the form of the request says it if hdr('X-Upscale-Signature'): mode = 2 elif ('n' in q) if is_poll else (isinstance(body, dict) and body.get('schema') == 'upscale.sealed/1'): mode = 3 else: mode = 1 if mode not in MODES: raise Refused(401, 'mode %d not accepted here' % mode, False) if mode == 1 and all(not_set(t) for t in TOKENS): raise Refused(503, 'set UPSCALE_TOKENS', False) device = qget('device') if is_poll else (to_text(body.get('device')) if isinstance(body, dict) else '') if mode != 1 and not_set(secret_for(device)): raise Refused(503, 'set UPSCALE_SECRET', False) data_dirs() # (the address of the live chart in the e-mails; behind a proxy: its Host and X-Forwarded-Proto) host = re.sub(r'[^A-Za-z0-9.:\[\]-]', '', hdr('Host')) if host: REQ.link = (hdr('X-Forwarded-Proto') or ('https' if CERT else 'http')).split(',')[0].strip() + '://' + host + u.path with LOCK, FileLock(): return self.locked(is_poll, mode, raw, body, device, qget, hdr) def locked(self, is_poll, mode, raw, body, device, qget, hdr): event, nonce, n = b'', '', 0 if mode == 1: auth = hdr('Authorization') given = auth[7:] if auth.startswith('Bearer ') else (hdr('X-API-Key') or qget('token')) if not any(not not_set(t) and hmac.compare_digest(t.encode(), given.encode('utf-8', 'replace')) for t in TOKENS): raise Refused(401, 'mode 1: wrong or missing token') event = raw elif mode == 2: nonce = hdr('X-Upscale-Nonce') want = 'sha256=' + hmac.new(secret_for(device).encode(), (hdr('X-Upscale-Time') + '.' + nonce + '.').encode() + raw, hashlib.sha256).hexdigest() if not hmac.compare_digest(want.encode(), hdr('X-Upscale-Signature').encode('utf-8', 'replace')): raise Refused(401, 'mode 2: signature wrong') event = raw else: if AESGCM is None: raise Refused(500, 'mode 3 needs the Python package "cryptography" (pip install cryptography)') n = qget('n') if is_poll else to_text(body.get('n')) if not re.fullmatch(r'[0-9a-fA-F]{12}', device) or not re.fullmatch(r'[0-9]{1,15}', n) or not 1 <= int(n) <= 0xFFFFFFFFFFFF: raise Refused(400, 'mode 3: device or n wrong') n = int(n) key = hashlib.sha256(secret_for(device).encode()).digest() if is_poll: # the poll carries t = the AES-256-GCM tag of an EMPTY text with the nonce of n tag = AESGCM(key).encrypt(seal_nonce(device, n, False), b'', None) if not hmac.compare_digest(tag.hex().encode(), qget('t').lower().encode('utf-8', 'replace')): raise Refused(401, 'mode 3: poll tag t wrong or missing') else: try: event = AESGCM(key).decrypt(seal_nonce(device, n, False), base64.b64decode(to_text(body.get('ct')), validate=True), None) except Exception: raise Refused(401, 'mode 3: the envelope does not open') # replay check: n only goes up (per scale) last_file = DATA + '/state/last-n.json' last = json_file(last_file) dev = device.lower() if n <= to_int(last.get(dev, 0)): raise Refused(409, 'mode 3: n %d not higher than %d (replay)' % (n, to_int(last.get(dev, 0)))) last[dev] = n json_save(last_file, last) answer, status = {}, 200 if not is_poll: try: ev = json.loads(event.decode('utf-8')) except (ValueError, UnicodeDecodeError): ev = None if not isinstance(ev, dict) or empty(ev.get('id')) or not isinstance(ev['id'], str) or empty(ev.get('type')): log_line('400 not an event (%s)' % self.client_address[0]) if mode == 1: raise Refused(400, 'not an event', False) # (modes 2 + 3: the refusal goes signed / sealed like an answer) answer, status = {'error': 'not an event'}, 400 else: # a doubled id (a lost answer, a resend): not taken again - acknowledged again (points: by their time, run_add_points) hid = hashlib.sha256(ev['id'].encode()).hexdigest() marker = DATA + '/state/seen/' + hid[:2] + '/' + hid once = ev['type'] not in ('points', 'weight') if once and os.path.isfile(marker): with open(marker, encoding='utf-8') as f: answer = {'ack': ev['id'], 'ref': f.read().strip()} else: try: if not take_event(ev): raise RuntimeError('could not store') except Exception as e: raise Refused(500, str(e)) ref = utc('%Y%m%d') + '-' + hid[:16] if once: os.makedirs(os.path.dirname(marker), 0o770, exist_ok=True) with open(marker, 'w', encoding='utf-8') as f: f.write(ref) answer = {'ack': ev['id'], 'ref': ref} # ---------- the answer: signed (mode 2) or sealed (mode 3) ---------- out = json.dumps(answer, ensure_ascii=False, separators=(',', ':')).encode('utf-8') headers = {} if mode == 2: t = str(int(time.time())) headers = {'X-Upscale-Time': t, 'X-Upscale-Nonce': nonce, 'X-Upscale-Signature': 'sha256=' + hmac.new(secret_for(device).encode(), (t + '.' + nonce + '.').encode() + out, hashlib.sha256).hexdigest()} elif mode == 3: ct = AESGCM(hashlib.sha256(secret_for(device).encode()).digest()).encrypt(seal_nonce(device, n, True), out, None) out = json.dumps({'schema': 'upscale.sealed/1', 'n': n, 'ct': base64.b64encode(ct).decode()}).encode() return status, out, headers, 'application/json' def view(self, q, qget, hdr): view = qget('view') if not_set(VIEW_KEY): raise Refused(503, 'set UPSCALE_VIEW_KEY', False) # (the chart page asks for the key itself and keeps it in this browser: the key is not in the address you share) given = qget('key') if 'key' in q else hdr('X-View-Key') if view != 'chart' and not hmac.compare_digest(VIEW_KEY.encode(), given.encode('utf-8', 'replace')): time.sleep(1) raise Refused(401, 'wrong or missing key', False) nostore = {'Cache-Control': 'no-store'} if view == 'chart': return 200, CHART_PAGE.encode('utf-8'), dict(nostore, **{'Content-Security-Policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'"}), 'text/html; charset=utf-8' if view == 'setup': return 200, setup_text().encode('utf-8'), nostore, 'text/plain; charset=utf-8' if view == 'runs': return 200, view_runs(), nostore, 'application/json' device = safe_device(qget('device')) run = safe_run(qget('run')) if not run or not os.path.isdir(run_dir(device, run)): raise Refused(404, 'no such run', False) d = run_dir(device, run) if view == 'csv': return 200, view_csv(d), {'Content-Disposition': 'attachment; filename="upscale-' + device + '-' + run + '.csv"'}, 'text/csv; charset=utf-8' if view == 'data': return 200, view_data(device, run, d, num(qget('since')) or 0.0), nostore, 'application/json' raise Refused(404, 'no such view', False) def main(): args = sys.argv[1:] if '--setup' in args: sys.stdout.write(setup_text()) print("(the command line may run as another user than the receiver - the setup page ?view=setup shows the receiver's view)") return 0 if '--check' in args: return check() if args: name = os.path.basename(__file__) print('usage: python3 %s (the receiver on UPSCALE_BIND:UPSCALE_PORT)\n' ' python3 %s --check (the silence check, e.g. every 5 minutes by cron)\n' ' python3 %s --setup (what works)' % (name, name, name), file=sys.stderr) return 2 if 3 in MODES and AESGCM is None: print('NOTE: mode 3 (sealed envelope) needs the package "cryptography" (pip install cryptography) - sealed requests are refused until then', file=sys.stderr) why = data_problem() if why: print('NOTE: ' + why + ' - every event is answered with 500 until then', file=sys.stderr) srv = ThreadingHTTPServer((BIND, PORT), Handler) scheme = 'http' if CERT: ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain(CERT, os.environ.get('UPSCALE_KEY')) srv.socket = ctx.wrap_socket(srv.socket, server_side=True) scheme = 'https' print('UP-SCALE tracking receiver on %s://%s:%d - modes %s - data in %s' % (scheme, BIND, PORT, ','.join(map(str, MODES)), DATA), flush=True) try: srv.serve_forever() except KeyboardInterrupt: pass return 0 # ---------- the live chart (plain JavaScript, no library) ---------- CHART_PAGE = r''' UP↑SCALE tracking - live chart

UP↑SCALE 📈 live chart

now-
change since start-
rate (last hour)-
points-
Alarms
none
''' if __name__ == '__main__': sys.exit(main())