def test_transport_write_from_queue(self, device, loop): payload = b'\x01\x01' unit = AsyncioTransport(device, loop, callback=mock.Mock()) unit.write(payload) device.write.assert_called_once_with(payload)
def test_transport_doesnt_write_with_emtpy_queue(self, device, loop): unit = AsyncioTransport(device, loop, callback=mock.Mock()) # Call write and verify it was added to the queue unit.write_queue = [] unit._writer() self.assertFalse(device.write.called)
def test_transport_read_empty_patcket(self, device, loop): device.read.return_value = b'\x00' unit = AsyncioTransport(device, loop, callback=mock.Mock()) with mock.patch.object(unit, 'log') as unit_log: unit.read() unit_log.warning.assert_called_once_with( "READ : Empty packet (Got \\x00)")
def test_transport_read_nothing(self, device, loop): device.read.return_value = b'' unit = AsyncioTransport(device, loop, callback=mock.Mock()) with mock.patch.object(unit, 'log') as unit_log: unit.read() unit_log.warning.assert_called_once_with( "READ : Nothing received")
def test_transport_setup(self, unit_write, device, loop): unit = AsyncioTransport(device, loop, callback=mock.Mock()) unit.setup() loop.remove_writer.assert_called_with(device.fd) device.write.assert_called_once(RESET_PACKET) loop.call_later.assert_any_call(mock.ANY, super(AsyncioTransport, unit).write, STATUS_PACKET) unit_write.assert_called_once_with(MODE_PACKET)
def test_transport_write_from_queue(self, device, loop): payload = b'\x01\x01' unit = AsyncioTransport(device, loop, callback=mock.Mock()) # Call write and verify it was added to the queue unit.write(payload) self.assertIn(payload, unit.write_queue) unit._writer() device.write.assert_called_once_with(payload)
def test_transport_read(self, device, loop): unit = AsyncioTransport(device, loop, callback=mock.Mock()) call_map = { (): b'\x02', (2, ): b'\x01\x01' } device.read = lambda *x: call_map[x] self.assertEquals(unit.read(), b'\x02\x01\x01')
def test_transport_read(self, device, loop, callback): unit = AsyncioTransport(device, loop, callback=mock.Mock()) def fake_read(*x): data = {(): b'\x02', (2, ): b'\x01\x01'} return data[x] device.read.side_effect = fake_read expected_result = b'\x02\x01\x01' self.assertEquals(unit.read(), expected_result) callback.assert_called_once_with(expected_result)
def test_transport_read(self, device, loop, callback): unit = AsyncioTransport(device, loop, callback=mock.Mock()) def fake_read(*x): data = { (): b'\x02', (2, ): b'\x01\x01' } return data[x] device.read.side_effect = fake_read expected_result = b'\x02\x01\x01' self.assertEquals(unit.read(), expected_result) callback.assert_called_once_with(expected_result)
def test_transport_do_callback(self, device, loop, get_parser): cb = mock.Mock() get_parser.return_value = (cb, "test") unit = AsyncioTransport(device, loop, callback=mock.Mock()) def fake_read(*x): data = {(): b'\x02', (2, ): b'\x01\x01'} return data[x] device.read.side_effect = fake_read expected_result = b'\x02\x01\x01' self.assertEquals(unit.read(), expected_result) loop.call_soon_threadsafe.assert_called_once_with( AsyncioTransport._do_async_callback, cb, "test")
def create_transport(self, device, event_loop): return AsyncioTransport(device, event_loop, callbacks={ protocol.TempHumidity: self.handle_temp_humidity, '*': self.default_callback })
class AsyncioTransportTestCase(TestCase): """AsyncioTransport test case.""" @mock.patch('rfxcom.transport.asyncio.AsyncioTransport._setup') @mock.patch('asyncio.async') @mock.patch('asyncio.AbstractEventLoop') @mock.patch('serial.Serial') def test_transport_setup(self, device, loop, async, _setup): AsyncioTransport(device, loop, callback=mock.Mock()) async .assert_called_once_with(_setup())
def test_transport__setup(self, device, loop, sleep, mode, status, reset): unit = AsyncioTransport(device, loop, callback=mock.Mock()) # reset mocks which have been 'called' by the constructor device.reset_mock() loop.reset_mock() # run: exaust the coroutine generator execute_coroutine(unit._setup()) loop.add_reader.assert_called_with(device.fd, unit.read) reset.assert_called_once_with() sleep.assert_has_calls((mock.ANY, mock.ANY)) slept_time = sleep.call_args[0][0] # by spec it needs to be between 0.5ms and 9000ms self.assertGreater(slept_time, 0.05) self.assertLess(slept_time, 9) mode.assert_called_once_with() status.assert_called_once_with()
def run_event_loop(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.rfxcom = AsyncioTransport(dev, loop, callback=self.handler) #time.sleep(1) #self.rfxcom.write(b'\r\x00\x00\x01\x03S\x00\xff\x0e/\x00\x00\x00\x00') loop.run_forever()
def test_transport_do_callback(self, device, loop, get_parser): cb = mock.Mock() get_parser.return_value = (cb, "test") unit = AsyncioTransport(device, loop, callback=mock.Mock()) def fake_read(*x): data = { (): b'\x02', (2, ): b'\x01\x01' } return data[x] device.read.side_effect = fake_read expected_result = b'\x02\x01\x01' self.assertEquals(unit.read(), expected_result) loop.call_soon_threadsafe.assert_called_once_with( AsyncioTransport._do_async_callback, cb, "test")
def collect(dev_name, callbacks): loop = get_event_loop() try: AsyncioTransport(dev_name, loop, callbacks=callbacks) loop.run_forever() finally: loop.close()
def collect(dev_name=None, callbacks=None): if callbacks is None: callbacks = dict(load_handlers(config.PACKET_HANDLERS)) loop = get_event_loop() try: logger.info("Starting collection from:", dev_name) AsyncioTransport(dev_name, loop, callbacks=callbacks) loop.run_forever() finally: loop.close()
def main(): dictConfig(LOGGING) loop = get_event_loop() parser = ArgumentParser() parser.add_argument('device') args = parser.parse_args() try: rfxcom = AsyncioTransport(args.device, loop, callbacks={ protocol.Status: printer, protocol.Elec: printer, protocol.TempHumidity: printer, '*': printer, }) loop.call_later(2, partial(write, rfxcom)) loop.run_forever() finally: loop.close()
def test_transport_constructor(self, device, loop): unit = AsyncioTransport(device, loop, callback=mock.Mock()) loop.add_writer.assert_called_once_with(device.fd, unit.setup)
class RFXCom(CommsDevice): def __init__(self, name, dev): super(RFXCom, self).__init__(name) def run_event_loop(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.rfxcom = AsyncioTransport(dev, loop, callback=self.handler) #time.sleep(1) #self.rfxcom.write(b'\r\x00\x00\x01\x03S\x00\xff\x0e/\x00\x00\x00\x00') loop.run_forever() threading.Thread(target=run_event_loop).start() def handler(self, packet): print(packet) if isinstance(packet, TempHumidity): for device in devices: if isinstance(device, TempSensor): if device.id == packet.data['id']: device.detected(packet.data['temperature']) if isinstance(device, HumiditySensor): if device.id == packet.data['id']: device.detected(packet.data['humidity_status']) # Each packet will have a dictionary which contains parsed data. print(packet.data) command = binascii.hexlify(packet.raw) for device in devices: try: # TODO: need to properly decode the protocol here, this is just lazy :-) if hasattr(device, "id") and device.id in command: if isinstance(device, MotionSensor): device.detected() if isinstance(device, TwilightSensor): device.detected(command[21] == 102) except TypeError: pass def switch(self, device, to): if device.status == to: return dim='00' logging.info("%s: switching '%s' to '%s'" % (self.name, device.name, to)) if to: if isinstance(device, SwitchDevice): level = "01" if isinstance(device, Dimmer): level = "02" dim = hex(device.level)[2:4] else: level = "00" self.send_command(device, level, dim) def send_command(self, device, level, dim): command = '0b11000a{id}0a{level}{dim}00'.format(id=device.id, level=level, dim=dim) if not settings.DISARM: for i in range(1): logging.info("%s: sending command '%s'" % (self.name, command)) self.rfxcom.write(binascii.unhexlify(command)) def undim(self, device): device.level += 2 if device.level > 255: device.level = 255 if device.status: dim = hex(device.level)[2:4] self.send_command(device, "02", dim) def dim(self, device): device.level -= 2 if device.level < 240: device.level = 240 print(device.level) if device.status: dim = hex(device.level)[2:4] self.send_command(device, "02", dim)
class RFXCom(CommsDevice): def __init__(self, name, dev): super(RFXCom, self).__init__(name) def run_event_loop(): loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) self.rfxcom = AsyncioTransport(dev, loop, callback=self.handler) #time.sleep(1) #self.rfxcom.write(b'\r\x00\x00\x01\x03S\x00\xff\x0e/\x00\x00\x00\x00') loop.run_forever() threading.Thread(target=run_event_loop).start() def handler(self, packet): print(packet) if isinstance(packet, TempHumidity): for device in devices: if isinstance(device, TempSensor): if device.id == packet.data['id']: device.detected(packet.data['temperature']) if isinstance(device, HumiditySensor): if device.id == packet.data['id']: device.detected(packet.data['humidity_status']) # Each packet will have a dictionary which contains parsed data. print(packet.data) command = binascii.hexlify(packet.raw) for device in devices: try: # TODO: need to properly decode the protocol here, this is just lazy :-) if hasattr(device, "id") and device.id in command: if isinstance(device, MotionSensor): device.detected() if isinstance(device, TwilightSensor): device.detected(command[21] == 102) except TypeError: pass def switch(self, device, to): if device.status == to: return dim = '00' logging.info("%s: switching '%s' to '%s'" % (self.name, device.name, to)) if to: if isinstance(device, SwitchDevice): level = "01" if isinstance(device, Dimmer): level = "02" dim = hex(device.level)[2:4] else: level = "00" self.send_command(device, level, dim) def send_command(self, device, level, dim): command = '0b11000a{id}0a{level}{dim}00'.format(id=device.id, level=level, dim=dim) if not settings.DISARM: for i in range(1): logging.info("%s: sending command '%s'" % (self.name, command)) self.rfxcom.write(binascii.unhexlify(command)) def undim(self, device): device.level += 2 if device.level > 255: device.level = 255 if device.status: dim = hex(device.level)[2:4] self.send_command(device, "02", dim) def dim(self, device): device.level -= 2 if device.level < 240: device.level = 240 print(device.level) if device.status: dim = hex(device.level)[2:4] self.send_command(device, "02", dim)