def control_pump_via_usb(pump_type, action):
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    if (pump_type == "RESET"):
        GPIO.setup(PUMP_PIN["pinA"], GPIO.OUT)
        GPIO.setup(PUMP_PIN["pinB"], GPIO.OUT)
        GPIO.setup(PUMP_PIN["pinW"], GPIO.OUT)
        GPIO.output(PUMP_PIN["pinA"], GPIO.LOW)
        GPIO.output(PUMP_PIN["pinB"], GPIO.LOW)
        GPIO.output(PUMP_PIN["pinW"], GPIO.LOW)
        GPIO.cleanup(PUMP_PIN["all"])
        print(" >>> Off all pumps - " + str(get_curr_datetime()))
    elif (pump_type == "WATER"):
        GPIO.setup(PUMP_PIN["pinW"], GPIO.OUT)
        if (action == "ON"):
            print("ON WATER_PUMP - " + str(get_curr_datetime()))
            GPIO.output(PUMP_PIN["pinW"], GPIO.HIGH)
        else:
            print("OFF WATER_PUMP - " + str((get_curr_datetime())))
            GPIO.output(PUMP_PIN["pinW"], GPIO.LOW)
            GPIO.cleanup([PUMP_PIN["pinW"]])
    elif (pump_type == "FER"):
        GPIO.setup(PUMP_PIN["pinA"], GPIO.OUT)
        GPIO.setup(PUMP_PIN["pinB"], GPIO.OUT)
        if (action == "ON"):
            print("ON FERTILILZER_PUMP - " + str(get_curr_datetime()))
            GPIO.output(PUMP_PIN["pinA"], GPIO.HIGH)
            GPIO.output(PUMP_PIN["pinB"], GPIO.HIGH)
        else:
            print("OFF FERTILILZER_PUMP - " + str(get_curr_datetime()))
            GPIO.output(PUMP_PIN["pinA"], GPIO.LOW)
            GPIO.output(PUMP_PIN["pinB"], GPIO.LOW)
            GPIO.cleanup([PUMP_PIN["pinA"], PUMP_PIN["pinB"]])
示例#2
0
def get_store_sensor_data(client, pub_time_dict, curr_pump_stat, arduino_input):
    data_obj, data_str = prepare_sensor_data_obj_main(
        SEN_SERIAL, curr_pump_stat, arduino_input)
    # FOR STORING MESSAGE
    if (pub_time_dict["last_store"] is not None):
        curr_time = get_curr_datetime()
        time_elapse = get_time_difference_in_sec(
            pub_time_dict["last_store"], curr_time)

        if (time_elapse < pub_time_dict["store_interval"]):
            return data_obj

    pub_time_dict["last_store"] = get_curr_datetime()
    data_obj["data_datetime"] = get_curr_datetime_without_format()
    insert_item('sensor_data', [data_obj], "[ sensor_data ] col")
    return data_obj
示例#3
0
def get_pub_sensor_data(client, pub_time_dict, curr_pump_stat, arduino_input):
    # Convert Sensor Data
    data_obj, data_str = prepare_sensor_data_obj_main(SEN_SERIAL, curr_pump_stat, arduino_input)

    # FOR PUBLISH MESSAGE
    if (pub_time_dict["last_pub"] is not None):
        curr_time = get_curr_datetime()
        time_elapse = get_time_difference_in_sec(
            pub_time_dict["last_pub"], curr_time)

        if (time_elapse < pub_time_dict["pub_interval"]):
            return data_obj

    pub_time_dict["last_pub"] = get_curr_datetime()
    #mqtt_pub_msg(client, PUB_CLOUD_TOPIC['pub_data'], data_str)
    return data_obj
def prepare_sensor_data_obj_main(serial_number, curr_pump_stat, arduino_input):
    data_tokens = arduino_input.decode('utf-8').split("#")
    # data_tokens = arduino_input.split("#")   #For Debugging - Dummy string

    res = {
        "data_datetime": get_curr_datetime(),
        "serial_number": serial_number,
        "waterPumpStat": curr_pump_stat["WATER"],
        "ferPumpStat": curr_pump_stat["FER"],
        "pumpStat": curr_pump_stat["WATER"] or curr_pump_stat["FER"],
        "temp": -1,
        "ph": -1,
        "ec": -1,  # Temporary reading
        "orp": -1,
        "tds": -1,
        "co2": -1,
        "air_temperature": -1,
        "humidity": -1,
        "fertilizer": -1,
        "water": -1
    }

    i = 0
    for t in data_tokens:
        if ("@" in t):
            d = t.split("@")
            if (d[1] == "inf" or d[1] == "nan"):
                continue

            if (d[0] == "TEMP"):
                res["temp"] = float(d[1])
            elif (d[0] == "PH"):
                res["ph"] = float(d[1])
            elif (d[0] == "EC"):
                res["ec"] = float(d[1])
            elif (d[0] == "ORP"):
                res["orp"] = float(d[1])
            elif (d[0] == "TDS"):
                res["tds"] = float(d[1])
            elif (d[0] == "CO2"):
                res["co2"] = float(d[1])
            elif (d[0] == "AIR_T"):
                res["air_temperature"] = float(d[1])
            elif (d[0] == "AIR_H"):
                res["humidity"] = float(d[1])
            elif (d[0] == "WLVL1" or d[0] == "FER_LVL"):
                res["fertilizer"] = float(d[1])
            elif (d[0] == "WLVL2" or d[0] == "W_LVL"):
                res["water"] = float(d[1])

    print(res)
    return res, encode_obj_to_json(res)
def prepare_gpio_pump_notification_message_obj(pump_type, action, shelf_id):

    res = {
        "serial_number": SEN_SERIAL,
        'shelf_id': shelf_id,
        "msg_datetime": get_curr_datetime(),
        "msg_title": MSG_TITLE[pump_type + '_pump_' + action],
        "msg_about": MSG_ABOUT[pump_type + '_pump'],
        "msg_location": MSG_LOC,
        "msg_severity": MSG_SEVERITY['pump'],
    }

    return encode_obj_to_json(res)
def prepare_pub_sensor_data(sensor_data):
    res = {
        "data_datetime": get_curr_datetime(),
        "temp": sensor_data["temp"],
        "ph": sensor_data["ph"],
        "ec": sensor_data["ec"],
        "orp": sensor_data["orp"],
        "tds": sensor_data["tds"],
        "co2": sensor_data["co2"],
        "air_temp": sensor_data["air_temperature"],
        "humid": sensor_data["humidity"],
        "fertilizer": sensor_data["fertilizer"],
        "water": sensor_data["water"]
    }
    return encode_obj_to_json(res)
def prepare_usb_notification_message_obj(is_pump_on, shelf_id):

    if (is_pump_on):
        msg_title = MSG_TITLE["pump_on"]
    else:
        msg_title = MSG_TITLE["pump_off"]

    res = {
        "serial_number": SEN_SERIAL,
        'shelf_id': shelf_id,
        "msg_datetime": get_curr_datetime(),
        "msg_title": msg_title,
        "msg_about": MSG_ABOUT['pump'],
        "msg_location": MSG_LOC,
        "msg_severity": MSG_SEVERITY['pump'],
    }

    return encode_obj_to_json(res)
示例#8
0
def mqtt_main(comm_with, topic_list):
    print("\nCommunicate with - " + str(comm_with))
    print("Subscribing MQTT Topic - " + str(topic_list))
    pump_ctrl("RESET", "OFF")

    global SUBSCRIBE_TOPIC
    global COMMUNICATE_WITH
    global PUB_TIME_DICT
    global CTRL_TIME_DICT
    global THRESHOLD_DICT
    global CURR_PUMP_DICT
    global READ_SERIAL
    global SER
    global C_SOCKET

    SUBSCRIBE_TOPIC = topic_list
    COMMUNICATE_WITH = comm_with
    PUB_TIME_DICT = {
        "pub_interval": CFP.PUB_DATA_INTERVAL_IN_SEC,
        "store_interval": CFP.STORE_DATA_INTERVAL_IN_SEC,
        "last_pub": None,
        "last_store": None
    }
    CTRL_TIME_DICT = {
        "check_interval": CFP.CHECK_INTERVAL_IN_SEC,
        "ctrl_interval": CFP.CTRL_INTERVAL_IN_SEC,
        "last_check": None,
        "last_ctrl": None,
        "ctrl_pump": None,
        "ctrl_method": "AUTO",
    }
    THRESHOLD_DICT = CFP.THRESHOLD_DICT
    CURR_PUMP_DICT = CFP.CURR_PUMP_STAT

    print("Total MQTT topic to subscribe : " + str(len(SUBSCRIBE_TOPIC)))
    print("Topic to subscribe : " + str(len(SUBSCRIBE_TOPIC)))

    client = mqtt.Client(client_id="RPi_" + CFP.SEN_SERIAL + "-" +
                         str(comm_with))
    l_client = mqtt.Client(client_id="RPi_" + CFP.SEN_SERIAL + "- local")

    #-----------------------------#
    # MQTT Authentication Method  #
    #-----------------------------#
    if (CPS.MQTT_ENABLE_AUTH):
        if (CPS.MQTT_AUTH_METHOD == "password"):
            client.username_pw_set(CPS.MQTT_USERNAME,
                                   password=CPS.MQTT_PASSWORD)

    #----------------------------------#
    # Attach Callback Function - CLOUD #
    #----------------------------------#
    client.on_connect = on_connect
    client.on_message = on_message
    client.on_publish = on_publish
    client.on_subscribe = on_subscribe
    # client.on_log = on_log
    #----------------------------------#
    # Attach Callback Function - LOCAL #
    #----------------------------------#
    l_client.on_connect = on_local_connect
    l_client.on_message = on_local_message
    l_client.on_publish = on_local_publish
    l_client.on_subscribe = on_local_subscribe

    #----------------------------#
    # Establish MQTT Connection  #
    #----------------------------#
    client.connect(CPS.MQTT_CLOUD_SERVER, CPS.MQTT_PORT, CPS.MQTT_KEEPALIVE)
    l_client.connect(CPS.MQTT_LOCAL_SERVER, CPS.MQTT_PORT, CPS.MQTT_KEEPALIVE)
    # if (CPS.MQTT_SERVER_TYPE == "cloud"):
    #     client.connect(CPS.MQTT_CLOUD_SERVER, CPS.MQTT_PORT, CPS.MQTT_KEEPALIVE)
    # else:
    #     client.connect(CPS.MQTT_LOCAL_SERVER, CPS.MQTT_PORT, CPS.MQTT_KEEPALIVE)

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.
    if (CFP.APPLICATION_TYPE == "WORKSHOP"):
        schedule.every().minute.at(":00").do(check_thres_pub_sensor_data,
                                             CFP.APPLICATION_TYPE, client,
                                             CTRL_TIME_DICT, CURR_PUMP_DICT,
                                             THRESHOLD_DICT)
    else:
        schedule.every().hour.at(":00").do(check_thres_pub_sensor_data,
                                           CFP.APPLICATION_TYPE, client,
                                           CTRL_TIME_DICT, CURR_PUMP_DICT,
                                           THRESHOLD_DICT)
    #---------------#  Get ShelfID - To ensure it is assigned
    # RUN API CALLS #  Get Threshold - If not set, add one
    #---------------#
    need_resync = sync_cloud_thres_info(CFP.SEN_SERIAL, THRESHOLD_DICT)
    last_resync_check = None

    #--------------------#
    # Endless Publisher  #  https://stackoverflow.com/questions/23909292/publish-a-message-every-10-seconds-mqtt
    #--------------------#
    SER = serial.Serial('/dev/ttyACM0', CFP.ARDUINO_BRAUD_RATE)
    C_SOCKET = {"sid": ""}
    client.loop_start()
    l_client.loop_start()
    read_serial = ""
    READ_SERIAL = {"data": read_serial}
    while True:
        readSerialAndPub(client, l_client)
        schedule.run_pending()
        #data = get_pub_sensor_data(client, PUB_TIME_DICT, CURR_PUMP_DICT, read_serial)

        # check_threshold(client, CTRL_TIME_DICT, CURR_PUMP_DICT,THRESHOLD_DICT, data)
        if (need_resync):  # Check once per 300 seconds
            if (last_resync_check is not None):
                curr_time = get_curr_datetime()
                time_elapse = get_time_difference_in_sec(
                    last_resync_check, curr_time)

                if (time_elapse < 300):
                    continue
            last_resync_check = get_curr_datetime()
            need_resync = sync_cloud_thres_info(CFP.SEN_SERIAL, THRESHOLD_DICT)
示例#9
0
def check_thres_pub_sensor_data(APP_TYPE, client, CTRL_TIME_DICT, CURR_PUMP_DICT, THRESHOLD_DICT):
    if (APP_TYPE!="WORKSHOP"):
        if (get_hour() not in SEND_DATA_HOUR):
            print("\n\nFATAL_INFO - NOT THE TIME YET - "+get_curr_datetime())
            return

    print("\n\nINFO - "+get_curr_datetime())
    #mqtt_pub_msg(client, PUB_CLOUD_TOPIC['pub_data'], data_str)
    all_data = get_prev_data()
    print(all_data)
    data_res = {
        "temp": 0,
        "ph": 0,
        "ec": 0,
        "orp": 0,
        "tds": 0,
        "co2": 0,
        "air_temperature": 0,
        "humidity": 0,
        "fertilizer": -1,
        "water": -1
    }
    # data_res = {"temp": 0, "ph": 0, "ec": 0,  "orp": 0,
    #             "tds": 0, "fertilizer": -1, "water": -1}

    if (len(all_data) > 0):
        for data in all_data:
            # data_res['temp'] += data['temp']
            # data_res['ph'] += data['ph']
            # data_res['ec'] += data['ec']
            # data_res['orp'] += data['orp']
            # data_res['tds'] += data['tds']
            data_res['temp'] += check_exist_sensor(data,'temp')
            data_res['ph'] += check_exist_sensor(data,'ph')
            data_res['ec'] += check_exist_sensor(data,'ec')
            data_res['orp'] += check_exist_sensor(data,'orp')
            data_res['tds'] += check_exist_sensor(data,'tds')
            data_res['co2'] += check_exist_sensor(data, 'co2')
            data_res['air_temperature'] += check_exist_sensor(data, 'air_temperature')
            data_res['humidity'] += check_exist_sensor(data, 'humidity')


    print("CALCULATE data_res for ", len(all_data), " data\n", data_res)
    data_res['temp'] /= len(all_data)
    data_res['ph'] /= len(all_data)
    data_res['ec'] /= len(all_data)
    data_res['orp'] /= len(all_data)
    data_res['tds'] /= len(all_data)
    data_res['co2'] /= len(all_data)
    data_res['air_temperature'] /= len(all_data)
    data_res['humidity'] /= len(all_data)
    data_res['fertilizer'] = all_data[-1]["fertilizer"]
    data_res['water'] = all_data[-1]["water"]
    print("SENSOR DATA : ", data_res)
    # if (APP_TYPE == "WORKSHOP"):
    #     if(get_minute() in CHECK_THRES_MINS):
    #         check_threshold(client, CTRL_TIME_DICT, CURR_PUMP_DICT,THRESHOLD_DICT, data_res)
    # elif (APP_TYPE == "SR"):
    if (APP_TYPE == "SR"):
        check_threshold_sr(client, CTRL_TIME_DICT,CURR_PUMP_DICT, THRESHOLD_DICT, data_res)
    elif (APP_TYPE == "WORKSHOP"):
        check_threshold_workshop(client, CTRL_TIME_DICT,CURR_PUMP_DICT, THRESHOLD_DICT, data_res)
    else:
        check_threshold(client, CTRL_TIME_DICT, CURR_PUMP_DICT,THRESHOLD_DICT, data_res)

    print(CTRL_TIME_DICT, "\n", CURR_PUMP_DICT, "\n", THRESHOLD_DICT)
    pub_data = prepare_pub_sensor_data(data_res)
    mqtt_pub_msg(client, PUB_CLOUD_TOPIC['pub_data'], str(pub_data))