#!/usr/bin/env python3 # --------------------------------- UPSCALE TCP SCALE ---------------------------------- # --------- UP-SCALES.COM NETWORK SCALE EMULATOR: TRY IT WITHOUT A NETWORK SCALE -------- # -------------------------------------------------------------------------------------- # A SCALE ON THE NETWORK, ON YOUR COMPUTER: IT BEHAVES LIKE A SCALE TERMINAL WITH AN # ETHERNET PORT OR AN RS-232 SCALE BEHIND A SERIAL-TO-LAN ADAPTER - SO YOU CAN SET UP THE # NETWORK SCALE OF YOUR UP↑SCALE RS-232 ADAPTER (232, DIY) BEFORE THE REAL ONE IS THERE. # PYTHON STANDARD LIBRARY ONLY, NOTHING TO INSTALL. # -------------------------------------------------------------------------------------- # ^^^ A WORKING EXAMPLE - COPY IT AND CHANGE IT AS NEEDED! # -------------------------------------------------------------------------------------- # NETWORK SCALE OF THE ADAPTER: https://up-scales.com/manual.html#RS232_NetworkScale # SERIAL-TO-LAN ADAPTER SET-UP: https://up-scales.com/hardware/integration-lims-webhook-api-examples.html#network-scale # 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: # Be a scale on the network, in one of two roles: # server: it waits on a port - the adapter connects to it ("TCP client" in the # card 📶 NETWORK SCALE; like a serial-to-LAN adapter in "TCP server" mode) # client: it connects to the adapter ("TCP server" in the card; like a serial-to- # LAN adapter in "TCP client" mode) # Send the weight in one of four formats: # any a continuous line " 1.234 kg" (scale type: any / generic) # cas continuous "ST,GS,1@,+0001.234 kg" (CAS / ST,GS style) # mtsics answers MT-SICS: SIR (stream), S / SI, T / TI (tare), Z (zero), @ # (METTLER TOLEDO) # dini answers READ, TARE, ZERO (DINI ARGEO style) # Take tare / zero from the adapter and log every byte it sends (commands, requests). # Change the weight while it runs: type a new gross weight in kg + Enter; # "n 0.02" = noise of +-0.02 kg (the weight is then "moving"). # # -------------------------------------------------------------------------------------- # 1st: How to try it: # -------------------------------------------------------------------------------------- # # 1.) This computer and the adapter in the same network; the port open in the firewall # of this computer (server role; Linux: sudo ufw allow 4001/tcp). # 2.) Start it: # python3 upscale-tcp-scale.py server --port 4001 --fmt mtsics # python3 upscale-tcp-scale.py client --host
--port 4001 --fmt cas # options: --gross 1.234 (kg) --noise 0.0 --interval 0.25 (s between two stream # lines) --log FILE (everything the adapter sends) # 3.) In the app: RS-232 settings -> 📶 NETWORK SCALE -> TCP client, the address of this # computer and the port (server role) - or TCP server and the port (client role) -> # 💾 SAVE NETWORK SCALE. The scale type above: the one of the format (any = the plain # RS232 WEIGHING SCALE, mtsics = METTLER TOLEDO, ...). # 4.) The app shows 1.234 kg; type 2.5 + Enter here and it shows 2.5 kg; TARE in the app # -> a tare command arrives here (mtsics: "T", dini: "TARE"). # -------------------------------------------------------------------------------------- import argparse, socket, threading, time, random, sys class Scale: def __init__(self, gross, noise): self.gross = gross; self.noise = noise; self.tare = 0.0; self.zero = 0.0; self.lock = threading.Lock() def read(self): with self.lock: g = self.gross - self.zero + random.uniform(-self.noise, self.noise) return g, g - self.tare, self.noise < 0.0005 def do_tare(self): with self.lock: self.tare = self.gross - self.zero def do_zero(self): with self.lock: self.zero = self.gross; self.tare = 0.0 def line_any(s): g, n, st = s.read(); return ('%9.3f kg\r\n' % n).encode() def line_cas(s): g, n, st = s.read(); return ('%s,%s,%c%c,%+09.3f kg\r\n' % ('ST' if st else 'US', 'NT' if s.tare else 'GS', '1', '@', n)).encode() def line_mtsics(s, cmd='S'): g, n, st = s.read(); return ('%s %s %10.3f kg\r\n' % (cmd, 'S' if st else 'D', n)).encode() def line_dini(s): g, n, st = s.read(); return ('ST,%s,%10.3f,kg\r\n' % ('NT' if s.tare else 'GS', n)).encode() def log(args, text): msg = '%s %s' % (time.strftime('%H:%M:%S'), text) print(msg, flush=True) if args.log: with open(args.log, 'a') as f: f.write(msg + '\n') def serve(conn, args, scale): conn.settimeout(0.05) stream = args.fmt in ('any', 'cas') sir = False buf = b'' last = 0 while True: now = time.time() if (stream or sir) and now - last >= args.interval: last = now out = {'any': line_any, 'cas': line_cas}.get(args.fmt) data = out(scale) if out else line_mtsics(scale) try: conn.sendall(data) except OSError: return try: chunk = conn.recv(256) if not chunk: log(args, 'closed by the adapter'); return buf += chunk except socket.timeout: continue except OSError: return while b'\n' in buf or b'\r' in buf: cut = min(i for i in (buf.find(b'\n'), buf.find(b'\r')) if i >= 0) raw, buf = buf[:cut], buf[cut + 1:] if not raw: continue cmd = raw.decode('latin-1').strip() log(args, 'IN %r' % cmd) reply = None if args.fmt == 'mtsics': if cmd == 'SIR': sir = True elif cmd in ('S', 'SI'): reply = line_mtsics(scale) elif cmd == 'T': scale.do_tare(); reply = ('T S %10.3f kg\r\n' % scale.tare).encode() elif cmd == 'TI': scale.do_tare(); reply = ('TI S %10.3f kg\r\n' % scale.tare).encode() elif cmd == 'Z': scale.do_zero(); reply = b'Z A\r\n' elif cmd == '@': sir = False; reply = b'I4 A "UPSCALE-TEST"\r\n' else: reply = b'ES\r\n' elif args.fmt == 'dini': if cmd == 'READ': reply = line_dini(scale) elif cmd == 'TARE': scale.do_tare(); reply = b'OK\r\n' elif cmd == 'ZERO': scale.do_zero(); reply = b'OK\r\n' else: if cmd in ('T', 'KT', 'D00KT'): scale.do_tare() elif cmd in ('Z', 'KZ', 'D00KZ'): scale.do_zero() if reply: try: conn.sendall(reply) except OSError: return def stdin_loop(scale): # type a new gross weight (kg) and Enter; "n 0.02" sets the noise for l in sys.stdin: p = l.split() try: if p and p[0] == 'n': scale.noise = float(p[1]) elif p: scale.gross = float(p[0]) print('gross %.3f kg, noise %.4f' % (scale.gross, scale.noise), flush=True) except (ValueError, IndexError): pass def main(): ap = argparse.ArgumentParser() ap.add_argument('mode', choices=['server', 'client']) ap.add_argument('--host', default='0.0.0.0'); ap.add_argument('--port', type=int, default=4001) ap.add_argument('--fmt', choices=['any', 'cas', 'mtsics', 'dini'], default='mtsics') ap.add_argument('--gross', type=float, default=1.234); ap.add_argument('--noise', type=float, default=0.0) ap.add_argument('--interval', type=float, default=0.25); ap.add_argument('--log') args = ap.parse_args() scale = Scale(args.gross, args.noise) threading.Thread(target=stdin_loop, args=(scale,), daemon=True).start() if args.mode == 'server': srv = socket.socket(); srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind((args.host, args.port)); srv.listen(2) log(args, 'listening on %s:%d (%s)' % (args.host, args.port, args.fmt)) while True: conn, peer = srv.accept(); log(args, 'adapter connected from %s:%d' % peer) threading.Thread(target=serve, args=(conn, args, scale), daemon=True).start() else: while True: try: conn = socket.create_connection((args.host, args.port), timeout=5) log(args, 'connected to the adapter %s:%d (%s)' % (args.host, args.port, args.fmt)) serve(conn, args, scale) except OSError as e: log(args, 'no connection: %s' % e) time.sleep(2) if __name__ == '__main__': main()