1
1
"""Sensor platform for Daily Sensor."""
2
+
2
3
import asyncio
3
4
import logging
4
5
from statistics import median , stdev , variance , StatisticsError
5
6
from datetime import datetime
6
7
8
+ from homeassistant .const import STATE_UNAVAILABLE , STATE_UNKNOWN
7
9
from homeassistant .core import callback , Event
8
10
9
11
# from homeassistant.helpers import entity_registry as er
@@ -96,29 +98,20 @@ def _handle_update(self, event: Event):
96
98
input_state = self .hass .states .get (self .coordinator .input_sensor )
97
99
state_minmax_changed = False
98
100
try :
99
- if input_state is not None :
100
- if input_state .state is None :
101
- the_val = self .convert_to_float (input_state )
102
- else :
103
- the_val = self .convert_to_float (input_state .state )
101
+ if input_state not in (None , STATE_UNKNOWN , STATE_UNAVAILABLE ):
102
+ the_val = self .convert_to_float (input_state )
104
103
# apply the operation and update self._state
105
104
if self .coordinator .operation == CONF_SUM :
106
105
if self ._state is None :
107
106
self ._state = the_val
108
107
else :
109
108
self ._state = self ._state + the_val
110
109
elif self .coordinator .operation == CONF_MAX :
111
- if self ._state is None :
112
- self ._state = the_val
113
- state_minmax_changed = True
114
- elif the_val > self ._state :
110
+ if self ._state is None or the_val > self ._state :
115
111
self ._state = the_val
116
112
state_minmax_changed = True
117
113
elif self .coordinator .operation == CONF_MIN :
118
- if self ._state is None :
119
- self ._state = the_val
120
- state_minmax_changed = True
121
- elif the_val < self ._state :
114
+ if self ._state is None or the_val < self ._state :
122
115
self ._state = the_val
123
116
state_minmax_changed = True
124
117
elif self .coordinator .operation == CONF_MEAN :
@@ -141,6 +134,14 @@ def _handle_update(self, event: Event):
141
134
if state_minmax_changed :
142
135
self ._occurrence = datetime .now ()
143
136
self .hass .add_job (self .async_write_ha_state )
137
+ else :
138
+ # sensor is unknown at startup, state which comes after is considered as initial state
139
+ _LOGGER .debug (
140
+ "Initial state for {} is {}" .format (
141
+ self .coordinator .input_sensor , input_state
142
+ )
143
+ )
144
+ return
144
145
except ValueError :
145
146
_LOGGER .error (
146
147
"unable to convert to float. Please check the source sensor ({}) is available." .format (
0 commit comments