def simple_hw(): simple_file = """{{ "device": {{ "iotile_id": "{0}", "trace": [ [0.001, "hello "], [0.001, "goodbye "] ] }} }} """ for i in [1, 3, 4, 6]: fname = "dev" + str(i) + ".json" with open(fname, 'w') as tf: tf.write(simple_file.format(str(i))) hw = HardwareManager( 'virtual:[email protected];[email protected];[email protected];[email protected]' ) yield hw hw.disconnect()
def setUp(self): self.vdev = subprocess.Popen( ['virtual_device', 'bled112', 'report_test']) bleds = BLED112Adapter.find_bled112_devices() print(bleds) self.hw = HardwareManager(port='bled112:{}'.format(bleds[1]))
class TestHardwareManager(unittest.TestCase): """ Test to make sure that the HardwareManager is working """ def setUp(self): self.hw = HardwareManager('virtual') def tearDown(self): pass def test_unknown_module(self): with pytest.raises(UnknownModuleTypeError): self.hw._create_proxy('UnknownTileBusModule', 8) def test_uuid_to_slug(self): """Test UUID to DeviceSlug.""" with pytest.raises(ArgumentError): uuid_to_slug('a') with pytest.raises(ArgumentError): uuid_to_slug(-1) with pytest.raises(ArgumentError): uuid_to_slug(0xffffffff) assert uuid_to_slug(1) == 'd--0000-0000-0000-0001' assert uuid_to_slug(0x9c400) == 'd--0000-0000-0009-c400' assert uuid_to_slug(0x0fffffff) == 'd--0000-0000-0fff-ffff'
def hw(virtual_interface): port, _ = virtual_interface hw = HardwareManager(port="ws2:127.0.0.1:{}".format(port)) yield hw hw.close()
def hw(server): port, _ = server logger.info("Creating HardwareManager at port %d", port) hw = HardwareManager(port="ws:127.0.0.1:{}".format(port)) yield hw hw.close()
def hw(server): path, _ = server logger.info("Creating HardwareManager at with socket path %s", path) hw = HardwareManager(port="unix:{}".format(path)) yield hw hw.close()
def tile_based(): conf_file = os.path.join(os.path.dirname(__file__), 'tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:tile_based@%s' % conf_file) yield hw hw.disconnect()
def tracer_hw(): conf_file = os.path.join(os.path.dirname(__file__), 'fast_realtime_trace.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:realtime_test@%s' % conf_file) yield hw hw.disconnect()
def conf2_report_hw(): conf_file = os.path.join(os.path.dirname(__file__), 'report_test_config_signed.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') hw = HardwareManager('virtual:report_test@%s' % conf_file) yield hw hw.disconnect()
class SemihostedRPCExecutor(RPCExecutor): """An RPC executor that runs RPCs on an IOTile device. This is used for "semihosting" a sensor graph where the SG engine runs on your computer but all RPCs are executed on a separete IOTile device. Semihosting is not 100% the same as running the SensorGraph on the device itself because: 1. system inputs and inputs are currently not forwarded from the device to the computer so you cannot respond to events from tiles. (This will be addressed in the future) 2. config variables set in the sensor graph are currently not set in the device, which means tiles that have required configurations need to be manually configured before semihosting a sensor graph. (This will be addressed in the future) Args: port (str): The port we should use to create a HardwareManager instance conected to our device. device_id (int): The device id we should connect to. """ def __init__(self, port, device_id): self.hw = HardwareManager(port=port) self.hw.connect(device_id) super(SemihostedRPCExecutor, self).__init__() def _call_rpc(self, address, rpc_id, payload): """Call an RPC with the given information and return its response. Must raise a hardware error of the appropriate kind if the RPC can not be executed correctly. Otherwise it should return the binary response payload received from the RPC. Args: address (int): The address of the tile we want to call the RPC on rpc_id (int): The id of the RPC that we want to call payload (bytes, bytearray): The data that we want to send as the payload """ # FIXME: Set a timeout of 1.1 seconds to make sure we fail if the device hangs but # this should be long enough to accommodate any actual RPCs we need to send. status, response = self.hw.stream.send_rpc(address, rpc_id, payload, timeout=1.1) return response
class TestHardwareManager(unittest.TestCase): """ Test to make sure that the HardwareManager is working """ def setUp(self): self.hw = HardwareManager('none') def tearDown(self): pass def test_unknown_module(self): with pytest.raises(UnknownModuleTypeError): self.hw._create_proxy('UnknownTileBusModule', 8)
def hw_man(gateway, local_broker): """Create a HardwareManager that can talk to our gateway over the local broker.""" reg = ComponentRegistry() reg.set_config('awsiot-endpoint', '') reg.set_config('awsiot-rootcert', '') reg.set_config('awsiot-iamkey', '') reg.set_config('awsiot-iamtoken', '') hw_dev = HardwareManager(port="awsiot:devices/d--0000-0000-0000-0002") yield hw_dev hw_dev.close()
def tile_based(): conf_file = os.path.join(os.path.dirname(__file__), 'tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') reg = ComponentRegistry() reg.register_extension('iotile.proxy', 'vitual_tile', 'test/test_hw/virtual_tile.py') hw = HardwareManager('virtual:tile_based@%s' % conf_file) yield hw reg.clear_extensions() hw.disconnect()
def hw(): hw = HardwareManager(port='virtual:{}'.format(path)) hw.connect_direct(1) yield hw hw.disconnect() hw.close()
def device(port, device_id, direct, record, request): """Return a HardwareManager instance connected to an IOTile Device This fixture shares the same device among all tests in the same module """ if record is not None: record = _build_record_string(record, request, module=True) with HardwareManager(port=port, record=record) as hw: # Sometimes in congested wireless environments we can miss the # device advertisement, so attempt the connection several times # before giving up to improve test robustness. max_attempts = 3 i = 0 for i in range(0, max_attempts): try: if direct: hw.connect_direct(direct) else: hw.connect(device_id) break except HardwareError: time.sleep(1) if i == max_attempts - 1: pytest.fail( "Could not connect to device after %d attempts, failing" % max_attempts) return hw.enable_streaming() yield hw hw.disconnect()
def stream_vibrations(min_value, max_value): """ Stream vibration data every second, all between min_value and max_value. """ with HardwareManager(port='virtual:./vibration_device.py') as hw: hw.connect('1') con = hw.controller() con.set_min_and_max(min_value, max_value) hw.enable_streaming() """ hw.iter_reports() will run forever until we kill the program with a control-c. """ try: for report in hw.iter_reports(blocking=True): # Verify that the device is sending realtime data as we expect. assert isinstance(report, IndividualReadingReport) assert len(report.visible_readings) == 1 reading = report.visible_readings[0] assert isinstance(reading, IOTileReading) # We just need the value here, use reading.stream and # reading.reading_time to respectively get the stream # and reading time. Print reading to get them all. print(reading.value) except KeyboardInterrupt: pass
def simple_hw(): if sys.version_info < (3, 5): pytest.skip('requires iotile-emulate on python 3.5+') simple_file = """{{ "device": {{ "iotile_id": "{0}", "trace": [ [0.001, "hello "], [0.001, "goodbye "] ], "simulate_time": true }} }} """ for i in [1, 3, 4, 6]: fname = "dev" + str(i) + ".json" with open(fname, 'w') as tf: tf.write(simple_file.format(str(i))) with HardwareManager( 'virtual:[email protected];[email protected];[email protected];[email protected]' ) as hw: yield hw
def test_service_delegate_tile(linked_tile): """Make sure our service delegate tile works correctly.""" hw = linked_tile # pylint:disable=invalid-name; We use hw throughout CoreTools to denote a HardwareManager instance # Normally this is not required but since we are conecting to a # virtual tile that doesn't have a known proxy ('bsctst'), we need # to temporarily register the proxy that we would like to use othweise # we will get a: # HardwareError: HardwareError: Could not find proxy object for tile # Additional Information: # - known_names: ['Simple', 'NO APP'] # - name: 'bsctst' HardwareManager.RegisterDevelopmentProxy(BasicRPCDispatcherProxy) # When we call get(address) the HardwareManager will ask the tile at that address, # in this case the ServiceDelegateTile what it's 6 character name is. It will # return, in this case 'bsctst' because that's what we put in the config.json # file we created in the linked_tile fixture. The HardwareManager will then # look up in its dictionary of known proxies for one whose ModuleName() exactly # matches and return that object. proxy = hw.get(11) result = proxy.add(5, 1) assert result == 5 + 1
def test_initialisation(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('get') == 20 assert con.manage_max_value('get') == 100 vibration_test(20, 100, con)
def per_test_device(port, device_id, direct, record, request): """Return a HardwareManager instance connected to an IOTile Device This fixture creates and tears down the connection for each test """ if record is not None: record = _build_record_string(record, request, module=False) with HardwareManager(port=port, record=record) as hw: max_attempts = 3 i = 0 for i in range(0, max_attempts): try: if direct: hw.connect_direct(direct) else: hw.connect(device_id) break except HardwareError: time.sleep(1) if i == max_attempts - 1: pytest.fail( "Could not connect to device after %d attempts, failing" % max_attempts) return hw.enable_streaming() yield hw hw.disconnect()
def test_set_correct_min_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('set=99') == 99 vibration_test(99, 100, con) assert con.manage_min_value('set=0') == 0 vibration_test(0, 100, con)
def proxy_variants_4(): conf_file = os.path.join(os.path.dirname(__file__), 'proxy_match_tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') reg = ComponentRegistry() # None, None reg.register_extension('iotile.proxy', 'proxy_match_tile', ProxyMatchTest1) reg.register_extension('iotile.proxy', 'proxy_match_tile', ProxyMatchTest2) hw = HardwareManager('virtual:tile_based@%s' % conf_file) yield hw reg.clear_extensions() hw.close()
def test_set_correct_max_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_max_value('set=21') == 21 vibration_test(20, 21, con) assert con.manage_max_value('set=1234567890') == 1234567890 vibration_test(20, 1234567890, con)
def con(): hw = HardwareManager(port='virtual:./radiation_device.py') hw.connect_direct(1) con = hw.controller() yield con hw.disconnect()
def test_find_virtual_script_withjson(): """Make sure we can find a script with a json """ path = os.path.join(os.path.dirname(__file__), 'virtual_device.py') jsonpath = os.path.join(os.path.dirname(__file__), 'report_test_config_signed.json') hw = HardwareManager(port="virtual:%s@%s" % (path, jsonpath))
def setUp(self): self.old_serial = serial.Serial serial.Serial = util.dummy_serial.Serial self.adapter = MockBLED112(3) self.dev1 = MockIOTileDevice(100, 'TestCN') self.dev1_ble = MockBLEDevice("00:11:22:33:44:55", self.dev1) self.adapter.add_device(self.dev1_ble) util.dummy_serial.RESPONSE_GENERATOR = self.adapter.generate_response self.dev1.reports = [ IndividualReadingReport.FromReadings(100, [IOTileReading(0, 1, 2)]) ] self._reports_received = threading.Event() logging.basicConfig(level=logging.INFO, stream=sys.stdout) self.scanned_devices = [] self.hw = HardwareManager(port='bled112:test')
def test_find_virtual_script_unknownjson(): """Make sure we can find a script with a json """ path = os.path.join(os.path.dirname(__file__), 'virtual_device.py') jsonpath = os.path.join(os.path.dirname(__file__), 'unknown_json_config.json') with pytest.raises(ArgumentError): hw = HardwareManager(port="virtual:%s@%s" % (path, jsonpath))
def test_set_incorrect_min_value(): with HardwareManager(port='virtual:./engine_vibration_device.py') as hw: hw.connect('1') con = hw.controller() assert con.manage_min_value('set=100') == 20 # initial value assert con.manage_min_value('set=zhrbjvk') == None with pytest.raises(APIError): con.manage_min_value('set=-1') with pytest.raises(APIError): # since min_value is converted in long before being compared to max_value this kind of error can appear con.manage_min_value('set=10000000000000000000000000000000000000')
def test_recording_rpcs(tmpdir): """Make sure we can record RPCs.""" record_path = tmpdir.join('recording.csv') conf_file = os.path.join(os.path.dirname(__file__), 'tile_config.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') reg = ComponentRegistry() reg.register_extension('iotile.proxy', 'virtual_tile', 'test/test_hw/virtual_tile.py') try: with HardwareManager('virtual:tile_based@%s' % conf_file, record=str(record_path)) as hw: hw.connect(1) con = hw.get(9) tile1 = hw.get(11) con.count() tile1.add(3, 5) tile1.count() finally: reg.clear_extensions() assert record_path.exists() rpcs = record_path.readlines(cr=False) assert len(rpcs) == 12 assert rpcs[:3] == ['# IOTile RPC Recording', '# Format: 1.0', ''] # Patch out the timestamps and run times for better comparison rpc_lines = [x.split(',') for x in rpcs[4:-1]] for rpc in rpc_lines: assert len(rpc) == 9 rpc[1] = "" rpc[5] = "" rpc_lines = [",".join(x) for x in rpc_lines] print(rpc_lines[4]) assert rpc_lines == [ '1,, 9,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,, 9,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,,11,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,,11,0x0004,0xc0,, ,ffff74657374303101000003 ,', '1,, 9,0x8001,0xc0,, ,00000000 ,', '1,,11,0x8000,0xc0,,0300000005000000 ,08000000 ,', '1,,11,0x8001,0xc0,, ,00000000 ,' ]
def test_invalid_length_combo(): """Make sure invalid length combinations throw an exception """ conf_file = os.path.join(os.path.dirname(__file__), 'report_length_invalid.json') if '@' in conf_file or ',' in conf_file or ';' in conf_file: pytest.skip('Cannot pass device config because path has [@,;] in it') with pytest.raises(ArgumentError): hw = HardwareManager('virtual:report_test@%s' % conf_file)