summaryrefslogtreecommitdiffstats
path: root/ci/find_device_id.py
blob: 816274e49be18dc3df16e24b328925d423337a9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#!/usr/bin/python3

"""Find the device ID for a given device in C8y and print it on the
command line.

For example:

    python3 ci/find_device_id.py --tenant t493319102 --user octocat
      --device devraspberrypi --url thin-edge-io.eu-latest.cumulocity.com

"""

import argparse
import os
import sys
from c8y_api import CumulocityApi


def get_device_id(c8y, name):
    """retrive the current device ID"""

    devices = c8y.device_inventory.get_all(name=name)
    if len(devices) == 1:
        return devices[0].id
    return None


def main():
    """Main entry point"""

    parser = argparse.ArgumentParser()
    parser.add_argument("--tenant", required=True, help="C8y Tenant")
    parser.add_argument("--user", required=True, help="C8y User")
    parser.add_argument("--device", required=True, help="Device to find")
    parser.add_argument("--url", required=True, help="URL of C8y")
    parser.add_argument("--verbose", "-v", action="count", default=0)

    args = parser.parse_args()

    tenant = args.tenant
    user = args.user
    device_name = args.device
    url = args.url
    verbose = args.verbose

    try:
        password = os.environ["C8YPASS"]
    except KeyError:
        print("Please export your password into $C8YPASS")
        sys.exit(1)

    c8y = CumulocityApi(url, tenant, user, password)

    device_id = get_device_id(c8y, device_name)
    if device_id:
        if verbose:
            print("The current device ID is:")
        print(device_id)

    else:
        print("Failed to find device in C8y")
        sys.exit(1)


if __name__ == "__main__":
    main()