import asyncnet import asyncdispatch import threadpool import sequtils import os import strutils var tcpClients: seq[AsyncSocket] tcpClients = @[] proc broadcast(msg: string) = for client in tcpClients: try: asyncCheck client.send(msg) except: client.close() tcpClients.keepIf(proc(x: AsyncSocket): bool = x != client) proc serveTcp(port: int) {.async.} = var socket = newAsyncSocket() socket.setSockOpt(OptReuseAddr, true) socket.bindAddr(Port(port)) socket.listen() while true: let client = await socket.accept() tcpClients.add(client) proc asyncReadLine*(file: File): Future[string] = var fut = newFuture[string]() var flowVar = spawn file.readLine() addTimer(50, false, proc(fd: AsyncFD): bool = if flowVar.isReady(): fut.complete(^flowVar) return true ) return fut proc readSerial(serial: string) {.async.} = let file = open(serial, fmReadWrite) while true: let line = await file.asyncReadLine() broadcast(line & '\n') let port = parseInt(getEnv("PORT")) let serial = getEnv("SERIAL_DEVICE") asyncCheck serveTcp(port) asyncCheck readSerial(serial) runForever()