async def set_strategy(app, name: str, strategy: str): interest = make_command('strategy-choice', 'set', name=name, strategy=strategy) try: _, _, data = await app.express_interest(interest, lifetime=1000, can_be_prefix=True, must_be_fresh=True) except (InterestCanceled, InterestTimeout, InterestNack, ValidationFailure, NetworkError): logging.error(f'Command failed') return False ret = parse_response(data) if ret['status_code'] <= 399: return True return False
async def remove_route(app, name: str, face_id: int): interest = make_command('rib', 'unregister', name=name, face_id=face_id) try: _, _, data = await app.express_interest(interest, lifetime=1000, can_be_prefix=True, must_be_fresh=True) except (InterestCanceled, InterestTimeout, InterestNack, ValidationFailure, NetworkError): logging.error(f'Command failed') return False ret = parse_response(data) if ret['status_code'] <= 399: return True return False
async def issue_command_interest(self, cmd): try: logging.info('Issuing command %s', Name.to_str(cmd)) _, _, data = await self.app.express_interest(cmd, lifetime=1000, can_be_prefix=True, must_be_fresh=True) except (InterestCanceled, InterestTimeout, InterestNack, ValidationFailure, NetworkError): logging.error(f'Command failed') return None return parse_response(data)
async def face_event(self): last_seq = -1 name_prefix = Name.from_str('/localhost/nfd/faces/events') while True: if last_seq >= 0: name = name_prefix + [ Component.from_sequence_num(last_seq + 1) ] init = False else: name = name_prefix init = True logging.info("Face event notification stream %s", Name.to_str(name)) try: data_name, _, content = await self.app.express_interest( name, must_be_fresh=init, can_be_prefix=init, lifetime=60000) last_seq = Component.to_number(data_name[-1]) timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") if not content: print('ERROR: Face event is empty') elif content[0] == 0x65: msg = parse_response(content) print('Query failed with response', msg['status_code'], msg['status_text']) else: dic = self.face_event_to_dict(content) dic['seq'] = str(last_seq) dic['time'] = timestamp await self.emit('face event', dic) self.event_list.append(dic) except (InterestCanceled, NetworkError): break except InterestTimeout: last_seq = -1 except InterestNack as e: print(f'Face events nacked with reason={e.reason}') last_seq = -1 except ValidationFailure: print('Face events failed to validate') last_seq = -1 await asyncio.sleep(0.1)
async def register(self, name: NonStrictName, func: Optional[Route], validator: Optional[Validator] = None, need_raw_packet: bool = False, need_sig_ptrs: bool = False) -> bool: """ Register a route for a specific prefix dynamically. :param name: the Name prefix for this route. :type name: :any:`NonStrictName` :param func: the onInterest function for the specified route. If ``None``, the NDNApp will only send the register command to forwarder, without setting any callback function. :type func: Optional[Callable[[:any:`FormalName`, :any:`InterestParam`, Optional[:any:`BinaryStr`]], ``None``]] :param validator: the Validator used to validate coming Interests. :type validator: Optional[:any:`Validator`] :return: ``True`` if the registration succeeded. :param need_raw_packet: if True, pass the raw Interest packet to the callback as a keyword argument ``raw_packet``. :type need_raw_packet: bool :param need_sig_ptrs: if True, pass the Signature pointers to the callback as a keyword argument ``sig_ptrs``. :type need_sig_ptrs: bool :raises ValueError: the prefix is already registered. :raises NetworkError: the face to NFD is down now. """ name = Name.normalize(name) if func is not None: node = self._prefix_tree.setdefault(name, PrefixTreeNode()) if node.callback: raise ValueError( f'Duplicated registration: {Name.to_str(name)}') node.callback = func node.extra_param = { 'raw_packet': need_raw_packet, 'sig_ptrs': need_sig_ptrs } if validator: node.validator = validator # Fix the issue that NFD only allows one packet signed by a specific key for a timestamp number async with self._prefix_register_semaphore: try: _, _, reply = await self.express_interest(make_command( 'rib', 'register', name=name), lifetime=1000) ret = parse_response(reply) if ret['status_code'] != 200: logging.error( f'Registration for {Name.to_str(name)} failed: ' f'{ret["status_code"]} {bytes(ret["status_text"]).decode()}' ) return False else: logging.debug( f'Registration for {Name.to_str(name)} succeeded: ' f'{ret["status_code"]} {bytes(ret["status_text"]).decode()}' ) return True except (InterestNack, InterestTimeout, InterestCanceled, ValidationFailure) as e: logging.error( f'Registration for {Name.to_str(name)} failed: {e.__class__.__name__}' ) return False