koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 1 | import Queue |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 2 | import logging |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 3 | import threading |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 4 | |
| 5 | from .deploy_sensors import (deploy_and_start_sensors, |
| 6 | stop_and_remove_sensors) |
| 7 | from .protocol import create_protocol, Timeout |
| 8 | |
| 9 | |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 10 | __all__ = ['Empty', 'recv_main', |
| 11 | 'deploy_and_start_sensors', |
| 12 | 'SensorConfig', |
| 13 | 'stop_and_remove_sensors', |
| 14 | 'start_listener_thread', |
| 15 | ] |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 16 | |
| 17 | |
| 18 | Empty = Queue.Empty |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 19 | logger = logging.getLogger("wally.sensors") |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 20 | |
| 21 | |
| 22 | class SensorConfig(object): |
Alyona Kiseleva | 7f6de4f | 2015-04-21 01:04:20 +0300 | [diff] [blame^] | 23 | def __init__(self, conn, url, sensors, source_id, |
| 24 | monitor_url=None): |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 25 | self.conn = conn |
| 26 | self.url = url |
| 27 | self.sensors = sensors |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 28 | self.source_id = source_id |
| 29 | self.monitor_url = monitor_url |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 30 | |
| 31 | |
| 32 | def recv_main(proto, data_q, cmd_q): |
| 33 | while True: |
| 34 | try: |
| 35 | data_q.put(proto.recv(0.1)) |
| 36 | except Timeout: |
| 37 | pass |
| 38 | |
| 39 | try: |
| 40 | val = cmd_q.get(False) |
| 41 | |
| 42 | if val is None: |
| 43 | return |
| 44 | |
| 45 | except Queue.Empty: |
| 46 | pass |
| 47 | |
| 48 | |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 49 | def start_listener_thread(uri): |
| 50 | data_q = Queue.Queue() |
| 51 | cmd_q = Queue.Queue() |
| 52 | logger.debug("Listening for sensor data on " + uri) |
| 53 | proto = create_protocol(uri, receiver=True) |
| 54 | th = threading.Thread(None, recv_main, None, (proto, data_q, cmd_q)) |
| 55 | th.daemon = True |
| 56 | th.start() |
koder aka kdanilov | cff7b2e | 2015-04-18 20:48:15 +0300 | [diff] [blame] | 57 | |
koder aka kdanilov | 168f609 | 2015-04-19 02:33:38 +0300 | [diff] [blame] | 58 | def stop_thread(): |
| 59 | cmd_q.put(None) |
| 60 | th.join() |
| 61 | |
| 62 | return data_q, stop_thread |