iot-with-document-store-db

git clone git://git.codymlewis.com/iot-with-document-store-db.git
Log | Files | Refs | README

Network.py (4359B)


      1 #!/usr/bin/env python3
      2 # -*- coding: utf-8 -*-
      3 #
      4 # Simulate an Internet of things network, and send data on nodes to the server
      5 # Author: Cody Lewis
      6 # Date: 2019-05-16
      7 
      8 
      9 import random
     10 import time
     11 from json.encoder import JSONEncoder
     12 
     13 import requests
     14 
     15 import Secrets
     16 import Functions
     17 
     18 
     19 ADMIN_DB_ADDR = f"http://{Secrets.DB_USERNAME}:{Secrets.DB_PASSWORD}@127.0.0.1:5984/sensors"
     20 DB_ADDR = f"http://127.0.0.1:5984/sensors"
     21 THING_TYPES = ["Themometer", "Acnemometer", "Smart Light", "Pulse Oximeter"]
     22 JSONENCODER = JSONEncoder()
     23 
     24 
     25 class Thing:
     26     '''
     27     A simulated thing in the network.
     28     '''
     29     def __init__(self, id_num=0, x_val=0, y_val=0, type_val="Thing"):
     30         self.__id = id_num
     31         self.__x = x_val
     32         self.__y = y_val
     33         self.__type = type_val
     34         self.__data = []
     35         self.rev = ""
     36 
     37     def get_type(self):
     38         return self.__type
     39 
     40     def get_id(self):
     41         return self.__id
     42 
     43     def get_json(self):
     44         '''
     45         Get a JSON style string from the values contained in this
     46         '''
     47         return JSONENCODER.encode(self.__get_vals())
     48 
     49     def __get_vals(self):
     50         '''
     51         Get a dictionary of the values in this
     52         '''
     53         return {
     54             "id": self.__id,
     55             "x": self.__x,
     56             "y": self.__y,
     57             "type": self.__type,
     58             "data": self.__data
     59         }
     60 
     61     def add_data(self, data):
     62         '''
     63         Add a row of data to this
     64         '''
     65         self.__data.append(data)
     66 
     67     def get_data_json(self):
     68         vals = self.__get_vals()
     69         vals["_rev"] = self.rev
     70         return JSONENCODER.encode(vals)
     71 
     72 
     73 class Network:
     74     '''
     75     The simulated network.
     76     '''
     77     def __init__(self, total_nodes):
     78         requests.put(f"{ADMIN_DB_ADDR}")
     79         self.__nodes = []
     80         for i in range(total_nodes):
     81             new_thing = Thing(i, random.randint(0, 255), random.randint(0, 255), THING_TYPES[i % len(THING_TYPES)])
     82             request = requests.put(f"{DB_ADDR}/{new_thing.get_id()}", data=new_thing.get_json())
     83             new_thing.rev = request.json()["rev"]
     84             self.__nodes.append(new_thing)
     85             Functions.print_progress(i + 1, total_nodes, prefix=f"{i + 1}/{total_nodes} created")
     86         print()
     87 
     88     def run(self):
     89         '''
     90         Run the network infinitely.
     91         '''
     92         cur_time = 0, 0
     93         while True:
     94             # chosen_node = self.__nodes[random.randint(0, len(self.__nodes) - 1)]
     95             for node in self.__nodes:
     96                 node_type = node.get_type()
     97                 if node_type == "Themometer":
     98                     node.add_data({"time": cur_time, "temp": random.randint(15, 40)})
     99                 elif node_type == "Acnemometer":
    100                     node.add_data({"time": cur_time, "speed": random.randint(0, 40), "pressure": random.randint(0, 20)})
    101                 elif node_type == "Smart Light":
    102                     node.add_data({
    103                         "time": cur_time,
    104                         "status": random.sample(["On", "Off"], 1)[0],
    105                         "usage": random.uniform(0, 1)
    106                     })
    107                 elif node_type == "Pulse Oximeter":
    108                     node.add_data({"time": cur_time, "rate": random.randint(50, 170)})
    109                 request = requests.put(f"{DB_ADDR}/{node.get_id()}", data=node.get_data_json())
    110                 node.rev = request.json()["rev"]
    111             print(f"\rAdded data for all nodes at time {cur_time}.", end="\r")
    112             time.sleep(1)
    113             cur_time += 1
    114 
    115     def cleanup(self):
    116         for index_node in enumerate(self.__nodes):
    117             ok = False
    118             while not ok:
    119                 rev = requests.get(f"{DB_ADDR}/{index_node[1].get_id()}").json()["_rev"]
    120                 request = requests.delete(f"{DB_ADDR}/{index_node[1].get_id()}?rev={rev}")
    121                 ok = request.json()["ok"]
    122             Functions.print_progress(index_node[0] + 1, len(self.__nodes), prefix=f"{index_node[0] + 1}/{len(self.__nodes)} deleted")
    123         print()
    124 
    125 
    126 if __name__ == '__main__':
    127     NUMBER_NODES = 10
    128     print(f"Creating a network with {NUMBER_NODES} nodes.")
    129     NETWORK = Network(NUMBER_NODES)
    130     try:
    131         print("Running the network...")
    132         NETWORK.run()
    133     except KeyboardInterrupt:
    134         print()
    135         print("Cleaning up...")
    136         NETWORK.cleanup()
    137         print("bye.")