summaryrefslogblamecommitdiffstats
path: root/coapClient.nim
blob: eeeacb144edf312ec287b2b2208591ef098771b0 (plain) (tree)
1
2
3
4
5
6


                   
                                       

 







                                                                                                                                                      
  
                                                                                     

      



                                              

                          
                                                
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)