def testI64(self): result = yield From(self.client.testI64(-34359738368)) self.assertEqual(result, -34359738368)
def go(): session = yield From(self.graph.connect()) with self.assertRaises(RuntimeError): stream = session.send("v = 1+1", processor="session")
def testVoid(self): result = yield From(self.client.testVoid()) self.assertEqual(result, None)
def go(): connection = yield From(self.graph.connect()) resp = connection.send("1 + 1") connection.close() with self.assertRaises(RuntimeError): msg = yield From(resp.read())
def go(): connection = yield From(self.graph.connect()) conn = connection.conn._conn self.assertIsNotNone(conn.protocol) self.assertIsInstance(conn, WebSocketClientConnection) conn.close()
def set_advertising(self, controller_id, enabled, uuids, name, company_id, advertising_data, scan_response, on_set, timeout): if isinstance(on_set, (tuple, list)): on_set_cb = on_set[0] on_set_params = on_set[1:] else: on_set_cb = on_set on_set_params = [] if uuids is not None: if not isinstance(uuids, (tuple, list)): uuids = [uuids] for i, uuid in enumerate(uuids): if isinstance(uuid, UUID): uuids[i] = uuid_to_string(uuid) elif isinstance(uuid, string_types): uuids[i] = switch_endianness_string(uuid) else: raise ValueError( "UUID must be either a uuid.UUID object or a string") @asyncio.coroutine def on_response_received(packet, future): self.logger.debug( "Set advertising response received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: data = packet.get_dict(['controller_id', 'state']) on_set_cb(True, data, None, *on_set_params) future.set_result(data) else: error = BaBLEException(packet, "Failed to set advertising") on_set_cb(False, None, error, *on_set_params) future.set_exception(error) future = asyncio.Future() request_packet = Packet.build(SetAdvertising, controller_id=controller_id, state=enabled, uuids=uuids, name=name, company_id=company_id, adv_manufacturer_data=advertising_data, scan_manufacturer_data=scan_response) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.send_packet(request_packet) self.logger.debug("Waiting for setting advertising response...") try: result = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(result) except asyncio.TimeoutError: self.remove_callback(request_packet.packet_uuid) raise RuntimeError("Set advertising timed out")
def con_fut(): session = yield From( pool.session('localhost', self.get_http_port())) with session as connection: if connection.closed(): yield From(connection.connect())
def echo_server(): yield From(asyncio.start_server(handle_connection, 'localhost', 8000))
def run_single(self): """ :return: """ conf = self.conf insert_queue = [] if not self.do_restore: if self.current_run == 0: # Only build arena on first run yield From(wait_for(self.build_arena())) # Set initial battery charge self.current_charge = self.conf.initial_charge self.last_charge_update = 0.0 self.births = 0 self.deaths = 0 # Generate a starting population trees, bboxes = yield From(self.generate_population(conf.initial_population_size)) insert_queue = zip(trees, bboxes, [None for _ in range(len(trees))]) # Simple loop timing mechanism timers = {k: Time() for k in ['reproduce', 'death', 'snapshot', 'log_fitness', 'rtf', 'insert_queue']} this = self def timer(name, t): """ :param t: :param name: :return: """ if this.last_time is not None and float(this.last_time - timers[name]) > t: timers[name] = this.last_time return True return False # Some variables real_time = time.time() rtf_interval = 10.0 sleep_time = 0.1 run_result = 'unknown' started = False while True: if insert_queue and (not started or timer('insert_queue', 1.0)): tree, bbox, parents = insert_queue.pop() res = yield From(self.birth(tree, bbox, parents)) if res: yield From(res) if not started: # Start the world yield From(wait_for(self.pause(False))) started = True # Perform operations only if there are no items # in the insert queue, makes snapshotting easier. if insert_queue: # Space out robot inserts with one simulation second # to allow them to drop in case they are too close. # Sleep for a very small interval every time until # all inserts are done yield From(trollius.sleep(0.01)) continue if timer('snapshot', 100.0): # Snapshot the world every 100 simulation seconds yield From(self.create_snapshot()) yield From(wait_for(self.pause(False))) if timer('death', 3.0): # Kill off robots over their age every 5 simulation seconds futs = yield From(self.kill_old_robots()) if futs: yield From(multi_future(futs)) if timer('reproduce', 3.0): # Attempt a reproduction every 3 simulation seconds potential_parents = self.select_parents() if potential_parents: ra = random.choice(potential_parents) rb = self.select_optimal_mate(ra) result = yield From(self.attempt_mate(ra, rb)) if result: child, bbox = result insert_queue.append((child, bbox, (ra, rb))) if timer('log_fitness', 2.0): # Log overall fitness every 2 simulation seconds self.log_fitness() self.log_summary() if timer('rtf', rtf_interval): # Print RTF to screen every so often nw = time.time() diff = nw - real_time real_time = nw print("RTF: %f" % (rtf_interval / diff)) # Stop conditions num_bots = len(self.robots) age = float(self.age()) if num_bots <= conf.extinction_cutoff: print("%d or fewer robots left in population - extinction." % conf.extinction_cutoff) run_result = 'extinction' break elif age > conf.stability_cutoff: print("World older than %f seconds, stable." % conf.stability_cutoff) run_result = 'stable' break yield From(trollius.sleep(sleep_time)) # Delete all robots and reset the world, just in case a new run # will be started. self.write_result(run_result) yield From(wait_for(self.delete_all_robots())) yield From(wait_for(self.reset())) yield From(wait_for(self.pause(True))) yield From(trollius.sleep(0.5))
def testOneway(self, seconds): t = time.time() yield From(asyncio.sleep(seconds)) yield From(self.onewaysQueue.put((t, time.time(), seconds)))
def handle_connection(reader, writer): while True: data = yield From(reader.read(8192)) if not data: break writer.write(data)
def testString(self, s): yield From(asyncio.sleep(0)) raise Return(s)
def testOneway(self): yield From(self.client.testOneway(2)) start, end, seconds = yield From(self.handler.onewaysQueue.get()) self.assertAlmostEqual(seconds, (end - start), places=1)
def testDouble(self): result = yield From(self.client.testDouble(-5.235098235)) self.assertAlmostEqual(result, -5.235098235)
def disconnect(self, controller_id, connection_handle, on_disconnected, timeout): disconnected_event_uuid = PacketUuid( payload_type=Payload.DeviceDisconnected, controller_id=controller_id, connection_handle=connection_handle) if isinstance(on_disconnected, (tuple, list)): on_disconnected_cb = on_disconnected[0] on_disconnected_params = on_disconnected[1:] else: on_disconnected_cb = on_disconnected on_disconnected_params = [] @asyncio.coroutine def on_device_disconnected(packet, future): self.logger.debug( "Device disconnected event received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: data = packet.get_dict( ['controller_id', 'connection_handle', 'reason', 'code']) self.remove_callback(PacketUuid( controller_id=controller_id, connection_handle=connection_handle), match_connection_only=True) on_disconnected_cb(True, data, None, *on_disconnected_params) future.set_result(data) else: error = BaBLEException(packet, "Failed to disconnect") on_disconnected_cb(False, None, error, *on_disconnected_params) future.set_exception(error) @asyncio.coroutine def on_response_received(packet, future): self.logger.debug("Disconnect response received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code != StatusCode.Success: self.remove_callback(disconnected_event_uuid) error = BaBLEException(packet, "Failed to disconnect") on_disconnected_cb(False, None, error, *on_disconnected_params) future.set_exception(error) future = asyncio.Future() request_packet = Packet.build(Disconnect, controller_id=controller_id, connection_handle=connection_handle) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.register_callback(disconnected_event_uuid, callback=on_device_disconnected, params={'future': future}, replace=True) self.send_packet(request_packet) self.logger.debug("Disconnecting...") try: result = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(result) except asyncio.TimeoutError: self.remove_callback(disconnected_event_uuid) on_disconnected_cb(False, None, "Disconnection timed out", *on_disconnected_params) raise RuntimeError("Disconnection timed out")
def getaddrinfo(*args, **kw): non_local['host'] = args[0] yield From(None)
def set_notification(self, controller_id, enabled, connection_handle, characteristic, on_notification_set, on_notification_received, timeout): if not isinstance(characteristic, Characteristic): raise ValueError( "Characteristic parameter must be a 'bable_interface.models.Characteristic' object" ) notification_event_uuid = PacketUuid( payload_type=Payload.NotificationReceived, controller_id=controller_id, connection_handle=connection_handle, attribute_handle=characteristic.value_handle) if isinstance(on_notification_set, (tuple, list)): on_notification_set_cb = on_notification_set[0] on_notification_set_params = on_notification_set[1:] else: on_notification_set_cb = on_notification_set on_notification_set_params = [] if isinstance(on_notification_received, (tuple, list)): on_notification_received_cb = on_notification_received[0] on_notification_received_params = on_notification_received[1:] else: on_notification_received_cb = on_notification_received on_notification_received_params = [] @asyncio.coroutine def on_notification_event(packet): result = packet.get_dict([ 'controller_id', 'connection_handle', 'attribute_handle', ('value', bytes) ]) on_notification_received_cb(True, result, None, *on_notification_received_params) try: read_result = yield From( self.read(controller_id, connection_handle, characteristic.config_handle, none_cb, timeout)) except (RuntimeError, BaBLEException) as err: on_notification_set_cb( False, None, "Error while reading notification configuration (exception={})". format(err), *on_notification_set_params) raise RuntimeError( "Error while reading notification config (exception={})".format( err)) current_state = struct.unpack('H', read_result['value'])[0] if enabled: self.register_callback(notification_event_uuid, callback=on_notification_event) new_state = current_state | 1 else: self.remove_callback(notification_event_uuid) new_state = current_state & 0xFFFE if new_state == current_state: on_notification_set_cb(True, read_result, None, *on_notification_set_params) returned_value = asyncio.Return(read_result) returned_value.raised = True # To avoid the warning emitted in Return destructor ("... used without raise") raise returned_value value = to_bytes(new_state, 2, byteorder='little') try: result = yield From( self.write(controller_id, connection_handle, characteristic.config_handle, value, none_cb, timeout)) on_notification_set_cb(True, result, None, *on_notification_set_params) returned_value = asyncio.Return(result) returned_value.raised = True # To avoid the warning emitted in Return destructor ("... used without raise") raise returned_value except (RuntimeError, BaBLEException) as err: if enabled: self.remove_callback(notification_event_uuid) on_notification_set_cb( False, None, "Error while writing notification configuration (exception={})". format(err), *on_notification_set_params) raise RuntimeError( "Error while writing notification config (exception={})".format( err))
def stop_loop_coro(loop): yield From(None) loop.stop()
def test_connect_timeout(self): connection = Connection(('10.0.0.0', 1), connect_timeout=2) with self.assertRaises(NetworkTimedOut): yield From(connection.connect())
def zero_error_coro(): yield From(asyncio.sleep(0.01, loop=self.loop)) 1 / 0
def go_to(self, pos, throw_timeout=False): """ go in a straight line to pos """ goal_pos = np.array(pos) # read the odometer start_reading = self.odometer.val start_pos = start_reading.pos # find the parallel and perpendicular directions dir = goal_pos - start_pos dir = dir / np.linalg.norm(dir) left_dir = np.array([[0, 1], [-1, 0]]).dot(dir) if np.isnan(dir).any(): return # choose the angle that results in the least turn from the current angle target_angle = self._fix_angle(np.arctan2(dir[1], dir[0])) # clear the state in the pid controllers a_pid = self._angle_pid d_pid = self._dist_pid a_pid.reset() d_pid.reset() # d_pid is given the distance to go, since it's not 1D d_pid.setpoint = 0 end_time = time.time() + 1.5 * self._distance_time( np.linalg.norm(goal_pos - start_pos)) + 1 try: while True: # promote sensor data to vectors sensor = self.odometer.val curr_pos = sensor.pos facing = sensor.dir curr_vel = sensor.vel # find error perpendicular to and along line perp_err = (curr_pos - goal_pos).dot(left_dir) perp_err_dt = curr_vel.dot(left_dir) dist_left = (curr_pos - goal_pos).dot(dir) dist_left_dt = curr_vel.dot(dir) # choose throttle based on forward error, and scale based on direction throttle = d_pid.iterate(dist_left, dval=dist_left_dt) * dir.dot(facing) # choose target angle based on transverse error # TODO: full PID here angle_corr = 0.1 * perp_err a_pid.setpoint = target_angle + np.clip( angle_corr, np.radians(-30), np.radians(+30)) # choose steer based on target angle steer = a_pid.iterate(sensor.theta, dval=sensor.omega) # control the motors self.go(throttle=np.clip(throttle, -0.2, 0.2), steer=np.clip(steer, -0.4, 0.4)) yield From(asyncio.sleep(0.05)) # ignore transverse distance when terminating, since it's hard to get right if d_pid.at_goal(err_t=0.25, derr_t=0.5): break if time.time() > end_time: if throw_timeout: raise asyncio.TimeoutError else: warnings.warn( 'Timed out during RegulatedDrive.drive_to') return finally: self.stop()
def getaddrinfo(*args, **kw): yield From(None)
def go(): c1 = yield From(pool.acquire()) yield From(pool.release(c1)) c2 = yield From(pool.acquire()) self.assertEqual(c1, c2)
def getaddrinfo(*args, **kw): yield From(None) raise Return([(2, 1, 6, '', ('107.6.106.82', 80))])
def go(): result = yield From(execute("1 + 1")) self.assertIsInstance(result, Stream) resp = yield From(result.read()) self.assertEqual(resp.data[0], 2)
def start_scan(self, controller_id, active_scan, on_device_found, on_scan_started, timeout): if isinstance(on_device_found, (tuple, list)): on_device_found_cb = on_device_found[0] on_device_found_params = on_device_found[1:] else: on_device_found_cb = on_device_found on_device_found_params = [] if isinstance(on_scan_started, (tuple, list)): on_scan_started_cb = on_scan_started[0] on_scan_started_params = on_scan_started[1:] else: on_scan_started_cb = on_scan_started on_scan_started_params = [] @asyncio.coroutine def on_device_found_event(packet): result = packet.get_dict([ 'controller_id', 'type', ('address', lambda value: value.decode()), ('address_type', lambda value: 'public' if value == 0 else 'random'), 'rssi', ('uuid', lambda value: string_to_uuid(value, input_byteorder='little')), 'company_id', ('device_name', lambda value: value.decode()), ('manufacturer_data', bytes) ]) on_device_found_cb(True, result, None, *on_device_found_params) @asyncio.coroutine def on_response_received(packet, future): self.logger.debug("Start scan response received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: on_scan_started_cb(True, packet.get_dict(['controller_id']), None, *on_scan_started_params) future.set_result(True) else: self.remove_callback( PacketUuid(payload_type=Payload.DeviceFound, controller_id=controller_id)) error = BaBLEException(packet, "Failed to start scan") on_scan_started_cb(False, None, error, *on_scan_started_params) future.set_exception(error) future = asyncio.Future() request_packet = Packet.build(StartScan, controller_id=controller_id, active_scan=active_scan) self.register_callback(PacketUuid(payload_type=Payload.DeviceFound, controller_id=controller_id), callback=on_device_found_event) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.send_packet(request_packet) self.logger.debug("Waiting for scan to start...") try: result = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(result) except asyncio.TimeoutError: self.remove_callback([ request_packet.packet_uuid, PacketUuid(payload_type=Payload.DeviceFound, controller_id=controller_id) ]) on_scan_started_cb(False, None, "Start scan timed out", *on_scan_started_params) raise RuntimeError("Start scan timed out")
def go(): with self.assertRaises(RuntimeError): connection = yield From(graph.connect())
def connect(self, controller_id, address, address_type, connection_interval, on_connected_with_info, on_disconnected, timeout): if not isinstance(connection_interval, (tuple, list)) \ or len(connection_interval) != 2 \ or not all(isinstance(v, (int, float)) for v in connection_interval): raise ValueError( "connection_interval must be a 2-number tuple or list ([min, max])" ) connected_event_uuid = PacketUuid(payload_type=Payload.DeviceConnected, controller_id=controller_id, address=address) if isinstance(on_connected_with_info, (tuple, list)): on_connected_cb = on_connected_with_info[0] on_connected_params = on_connected_with_info[1:] else: on_connected_cb = on_connected_with_info on_connected_params = [] if isinstance(on_disconnected, (tuple, list)): on_disconnected_cb = on_disconnected[0] on_disconnected_params = on_disconnected[1:] else: on_disconnected_cb = on_disconnected on_disconnected_params = [] @asyncio.coroutine def on_unexpected_disconnection(packet): self.logger.info( "Unexpected disconnection event received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) data = packet.get_dict( ['controller_id', 'connection_handle', 'reason', 'code']) self.remove_callback(PacketUuid( controller_id=controller_id, connection_handle=data['connection_handle']), match_connection_only=True) on_disconnected_cb(True, data, None, *on_disconnected_params) @asyncio.coroutine def on_connected(packet, future): self.logger.debug( "Device connected event received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code == StatusCode.Success: device = packet.get_dict([ 'controller_id', 'connection_handle', 'address', ('address_type', lambda value: 'public' if value == 0 else 'random') ]) self.register_callback(PacketUuid( payload_type=Payload.DeviceDisconnected, controller_id=controller_id, connection_handle=device['connection_handle']), callback=on_unexpected_disconnection) on_connected_cb(True, device, None, *on_connected_params) future.set_result(device) else: error = BaBLEException(packet, "Failed to connect", address=address) on_connected_cb(False, None, error, *on_connected_params) future.set_exception(error) return @asyncio.coroutine def on_response_received(packet, future): self.logger.debug("Connect response received with status={}".format( packet.status)) self.remove_callback(packet.packet_uuid) if packet.status_code != StatusCode.Success: self.remove_callback(connected_event_uuid) error = BaBLEException(packet, "Failed to connect", address=address) on_connected_cb(False, None, error, *on_connected_params) future.set_exception(error) future = asyncio.Future() request_packet = Packet.build( Connect, controller_id=controller_id, address=address, address_type=0 if address_type == 'public' else 1, connection_interval_min=connection_interval[0], connection_interval_max=connection_interval[1]) self.register_callback(request_packet.packet_uuid, callback=on_response_received, params={'future': future}) self.register_callback(connected_event_uuid, callback=on_connected, params={'future': future}) self.send_packet(request_packet) self.logger.debug("Connecting...") try: result = yield From(asyncio.wait_for(future, timeout=timeout)) raise asyncio.Return(result) except asyncio.TimeoutError: self.remove_callback(connected_event_uuid) on_connected_cb(False, None, "Connection timed out", *on_connected_params) raise RuntimeError("Connection timed out")
def testString(self): result = yield From(self.client.testString('Python')) self.assertEqual(result, 'Python')
def testI32(self): result = yield From(self.client.testI32(-1)) self.assertEqual(result, -1) result = yield From(self.client.testI32(0)) self.assertEqual(result, 0)