#!/usr/bin/env python3 # ------------------------------- UPSCALE MODBUS SCALE --------------------------------- # ------ UP-SCALES.COM MODBUS TCP SCALE EMULATOR: TRY IT WITHOUT A NETWORK SCALE -------- # -------------------------------------------------------------------------------------- # A MODBUS TCP SCALE ON YOUR COMPUTER: SET UP THE MODBUS TCP NETWORK SCALE OF YOUR # UP↑SCALE RS-232 ADAPTER (232, DIY) - REGISTERS, DATA TYPES, WORD ORDER, STATUS BITS, # TARE / ZERO COMMANDS - BEFORE THE REAL SCALE 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 # 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: # Answer Modbus TCP (functions 1, 3, 4, 5, 6, 16) like a scale, with this map # (holding AND input registers, counted from 0 - "40001" / "30001" = register 0): # 0-1 gross, int32 (two words, big endian): weight x 10^dec # 2-3 net, int32 # 4 status bits: bit 0 stable, bit 1 net (a tare is set), bit 2 overload # 10-11 gross, float32 (word order ABCD) # 12-13 gross, float32 word-swapped (CDAB) # 20 gross, int16 (weight x 10^dec, clipped) # 100 command register: write 1 = tare, 2 = zero, 3 = clear the tare # Coils: 0 = tare, 1 = zero (write 1 / ON). # Log every request and every write (the tare / zero of the adapter). # Change the weight while it runs: type a new gross weight + Enter; "n 0.02" = noise # (the weight is then "moving": status bit 0 off). # # -------------------------------------------------------------------------------------- # 1st: How to try it: # -------------------------------------------------------------------------------------- # # 1.) This computer and the adapter in the same network; the port open in the firewall # (Linux: sudo ufw allow 5020/tcp). Port 502 (the Modbus port) needs root rights on # Linux / macOS - this emulator uses 5020. # 2.) python3 upscale-modbus-scale.py --port 5020 --unit 1 # options: --gross 12.345 --dec 3 (decimals of the integer registers) --noise 0.0 # --verbose (log every read) # 3.) In the app: RS-232 settings -> 📶 NETWORK SCALE -> Modbus TCP, the address of this # computer, port 5020, unit ID 1, holding registers (function 3), weight register 0, # data type "32 bit signed", word order "high word first", decimals 3 (or register 12, # "32 bit float", "low word first"), status register 4 with stable bit 0 and net bit 1, # command register 100 with the tare code 1 and the zero code 2 (write: 1 register, # function 6) -> 💾 SAVE NETWORK SCALE. The app shows 12.345 kg; TARE / ZERO in the app -> # "WRITE REG 100 = 1 / 2" here. # -------------------------------------------------------------------------------------- import argparse, socket, struct, threading, time, random, sys class Scale: def __init__(self, gross, dec, noise): self.gross = gross; self.dec = dec; self.noise = noise; self.tare = 0.0; self.zero = 0.0; self.lock = threading.Lock() def regs(self): with self.lock: g = self.gross - self.zero + random.uniform(-self.noise, self.noise) n = g - self.tare f = 10 ** self.dec r = [0] * 128 gi, ni = int(round(g * f)), int(round(n * f)) r[0], r[1] = struct.unpack('>HH', struct.pack('>i', gi)) r[2], r[3] = struct.unpack('>HH', struct.pack('>i', ni)) r[4] = (1 if self.noise < 0.0005 else 0) | (2 if self.tare else 0) a, b = struct.unpack('>HH', struct.pack('>f', g)); r[10], r[11] = a, b; r[12], r[13] = b, a r[20] = struct.unpack('>H', struct.pack('>h', max(-32768, min(32767, gi))))[0] return r def command(self, v): with self.lock: if v == 1: self.tare = self.gross - self.zero elif v == 2: self.zero = self.gross; self.tare = 0.0 elif v == 3: self.tare = 0.0 def log(text): print('%s %s' % (time.strftime('%H:%M:%S'), text), flush=True) def handle(conn, peer, args, scale): log('client %s:%d' % peer) buf = b'' while True: try: chunk = conn.recv(260) except OSError: break if not chunk: break buf += chunk while len(buf) >= 7: tid, pid, length, unit = struct.unpack('>HHHB', buf[:7]) if len(buf) < 6 + length: break pdu = buf[7:6 + length]; buf = buf[6 + length:] fn = pdu[0] def reply(body): conn.sendall(struct.pack('>HHHB', tid, 0, len(body) + 1, unit) + body) def error(code): reply(bytes([fn | 0x80, code])) if unit != args.unit and args.unit != 0: log('unit %d ignored' % unit); error(0x0B); continue if fn in (3, 4): addr, cnt = struct.unpack('>HH', pdu[1:5]) r = scale.regs() if addr + cnt > len(r) or cnt == 0 or cnt > 125: error(2); log('fn %d addr %d cnt %d -> error' % (fn, addr, cnt)); continue vals = r[addr:addr + cnt] reply(bytes([fn, cnt * 2]) + struct.pack('>%dH' % cnt, *vals)) if args.verbose: log('fn %d addr %d cnt %d -> %s' % (fn, addr, cnt, vals)) elif fn == 1: addr, cnt = struct.unpack('>HH', pdu[1:5]); reply(bytes([1, 1, 0])) elif fn == 5: addr, val = struct.unpack('>HH', pdu[1:5]) log('WRITE COIL %d = %s' % (addr, 'ON' if val == 0xFF00 else 'OFF')) if val == 0xFF00 and addr in (0, 1): scale.command(1 if addr == 0 else 2) reply(pdu[:5]) elif fn == 6: addr, val = struct.unpack('>HH', pdu[1:5]) log('WRITE REG %d = %d' % (addr, val)) if addr == 100: scale.command(val) reply(pdu[:5]) elif fn == 16: addr, cnt, nbytes = struct.unpack('>HHB', pdu[1:6]) vals = struct.unpack('>%dH' % cnt, pdu[6:6 + nbytes]) log('WRITE REGS %d.. = %s' % (addr, list(vals))) if addr == 100 and vals: scale.command(vals[0]) reply(pdu[:5]) else: log('function %d not supported' % fn); error(1) log('client %s:%d gone' % peer) def stdin_loop(scale): 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, noise %.4f' % (scale.gross, scale.noise), flush=True) except (ValueError, IndexError): pass def main(): ap = argparse.ArgumentParser() ap.add_argument('--port', type=int, default=5020); ap.add_argument('--unit', type=int, default=1) ap.add_argument('--gross', type=float, default=12.345); ap.add_argument('--dec', type=int, default=3) ap.add_argument('--noise', type=float, default=0.0); ap.add_argument('--verbose', action='store_true') args = ap.parse_args() scale = Scale(args.gross, args.dec, args.noise) threading.Thread(target=stdin_loop, args=(scale,), daemon=True).start() srv = socket.socket(); srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind(('0.0.0.0', args.port)); srv.listen(4) log('Modbus TCP scale on port %d, unit %d' % (args.port, args.unit)) while True: conn, peer = srv.accept() threading.Thread(target=handle, args=(conn, peer, args, scale), daemon=True).start() if __name__ == '__main__': main()