{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "https://synacl.com/protocol/v1/schemas/gateway-cmd.json",
  "title": "Gateway command (cloud -> gateway)",
  "description": "Commands addressed to the gateway itself, published on `<prefix>/cmd` (QoS 1, not retained). Every body carries `command`; the other keys depend on it. IGNORE a command you do not recognise — new ones are added within v1, and a gateway that errors or reboots on an unknown command will break. `job/config` is also re-sent after every config/request whose `jh` does not match it, so it arrives on every boot and whenever it changed. `job/ack` confirms a `job` boundary. The bus-port commands (`identify`, `bus/tap/start|stop`, `bus/scan`, `bus/scan/stop`, `bus/capture`) are only sent to gateways whose capability report says `busPort` (and `busScan` / `busCapture` for those two); every one that carries a `correlationId` is answered on `<prefix>/cmd/ack` (gateway-cmd-ack) before its own stream starts. Commands that expect a reply name the reply topic below; the rest are fire-and-forget. The backend does not validate what it publishes — this schema documents it; validate with a plain draft-07 validator (not Ajv `removeAdditional`, which corrupts `oneOf`). New optional keys may be added within v1; ignore keys you do not use.",
  "type": "object",
  "required": [
    "command"
  ],
  "properties": {
    "command": {
      "type": "string"
    }
  },
  "oneOf": [
    {
      "$ref": "#/definitions/restart"
    },
    {
      "$ref": "#/definitions/resetConfig"
    },
    {
      "$ref": "#/definitions/simStart"
    },
    {
      "$ref": "#/definitions/simStop"
    },
    {
      "$ref": "#/definitions/debugDiag"
    },
    {
      "$ref": "#/definitions/debugLogsStart"
    },
    {
      "$ref": "#/definitions/debugLogsStop"
    },
    {
      "$ref": "#/definitions/bleScan"
    },
    {
      "$ref": "#/definitions/jobConfig"
    },
    {
      "$ref": "#/definitions/jobAck"
    },
    {
      "$ref": "#/definitions/identify"
    },
    {
      "$ref": "#/definitions/busTapStart"
    },
    {
      "$ref": "#/definitions/busTapStop"
    },
    {
      "$ref": "#/definitions/busScan"
    },
    {
      "$ref": "#/definitions/busScanStop"
    },
    {
      "$ref": "#/definitions/busCapture"
    }
  ],
  "definitions": {
    "restart": {
      "title": "restart",
      "description": "Reboot now. The backend refuses to send it while a firmware update or config apply is in flight unless the user forces it.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "restart"
        }
      }
    },
    "resetConfig": {
      "title": "reset/config",
      "description": "Discard the stored device configuration (and its hash) and reboot; the next config/request then carries no hash and receives the full configuration.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "reset/config"
        }
      }
    },
    "simStart": {
      "title": "sim/start",
      "description": "Enter simulation mode: publish synthetic readings instead of polling hardware. Report `simMode: true` in the heartbeat while it is on.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "sim/start"
        }
      }
    },
    "simStop": {
      "title": "sim/stop",
      "description": "Leave simulation mode.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "sim/stop"
        }
      }
    },
    "debugDiag": {
      "title": "debug/diag",
      "description": "Publish one diagnostics snapshot on `<prefix>/debug/response` (see debug-response), echoing `correlationId`.",
      "type": "object",
      "required": [
        "command",
        "correlationId"
      ],
      "properties": {
        "command": {
          "const": "debug/diag"
        },
        "correlationId": {
          "description": "A UUID.",
          "type": "string"
        }
      }
    },
    "debugLogsStart": {
      "title": "debug/logs/start",
      "description": "Start (or, if already running, re-scope) the live log tail on `<prefix>/debug/log` (see debug-log). Replace the current category mask with `cats`; end the tail on your own after a while.",
      "type": "object",
      "required": [
        "command",
        "cats"
      ],
      "properties": {
        "command": {
          "const": "debug/logs/start"
        },
        "cats": {
          "description": "Bitmask of log categories to stream: 1 system (always set), 2 network, 4 commands, 8 modbus, 16 sensors, 32 macros. These bit values are a wire contract. At most three categories besides system are selected at once.",
          "type": "integer",
          "minimum": 1,
          "maximum": 63
        }
      }
    },
    "debugLogsStop": {
      "title": "debug/logs/stop",
      "description": "Stop the live log tail.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "debug/logs/stop"
        }
      }
    },
    "bleScan": {
      "title": "ble/scan",
      "description": "Listen for Bluetooth LE sensors for `durationMs`, then publish the result on `<prefix>/discovery/ble` (see ble-discovery), echoing `correlationId`. Only sent to gateways whose capability report lists the `ble` protocol.",
      "type": "object",
      "required": [
        "command",
        "correlationId",
        "durationMs"
      ],
      "properties": {
        "command": {
          "const": "ble/scan"
        },
        "correlationId": {
          "description": "A UUID.",
          "type": "string"
        },
        "durationMs": {
          "description": "Scan window, 1-30 s (default 15 s).",
          "type": "integer",
          "minimum": 1000,
          "maximum": 30000
        }
      }
    },
    "jobConfig": {
      "title": "job/config",
      "description": "Edge-owned job settings: which input opens a job, the hooter (alarm output) binding and the operational limit bands. Persist them apart from the device configuration — they deliberately do not ride config/push, whose hash change would reboot the gateway. Only sent when the machine has an edge-mode job profile, and always with at least one of `control`, `hooter`, `limits`. Devices are named by their id (the config/push `_id`).",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "job/config"
        },
        "control": {
          "description": "The digital input that opens and closes jobs (reported on the `job` topic).",
          "type": "object",
          "required": [
            "deviceName",
            "startOn",
            "debounceMs",
            "minJobMs"
          ],
          "properties": {
            "deviceName": {
              "description": "The input device's id.",
              "type": "string"
            },
            "startOn": {
              "description": "Which edge starts a job.",
              "type": "string",
              "enum": [
                "rising",
                "falling"
              ]
            },
            "debounceMs": {
              "type": "number",
              "minimum": 0
            },
            "minJobMs": {
              "description": "Discard a job shorter than this (switch chatter).",
              "type": "number",
              "minimum": 0
            }
          }
        },
        "hooter": {
          "description": "The output to sound on a violation.",
          "type": "object",
          "required": [
            "deviceName",
            "onSafety",
            "onJob"
          ],
          "properties": {
            "deviceName": {
              "description": "The output device's id.",
              "type": "string"
            },
            "onSafety": {
              "description": "Sound on a safety-band violation.",
              "type": "boolean"
            },
            "onJob": {
              "description": "Sound on an operational-band violation during a job.",
              "type": "boolean"
            }
          }
        },
        "jobAck": {
          "description": "When true, the backend confirms every `job` boundary it handles with a `job/ack` command: keep a boundary queued until its ack arrives (match localJobId + event + ts) and resend unconfirmed ones with backoff, in order. Absent or false (an older backend): free a boundary once it has been published, as before. Persist it with the other job settings.",
          "type": "boolean"
        },
        "limits": {
          "description": "Operational bands, already compiled to a single [start, end] range per tag: a reading outside it is a violation. An unbounded side is sent as -1e9 / 1e9.",
          "type": "array",
          "items": {
            "type": "object",
            "required": [
              "deviceName",
              "tag",
              "start",
              "end",
              "duringJob"
            ],
            "properties": {
              "deviceName": {
                "description": "The device's id.",
                "type": "string"
              },
              "tag": {
                "description": "The tag's name, as in config/push.",
                "type": "string"
              },
              "start": {
                "type": "number"
              },
              "end": {
                "type": "number"
              },
              "duringJob": {
                "description": "When the band applies.",
                "type": "string",
                "enum": [
                  "safety_only",
                  "job_only",
                  "both",
                  "none"
                ]
              }
            }
          }
        }
      },
      "anyOf": [
        {
          "required": [
            "control"
          ]
        },
        {
          "required": [
            "hooter"
          ]
        },
        {
          "required": [
            "limits"
          ]
        }
      ]
    },
    "jobAck": {
      "title": "job/ack",
      "description": "The backend has durably handled one `job` boundary. Sent only after the boundary was applied or recognised as a duplicate, or deliberately dropped (`ignored`: jobs are off for the account, the machine has no edge-mode job profile, or an end whose start never arrived). Never sent for a transient error (resend the boundary; the backend is idempotent on localJobId) nor for a gateway the backend does not recognise as the topic tenant's. Free the matching pending boundary for any of the three statuses; an ack that matches nothing (already freed) is ignored.",
      "type": "object",
      "required": [
        "command",
        "localJobId",
        "event",
        "ts",
        "status"
      ],
      "properties": {
        "command": {
          "const": "job/ack"
        },
        "localJobId": {
          "description": "The boundary's localJobId, echoed.",
          "type": "integer",
          "minimum": 0
        },
        "event": {
          "description": "The boundary's event, echoed.",
          "type": "string",
          "enum": [
            "start",
            "end",
            "resume"
          ]
        },
        "ts": {
          "description": "The boundary's ts, echoed verbatim (epoch milliseconds) — it tells two resumes of one job apart.",
          "type": "integer",
          "minimum": 0
        },
        "status": {
          "description": "applied = it changed the job record; duplicate = already recorded; ignored = dropped on purpose, do not resend.",
          "type": "string",
          "enum": [
            "applied",
            "duplicate",
            "ignored"
          ]
        }
      }
    },
    "identify": {
      "title": "identify",
      "description": "Make this unit findable in a rack of identical boxes: blink the on-board LED (GPIO2) at 2 Hz for `durationMs` on a timer (no task, no blocking), then restore the pin's previous state. Ack on cmd/ack at once — `status: error`, `error: PIN_IN_USE` when a configured device already claims GPIO2, so the app can say why nothing blinks. Firmware with a configured hooter may pulse it as well. Sent by POST /gateway/:id/identify.",
      "type": "object",
      "required": [
        "command",
        "correlationId",
        "durationMs"
      ],
      "properties": {
        "command": {
          "const": "identify"
        },
        "correlationId": {
          "description": "A UUID, echoed on cmd/ack.",
          "type": "string"
        },
        "durationMs": {
          "description": "How long to blink, 1-60 s (the backend defaults to 30 s and clamps to this range).",
          "type": "integer",
          "minimum": 1000,
          "maximum": 60000
        }
      }
    },
    "busTapStart": {
      "title": "bus/tap/start",
      "description": "Start (or, if already running, extend and re-scope) the RS485 frame tap on `<prefix>/bus/tap` (see bus-tap) for `durationMs`, then stop on your own. Ack on cmd/ack first. `unitId` narrows the tap to frames to or from one slave address. The tap is a sampler under a per-message and per-second budget — it must never block the polling loop or publish from inside the bus mutex. Sent by POST /gateway/:id/bus/tap {enabled: true}.",
      "type": "object",
      "required": [
        "command",
        "correlationId",
        "durationMs"
      ],
      "properties": {
        "command": {
          "const": "bus/tap/start"
        },
        "correlationId": {
          "description": "A UUID, echoed on cmd/ack.",
          "type": "string"
        },
        "durationMs": {
          "description": "Auto-stop after this long, 1 s - 5 min (the backend defaults to 60 s and clamps to this range). A new start while a tap runs restarts the timer.",
          "type": "integer",
          "minimum": 1000,
          "maximum": 300000
        },
        "unitId": {
          "description": "Only frames addressed to or answered by this slave. Absent = every frame on the bus.",
          "type": "integer",
          "minimum": 1,
          "maximum": 247
        }
      }
    },
    "busTapStop": {
      "title": "bus/tap/stop",
      "description": "Stop the frame tap now. No ack unless a `correlationId` is present. Sent by POST /gateway/:id/bus/tap {enabled: false}.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "bus/tap/stop"
        },
        "correlationId": {
          "description": "Optional; when present, ack it.",
          "type": "string"
        }
      }
    },
    "busScan": {
      "title": "bus/scan",
      "description": "Sweep the bus for Modbus RTU slaves: pause polling, take the bus mutex, and for each baud x parity x id send one FC03/FC04 read of register 0 (quantity 1) with `timeoutMs` as the response timeout; a normal reply OR an exception means a slave is there. With `ident`, follow each hit with FC43/14 (Read Device Identification, basic objects 0x00-0x02). Report on `<prefix>/bus/scan` (see bus-scan): `progress` about every 2 s, then `done` or `error`. Restore the configured serial settings and resume polling afterwards. Budget: 247 ids x 120 ms is about 30 s per (baud, parity); the backend's default sweep (configured baud + 9600/19200/38400, parity N) runs about 2 minutes. Ack on cmd/ack first; `BUS_BUSY` if a tap or capture holds the bus. Only sent to firmware reporting `busScan`. Sent by POST /gateway/:id/bus/scan.",
      "type": "object",
      "required": [
        "command",
        "correlationId",
        "bauds"
      ],
      "properties": {
        "command": {
          "const": "bus/scan"
        },
        "correlationId": {
          "description": "A UUID, echoed on cmd/ack and on every bus/scan message.",
          "type": "string"
        },
        "bauds": {
          "description": "Baud rates to try, in order, 1-4 of them.",
          "type": "array",
          "minItems": 1,
          "maxItems": 4,
          "items": {
            "type": "integer",
            "minimum": 1
          }
        },
        "parity": {
          "description": "Parities to try (8 data bits, 1 stop bit): `N` none, `E` even, `O` odd. Absent = [\"N\"].",
          "type": "array",
          "minItems": 1,
          "maxItems": 3,
          "items": {
            "type": "string",
            "enum": [
              "N",
              "E",
              "O"
            ]
          }
        },
        "ids": {
          "description": "Inclusive slave-address range [from, to]. Absent = [1, 247].",
          "type": "array",
          "minItems": 2,
          "maxItems": 2,
          "items": {
            "type": "integer",
            "minimum": 1,
            "maximum": 247
          }
        },
        "timeoutMs": {
          "description": "Response timeout per probe, 20-2000 ms. Absent = 120.",
          "type": "integer",
          "minimum": 20,
          "maximum": 2000
        },
        "fc": {
          "description": "The probe's function code: 3 (holding registers) or 4 (input registers). Absent = 3.",
          "type": "integer",
          "enum": [
            3,
            4
          ]
        },
        "ident": {
          "description": "Ask each hit for FC43/14 device identification. Absent = true. Optional in the Modbus spec: a slave that does not answer is still reported, without `ident`.",
          "type": "boolean"
        }
      }
    },
    "busScanStop": {
      "title": "bus/scan/stop",
      "description": "Abort a running sweep: publish one `phase: error, error: aborted` on bus/scan, restore the serial settings and resume polling. No ack unless a `correlationId` is present. Sent by POST /gateway/:id/bus/scan/stop.",
      "type": "object",
      "required": [
        "command"
      ],
      "properties": {
        "command": {
          "const": "bus/scan/stop"
        },
        "correlationId": {
          "description": "Optional; when present, ack it.",
          "type": "string"
        }
      }
    },
    "busCapture": {
      "title": "bus/capture",
      "description": "Arm one logic-analyser capture of the RX line (RMT on the UART RX pad) and publish it on `<prefix>/bus/capture` (see bus-capture). `trigger` says when to start: `now`, or on the next received (`next-rx`) or transmitted (`next-tx`) frame. Stop on idle, on buffer overflow, or after `maxMs`. Needs the bus mutex: polling pauses for the capture. Ack on cmd/ack first; `BUS_BUSY` if a scan holds the bus. Only sent to firmware reporting `busCapture`. Sent by POST /gateway/:id/bus/capture.",
      "type": "object",
      "required": [
        "command",
        "correlationId",
        "trigger",
        "maxMs"
      ],
      "properties": {
        "command": {
          "const": "bus/capture"
        },
        "correlationId": {
          "description": "A UUID, echoed on cmd/ack and on the capture.",
          "type": "string"
        },
        "trigger": {
          "description": "When to start sampling. The backend defaults to `now`.",
          "type": "string",
          "enum": [
            "now",
            "next-rx",
            "next-tx"
          ]
        },
        "maxMs": {
          "description": "Give up (and publish what was captured) after this long, 10-2000 ms. The backend defaults to 500 and clamps to this range.",
          "type": "integer",
          "minimum": 10,
          "maximum": 2000
        }
      }
    }
  }
}
