#!/usr/bin/env python3 """FortiKDS test POS. Sends test orders to a FortiKDS over the store network with the FortiKDS Local API, version 1 (https://fortikds.com/developers/local-api), and shows everything the KDS sends back. One file, Python 3.8 or newer, standard library only. Usage: python fortikds-test-pos.py HOST [--port 9200] [--wait SECONDS] COMMAND [args] Run "python fortikds-test-pos.py --help" for the commands. """ import argparse import json import random import socket import sys import time TOOL_VERSION = "1.0" DEFAULT_PORT = 9200 DEFAULT_WAIT = 3.0 ANSWER_SECONDS = 10 # a POS sends a message again when no answer comes within 10 seconds POLL_SECONDS = 0.5 # short socket waits, so Ctrl+C stops the tool at once, on Windows too STATUS_TYPES = ("ORDER_BUMPED", "ITEM_BUMPED", "ITEM_FORWARDED", "ORDER_RECALLED") ANSWERS = {"HANDSHAKE": "HANDSHAKE_ACK", "PING": "PONG"} # other messages are answered with ORDER_ACK or ERROR NO_ANSWER = ("ORDER_ACK", "HEARTBEAT_ACK") # the KDS does not answer these EXIT_ANSWERED = 0 EXIT_ERROR = 1 EXIT_NO_ANSWER = 2 USAGE = "python fortikds-test-pos.py HOST [--port 9200] [--wait SECONDS] COMMAND [args]" EPILOG = """\ commands: hello send HANDSHAKE and show the HANDSHAKE_ACK new [ORDER_ID] send a sample ORDER_NEW: 2 items (lines ln-1 and ln-2), table 12; without ORDER_ID the order ID is test- add ORDER_ID [--seq N] ORDER_UPDATE: one item in items_added, with add_on_sequence N (default 1); the item is line ln-3 for N=1, ln-4 for N=2, ... table ORDER_ID TABLE ORDER_UPDATE: order_metadata with table_number TABLE remove ORDER_ID ITEM_ID [QTY] ORDER_UPDATE: items_removed (without QTY the KDS removes 1) qty ORDER_ID ITEM_ID QTY ORDER_UPDATE: items_modified, the line's new total quantity rush ORDER_ID on|off ORDER_RUSH void ORDER_ID ORDER_VOID send FILE send any JSON message from a file, as one line; adds a message_id if the file has none listen stay connected and show what the KDS sends, until Ctrl+C Each line sent is shown after ">> ", each line received after "<< ", and notes after "-- ". After the answer the tool keeps listening for --wait seconds. It answers ORDER_BUMPED, ITEM_BUMPED, ITEM_FORWARDED and ORDER_RECALLED with ORDER_ACK, as a POS must. exit code: 0 the KDS answered: ORDER_ACK (HANDSHAKE_ACK for HANDSHAKE, PONG for PING) 1 the KDS answered ERROR 2 no answer within 10 seconds, no connection, or a wrong command line or file examples: python fortikds-test-pos.py 192.168.1.50 hello python fortikds-test-pos.py 192.168.1.50 new ord-1 python fortikds-test-pos.py 192.168.1.50 add ord-1 --seq 1 python fortikds-test-pos.py 192.168.1.50 void ord-1 """ class UsageError(Exception): """A problem with the command line or the message file.""" class Closed(Exception): """The connection to the KDS ended.""" def show(prefix, text): print(prefix + text, flush=True) def note(text): show("-- ", text) def reason(error): return getattr(error, "strerror", None) or str(error) or error.__class__.__name__ def now_ms(): return int(time.time() * 1000) def new_message_id(): return "testpos-%d-%04x" % (now_ms(), random.getrandbits(16)) def payload_of(message): payload = message.get("payload") return payload if isinstance(payload, dict) else {} class Kds: """One TCP connection to a FortiKDS: one JSON object per line, both ways, each line shown.""" def __init__(self, host, port): self.sock = socket.create_connection((host, port), timeout=ANSWER_SECONDS) self.pending = b"" def close(self): try: self.sock.close() except OSError: pass def send(self, message): line = json.dumps(message, ensure_ascii=False) show(">> ", line) try: self.sock.settimeout(ANSWER_SECONDS) self.sock.sendall(line.encode("utf-8") + b"\n") except OSError as error: raise Closed("the connection failed: %s" % reason(error)) def messages(self, deadline): """Yields each message from the KDS until the deadline (a time.monotonic() value; None: no end). Status messages are answered with ORDER_ACK before they are yielded.""" while True: end = self.pending.find(b"\n") if end >= 0: raw, self.pending = self.pending[:end], self.pending[end + 1:] message = self._parse(raw) if message is not None: self._answer_status(message) yield message continue wait = POLL_SECONDS if deadline is not None: left = deadline - time.monotonic() if left <= 0: return wait = min(left, POLL_SECONDS) self.sock.settimeout(wait) try: chunk = self.sock.recv(65536) except socket.timeout: continue except OSError as error: raise Closed("the connection failed: %s" % reason(error)) if not chunk: raise Closed("the KDS closed the connection") self.pending += chunk def _parse(self, raw): text = raw.decode("utf-8", errors="replace").rstrip("\r") if not text.strip(): return None show("<< ", text) try: message = json.loads(text) except ValueError: note("that line is not JSON") return None if not isinstance(message, dict): note("that line is not a JSON object") return None return message def _answer_status(self, message): if message.get("type") not in STATUS_TYPES: return message_id = message.get("message_id") if message_id is None: note("that status message has no message_id, so it cannot be answered") return self.send({"type": "ORDER_ACK", "payload": {"message_id": message_id}}) # ---------- the messages ---------- def order_message(kind, payload): return {"type": kind, "message_id": new_message_id(), "payload": payload} def order_update(order_id, changes): return order_message("ORDER_UPDATE", {"order_id": order_id, "changes": changes}) def sample_order(order_id, created): return { "id": order_id, "order_number": str(1000 + created // 1000 % 9000), "type": "dine_in", "table_number": "12", "server_name": "Test", "guest_count": 2, "notes": "Test order", "items": [ { "id": "ln-1", "name": "Beef Noodle Soup", "name_secondary": "\u725b\u8089\u9762", # beef noodle soup in Chinese "quantity": 2, "modifiers": [ {"text": "No cilantro", "type": "removal"}, {"text": "Extra spicy", "type": "addition"}, ], "notes": ["Peanut allergy"], }, {"id": "ln-2", "name": "Spring Rolls", "quantity": 1}, ], } def read_message_file(path): try: with open(path, encoding="utf-8-sig") as file: message = json.load(file) except OSError as error: raise UsageError("cannot read %s: %s" % (path, reason(error))) except ValueError as error: raise UsageError("%s is not valid JSON: %s" % (path, error)) if not isinstance(message, dict): raise UsageError("%s must hold one JSON object" % path) if "message_id" in message: return message # The new message_id goes right after "type", where it is easy to see. with_id = {} for key, value in message.items(): with_id[key] = value if key == "type": with_id["message_id"] = new_message_id() with_id.setdefault("message_id", new_message_id()) return with_id def build_message(args): """The message the command sends; None for listen.""" command = args.command if command == "listen": return None if command == "hello": return {"type": "HANDSHAKE", "payload": {"pos_name": "FortiKDS test POS", "pos_version": TOOL_VERSION}} if command == "send": return read_message_file(args.file) if command == "new": created = now_ms() order_id = args.order_id if args.order_id is not None else "test-%d" % created return order_message("ORDER_NEW", {"order": sample_order(order_id, created)}) if command == "add": item = {"id": "ln-%d" % (args.seq + 2), "name": "Iced Tea", "quantity": 2} return order_update(args.order_id, {"items_added": [item], "add_on_sequence": args.seq}) if command == "table": return order_update(args.order_id, {"order_metadata": {"table_number": args.table}}) if command == "remove": line = {"id": args.item_id} if args.quantity is not None: line["quantity"] = args.quantity return order_update(args.order_id, {"items_removed": [line]}) if command == "qty": return order_update(args.order_id, {"items_modified": [{"id": args.item_id, "quantity": args.quantity}]}) if command == "rush": return order_message("ORDER_RUSH", {"order_id": args.order_id, "is_rush": args.state == "on"}) if command == "void": return order_message("ORDER_VOID", {"order_id": args.order_id}) raise UsageError("unknown command: %s" % command) # ---------- answers ---------- def verdict(message, sent): """EXIT_ANSWERED or EXIT_ERROR when this message from the KDS answers the message sent, otherwise None.""" kind = message.get("type") payload = payload_of(message) sent_id = sent.get("message_id") if kind == "ERROR": refused_id = payload.get("message_id") return EXIT_ERROR if refused_id is None or refused_id == sent_id else None expected = ANSWERS.get(sent.get("type")) if expected is not None: return EXIT_ANSWERED if kind == expected else None if kind == "ORDER_ACK" and sent_id is not None and payload.get("message_id") == sent_id: return EXIT_ANSWERED return None def explain(message): kind = message.get("type") payload = payload_of(message) if kind == "ERROR": note("refused: %s: %s" % (payload.get("error_code"), payload.get("error_message"))) elif kind == "ORDER_ACK": note("saved") elif kind == "HANDSHAKE_ACK": if payload.get("status") == "ready": note("the KDS is ready") else: note("the KDS is not accepting orders: %s" % payload.get("reason")) else: note("answered") def wait_for_answer(kds, sent): for message in kds.messages(time.monotonic() + ANSWER_SECONDS): result = verdict(message, sent) if result is not None: explain(message) return result # Replies carry the message_id back exactly as sent: 123 stays 123, it never becomes "123". echoed = payload_of(message).get("message_id") mine = sent.get("message_id") if message.get("type") in ("ORDER_ACK", "ERROR") and echoed is not None and echoed != mine and str(echoed) == str(mine): note("that answer's message_id is not exactly the one sent (%s instead of %s)" % (json.dumps(echoed), json.dumps(mine))) note("no answer within %d seconds" % ANSWER_SECONDS) return EXIT_NO_ANSWER def run(args, message): try: kds = Kds(args.host, args.port) except OSError as error: note("cannot connect to %s port %d: %s" % (args.host, args.port, reason(error))) return EXIT_NO_ANSWER note("connected to %s port %d" % (args.host, args.port)) result = None try: if message is None: note("listening; press Ctrl+C to stop") for _ in kds.messages(None): pass return EXIT_NO_ANSWER # not reached: without a deadline, only a closed connection ends the loop kds.send(message) if message.get("type") in NO_ANSWER: result = EXIT_ANSWERED note("the KDS does not answer %s; listening for %g seconds" % (message.get("type"), args.wait)) for reply in kds.messages(time.monotonic() + args.wait): if verdict(reply, message) == EXIT_ERROR: explain(reply) result = EXIT_ERROR return result result = wait_for_answer(kds, message) if result != EXIT_NO_ANSWER and args.wait > 0: for _ in kds.messages(time.monotonic() + args.wait): pass return result except Closed as closed: note(str(closed)) return EXIT_NO_ANSWER if result is None else result except KeyboardInterrupt: note("stopped") if message is None: return EXIT_ANSWERED return EXIT_NO_ANSWER if result is None else result finally: kds.close() # ---------- command line ---------- def port_number(text): try: value = int(text) except ValueError: raise argparse.ArgumentTypeError("not a port number: %r" % text) if not 1 <= value <= 65535: raise argparse.ArgumentTypeError("the port must be 1 to 65535, not %d" % value) return value def seconds(text): try: value = float(text) except ValueError: raise argparse.ArgumentTypeError("not a number of seconds: %r" % text) if not value >= 0: raise argparse.ArgumentTypeError("must be 0 or more seconds, not %s" % text) return value def whole_number(minimum, maximum): def check(text): try: value = int(text) except ValueError: raise argparse.ArgumentTypeError("not a whole number: %r" % text) if not minimum <= value <= maximum: raise argparse.ArgumentTypeError("must be %d to %d, not %d" % (minimum, maximum, value)) return value return check def add_connection_options(parser, with_defaults): # --port and --wait work before or after the command; the values before it are the defaults. parser.add_argument( "--port", type=port_number, default=DEFAULT_PORT if with_defaults else argparse.SUPPRESS, help="the KDS's port (default %d)" % DEFAULT_PORT, ) parser.add_argument( "--wait", type=seconds, metavar="SECONDS", default=DEFAULT_WAIT if with_defaults else argparse.SUPPRESS, help="how long to keep listening after the answer (default %g)" % DEFAULT_WAIT, ) def build_parser(): parser = argparse.ArgumentParser( prog="fortikds-test-pos.py", usage=USAGE, description="A test POS for the FortiKDS Local API, version 1: https://fortikds.com/developers/local-api", epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.add_argument("host", metavar="HOST", help="the KDS's IP address, shown on the KDS in Settings > POS") add_connection_options(parser, with_defaults=True) commands = parser.add_subparsers(dest="command", metavar="COMMAND", prog="python fortikds-test-pos.py HOST") commands.required = True def command(name, description): sub = commands.add_parser(name, description=description) add_connection_options(sub, with_defaults=False) return sub command("hello", "Send HANDSHAKE and show the HANDSHAKE_ACK.") new = command("new", "Send a sample ORDER_NEW: 2 items (lines ln-1 and ln-2), table 12.") new.add_argument("order_id", nargs="?", metavar="ORDER_ID", help="your order ID (default: test-)") add = command("add", "Send ORDER_UPDATE with one item in items_added and add_on_sequence N.") add.add_argument("order_id", metavar="ORDER_ID") add.add_argument("--seq", type=whole_number(1, 99999), default=1, metavar="N", help="add_on_sequence, 1 to 99999 (default 1); the item is line ln-") table = command("table", "Send ORDER_UPDATE with a new table_number in order_metadata.") table.add_argument("order_id", metavar="ORDER_ID") table.add_argument("table", metavar="TABLE") remove = command("remove", "Send ORDER_UPDATE with items_removed.") remove.add_argument("order_id", metavar="ORDER_ID") remove.add_argument("item_id", metavar="ITEM_ID") remove.add_argument("quantity", nargs="?", type=whole_number(1, 999), metavar="QTY", help="how many to remove, 1 to 999 (without it the KDS removes 1)") qty = command("qty", "Send ORDER_UPDATE with items_modified: the line's new total quantity (0 removes the line).") qty.add_argument("order_id", metavar="ORDER_ID") qty.add_argument("item_id", metavar="ITEM_ID") qty.add_argument("quantity", type=whole_number(0, 999), metavar="QTY", help="the line's new total quantity, 0 to 999") rush = command("rush", "Send ORDER_RUSH.") rush.add_argument("order_id", metavar="ORDER_ID") rush.add_argument("state", choices=("on", "off"), metavar="on|off") void = command("void", "Send ORDER_VOID.") void.add_argument("order_id", metavar="ORDER_ID") send = command("send", "Send any JSON message from a file, as one line. Adds a message_id if the file has none.") send.add_argument("file", metavar="FILE") command("listen", "Stay connected and show what the KDS sends, until Ctrl+C.") return parser def safe_output(): # Item names can be in any language; a console or file that can't show a character gets \u.... instead of a crash. for stream in (sys.stdout, sys.stderr): try: stream.reconfigure(errors="backslashreplace") except (AttributeError, ValueError): pass def main(argv=None): safe_output() args = build_parser().parse_args(argv) try: message = build_message(args) except UsageError as error: print("fortikds-test-pos.py: error: %s" % error, file=sys.stderr) return EXIT_NO_ANSWER try: return run(args, message) except KeyboardInterrupt: note("stopped") return EXIT_ANSWERED if message is None else EXIT_NO_ANSWER if __name__ == "__main__": sys.exit(main())