1#!/usr/bin/env python
2
3import boto3
4import json
5
6
7class Thing():
8    def __init__(self, name):
9        self.client = boto3.client('iot')
10        self.name = name
11        self.arn = ''
12
13    def create(self):
14        assert not self.exists(), "Thing already exists"
15        result = self.client.create_thing(thingName=self.name)
16        self.arn = result['thingArn']
17
18    def delete(self):
19        assert self.exists(), "Thing does not exist"
20        principals = self.list_principals()
21        for principal in principals:
22            self.detach_principal(principal)
23        self.client.delete_thing(thingName=self.name)
24
25    def exists(self):
26        list_of_things = self.client.list_things()['things']
27        for thing in list_of_things:
28            if thing['thingName'] == self.name:
29                return True
30        return False
31
32    def attach_principal(self, arn):
33        assert self.exists(), "Thing does not exist"
34        self.client.attach_thing_principal(thingName=self.name, principal=arn)
35
36    def detach_principal(self, arn):
37        assert self.exists(), "Thing does not exist"
38        self.client.detach_thing_principal(thingName=self.name, principal=arn)
39
40    def list_principals(self):
41        assert self.exists(), "Thing does not exist"
42        principals = self.client.list_thing_principals(thingName=self.name)
43        principals = principals['principals']
44        return principals
45