-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
57 lines (47 loc) · 2.04 KB
/
main.py
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
"""
The main file of the simulated device. It is responsible for:
- Reading the MAC Address and Device Token from the command line
- Creating a simulated device
- Registering the device on the IoT platform
- Sending telemetry data to the IoT platform
"""
import logging
import random
import time
# Import all the core modules.
from core import ConfigHandler, DataGenerator
from core import Device, ThingsboardConnector
# Create a custom logger interface.
LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
logging.basicConfig(level=logging.INFO, format=LOG_FORMAT)
logger = logging.getLogger(__name__)
if __name__ == "__main__":
# Read the configurations.
config = ConfigHandler.read()
# Create a ThingsboardConnector instance.
connector = ThingsboardConnector(config["host"], config["port"])
# Create a device instance.
device = Device(config["mac_addr"])
if config["token"]:
# If the token is provided, set it to the device.
# It means the device is already registered.
device.set_token(config["token"])
else:
# If the token is not provided, set the provision key and secret.
# It means the device is not registered. Use ThingsboardConnector
# to register.
device.set_provision_key(config["provision_key"])
device.set_provision_secret(config["provision_secret"])
connector.register_device(device)
# Create a data generator function.
sensor_1 = DataGenerator(5, "exponantial", {"base": 2.67, "offset": 25})
sensor_2 = DataGenerator(3, "exponantial", {"base": 3.38, "shift": 0.12})
# Send telemetry data to the IoT platform.
while True:
# Create formatted data to be sent to the ThingSpeak.
data_packet = device.get_formatted_data(
"e1", sensor_1.generate(1, 25),
"e2", sensor_2.generate(error_percentage=10),
)
connector.send_telemetry_data(device.get_token(), data_packet)
time.sleep(random.randint(10, 60))