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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
|
from sys import version_info
if version_info.major == 3:
from json.decoder import JSONDecodeError
else:
JSONDecodeError = ValueError
from requests import post
from requests.auth import HTTPBasicAuth
from .error import BadLogin, NotFound, BadResponse
from .base import ShellyBase
class ShellyGen1(ShellyBase):
def __init__(self, ip, port = "80", *args, **kwargs):
"""
@param ip the target IP of the shelly device. Can be a string, list of strings or list of integers
@param port target port, may be useful for non Shelly devices that have the same HTTP Api
@param login dict of login credentials. Keys needed are "username" and "password"
@param timeout specify the amount of time until requests are aborted.
@param debug enable debug printing
@param init calls the update method on init
"""
super().__init__(ip, port, *args, **kwargs)
self.__generation__ = 1
def update(self):
"""
@brief update the Shelly attributes
@param index index of the relay
"""
status = self.settings()
self.__type__ = status['device'].get("type", self.__type__)
self.__name__ = status['device'].get("hostname", self.__name__)
# Settings are already fetched to get device information might as well put the list of things the device has somewhere
self.relays = status.get("relays", [])
self.rollers = status.get("rollers", [])
# RGBW reuses the same lights array
self.lights = status.get("lights", [])
self.irs = status.get("light_sensor", None)
self.emeters = status.get("emeter", [])
self.meters = []
meter_index = 0
# Meters are not returned as part of the settings
while True:
try:
# Request meter information
self.meter.append(self.meter(meter_index))
meter_index += 1
except:
break
def post(self, page, values = None):
"""
@brief returns settings
@param page page to be accesed. Use the Shelly HTTP API Reference to see whats possible
@return returns json response
"""
url = "{}://{}:{}/{}?".format(self.__PROTOCOL__, self.__ip__, self.__port__, page)
if values:
url += "&".join(["{}={}".format(key, value) for key, value in values.items()])
if self.__debugging__:
print("Target Adress: {}\n"
"Authentication: {}\n"
"Timeout: {}"
"".format(url, any(self.__credentials__), self.__timeout__))
credentials = HTTPBasicAuth(*self.__credentials__)
response = post(url, auth=credentials,
timeout=self.__timeout__)
if response.status_code == 401:
raise BadLogin()
elif response.status_code == 404:
raise NotFound("Not Found")
try:
return response.json()
except JSONDecodeError:
raise BadResponse("Bad JSON")
def status(self):
"""
@brief returns status response
@return status dict
"""
return self.post("status")
def settings(self, subpage = None):
"""
@brief returns settings
@param page page to be accesed. Use the Shelly HTTP API Reference to see whats possible
@return returns settings as a dict
"""
page = "settings"
if subpage:
page += "/" + subpage
return self.post(page)
def meter(self, index):
"""
@brief Get meter information from a relay at the given index
@param index index of the relay
@return returns attributes of meter: power, overpower, is_valid, timestamp, counters, total
"""
return self.post("meter/{}".format(index))
def relay(self, index, *args, **kwargs):
"""
@brief Interacts with a relay at the given index
@param index index of the relay
@param turn Will turn the relay on or off
@param timer a one-shot flip-back timer in seconds
"""
values = {}
turn = kwargs.get("turn", None)
timer = kwargs.get("timer", None)
if turn is not None:
if turn:
values["turn"] = "on"
else:
values["turn"] = "off"
if timer:
values["timer"] = timer
return self.post("relay/{}".format(index), values)
def roller(self, index, *args, **kwargs):
"""
@brief Interacts with a roller at a given index
@param self The object
@param index index of the roller. When in doubt use 0
@param go way of the roller to go. Accepted are "open", "close", "stop", "to_pos"
@param roller_pos the wanted position in percent
@param duration how long it will take to get to that position
"""
go = kwargs.get("go", None)
roller_pos = kwargs.get("roller_pos", None)
duration = kwargs.get("duration", None)
values = {}
if go:
values["go"] = go
if roller_pos is not None:
values["roller_pos"] = self.__clamp_percentage__(roller_pos)
if duration is not None:
values["duration"] = duration
return self.post("roller/{}".format(index), values)
def light(self, index, *args, **kwargs):
"""
@brief Interacts with lights at a given index
@param mode Accepts "white" and "color" as possible modes
@param index index of the light. When in doubt use 0
@param timer a one-shot flip-back timer in seconds
@param turn Will turn the lights on or off
@param red Red brightness, 0..255, only works if mode="color"
@param green Green brightness, 0..255, only works if mode="color"
@param blue Blue brightness, 0..255, only works if mode="color"
@param white White brightness, 0..255, only works if mode="color"
@param gain Gain for all channels, 0...100, only works if mode="color"
@param temp Color temperature in K, 3000..6500, only works if mode="white"
@param brightness Brightness, 0..100, only works if mode="white"
"""
mode = kwargs.get("mode", None)
timer = kwargs.get("timer", None)
turn = kwargs.get("turn", None)
red = kwargs.get("red", None)
green = kwargs.get("green", None)
blue = kwargs.get("blue", None)
white = kwargs.get("white", None)
gain = kwargs.get("gain", None)
temp = kwargs.get("temp", None)
brightness = kwargs.get("brightness", None)
values = {}
if mode:
values["mode"] = mode
if timer is not None:
values["timer"] = timer
if turn is not None:
if turn:
values["turn"] = "on"
else:
values["turn"] = "off"
if red is not None:
values["red"] = self.__clamp__(red)
if green is not None:
values["green"] = self.__clamp__(green)
if blue is not None:
values["blue"] = self.__clamp__(blue)
if white is not None:
values["white"] = self.__clamp__(white)
if gain is not None:
values["gain"] = self.__clamp_percentage__(gain)
if temp is not None:
values["temp"] = self.__clamp_kalvin__(temp)
if brightness is not None:
values["brightness"] = self.__clamp_percentage__(brightness)
return self.post("light/{}".format(index), values)
def emeter(self, index, *args, **kwargs):
return self.post("emeter/{}".format(index))
# backwards compatibility with old code
Shelly = ShellyGen1
|