class Receiver(): def __init__(self): info('receiver', 'init') self.queue = Queue() self.mqtt = MQTT(os.environ['KIT_CHANNEL'], client_id='receiver-mqtt', queue=self.queue) self.running = False # Start the signer. def start(self, pipe): info('receiver', 'start') self.mqtt.connect(os.environ['KIT_MQTT_HOST'], int(os.environ['KIT_MQTT_PORT']), os.environ['KIT_DEVICE_ID'], os.environ['KIT_DEVICE_KEY']) while not self.mqtt.connected: info('receiver', 'waiting for connection') time.sleep(1) info('receiver', 'connected') self.pipe = pipe self.running = True while self.running: # Check the queue for a received message. msg = self.queue.get() # If for this device then pass to controller. if msg.is_valid() and msg.for_device(): info('receiver', 'queue: ' + str(msg)) self.pipe.send(msg) # Stop the signer. def stop(self): info('receiver', 'stop') self.running = False try: self.mqtt.disconnect() #self.pipe.close() except Exception as ex: error('receiver', 'stop error: ' + str(ex))
class Alarm(object): def __init__(self, name, device, passcode, mqtt_host, speed=115200, **kwargs): log.debug(kwargs) self.name = name self.passcode = passcode self.port = serial.serial_for_url(device, baudrate=speed, timeout=0) self.broker = mqtt_host self.dcs1500state = 'unknown' self.status = 'unknown' self.lastStatus = 'unknown' self.mqtt = MQTT(broker=self.broker, name=self.name, menu=self.command) def start(self): self.thread = Thread(name="alarm_monitor", target=self.__monitor) self.event = threading.Event() self.thread.start() self.__monitor() def stop(self): self.mqtt.loop_stop() self.mqtt.disconnect() self.event.set() def __readSerial(self): buffer_string = '' while not self.event.is_set(): self.event.wait(timeout=1.0) buffer_string = buffer_string + self.port.read( self.port.inWaiting()).decode(('utf-8')) if '\n' in buffer_string: timestamp = datetime.today().isoformat() lines = buffer_string.split('\n') last_received = lines[-2] # Last full line. buffer_string = lines[-1] # First part of next line. self.dcs1500state = last_received self.alarmTime = timestamp break def __get_status(self): """ Monitors serial port until there is a full update from the arduino.Monitors """ self.__readSerial() if self.dcs1500state[21:26] == 'Armed': self.status = 'ARMED' if self.dcs1500state[39] == 'A': self.status = 'TRIPPED' elif self.dcs1500state[1:3] == 'RA': self.status = 'ARMING' else: self.status = 'DISARMED' pass def __monitor(self): log.debug("started Monitor") while not self.event.is_set(): self.event.wait(timeout=1.0) self.__get_status() if self.status != self.lastStatus: self.sendEventNotification("alarm is {}, previously {}".format( self.status, self.lastStatus.lower())) log.info( "alarm status change to: {} previous status: {}".format( self.status, self.lastStatus)) self.lastStatus = self.status def __on(self): self.port.write(self.passcode.encode()) def __off(self): self.port.write(self.passcode.encode()) def get_status(self): return self.status def sendEventNotification(self, msg): message = { "recipientId": "admins", "sender": self.name, "message": msg } try: log.debug("publish {}/event msg: {}".format( self.name, str(message))) self.mqtt.publish(self.name + "/event", str(message)) except requests.exceptions.ConnectionError as e: log.warning("Connection Error: {}".format(e)) pass def command(self, cmd, respond): command = cmd.lower() if self.status == 'unknown': self.get_status() respond('connot process command at this time') elif command == 'off': if self.status != 'DISARMED': self.__off() respond('alarm turning off') else: respond('alarm already off') elif command == 'on': if self.status == 'DISARMED': self.__on() respond('alarm turning on') else: respond('alarm aLready on') elif command == 'hi': respond(self.get_status()) else: respond('invalid command')
def handle_stop_signals(signum, frame): global running print("Received signal %d." % signum) running = False running = True rx_buffer = deque(maxlen = 10) with Radio(FREQ_433MHZ, conf.node_id, conf.network_id, isHighPower=True, power=conf.radio_power, interruptPin=conf.interrupt_pin, resetPin=conf.reset_pin, spiBus=conf.spi_bus, spiDevice=conf.spi_device, autoAcknowledge=False) as radio: signal.signal(signal.SIGINT, handle_stop_signals) signal.signal(signal.SIGTERM, handle_stop_signals) print("rfm69-mqtt-gateway starting..") print("Used configuration:") pprint(conf.__dict__) mqtt = MQTT(conf.mqtt_broker, conf.tx_subs_topic) while running: forward_from_radio_to_mqtt(radio, mqtt) forward_from_mqtt_to_radio(mqtt, radio) time.sleep(0.005) print("Disconnecting MQTT.") mqtt.disconnect() print("Exiting.")