#!/usr/bin/env python3 # ---------------------------------- UPSCALE TO LIMS ----------------------------------- # ------------- UP-SCALES.COM RECORDS INTO YOUR LIMS / ELN: FOLDER IMPORT + REST -------- # -------------------------------------------------------------------------------------- # A RECEIVER THAT HANDS THE RECORDS OF YOUR UP↑SCALE SCALES TO YOUR LIMS OR ELN: # FOLDER IMPORT: one CSV and / or XML file per record into a folder your LIMS watches # (nearly every LIMS can import a watched folder) # REST: one call of the REST API of your LIMS per record, with a field mapping # you change below (which field of the record goes into which field) # THE RECORDS COME FROM THE WEBHOOK EXPORT OF THE SCALE, THE LIMS / ELN FORWARDING OF THE # APP - OR AS JSON LINES ON STDIN (E.G. FROM upscale-api.py follow activity). # PYTHON STANDARD LIBRARY ONLY (THE SEALED ENVELOPE NEEDS THE PACKAGE "cryptography"). # -------------------------------------------------------------------------------------- # ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # -------------------------------------------------------------------------------------- # LIMS / ELN FORWARDING OF THE APP: https://up-scales.com/manual.html#LimsForwarding # WEBHOOK EXPORT OF THE SCALE: https://up-scales.com/manual.html#WiFiWebhook # 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: # Check every request with the security mode of the scale / the app: # 1 https + a token (Bearer, X-API-Key or ?token=) - the mode of the app # 2 HMAC-signed - it signs its answer # 3 sealed envelope (AES-256-GCM) - it seals its answer, refuses a replayed n # Hand every new record to your LIMS: files into the import folder (written under a # temporary name, then renamed - the LIMS never reads half a file) and / or the REST # call with your field mapping. # Acknowledge a record ({"ack","ref"}) only AFTER the folder / the LIMS took it - else # the scale (or the app) sends it again later. A record that comes twice (same "id") # goes to the LIMS once and is acknowledged again. # Keep every record as it came in /events//.jsonl as well. # # For the checks - the hash chains of the activity log, the LEGAL MODE store and the # sales log, the seals and the chain checkpoints of the scale -, the requests to the # scale and the poll: upscale-receiver.py next to this file (an offline check of its # folder: upscale-verify.py). # # -------------------------------------------------------------------------------------- # 1st: What you need: # -------------------------------------------------------------------------------------- # # 1.) Python 3.8 or newer. Mode 3 (sealed envelope): pip install cryptography # (Debian / Ubuntu: apt install python3-cryptography). # 2.) Your settings (environment variables, or change the defaults below): # UPSCALE_PORT the port of the receiver (default 8081) # UPSCALE_MODES the modes it takes, e.g. "1,2,3" # UPSCALE_TOKENS mode 1: the token(s), comma separated (the app's LIMS forwarding, # the scale with the credential "Bearer token") # UPSCALE_SECRET modes 2 + 3: the secret of the webhook box of the scale # UPSCALE_OUT "folder", "rest" or "folder,rest" # UPSCALE_FOLDER the import folder of your LIMS (folder output) # UPSCALE_FORMAT "csv", "xml" or "csv,xml" (folder output) # UPSCALE_TYPES the record types to hand on, e.g. "weighing,sales,activity" # (empty = all; ping / status / weight are never handed on) # LIMS_URL the address of the REST API of your LIMS (rest output) # LIMS_TOKEN its token (sent as "Authorization: Bearer ...") # UPSCALE_DATA the folder for the copy of the records and the state files # 3.) In the app: Settings -> 🔗 LIMS / ELN FORWARDING (the https address of this # receiver + the token), or LINK -> 🔗 Webhook & JSON API -> 🔗 Webhook export (its address, the # security mode and the secret). https for mode 1: a web server in front (nginx / # Apache as a proxy), or UPSCALE_CERT=/path/cert.pem UPSCALE_KEY=/path/key.pem. # # UPSCALE_OUT=folder UPSCALE_FOLDER=/srv/lims/import UPSCALE_SECRET=my-secret \ # python3 upscale-to-lims.py # UPSCALE_OUT=rest LIMS_URL=https://lims.example.com/api LIMS_TOKEN=... \ # UPSCALE_TOKENS=app-token python3 upscale-to-lims.py # python3 upscale-api.py follow activity | UPSCALE_OUT=folder python3 upscale-to-lims.py --stdin # # -------------------------------------------------------------------------------------- # The records (the envelope of the scale and of the app): # -------------------------------------------------------------------------------------- # # {"schema":"upscale.event/1","id":"::","type":"weighing", # "device":"24EC4A1DD408","scale":"UP⬆SCALE (710) #93682","user":"anna", # "sent_at":"2026-11-27T22:48:16Z","data":{...},"env":{...}} # weighing (app): data.mode, log, time, name, grams, count, user, lot, alibi, values # sales: data.seq, sale_id, day, time, thing, pieces, grams, revenue, ... # activity: data.seq, time, kind, detail, user_id, extra, value, aux, raw, chain # legal (232/DIY): data.number, ... raw, chain # reply (scale): data.request, id, ok, grams, stable, ... (answers to requests) # sealed: data.seal_kind, kind, log_seq, seal, cert, pk, has_certificate, # sha256 (kinds 1-3) | the decoded checkpoint fields (kinds 4, 5) # stock, tracking, validation, programs ... (app): see the manual # -------------------------------------------------------------------------------------- import base64, csv, hashlib, hmac, io, json, os, re, ssl, sys, threading, time import urllib.error, urllib.request from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from urllib.parse import urlparse, parse_qs from xml.sax.saxutils import escape, quoteattr try: from cryptography.hazmat.primitives.ciphers.aead import AESGCM except ImportError: AESGCM = None # ---------- your settings ---------- env = os.environ.get PORT = int(env('UPSCALE_PORT') or 8081) MODES = [int(m) for m in (env('UPSCALE_MODES') or '1,2,3').split(',') if m.strip()] TOKENS = [t.strip() for t in (env('UPSCALE_TOKENS') or 'CHANGE-ME-TOKEN').split(',') if t.strip()] SECRET = env('UPSCALE_SECRET') or 'CHANGE-ME-SECRET' OUT = [o.strip() for o in (env('UPSCALE_OUT') or 'folder').split(',') if o.strip()] FOLDER = env('UPSCALE_FOLDER') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lims-import') FORMATS = [f.strip() for f in (env('UPSCALE_FORMAT') or 'csv,xml').split(',') if f.strip()] TYPES = [t.strip() for t in (env('UPSCALE_TYPES') or '').split(',') if t.strip()] LIMS_URL = (env('LIMS_URL') or 'http://127.0.0.1:9000/api').rstrip('/') LIMS_TOKEN = env('LIMS_TOKEN') or '' DATA = (env('UPSCALE_DATA') or os.path.join(os.path.dirname(os.path.abspath(__file__)), 'upscale-lims-data')).rstrip('/') ORIGINS = ['https://up-scales.com'] NEVER = ('ping', 'status', 'weight') # (tests, health and the live weight: not for a LIMS) # ---------- REST: the field mapping (CHANGE IT for your LIMS) ---------- # Per record type: the path of the call (after LIMS_URL), the method, and the body: "LIMS field": "path in the record" # (dots go into the record: "data.grams"; "=text" is a fixed value; a dict / list is built the same way). # A type that is not here goes to "*" (or nowhere when "*" is missing). MAPPING = { 'weighing': {'method': 'POST', 'path': '/results', 'body': { 'sampleId': 'data.lot', 'test': 'data.name', 'result': 'data.grams', 'unit': '=g', 'count': 'data.count', 'operator': 'data.user', 'measuredAt': 'data.time', 'instrument': {'id': 'device', 'name': 'scale'}, 'alibi': 'data.alibi', 'externalId': 'id'}}, 'reply': {'method': 'POST', 'path': '/results', 'body': { 'test': 'data.request', 'result': 'data.grams', 'unit': 'data.unit', 'stable': 'data.stable', 'measuredAt': 'data.time', 'instrument': {'id': 'device', 'name': 'scale'}, 'externalId': 'id'}}, 'sales': {'method': 'POST', 'path': '/dispensing', 'body': { 'item': 'data.thing', 'grams': 'data.grams', 'pieces': 'data.pieces', 'bookedAt': 'data.booked_at', 'lot': 'data.lot_key', 'instrument': {'id': 'device'}, 'externalId': 'id'}}, '*': {'method': 'POST', 'path': '/instrument-events', 'body': { 'type': 'type', 'instrument': {'id': 'device', 'name': 'scale'}, 'user': 'user', 'sentAt': 'sent_at', 'payload': 'data', 'externalId': 'id'}}, } def lims_headers(): """The headers of every LIMS call - change them for your LIMS (an API key header, Basic, ...).""" h = {'Content-Type': 'application/json', 'Accept': 'application/json'} if LIMS_TOKEN: h['Authorization'] = 'Bearer ' + LIMS_TOKEN return h # ---------- the outputs ---------- def pick(event, path): if isinstance(path, dict): return {k: pick(event, v) for k, v in path.items()} if isinstance(path, list): return [pick(event, v) for v in path] if path.startswith('='): return path[1:] v = event for part in path.split('.'): if isinstance(v, dict): v = v.get(part) elif isinstance(v, list) and part.isdigit() and int(part) < len(v): v = v[int(part)] else: return None return v def flat(event): """The record as one flat row: type, id, device, ..., data.grams, data.lot, env.ta ... (lists as JSON).""" row = {} def walk(prefix, v): if isinstance(v, dict): for k, x in v.items(): walk(prefix + '.' + k if prefix else k, x) else: row[prefix] = json.dumps(v, ensure_ascii=False) if isinstance(v, list) else ('' if v is None else v) walk('', {k: v for k, v in event.items() if k != '_rx'}) return row def file_name(event): """One file per record: __