| 1 |
import functools |
| 2 |
import json |
| 3 |
import os |
| 4 |
import time |
| 5 |
|
| 6 |
import requests |
| 7 |
|
| 8 |
try: |
| 9 |
import urlparse |
| 10 |
except ImportError: |
| 11 |
import urllib.parse as urlparse |
| 12 |
|
| 13 |
|
| 14 |
TIME_FORMAT = "%Y-%m-%dT%H:%M:%S" |
| 15 |
|
| 16 |
|
| 17 |
class FailedToLogin(Exception): |
| 18 |
pass |
| 19 |
|
| 20 |
|
| 21 |
class DeviceNotFound(Exception): |
| 22 |
pass |
| 23 |
|
| 24 |
|
| 25 |
class RequestFailed(Exception): |
| 26 |
pass |
| 27 |
|
| 28 |
|
| 29 |
class Device: |
| 30 |
def __init__(self, client, ident): |
| 31 |
self._client = client |
| 32 |
self.ident = ident |
| 33 |
self._devinfo = {} |
| 34 |
self._ports = {} |
| 35 |
|
| 36 |
def refresh(self, info=None): |
| 37 |
if info is None: |
| 38 |
info = self._client._find_device(ident=self.ident) |
| 39 |
self._devinfo = info |
| 40 |
|
| 41 |
def set_port(self, port): |
| 42 |
self._ports[port.ident] = port |
| 43 |
|
| 44 |
@property |
| 45 |
def ports(self): |
| 46 |
return self._ports |
| 47 |
|
| 48 |
@property |
| 49 |
def data(self): |
| 50 |
return self._devinfo |
| 51 |
|
| 52 |
|
| 53 |
class Port: |
| 54 |
def __init__(self, client, ident): |
| 55 |
self._client = client |
| 56 |
self.ident = ident |
| 57 |
self._portinfo = {} |
| 58 |
|
| 59 |
def refresh(self, info=None): |
| 60 |
if info is None: |
| 61 |
sensors = self._client._get_sensors() |
| 62 |
info = self._client._find_sensor(sensors, self.ident) |
| 63 |
self._portinfo.update(info) |
| 64 |
|
| 65 |
def __repr__(self): |
| 66 |
try: |
| 67 |
data = "%s=%s" % (self.tag, self.value) |
| 68 |
except ValueError: |
| 69 |
data = "?" |
| 70 |
return "<Port %s %s>" % (self.ident, data) |
| 71 |
|
| 72 |
@property |
| 73 |
def value(self): |
| 74 |
if "tag" not in self._portinfo: |
| 75 |
raise ValueError("Port has no value") |
| 76 |
return self._portinfo.get(self.tag) |
| 77 |
|
| 78 |
@property |
| 79 |
def tag(self): |
| 80 |
if "tag" not in self._portinfo: |
| 81 |
raise ValueError("Port is not initialized") |
| 82 |
return self._portinfo["tag"] |
| 83 |
|
| 84 |
@property |
| 85 |
def data(self): |
| 86 |
return self._portinfo |
| 87 |
|
| 88 |
@property |
| 89 |
def label(self): |
| 90 |
return self._portinfo["label"] |
| 91 |
|
| 92 |
@property |
| 93 |
def model(self): |
| 94 |
return self._portinfo["model"] |
| 95 |
|
| 96 |
@property |
| 97 |
def output(self): |
| 98 |
return self._portinfo.get("output") |
| 99 |
|
| 100 |
def control(self, state): |
| 101 |
self._client._control_port(self.ident, state) |
| 102 |
|
| 103 |
|
| 104 |
def retries_login(fn): |
| 105 |
@functools.wraps(fn) |
| 106 |
def wrapper(self, *args, **kwargs): |
| 107 |
for i in (0, 1): |
| 108 |
try: |
| 109 |
return fn(self, *args, **kwargs) |
| 110 |
except RequestFailed: |
| 111 |
if i == 0: |
| 112 |
self._login() |
| 113 |
else: |
| 114 |
|
| 115 |
|
| 116 |
raise |
| 117 |
|
| 118 |
return wrapper |
| 119 |
|
| 120 |
|
| 121 |
class MFiClient: |
| 122 |
def __init__(self, host, username, password, port=None, use_tls=True, verify=True): |
| 123 |
self._host = host |
| 124 |
self._port = port |
| 125 |
self._user = username |
| 126 |
self._pass = password |
| 127 |
self._stat_cache = None |
| 128 |
self._cookie = None |
| 129 |
self._session = requests.Session() |
| 130 |
self._verify = verify |
| 131 |
if use_tls: |
| 132 |
port = port or 6443 |
| 133 |
self._baseurl = "https://%s:%i" % (host, port) |
| 134 |
else: |
| 135 |
port = port or 6080 |
| 136 |
self._baseurl = "http://%s:%i" % (host, port) |
| 137 |
|
| 138 |
self._login() |
| 139 |
|
| 140 |
def _login(self): |
| 141 |
response = self._session.get(self._baseurl, verify=self._verify) |
| 142 |
|
| 143 |
data = {"username": self._user, "password": self._pass, "login": "Login"} |
| 144 |
|
| 145 |
response = self._session.post( |
| 146 |
"%s/login" % self._baseurl, data=data, verify=self._verify |
| 147 |
) |
| 148 |
if response.status_code == 200 and response.url.endswith("/manage"): |
| 149 |
return |
| 150 |
|
| 151 |
raise FailedToLogin("Server rejected login") |
| 152 |
|
| 153 |
@retries_login |
| 154 |
def _get_stat(self): |
| 155 |
response = self._session.get( |
| 156 |
"%s/api/v1.0/stat/device" % self._baseurl, verify=self._verify |
| 157 |
) |
| 158 |
if response.status_code == 200: |
| 159 |
return response.json()["data"] |
| 160 |
raise RequestFailed() |
| 161 |
|
| 162 |
@retries_login |
| 163 |
def _get_sensors(self): |
| 164 |
data = {"json": json.dumps({"hello": 2})} |
| 165 |
response = self._session.post( |
| 166 |
"%s/api/v1.0/list/sensors" % self._baseurl, data=data, verify=self._verify |
| 167 |
) |
| 168 |
if response.status_code == 200: |
| 169 |
return response.json()["data"] |
| 170 |
raise RequestFailed() |
| 171 |
|
| 172 |
get_raw_sensors = _get_sensors |
| 173 |
get_raw_status = _get_stat |
| 174 |
|
| 175 |
@staticmethod |
| 176 |
def _find_sensor(sensors, ident): |
| 177 |
for sensor in sensors: |
| 178 |
if sensor["_id"] == ident: |
| 179 |
return sensor |
| 180 |
raise DeviceNotFound("No sensor %s" % ident) |
| 181 |
|
| 182 |
def get_devices(self): |
| 183 |
stat = self._get_stat() |
| 184 |
sensors = self._get_sensors() |
| 185 |
|
| 186 |
devices = [] |
| 187 |
for devinfo in stat: |
| 188 |
device = Device(self, devinfo["_id"]) |
| 189 |
for portinfo in devinfo["port_cfg"]: |
| 190 |
if portinfo["_id"] == "NONE": |
| 191 |
continue |
| 192 |
sensorinfo = self._find_sensor(sensors, portinfo["_id"]) |
| 193 |
|
| 194 |
port = Port(self, portinfo["_id"]) |
| 195 |
port.refresh(portinfo) |
| 196 |
port.refresh(sensorinfo) |
| 197 |
device.set_port(port) |
| 198 |
devices.append(device) |
| 199 |
return devices |
| 200 |
|
| 201 |
def get_port(self, ident=None, label=None): |
| 202 |
for device in self.get_devices(): |
| 203 |
for port in device.ports.values(): |
| 204 |
if port.label == label or port.ident == ident: |
| 205 |
return port |
| 206 |
return None |
| 207 |
|
| 208 |
def get_stat(self): |
| 209 |
if not self._stat_cache: |
| 210 |
self._stat_cache = self._get_stat() |
| 211 |
return self._stat_cache |
| 212 |
|
| 213 |
@retries_login |
| 214 |
def _control_port(self, ident, state, voltage=0): |
| 215 |
the_port = self._find_port(ident=ident) |
| 216 |
|
| 217 |
voltages = { |
| 218 |
"Output 5v": 5, |
| 219 |
"Output 12v": 12, |
| 220 |
"Output 24v": 24, |
| 221 |
} |
| 222 |
voltage = state and voltages.get(the_port["model"], 0) or 0 |
| 223 |
|
| 224 |
data = { |
| 225 |
"sId": ident, |
| 226 |
"mac": the_port["mac"], |
| 227 |
"model": the_port["model"], |
| 228 |
"port": int(the_port["port"]), |
| 229 |
"cmd": "mfi-output", |
| 230 |
"val": int(state), |
| 231 |
"volt": voltage, |
| 232 |
} |
| 233 |
data = {"json": json.dumps(data)} |
| 234 |
response = self._session.post( |
| 235 |
"%s/api/v1.0/cmd/devmgr" % self._baseurl, data=data, verify=self._verify |
| 236 |
) |
| 237 |
if response.status_code == 200: |
| 238 |
return response.text |
| 239 |
raise RequestFailed() |
| 240 |
|
| 241 |
def _find_port(self, ident=None, device_name=None): |
| 242 |
devices = self.get_stat() |
| 243 |
|
| 244 |
for dev in devices: |
| 245 |
for port in dev["port_cfg"]: |
| 246 |
if port["_id"] == ident: |
| 247 |
return port |
| 248 |
if port["label"] == device_name: |
| 249 |
return port |
| 250 |
raise DeviceNotFound("No such device") |
| 251 |
|
| 252 |
def get_device_data(self, device, since=60): |
| 253 |
|
| 254 |
port = self._find_device(device) |
| 255 |
sensor = self._find_sensor(device) |
| 256 |
|
| 257 |
start = time.time() - since |
| 258 |
end = time.time() |
| 259 |
data = { |
| 260 |
"fmt": "json", |
| 261 |
"ids": port["_id"], |
| 262 |
"tags": sensor["tag"], |
| 263 |
"indices": "1,2,3,4", |
| 264 |
"func": "trend", |
| 265 |
"collection": "null", |
| 266 |
"startTime": int(start) * 1000, |
| 267 |
"endTime": int(end) * 1000, |
| 268 |
} |
| 269 |
response = self._session.get( |
| 270 |
"%s/api/v1.0/data/m2mgeneric_by_id" % self._baseurl, |
| 271 |
params=data, |
| 272 |
verify=self._verify, |
| 273 |
) |
| 274 |
return response.json()["data"][0]["%s.0" % sensor["tag"]] |
| 275 |
|
| 276 |
|
| 277 |
def get_auth_from_env(): |
| 278 |
""" |
| 279 |
Attempt to get mFi connection information from the environment. |
| 280 |
|
| 281 |
Supports either a combined variable called MFI formatted like: |
| 282 |
|
| 283 |
MFI="http://user:[email protected]:6080/ |
| 284 |
|
| 285 |
or individual ones like: |
| 286 |
|
| 287 |
MFI_HOST=192.168.1.1 |
| 288 |
MFI_PORT=6080 |
| 289 |
MFI_USER=foo |
| 290 |
MFI_PASS=pass |
| 291 |
|
| 292 |
:returns: A tuple like (host, port, user, pass, path) |
| 293 |
""" |
| 294 |
combined = os.getenv("MFI") |
| 295 |
if combined: |
| 296 |
|
| 297 |
result = urlparse.urlparse(combined) |
| 298 |
netloc = result.netloc |
| 299 |
if "@" in netloc: |
| 300 |
creds, netloc = netloc.split("@", 1) |
| 301 |
user, _pass = creds.split(":", 1) |
| 302 |
else: |
| 303 |
user = "mfiadmin" |
| 304 |
_pass = "password" |
| 305 |
if ":" in netloc: |
| 306 |
host, port = netloc.split(":", 1) |
| 307 |
port = int(port) |
| 308 |
else: |
| 309 |
host = netloc |
| 310 |
port = 6080 |
| 311 |
path = result.path |
| 312 |
tls = combined.startswith("https://") |
| 313 |
else: |
| 314 |
host = os.getenv("MFI_HOST") |
| 315 |
port = int(os.getenv("MFI_PORT", 7080)) |
| 316 |
user = os.getenv("MFI_USER") |
| 317 |
_pass = os.getenv("MFI_PASS") |
| 318 |
path = "/" |
| 319 |
tls = False |
| 320 |
return host, port, user, _pass, path, tls |
| 321 |
|
| 322 |
|
| 323 |
def envclient(): |
| 324 |
host, port, user, _pass, path = get_auth_from_env() |
| 325 |
return MFiClient(host, user, _pass, port=port) |