https://toitlang.org/ logo
``` main: backoff := 1000 while true: star...
# general
f
Copy code
main:
  backoff := 1000
  while true:
    start := Time.monotonic-us
    e := catch:
      run-mqtt
    if e:
      attempt-duration := Time.monotonic-us - start
      if attempt-duration < 1_000_000:
        // Immediate failure. Increase backoff.
        backoff = min (2 * backoff) 60_000
      else:
        // Slow failure. Reset backoff.
        backoff = 1000
      print "caught exception $e"
      sleep --ms=backoff

run-mqtt:
  transport/mqtt.Transport? := null
  client/mqtt.SimpleClient? := null
  receive-task/Task? := null
  try:
    transport = mqtt.TcpTransport --host=HOST --port=PORT
    logger := log.default.with-level log.INFO-LEVEL
    client = mqtt.SimpleClient --transport=transport --logger=logger

    options := mqtt.SessionOptions
        --client-id=CLIENT-ID
        --username=USERNAME
        --password=PASSWORD

    client.start --options=options

    receive-task = task --no-background::
      catch:
        while true:
          publish := client.receive
          if not publish: break  // Closed.
          if publish.topic == "$TOPIC/control":
            handle-control (json.decode publish.payload)
          else:
            print "Received unexpected topic: $publish.topic"

    client.subscribe "$TOPIC/control"

    while true:
      sleep --ms=2_000
      payload := json.encode {
        "solar": solar,
        "mains": "21",
        "solar_power": "192",
        "diverted_power": "7777",
        "diverted_power_percent": "9966"
      }
      client.publish "$TOPIC/data" payload  // our payload is published every two seconds

  finally:
    if client: client.close
    if receive-task: receive-task.cancel
    if transport: transport.close