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 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
import json, strutils, options, algorithm

import coapClient
import gatewayTypes, deviceTypes
import mappings, helpers

proc parseDevice (data: JsonNode): TradfriDevice = 
  let deviceType = TradfriDeviceType(data[ParameterType].getInt)
  var state:       TradfriDeviceState

  case deviceType:
    of Remote:
      state = TradfriDeviceState(
          kind:                     deviceType,
          remoteSupported:          false
        )

    of slaveRemote:
      state = TradfriDeviceState(
          kind:                     deviceType,
          slaveRemoteSupported:     false
        )

    of Lightbulb:
      state = TradfriDeviceState(
          kind:                     deviceType,
          lightPowered:             parseBool($data[DeviceLightbulb][0][ParameterPowerState].getInt),
          lightBrightness:          data[DeviceLightbulb][0][ParameterDimmerValue].getInt
        )

      #get hue and saturation (only for RGB-bulbs)
      if data[DeviceLightbulb][0].hasKey(ParameterHue):
        state.lightHue        = some(data[DeviceLightbulb][0][ParameterHue].getInt)
        state.lightSaturation = some(data[DeviceLightbulb][0][ParameterSaturation].getInt)
      else:
        state.lightHue        = none(int)
        state.lightSaturation = none(int)      


      #get color hex-value (for white-spectrum and RGB, but only some presets)
      if data[DeviceLightbulb][0].hasKey(ParameterColorHex):
        state.lightColorHex   = some(data[DeviceLightbulb][0][ParameterColorHex].getStr)
      else:
        state.lightColorHex   = none(string)

      #get colorX and colorY values (can be used to set any color on RGB bulbs)
      if data[DeviceLightbulb][0].hasKey(ParameterColorX):
        state.lightColorX     = some(data[DeviceLightbulb][0][ParameterColorX].getFloat)
        state.lightColorY     = some(data[DeviceLightbulb][0][ParameterColorY].getFloat)
      else:
        state.lightColorX     = none(float)
        state.lightColorY     = none(float)


      #get color-specturm value
      if data[DeviceLightbulb][0].hasKey(ParameterColorTemperature):
        state.lightColorTemperature = some(data[DeviceLightbulb][0][ParameterColorTemperature].getInt)
      else:
        state.lightColorTemperature = none(int)

      #determine type of bulb
      if state.lightHue.isSome:
        state.lightSpectrum = RGB
      elif state.lightColorTemperature.isSome:
        state.lightSpectrum = White
      else:
        state.lightSpectrum = None
      
    of Plug:
      state = TradfriDeviceState(
          kind:                    deviceType,
          plugPowered:             parseBool($data[DevicePlug][0][ParameterPowerState].getInt),
          plugDimmer:              data[DevicePlug][0][ParameterDimmerValue].getInt
        )

    of motionSensor:
      state = TradfriDeviceState(
          kind:                    deviceType,
          motionSensorSupported:   false
        )

    of signalRepeater:
      state = TradfriDeviceState(
          kind:                    deviceType,
          signalRepeaterSupported: false
        )

    of Blind:
      state = TradfriDeviceState(
          kind:                    deviceType,
          blindPosition:           data["3"][ParameterBlindPosition].getFloat,
          blindTrigger:            data["3"][ParameterBlindTrigger].getFloat
        )

    of soundRemote:
      state = TradfriDeviceState(
          kind:                    deviceType,
          soundRemoteSupported:    false
        )

  return TradfriDevice(
      `type`:      deviceType,
      id:          data[ParameterId].getInt,
      name:        data[ParameterName].getStr,
      alive:       intToBool(data[ParameterAlive].getInt),
      createdAt:   data[ParameterCreatedAt].getInt,
      lastSeen:    data[ParameterLastSeen].getInt,
      state:       state,
      info:        TradfriDeviceInfo(
        manufacturer:    data["3"]["0"].getStr,
        modelNumber:     data["3"]["1"].getStr,
        serialNumber:    data["3"]["2"].getStr,
        firmwareVersion: data["3"]["3"].getStr,
        power:           TradfriPowerSource(data["3"]["6"].getInt),
        battery:         data["3"]{"9"}.getInt
      )
    )


proc operateDevice* (device: TradfriDevice, action: TradfriDeviceAction): bool = 
  var requestParams = %* {}

  template CheckDeviceType(typeId: TradfriDeviceType) = 
    if device.`type` != TradfriDeviceType(typeId):
      raise newException(ValueError, "Wrong action for this Devicetype")
    
  case action.kind:
  of DeviceRename:
    requestParams.add(ParameterName, %action.deviceName)

  of LightSetPowerState:
    CheckDeviceType(Lightbulb)
    
    requestParams.add(DeviceLightbulb, %* [{
      ParameterPowerState:          boolToInt(action.lightPowerState),
      ParameterTransitionTime:      action.transitionTime
    }])

  of LightSetBrightness:
    CheckDeviceType(Lightbulb)

    requestParams.add(DeviceLightbulb, %* [{
      ParameterDimmerValue:         action.lightBrightness,
      ParameterTransitionTime:      action.transitionTime
    }])

  of LightSetColorHex:
    CheckDeviceType(Lightbulb)

    requestParams.add(DeviceLightbulb, %* [{
      ParameterColorHex:            action.lightColorHex,
      ParameterTransitionTime:      action.transitionTime
    }])

  of LightSetColorXY:
    CheckDeviceType(Lightbulb)

    requestParams.add(DeviceLightbulb, %* [{
      ParameterColorX:              action.lightColorX,
      ParameterColorY:              action.lightColorY,
      ParameterTransitionTime:      action.transitionTime
    }])

  of LightSetHueSaturation:
    CheckDeviceType(Lightbulb)

    requestParams.add(DeviceLightbulb, %* [{
      ParameterHue:                 action.lightHue,
      ParameterSaturation:          action.lightSaturation,
      ParameterTransitionTime:      action.transitionTime
    }])

  of LightSetColorTemperature:
    CheckDeviceType(Lightbulb)

    requestParams.add(DeviceLightbulb, %* [{
      ParameterColorTemperature:    action.lightColorTemperature,
      ParameterTransitionTime:      action.transitionTime
    }])

  of PlugSetPowerState:
    CheckDeviceType(Plug)

    requestParams.add(DevicePlug, %* [{
      ParameterPowerState:          boolToInt(action.plugPowerState),
    }])

  of PlugSetDimmerValue:
    CheckDeviceType(Plug)

    requestParams.add(DevicePlug, %* [{
      ParameterDimmerValue:         action.plugDimmerValue,
    }])


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


proc getDevice* (gatewayRef: TradfriGatewayRef, deviceId: int): TradfriDevice = 
  let request = makeCoapRequest(gatewayRef.host, gatewayRef.port, "get", gatewayRef.user, gatewayRef.pass, EndpointDevices & $deviceId, %* {})

  result = parseDevice(request)
  result.gatewayRef = gatewayRef

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

  result = newSeq[TradfriDevice]()

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

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