import std/asyncdispatch import std/[strutils, strtabs] import std/[os, parseopt, httpclient] import std/[json, times] import nmqtt var p = initOptParser(commandLineParams()) var stations : seq[string] var host : string var port : int var user : string var pass : string var topic : string while true: p.next() case p.kind of cmdEnd: break of cmdArgument: break of cmdShortOption, cmdLongOption: case p.key: of "stations": if p.val == "": quit("option 'stations' can't be empty!", 1) else: stations = p.val.split(",") of "mqtt-host": if p.val == "": quit("option 'mqtt-host' can't be empty!", 1) else: host = p.val of "mqtt-port": if p.val == "": quit("option 'mqtt-port' can't be empty!", 1) else: port = p.val.parseInt of "mqtt-user": if p.val == "": quit("option 'mqtt-user' can't be empty!", 1) else: user = p.val of "mqtt-pass": if p.val == "": quit("option 'mqtt-pass' can't be empty!", 1) else: pass = p.val of "mqtt-topic": if p.val == "": quit("option 'mqtt-topic' can't be empty!", 1) else: topic = p.val else: quit("unknown option: '" & $p.key & "'", 1) if (stations.len == 0): quit("You need to specify at least one station!", 1) if (host == ""): quit("You need to specify an mqtt-host!", 1) if (port == 0): port = 1883 if (topic == ""): quit("You need to specify a mqtt-topic!", 1) let client = newHttpClient() var data = newJObject() data.add("lastUpdated", newJInt(getTime().toUnix())) data.add("departures", newJObject()) for id in stations: let jsonData = parseJson(client.getContent("https://www.kvg-kiel.de/internetservice/services/passageInfo/stopPassages/stop?stop=" & $id & "&mode=departure&language=en")) var departures = newJArray() for entry in jsonData{"actual"}: departures.add(%* { "line": entry{"patternText"}, "direction": entry{"direction"}, "departure_in": entry{"mixedTime"}.getStr.replace(" %UNIT_MIN%", "") }) data["departures"].add(jsonData{"stopName"}.getStr, departures) let mqtt = newMqttCtx("departures2mqtt") mqtt.set_verbosity(1) mqtt.set_host(host, port) if (user != "" and pass != ""): mqtt.set_auth(user, pass) waitFor mqtt.connect() waitFor sleepAsync 500 waitFor mqtt.publish(topic, $data, 2, true) waitFor sleepAsync 500 waitFor mqtt.disconnect()