import asyncdispatch, strutils, tables, httpclient, options, json, uri import types, vars proc existsDatabase* (config: InfluxConfig, databaseName: string): Future[bool] {.async.}= try: var client = newAsyncHttpClient() if config.authToken.isSome: client.headers["Authorization"] = "Token " & $config.authToken.get let baseUrl = "http://" & config.host & ":" & $config.port & "/" let response = await client.getContent(baseUrl & "query?" & encodeQuery({"db": databaseName, "q": "select * FROM test LIMIT 1"})) let data = parseJson(response) client.close() if data["results"][0].hasKey("error"): return false return true except: echo "Error[existsDatabase]:\n", getCurrentExceptionMsg() proc insertDatabase* (config: InfluxConfig, databaseName: string, tableName: string, tags: Table[string, string], fields: Table[string, string], timestamp: int64): Future[bool] {.async.} = try: var client = newAsyncHttpClient() if config.authToken.isSome: client.headers["Authorization"] = "Token " & $config.authToken.get let baseUrl = "http://" & config.host & ":" & $config.port & "/" var tagsCombined: seq[string] var fieldsCombined: seq[string] for key, value in pairs(tags): tagsCombined.add(key & "=" & value) for key, value in pairs(fields): fieldsCombined.add(key & "=" & value) let body = tableName & "," & tagsCombined.join(",") & " " & fieldsCombined.join(",") & " " & $timestamp let response = await client.request(baseUrl & "write?db=" & databaseName, httpMethod = HttpPost, body = body) client.close() if response.code != Http204: return false return true except: echo "Error[insertDatabase]:\n", getCurrentExceptionMsg() proc initInflux* () = let config = server.config.serverConfig.influx.get try: if config.powermetersDatabase.isSome: if not waitFor config.existsDatabase(config.powermetersDatabase.get): echo "Specified Influxdatabase for powermeters does not exist!" quit() if config.sensorsDatabase.isSome: if not waitFor config.existsDatabase(config.sensorsDatabase.get): echo "Specified Influxdatabase for sensors does not exist!" quit() except: echo "Error[initInflux]:\n", getCurrentExceptionMsg() quit()