コード例 #1
0
    def setup(self):
        # Check if API key is in environmental vars
        if 'MBED_CLOUD_SDK_API_KEY' in os.environ:
            api_key = (os.environ[str('MBED_CLOUD_SDK_API_KEY')])
        else:
            api_key = self.config.get("api_key")

        if not api_key.startswith('ak_'):
            raise TestStepFail(
                "No API key in MBED_CLOUD_SDK_API_KEY or in pelion.tc_cfg")

        self.device_id = self.config.get("device_id")
        host = self.config.get("host")
        self.test_config = {"api_key": api_key, "host": host}
        self.account_api = AccountManagementAPI(self.test_config)
        self.connect_api = ConnectAPI(self.test_config)
        self.device_api = DeviceDirectoryAPI(self.test_config)

        # Additional parameters for handling REST requests without SDK
        self.rest_headers = {'Authorization': 'Bearer ' + api_key}
        self.rest_address = self.config.get("host")

        # Init delay due to internal usage of PULL notification in SDK. Notications might be lost between
        # tests.
        # TODO: Remove workaround after limitation in SDK has been fixed.
        self.delay(5)
コード例 #2
0
    def test_list_disconnected(self):
        # an example: list deregistered devices in Pelion Device Management
        from mbed_cloud import DeviceDirectoryAPI
        api = DeviceDirectoryAPI()

        # Print all devices
        for device in api.list_devices(filter=dict(state='deregistered'), order='asc', max_results=900):
            print(device.id, device.state)
コード例 #3
0
def _main():
    api = DeviceDirectoryAPI()

    # List all devices, ordering by the most recently created first.
    for idx, d in enumerate(api.list_devices(order='desc', limit=10)):
        _print_device(idx + 1, d)

    print("\n" + "-" * 30 + "\n")

    # Now only list the devices that are registered.
    filters = {'state': {'$eq': "deregistered"}}
    registered = api.list_devices(order='desc', limit=10, filters=filters)
    for idx, d in enumerate(registered):
        _print_device(idx + 1, d)
コード例 #4
0
def _main():
    api = DeviceDirectoryAPI()
    events = list(api.list_device_events(limit=5, order='desc'))

    for idx, event in enumerate(events):
        _print_event(idx + 1, event)

    print("-" * 30 + "\n")

    filters = {
        'id': str(events[0].id),
    }
    device_events = api.list_device_events(limit=5, filters=filters)
    for idx, device_event in enumerate(device_events):
        _print_event(idx + 1, device_event)
コード例 #5
0
    def setup(self):
        self.device_id = self.config.get("device_id")
        api_key = self.config.get("api_key")
        host = self.config.get("host")
        self.test_config = {"api_key": api_key, "host": host}
        self.account_api = AccountManagementAPI(self.test_config)
        self.connect_api = ConnectAPI(self.test_config)
        self.device_api = DeviceDirectoryAPI(self.test_config)

        # Additional parameters for handling REST requests without SDK
        self.rest_headers = {'Authorization': 'Bearer ' + self.config.get("api_key")}
        self.rest_address = self.config.get("host")

        # Init delay due to internal usage of PULL notification in SDK. Notications might be lost between
        # tests.
        # TODO: Remove workaround after limitation in SDK has been fixed.
        self.delay(5)
コード例 #6
0
def _main():
    api = DeviceDirectoryAPI()

    # Create a new device
    print("Creating new device...")
    device = {
        "certificate_issuer_id": _id_generator(12),
        "certificate_fingerprint": _id_generator(12)
    }
    new_device = api.add_device(**device)
    print("Successfully created device with id: %r" % new_device.id)

    # Update device
    updated_device = api.update_device(
        new_device.id,
        certificate_fingerprint=new_device.certificate_fingerprint,
        certificate_issuer_id=_id_generator(12))

    # Delete the device
    print("Attempting to delete device from catalog...")
    api.delete_device(updated_device.id)
    print("Successfully deleted device (ID: %r)" % updated_device.id)
コード例 #7
0
class PelionBase(Bench):
    """
    Base class containing common implementation shared by tests
    """
    def __init__(self, **kwargs):
        Bench.__init__(self, **kwargs)
        self.test_config = None
        self.device_id = None
        self.manifest_id = None
        self.account_api = None
        self.connect_api = None
        self.device_api = None
        self.update_api = None
        self.rest_headers = None
        self.rest_address = None
        self.pattern_value1 = "1000:1000:1000:1000"
        self.pattern_value2 = "2000:1000:2000:1000"
        self.pattern_value3 = "3000:1000:3000:1000"
        self.notified_value = ""

    def setup(self):
        # Check if API key is in environmental vars
        if 'MBED_CLOUD_SDK_API_KEY' in os.environ:
            api_key = (os.environ[str('MBED_CLOUD_SDK_API_KEY')])
        else:
            api_key = self.config.get("api_key")

        if not api_key.startswith('ak_'):
            raise TestStepFail(
                "No API key in MBED_CLOUD_SDK_API_KEY or in pelion.tc_cfg")

        self.device_id = self.config.get("device_id")
        host = self.config.get("host")
        self.test_config = {"api_key": api_key, "host": host}
        self.account_api = AccountManagementAPI(self.test_config)
        self.connect_api = ConnectAPI(self.test_config)
        self.device_api = DeviceDirectoryAPI(self.test_config)

        # Additional parameters for handling REST requests without SDK
        self.rest_headers = {'Authorization': 'Bearer ' + api_key}
        self.rest_address = self.config.get("host")

        # Init delay due to internal usage of PULL notification in SDK. Notications might be lost between
        # tests.
        # TODO: Remove workaround after limitation in SDK has been fixed.
        self.delay(5)

    def setup_update(self):
        self.manifest_id = self.config.get("manifest_id")
        self.update_api = UpdateAPI(self.test_config)

    def _callback_fn(self, device_id, path, value):
        string = value.decode("utf-8")
        self.logger.info("Notification for %s received: %r value: %r",
                         device_id, path, string)
        self.notified_value = string

    def verify_registration(self, expected_state):
        self.logger.info("Verify device to in state %s", expected_state)
        device = self.device_api.get_device(self.device_id)
        if device is None:
            raise TestStepFail(
                "device_id %s does not exist/is not listed in Device Directory"
                % self.device_id)
        else:
            if device.state == expected_state:
                self.logger.info("Endpoint %s is in state: %s", self.device_id,
                                 expected_state)
            else:
                raise TestStepFail(
                    "Endpoint %s is in state %s, expected %s" %
                    (self.device_id, device.state, expected_state))

    def prepare_campaign_filter(self, state):
        # Create filter for the update campaign. Here we only update one endpoint.
        payload = {}
        payload["device_filter"] = "id=" + self.device_id
        payload["root_manifest_id"] = self.manifest_id
        payload["name"] = str(uuid.uuid4())
        payload["state"] = state
        return payload

    ## Function for starting a update campaign
    ## TODO: Replace with Python SDK implementation
    def post_campaign(self, payload):
        req_address = self.rest_address + '/v3/update-campaigns'
        res = requests.post(req_address,
                            json=payload,
                            headers=self.rest_headers)
        if res.status_code == 409:
            # Endpoint can be targeted by only one active campaign. The older campaign must be deleted/stopped.
            raise TestStepFail("Campaign already exists for device %s" %
                               self.device_id)
        elif res.status_code != 201:
            raise TestStepFail("Campaign creation failed with %d" %
                               res.status_code)

        data = res.json()
        campaign_id = data["id"]
        return campaign_id

    ## Function for checking firmware update status from Cloud
    ## TODO: Replace with Python SDK implementation
    def check_campaign_state(self, campaign_id):
        results = []
        base_url = self.rest_address + "/v3/update-campaigns"
        campaign_url = base_url + "/" + campaign_id
        metadata_url = campaign_url + "/" + "campaign-device-metadata"

        # Short wait until campaign has been initialized properly.
        self.delay(5)

        # Fetch basic campaign information
        response = requests.get(campaign_url, headers=self.rest_headers)
        if response.status_code != 200:
            raise TestStepFail("Get Campaign state returned %d" %
                               response.status_code)

        resp = json.loads(response.content)
        results.append(resp["state"])

        # Fetch campaign metadata information
        response = requests.get(metadata_url, headers=self.rest_headers)
        if response.status_code != 200:
            raise TestStepFail("Get Campaign metadata returned %d" %
                               response.status_code)

        resp = json.loads(response.content)
        if 'data' in resp and resp['data'][0]['deployment_state']:
            meta_data = resp['data']
            device_state = meta_data[0]['deployment_state']
            results.append(device_state)
        else:
            raise TestStepFail("No metadata for %d" % self.device_id)

        return results

    restTimeout = 60
コード例 #8
0
def _main():
    api = DeviceDirectoryAPI()

    # Pretty print all the registered queries
    for idx, e in enumerate(api.list_queries(limit=5)):
        print(e)

    # Create a new query
    new_query = api.add_query("test_filter",
                              {'device_id': {
                                  '$eq': str(uuid.uuid4())
                              }})
    print("\nCreated new query: %r" % (new_query.name))

    # Delete same query
    api.delete_query(new_query.id)
    print("Deleted newly created query")

    # Create more complex query
    print("Creating complex query")
    new_c_query = api.add_query(
        "complex_test_query %s" % _id_generator(), {
            'device_id': {
                '$eq': str(uuid.uuid4())
            },
            'auto_update': {
                '$eq': True
            },
            'state': {
                '$eq': 'bootstrapped'
            },
            'device_class': {
                '$eq': 'embedded'
            },
            'serial_number': {
                '$eq': '1234'
            },
            'vendor_id': {
                '$eq': 'Arm'
            },
            'description': {
                '$eq': 'Loreum ipsum'
            },
            'device_name': {
                '$eq': 'DeviceName'
            },
            'custom_attributes': {
                'customA': {
                    '$eq': 'SomethingA'
                },
                'customB': {
                    '$eq': 'Something B'
                }
            }
        })

    # Manually get it
    gf = api.get_query(new_c_query.id)
    print("Got query %r using 'get'" % gf.name)
    # Update the query
    new_filter_dict = gf.filter
    new_filter_dict['serial_number']['$eq'] = '12345'
    updated_gf = api.update_query(query_id=gf.id,
                                  name=gf.name,
                                  filter=new_filter_dict)
    # Check it was successful
    assert updated_gf.filter['serial_number']['$eq'] == '12345'
    print("Updated query with new serial number")

    # Find device using query object
    print("Find devices that are matching the created query")
    devicesResponse = api.list_devices(filters=updated_gf.filter)
    # Print all devices that are matching provided query
    print(list(devicesResponse))

    # And delete that too
    api.delete_query(new_c_query.id)
    print("Deleted complex query")
コード例 #9
0
def _main():
    update_api = UpdateAPI()

    # Read manifest from first argument on command line
    if len(sys.argv) < 2:
        raise ValueError("No manifest filename found on command line")
    filename = os.path.abspath(sys.argv[1])

    # Upload manifest
    mobj = update_api.add_firmware_manifest(
        name="Auto manifest %s" % _rand_id(),
        datafile=filename,
        description="Manifest uploaded using Mbed Cloud SDK")
    print("Successfully uploaded manifest %r\n\tURL: %s\nProperties:" %
          (mobj.name, mobj.url))

    # List all manifests currently uploaded
    mresp = update_api.list_firmware_manifests(limit=10)
    _print_manifests(mresp)

    # List all filters
    device_api = DeviceDirectoryAPI()
    fresp = device_api.list_queries()
    header = "Current filters:"
    print("\n%s\n%s" % (header, "-" * len(header)))
    if fresp.count() == 0:
        print("No filters created. Please create one to apply the update on.")
        sys.exit(1)
    filters = [f for idx, f in enumerate(fresp)]
    print("\n".join(["\t- %s" % (f.name) for f in filters]))
    selected_query = random.choice(filters)
    print("Randomly chose %r for applying update" % (selected_query.name))

    # Create update campaign. For this step we need three pieces of information:
    # 1. The name of the update campaign (we auto-generate this)
    # 2. What manifest to use for running the update
    # 3. What devices we should apply the updat on (i.e. the filter to use)
    campaign_name = _rand_id()
    print(
        "\nCreating campaign %r using:\n\t- Manifest ID: %r\n\t- Filter ID: %r"
        % (campaign_name, mobj.id, selected_query.id))
    cobj = update_api.add_campaign(name=campaign_name,
                                   manifest_id=mobj.id,
                                   device_filter=selected_query.filter)
    print("Campaign successfully created. Current state: %r" % (cobj.state))

    #
    # List the current campaigns
    #
    header = "Update campaigns"
    print("\n%s\n%s" % (header, "-" * len(header)))
    for idx, c in enumerate(update_api.list_campaigns()):
        print("\t- %s (State: %r)" % (c.name, c.state))

    #
    # Start the update campaign we've created.
    #
    print("\n** Starting the update campign **")
    # By default a new campaign is created with the 'draft' status. We can manually start it.
    new_cobj = update_api.start_campaign(cobj)
    print(
        "Campaign successfully started. Current state: %r. Checking updates.."
        % (new_cobj.state))
    countdown = 10
    while countdown > 0:
        c = update_api.get_campaign(new_cobj.id)
        print("[%d/10] Current state: %r (Finished: %s)" %
              (countdown, c.state, c.finished_at))
        countdown -= 1

    #
    # Cleanup.
    #
    print("\n** Deleting update campaign and manifest **")
    update_api.delete_campaign(new_cobj.id)
    update_api.delete_firmware_manifest(mobj.id)