Ver código fonte

Initial Leyk implementation

master
Dirk Alders 2 anos atrás
pai
commit
82521d16c1
14 arquivos alterados com 726 adições e 0 exclusões
  1. 2
    0
      .gitignore
  2. 12
    0
      .gitmodules
  3. 17
    0
      .project
  4. 8
    0
      .pydevproject
  5. 41
    0
      __install__.py
  6. 22
    0
      examples/config.py
  7. 1
    0
      geo
  8. 23
    0
      leyk.py
  9. 4
    0
      leyk.sh
  10. 590
    0
      piface_function.py
  11. 1
    0
      report
  12. 3
    0
      requirements.txt
  13. 1
    0
      state_machine
  14. 1
    0
      task

+ 2
- 0
.gitignore Ver arquivo

@@ -1,3 +1,5 @@
1
+config.py
2
+
1 3
 # ---> Python
2 4
 # Byte-compiled / optimized / DLL files
3 5
 __pycache__/

+ 12
- 0
.gitmodules Ver arquivo

@@ -0,0 +1,12 @@
1
+[submodule "report"]
2
+	path = report
3
+	url = https://git.mount-mockery.de/pylib/report.git
4
+[submodule "geo"]
5
+	path = geo
6
+	url = https://git.mount-mockery.de/pylib/geo.git
7
+[submodule "state_machine"]
8
+	path = state_machine
9
+	url = https://git.mount-mockery.de/pylib/state_machine.git
10
+[submodule "task"]
11
+	path = task
12
+	url = https://git.mount-mockery.de/pylib/task.git

+ 17
- 0
.project Ver arquivo

@@ -0,0 +1,17 @@
1
+<?xml version="1.0" encoding="UTF-8"?>
2
+<projectDescription>
3
+	<name>leyk</name>
4
+	<comment></comment>
5
+	<projects>
6
+	</projects>
7
+	<buildSpec>
8
+		<buildCommand>
9
+			<name>org.python.pydev.PyDevBuilder</name>
10
+			<arguments>
11
+			</arguments>
12
+		</buildCommand>
13
+	</buildSpec>
14
+	<natures>
15
+		<nature>org.python.pydev.pythonNature</nature>
16
+	</natures>
17
+</projectDescription>

+ 8
- 0
.pydevproject Ver arquivo

@@ -0,0 +1,8 @@
1
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
2
+<?eclipse-pydev version="1.0"?><pydev_project>
3
+    <pydev_pathproperty name="org.python.pydev.PROJECT_SOURCE_PATH">
4
+        <path>/${PROJECT_DIR_NAME}</path>
5
+    </pydev_pathproperty>
6
+    <pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python interpreter</pydev_property>
7
+    <pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
8
+</pydev_project>

+ 41
- 0
__install__.py Ver arquivo

@@ -0,0 +1,41 @@
1
+#!/bin/python
2
+#
3
+import os
4
+import sys
5
+
6
+SERVICE_FILE = """
7
+[Unit]
8
+Description=Leyk Service
9
+After=network-online.target
10
+Wants=network-online.target
11
+[Service]
12
+User=%(UID)d
13
+Group=%(GID)d
14
+ExecStart=%(MY_PATH)s/leyk.sh
15
+Type=simple
16
+[Install]
17
+WantedBy=default.target
18
+"""
19
+
20
+
21
+def help():
22
+    print("Usage: prog <UID> <GID> <TARGET_PATH>")
23
+
24
+if __name__ == "__main__":
25
+    if len(sys.argv) == 4:
26
+        try:
27
+            uid = int(sys.argv[1])
28
+            gid = int(sys.argv[2])
29
+        except ValueError:
30
+            help()
31
+        else:
32
+            if os.path.isdir(sys.argv[3]):
33
+                with open(os.path.join(sys.argv[3], 'leyk.service'), "w") as fh:
34
+                    fh.write(SERVICE_FILE % {
35
+                        "MY_PATH": os.path.dirname(os.path.abspath(__file__)),
36
+                        "UID": uid,
37
+                        "GID": gid})
38
+            else:
39
+                help()
40
+    else:
41
+        help()

+ 22
- 0
examples/config.py Ver arquivo

@@ -0,0 +1,22 @@
1
+#!/usr/bin/env python
2
+# -*- coding: UTF-8 -*-
3
+import os
4
+import report
5
+
6
+MQTT_USER = "user"
7
+MQTT_PASS = "password"
8
+MQTT_SERVER = "host"
9
+MQTT_TOPIC = "leyk"
10
+
11
+#
12
+# Logging
13
+#
14
+__BASEPATH__ = os.path.abspath(os.path.dirname(__file__))
15
+APP_NAME = "leyk"
16
+LOGTARGET = 'stdout'   # possible choices are: 'logfile' or 'stdout'
17
+LOGLVL = 'DEBUG'
18
+
19
+LOGHOST = 'cutelog'
20
+LOGPORT = 19996
21
+
22
+formatter = report.SHORT_FMT

+ 1
- 0
geo

@@ -0,0 +1 @@
1
+Subproject commit 11166bb27ad2335f7812fcb88c788397f5106751

+ 23
- 0
leyk.py Ver arquivo

@@ -0,0 +1,23 @@
1
+import config
2
+import logging
3
+import report
4
+import socket
5
+import subprocess
6
+import time
7
+import piface_function
8
+
9
+try:
10
+    from config import APP_NAME as ROOT_LOGGER_NAME
11
+except ImportError:
12
+    ROOT_LOGGER_NAME = 'root'
13
+logger = logging.getLogger(ROOT_LOGGER_NAME).getChild('main')
14
+
15
+
16
+if __name__ == '__main__': 
17
+    report.appLoggingConfigure(config.__BASEPATH__, config.LOGTARGET, ((config.APP_NAME, config.LOGLVL), ), fmt=config.formatter, host=config.LOGHOST, port=config.LOGPORT)
18
+    #    
19
+    l = piface_function.leyk()
20
+
21
+    while True:
22
+        time.sleep(30)
23
+        #l.publish_states()

+ 4
- 0
leyk.sh Ver arquivo

@@ -0,0 +1,4 @@
1
+#!/bin/sh
2
+#
3
+BASEPATH=`dirname $0`
4
+$BASEPATH/venv/bin/python $BASEPATH/leyk.py

+ 590
- 0
piface_function.py Ver arquivo

@@ -0,0 +1,590 @@
1
+#!/usr/bin/env python
2
+# -*- coding: UTF-8 -*-
3
+
4
+try:
5
+    import pifacedigitalio
6
+except ImportError:
7
+    pifacedigitalio = None
8
+import config
9
+import geo
10
+import json
11
+import logging
12
+import paho.mqtt.client as mqtt
13
+import state_machine
14
+import task
15
+import random
16
+import socket
17
+import time
18
+
19
+try:
20
+    from config import APP_NAME as ROOT_LOGGER_NAME
21
+except ImportError:
22
+    ROOT_LOGGER_NAME = 'root'
23
+logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
24
+
25
+geo_position = geo.gps.coordinate(lat=49.976596, lon=9.1481443)
26
+
27
+
28
+class pi_face(object):
29
+    LOG_PREFIX = 'PiFace:'
30
+
31
+    PF_OUT_NAMES = ['Output 0',     # 0
32
+                    'Output 1',     # 1
33
+                    'Output 2',     # 2
34
+                    'Ploenlein',    # 3
35
+                    'Bakery',       # 4
36
+                    'Mill',         # 5
37
+                    'Reese House',  # 6
38
+                    'Bake House']   # 7
39
+
40
+    def __init__(self, client):
41
+        self.__client__ = client
42
+
43
+        if pifacedigitalio is not None:
44
+            pifacedigitalio.init()
45
+            pi = pifacedigitalio.PiFaceDigital()
46
+            self.__pf_outputs__ = pi.output_pins
47
+        self.__pf_output_states__ = 8 * [False]
48
+        #
49
+        self._reload = 0
50
+        self._task_10ms = task.periodic(0.01 - 0.007, self.task_10ms)
51
+        #
52
+        for i in range(0, 8):
53
+            self.set_output(i, self.__pf_output_states__[i])
54
+
55
+    def set_output(self, index, state, tries=5):
56
+        tries = min(max(1, tries), 5)
57
+        try_txt = ['1st', '2nd', '3rd', '4th', '5th']
58
+        state = state is True
59
+        if pifacedigitalio is not None:
60
+            cnt = 0
61
+            while (cnt < tries) and (self.__pf_outputs__[index].value != state):
62
+                self.__pf_outputs__[index].value = 1 * state
63
+                time.sleep(0.1)
64
+                cnt += 1
65
+            if self.__pf_outputs__[index].value != state:
66
+                logger.warning('%s Control of output[%d] (%s) after %s try not successfull!', self.LOG_PREFIX, index, self.PF_OUT_NAMES[index], try_txt[cnt - 1])
67
+            else:
68
+                logger.info('%s Set output "%s" to %s.', self.LOG_PREFIX, self.PF_OUT_NAMES[index], repr(state))
69
+            self.__pf_output_states__[index] = self.__pf_outputs__[index].value == 1
70
+        else:
71
+            logger.info('%s Set virtual output "%s" to %s.', self.LOG_PREFIX, self.PF_OUT_NAMES[index], repr(state))
72
+            self.__pf_output_states__[index] = state
73
+
74
+    def get_output(self, index):
75
+        return self.__pf_output_states__[index]
76
+
77
+    def get_ploenlein(self):
78
+        return self.get_output(3)
79
+
80
+    def set_bakery(self, state):
81
+        self.set_output(4, state)
82
+
83
+    def get_bakery(self):
84
+        return self.get_output(4)
85
+
86
+    def set_mill(self, state):
87
+        self.set_output(5, state)
88
+
89
+    def get_mill(self):
90
+        return self.get_output(5)
91
+
92
+    def set_ploenlein(self, state):
93
+        self.set_output(3, state)
94
+
95
+    def set_reese_house(self, state):
96
+        self.set_output(6, state)
97
+
98
+    def get_reese_house(self):
99
+        return self.get_output(6)
100
+
101
+    def set_bake_house(self, state):
102
+        if state is True:
103
+            self.set_output(7, state)
104
+            self._task_10ms.run()
105
+        elif state is False:
106
+            self._task_10ms.stop()
107
+            self.join()
108
+            time.sleep(0.1)
109
+            self.set_output(7, state)
110
+
111
+    def get_bake_house(self):
112
+        return not self._task_10ms._stopped
113
+
114
+    def task_10ms(self, task_inst):
115
+        if self._reload <= 0:
116
+            if pifacedigitalio is not None:
117
+                self.__pf_outputs__[7].turn_on()
118
+            self._reload = random.choice(2 * [0] + 20 * [1] + 1 * [2])
119
+        else:
120
+            if pifacedigitalio is not None:
121
+                self.__pf_outputs__[7].turn_off()
122
+            self._reload -= 1
123
+
124
+    def join(self):
125
+        self._task_10ms.join()
126
+
127
+    def stop(self):
128
+        self._task_10ms.stop()
129
+        self._task_10ms.join()
130
+        for i in range(0, 8):
131
+            self.set_output(i, False)
132
+        pifacedigitalio.deinit()
133
+
134
+    def __del__(self):
135
+        self.stop()
136
+
137
+
138
+class state_machine_mode(state_machine.state_machine):
139
+    LOG_PREFIX = 'LeykMode:'
140
+
141
+    STATE_AUTOMATIC = 'automatic'
142
+    STATE_MANUAL = 'manual'
143
+
144
+    CONDITION_EXTERNAL_TRIGGER = 'external_trigger'
145
+
146
+    TRANSITIONS = {
147
+        STATE_AUTOMATIC: (
148
+            (CONDITION_EXTERNAL_TRIGGER, 1, STATE_MANUAL),
149
+        ),
150
+        STATE_MANUAL: (
151
+            (CONDITION_EXTERNAL_TRIGGER, 1, STATE_AUTOMATIC),
152
+        ),
153
+    }
154
+
155
+    def __init__(self, **kwargs):
156
+        state_machine.state_machine.__init__(self, self.STATE_AUTOMATIC, logging.INFO)
157
+        self.__reset_triggers__()
158
+
159
+    def __reset_triggers__(self):
160
+        self.__to_automatic__ = False
161
+        self.__to_manual__ = False
162
+
163
+    def external_trigger(self):
164
+        rv = False
165
+        if self.this_state() == self.STATE_AUTOMATIC:
166
+            rv = self.__to_manual__
167
+        elif self.this_state() == self.STATE_MANUAL:
168
+            rv = self.__to_automatic__
169
+        self.__reset_triggers__()
170
+        return rv
171
+        
172
+    def trigger_to_maual(self):
173
+        if self.this_state() == self.STATE_AUTOMATIC:
174
+            self.__to_manual__ = True
175
+            return True
176
+        return False
177
+
178
+    def trigger_to_automatic(self):
179
+        if self.this_state() == self.STATE_MANUAL:
180
+            self.__to_automatic__ = True
181
+            return True
182
+        return False
183
+
184
+
185
+class state_machine_day_state(state_machine.state_machine):
186
+    LOG_PREFIX = 'LeykState:'
187
+
188
+    STATE_IDLE = 'idle'
189
+    STATE_WAKE = 'wake'
190
+    STATE_SUNRISE = 'sunrise'
191
+    STATE_SUNSET = 'sunset'
192
+    STATE_SLEEP = 'sleep'
193
+
194
+    CONDITION_WAKE = 'condition_wake'
195
+    CONDITION_SUNRISE = 'condition_sunrise'
196
+    CONDITION_SUNSET = 'condition_sunset'
197
+    CONDITION_SLEEP = 'condition_sleep'
198
+    CONDITION_IDLE = 'condition_idle'
199
+
200
+    TRANSITIONS = {
201
+        STATE_IDLE: (
202
+            (CONDITION_WAKE, 1, STATE_WAKE),
203
+            (CONDITION_SUNRISE, 1, STATE_SUNRISE),
204
+            (CONDITION_SUNSET, 1, STATE_SUNSET),
205
+            (CONDITION_SLEEP, 1, STATE_SLEEP),
206
+        ),
207
+        STATE_WAKE: (
208
+            (CONDITION_SUNRISE, 1, STATE_SUNRISE),
209
+            (CONDITION_IDLE, 1, STATE_IDLE),
210
+        ),
211
+        STATE_SUNRISE: (
212
+            (CONDITION_SLEEP, 1, STATE_SLEEP),
213
+            (CONDITION_SUNSET, 1, STATE_SUNSET),
214
+            (CONDITION_IDLE, 1, STATE_IDLE),
215
+        ),
216
+        STATE_SUNSET: (
217
+            (CONDITION_SLEEP, 1, STATE_SLEEP),
218
+            (CONDITION_IDLE, 1, STATE_IDLE),
219
+        ),
220
+        STATE_SLEEP: (
221
+            (CONDITION_WAKE, 1, STATE_WAKE),
222
+            (CONDITION_SUNRISE, 1, STATE_SUNRISE),
223
+            (CONDITION_IDLE, 1, STATE_IDLE),
224
+        ),
225
+    }
226
+
227
+    def __init__(self, **kwargs):
228
+        state_machine.state_machine.__init__(self, self.STATE_IDLE, logging.INFO, **kwargs)
229
+
230
+    def __current_state_calc__(self):
231
+        def wake_time():
232
+            tm = time.localtime()
233
+            tm = list(tm)
234
+            tm[3] = 6   # tm_hour
235
+            tm[4] = 0   # tm_min
236
+            tm[5] = 0   # tm_sec=0
237
+            return time.mktime(time.struct_time(tm))
238
+    
239
+        def sunrise_time():
240
+            return time.mktime(geo.sun.sunrise(geo_position)) + 30 * 60
241
+    
242
+        def sunset_time():
243
+            return time.mktime(geo.sun.sunset(geo_position)) - 30 * 60
244
+    
245
+        def sleep_time():
246
+            tm = time.localtime()
247
+            tm = list(tm)
248
+            tm[3] = 21  # tm_hour
249
+            tm[4] = 15  # tm_min
250
+            tm[5] = 0   # tm_sec=0
251
+            return time.mktime(time.struct_time(tm))
252
+
253
+        now = time.mktime(time.localtime())
254
+        if now > sleep_time():
255
+            return self.STATE_SLEEP
256
+        elif now > sunset_time():
257
+            return self.STATE_SUNSET
258
+        elif now > sunrise_time():
259
+            return self.STATE_SUNRISE
260
+        elif now > wake_time():
261
+            return self.STATE_WAKE
262
+        else:
263
+            return self.STATE_IDLE
264
+
265
+    def condition_wake(self):
266
+        if self.condition_idle():
267
+            return False
268
+        return self.__current_state_calc__() == self.STATE_WAKE
269
+
270
+    def condition_sunrise(self):
271
+        if self.condition_idle():
272
+            return False
273
+        return self.__current_state_calc__() == self.STATE_SUNRISE
274
+
275
+    def condition_sunset(self):
276
+        if self.condition_idle():
277
+            return False
278
+        return self.__current_state_calc__() == self.STATE_SUNSET
279
+
280
+    def condition_sleep(self):
281
+        if self.condition_idle():
282
+            return False
283
+        return self.__current_state_calc__() == self.STATE_SLEEP
284
+
285
+    def condition_idle(self):
286
+        return not self.sm_mode.this_state_is(self.sm_mode.STATE_AUTOMATIC)
287
+
288
+    def report_sunset_sunrise(self):
289
+        state_machine.logger.debug('Sunrise: %s - Sunset: %s;', time.strftime("%H:%M", geo.sun.sunrise(geo_position)), time.strftime("%H:%M", geo.sun.sunset(geo_position))
290
+)
291
+
292
+
293
+class leyk(object):
294
+    LOG_PREFIX = 'Leyk:'
295
+
296
+    TOPIC_BAKE_HOUSE = config.MQTT_TOPIC + '/status/Bake House'
297
+    TOPIC_BAKERY = config.MQTT_TOPIC + '/status/Bakery'
298
+    TOPIC_MILL = config.MQTT_TOPIC + '/status/Mill'
299
+    TOPIC_MODE = config.MQTT_TOPIC + '/status/mode'
300
+    TOPIC_MODE_BOOL = config.MQTT_TOPIC + '/status/mode_bool'
301
+    TOPIC_PLOENLEIN = config.MQTT_TOPIC + '/status/Ploenlein'
302
+    TOPIC_REESE_HOUSE = config.MQTT_TOPIC + '/status/Reese House'
303
+    TOPIC_STATE = config.MQTT_TOPIC + '/status/state'
304
+
305
+
306
+    RX_TOPIC_BAKE_HOUSE = config.MQTT_TOPIC + '/set/Bake House'
307
+    RX_TOPIC_BAKERY = config.MQTT_TOPIC + '/set/Bakery'
308
+    RX_TOPIC_MILL = config.MQTT_TOPIC + '/set/Mill'
309
+    RX_TOPIC_MODE = config.MQTT_TOPIC + '/set/mode'
310
+    RX_TOPIC_PLOENLEIN = config.MQTT_TOPIC + '/set/Ploenlein'
311
+    RX_TOPIC_REESE_HOUSE = config.MQTT_TOPIC + '/set/Reese House'
312
+    
313
+    RX_TOPICS = [
314
+        RX_TOPIC_BAKE_HOUSE,
315
+        RX_TOPIC_BAKERY,
316
+        RX_TOPIC_MILL,
317
+        RX_TOPIC_MODE,
318
+        RX_TOPIC_PLOENLEIN,
319
+        RX_TOPIC_REESE_HOUSE
320
+    ]
321
+
322
+    def __init__(self):
323
+        self.__client__ = mqtt.Client("mqtt_leyk")                              # create client object
324
+        self.__client__.on_message = self.__receive__                           # attach function to callback
325
+        self.__client__.username_pw_set(config.MQTT_USER, config.MQTT_PASS)     # login with credentials
326
+        try:
327
+            self.__client__.connect(config.MQTT_SERVER, 1883)                       # establish connection
328
+            self.__client__.loop_start()                                            # start the loop
329
+            self.__topics__ = []
330
+            for topic in self.RX_TOPICS:
331
+                self.__client__.subscribe(topic)          # subscibe a topic
332
+        except (socket.timeout, OSError) as e:
333
+            logger.warning("Error while setting up mqtt instance and listener")
334
+
335
+        self.TOPIC_DATA = {
336
+            self.TOPIC_BAKE_HOUSE: self.get_bake_house,
337
+            self.TOPIC_BAKERY: self.get_bakery,
338
+            self.TOPIC_MILL: self.get_mill,
339
+            self.TOPIC_MODE: self.get_mode,
340
+            self.TOPIC_MODE_BOOL: self.get_mode_bool,
341
+            self.TOPIC_PLOENLEIN: self.get_ploenlein,
342
+            self.TOPIC_REESE_HOUSE: self.get_reese_house,
343
+            self.TOPIC_STATE: self.get_state
344
+        }
345
+
346
+        self.sm_mode = state_machine_mode()
347
+        self.sm_day_state = state_machine_day_state(sm_mode=self.sm_mode)
348
+        self.__pf__ = pi_face(self.__client__)
349
+        self._queue = task.threaded_queue()
350
+        self._queue.run()
351
+        self._task_1s = task.periodic(1, self.task_1s)
352
+        self._task_1s.run()
353
+        self.sm_mode.register_state_change_callback(self.sm_mode.STATE_MANUAL, None, self._queue.clean_queue)
354
+        self.sm_mode.register_state_change_callback(None, None, self.publish, self.TOPIC_MODE)
355
+        self.sm_mode.register_state_change_callback(None, None, self.publish, self.TOPIC_MODE_BOOL)
356
+        self.sm_day_state.register_state_change_callback(None, None, self.clean_queue)
357
+        self.sm_day_state.register_state_change_callback(None, None, self.publish, self.TOPIC_STATE)
358
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_SLEEP, None, self.sm_day_state.report_sunset_sunrise)
359
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_SLEEP, None, self.fill_sleep_queue)
360
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_SUNRISE, None, self.sm_day_state.report_sunset_sunrise)
361
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_SUNRISE, None, self.fill_sunrise_queue)
362
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_SUNSET, None, self.sm_day_state.report_sunset_sunrise)
363
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_SUNSET, None, self.fill_sunset_queue)
364
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_WAKE, None, self.sm_day_state.report_sunset_sunrise)
365
+        self.sm_day_state.register_state_change_callback(self.sm_day_state.STATE_WAKE, None, self.fill_wake_queue)
366
+
367
+        self.publish(self.TOPIC_MODE)
368
+        self.publish(self.TOPIC_MODE_BOOL)
369
+        self.publish(self.TOPIC_STATE)
370
+
371
+    def __receive__(self, client, userdata, message):
372
+        logger.info("Received message %s with %s", message.topic, str(message.payload))
373
+        if message.topic == self.RX_TOPIC_MODE:
374
+            self.set_mode(self.sm_mode.STATE_AUTOMATIC if message.payload == b'true' else self.sm_mode.STATE_MANUAL)
375
+        elif message.topic == self.RX_TOPIC_BAKE_HOUSE:
376
+            self.set_bake_house(message.payload == b'true')
377
+        elif message.topic == self.RX_TOPIC_BAKERY:
378
+            self.set_bakery(message.payload == b'true')
379
+        elif message.topic == self.RX_TOPIC_MILL:
380
+            self.set_mill(message.payload == b'true')
381
+        elif message.topic == self.RX_TOPIC_PLOENLEIN:
382
+            self.set_ploenlein(message.payload == b'true')
383
+        elif message.topic == self.RX_TOPIC_REESE_HOUSE:
384
+            self.set_reese_house(message.payload == b'true')
385
+        else:
386
+            logger.warning("Ignoring unknown mqtt topic %s", message.topic)
387
+
388
+    def publish_states(self):
389
+        for name in self.TOPIC_DATA:
390
+            self.publish(name)
391
+
392
+    def publish(self, topic):
393
+        logger.info("Sending Leyk status information to mqtt %s = %s", topic, json.dumps(self.TOPIC_DATA[topic]()))
394
+        try:
395
+            self.__client__.publish(topic, json.dumps(self.TOPIC_DATA[topic]()))
396
+        except (socket.timeout, OSError) as e:
397
+            logger.warning("Error while sending state information information")
398
+
399
+    def set_mode(self, mode):
400
+        if mode == self.sm_mode.STATE_AUTOMATIC:
401
+            rv = self.sm_mode.trigger_to_automatic()
402
+        elif mode == self.sm_mode.STATE_MANUAL:
403
+            rv = self.sm_mode.trigger_to_maual()
404
+        else:
405
+            rv = False
406
+        return rv
407
+
408
+    def get_mode(self):
409
+        return self.sm_mode.this_state()
410
+
411
+    def get_mode_bool(self):
412
+        return self.get_mode() == self.sm_mode.STATE_AUTOMATIC
413
+
414
+    def get_state(self):
415
+        return self.sm_day_state.this_state()
416
+
417
+    def __queue_wrapper__(self, queue_inst, function, *args, **kwargs):
418
+        function(*args, **kwargs)
419
+
420
+    def set_ploenlein(self, state, force=False):
421
+        if force or self.sm_mode.this_state_is(self.sm_mode.STATE_MANUAL):
422
+            self.__pf__.set_ploenlein(state)
423
+            self.publish(self.TOPIC_PLOENLEIN)
424
+            return True
425
+        else:
426
+            return False
427
+
428
+    def get_ploenlein(self):
429
+        return self.__pf__.get_ploenlein()
430
+
431
+    def set_bakery(self, state, force=False):
432
+        if force or self.sm_mode.this_state_is(self.sm_mode.STATE_MANUAL):
433
+            self.__pf__.set_bakery(state)
434
+            self.publish(self.TOPIC_BAKERY)
435
+            return True
436
+        else:
437
+            return False
438
+
439
+    def get_bakery(self):
440
+        return self.__pf__.get_bakery()
441
+
442
+    def set_bake_house(self, state, force=False):
443
+        if force or self.sm_mode.this_state_is(self.sm_mode.STATE_MANUAL):
444
+            self.__pf__.set_bake_house(state)
445
+            self.publish(self.TOPIC_BAKE_HOUSE)
446
+            return True
447
+        else:
448
+            return False
449
+
450
+    def get_bake_house(self):
451
+        return self.__pf__.get_bake_house()
452
+
453
+    def set_mill(self, state, force=False):
454
+        if force or self.sm_mode.this_state_is(self.sm_mode.STATE_MANUAL):
455
+            self.__pf__.set_mill(state)
456
+            self.publish(self.TOPIC_MILL)
457
+            return True
458
+        else:
459
+            return False
460
+
461
+    def get_mill(self):
462
+        return self.__pf__.get_mill()
463
+
464
+    def set_reese_house(self, state, force=False):
465
+        if force or self.sm_mode.this_state_is(self.sm_mode.STATE_MANUAL):
466
+            self.__pf__.set_reese_house(state)
467
+            self.publish(self.TOPIC_REESE_HOUSE)
468
+            return True
469
+        else:
470
+            return False
471
+
472
+    def get_reese_house(self):
473
+        return self.__pf__.get_reese_house()
474
+
475
+    def wake_time(self):
476
+        tm = time.localtime()
477
+        tm = list(tm)
478
+        tm[3] = 6   # tm_hour
479
+        tm[4] = 0   # tm_min
480
+        tm[5] = 0   # tm_sec=0
481
+        return time.mktime(time.struct_time(tm))
482
+
483
+    def sunrise_time(self):
484
+        return time.mktime(geo.sun.sunrise(geo_position)) + 30 * 60
485
+
486
+    def sunset_time(self):
487
+        return time.mktime(geo.sun.sunset(geo_position)) - 30 * 60
488
+
489
+    def sleep_time(self):
490
+        tm = time.localtime()
491
+        tm = list(tm)
492
+        tm[3] = 21  # tm_hour
493
+        tm[4] = 15  # tm_min
494
+        tm[5] = 0   # tm_sec=0
495
+        return time.mktime(time.struct_time(tm))
496
+
497
+    def identify_current_state(self):
498
+        now = time.mktime(time.localtime())
499
+        if now > self.sleep_time():
500
+            return self.ST_SLEEP
501
+        elif now > self.sunset_time():
502
+            return self.ST_SUNSET
503
+        elif now > self.sunrise_time():
504
+            return self.ST_SUNRISE
505
+        elif now > self.wake_time():
506
+            return self.ST_WAKE
507
+        else:
508
+            return self.ST_SLEEP
509
+
510
+    def wait(self, queue_inst, delay):
511
+        if delay > 0:
512
+            logger.debug('%s Wait for %d seconds initiated. %d elements left in queue.', self.LOG_PREFIX, delay, queue_inst.qsize())
513
+            cnt = 0
514
+            while cnt < delay * 5:
515
+                if queue_inst.qsize() == 0:
516
+                    logger.debug('%s Quit wait for %d seconds. %d elements left in queue.', self.LOG_PREFIX, delay, queue_inst.qsize())
517
+                    break
518
+                time.sleep(0.2)
519
+                cnt += 1
520
+
521
+    def clean_queue(self):
522
+        if self._queue.qsize() > 0:
523
+            logger.info('Cleaning up remaining %d elements from queue', self._queue.qsize())
524
+            self._queue.clean_queue()
525
+
526
+    def fill_wake_queue(self):
527
+        no_delay = self.sm_day_state.previous_state_was(self.sm_day_state.STATE_IDLE)
528
+        # WAKE
529
+        self._queue.enqueue(1, self.__queue_wrapper__, self.set_bakery, True, True)
530
+        self._queue.enqueue(2, self.wait, 0 if no_delay else 5 * 60)
531
+        self._queue.enqueue(3, self.__queue_wrapper__, self.set_bake_house, True, True)
532
+        self._queue.enqueue(4, self.wait, 0 if no_delay else 10 * 60)
533
+        self._queue.enqueue(5, self.__queue_wrapper__, self.set_reese_house, True, True)
534
+        self._queue.enqueue(6, self.wait, 0 if no_delay else 7 * 60)
535
+        self._queue.enqueue(7, self.__queue_wrapper__, self.set_ploenlein, True, True)
536
+        self._queue.enqueue(8, self.wait, 0 if no_delay else 8 * 60)
537
+        self._queue.enqueue(9, self.__queue_wrapper__, self.set_mill, True, True)
538
+
539
+    def fill_sunrise_queue(self):
540
+        no_delay = self.sm_day_state.previous_state_was(self.sm_day_state.STATE_IDLE)
541
+        # SUNRISE
542
+        self._queue.enqueue(1, self.__queue_wrapper__, self.set_bake_house, True, True)
543
+        self._queue.enqueue(2, self.__queue_wrapper__, self.set_ploenlein, False, True)
544
+        self._queue.enqueue(3, self.wait, 0 if no_delay else 5 * 60)
545
+        self._queue.enqueue(4, self.__queue_wrapper__, self.set_mill, False, True)
546
+        self._queue.enqueue(5, self.wait, 0 if no_delay else 8 * 60)
547
+        self._queue.enqueue(6, self.__queue_wrapper__, self.set_bakery, False, True)
548
+        self._queue.enqueue(7, self.wait, 0 if no_delay else 12 * 60)
549
+        self._queue.enqueue(8, self.__queue_wrapper__, self.set_reese_house, False, True)
550
+
551
+    def fill_sunset_queue(self):
552
+        no_delay = self.sm_day_state.previous_state_was(self.sm_day_state.STATE_IDLE)
553
+        # SUNSET
554
+        self._queue.enqueue(1, self.__queue_wrapper__, self.set_bake_house, True, True)
555
+        self._queue.enqueue(2, self.__queue_wrapper__, self.set_bakery, True, True)
556
+        self._queue.enqueue(3, self.wait, 0 if no_delay else 10 * 60)
557
+        self._queue.enqueue(4, self.__queue_wrapper__, self.set_reese_house, True, True)
558
+        self._queue.enqueue(5, self.wait, 0 if no_delay else 8 * 60)
559
+        self._queue.enqueue(6, self.__queue_wrapper__, self.set_mill, True, True)
560
+        self._queue.enqueue(7, self.wait, 0 if no_delay else 7 * 60)
561
+        self._queue.enqueue(8, self.__queue_wrapper__, self.set_ploenlein, True, True)
562
+
563
+    def fill_sleep_queue(self):
564
+        no_delay = self.sm_day_state.previous_state_was(self.sm_day_state.STATE_IDLE)
565
+        # SLEEP
566
+        self._queue.enqueue(1, self.__queue_wrapper__, self.set_bake_house, False, True)
567
+        self._queue.enqueue(2, self.wait, 0 if no_delay else 5 * 60)
568
+        self._queue.enqueue(3, self.__queue_wrapper__, self.set_bakery, False, True)
569
+        self._queue.enqueue(4, self.wait, 0 if no_delay else 9 * 60)
570
+        self._queue.enqueue(5, self.__queue_wrapper__, self.set_ploenlein, False, True)
571
+        self._queue.enqueue(6, self.wait, 0 if no_delay else 9 * 60)
572
+        self._queue.enqueue(7, self.__queue_wrapper__, self.set_mill, False, True)
573
+        self._queue.enqueue(8, self.wait, 0 if no_delay else 6 * 60)
574
+        self._queue.enqueue(9, self.__queue_wrapper__, self.set_reese_house, False, True)
575
+
576
+    def task_1s(self, task_inst):
577
+        self.sm_mode.work()
578
+        self.sm_day_state.work()
579
+
580
+    def join(self):
581
+        self._task_1s.join()
582
+        self._queue.join()
583
+
584
+    def stop(self):
585
+        self._task_1s.stop()
586
+        self._queue.stop()
587
+
588
+    def __del__(self):
589
+        self.__client__.loop_stop()                                              # stop the loop
590
+        self.stop()

+ 1
- 0
report

@@ -0,0 +1 @@
1
+Subproject commit 21bac82e0c459ebf6d34783c9249526a657a6bbd

+ 3
- 0
requirements.txt Ver arquivo

@@ -0,0 +1,3 @@
1
+pifacecommon
2
+pifacedigitalio
3
+paho-mqtt

+ 1
- 0
state_machine

@@ -0,0 +1 @@
1
+Subproject commit c47c20e0d69cdefe498c38e459ec8f4accb642bd

+ 1
- 0
task

@@ -0,0 +1 @@
1
+Subproject commit 7583bb5f3bd2420c901374ba95b678af6ce88433

Carregando…
Cancelar
Salvar