Example #1
0
def insertRawData(timeStamp,moisture,temp,light):
    print("Database: insertDataList")
    result = False
    nextTime = 0
    lessTime = (int(timeStamp)-(int(sp.get(ageData))*int(dayStamp)))

    sql = "insert into raw_data (time,mos1,mos2,tmp1,tmp2,light_in,light_out)"\
          "values (" +str(timeStamp) +", "+str(moisture["point1"])+", "+str(moisture["point2"]) \
          +","+str(temp["point1"])+","+str(temp["point2"])+","+str(light["light_in"])+","+str(light["light_out"]) +");"

    sql2 = "delete from raw_data where time < " +str(lessTime)+";"

    #print(str(sql))
    #print(str(sql2))

    try:
        db = db = MySQLdb.connect(host,username,password,database)
        cursor = db.cursor()
        cursor.execute(sql)
        db.commit()
        cursor.execute(sql2)
        db.commit()
        result = True
    except MySQLdb.Error:
        print("  - Database: Error")
    finally:
        if db:
            db.close()
            print("  - Database: close connection..." +"\n")

    if(result):
        nextTime = int(timeStamp) +(int(sp.get(fqIData))*int(hourStamp))
    return result,nextTime
Example #2
0
def getSlatStatus(lightIn, lightOut):
    print(" get slat status")

    stSlat = int(sp.get(slatStatus))
    print("  slat status from preference: " + str(stSlat))
    if ((float(lightIn) > 0) and (float(lightOut) > 0)):
        #print("  light in: "+str(lightIn) +" lux")
        #print("  light out: "+str(lightOut) +" lux")
        if ((float(lightOut) - float(lightIn)) >
                float(3000)):  #value have different motr than 2,000 lux
            if (stSlat != int(0)):
                print(
                    "  light in and out different more 3000 lux, But slat status = open (1)"
                )
                if (ctrl.closeSlat()):  #if can close slat
                    time.sleep(10)
                    sp.put(slatStatus, int(0))
                    global isConn
                    if (isConn):
                        gear.publisSlatStatus(0)
                stSlat = 0
        else:
            if (int(stSlat) == 0):
                if ((float(lightOut) - float(lightIn)) < float(1000)):
                    if (ctrl.openSlat()):
                        time.sleep(10)
                        sp.put(slatStatus, int(1))
                        global isConn
                        if (isConn):
                            gear.publisSlatStatus(1)
                stSlat = 1
    else:
        print("  sensor light error!!")
    return stSlat
Example #3
0
def reload():
    global nextTimePubData
    global nextTimeInsertData
    global nextTimePubImage
    global lastTimePubImage
    nextTimePubImage = int(
        int(lastTimePubImage) +
        (int(sp.get(fqPImage)) * int(3600)))  #1 hour in time stamp
    nextTimePubData = t.getNextTimePubData(sp.get(fqPData))
    nextTimeInsertData = t.getNextTimeInsertData(sp.get(fqIData))
Example #4
0
def insertLogData(timeStamp,working,typeA,valBefore,valAfter):
    print(" Database: log data ( working: "+str(working) +", type: "+str(typeA) +" )")
    result = False
    lessTime = (int(timeStamp)-(int(sp.get(ageData))*int(dayStamp)))
    
    try:
        db = db = MySQLdb.connect(host,username,password,database)#localhost,username,password,Database name
        cursor = db.cursor()
        sql = "insert into log_data (time,working,working_type,val_before,val_after)"\
              "values (" +str(timeStamp) +", "+str(working) +", "+str(typeA)+", "+str(valBefore) +", "+str(valAfter) +");"
        cursor.execute(sql)
        db.commit()
        sql = "delete from log_data where time < " +str(lessTime)+";"
        cursor.execute(sql)
        db.commit()
        result = True
        
    except MySQLdb.Error:
        print("  Database: Error")
    finally:
        if db:
            db.close()
            print("  success")
            print("  Database: close connection..." +"\n")
    return result
Example #5
0
def pushNotification(data):
    print("  GCM, pushNotification")

    reg_id = str(sp.get("token"))
    print("    token: " + str(reg_id))
    print("    data: " + str(data))
    try:
        gcm.plaintext_request(registration_id=reg_id, data=data)
        print("    pushNotification success")
    except:
        print("    Opps! has error...")
Example #6
0
def subscription(topic,message):
    topic = topic.split("/")
    topic = topic[2]
    payload = message[2:-1]
    print ("\nMicrogear, on subscription \n topic: "+topic+"\n message: "+message +"\n")
    #print ("-----------------------")

    if(topic == "preferences"):
        sp.setSharedPreferences(json.loads(payload))
    elif(topic == "token"):
        sp.put("token",payload)
    elif(topic == "slatStatus"):
        sp.put("slatStatus",payload)
    elif(topic == "refreshIM"):
        refreshImage()
    elif(topic == "settingDetails"):
        settingDetails(payload)
    elif(topic == "settingStandard"):
        settingStandard(payload)
    elif(topic == "controlDevices"):
        controlsDevices(int(payload))
    elif(topic == "refresh"):
        onRefresh()
    elif(topic == "alarm"):
        onSaveClock(payload)
Example #7
0
def settingStandard(payload):

    mosStd = "mosStd"           #moisture standard
    tmpStd = "tmpStd"           #temp standard
    ligStd = "ligStd"           #light standard

    #errorCode  0: database error
    #           1: water not flows
    #           2: water not true arare
    #           3: temp not decrease after shower
    #           4: not time to shower
    #           5: slat is opened
    #           6: slat is closed
    #           7: light value not decrease
    
    objecStan = json.loads(payload)
    for i in objecStan:
        print("  - key: "+str(i))
        print("  - value: "+str(objecStan[i]))
        print("  ---------------------")
        if(i == mosStd):
            sp.put(mosStd,objecStan[i])
        elif(i == tmpStd):
            sp.put(tmpStd,objecStan[i])
        elif(i == ligStd):
            sp.put(ligStd,objecStan[i]) 
    if(isConnect()):
        response = json.dumps({"topic":"settingStandard","success":True,"message":payload})
        microgear.publish("/response",str(response))
Example #8
0
def compareMosture(timeStamp, mosObj, isConn):
    result = False
    timeExceptWater = 0
    print("Compare, check moisture...")

    if (float(mosObj["average"]) >
            0):  #if sensor not error  # chamge point1 to average
        if (float(mosObj["average"]) < float(sp.get(mosStd))):
            print(" moisture less than standard")
            if (ctrl.water()):
                time.sleep(30)  #wait 30 second
                newMosObj = json.loads(inputs.getMoistureObject())
                print(" old moisture: " +
                      str(mosObj["average"]))  # chamge point1 to average
                print(" new moisture: " +
                      str(newMosObj["average"]))  # chamge point1 to average
                if (
                    (float(newMosObj["point1"] - float(mosObj["average"]) > 5))
                ):  # if moisture value more than valus before  chamge point1 to average
                    print(" All success")
                    db.insertLogData(
                        timeStamp, 1, 1, float(mosObj["average"]),
                        float(newMosObj["average"]))  #insert log to database
                    result = True
                else:
                    print(" Error! water to true Arare")
                    timeExceptWater = onExceptWater(timeStamp, 2, isConn)
            else:
                print(" Error! water not flows")
                timeExceptWater = onExceptWater(timeStamp, 1, isConn)
        else:
            print(" no working...")
    else:
        print(" moisture sensor error!!")

    return result, timeExceptWater
Example #9
0
def controlsDevices(working):
    success = False
    data = ""
    if (working == 1):
        print(" Water from alarm clock")
        mosObj = json.loads(inputs.getMoistureObject())
        if (ctrl.water()):
            time.sleep(30)  #wait 30 second
            newMosObj = json.loads(inputs.getMoistureObject())
            print("  old moisture: " + str(mosObj["average"]))
            print("  new moisture: " + str(newMosObj["average"]))
            if ((float(newMosObj["average"] - float(mosObj["average"]) > 5)
                 )):  # if moisture value more than valus before
                result = db.insertLogData(
                    int(time.time()), 1, 3, float(mosObj["average"]),
                    float(newMosObj["average"]))  #insert log to database
                if (result):
                    print("  All success")
                    success = True
                    data = {
                        "valBefore": float(mosObj["average"]),
                        "valAfter": float(newMosObj["average"])
                    }
                else:
                    data = {
                        "errorCode": 0,
                        "msg": "database error",
                        "valBefore": float(mosObj["average"]),
                        "valAfter": float(newMosObj["average"])
                    }
            else:
                print("  Error! water not true Arare")
                data = {"errorCode": 2, "msg": "water not true arare"}
        else:
            print("  Error! water not flows")
            data = {"errorCode": 1, "msg": "water not flows"}
    elif (working == 2):
        print(" Shower from alarm clock")
        temObj = json.loads(inputs.getTempObject())
        if (ctrl.shower()):
            time.sleep(20)
            newTemObj = json.loads(inputs.getTempObject())
            print("  old temp: " + str(temObj["average"]))
            print("  new temp: " + str(newTemObj["average"]))
            if (float(newTemObj["average"]) <= float(temObj["average"])):
                result = db.insertLogData(
                    int(time.time()), 2, 3, float(temObj["average"]),
                    float(newTemObj["average"]))  #insert log to database
                if (result):
                    success = True
                    data = {
                        "valBefore": float(temObj["average"]),
                        "valAfter": float(newTemObj["average"])
                    }
                    print("  All success")
                    sp.put("lastTimeShower", int(time.time()))
            else:
                print(" Error! temp not decrease after shower")
                data = {
                    "errorCode": 3,
                    "msg": "temp not decrease after shower"
                }
        else:
            print(" Error! water not flows")
            data = {"errorCode": 1, "msg": "water not flows"}

    elif (working == 3):
        print(" Open slat from alarm clock")
        slatStatus = sp.get("slatStatus")  #status of slat
        print("  slatStatus: " + str(slatStatus))
        if (int(slatStatus) != 1):
            ligObj = json.loads(inputs.getLightObject())
            if (ctrl.openSlat()):  #if can open slat
                time.sleep(20)
                newLigObj = json.loads(inputs.getLightObject())
                sp.put("slatStatus", str("1"))
                result = db.insertLogData(
                    int(time.time()), 3, 3, float(ligObj["light_in"]),
                    float(newLigObj["light_in"]))  #insert log to database
                if (result):
                    success = True
                    data = {
                        "valBefore": float(ligObj["light_in"]),
                        "valAfter": float(newLigObj["light_in"])
                    }
                    print("  All success")
                else:
                    data = {
                        "errorCode": 0,
                        "msg": "database error",
                        "valBefore": float(ligObj["light_in"]),
                        "valAfter": float(newLigObj["light_in"])
                    }
        else:
            print("  slat is opened (1)")
            data = {"errorCode": 5, "msg": "slat is opened"}
        print(str(data))
    elif (working == 4):
        print(" Close slat from alarm clock")
        slatStatus = sp.get("slatStatus")  #status of slat
        print("  slatStatus: " + str(slatStatus))
        if (int(slatStatus) != 0):
            ligObj = json.loads(inputs.getLightObject())
            if (ctrl.closeSlat()):  #if can close slat
                time.sleep(20)
                newLigObj = json.loads(inputs.getLightObject())
                print("  old light: " + str(ligObj["light_in"]))
                print("  new light: " + str(newLigObj["light_in"]))

                sp.put("slatStatus", str("0"))
                result = db.insertLogData(
                    int(time.time()), 4, 3, float(ligObj["light_in"]),
                    float(newLigObj["light_in"]))  #insert log to database
                if (result == False):
                    data = {
                        "errorCode": 0,
                        "msg": "database error",
                        "valBefore": float(ligObj["light_in"]),
                        "valAfter": float(newLigObj["light_in"])
                    }
                if (float(newLigObj["light_in"]) < float(ligObj["light_in"])):
                    success = True
                    data = {
                        "valBefore": float(ligObj["light_in"]),
                        "valAfter": float(newLigObj["light_in"])
                    }
                else:
                    print("  new light value not decrease")
                    data = {"errorCode": 7, "msg": "light value not decrease"}
        else:
            print("  slat is closed (0)")
            data = {"errorCode": 6, "msg": "slat is closed"}

    return success, data
Example #10
0
from gcm import *
import json
import preference.SharedPreferences as sp
import time

sp.getSharedPreferences()
gcm = GCM("<API Key Google cloud messageing>")


def setData(title, message):
    return {"body": message, "title": title, "icon": "ic_launcher"}


def pushNotification(data):
    print("  GCM, pushNotification")

    reg_id = str(sp.get("token"))
    print("    token: " + str(reg_id))
    print("    data: " + str(data))
    try:
        gcm.plaintext_request(registration_id=reg_id, data=data)
        print("    pushNotification success")
    except:
        print("    Opps! has error...")
Example #11
0
def MainFunction():
    inputs.setSensorPoint(sensorPoint)
    while True:
        print("")
        alarmClock.getAlarmList()
        have, body = alarmClock.haveAlarmClock()
        if (have and isConn):
            gear.onRefreshRawData()
            gear.publisLogDataList()
            gear.publisSlatStatus(sp.get(slatStatus))
            noti = gcm.setData("alarm", str(body))
            gcm.pushNotification(noti)
        else:
            print("not alarm clock")

        timeStamp = int(time.time())
        print(
            str(timeStamp) + " (" + str(t.timeStampToDateTime(timeStamp)) +
            ") " + getNetStatus())

        if (gear.isHasReload()):
            reload()

        mosObj = json.loads(inputs.getMoistureObject())
        temObj = json.loads(inputs.getTempObject())
        ligObj = json.loads(inputs.getLightObject())

        if (sp.get(autoMode)):
            global stSlat
            stSlat = getSlatStatus(ligObj["light_in"], ligObj["light_out"])
        else:
            stSlat = sp.get("slatStatus")

        if (mosObj["average"] > 0):
            for i in range(0, int(sensorPoint)):
                print(" moisture at point " + str(i + 1) + ": " +
                      str(mosObj[("point" + str(i + 1))]) + " %")
        else:
            print(" moisture sensors error!")
        if (temObj["average"] > 0):
            for i in range(0, int(sensorPoint)):
                print(" temp at point     " + str(i + 1) + ":   " +
                      str(temObj[("point" + str(i + 1))]) + " *C")
        else:
            print(" temp sensors error!")
        print(" lightIn:          " + str(ligObj["light_in"]) + " Lux")
        print(" lightOut:         " + str(ligObj["light_out"]) + " Lux")
        print(" slat status:      " + str(stSlat))
        print("")

        print("  mosStd: " + str(sp.get(mosStd)))
        print("  tmpStd: " + str(sp.get(tmpStd)))
        print("  ligStd: " + str(sp.get(ligStd)))
        print("  fqPData: " + str(sp.get(fqPData)))
        print("  fqPImage: " + str(sp.get(fqPImage)))
        print("  fqIData: " + str(sp.get(fqIData)))
        print("  fqShower: " + str(sp.get(fqShower)))
        print("  ageData: " + str(sp.get(ageData)))
        print("  lastUpdate: " + str(sp.get(lastUpdate)))
        print("  autoMode: " + str(sp.get(autoMode)))
        print("")

        global isConn
        global nextTimePubData
        global nextTimePubImage
        global nextTimeInsertData
        global lastTimePubImage

        if (int(timeStamp) >= int(nextTimePubData)):
            if (isConn):
                payload = "{\"time\":" + str(
                    timeStamp) + ",\"moisture\":" + str(
                        json.dumps(mosObj)) + ",\"temp\":" + str(
                            json.dumps(temObj) + ",\"light\":" +
                            str(json.dumps(ligObj))) + "}"
                result, nextTime = gear.publishRawData(str(payload),
                                                       sp.get(fqPData),
                                                       timeStamp)
                if (result):
                    nextTimePubData = nextTime
        if (int(timeStamp) >= int(nextTimePubImage)):
            if (isConn):
                result, nextTime = gear.publishImage(sp.get(fqPImage),
                                                     timeStamp)
                if (result):
                    nextTimePubImage = nextTime
                    lastTimePubImage = timeStamp
        if (int(timeStamp) >= int(nextTimeInsertData)):
            reult, nextTime = db.insertRawData(timeStamp, mosObj, temObj,
                                               ligObj)
            if (reult):
                nextTimeInsertData = nextTime
                if (isConn):
                    gear.publisRawDataList()

        print("")
        print(" nextTimePubData: " +
              str(t.timeStampToDateTime(nextTimePubData)))
        print(" nextTimePubImage: " +
              str(t.timeStampToDateTime(nextTimePubImage)))
        print(" nextTimeInsertData: " +
              str(t.timeStampToDateTime(nextTimeInsertData)))
        print("")

        #Compare and validate
        global timeExceptWater
        global timeExceptShower

        if (sp.get(autoMode)):
            print("\nOn Work in Auto Mode...")
            if (t.isDay()):
                #-----------------------------------------------

                if (int(timeStamp) > int(timeExceptWater)):
                    result, timeExcept = compare.compareMosture(
                        timeStamp, mosObj, isConn)
                    if (result):
                        if (isConn):
                            gear.publisLogDataList()
                        timeExceptWater = 0
                    else:
                        if (int(timeExcept) > 0):
                            timeExceptWater = timeExcept
                else:
                    print("wait to " +
                          str(t.timeStampToDateTime(timeExceptWater)) +
                          " for water agains ")

                #-----------------------------------------------

                global lastTimeShower
                if (int(timeStamp) > int(timeExceptShower)):
                    result, timeExcept = compare.compareTemp(
                        timeStamp, temObj, lastTimeShower, isConn, mosObj,
                        stSlat, ligObj)
                    if (result):
                        if (isConn):
                            gear.publisLogDataList()
                        timeExceptShower = 0
                        lastTimeShower = timeStamp
                        sp.put("lastTimeShower", lastTimeShower)
                    else:
                        if (int(timeExcept) > 0):
                            timeExceptShower = timeExcept
                else:
                    print("wait to " +
                          str(t.timeStampToDateTime(timeExceptShower)) +
                          " for shower agains")

                #------------------------------------------------

                result, st = compare.compareLight(timeStamp, ligObj, stSlat,
                                                  isConn)
                if (result):
                    if (isConn):
                        gear.publisSlatStatus(st)

                #-------------------------------------------------

            else:
                print(" But this time is a nigth!...")
        else:
            print("manual mode....")

        checkNet(timeStamp)
        print("----------------------------------------------------\n")

        time.sleep(10)
Example #12
0

def reload():
    global nextTimePubData
    global nextTimeInsertData
    global nextTimePubImage
    global lastTimePubImage
    nextTimePubImage = int(
        int(lastTimePubImage) +
        (int(sp.get(fqPImage)) * int(3600)))  #1 hour in time stamp
    nextTimePubData = t.getNextTimePubData(sp.get(fqPData))
    nextTimeInsertData = t.getNextTimeInsertData(sp.get(fqIData))


#Start!!!-------------------------------------------
sp.getSharedPreferences()
global nextTimePubData
global nextTimeInsertData
nextTimePubData = t.getNextTimePubData(sp.get(fqPData))
nextTimeInsertData = t.getNextTimeInsertData(sp.get(fqIData))

if (network.isConnectInternet()):
    print("is connect internet")
    global isConn
    global timeCheckNet
    isConn = True
    timeCheckNet = (int(time.time()) + int(fqCheckNet))
    gear.onConnection()  #connect netpie
    ligObj = json.loads(inputs.getLightObject())
    gear.publisSlatStatus(
        getSlatStatus(ligObj["light_in"], ligObj["light_out"]))
Example #13
0
def settingDetails(payload):
    fqPData = "fqPData"         #frequency to publish data to netpie
    fqPImage = "fqPImage"       #frequency to publish image to netpie
    fqIData = "fqIData"         #frequency to insert data to database
    fqShower = "fqShower"       #frequency to shower (0 = auto, > 0 = user setting)
    ageData = "ageData"         #day off store data in database
    autoMode = "autoMode"       #auto mode
    lastUpdate = "lastUpdate"

    objDetails = json.loads(payload)

    if(int(objDetails[lastUpdate]) > int(sp.get(lastUpdate))):

        global hasReload
        hasReload = True

        for i in objDetails:
            print("  - key: "+str(i))
            print("  - value: "+str(objDetails[i]))
            print("  ---------------------")
            
            if(i == fqPData ):
                sp.put(fqPData,objDetails[i])
                
            elif(i== fqPImage):
                sp.put(fqPImage,objDetails[i])
                
            elif(i== fqIData):
                sp.put( fqIData,objDetails[i])
                
            elif(i == fqShower):
                sp.put(fqShower,objDetails[i])
               
            elif(i == ageData):
                sp.put(ageData,objDetails[i])
      
            elif(i== autoMode):
                sp.put(autoMode,objDetails[i])
            elif(i == lastUpdate):
                sp.put(lastUpdate,objDetails[i])
                
        if(isConnect()):
            response = json.dumps({"topic":"settingDetails","success":True,"message":payload})
            microgear.publish("/response",str(response))
Example #14
0
def controlsDevices(payload):
    success = False
    message = ""
    response = None
    
    if(payload == 1):
        print(" Water from user command")
        mosObj = json.loads(inputs.getMoistureObject())
        if(ctrl.water()): 
            time.sleep(10) #wait 10 second
            newMosObj = json.loads(inputs.getMoistureObject())
            print("  old moisture: "+str(mosObj["average"]))
            print("  new moisture: "+str(newMosObj["average"]))
            if((float(newMosObj["average"]-float(mosObj["average"])>5))):# if moisture value more than valus before
                onRefreshRawData()
                result = db.insertLogData(int(time.time()),1,2,float(mosObj["average"]),float(newMosObj["average"])) #insert log to database
                if(result):
                    print("  All success")
                    success = True
                    message = json.dumps({"working":payload,"valBefore":float(mosObj["average"]),"valAfter":float(newMosObj["average"])})
                    publisLogDataList()
                else:
                    message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(mosObj["average"]),"valAfter":float(newMosObj["average"])})  
            else:
                if((float(newMosObj["average"])>float(mosObj["average"]))>=1):
                    message = json.dumps({"errorCode":8,"working":payload,"valBefore":float(mosObj["average"]),"valAfter":float(newMosObj["average"])})
                    publisLogDataList()
                else:   
                    print("  Error! water not true Arare")
                    message = json.dumps({"working":payload,"errorCode":2,"msg":"water not true arare"})
        else:
            print("  Error! water not flows")
            message = json.dumps({"working":payload,"errorCode":1,"msg":"water not flows"})
     
    elif(payload == 2):
        print(" Shower from user command")
        fqShower = "fqShower"       #frequency to shower (0 = auto, > 0 = user setting)
        timeStamp = int(time.time())
        lastTimeShower = sp.get("lastTimeShower")
        print("lastTimeShower: "+str(lastTimeShower))
        minStamp = 60
        m = ""
        fq = sp.get(fqShower)
        if(fq == 0):
            fq = t.getFqShower()#get ferquency from system (fq in minute *60) minStamp
        if(int(timeStamp)>=(int(lastTimeShower)+(int(fq)*int(minStamp)))):
            temObj = json.loads(inputs.getTempObject())
            if(ctrl.shower()):
                time.sleep(10)
                newTemObj = json.loads(inputs.getTempObject())
                print("  old temp: "+str(temObj["average"]))
                print("  new temp: "+str(newTemObj["average"]))
                if(float(newTemObj["average"])<=float(temObj["average"])):
                    onRefreshRawData()
                    result = db.insertLogData(timeStamp,2,2,float(temObj["average"]),float(newTemObj["average"])) #insert log to database
                    if(result):
                        success = True
                        message = json.dumps({"working":payload,"valBefore":float(temObj["average"]),"valAfter":float(newTemObj["average"])})
                        print("  All success")
                        publisLogDataList()
                        sp.put("lastTimeShower",timeStamp)
                    else:
                        message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(temObj["average"]),"valAfter":float(newTemObj["average"])})
                else:
                    print(" Error! temp not decrease after shower")
                    message = json.dumps({"working":payload,"errorCode":3,"msg":"temp not decrease after shower"})
            else:
                print(" Error! water not flows")
                message = json.dumps({"working":payload,"errorCode":1,"msg":"water not flows"})
        else:
            nextTime = (int(lastTimeShower)+(int(fq)*int(minStamp)))
            print(" not time to shower, Working again at "+str(t.timeStampToDateTime(nextTime)))
            message = json.dumps({"working":payload,"errorCode":4,"msg":str(nextTime)})
 
    elif(payload == 3):
        print(" Open slat from user command")
        slatStatus = sp.get("slatStatus")   #status of slat
        print("  slatStatus: " +str(slatStatus))
        if(int(slatStatus) != 1):
            ligObj = json.loads(inputs.getLightObject())
            if(ctrl.openSlat()):#if can open slat
                time.sleep(10)
                newLigObj = json.loads(inputs.getLightObject())
                sp.put("slatStatus",str("1"))
                publisSlatStatus(1)
                result = db.insertLogData(int(time.time()),3,2,float(ligObj["light_in"]),float(newLigObj["light_in"])) #insert log to database
                onRefreshRawData()
                if(result):
                    publisLogDataList()
                    success = True
                    message = json.dumps({"working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])})
                    print("  All success")
                else:
                    message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])})
                    
        else:
            print("  slat is opened (1)")
            message = json.dumps({"working":payload,"errorCode":5,"msg":"slat is opened"})

    elif(payload == 4):
        print(" Close slat from user command")
        slatStatus = sp.get("slatStatus")   #status of slat
        print("  slatStatus: " +str(slatStatus))
        if(int(slatStatus) != 0):
            ligObj = json.loads(inputs.getLightObject())
            if(ctrl.closeSlat()): #if can close slat
                time.sleep(10)
                newLigObj = json.loads(inputs.getLightObject())
                print("  old light: "+str(ligObj["light_in"]))
                print("  new light: "+str(newLigObj["light_in"]))
                
                sp.put("slatStatus",str("0"))
                publisSlatStatus(0)
                result = db.insertLogData(int(time.time()),4,2,float(ligObj["light_in"]),float(newLigObj["light_in"])) #insert log to database
                onRefreshRawData()
                if(result):
                    publisLogDataList()
                else:
                    message = json.dumps({"errorCode":0,"msg":"database error","working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])})
                    
                if(float(newLigObj["light_in"]) < float(ligObj["light_in"])):
                    success = True
                    message = json.dumps({"working":payload,"valBefore":float(ligObj["light_in"]),"valAfter":float(newLigObj["light_in"])})
                else:
                    print("  new light value not decrease")
                    message = json.dumps({"working":payload,"errorCode":7,"msg":"light value not decrease"})
        else:
            print("  slat is closed (0)")
            message = json.dumps({"working":payload,"errorCode":6,"msg":"slat is closed"})

    response = json.dumps({"topic":"controlDevices","success":success,"message":message})
    #print("response: "+str(response))
    if(isConnect()):
        microgear.publish("/response",str(response))
Example #15
0
def compareLight(timeStamp, ligObj, st, isConn):
    result = False
    std = float(sp.get(ligStd))
    ligIn = float(ligObj["light_in"])
    ligOut = float(ligObj["light_out"])

    print("Compare, check light...")

    if ((ligIn > 0) and (ligOut > 0)):
        if ((ligIn > std) and (ligOut > std)):
            print(" light more than standard")
            if (st != 0):
                if (ctrl.closeSlat()):  #if can close slat
                    time.sleep(10)
                    newLigObj = json.loads(inputs.getLightObject())
                    if (float(newLigObj["light_in"]) > float(ligIn)):
                        print("  but new light value not decrease")
                        if (isConn):
                            noti = gcm.setData("except", str(7))
                            gcm.pushNotification(noti)
                db.insertLogData(
                    timeStamp, 4, 1, float(ligIn),
                    float(newLigObj["light_in"]))  #insert log to database
                sp.put(slatStatus, str("0"))
                result = True
                st = 0
            else:
                print(" but slat is closed (0)")
        elif ((ligIn < std) and (ligOut < std)):
            print(" light lessthan standard")
            if (st != 1):
                if (ctrl.openSlat()):  #if can open slat
                    time.sleep(10)
                    newLigObj = json.loads(inputs.getLightObject())
                    db.insertLogData(
                        timeStamp, 3, 1, float(ligIn),
                        float(newLigObj["light_in"]))  #insert log to database
                    sp.put(slatStatus, int(1))
                    result = True
                    st = 1
            else:
                print(" but slat is opened (1)")
    elif (float(ligObj["light_in"]) > 0):
        print(" light out error, Compare in one sensor mode")
        if (ligIn > std):  #close slat
            print(" light more than standard")
            if (st != 0):
                if (ctrl.closeSlat()):  #if can close slat
                    time.sleep(10)
                    newLigObj = json.loads(inputs.getLightObject())
                    if (float(newLigObj["light_in"]) > float(ligIn)):
                        print("  but new light value not decrease")
                        if (isConn):
                            noti = gcm.setData("except", str(5))
                            gcm.pushNotification(noti)
                db.insertLogData(
                    timeStamp, 4, 1, float(ligIn),
                    float(newLigObj["light_in"]))  #insert log to database
                sp.put(slatStatus, str("0"))
                result = True
                st = 0
            else:
                print(" but slat is closed (0)")

        elif ((std - ligIn) > 2000):  #open slat
            print(" light lessthan standard ever 2,000 lux")
            if (st != 1):
                if (ctrl.openSlat()):  #if can open slat
                    time.sleep(10)
                    newLigObj = json.loads(inputs.getLightObject())
                    db.insertLogData(
                        timeStamp, 3, 1, float(ligIn),
                        float(newLigObj["light_in"]))  #insert log to database
                    sp.put(slatStatus, int(1))
                    result = True
                    st = 1
            else:
                print(" but slat is opened (1)")

    else:
        print(" light sensor error!!")
    return result, st
Example #16
0
def compareTemp(timeStamp, temObj, lastTimeShower, isConn, mosObj, stSlat,
                ligObj):
    result = False
    timeExceptShower = 0
    print("Compare, check temp...")
    if (float(temObj["point1"]) > 0):  # chamge point1 to average
        if (float(temObj["average"]) > float(
                sp.get(tmpStd))):  # chamge point1 to average
            fq = sp.get(fqShower)
            if (fq == 0):
                fq = t.getFqShower(
                )  #get ferquency from system (fq in minute *60) minStamp
            print(" ferquency: " + str(fq) + " minute")
            if (int(timeStamp) >=
                (int(lastTimeShower) + (int(fq) * int(minStamp)))):
                if (float(mosObj["average"]) <= float(
                        sp.get(mosStd))):  #dgfbndgfnhdgnmhjmk
                    if (ctrl.shower()):
                        time.sleep(30)  #wait 30 seccond
                        newTemObj = json.loads(inputs.getTempObject())
                        print(
                            " old temp: " +
                            str(temObj["average"]))  # chamge point1 to average
                        print(" new temp: " + str(
                            newTemObj["average"]))  # chamge point1 to average
                        if (float(newTemObj["point1"]) <= float(
                                temObj["average"])
                            ):  # chamge point1 to average
                            print(" All success")
                            db.insertLogData(
                                timeStamp, 2, 1, float(temObj["average"]),
                                float(newTemObj["average"])
                            )  #insert log to database # chamge point1 to average
                            result = True
                        else:
                            print(" Error! temp not decrease after shower")
                            timeExceptShower = onExceptShower(
                                timeStamp, 3, isConn)
                    else:
                        print(" Error! water not flows")
                        timeExceptShower = onExceptShower(timeStamp, 1, isConn)
                else:
                    if (int(stSlat) == 1):  #close slat
                        ligIn = float(ligObj["light_in"])
                        ligOut = float(ligObj["light_out"])
                        if (ctrl.closeSlat()):  #if can close slat
                            time.sleep(10)
                            newLigObj = json.loads(inputs.getLightObject())
                            if (float(newLigObj["light_in"]) > float(ligIn)):
                                print("  but new light value not decrease")
                                if (isConn):
                                    noti = gcm.setData("except", str(7))
                                    gcm.pushNotification(noti)
                            db.insertLogData(timeStamp, 4, 1, float(ligIn),
                                             float(newLigObj["light_in"])
                                             )  #insert log to database
                            sp.put(slatStatus, str("0"))
                            result = True
                    else:
                        if (ctrl.shower()):
                            time.sleep(30)  #wait 30 seccond
                            newTemObj = json.loads(inputs.getTempObject())
                            print(" old temp: " + str(
                                temObj["average"]))  # chamge point1 to average
                            print(" new temp: " + str(newTemObj["average"])
                                  )  # chamge point1 to average
                            if (float(newTemObj["point1"]) <= float(
                                    temObj["average"])
                                ):  # chamge point1 to average
                                print(" All success")
                                db.insertLogData(
                                    timeStamp, 2, 1, float(temObj["average"]),
                                    float(newTemObj["average"])
                                )  #insert log to database # chamge point1 to average
                                result = True
                            else:
                                print(" Error! temp not decrease after shower")
                                timeExceptShower = onExceptShower(
                                    timeStamp, 3, isConn)
                        else:
                            print(" Error! water not flows")
                            timeExceptShower = onExceptShower(
                                timeStamp, 1, isConn)
            else:
                print(" not time to shower, Working again at " +
                      t.timeStampToDateTime((int(lastTimeShower) +
                                             (int(fq) * int(minStamp)))))
        else:
            print(" no working...")
    else:
        print(" temp sensor error!!")

    return result, timeExceptShower