Esempio n. 1
0
def prosesIOT():

    print('IoT\n')
    clientthingsboard = TBDeviceMqttClient("202.46.7.33", "TEWSSiporaPower")
    clientthingsboard.connect()
    while True:
        if (powerDataQueue.empty() == False):

            #get data queue
            lock.acquire()
            powerdata = powerDataQueue.get()
            lock.release()

            #send to RDS
            #clientRDS = client()
            #payload = str(xdata) + ',' + str(ydata) + ',' + str(zdata)
            #clientRDS.setBrokerParameter("202.46.3.41",1883, userName="******", password="******")
            #clientRDS.publishData(payload, "node/sensor/siberut/accelerometer", sensorType=1, qosValue=1)

            #send to thingsboard
            telemetry_with_ts = {
                "ts": int(round(time.time() * 1000)),
                "values": {
                    "volt1": float(powerdata),
                    "volt2": float(powerdata)
                }
            }
            clientthingsboard.send_telemetry(telemetry_with_ts)

    clientthingsboard.disconnect()
Esempio n. 2
0
def tb_client_start(telemetries, token):
    logging.basicConfig(
        filename=token + '_app.log',
        filemode='w',
        format='%(asctime)s : %(levelname)s : %(name)s : %(message)s',
        level=logging.INFO)
    client = TBDeviceMqttClient(mqtt_host, token)
    client.max_inflight_messages_set(50)
    client.connect()
    # logging.info("connect device: ", token)
    for telemetry in telemetries:
        logging.info("send telemetry: {0} for device with token: {1}".format(
            telemetries.index(telemetry), token))
        client.send_telemetry(telemetry)
        time.sleep(delay)
        # Sending telemetry and checking the delivery status (QoS = 1 by default)
        result = client.send_telemetry(telemetry)
        logging.debug(
            "results of client.send_telemetry(telemetry): {}".format(result))
        # get is a blocking call that awaits delivery status
        # success = result.get() == TBPublishInfo.TB_ERR_SUCCESS
        # if (success):
        #     # print("Success")
        #     logging.info("message sent successfully:{0} ".format(success))
        # else:
        #     logging.error("MQTT Failure: {0}".format(result))
    # Disconnect from ThingsBoard
    client.disconnect()
    # logging.info("all thread: ", threading.enumerate())
    global all_done
    all_done = True
def hello(event, context):


    telemetry = []

    for result in event['Records']:
        base64_message = result['kinesis']['data']
        base64_bytes = base64_message.encode('ascii')
        message_bytes = base64.b64decode(base64_bytes)
        message = message_bytes.decode('ascii')

        message = json.loads(message)

        if message['heat_index'] != 0:
            celsius  = (message['heat_index'] - 32) / 1.8

            if celsius <= 27.0:
                message['warning'] = "Normal"
            elif celsius >= 27.0 and celsius <= 32.0:
                message['warning'] = "Caution"
            elif  celsius >= 32.1 and celsius <= 41.0:
                message['warning'] = "Extreme caution"
            elif celsius >= 41.1 and celsius <= 54.0:
                message['warning'] = "Danger"
            else:
                message['warning'] = "Extreme danger"

            message['heat_index'] = celsius


        else:
            message['warning'] = "Normal"
        telemetry.append(message)

    print(telemetry)

    try:
        #telemetry = [{"uf": "fd","index": 20.5}, {"uf": "df","index": 110.5}]
        client = TBDeviceMqttClient("demo.thingsboard.io", "ONISUjegn6ndL5GBIHNf")
        client.connect()

        for station in telemetry:
            print(station)
            result = client.send_telemetry(station)
            #print(result)
            success = result.get() == TBPublishInfo.TB_ERR_SUCCESS
            #print(success)
        client.disconnect()



    except:
        print("Unable to send telemetry")

    # serverless invoke local --function hello
Esempio n. 4
0
import time
from tb_device_mqtt import TBDeviceMqttClient, TBPublishInfo

telemetry = {"Attribute": 41.9, "enabled": False, "Gideon Status": "Yesn't"}

# Timer start counting from connecting
start_time = time.time()
#Please dont change this IP address and Token
client = TBDeviceMqttClient("129.126.163.157", "TrafficController")

client.connect()
client.send_telemetry(telemetry)
result = client.send_telemetry(telemetry)
success = result.get() == TBPublishInfo.TB_ERR_SUCCESS

client.disconnect()
print("--- %s seconds ---" % (time.time() - start_time))
Esempio n. 5
0
def parse_msg(msg):
    print("MSG: ", msg)
    # print(msg.split(";"))
    telemetry = {}
    # msg = "1060;003368;2;20;1;22;220;05:46:52 IST 05/21/2019;00:06:8E:03:57:0B;0;0;0000020F000000000000000000000000;26"
    if (msg.strip().split(";")[0] == "1060" and msg.strip() != ""):
        if (msg.split(";")[4] == "1" and msg.split(";")[5] == "22"):
            print("MSG Inside: ", msg)
            telemetry["eventid"] = msg.split(";")[0]
            telemetry["msgid"] = msg.split(";")[1]
            telemetry["eventmessagetype"] = msg.split(";")[2]
            telemetry["classcode"] = msg.split(";")[3]
            telemetry["taskcode"] = msg.split(";")[4]
            telemetry["eventcode"] = msg.split(";")[5]
            telemetry["priority"] = msg.split(";")[6]
            telemetry["msgtime"] = msg.split(";")[7]
            telemetry["macaddr"] = msg.split(";")[8]
            telemetry["Interface  Adddress"] = msg.split(";")[9]
            telemetry["Reader  Adddress"] = msg.split(";")[10]
            telemetry["Card Number "] = msg.split(";")[11]
            telemetry["Card byte "] = msg.split(";")[12]
            # telemetry = {"temperature": 41.9, "enabled": False, "currentFirmwareVersion": "v1.2.2"}
            client = TBDeviceMqttClient("dev.dataexchange.io",
                                        "JUSf1I0L3cGBTskcTDgw")
            # Connect to ThingsBoard
            client.connect()
            # Sending telemetry without checking the delivery status
            client.send_telemetry(telemetry)
            # Sending telemetry and checking the delivery status (QoS = 1 by default)
            result = client.send_telemetry(telemetry)
            # get is a blocking call that awaits delivery status
            success = result.get() == TBPublishInfo.TB_ERR_SUCCESS
            print("MESSAGE SENT: ", success)
            print(success)
            # Disconnect from ThingsBoard
            client.disconnect()
        elif (msg.strip().split(";")[0] == "1060" and msg.strip() != ""):
            if (msg.split(";")[4] == "2" and msg.split(";")[5] == "20"):
                print("MSG Inside: ", msg)
                telemetry["eventid"] = msg.split(";")[0]
                telemetry["msgid"] = msg.split(";")[1]
                telemetry["eventmessagetype"] = msg.split(";")[2]
                telemetry["classcode"] = msg.split(";")[3]
                telemetry["taskcode"] = msg.split(";")[4]
                telemetry["eventcode"] = msg.split(";")[5]
                telemetry["priority"] = msg.split(";")[6]
                telemetry["msgtime"] = msg.split(";")[7]
                telemetry["macaddr"] = msg.split(";")[8]
                telemetry["Interface  Adddress"] = msg.split(";")[9]
                telemetry["Reader  Adddress"] = msg.split(";")[10]
                telemetry["Card Number "] = msg.split(";")[11]
                # telemetry = {"temperature": 41.9, "enabled": False, "currentFirmwareVersion": "v1.2.2"}
                client = TBDeviceMqttClient("dev.dataexchange.io",
                                            "JUSf1I0L3cGBTskcTDgw")
                # Connect to ThingsBoard
                client.connect()
                # Sending telemetry without checking the delivery status
                client.send_telemetry(telemetry)
                # Sending telemetry and checking the delivery status (QoS = 1 by default)
                result = client.send_telemetry(telemetry)
                # get is a blocking call that awaits delivery status
                success = result.get() == TBPublishInfo.TB_ERR_SUCCESS
                print("MESSAGE SENT: ", success)
                print(success)
                # Disconnect from ThingsBoard
                client.disconnect()
Esempio n. 6
0
def main():

    # Grove - Servo connected to PWM port
    servo = GroveServo(12)
    servo_angle = 90

    # Grove - mini PIR motion pir_sensor connected to port D5
    pir_sensor = GroveMiniPIRMotionSensor(5)

    # Grove - Ultrasonic Ranger connected to port D16
    ultrasonic_sensor = GroveUltrasonicRanger(16)

    # Grove - LED Button connected to port D18
    button = GroveLedButton(18)

    # Grove - Moisture Sensor connected to port A0
    moisture_sensor = GroveMoistureSensor(0)

    # Grove - Light Sensor connected to port A2
    light_sensor = GroveLightSensor(2)
    light_state = False

    # Grove - Temperature&Humidity Sensor connected to port D22
    dht_sensor = DHT('11', 22)

    # Callback for server RPC requests (Used for control servo and led blink)
    def on_server_side_rpc_request(request_id, request_body):
        log.info('received rpc: {}, {}'.format(request_id, request_body))
        if request_body['method'] == 'getLedState':
            client.send_rpc_reply(request_id, light_state)
        elif request_body['method'] == 'setLedState':
            light_state = request_body['params']
            button.led.light(light_state)
        elif request_body['method'] == 'setServoAngle':
            servo_angle = float(request_body['params'])
            servo.setAngle(servo_angle)
        elif request_body['method'] == 'getServoAngle':
            client.send_rpc_reply(request_id, servo_angle)

    # Connecting to ThingsBoard
    client = TBDeviceMqttClient(thingsboard_server, access_token)
    client.set_server_side_rpc_request_handler(on_server_side_rpc_request)
    client.connect()

    # Callback on detect the motion from motion sensor
    def on_detect():
        log.info('motion detected')
        telemetry = {"motion": True}
        client.send_telemetry(telemetry)
        time.sleep(5)
        # Deactivating the motion in Dashboard
        client.send_telemetry({"motion": False})
        log.info("Motion alert deactivated")

    # Callback from button if it was pressed or unpressed
    def on_event(index, event, tm):
        if button._GroveLedButton__btn.is_pressed():
            log.debug('button: single click')
            telemetry = {"button_press": True}
            client.send_telemetry(telemetry)
            log.info("Pressed")
        else:
            log.debug('button: single click')
            telemetry = {"button_press": False}
            client.send_telemetry(telemetry)
            log.info("Unpressed")
        if event & Button.EV_SINGLE_CLICK:
            button.led.light(True)
        elif event & Button.EV_DOUBLE_CLICK:
            button.led.blink()
        elif event & Button.EV_LONG_PRESS:
            button.led.light(False)

    # Adding the callback to the motion sensor
    pir_sensor.on_detect = on_detect
    # Adding the callback to the button
    button.on_event = on_event
    try:
        while True:
            distance = ultrasonic_sensor.get_distance()
            log.debug('distance: {} cm'.format(distance))

            humidity, temperature = dht_sensor.read()
            log.debug('temperature: {}C, humidity: {}%'.format(
                temperature, humidity))

            moisture = moisture_sensor.moisture
            log.debug('moisture: {}'.format(moisture))

            log.debug('light: {}'.format(light_sensor.light))

            # Formatting the data for sending to ThingsBoard
            telemetry = {
                'distance': distance,
                'temperature': temperature,
                'humidity': humidity,
                'moisture': moisture,
                'light': light_sensor.light
            }

            # Sending the data
            client.send_telemetry(telemetry).get()

            time.sleep(.1)
    except Exception as e:
        raise e
    finally:
        client.disconnect()
Esempio n. 7
0
def main():

    #declaration des ports temperature
    temp_meteo_1 = 2
    temp_meteo_2 = 3
    temp_meteo_3 = 4
    temp_meteo_4 = 5
    temp_piece = 6
    temp_exte = 16
    #declaration des ports relais
    chauffe_meteo = 8
    chauffe_piece = 15
    ventilateur = 14
    grovepi.pinMode(chauffe_meteo, "OUTPUT")
    grovepi.pinMode(chauffe_piece, "OUTPUT")
    grovepi.pinMode(ventilateur, "OUTPUT")

    #declaration led
    led = 7
    count = 4
    grovepi.pinMode(led, "OUTPUT")
    grovepi.analogWrite(led, 255)

    #déclaration des différents états à gérer
    #état des chauffages
    ChauffePieceState = False
    ChauffeMeteoState = False
    #etat des ventilateurs
    VentilateurState = False
    #etat des modes de chauffages
    MeteoAutoState = False
    PieceAutoState = False

    # Définition de la fonction servant à gérer les RPC (remote prcedure calls) entre l'interface et le rapsberry
    def on_server_side_rpc_request(request_id, request_body):
        #on affiche en log le rpc reçu
        log.info('received rpc: {}, {}'.format(request_id, request_body))
        #get et set du chauffage de la piéce
        if request_body['method'] == 'getChauffePieceState':
            client.send_rpc_reply(request_id, ChauffePieceState)
        elif request_body['method'] == 'setChauffePieceState':
            ChauffePieceState = request_body['params']
            grovepi.digitalWrite(chauffe_piece, ChauffePieceState)
        #get et set du chauffage de la météo
        elif request_body['method'] == 'setChauffeMeteoState':
            ChauffeMeteoState = request_body['params']
            grovepi.digitalWrite(chauffe_meteo, ChauffeMeteoState)
        elif request_body['method'] == 'getChauffeMeteoState':
            client.send_rpc_reply(request_id, ChauffeMeteoState)
        #get et set de l'activation des ventilateurs
        elif request_body['method'] == 'setVentilateurState':
            VentilateurState = request_body['params']
            grovepi.digitalWrite(ventilateur, VentilateurState)
        elif request_body['method'] == 'getVentilateurState':
            client.send_rpc_reply(request_id, VentilateurState)
        #get et set des modes de chauffages piéce et météo
        elif request_body['method'] == 'getMeteoAutoState':
            client.send_rpc_reply(request_id, MeteoAutoState)
        elif request_body['method'] == 'setMeteoAutoState':
            MeteoAutoState = request_body['params']
        elif request_body['method'] == 'getPieceAutoState':
            client.send_rpc_reply(request_id, PieceAutoState)
        elif request_body['method'] == 'setPieceAutoState':
            PieceAutoState = request_body['params']

    # Connection à Thingsboard
    client = TBDeviceMqttClient(thingsboard_server, access_token)
    client.set_server_side_rpc_request_handler(on_server_side_rpc_request)
    client.connect()

    #fonction retournant un dictionnaire avec toutes les temperatures
    def getTemperatures():
        Temperatures = {}
        Temperatures['TemperatureMeteo1'] = grovepi.dht(temp_meteo_1, 1)[0]
        if isnan(Temperatures['TemperatureMeteo1']):
            Temperatures['TemperatureMeteo1'] = 0
        Temperatures['TemperatureMeteo2'] = grovepi.dht(temp_meteo_2, 1)[0]
        if isnan(Temperatures['TemperatureMeteo2']):
            Temperatures['TemperatureMeteo2'] = 0
        Temperatures['TemperatureMeteo3'] = grovepi.dht(temp_meteo_3, 1)[0]
        if isnan(Temperatures['TemperatureMeteo3']):
            Temperatures['TemperatureMeteo3'] = 0
        Temperatures['TemperatureMeteo4'] = grovepi.dht(temp_meteo_4, 1)[0]
        if isnan(Temperatures['TemperatureMeteo4']):
            Temperatures['TemperatureMeteo4'] = 0
        #moyenne des Températures extérieures
        TemperatureMoyenneMeteo = mean([
            Temperatures.get('TemperatureMeteo1'),
            Temperatures.get('TemperatureMeteo2'),
            Temperatures.get('TemperatureMeteo3'),
            Temperatures.get('TemperatureMeteo4')
        ])
        Temperatures['TemperatureMoyenneMeteo'] = TemperatureMoyenneMeteo
        if isnan(Temperatures['TemperatureMoyenneMeteo']):
            Temperatures['TemperatureMoyenneMeteo'] = 0
        Temperatures['TemperaturePiece'] = grovepi.dht(temp_piece, 1)[0]
        if isnan(Temperatures['TemperaturePiece']):
            Temperatures['TemperaturePiece'] = 0
        Temperatures['TemperatureExte'] = grovepi.dht(temp_exte, 1)[0]
        if isnan(Temperatures['TemperatureExte']):
            Temperatures['TemperatureExte'] = 0
        return Temperatures

    #fonbction qui permet de déterminer l'état de chauffage nécessaire dans la piéce
    def HotOrColdPiece(TemperaturePiece):
        etat = False
        #ouverture du CSV
        CsvPiece = open("/home/pi/GrovePi/YES/automatisation/piece.csv", "r+")
        reader = csv.reader(CsvPiece)
        i = 0
        for row in reader:
            #si On est à la premiére itération on regarde le mode de chauffage
            if i == 1:
                mode = row[0]
                log.info(mode)
            if i >= 1:
                #Si on est en monde conventionnel on récupére les créneux en les transformant
                #en format datetime.datetime.time(), on regarde si l'heure actuelle appartient à ce créneau
                #si c'est le cas on regarde la température nécessaire dans ce créneau et on en déduit l'état du
                #chauffage
                if mode == 'conv':
                    debut = datetime.datetime.strptime(row[1],
                                                       '%H:%M:%S').time()
                    fin = datetime.datetime.strptime(row[2], '%H:%M:%S').time()
                    if debut <= datetime.datetime.now().time() <= fin:
                        log.info('bon créneau')
                        if TemperaturePiece > int(row[3]):
                            etat = False
                        else:
                            etat = True
                        break
                #En mode smart on récupérer seulement l'état rentré du côté Matlab dans la derniére colonne du CSV
                if mode == "smart":
                    if int(row[4]) == 1:
                        etat = True
                    else:
                        etat = False
                    break
            i = i + 1

        CsvPiece.close()
        return etat

    #fonction qui génére l'état de la météo de maniére aléatoire
    def HotOrColdMeteo(TemperatureMoyenneMeteo):
        etat = random.choice((True, False))
        return etat

    try:
        while True:
            #Obtention de toutes les données nécessaires
            Telemetry = getTemperatures()
            #si le chuffage de la piéce est en mode auto on génére l'état de la résistance grace à la fonction prédéfinie
            if PieceAutoState:
                print('mode auto')
                grovepi.digitalWrite(
                    chauffe_piece,
                    HotOrColdPiece(Telemetry['TemperaturePiece']))
            #Si le chauffage de la météo est en mode auto on génére l'état des résistances et des ventilateurs en fonction de lma fonction prédéfinie
            if MeteoAutoState:
                if HotOrColdMeteo(Telemetry['TemperatureMoyenneMeteo']):
                    grovepi.digitalWrite(chauffe_meteo, True)
                    grovepi.digitalWrite(ventilateur, False)
                else:
                    grovepi.digitalWrite(chauffe_meteo, False)
                    grovepi.digitalWrite(ventilateur, True)

            log.info(Telemetry)
            #On envoie les données de telpératures à Thingsboard
            client.send_telemetry(Telemetry).get()
            #On crée la nouvelle ligne qui sera insérée dans le CSV
            ligne = [0, 0, 0, 0, 0, 0, 0, 0]
            ligne[0] = str(datetime.datetime.now())
            ligne[1] = str(Telemetry['TemperatureMeteo1'])
            ligne[2] = str(Telemetry['TemperatureMeteo2'])
            ligne[3] = str(Telemetry['TemperatureMeteo3'])
            ligne[4] = str(Telemetry['TemperatureMeteo4'])
            ligne[5] = str(Telemetry['TemperatureMoyenneMeteo'])
            ligne[6] = str(Telemetry['TemperaturePiece'])
            ligne[7] = str(Telemetry['TemperatureExte'])
            f = open(
                '/home/pi/Desktop/DataTemperatures/' +
                datetime.datetime.now().strftime('%d:%m:%y') + '-dataTemp.csv',
                'a')
            writer = csv.writer(f)
            writer.writerow(ligne)
            log.info('written in csv')
            f.close()

            #condition sécuritaire si la température dépasse les 60 on quitte la boucle et va directeent au finally ou les actionneurs sont arretes
            if Telemetry["TemperatureMoyenneMeteo"] >= 60 or Telemetry[
                    "TemperaturePiece"] >= 60:
                break
            #Ici on décide tous les combien de temps la prise de température doit être faite ainsi que l'actvation ou non des chauffages
            time.sleep(2)

    except Exception as e:
        raise e
        log.warning(e)
    finally:
        log.info("client disconnect")
        client.disconnect()
        grovepi.digitalWrite(chauffe_piece, False)
        grovepi.digitalWrite(chauffe_meteo, False)
        grovepi.digitalWrite(ventilateur, True)
Esempio n. 8
0
class SendAiDetections:
    """
    Sends JSON representation of Ai Object Detections
    """
    def __init__(self, tot_cams):
        self.json_dict = \
            {
                "dnn_inference_device":
                    {
                        "sbc_id": "ZARGAU00020000010001",
                        "sbc_name": "Intel UP Squared",
                        "sbc_ie_details":
                            {
                                "vpu_device id": "0",
                                "vpu_device name": "MYRIAD 2",
                                "model_id": "0",
                                "model_name": "MobilenetSSD",
                                "model_detection_details":[]
                                #[
                                #{
                                #   "capture_id": "0",
                                #   "zone_id": "0",
                                #   "classification": "null",
                                #   "probability": "00.00",
                                #   "bb_coordinates": ["0","0","0","0"]
                                #},
                                #{
                                #  "capture_id": "0",
                                #  "zone_id": "0",
                                #  "classification": "person",
                                #  "probability": "65.21",
                                #  "bb_coordinates": ["100","50","170","101"]
                                #}
                                #]
                            }
                    }
            }

        self.total_cams = tot_cams
        # Telemetry buffer
        self.telemetry_buf_max = 100
        self.telemetry_buf = []
        # Create a dictionary list of the total number of dnn_detector streams
        self.json_dict_list = []
        for i in range(self.total_cams):
            self.json_dict_list.append(self.json_dict)

        self.send_buffer = []
        self.reset_buffer()
        self.stopped = False
        self.name = "JSON message sender"

        self.tb_telemetry = False
        if settings.TB_CONNECT:
            try:
                self.tb_client = TBDeviceMqttClient(settings.TB_URL, settings.TB_TOKEN)
                self.tb_client.connect()
                self.tb_telemetry = True
                log = "TB connected!"
                logging.info(log)
                print("[", colored("INFO", 'green', attrs=['bold']), "   ] " + log)
            except Exception as e:
                print("[", colored("ERROR", 'red', attrs=['bold']), "  ] TB connection failed: ", str(e))

    def start(self):
        t = Thread(target=self.update, name=self.name, args=())
        t.daemon = True
        t.start()
        log = "message sender started"
        logging.info(log)
        print("[", colored("INFO", 'green', attrs=['bold']), "   ] " + log)

        return self

    def stop(self):
        self.stopped = True

    def update(self):
        prctl.set_name("E:T Message JSON Sender")
        while True:
            # Send update over socket every second
            time.sleep(1)

            if self.stopped:
                log = "message sender has stopped"
                logging.info(log)
                print("[", colored("INFO", 'green', attrs=['bold']), "   ] " + log)
                #self.sock0.shutdown(socket.SHUT_RDWR)
                #self.sock0.detach()

                if settings.TB_CONNECT:
                    try:
                        self.tb_client.disconnect()
                        log = "disconnecting mqtt clients"
                        logging.info(log)
                        print("[", colored("INFO", 'green', attrs=['bold']), "   ] " + log)

                    except Exception as e:
                        print("[", colored("ERROR", 'red', attrs=['bold']), "  ] TB disconnect failed: ", str(e))

                return

            if settings.JP_SOCK:
                self.send_json()

            if self.tb_telemetry:
                self.send_telemetry()

    def create_socket(self):
        # Create sockets
        self.sock0 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)         # Create a socket object
        # Connect the socket to the port where the server is listening
        server_address_0 = ('127.0.0.1', 55001)
        #connection = ('%s port %s ' % server_address_0)
        #print("[", colored("INFO", 'green', attrs=['bold']), "   ] connecting to ", connection)
        try:
            self.sock0.connect(server_address_0)
            connected = True
        except socket.error as msg:
            #log = "socket failed: ", str(msg)"
            #logging.error(log)
            print("[", colored("ERROR", 'red', attrs=['bold']), "  ] socket failed: ", str(msg))
            connected = False

        return connected

    def send_json(self):
        if self.create_socket():
            time.sleep(0.1)
            for i in range(len(self.json_dict_list)):
                # Dumps = dict->str, Loads= str->dict
                #packet = ast.literal_eval(send_buffer[x])
                #send_packet = json.dumps(packet)
                send_packet = json.dumps(self.json_dict_list[i])
                try:
                    self.sock0.send(send_packet.encode())
                    time.sleep(0.12)
                except socket.error as msg:
                    #log = "socket failed: ", str(msg)
                    #logging.error(log)
                    print("[", colored("ERROR", 'red', attrs=['bold']), "  ] socket failed: ", str(msg))

        self.sock0.close()

    def send_telemetry(self):
        if self.telemetry_buf:
            while self.telemetry_buf:
                send_packet = self.telemetry_buf[0]
                try:
                    # Sending telemetry
                    result = self.tb_client.send_telemetry(send_packet)

                    # Checking the delivery status (QoS = 1 by default)
                    # get is a blocking call that awaits delivery status
                    # success = result.get() == TBPublishInfo.TB_ERR_SUCCESS
                    # if success:
                    #     log = "Telemetry data success"
                    #     logging.info(log)
                    #     print("[", colored("INFO", 'green', attrs=['bold']), "   ] " + log)

                    time.sleep(0.12)

                except Exception as e:
                    log = "Telemetry send failed: ", str(e)
                    logging.error(log)
                    print("[", colored("ERROR", 'red', attrs=['bold']), "  ] ", str(log))

                self.telemetry_buf.pop(0)
        else:
            # If no data, send a keep-alive timestamp
            send_packet = dict(ts=int(time.time() * 1000.0))
            self.tb_client.send_telemetry(send_packet)

    def add_to_buffer(self, dictionary, position=0):
        #self.send_buffer[position] = dictionary
        self.json_dict_list[position] = dictionary
        if len(self.telemetry_buf) < self.telemetry_buf_max:
            self.telemetry_buf.insert(0, dictionary)

    def reset_buffer(self):
        for i in range(len(self.json_dict_list)):
            dictionary = \
                {
                    "dnn_inference_device":
                        {
                            "sbc_id": "ZARGAU00020000010001",
                            "sbc_name": "Intel UP Squared",
                            "sbc_ie_details":
                                {
                                    "vpu_device id": "0",
                                    "vpu_device name": "MYRIAD 2",
                                    "model_id": "0",
                                    "model_name": "MobilenetSSD",
                                    "model_detection_details": []
                                }
                        }
                }

            dict_array = []
            dict_array.append(dict(capture_id=str(i), zone_id="0", classification=None,
                                   probability="0.00", bb_coordinates=["0", "0", "0", "0"]))
            dictionary["dnn_inference_device"]["sbc_ie_details"]["model_detection_details"] = dict_array
            # Convert dictionary to string otherwise capture id will not increment in the array
            self.json_dict_list[i] = dictionary

    """
    def reset_buffer(self):
      self.send_buffer = []
      for cams in range(self.total_cams):      
        dictionary = self.json_dict
        dict_array = []
        dict_array.append(dict(capture_id=str(cams), zone_id="0", classification=None,
                               probability="0.00", bb_coordinates=["0","0","0","0"]))
        dictionary["dnn_inference_device"]["sbc_ie_details"]["model_detection_details"] = dict_array
        # Convert dictionary to string otherwise capture id will not increment in the array
        self.send_buffer.append(str(dictionary))  
    """

    def close_socket(self):
        self.sock0.close()
Esempio n. 9
0
def main():

    # Particulate Matter
    PLANTOWER = plantower.Plantower(port=USB_DEVICE_1)
    print("Making sure it's correctly setup for active mode. Please wait")
    #make sure it's in the correct mode if it's been used for passive beforehand
    #Not needed if freshly plugged in
    PLANTOWER.mode_change(
        plantower.PMS_ACTIVE_MODE)  #change back into active mode
    PLANTOWER.set_to_wakeup()  #ensure fan is spinning

    # Renology Wanderer 10A Charge Controller
    rover = RenogyRover(USB_DEVICE_2, 1)

    # BME 280 Temp, Humidity, Pressure
    port = 1
    address = 0x77  # Adafruit BME280 address. Other BME280s may be different
    bus = smbus2.SMBus(port)
    bme280.load_calibration_params(bus, address)

    # delay 30 seconds to warmup devices
    print('30 second warmup....')
    time.sleep(30)
    print('30 second warmup done....')

    telemetry = {
        "pm_10": 'not set',
        "pm_2_5": 'not set',
        "pm_1_0": 'not set',
        "ambient_humidity": 'not set',
        "ambient_pressure": 'not set',
        "ambient_temperature": 'not set',
        "wind_speed": 'not set',
        "wind_gust": 'not set',
        "wind_direction": 'not set',
        "rainfall": 'not set',
        "battery_percentage": 'not set',
        "battery_type": 'not set',
        "battery_capacity": 'not set',
        "battery_voltage": 'not set',
        "battery_temperature": 'not set',
        "controller_model": 'not set',
        "controller_charging_status": 'not set',
        "controller_temperature": 'not set',
        "load_voltage": 'not set',
        "load_current": 'not set',
        "load_power": 'not set',
        "solar_voltage": 'not set',
        "solar_current": 'not set',
        "solar_power": 'not set',
        "power_generation_today": 'not set',
        "charging_amp_hours_today": 'not set',
        "discharging_amp_hours_today": 'not set'
    }

    #MQTT ~~~~
    config = configparser.ConfigParser()
    config.read("config.ini")
    THINGSBOARD_HOST = config.get("thingsboard", "host")
    ACCESS_TOKEN = config.get("thingsboard", "token")

    #SSL Cert locations
    CA_CERTS = ''
    CERT_FILE = ''
    KEY_FILE = ''

    # Set access token
    client = TBDeviceMqttClient(THINGSBOARD_HOST, ACCESS_TOKEN)

    # Connect to ThingsBoard
    client.connect()

    # Data capture and upload interval in seconds. Less interval will eventually hang the DHT22.
    INTERVAL = 1
    AVG_INTERVAL = 60
    next_reading = time.time()
    # Lists for averages
    pm_1_0_list = []
    pm_2_5_list = []
    pm_10_list = []

    try:
        while True:
            # Every second do this...
            try:
                pm = PLANTOWER.read()
            except Exception as e:
                print("PMS7003: exception: " + str(e))
            # print(pm)
            pm_1_0_list.append(pm.pm10_std)
            pm_2_5_list.append(pm.pm25_std)
            pm_10_list.append(pm.pm100_std)
            # wind
            wind.store_speeds.append(wind.calculate_speed(INTERVAL))
            wind_d = wind_direction_byo.get_value()
            if wind_d is not None:
                wind.store_directions.append(wind_d)
            wind.reset_wind()
            # Every 60 seconds do this...
            if len(pm_1_0_list) == AVG_INTERVAL and len(
                    pm_2_5_list) == AVG_INTERVAL and len(
                        pm_10_list) == AVG_INTERVAL:
                # average wind
                wind_average = wind_direction_byo.get_average(
                    wind.store_directions)
                wind_gust = max(wind.store_speeds)
                wind_speed = statistics.mean(wind.store_speeds)
                telemetry["wind_speed"] = str(wind_speed *
                                              0.621371)  # convert to mph
                telemetry["wind_gust"] = str(wind_gust *
                                             0.621371)  # convert to mph
                telemetry["wind_direction"] = str(wind_average)
                # at end of interval average value and add to telemetry
                pm_1_0_avg = statistics.mean(pm_1_0_list)
                pm_2_5_avg = statistics.mean(pm_2_5_list)
                pm_10_avg = statistics.mean(pm_10_list)
                telemetry["pm_1_0"] = str(pm_1_0_avg)
                telemetry["pm_2_5"] = str(pm_2_5_avg)
                telemetry["pm_10"] = str(pm_10_avg)
                # rain
                rain = rainfall.get_value()
                telemetry["rainfall"] = str(rain)
                rainfall.reset_rainfall()
                # BME280
                bme280_data = bme280.sample(bus, address)
                humidity = bme280_data.humidity
                pressure = bme280_data.pressure
                temperature = (bme280_data.temperature *
                               1.8) + 32  # convert to Farenheit
                # print(pressure, humidity, ambient_temperature)
                telemetry["ambient_pressure"] = str(pressure)
                telemetry["ambient_humidity"] = str(humidity)
                telemetry["ambient_temperature"] = str(temperature)
                # Controller Battery telemetry
                telemetry["battery_percentage"] = rover.battery_percentage()
                telemetry["battery_type"] = rover.battery_type()
                telemetry["battery_capacity"] = rover.battery_capacity()
                telemetry["battery_voltage"] = rover.battery_voltage()
                telemetry["battery_temperature"] = rover.battery_temperature()
                # Controller telemetry
                telemetry["controller_model"] = rover.model()
                telemetry[
                    "controller_temperature"] = rover.controller_temperature()
                telemetry[
                    "controller_charging_status"] = rover.charging_status_label(
                    )
                # Load Telemetry
                telemetry["load_voltage"] = rover.load_voltage()
                telemetry["load_current"] = rover.load_current()
                telemetry["load_power"] = rover.load_power()
                # Solar Telemetry
                telemetry["solar_voltage"] = rover.solar_voltage()
                telemetry["solar_current"] = rover.solar_current()
                telemetry["solar_power"] = rover.solar_power()
                # Controller Stats Telemetry
                telemetry[
                    "power_generation_today"] = rover.power_generation_today()
                telemetry[
                    "charging_amp_hours_today"] = rover.charging_amp_hours_today(
                    )
                telemetry[
                    "discharging_amp_hours_today"] = rover.discharging_amp_hours_today(
                    )
                # Sending telemetry and checking the delivery status (QoS = 1 by default)
                result = client.send_telemetry(telemetry)
                result.get()
                print("Telemetry update sent: " +
                      str(result.rc() == TBPublishInfo.TB_ERR_SUCCESS))
                print("Telemetry: " + str(telemetry))
                # reset list
                pm_1_0_list.clear()
                pm_2_5_list.clear()
                pm_10_list.clear()
                wind.store_speeds.clear()
                wind.store_directions.clear()

            next_reading += INTERVAL
            sleep_time = next_reading - time.time()
            if sleep_time > 0:
                time.sleep(sleep_time)
    except KeyboardInterrupt:
        pass

    client.disconnect()