Exemplo n.º 1
0
    def __init__(self, device_id, queue=None):
        try:
            self.get_vars = GetVars()
            if queue is not None:
                self.queue = queue
            self.runPrs = False
            self.ssl_algorithm = self.get_vars.get_var(
                "GoogleIOT_Algorithm")  # Either RS256 or ES256
            self.ssl_private_key_filepath = self.get_vars.get_var(
                "GoogleIOT_PrivateKey")
            self.root_cert_filepath = self.get_vars.get_var(
                "GoogleIOT_CertPath")
            self.project_id = self.get_vars.get_var("GoogleIOT_ProjectID")
            self.gcp_location = self.get_vars.get_var("GoogleIOT_Location")
            self.registry_id = self.get_vars.get_var("GoogleIOT_RegistryId")
            self.device_id = device_id
            self._CLIENT_ID = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
                self.project_id, self.gcp_location, self.registry_id,
                self.device_id)
            self.topic = '/devices/{}/events'.format(self.device_id)
            self.commandTopic = '/devices/{}/commands/#'.format(self.device_id)
            self.client = mqtt.Client(client_id=self._CLIENT_ID)
            self.start()

        except Exception as ex:
            logging.error(ex)
Exemplo n.º 2
0
 def __init__(self):
     try:
         self.get_vars = GetVars()
         self.host = "Kitchen"
         self.mqtt = MQTT(self.get_vars.get_var("Topic"))
         self.start()
     except Exception as ex:
         logging.error(ex)
Exemplo n.º 3
0
 def __init__(self):
     try:
         self.get_vars = GetVars()
         self.messages_queue = Queue()
         self.influxdb = Influxdb()
         self.start()
     except Exception as ex:
         logging.error(ex)
 def __init__(self, token_type="Pi"):
     try:
         self.get_vars = GetVars()
         self.connection = False
         self.Messages = []
         """ check which device it is """
         if token_type == "Pi":
             self.token = self.get_vars.get_var("InfluxDB_Token_Pi")
         else:
             self.token = self.get_vars.get_var("InfluxDB_Token_Cloud")
         self.start()
     except Exception as ex:
         logging.error(ex)
Exemplo n.º 5
0
class PiKitchen:
    def __init__(self):
        try:
            self.get_vars = GetVars()
            self.host = "Kitchen"
            self.mqtt = MQTT(self.get_vars.get_var("Topic"))
            self.start()
        except Exception as ex:
            logging.error(ex)

    def start(self):
        while True:
            try:
                data = []
                data.append(Data("temperature", self.temperature_sensor()))
                sensordata = Sensordata("temperature_room", self.host,
                                        datetime.now(), data)
                self.mqtt.publish(sensordata)
                sleep(3)
            except Exception as ex:
                logging.info(ex)
                raise Exception(ex)

    def temperature_sensor(self):
        try:
            temperature = random.uniform(-1.1, 31.1)
            return temperature
        except Exception as ex:
            logging.info(ex)
            raise Exception(ex)
Exemplo n.º 6
0
class PiHead:
    def __init__(self):
        try:
            self.get_vars = GetVars()
            self.messages_queue = Queue()
            self.influxdb = Influxdb()
            self.start()
        except Exception as ex:
            logging.error(ex)

    def start(self):
        try:
            t_mqtt = Thread(target=self.start_mqtt)
            t_mqtt.start()

            t_get_data = Thread(target=self.get_data)
            t_get_data.start()
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)

    def start_mqtt(self):
        try:
            mqtt = MQTT(self.get_vars.get_var("Topic"), True,
                        self.messages_queue)
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)

    def get_data(self):
        try:
            message = self.messages_queue.get()
            while True:
                try:
                    self.influxdb.write_data(message)
                    self.messages_queue.task_done()
                    message = self.messages_queue.get()
                except Exception as ex:
                    logging.error(ex)
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)
Exemplo n.º 7
0
class SendMail:
    def __init__(self):
        try:
            self.getvars = GetVars()
            self.sg = SendGridAPIClient(self.getvars.get_var("SendGrid_key"))
        except Exception as ex:
            logging.error(ex)

    def send_message(self,
                     message_subject,
                     message_body,
                     message_to=[],
                     message_from="*****@*****.**"):
        try:
            message = Mail(from_email=message_from,
                           to_emails=message_to,
                           subject=message_subject,
                           html_content=message_body)
            response = self.sg.send(message)
            return response.status_code
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)
Exemplo n.º 8
0
import os
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)
sys.path.insert(0, BASE_DIR)

from Logic.get_vars import GetVars
import logging

logging.basicConfig(
    filename=f"{BASE_DIR}/data/logging.txt",
    level=logging.ERROR,
    format=
    "%(asctime)s	%(levelname)s -- %(processName)s %(filename)s:%(lineno)s -- %(message)s"
)

get_vars = GetVars()

ACCESS_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'
AUTHORIZATION_URL = 'https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent'

AUTHORIZATION_SCOPE = 'openid email profile'

AUTH_REDIRECT_URI = get_vars.get_var("RedirectURL")
BASE_URI = get_vars.get_var("BaseURL")
CLIENT_ID = get_vars.get_var("Google_Login_ClientID")
CLIENT_SECRET = get_vars.get_var("Google_Login_Secret")

AUTH_TOKEN_KEY = 'auth_token'
AUTH_STATE_KEY = 'auth_state'

app = flask.Blueprint('google_auth', __name__)
Exemplo n.º 9
0
 def __init__(self):
     try:
         self.getvars = GetVars()
         self.sg = SendGridAPIClient(self.getvars.get_var("SendGrid_key"))
     except Exception as ex:
         logging.error(ex)
Exemplo n.º 10
0
from oauthlib.oauth2 import WebApplicationClient
import requests


PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
BASE_DIR = os.path.dirname(PROJECT_ROOT)
sys.path.insert(0, BASE_DIR)

from Logic.server import Server
from Logic.get_vars import GetVars
from Models.user import User

logging.basicConfig(filename="Logging.txt", level=logging.ERROR,
                    format="%(asctime)s	%(levelname)s -- %(processName)s %(filename)s:%(lineno)s -- %(message)s")

get_vars = GetVars()

app = Flask(__name__)
CORS(app)
app.config['SECRET_KEY'] = 'Secret!'
socketio = SocketIO(app, cors_allowed_origins='*')

login_manager = LoginManager()
login_manager.init_app(app)

endpoint = '/api/v1'

# Configuration
GOOGLE_CLIENT_ID = get_vars.get_var("Google_Login_ClientID")
GOOGLE_CLIENT_SECRET = get_vars.get_var("Google_Login_Secret")
GOOGLE_DISCOVERY_URL = ("https://accounts.google.com/.well-known/openid-configuration")
Exemplo n.º 11
0
class MQTT:
    def __init__(self, device_id, queue=None):
        try:
            self.get_vars = GetVars()
            if queue is not None:
                self.queue = queue
            self.runPrs = False
            self.ssl_algorithm = self.get_vars.get_var(
                "GoogleIOT_Algorithm")  # Either RS256 or ES256
            self.ssl_private_key_filepath = self.get_vars.get_var(
                "GoogleIOT_PrivateKey")
            self.root_cert_filepath = self.get_vars.get_var(
                "GoogleIOT_CertPath")
            self.project_id = self.get_vars.get_var("GoogleIOT_ProjectID")
            self.gcp_location = self.get_vars.get_var("GoogleIOT_Location")
            self.registry_id = self.get_vars.get_var("GoogleIOT_RegistryId")
            self.device_id = device_id
            self._CLIENT_ID = 'projects/{}/locations/{}/registries/{}/devices/{}'.format(
                self.project_id, self.gcp_location, self.registry_id,
                self.device_id)
            self.topic = '/devices/{}/events'.format(self.device_id)
            self.commandTopic = '/devices/{}/commands/#'.format(self.device_id)
            self.client = mqtt.Client(client_id=self._CLIENT_ID)
            self.start()

        except Exception as ex:
            logging.error(ex)

    def start(self):
        try:
            # authorization is handled purely with JWT, no user/pass, so username can be whatever
            self.client.username_pw_set(username='******',
                                        password=self.create_jwt())

            self.client.on_connect = self.on_connect
            self.client.on_publish = self.on_publish
            self.client.on_message = self.on_message

            self.client.tls_set(
                ca_certs=self.root_cert_filepath
            )  # Replace this with 3rd party cert if that was used when creating registry
            self.client.connect('mqtt.googleapis.com', 8883)
            self.client.loop_start()
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)

    def create_jwt(self):
        try:
            cur_time = datetime.datetime.utcnow()
            token = {
                'iat': cur_time,
                'exp': cur_time + datetime.timedelta(minutes=60),
                'aud': self.project_id
            }

            with open(self.ssl_private_key_filepath, 'r') as f:
                private_key = f.read()

            return jwt.encode(token, private_key, self.ssl_algorithm)
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)

    def error_str(self, rc):
        return '{}: {}'.format(rc, mqtt.error_string(rc))

    def on_connect(self, unusued_client, unused_userdata, unused_flags, rc):
        print('on_connect', self.error_str(rc))
        self.client.subscribe(self.commandTopic, qos=1)

    def on_publish(self, unused_client, unused_userdata, unused_mid):
        print('on_publish')

    def on_message(self, unused_client, unused_userdata, message):
        try:
            payload = str(message.payload.decode('utf-8'))
            print(payload)
            command = jsonpickle.loads(payload)
            keys = command.keys()
            k = ""
            for key in keys:
                k = key
                break
            value = command[k]
            if k == "people":
                if value == "off":
                    self.runPrs = False
                    print("people counter stopped")
                elif value == "on":
                    self.runPrs = True
                    self.queue.put("people")
                    print("people counter started")
                else:
                    print("command not recognised")
            elif k == "update":
                self.queue.put("quit")
                time.sleep(10)

        except Exception as ex:
            logging.error(ex)
            print("failed to execute command")

    def send(self, payload):
        try:
            self.client.publish(self.topic, payload, qos=1)
            time.sleep(1)
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)
Exemplo n.º 12
0
class Influxdb:
    def __init__(self, token_type="Pi"):
        try:
            self.get_vars = GetVars()
            self.connection = False
            self.Messages = []
            """ check which device it is """
            if token_type == "Pi":
                self.token = self.get_vars.get_var("InfluxDB_Token_Pi")
            else:
                self.token = self.get_vars.get_var("InfluxDB_Token_Cloud")
            self.start()
        except Exception as ex:
            logging.error(ex)

    def start(self):
        try:
            self.bucket = self.get_vars.get_var("Bucket")
            self.org = self.get_vars.get_var("Org")
            self.client = InfluxDBClient(
                url=self.get_vars.get_var("InfluxDB_URL"), token=self.token)
            self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
            self.connection = True
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)

    def write_data(self, sensordata):
        try:
            fields = ""
            for i, data in enumerate(sensordata.data):
                """ Check if the value is a string """
                if isinstance(data.value, str):
                    data.value = f'"{data.value}"'
                """ Put the keys and values in a string """
                if i != 0:
                    fields += f",{data.key}={data.value}"
                else:
                    fields = f"{data.key}={data.value}"
            """ Put the row into the database """
            self.write_data_to_influxdb(sensordata.measurement,
                                        sensordata.host, fields,
                                        sensordata.timestamp)
            return True
        except Exception as ex:
            logging.error(ex)
            return False

    def write_data_to_influxdb(self, measurement, host, fields, timestamp):
        try:
            """ Convert the datatime to a timestamp in nanoseconds """
            #timestamp = int(datetime.timestamp()*1000000000)
            sequence = [f"{measurement},host={host} {fields} {timestamp}"]
            """ Push it into the influxDB cloud """
            self.write_api.write(self.bucket, self.org, sequence)
        except Exception as ex:
            logging.error(ex)
            raise ex

    def get_data(self, query_in, change_format=True, in_import=""):
        try:
            if change_format:
                query_in += ' |> pivot(rowKey:["_time"], columnKey: ["_field"], valueColumn: "_value")'
            query = f'{in_import} from(bucket: "{self.bucket}") {query_in}'
            results = self.client.query_api().query_data_frame(query,
                                                               org=self.org)
            return results
        except Exception as ex:
            logging.error(ex)
            raise Exception(ex)