Skip to content

Commit

Permalink
Powerstrip fixes (#121)
Browse files Browse the repository at this point in the history
* Fix invalid JSON as delivered by powerstrip's info() when it has no cloud connectivity

* wrap mode to avoid crashing on None, use __repr__ instead of __str__
  • Loading branch information
rytilahti authored Nov 19, 2017
1 parent c51e8cc commit bd532b2
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
8 changes: 5 additions & 3 deletions miio/powerstrip.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,13 @@ def load_power(self) -> Optional[float]:
return None

@property
def mode(self) -> PowerMode:
def mode(self) -> Optional[PowerMode]:
"""Current operation mode, can be either green or normal."""
return PowerMode(self.data["mode"])
if self.data["mode"] is not None:
return PowerMode(self.data["mode"])
return None

def __str__(self) -> str:
def __repr__(self) -> str:
s = "<PowerStripStatus power=%s, temperature=%s, " \
"load_power=%s mode=%s>" % \
(self.power,
Expand Down
16 changes: 10 additions & 6 deletions miio/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,16 +167,20 @@ def _decode(self, obj, context):
decrypted = Utils.decrypt(obj, context['_']['token'])
decrypted = decrypted.rstrip(b"\x00")
except Exception:
_LOGGER.debug("Unable to decrypt, returning raw bytes.")
_LOGGER.debug("Unable to decrypt, returning raw bytes: %s", obj)
return obj

decoded = decrypted.decode('utf-8')
try:
jsoned = json.loads(decrypted.decode('utf-8'))
return json.loads(decoded)
except:
_LOGGER.error("unable to parse json, was: %s", decrypted)
raise

return jsoned
try:
# powerstrip returns invalid JSON if the device is not
# connected to the cloud, so we try to fix it here carefully.
decoded = decoded.replace(',,"otu_stat"', ',"otu_stat"')
return json.loads(decoded)
except Exception as ex:
_LOGGER.error("unable to parse json '%s': %s", decoded, ex)


Message = Struct(
Expand Down

0 comments on commit bd532b2

Please sign in to comment.