Ejemplo n.º 1
0
def prosesACC():
    print('ACC\n')
    serialACC = serial.Serial('COM19', 9600)
    clientthingsboard = TBDeviceMqttClient("202.46.7.33", "TEWSSiporaAccelero")
    clientthingsboard.max_inflight_messages_set(50)
    clientthingsboard.connect()
    while True:
        dataInput = serialACC.readline()[:-2]
        data = dataInput.decode()
        print(data)
        if data:
            dataacc = parsingACC(data)
            telemetry_with_ts = {
                "ts": int(round(time.time() * 1000)),
                "values": {
                    "x": float(dataacc[0]),
                    "y": float(dataacc[1]),
                    "z": float(dataacc[2])
                }
            }
            clientthingsboard.send_telemetry(telemetry_with_ts)

            lock.acquire()
            xDataQueue.put(dataacc[0])
            yDataQueue.put(dataacc[1])
            zDataQueue.put(dataacc[2])
            timestampDataQueue.put(int(round(time.time() * 1000)))
            lock.release()
            writelogdataaccelerometer(dataacc)
Ejemplo n.º 2
0
def main():
    client = TBDeviceMqttClient(THINGSBOARD_HOST, DEVICE_ACCESS_TOKEN)
    client.connect()
    rc = client.claim(secret_key=SECRET_KEY, duration=DURATION).get()
    if rc == 0:
        print("Claiming request was sent.")
    client.stop()
Ejemplo n.º 3
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()
Ejemplo n.º 4
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 main():
    client = TBDeviceMqttClient("127.0.0.1", "A2_TEST_TOKEN")
    client.connect()
    sub_id_1 = client.subscribe_to_attribute("uploadFrequency", callback)
    sub_id_2 = client.subscribe_to_all_attributes(callback)
    client.unsubscribe_from_attribute(sub_id_1)
    client.unsubscribe_from_attribute(sub_id_2)
Ejemplo n.º 6
0
    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 main():
    client = TBDeviceMqttClient("127.0.0.1", "A2_TEST_TOKEN")

    client.connect()
    # call "getTime" on server and receive result, then process it with callback
    client.send_rpc_call("getTime", {}, callback)
    while not client.stopped:
        time.sleep(1)
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
Ejemplo n.º 9
0
def main():
    client = TBDeviceMqttClient("127.0.0.1", "A2_TEST_TOKEN")
    # we set maximum amount of messages sent to send them at the same time. it may stress memory but increases performance
    client.max_inflight_messages_set(100)
    client.connect()

    results = []
    result = True

    for i in range(0, 100):
        results.append(client.send_telemetry(telemetry_with_ts))

    for tmp_result in results:
        result &= tmp_result.get() == TBPublishInfo.TB_ERR_SUCCESS

    print("Result " + str(result))

    client.stop()
Ejemplo n.º 10
0
def main():
    client = TBDeviceMqttClient("127.0.0.1", "A2_TEST_TOKEN")
    client.connect()
    # Sending data in async way
    client.send_attributes(attributes)
    client.send_telemetry(telemetry)
    client.send_telemetry(telemetry_as_array, quality_of_service=1)
    client.send_telemetry(telemetry_with_ts)
    client.send_telemetry(telemetry_with_ts_as_array)

    # Waiting for data to be delivered
    result = client.send_attributes(attributes)
    result.get()
    print("Attribute update sent: " +
          str(result.rc() == TBPublishInfo.TB_ERR_SUCCESS))
    result = client.send_attributes(attributes)
    result.get()
    print("Telemetry update sent: " +
          str(result.rc() == TBPublishInfo.TB_ERR_SUCCESS))
    client.stop()
Ejemplo n.º 11
0
def prosesBPR():
    print('BPR\n')
    global pressurebuffer
    global serialBPR
    clientthingsboard = TBDeviceMqttClient("202.46.7.33", "TEWSSiporaBPR")
    clientthingsboard.max_inflight_messages_set(10)
    clientthingsboard.connect()
    while True:
        dataInput = serialBPR.readline()[:-2]
        data=dataInput.decode()
        print(data)
        if data:
            databpr = parsingBPR(data)
            #send to thingsboard
            telemetry_with_ts = {"ts": int(round(time.time() * 1000)), "values": {"pressure": float(pressuredata), "temperature": float(temperaturedata)}}
            clientthingsboard.send_telemetry(telemetry_with_ts)                         

            lock.acquire()
            pressureDataQueue.put(databpr[1])
            temperatureDataQueue.put(databpr[2])
            timestampDataQueue.put(int(round(time.time() * 1000)))
            lock.release()
            pressurebuffer = databpr[1]
            writelogdataBPR(databpr)
def main():
    """
    We can provide the following parameters to provisioning function:
      host - required - Host of ThingsBoard
      provision_device_key - required - device provision key from device profile
      provision_device_secret - required - device provision secret from device profile
      port=1883 - not required - MQTT port of ThingsBoard instance
      device_name=None - may be generated on ThingsBoard - You may pass here name for device, if this parameter is not assigned, the name will be generated

      ### Credentials type = ACCESS_TOKEN

      access_token=None - may be generated on ThingsBoard - You may pass here some access token and it will be saved as accessToken for device on ThingsBoard.

      ### Credentials type = MQTT_BASIC

      client_id=None - not required (if username is not None) - You may pass here client Id for your device and use it later for connecting
      username=None - not required (if client id is not None) - You may pass here username for your client and use it later for connecting
      password=None - not required - You may pass here password and use it later for connecting

      ### Credentials type = X509_CERTIFICATE
      hash=None - required (If you wanna use this credentials type) - You should pass here public key of the device, generated from mqttserver.jks

    """

    # Call device provisioning, to do this we don't need an instance of the TBDeviceMqttClient to provision device

    credentials = TBDeviceMqttClient.provision("127.0.0.1",
                                               "PROVISION_DEVICE_KEY",
                                               "PROVISION_DEVICE_SECRET")

    if credentials is not None:
        client = TBDeviceMqttClient("127.0.0.1", credentials)
        client.connect()
        # Sending data in async way

        client.stop()
Ejemplo n.º 13
0
    # 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"
    if(msg.strip().split(";")[0]=="1060" and msg.strip() != ""):
        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)
        # Disconnect from ThingsBoard
        client.disconnect()
Ejemplo n.º 14
0
#ThingsBoard IP
THINGSBOARD_HOST = '129.126.163.157'

#Access token of Controller
ACCESS_TOKEN = 'M5enL3ND6Jl9KX1mRwje'

INTERVAL = 2

#Access token of edge device 1
ACCESS_TOKEN_EDGE_1 = 'CnpDrS1iinb5fZ4dQD90'

#Sample
sensor_data = {'temperature': 1414114, 'humidity': 0}

#Controller device
client = TBDeviceMqttClient(THINGSBOARD_HOST, ACCESS_TOKEN)
client_to_edge = TBDeviceMqttClient(THINGSBOARD_HOST, ACCESS_TOKEN_EDGE_1)
client.connect()
client_to_edge.connect()

# Sending to attribute and checking the delivery status (QoS = 1 by default)
result = client.send_attributes({
    "Edge1_Len": 10,
    "Edge1_Straight": 7,
    "Edge1_Right": 3
})

# send to edge attribute
result2 = client_to_edge.send_attributes({
    "Edge1_Len": 10,
    "Edge1_Straight": 7,
import logging
import time

from tb_device_mqtt import TBDeviceMqttClient
logging.basicConfig(level=logging.DEBUG)


def callback(result):
    print(result)


client = TBDeviceMqttClient("127.0.0.1", "A2_TEST_TOKEN")
client.connect()
sub_id_1 = client.subscribe_to_attribute("uploadFrequency", callback)
sub_id_2 = client.subscribe_to_all_attributes(callback)
client.unsubscribe_from_attribute(sub_id_1)
client.unsubscribe_from_attribute(sub_id_2)
while True:
    time.sleep(1)
from tb_device_mqtt import TBDeviceMqttClient, TBPublishInfo
import logging
import time

#ThingsBoard IP
THINGSBOARD_HOST = '129.126.163.157'

#Access token of Controller
ACCESS_TOKEN = 'M5enL3ND6Jl9KX1mRwje'

INTERVAL = 2

#Controller device
client = TBDeviceMqttClient(THINGSBOARD_HOST, ACCESS_TOKEN)


#Call back
def on_attribute_change(client, result, exception):
    print(client)

    # get client key & values and print it
    # junction1_result will be the value
    clientObj = result["client"]
    junction1_result = clientObj["junction1"]
    print(junction1_result)
    if exception is not None:
        print("Exception: " + str(exception))
    else:
        print(result)

Ejemplo n.º 17
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))
Ejemplo n.º 18
0
import logging
from tb_device_mqtt import TBDeviceMqttClient
import socket

logging.basicConfig(level=logging.DEBUG)
# connecting to localhost
client = TBDeviceMqttClient(socket.gethostname())
client.connect(tls=True,
               ca_certs="mqttserver.pub.pem",
               cert_file="mqttclient.nopass.pem")
client.disconnect()
Ejemplo n.º 19
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()
Ejemplo n.º 20
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()
Ejemplo n.º 21
0
        f = open("/sys/class/leds/igt30::usr" + str(i) + "/brightness", "w")
        f.write("1")
        f.close()


# dependently of request method we send different data back
def on_server_side_rpc_request(request_id, request_body):
    print(request_id, request_body)
    if request_body["method"] == "sendCommand":
        print(2)
        client.send_rpc_reply(request_id,
                              {"CPU percent": psutil.cpu_percent()})
    elif request_body["method"] == "getValue":
        client.send_rpc_reply(request_id, {"value": 0})
    elif request_body["method"] == "setValue":
        if request_body["params"] == True:
            print(1)
            led(4, 1)
        else:
            print(0)
            led(4, 0)


client = TBDeviceMqttClient("demo.thingsboard.io", "wjH4O6ArXM535TBSPyxO")
client.set_server_side_rpc_request_handler(on_server_side_rpc_request)
client.connect()
while True:
    time.sleep(1)
    #print( psutil.cpu_percent())
    #print( psutil.virtual_memory().percent)
Ejemplo n.º 22
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)
Ejemplo n.º 23
0
def main():
    client = TBDeviceMqttClient("127.0.0.1", "A2_TEST_TOKEN")
    client.connect()
    client.request_attributes(["atr1", "atr2"], callback=on_attributes_change)
    while not client.stopped:
        time.sleep(1)
Ejemplo n.º 24
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()
    config["host"] = host if host else "thingsboard.cloud"
    token = ""
    while not token:
        token = input("Please write accessToken for device: ")
        if not token:
            print("Access token is required!")
    config["token"] = token
    config["secret_key"] = input(
        "Please write secret key for claiming request: ")
    if not config["secret_key"]:
        print(
            "Please make sure that you have claimData in server attributes for device to use this feature without device secret in the claiming request."
        )
    duration_ms = input(
        "Please write duration in milliseconds for claiming request or leave it blank to use default (30000): "
    )
    config["duration_ms"] = int(duration_ms) if duration_ms else 30000
    print("\n", "=" * 80, "\n", sep="")
    return config


if __name__ == '__main__':
    config = collect_required_data()
    client = TBDeviceMqttClient(host=config["host"], token=config["token"])
    client.connect()
    client.claim(secret_key=config["secret_key"],
                 duration=config["duration_ms"]).get()
    print(
        "Claiming request was sent, now you should use claiming device widget to finish the claiming process."
    )