async def observe(self, to, callback=None): try: token = self.coap.token msg = OcfRequest( to=to, fr=self.link, op='retrieve', token=token, mid=self.coap.mid, obs=1 if callback is None else 0 ) coap_msg, remote = msg.encode_to_coap() await self.coap.send_multi_answer_request(coap_msg, remote, callback) if callback is None: del self.coap.answer[token] except TimeoutError as e: raise ExtTimeoutError(action='request', dump=dict(op='observe', to=to)) from None except ExtException as e: raise ExtException(parent=e, action='{}.request()'.format(self.__class__.__name__), dump=dict(op='observe', to=to)) from None except Exception as e: raise ExtException(parent=e, action='{}.request()'.format(self.__class__.__name__), dump=dict(op='observe', to=to)) from None
async def send_request(self, operation, to, data=None, **kwargs): try: msg = OcfRequest( to=to, fr=self.link, op=operation, cn=data, # uri_path=link['href'], # operation=operation, # data=data, # code=kwargs.pop('code', 1), # token=self.coap.token, # mid=self.coap.mid, **kwargs ) coap_msg, remote = msg.encode_to_coap() result = await self.coap.send_request(coap_msg, remote) return result except TimeoutError: raise ExtTimeoutError(action='request', dump=dict(op=operation, to=to, data=data, kwargs=kwargs)) from None except ExtException as err: raise ExtException(parent=err, action='{}.request()'.format(self.__class__.__name__), dump=dict(op=operation, to=to, data=data, kwargs=kwargs)) from None except Exception as err: raise ExtException(parent=err, action='{}.request()'.format(self.__class__.__name__), dump=dict(op=operation, to=to, data=data, kwargs=kwargs)) from None
def test_set_light_baseline(self): self.device = Device.init_from_config(self.config) data = dict(value=True, brightness=100) message = OcfRequest( **dict(operation='update', uri_path=['light'], data=data)) self.device.on_init() result = self.device.on_post_request(message) self.assertDictEqual(result, data)
def test_domx_encode_decode(self): data = b'X\x01\xb4\x85\xa0\x02\xacA\x8d\x04N*\xb3oic\x03sec\x04doxmKowned=FALSE"\'\x10\xe2\x06\xe3\x08\x00' coap_message = Message.decode(data, ('192.168.1.15', 61689)) ocf_message = OcfRequest.decode_from_coap(coap_message, False) coap_message2, address = ocf_message.encode_to_coap() data2 = coap_message2.encode() self.assertEqual(data, data2) pass
def test_get_light_brightness(self): self.device = Device.init_from_config( None, dict(handler=Device.__name__, data=self.config)) message = OcfRequest(**dict(operation='get', uri='/light', query={'rt': ['oic.r.light.brightness']})) self.device.on_get_request(message) # self.OcfDevice.run() pass
async def test_get_retrieve_switch(self): number = 1 value = False modbus_device = ModbusDevice.init_from_config(self.modbus_config, path=self.config_path) mobus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master'] = modbus_device.link self.device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(self.device) message = OcfRequest(op='retrieve', to=dict(href='/switch/{}'.format(number))) result = await self.device.on_post_request(message) self.assertEqual(result['value'], value)
async def discovery_unowned_devices(self, **kwargs): try: token = self.coap.token result = {} msg = OcfRequest( to=dict(href='/oic/res'), fr=self.link, op='retrieve', token=token, mid=self.coap.mid, multicast=True, **kwargs ) coap_msg, remote = msg.encode_to_coap() if self.coap.ipv6: await self.coap.send_multi_answer_request( coap_msg, (self.coap.coap_discovery_ipv6[0], self.coap.multicast_port), self.on_response_oic_res, result ) if self.coap.ipv4: await self.coap.send_multi_answer_request( coap_msg, (self.coap.coap_discovery_ipv4[0], self.coap.multicast_port), self.on_response_oic_res, result ) await asyncio.sleep(2) result = self.coap.answer[token]['result'] # del (self.coap.answer[token]) return result except ExtException as e: raise Exception(e) except Exception as e: raise ExtException(e)
async def test_retrieve_switch(self): number = 1 value = False modbus_device = ModbusDevice.init_from_config(self.modbus_config, path=self.config_path) mobus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master'] = modbus_device.link self.device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(self.device) tasks = [] for i in range(16): message = OcfRequest(op='retrieve', to=dict(href='/switch/{}'.format(number))) tasks.append(self.device.on_post_request(message)) res = await asyncio.gather(*tasks) pass
async def test_retrieve_switch(self): value = False modbus_device = ModbusDevice.init_from_file(path='./config/', di='2') modbus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master']['anchor'] = modbus_device.link[ 'anchor'] self.config['/oic/con']['master']['eps'] = modbus_device.link['eps'] self.device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(self.device) message = OcfRequest(op='retrieve', to=dict(href='/power')) result = await self.device.on_get_request(message) print(result.get('value')) self.assertEqual(result['value'], value) pass
async def test_update_switch(self): value = False modbus_device = ModbusDevice.init_from_config(self.modbus_config, path=self.config_path) modbus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master'] = modbus_device.link self.device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(self.device) message = OcfRequest(op='update', to=dict(href='/power'), cn=dict(value=value)) result = await self.device.on_post_request(message) self.assertEqual(result['value'], value) modbus_task.cancel() device_task.cancel() pass
def test_retrieve(self): sender = {'href': '/light', 'eps': [{'ep': 'coap://127.0.0.1:1111'}]} receiver = { 'href': '/oic/res', 'eps': [{ 'ep': 'coap://127.0.0.1:2222' }] } request = OcfRequest(to=receiver, fr=sender, op='retrieve', token=1, mif=2, **dict(query={'if': "oic.d"})) data = None answer = OcfResponse.generate_answer(data, request) pass
async def test_update_brightness(self): brightness = 0 modbus_device = ModbusDevice.init_from_config(self.modbus_config, path=self.config_path) modbus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master'] = modbus_device.link self.device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(self.device) message = OcfRequest(op='update', to=dict(href='/brightness'), cn=dict(brightness=brightness)) result = await self.device.on_post_request(message) self.assertEqual(result['brightness'], brightness) modbus_task.cancel() device_task.cancel() pass
async def test_maximum_load(self): modbus_device = ModbusDevice.init_from_file('SerialServerHF511', '2') modbus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master']['anchor'] = modbus_device.link['anchor'] self.config['/oic/con']['master']['eps'] = modbus_device.link['eps'] device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(device) task = [] count = 50 for i in range(50): message = OcfRequest(op='retrieve', to=dict(href='/switch/1')) task.append(device.on_get_request(message)) begin = datetime.now() result = await asyncio.gather(*task) end = datetime.now() print(end - begin) await wait_cancelled_device(device, device_task) await wait_cancelled_device(modbus_device, modbus_task)
async def test_retrieve_color(self): modbus_device = ModbusDevice.init_from_config(self.modbus_config, path=self.config_path) modbus_task = await wait_run_device(modbus_device) self.config['/oic/con']['master'] = modbus_device.link self.device = Device.init_from_config(self.config, path=self.config_path) device_task = await wait_run_device(self.device) message = OcfRequest(op='retrieve', to=dict(href='/color')) result = await self.device.on_get_request(message) print(result) # self.assertEqual(result['color'], value) modbus_task.cancel() device_task.cancel() await modbus_task await device_task pass
async def test_echo_post_message(self, **kwargs): device_task = await wait_run_device(self.device) # from aio_modbus_client.ModbusProtocolEcho import ModbusProtocolEcho pdu = '\x00\x02\x00\x01' # self.device.modbus = ModbusProtocolEcho({ # pdu: '\x01\x00\x01' # }) data = dict(slave=0x78, function=16, pdu=OcfMessageRequest.b64decode(pdu.encode()), answerSize=10, baudRate=9600, parity=0, stopBits=2, dataBits=8) message = OcfRequest( **dict(op='update', to=dict(href='/modbus_msg'), cn=data)) result = await self.device.on_post_request(message) self.assertEqual(result, '\x01\x00\x01') pass
async def test_echo_post_message_timeout_host(self, **kwargs): self.device.set_param('/oic/con', 'host', '192.168.168.168') device_task = await wait_run_device(self.device) # from aio_modbus_client.ModbusProtocolEcho import ModbusProtocolEcho pdu = '\x00\x02\x00\x01' # self.device.modbus = ModbusProtocolEcho({ # pdu: '\x01\x00\x01' # }) data = dict(slave=0x78, function=16, pdu=OcfMessageRequest.b64decode(pdu.encode()), answerSize=10, baudRate=9600, parity=0, stopBits=2, dataBits=8) message = OcfRequest( **dict(op='update', to=dict(href='/modbus_msg'), cn=data)) with self.assertRaises(ExtTimeoutError): await self.device.on_post_request(message)
async def notify(self, href, data): # send notify response to observer listening = self.get_param('/oic/con', 'listening') if not listening: return to = ResourceLink.init_from_link(self.link) to.href = href for elem in listening: if elem['href'] != href: continue try: self.log.debug('notify {0} {1}'.format(self.get_device_id(), href)) msg = OcfResponse.generate_answer( data, OcfRequest(to=to, fr=ResourceLink.init_from_link( dict(di=elem['di'], ep=elem['ep'])), op='retrieve', token=elem['token'], mid=self.coap.mid, obs=0)) await self.coap.send_answer(msg) except TimeoutError as e: raise Exception(9001, action='notify', dump=dict(op='observe', to=to)) from None except ExtException as e: raise ExtException(parent=e, action='{}.notify()'.format( self.__class__.__name__), dump=dict(op='observe', to=to)) from None except Exception as e: raise ExtException(parent=e, action='{}.notify()'.format( self.__class__.__name__), dump=dict(op='observe', to=to)) from None
async def test_local_discovery(self): msg = OcfRequest(**dict(uri_path=['oic', 'res'], operation='get')) res = self.device.on_get_request(msg) await asyncio.sleep(600) pass
def test_get_light1_baseline(self): self.device = Device.init_from_config( None, dict(handler=Device.__name__, data=self.config)) message = OcfRequest(**dict(operation='get', uri='/light')) result = self.device.on_get_request(message) pass