Completed
Push — master ( 57d64c...05be55 )
by Tomaz
02:22
created

AstralSunSensor._update_sun_info()   A

Complexity

Conditions 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 1
c 2
b 1
f 0
dl 0
loc 4
rs 10
1
from st2reactor.sensor.base import PollingSensor
2
import st2common.util.date as date
3
from astral import Location
4
5
6
__all__ = [
7
    'AstralSunSensor'
8
]
9
10
11
class AstralSunSensor(PollingSensor):
12
    def __init__(self, sensor_service, config=None, poll_interval=None):
13
        super(AstralSunSensor, self).__init__(sensor_service=sensor_service,
14
                                              config=config,
15
                                              poll_interval=poll_interval)
16
        self._logger = self._sensor_service.get_logger(__name__)
17
18
    def setup(self):
19
        self._latitude = self._config['latitude']
20
        self._longitude = self._config['longitude']
21
        self._update_sun_info()
22
        self._update_counter = 0
23
24
    def poll(self):
25
        if self._update_counter > 60:
26
            self._update_sun_info()
27
            self._update_counter = 0
28
29
        checks = ['dawn', 'sunrise', 'sunset', 'dusk']
30
31
        currenttime = date.get_datetime_utc_now()
32
33
        self._logger.debug("Checking current time %s for sun information" %
34
                           str(currenttime))
35
36
        for key in checks:
37
            if self.is_within_minute(self.sun[key], currenttime):
38
                trigger = 'astral.' + key
39
                self.sensor_service.dispatch(trigger=trigger, payload={})
40
41
        self._update_counter += 1
42
43
    def cleanup(self):
44
        pass
45
46
    def add_trigger(self, trigger):
47
        pass
48
49
    def update_trigger(self, trigger):
50
        pass
51
52
    def remove_trigger(self, trigger):
53
        pass
54
55
    def _update_sun_info(self):
56
        location = Location(('name', 'region', float(self._latitude),
57
                            float(self._longitude), 'GMT+0', 0))
58
        self.sun = location.sun()
59
60
    def is_within_minute(self, time1, time2):
61
        timediff = time1 - time2
62
        diff = abs(timediff.total_seconds() // 60)
63
        if diff < 1:
64
            return True
65
        return False
66