From 00bbc17e11753cd10f57f07e437aab6f22f87f70 Mon Sep 17 00:00:00 2001 From: Paulus Schoutsen Date: Tue, 31 Mar 2015 23:08:38 -0700 Subject: [PATCH] Add State.last_updated to JSON obj --- homeassistant/__init__.py | 15 +++++++++++---- homeassistant/components/recorder.py | 3 ++- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/homeassistant/__init__.py b/homeassistant/__init__.py index d1cb17f22c620..898b66c4ef94d 100644 --- a/homeassistant/__init__.py +++ b/homeassistant/__init__.py @@ -463,7 +463,8 @@ class State(object): __slots__ = ['entity_id', 'state', 'attributes', 'last_changed', 'last_updated'] - def __init__(self, entity_id, state, attributes=None, last_changed=None): + def __init__(self, entity_id, state, attributes=None, last_changed=None, + last_updated=None): if not ENTITY_ID_PATTERN.match(entity_id): raise InvalidEntityFormatError(( "Invalid entity id encountered: {}. " @@ -472,7 +473,7 @@ def __init__(self, entity_id, state, attributes=None, last_changed=None): self.entity_id = entity_id.lower() self.state = state self.attributes = attributes or {} - self.last_updated = dt.datetime.now() + self.last_updated = last_updated or dt.datetime.now() # Strip microsecond from last_changed else we cannot guarantee # state == State.from_dict(state.as_dict()) @@ -510,7 +511,8 @@ def as_dict(self): return {'entity_id': self.entity_id, 'state': self.state, 'attributes': self.attributes, - 'last_changed': util.datetime_to_str(self.last_changed)} + 'last_changed': util.datetime_to_str(self.last_changed), + 'last_updated': util.datetime_to_str(self.last_updated)} @classmethod def from_dict(cls, json_dict): @@ -527,8 +529,13 @@ def from_dict(cls, json_dict): if last_changed: last_changed = util.str_to_datetime(last_changed) + last_updated = json_dict.get('last_updated') + + if last_updated: + last_updated = util.str_to_datetime(last_updated) + return cls(json_dict['entity_id'], json_dict['state'], - json_dict.get('attributes'), last_changed) + json_dict.get('attributes'), last_changed, last_updated) def __eq__(self, other): return (self.__class__ == other.__class__ and diff --git a/homeassistant/components/recorder.py b/homeassistant/components/recorder.py index f2e5fa35ad4f0..6856ce4d7b563 100644 --- a/homeassistant/components/recorder.py +++ b/homeassistant/components/recorder.py @@ -60,7 +60,8 @@ def row_to_state(row): """ Convert a databsae row to a state. """ try: return State( - row[1], row[2], json.loads(row[3]), datetime.fromtimestamp(row[4])) + row[1], row[2], json.loads(row[3]), datetime.fromtimestamp(row[4]), + datetime.fromtimestamp(row[5])) except ValueError: # When json.loads fails _LOGGER.exception("Error converting row to state: %s", row)