summaryrefslogtreecommitdiffstats
path: root/coapClient.nim
blob: eeeacb144edf312ec287b2b2208591ef098771b0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import osproc, json

type 
  CoapException* = object of ValueError


proc makeCoapRequest* (host: string, port: int, reqMethod: string, user: string, password: string, endpoint: string, reqPayload: JsonNode): JsonNode =
  var arguments = @["-B", "2", "-m", reqMethod, "-u", user, "-k", password]

  if reqMethod == "put":
    arguments.add("-e")
    arguments.add($reqPayload)

  arguments.add("coaps://" & host & ":" & $port & endpoint)
  
  let reqResult = execProcess("coap-client", args = arguments, options = {poUsePath})

  try:
    if reqMethod == "put" and reqResult == "":
      return %* {}

    return parseJson(reqResult)

  except JsonParsingError:
    raise newException(CoapException, reqResult)