ctucx.git: nimtradfri

[nimlang] incomplete library to interact with ikea tradfri-gateways

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 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
import json, strutils, sequtils, options, algorithm

import coapClient
import gatewayTypes, groupTypes, deviceTypes
import mappings, helpers, devices

proc operateGroup* (group: TradfriGroup, action: TradfriGroupAction): bool = 
  var requestParams = %* {}

  case action.kind:
  of GroupRename:
    requestParams.add(ParameterName, %action.groupName)

  of GroupSetPowerState:
    requestParams.add(DeviceLightbulb, %* [{
      ParameterPowerState:          boolToInt(action.groupPowerState),
    }])


  discard makeCoapRequest(group.gatewayRef.host, group.gatewayRef.port, "put", group.gatewayRef.user, group.gatewayRef.pass, EndpointGroups & $group.id, requestParams)


proc getGroup* (gatewayRef: TradfriGatewayRef, groupId: int): TradfriGroup = 
  let request = makeCoapRequest(gatewayRef.host, gatewayRef.port, "get", gatewayRef.user, gatewayRef.pass, EndpointGroups & $groupId, %* {})

  var devices = newSeq[TradfriDevice]()
  for deviceId in request[ParameterDeviceIds]["15002"]["9003"]:
    devices.add(gatewayRef.getDevice(deviceId.getInt))

  devices.sort do (x, y: TradfriDevice) -> int:
    result = cmp(x.id, y.id)

  result = TradfriGroup(
    gatewayRef:   gatewayRef,
    name:         request[ParameterName].getStr,
    createdAt:    request[ParameterCreatedAt].getInt,
    id:           request[ParameterId].getInt,
    powerState:   intToBool(request[ParameterPowerState].getInt),
    dimmerValue:  request[ParameterDimmerValue].getInt,
    sceneId:      request[ParameterSceneId].getInt,
    devices:      devices
  )


proc getGroups* (gatewayRef: TradfriGatewayRef): seq[TradfriGroup] = 
  let request = makeCoapRequest(gatewayRef.host, gatewayRef.port, "get", gatewayRef.user, gatewayRef.pass, EndpointGroups, %* {})

  result = newSeq[TradfriGroup]()

  for id in request:
    result.add(getGroup(gatewayRef, id.getInt))

  result.sort do (x, y: TradfriGroup) -> int:
    result = cmp(x.id, y.id)