koder aka kdanilov | dda86d3 | 2015-03-16 11:20:04 +0200 | [diff] [blame] | 1 | import Queue |
| 2 | import threading |
| 3 | |
| 4 | from contextlib import contextmanager |
| 5 | |
| 6 | from deploy_sensors import (deploy_and_start_sensors, |
| 7 | stop_and_remove_sensors) |
| 8 | from protocol import create_protocol, Timeout |
| 9 | |
| 10 | |
| 11 | Empty = Queue.Empty |
| 12 | |
| 13 | |
| 14 | def recv_main(proto, data_q, cmd_q): |
| 15 | while True: |
| 16 | try: |
| 17 | data_q.put(proto.recv(0.1)) |
| 18 | except Timeout: |
| 19 | pass |
| 20 | try: |
| 21 | val = cmd_q.get(False) |
| 22 | |
| 23 | if val is None: |
| 24 | return |
| 25 | |
| 26 | except Queue.Empty: |
| 27 | pass |
| 28 | |
| 29 | |
| 30 | @contextmanager |
| 31 | def start_monitoring(uri, config): |
| 32 | deploy_and_start_sensors(uri, config) |
| 33 | try: |
| 34 | data_q = Queue.Queue() |
| 35 | cmd_q = Queue.Queue() |
| 36 | proto = create_protocol(uri, receiver=True) |
| 37 | th = threading.Thread(None, recv_main, None, (proto, data_q, cmd_q)) |
| 38 | th.daemon = True |
| 39 | th.start() |
| 40 | |
| 41 | try: |
| 42 | yield data_q |
| 43 | finally: |
| 44 | cmd_q.put(None) |
| 45 | th.join() |
| 46 | finally: |
| 47 | stop_and_remove_sensors(config) |