Exemplo n.º 1
0
def setup_mqtt():
    try:
        m = Mqtt(MQTT_CLIENT_NAME, MQTT_BROKER)
        m.connect()
    except OSError as ose:
        logger.print_error("MQTT Setup Failed!")
        raise

    return m
Exemplo n.º 2
0
def main():
    # Fetch the arguments from command line
    args = build_argparser().parse_args()
    # Connect to the MQTT server and return MQTT client
    mqtt = Mqtt()
    mqtt.connect()
    # Perform inference on the input stream
    infer_on_stream(args, mqtt)
    mqtt.disconnect()
Exemplo n.º 3
0
def main():

    parametros = validacao_parametros()

    global mqtt
    global logs

    mqtt = Mqtt(parametros['broker'], parametros['user'],
                parametros['password'], parametros['topic'])
    logs = Logs(parametros['group'], parametros['stream'])

    scheduler = sched.scheduler(time.time, time.sleep)
    schedule_it(scheduler, int(parametros['messages']),
                int(parametros['seconds']), publisher)

    mqtt.connect()
    mqtt.client.loop_start()

    scheduler.run()

    mqtt.client.loop_stop()
    mqtt.client.disconnect()
Exemplo n.º 4
0
    def transform(self, data):
        if self.counter == 0:
            print('main_state: mqtt/up')
        config = data['config']

        broker_address = config.state['broker_address']
        device_name = config.state['device_name']
        main_topic = config.state['main_topic']
        mqtt = Mqtt(device_name, main_topic)
        if mqtt.connect(broker_address):
            data['mqtt_server'] = mqtt
            return 'main/loop_once'
        else:
            self.counter += 1
            if self.counter >= MAX_TRIES:
                config.delete()
                machine.reset()
Exemplo n.º 5
0
class Main:
    """
    Main class for full logic this program.
    Run this class by call 'main'
    """
    def __init__(self):
        self.wifi = Wifi(
            ssid=CONFIG["WIFI_SSID"],
            password=CONFIG["WIFI_PASSWORD"],
            gmt=CONFIG["GMT"],
        )
        self.mqtt = Mqtt(
            ip=CONFIG["MQTT_IP"],
            user=CONFIG["MQTT_USER"],
            password=CONFIG["MQTT_PASS"],
            keepalive=CONFIG["MQTT_KEEPALIVE"],
        )
        self.mqtt.set_last_will(
            topic=CONFIG["LW_TOPIC"],
            msg=ujson.dumps(CONFIG["LW_MSG_OFFLINE"]),
            retain=CONFIG["LW_RETAIN"],
            qos=CONFIG["LW_QOS"],
        )

        self.dht22 = DHT22(Pin(CONFIG["DHT22_PIN"]))
        self.is_sending_synchronizate = False

    def _send_data(self):
        """
        Meas dht22 data and publish temperature and humidity via mqtt.
        """
        try:
            local_time = localtime()[:-2]  # remove mili and micro seconds
            self.dht22.measure()  # important for take actual values
            temp = {
                "name": CONFIG["NAME_DEVICE"],
                "date": local_time,
                "value": str(self.dht22.temperature()),
            }
            hum = {
                "name": CONFIG["NAME_DEVICE"],
                "date": local_time,
                "value": str(self.dht22.humidity()),
            }
            self.mqtt.publish(CONFIG["TOPIC_TEMP"],
                              ujson.dumps(temp),
                              retain=True)
            self.mqtt.publish(CONFIG["TOPIC_HUM"],
                              ujson.dumps(hum),
                              retain=True)
        except Exception as ex:
            print("\t_send_data unable to send `{}`".format(ex))
            pass

    # Main loop
    def main(self):
        """
        Main loop.
        """
        start = ticks_ms()
        first_start = True  # defined for timing interval
        while True:
            sleep_ms(50)
            ######## WIFI CHECK
            if not self.wifi.is_connected():
                self.is_sending_synchronizate = False
                self.mqtt.disconnect()
                self.wifi.connect()  # infinity loop for connecting to wifi

            ######## MQTT CHECK
            if not self.mqtt.is_connected():
                self.is_sending_synchronizate = False

                if not self.mqtt.connect():
                    sleep(10)
                    continue
                else:
                    # on connect
                    self.mqtt.publish(
                        CONFIG["LW_TOPIC"],
                        ujson.dumps(CONFIG["LW_MSG_ONLINE"]),
                        retain=True,
                    )
            ######## INTERVAL & SEND DATA

            ### check sending data with synchro time
            if CONFIG["SYNC_SEND_DATA"]:
                # if synchronizate sending setted
                # waiting on whole minute with 0 seconds
                if not self.is_sending_synchronizate:
                    second = localtime()[5]
                    if second != 0:
                        # if not synchronizated
                        continue
                    self.is_sending_synchronizate = True

            #### Sending data
            # timing sending data this way is not the best solution
            # if you want excelent timig. Find better solution.
            diff = ticks_diff(ticks_ms(), start)  # ms
            if first_start or diff >= CONFIG["INTERVAL_SEND_DATA"] * 1000:
                first_start = False
                start = ticks_ms()
                self._send_data()
class Controller:
    #Safe box temperature minimum temperature
    min_temp = 20
    #Safe box temperature maximum temperature
    max_temp = 21
    #Safe box temperature
    current_in_temp = 0
    #Safe box humidity
    current_in_hum = 0
    #Air conditioner temperature change rate
    current_in_air_cond_state = 0
    #External temperature
    current_ex_temp = 0

    #Daily sensors sample
    daily_samples = list()

    #MQTT client
    mqtt = None

    #Path to application folder
    ROOT_PATH = "/home/franklin/Desktop/Projetos/pgcc008-problem01/web-application/"

    def __init__(self):
        #Starts and connect MQTT client to AWS MQTT Broker
        self.mqtt = Mqtt()
        self.mqtt.connect()

        #Stats loading data
        self.loadData()

    #Refresh all data readed to a new sample
    def refreshData(self):
        #Gets read time
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        #Data update check
        newData = False

        #Checks current internal temperature changes and updates
        if self.current_in_temp != self.mqtt.dataSubscribed[0]:
            self.current_in_temp = self.mqtt.dataSubscribed[0]
            print(
                "[SERVER at", current_time + "] Internal temperature: " +
                str(self.current_in_temp) + "C")
            newData = True

        #Checks current internal humidity changes and updates
        if self.current_in_hum != self.mqtt.dataSubscribed[1]:
            self.current_in_hum = self.mqtt.dataSubscribed[1]
            print(
                "[SERVER at", current_time + "] Internal humidity: " +
                str(self.current_in_hum) + "%")
            newData = True

        #Checks current internal air conditioner changes and updates
        if self.current_in_air_cond_state != self.mqtt.dataSubscribed[2]:
            self.current_in_air_cond_state = self.mqtt.dataSubscribed[2]
            if self.current_in_air_cond_state == 0.0:
                print("[SERVER at",
                      current_time + "] Air conditioning state: off")
            elif self.current_in_air_cond_state > 0.0:
                print(
                    "[SERVER at",
                    current_time + "] Air conditioning state: heating (" +
                    str(self.current_in_air_cond_state) + "C/min)")
            elif self.current_in_air_cond_state < 0.0:
                print(
                    "[SERVER at",
                    current_time + "] Air conditioning state: cooling (" +
                    str(self.current_in_air_cond_state) + "C/min)")
            newData = True

        #Checks current external temperature changes and updates
        if self.current_ex_temp != self.mqtt.dataSubscribed[3]:
            self.current_ex_temp = self.mqtt.dataSubscribed[3]
            print(
                "[SERVER at", current_time + "] External temperature: " +
                str(self.current_ex_temp) + "C")
            newData = True

        #Save a new daily sample
        sample = [
            current_time, self.current_in_temp, self.current_in_hum,
            self.current_in_air_cond_state, self.current_ex_temp
        ]
        self.saveData(sample)

        #Refresh graphs
        if newData == True or int(now.strftime("%S")) == 0:
            self.plotCharts()

    #Saves daily samples on a file
    def saveData(self, sample):
        today = date.today()
        current_date = today.strftime("%Y/%m/%d")

        #Path to daily samples file
        path = self.ROOT_PATH + "files/" + current_date.replace('/',
                                                                '-') + ".csv"

        #Starts a new daily sample file
        fileExists = True
        if not os.path.isfile(path):
            fileExists = False
            self.daily_samples = list()

        #Open daily sample file and write new sample
        with open(path, 'a') as file:
            file_writer = csv.writer(file)
            if fileExists is False:
                file_writer.writerow([
                    "time", "in_temp", "in_hum", "in_air_cond_state", "ex_temp"
                ])
            file_writer.writerow(sample)

        #Saves sample
        self.daily_samples.append(sample)

    #Load current daily samples if exists
    def loadData(self):
        today = date.today()
        day = today.strftime("%Y/%m/%d")

        #Path to daily samples file
        path = self.ROOT_PATH + "files/" + day.replace('/', '-') + ".csv"

        #Reads daily samples file and saves data on daily_samples list
        self.daily_samples = list()
        if os.path.isfile(path):
            with open(path, 'r') as file:
                file_reader = csv.reader(file)
                firstRead = True

                for row in file_reader:
                    if firstRead is True:
                        firstRead = False
                    else:
                        sample = [
                            row[0],
                            float(row[1]),
                            float(row[2]),
                            float(row[3]),
                            float(row[4])
                        ]
                        self.daily_samples.append(sample)

                nSamples = len(self.daily_samples)
                self.current_in_temp = self.daily_samples[nSamples - 1][1]
                self.current_in_hum = self.daily_samples[nSamples - 1][2]
                self.current_in_air_cond_state = self.daily_samples[nSamples -
                                                                    1][3]
                self.current_ex_temp = self.daily_samples[nSamples - 1][4]

                self.mqtt.dataSubscribed[0] = self.current_in_temp
                self.mqtt.dataSubscribed[1] = self.current_in_hum
                self.mqtt.dataSubscribed[2] = self.current_in_air_cond_state
                self.mqtt.dataSubscribed[3] = self.current_ex_temp

                #Plots chats
                self.plotCharts()

    #Plots chats
    def plotCharts(self):
        time_axis = list()
        in_temp_axis = list()
        in_hum_axis = list()
        in_air_cond_state_axis = list()
        ex_temp_axis = list()

        #current_time =
        #Creates multiple y-axis
        for sample in self.daily_samples:
            time_axis_sample = int(sample[0][0:2]) + float(
                (int(sample[0][3:5]) * 60) + int(sample[0][6:8])) / 3600.0
            time_axis.append(time_axis_sample)
            in_temp_axis.append(sample[1])
            in_hum_axis.append(sample[2])
            in_air_cond_state_axis.append(sample[3])
            ex_temp_axis.append(sample[4])

        #Plots all charts and save figure to show
        plt.plot(time_axis, in_temp_axis)
        plt.grid()
        plt.savefig(self.ROOT_PATH + "static/images/charts/in_temp.png",
                    transparent=True)
        plt.clf()

        plt.plot(time_axis, ex_temp_axis)
        plt.grid()
        plt.savefig(self.ROOT_PATH + "static/images/charts/ex_temp.png",
                    transparent=True)
        plt.clf()

        plt.plot(time_axis, in_hum_axis)
        plt.grid()
        plt.savefig(self.ROOT_PATH + "static/images/charts/in_hum.png",
                    transparent=True)
        plt.clf()

        plt.plot(time_axis, in_air_cond_state_axis)
        plt.grid()
        plt.savefig(self.ROOT_PATH +
                    "static/images/charts/in_air_cond_state.png",
                    transparent=True)
        plt.clf()

    #Increase or decrease minimum temperature
    def changeMinTemp(self, increase):
        confirmation = False
        if increase is True:
            #Checks relation between minimum and maximum temperatures.
            if (self.min_temp + 1) < self.max_temp:
                self.min_temp = self.min_temp + 1
                self.mqtt.publish("pgcc008/problem01/limit/min", self.min_temp)
                confirmation = True
        else:
            self.min_temp = self.min_temp - 1
            self.mqtt.publish("pgcc008/problem01/limit/min", self.min_temp)
            confirmation = True

        if confirmation is True:
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            print(
                "[SERVER at", current_time + "] Internal temperature range: " +
                str(self.min_temp) + " to " + str(self.max_temp) + "C")

        return confirmation

    #Increase or decrease maximum temperature
    def changeMaxTemp(self, increase):
        confirmation = False

        if increase is True:
            #Checks relation between minimum and maximum temperatures.
            self.max_temp = self.max_temp + 1
            self.mqtt.publish("pgcc008/problem01/limit/max", self.max_temp)
            confirmation = True
        else:
            if (self.max_temp - 1) > self.min_temp:
                self.max_temp = self.max_temp - 1
                self.mqtt.publish("pgcc008/problem01/limit/max", self.max_temp)
                confirmation = True

        if confirmation is True:
            now = datetime.now()
            current_time = now.strftime("%H:%M:%S")
            print(
                "[SERVER at", current_time + "] Internal temperature range: " +
                str(self.min_temp) + " to " + str(self.max_temp) + "C")

        return confirmation

    #Returns temperature on display format
    def getTempFormatted(self, variable):
        if variable == "MIN":
            temp = self.min_temp
        elif variable == "MAX":
            temp = self.max_temp
        elif variable == "IN_TEMP":
            temp = self.current_in_temp
        elif variable == "EX_TEMP":
            temp = self.current_ex_temp

        temp_form = str(int(temp)) + 'º'

        if temp >= 0 and temp < 10:
            temp_form = '0' + str(int(temp)) + 'º'

        return temp_form

    #Returns humidity on display format
    def getHumFormatted(self):
        hum_form = str(int(self.current_in_hum)) + '%'
        if self.current_in_hum >= 0 and self.current_in_hum < 10:
            hum_form = '0' + str(int(self.current_in_hum)) + '%'
        return hum_form

    #Returns air conditioner on display format
    def getAirCondState(self):
        air_cond_state_form = "DES"
        if self.current_in_air_cond_state > 0.0:
            air_cond_state_form = "AQU"
        if self.current_in_air_cond_state < 0.0:
            air_cond_state_form = "RES"
        return air_cond_state_form
Exemplo n.º 7
0
def mqttConnect():
    m = Mqtt(queue, con)
    m.connect()
Exemplo n.º 8
0
class States:
    #Safe box temperature
    current_in_temp = 20
    #Safe box humidity
    current_in_hum = 50
    #External temperature
    current_ex_temp = 20
    #Air conditioner temperature change rate
    air_cond_interaction = 0.0
    #Safe box temperature minimum temperature
    min_temp = 20
    #Safe box temperature maximum temperature
    max_temp = 21

    #MQTT client
    mqtt = None

    def __init__(self):
        #Gets args
        ap = argparse.ArgumentParser()
        ap.add_argument("-s",
                        "--simulated",
                        type=int,
                        help="simulated environment")
        args = vars(ap.parse_args())

        #Starts and connect MQTT client to AWS MQTT Broker
        self.mqtt = Mqtt()
        self.mqtt.connect()

        #Simulation case 1:
        #Internal temperature from NODEMCU
        #Internal humidity from potentiometer
        #Air conditioner from NODEMCU
        #External temperature from potentiometer
        if args["simulated"] == 1:
            self.internalSensor = SimulatedEnvironment(None)
            self.internalSensor.start()
            self.airCondControl = self.internalSensor
            self.externalSensor = self.internalSensor
        #Simulation case 2:
        #Internal temperature from NODEMCU
        #Internal humidity from DHT22
        #Air conditioner from NODEMCU
        #External temperature from DHT22
        elif args["simulated"] == 2:
            self.internalSensor = SimulatedEnvironment(Dht22(22))
            self.internalSensor.start()
            self.airCondControl = self.internalSensor
            self.externalSensor = Dht22(23)
            self.externalSensor.start()
        #Simulation case 3:
        #Internal temperature from DHT22(1)
        #Internal humidity from DHT22(1)
        #Air conditioner from NODEMCU
        #External temperature from DHT22(2)
        else:
            self.internalSensor = Dht22(22)
            self.internalSensor.start()
            self.airCondControl = SimulatedEnvironment(None)
            self.airCondControl.start()
            self.externalSensor = Dht22(23)
            self.externalSensor.start()

        #Read initial data from sensors
        self.current_in_temp = self.internalSensor.read("IN_TEMP")
        self.current_in_hum = self.internalSensor.read("IN_HUM")
        self.current_ex_temp = self.externalSensor.read("EX_TEMP")

        #Publish initial data on respective topics
        self.mqtt.publish("pgcc008/problem01/sensor/internal/temperature",
                          self.current_in_temp)
        self.mqtt.publish("pgcc008/problem01/sensor/internal/humidity",
                          self.current_in_hum)
        self.mqtt.publish("pgcc008/problem01/sensor/internal/air_cond_state",
                          self.air_cond_interaction)
        self.mqtt.publish("pgcc008/problem01/sensor/external/temperature",
                          self.current_ex_temp)
        print("[DEVICE] Control System started")

    #Reads all sensors
    def readSensors(self):
        #Gets read time
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        #Checks update on temperature range and change this range.
        newRange = False
        #Minimum
        newData = self.mqtt.dataSubscribed[0]
        if newData != self.min_temp:
            self.min_temp = newData
            newRange = True
        #Maximum
        newData = self.mqtt.dataSubscribed[1]
        if newData != self.max_temp:
            self.max_temp = newData
            newRange = True

        if newRange is True:
            print(
                "[DEVICE at", current_time + "] Internal temperature range: " +
                str(self.min_temp) + " to " + str(self.max_temp) + "C")

        #Checks internal temperature change, updates and publish on topic
        next_in_temp = self.internalSensor.read("IN_TEMP")
        if next_in_temp != self.current_in_temp:
            self.current_in_temp = next_in_temp
            self.mqtt.publish("pgcc008/problem01/sensor/internal/temperature",
                              self.current_in_temp)
            print(
                "[DEVICE at", current_time + "] Internal temperature: " +
                str(self.current_in_temp) + "C")

        #Checks internal humidity change, updates and publish on topic
        next_in_hum = self.internalSensor.read("IN_HUM")
        if next_in_hum != self.current_in_hum:
            self.current_in_hum = next_in_hum
            self.mqtt.publish("pgcc008/problem01/sensor/internal/humidity",
                              self.current_in_hum)
            print(
                "[DEVICE at", current_time + "] Internal humidity: " +
                str(self.current_in_hum) + "%")

        #Checks external temperature change, updates and publish on topic
        next_ex_temp = self.externalSensor.read("EX_TEMP")
        if next_ex_temp != self.current_ex_temp:
            self.current_ex_temp = next_ex_temp
            self.mqtt.publish("pgcc008/problem01/sensor/external/temperature",
                              self.current_ex_temp)
            print(
                "[DEVICE at", current_time + "] External temperature: " +
                str(self.current_ex_temp) + "C")

    #Sends air conditioner command
    def sendAirCondCommand(self, command):
        now = datetime.now()
        current_time = now.strftime("%H:%M:%S")

        previous_cond_interaction = self.air_cond_interaction
        air_cond_change_rate = 0.0

        #Checks command to heating safe box
        if command == "heating":
            #Calculates Heating rate (minmum = 0.1C/min)
            air_cond_change_rate = 1 - (
                (self.current_in_temp - self.current_ex_temp) * 0.05)
            if air_cond_change_rate < 0.0:
                air_cond_change_rate = 0.1

        #Calculates Cooling rate (maximum = -0.1C/min)
        elif command == "cooling":
            air_cond_change_rate = 1 - (
                (self.current_ex_temp - self.current_in_temp) * 0.05)
            air_cond_change_rate = -air_cond_change_rate
            if air_cond_change_rate > 0.0:
                air_cond_change_rate = -0.1

        self.air_cond_interaction = float('%.2f' % air_cond_change_rate)

        #Checks change on cooling or heating rate, sends command to change temperature and publish on topic
        if previous_cond_interaction != self.air_cond_interaction:
            self.airCondControl.write(str(self.air_cond_interaction))
            print(
                "[DEVICE at", current_time + "] Air conditioner state: " +
                command + " (" + str(self.air_cond_interaction) + "C/min)")
            self.mqtt.publish(
                "pgcc008/problem01/sensor/internal/air_cond_state",
                self.air_cond_interaction)

    #Finishs application
    def stop(self):
        #Turn off air conditioner
        self.sendAirCondCommand("off")
        #Stop all sensors
        self.internalSensor.stopRead()
        self.externalSensor.stopRead()
        self.airCondControl.stopRead()
        #Closes connection with MQTT broker
        self.mqtt.disconnect()