Exemple #1
0
def checkUpdateTimes(items):
    notReporting = []
    try:
        mdbconn = mdb.connect(host=dbHost, user=dbUser, passwd=dbPassword, db=dbName)
        mc = mdbconn.cursor()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def ThermostatStatus():
    # The scheduler will run this as a separate thread
    # so I have to open and close the database within
    # this routine
    # print(time.strftime("%A, %B %d at %H:%M:%S"))
    # open the database and set up the cursor
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        for whichOne in ["North", "South"]:
            hc.execute("select address from thermostats " "where location=%s; ", (whichOne,))
            thermoIp = hc.fetchone()
            try:
                status = getThermoStatus(thermoIp)
            except:
                break
            # print whichOne + " reports: " + str(status)
            hc.execute(
                "update thermostats set `temp-reading` = %s, "
                "status = %s, "
                "`s-temp` = %s, "
                "`s-mode` = %s, "
                "`s-fan` = %s, "
                "peak = %s,"
                "utime = %s"
                "where location = %s;",
                (status[0], status[1], status[2], status[3], status[4], status[5], dbTimeStamp(), whichOne),
            )
            hdbconn.commit()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
Exemple #3
0
def handleTempSensor(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    #print "name       : ", jData["TempSensor"]["name"]
    #print "command    : ", jData["TempSensor"]["command"]
    #print "processor V: ", jData["TempSensor"]["voltage"]
    #print "room  T    : ", jData["TempSensor"]["temperature"]
    try:
        hdbconn = mdb.connect(host=hdbHost,
                              user=hdbUser,
                              passwd=hdbPassword,
                              db=hdbName)
        hc = hdbconn.cursor()
        lprint("recording tempsensor ", jData['TempSensor']['name'])
        hc.execute(
            "insert into tempsensor(name,"
            "pvolt, temp, utime)"
            "values (%s, %s, %s, %s);",
            (jData["TempSensor"]["name"], jData["TempSensor"]["voltage"],
             jData["TempSensor"]["temperature"], dbTimeStamp()))
        hdbconn.commit()
        hdbconn.close()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
        hdbconn.close()
def on_awsConnect(client, userdata, flags, rc):
    lprint("mqtt connection to AWSIoT returned result: " + str(rc) )
    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed. You still have to do the
    # reconnect in code because that doesn't happen automatically
    client.subscribe ([(awsShadowDelta , 1 ),
                      (awsShadowDocuments, 1)])
def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    if msg.topic == 'Desert-Home/Device/TempSensor':
        logIt("got room temperature sensor")
        handleTempSensor(msg.payload)
    elif msg.topic == 'Desert-Home/Device/Garage':
        logIt("got garage controller")
        handleGarage(msg.payload)
    elif msg.topic == 'Desert-Home/Device/HouseFreezer':
        logIt("got house freezer monitor")
        handleHouseFreezer(msg.payload)
    elif msg.topic == 'Desert-Home/Device/HouseFridge':
        logIt("got house fridge monitor")
        handleHouseFridge(msg.payload)
    elif msg.topic == 'Desert-Home/Device/GarageFreezer':
        logIt("got garage freezer monitor")
        handleGarageFreezer(msg.payload)
    elif msg.topic == 'Desert-Home/Device/PowerMon':
        logIt("got power monitor")
        handlePowerMon(msg.payload)
    elif msg.topic == 'Desert-Home/Device/WaterHeater':
        logIt("got waterheater")
        handleWaterHeater(msg.payload)
    else:
        lprint("got odd topic back: {}".format(msg.topic))
        logIt("got odd topic back: {}".format(msg.topic))
    # update the timer for saving things.
    checkTimer.tick()
Exemple #6
0
def updateDatabase(whichone, status, force=False):
    ''' 
    This is running on a Pi and is not event driven, so polling like
    this will result in considerable wear to the SD card.  So, I'm going to 
    read the database to see if it needs to be changed before I change it.  
    According to everything I've read, reads are free, it's the writes that
    eat up the card.
    '''
    dbconn = mdb.connect(host=dbHost,
                         user=dbUser,
                         passwd=dbPassword,
                         db=dbName)
    c = dbconn.cursor()
    c.execute("select status from wemo where name = %s;", (whichone, ))
    oldstatus = c.fetchone()
    if oldstatus[0] != status or force == True:
        lprint("Had to update database %s, %s" % (whichone, status))
        try:
            c.execute(
                "update wemo "
                "set status = %s, utime = %s where name = %s;",
                (status, dbTimeStamp(), whichone))
            dbconn.commit()
        except mdb.Error, e:
            lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
Exemple #7
0
def sendMail(subject, body):
    global mailTime

    now = datetime.datetime.now()
    if (now < (mailTime + timedelta(hours=1))):
        return
    try:
        fromaddr = hv["emailaddr"]
        toaddr = hv["emailaddr"]
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = subject

        body = body
        msg.attach(MIMEText(body, 'plain'))

        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(fromaddr, hv["mailpassword"])
        text = msg.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()
    except subprocess.CalledProcessError, e:
        lprint(e.output)
        lprint(e.cmd)
Exemple #8
0
def handleGarage(data):
    #print("Got Garage")
    #print(data)
    # This is not JSON, it's a comma separated list
    rxList = data.split(',')
    if rxList[0] != 'Garage':
        logIt("published as Garage, but found {}".format(rxList[0]))
    if len(rxList) > 2:  #this means it's a status from the garage
        # not a command to the garage
        #print "updating garage in database"
        # Now stick it in the database
        try:
            hdbconn = mdb.connect(host=hdbHost,
                                  user=hdbUser,
                                  passwd=hdbPassword,
                                  db=hdbName)
            hc = hdbconn.cursor()
            hc.execute(
                "update garage set door1 = %s, "
                "door2 = %s,"
                "waterh = %s,"
                "utime = %s;",
                (rxList[1], rxList[2], rxList[3].rstrip(), dbTimeStamp()))
            hdbconn.commit()
        except mdb.Error, e:
            lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
        hdbconn.close()
def handleGarage(data):
    #print("Got Garage")
    #print(data)
    # This is not JSON, it's a comma separated list
    rxList = data.split(',')
    if rxList[0] != 'Garage':
        logIt("published as Garage, but found {}".format(rxList[0]))
    if len(rxList) > 2: #this means it's a status from the garage
                        # not a command to the garage
        #print "updating garage in database"
        # Now stick it in the database
        try:
            hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
            hc = hdbconn.cursor()
#            hc.execute("update garage set door1 = %s, "
#                "door2 = %s,"
#                "waterh = %s,"
#                "utime = %s;",
#                (rxList[1], rxList[2],rxList[3].rstrip(),
#                dbTimeStamp())) 
            hc.execute("insert into garage (door1, door2, waterh, utime)"
                "values(%s, %s, %s, %s);",
                (rxList[1], rxList[2], rxList[3].rstrip(),
                dbTimeStamp() ))
            hdbconn.commit()
        except mdb.Error, e:
            lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
        hdbconn.close()
def getIt(c, query):
    try:
        c.execute(query)
        result = c.fetchone()[0]
        #print "gotback", result
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def checkUpdateTimes(items):
    notReporting = []
    try:
        mdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        mc = mdbconn.cursor()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
Exemple #12
0
def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    if msg.topic == 'Desert-Home/Device/TempSensor':
        logIt("got room temperature sensor")
        handleTempSensor(msg.payload)
    elif msg.topic == 'Desert-Home/Device/Garage':
        logIt("got garage controller")
        handleGarage(msg.payload)
    elif msg.topic == 'Desert-Home/Device/HouseFreezer':
        logIt("got house freezer monitor")
        handleHouseFreezer(msg.payload)
    elif msg.topic == 'Desert-Home/Device/HouseFridge':
        logIt("got house fridge monitor")
        handleHouseFridge(msg.payload)
    elif msg.topic == 'Desert-Home/Device/GarageFreezer':
        logIt("got garage freezer monitor")
        handleGarageFreezer(msg.payload)
    elif msg.topic == 'Desert-Home/Device/PowerMon':
        logIt("got power monitor")
        handlePowerMon(msg.payload)
    else:
        lprint("got odd topic back: {}".format(msg.topic))
        logIt("got odd topic back: {}".format(msg.topic))
    # update the timer for saving things.
    checkTimer.tick()
Exemple #13
0
def getIt(c, query):
    try:
        c.execute(query)
        result = c.fetchone()[0]
        #print "gotback", result
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def sendMail(subject, body):
    global mailTime
    
    now = datetime.datetime.now()
    if ( now < (mailTime + timedelta(hours=1)) ):
        return
    try:
        fromaddr = hv["emailaddr"]
        toaddr = hv["emailaddr"]
        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = subject
         
        body = body
        msg.attach(MIMEText(body, 'plain'))
         
        server = smtplib.SMTP('smtp.gmail.com', 587)
        server.starttls()
        server.login(fromaddr, hv["mailpassword"])
        text = msg.as_string()
        server.sendmail(fromaddr, toaddr, text)
        server.quit()    
    except subprocess.CalledProcessError, e:
        lprint (e.output)
        lprint (e.cmd)
Exemple #15
0
def poolMotorState():
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("select motor from pool")
        tmp = hc.fetchone()[0];
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
Exemple #16
0
def openSite(Url):
    lprint (Url)
    webHandle = None
    try:
        webHandle = urllib2.urlopen(Url, timeout=5) #if it doesn't answer in 5 seconds, it won't
    except urllib2.HTTPError, e:
        errorDesc = BaseHTTPServer.BaseHTTPRequestHandler.responses[e.code][0]
        print "Error: cannot retrieve URL: " + str(e.code) + ": " + errorDesc
def printHouseData():
    lprint('Power Data: Current %s, Min %s, Max %s' %
           (int(float(CurrentPower)), int(
               float(DayMinPower)), int(float(DayMaxPower))))
    lprint('Outside Temp: Current %s, Min %s, Max %s' %
           (int(float(CurrentOutTemp)), int(
               float(DayOutMinTemp)), int(float(DayOutMaxTemp))))
    print
def gracefulEnd():
    lprint("****************************got to gracefulEnd")
    scheditem.shutdown(wait=False)  # shut down the apscheduler
    # halt() must be called before closing the serial
    # port in order to ensure proper thread shutdown
    # for the xbee thread
    zb.halt()  # shut down the XBee receive thread
    ser.close()
def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    if msg.topic == 'Desert-Home/Device/Barometer':
        logIt("got barometer")
        handleBarometer(msg.payload)
    else:
        lprint("got odd topic back: {}".format(msg.topic))
        logIt("got odd topic back: {}".format(msg.topic))
def gracefulEnd():
    lprint("****************************got to gracefulEnd")
    scheditem.shutdown(wait=False)  # shut down the apscheduler
    # halt() must be called before closing the serial
    # port in order to ensure proper thread shutdown
    # for the xbee thread
    zb.halt()  # shut down the XBee receive thread
    ser.close()
def controlThermo(whichOne, command):
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("select address from thermostats " "where location=%s; ", (whichOne,))
        thermoIp = hc.fetchone()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def on_message(client, userdata, msg):
    #print(msg.topic+" "+str(msg.payload))
    if msg.topic == 'Desert-Home/Device/Barometer':
        logIt("got barometer")
        handleBarometer(msg.payload)
    else:
        lprint("got odd topic back: {}".format(msg.topic))
        logIt("got odd topic back: {}".format(msg.topic))
def sendCommand(deviceGroup, command):
    lprint("alexa send to " + deviceGroup + ' ' + command)
    err = dhMqtt.publish("Desert-Home/Command/"+deviceGroup, command)
    if err[0] != 0:
        lprint("got error {} on publish".format(err[0]))
        # This is likely a broken pipe from mqtt timout, just reconnect
        # because AWS will send the message over and over until it is 
        # taken care of.
        dhMqtt.reconnect()
Exemple #24
0
def openSite(Url):
    lprint(Url)
    webHandle = None
    try:
        webHandle = urllib2.urlopen(
            Url, timeout=5)  #if it doesn't answer in 5 seconds, it won't
    except urllib2.HTTPError, e:
        errorDesc = BaseHTTPServer.BaseHTTPRequestHandler.responses[e.code][0]
        print "Error: cannot retrieve URL: " + str(e.code) + ": " + errorDesc
def sendCommand(deviceGroup, command):
    lprint("alexa send to " + deviceGroup + ' ' + command)
    err = dhMqtt.publish("Desert-Home/Command/" + deviceGroup, command)
    if err[0] != 0:
        lprint("got error {} on publish".format(err[0]))
        # This is likely a broken pipe from mqtt timout, just reconnect
        # because AWS will send the message over and over until it is
        # taken care of.
        dhMqtt.reconnect()
def printHouseData():
    lprint(
        "Power Data: Current %s, Min %s, Max %s"
        % (int(float(CurrentPower)), int(float(DayMinPower)), int(float(DayMaxPower)))
    )
    lprint(
        "Outside Temp: Current %s, Min %s, Max %s"
        % (int(float(CurrentOutTemp)), int(float(DayOutMinTemp)), int(float(DayOutMaxTemp)))
    )
    print
def keepAlive():
    '''
    I update the database periodically with the time so I can check to see 
    if things are holding together.  I currently use the time in the light 
    switch records for this.
    '''
    lprint(" keep alive")
    for switch in switches:
        thisOne = switch['name']
        updateDatabase(thisOne, get(thisOne), force=True)
def checkTempSensor(name, hc):
    try:
        select = "SELECT pvolt FROM tempsensor where name = '" + name + "' ORDER BY rdate DESC limit 1"
        hc.execute(select)
        volt = hc.fetchone()[0]
        print "Voltage at", name, "is", volt
        if float(volt) < 2.5:
            return {name:volt}
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
Exemple #29
0
def keepAlive():
    '''
    I update the database periodically with the time so I can check to see 
    if things are holding together.  I currently use the time in the light 
    switch records for this.
    '''
    lprint(" keep alive")
    for switch in switches:
        thisOne = switch['name']
        updateDatabase(thisOne, get(thisOne), force=True)
Exemple #30
0
def poolMotorState():
    try:
        hdbconn = mdb.connect(host=hdbHost,
                              user=hdbUser,
                              passwd=hdbPassword,
                              db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("select motor from pool")
        tmp = hc.fetchone()[0]
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def get(whichone):
    ''' 
    Returns On or Off
    '''
    resp = sendCommand('GetBinaryState', whichone, {})
    if resp is not None:
        try:
            tagValue = extractSingleTag(resp, 'BinaryState').split('|')[0]
            return 'Off' if tagValue == '0' else 'On'
        except:
            lprint("Couldn't get BinaryState")
    return 'Off'
Exemple #32
0
def get(whichone):
    ''' 
    Returns On or Off
    '''
    resp = sendCommand('GetBinaryState', whichone, {})
    if resp is not None:
        try:
            tagValue = extractSingleTag(resp, 'BinaryState').split('|')[0]
            return 'Off' if tagValue == '0' else 'On'
        except:
            lprint("Couldn't get BinaryState")
    return 'Off'
def checkGarageFreezer():    
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("SELECT temperature FROM garagefreezer ORDER BY timestamp DESC limit 1")
        temp = hc.fetchone()[0]
        cutOff = hv["housefreezertemp"]
        print "Garage freezer", temp, cutOff
        if temp > cutOff:
            return {"Garage Freezer":temp}
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def off(whichone):
    """
    BinaryState is set to 'Error' in the case that it was already off.
    """
    resp = sendCommand('SetBinaryState', whichone, {'BinaryState': (0, 'Boolean')})
    if resp is not None:
        tagValue = extractSingleTag(resp, 'BinaryState').split('|')[0]
        status = 'Off' if tagValue in ['0', 'Error'] else 'On'
        handleUpdate(whichone, status)
        lprint("turned %s off"%(whichone))
        return status
    return 'Off'
Exemple #35
0
def off(whichone):
    """
    BinaryState is set to 'Error' in the case that it was already off.
    """
    resp = sendCommand('SetBinaryState', whichone, {'BinaryState': (0, 'Boolean')})
    if resp is not None:
        tagValue = extractSingleTag(resp, 'BinaryState').split('|')[0]
        status = 'Off' if tagValue in ['0', 'Error'] else 'On'
        handleUpdate(whichone, status)
        lprint("turned %s off"%(whichone))
        return status
    return 'Off'
def controlThermo(whichOne, command):
    try:
        hdbconn = mdb.connect(host=hdbHost,
                              user=hdbUser,
                              passwd=hdbPassword,
                              db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("select address from thermostats "
                   "where location=%s; ", (whichOne, ))
        thermoIp = hc.fetchone()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def monitorTheMonitor():
    #Check to see if all the processes are running
    deadOnes = processExists(processList)
    lateOnes = checkUpdateTimes(recordList)
    if (len(deadOnes) != 0 or len(lateOnes) != 0):
        badThings = "Problems with %s %s"%(str(deadOnes), str(lateOnes))
        lprint ("Problem with: ", badThings)
        sendMail("Problem Found", badThings)
    otherThings = checkOtherThings()
    if len(otherThings) != 0:
        somethingBad = str(otherThings)
        lprint ("Problem with:", somethingBad)
        sendMail("Problem Found", somethingBad)
Exemple #38
0
def monitorTheMonitor():
    #Check to see if all the processes are running
    deadOnes = processExists(processList)
    lateOnes = checkUpdateTimes(recordList)
    if (len(deadOnes) != 0 or len(lateOnes) != 0):
        badThings = "Problems with %s %s" % (str(deadOnes), str(lateOnes))
        lprint("Problem with: ", badThings)
        sendMail("Problem Found", badThings)
    otherThings = checkOtherThings()
    if (len(otherThings) != 0):
        somethingBad = "Go check %s" % (str(otherThings))
        lprint("Problem with:", somethingBad)
        sendMail("Problem Found", somethingBad)
def updateIotShadow():
    dbconn = mdb.connect(host=dbHost,
                         user=dbUser,
                         passwd=dbPassword,
                         db=dbName)
    try:
        c = dbconn.cursor()
        c.execute("select reading from ftemperature where utime = "
                  "(select max(utime) from ftemperature);")
        temperature = c.fetchone()[0]
        c.execute("select reading from barometer where utime = "
                  "(select max(utime) from barometer);")
        barometer = c.fetchone()[0]
        c.execute("select reading from humidity where utime = "
                  "(select max(utime) from humidity);")
        humidity = c.fetchone()[0]
        c.execute("select speed from wind where utime = "
                  "(select max(utime) from wind);")
        windSpeed = c.fetchone()[0]
        c.execute("select directionc from wind where utime = "
                  "(select max(utime) from wind);")
        windDirectionC = c.fetchone()[0]
        directionStrings = {
            "N": "north",
            "NNE": "north northeast",
            "NE": "northeast",
            "ENE": "east northeast",
            "E": "east ",
            "ESE": "east southeast",
            "SE": "south east",
            "SSE": "south southeast",
            "S": "south",
            "SSW": "south southwest",
            "SW": "southwest",
            "WSW": "west southwest",
            "W": "west",
            "WNW": "west northwest",
            "NW": "northwest",
            "NNW": "north northwest"
        }
        directionString = directionStrings[windDirectionC]
        c.execute("SELECT reading, rdate FROM `raincounter` "
                  "where rdate > date_sub(now(), interval 24 hour) "
                  "ORDER BY `rdate` asc limit 1")
        startCount = c.fetchone()[0]
        c.execute("select reading  from raincounter where rdate = "
                  "(select max(rdate) from raincounter);")
        endCount = c.fetchone()[0]
        rainToday = str((float(endCount) - float(startCount)) * 0.01)
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def updateXively():
    lprint ("Updating Xively Legacy ")
    sys.stdout.flush()
    # Currently I have to use UTC for the time,
    # there's a bug somewhere in the library or 
    # Xively.  It doesn't matter though because
    # it's easy to convert
    now = datetime.datetime.utcnow()
    # open the database
    try:
        wdbconn = mdb.connect(host=wdbHost, user=wdbUser, passwd=wdbPassword, db=wdbName)
        wc = wdbconn.cursor()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def handleBarometer(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    pressure = jData["Barometer"]["pressure"]
    temperature = jData["Barometer"]["temperature"]
    #print "Pressure is: " + pressure
    #print "Temperature is: " + temperature
    try:
        dbconn = mdb.connect(host=dbHost,
                             user=dbUser,
                             passwd=dbPassword,
                             db=dbName)
        c = dbconn.cursor()
        c.execute("insert into barometer (reading, utime)"
                  "values(%s, %s);", (pressure, dbTimeStamp()))
        c.execute(
            "insert into ftemperature (reading, utime)"
            "values(%s, %s);", (temperature, dbTimeStamp()))
        dbconn.commit()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def handleBarometer(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    pressure = jData["Barometer"]["pressure"]
    temperature = jData["Barometer"]["temperature"]
    #print "Pressure is: " + pressure
    #print "Temperature is: " + temperature
    try:
        dbconn = mdb.connect(host=dbHost, user=dbUser, passwd=dbPassword, db=dbName)
        c = dbconn.cursor()
        c.execute("insert into barometer (reading, utime)"
            "values(%s, %s);",
            (pressure,dbTimeStamp()))
        c.execute("insert into ftemperature (reading, utime)"
            "values(%s, %s);",
            (temperature,dbTimeStamp()))
        dbconn.commit()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
Exemple #43
0
def switchOff(whichOne):
    print "Turning Off", whichOne;
    try:
        if (hv["iriscontrol"][whichOne] == "switchable"):
            databytes1 = '\x01'
            databytesOff = '\x00\x01'
            sendSwitch(sSwitches[whichOne]["lAddress"], sSwitches[whichOne]["sAddress"],
            '\x00', '\x02', '\x00\xee', '\xc2\x16', '\x01', databytes1)
            sendSwitch(sSwitches[whichOne]["lAddress"], sSwitches[whichOne]["sAddress"], 
            '\x00', '\x02', '\x00\xee', '\xc2\x16', '\x02', databytesOff)
        else:
            lprint(whichOne + "cannot be switched")
    except KeyError:
        print "couldn't find an entry in .houserc for", whichOne
Exemple #44
0
def updatePower():
    #print ('rpower %s, apower %s, pfactor %s, voltage %s, current %s, frequency %s' 
    #   %(rpower, apower, pfactor, voltage, current, frequency))
    #print "updating power in database"
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("insert into power (rpower, apower, pfactor, voltage, current, frequency, utime)"
            "values(%s,%s,%s,%s,%s,%s,%s);",
            (rpower, apower, pfactor, voltage, current, 
            frequency, dbTimeStamp()))
        hdbconn.commit()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def switchOff(whichOne):
    print "Turning Off", whichOne;
    try:
        if (hv["iriscontrol"][whichOne] == "switchable"):
            databytes1 = '\x01'
            databytesOff = '\x00\x01'
            sendSwitch(sSwitches[whichOne]["lAddress"], sSwitches[whichOne]["sAddress"],
            '\x00', '\x02', '\x00\xee', '\xc2\x16', '\x01', databytes1)
            sendSwitch(sSwitches[whichOne]["lAddress"], sSwitches[whichOne]["sAddress"], 
            '\x00', '\x02', '\x00\xee', '\xc2\x16', '\x02', databytesOff)
        else:
            lprint(whichOne + "cannot be switched")
    except KeyError:
        print "couldn't find an entry in .houserc for", whichOne
def handleWaterHeater(data):
    print "updating water heater in database"
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    print jData
    print "voltage       : ", jData["WaterHeater"]["V"]
    print "current       : ", jData["WaterHeater"]["I"]
    print "power         : ", jData["WaterHeater"]["P"]
    print "energy        : ", jData["WaterHeater"]["E"]
    print "top temp      : ", jData["WaterHeater"]["TT"]
    print "bottom temp   : ", jData["WaterHeater"]["BT"]
    print "power applied : ", jData["WaterHeater"]["PA"]
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        whichone = dbTimeStamp()
        hc.execute("insert into waterheater (voltage, current, power, energy,ttemp,btemp,waterh)"
            "values(%s,%s,%s,%s,%s,%s,%s);",
            (jData["WaterHeater"]["V"],
            jData["WaterHeater"]["I"],
            jData["WaterHeater"]["P"],
            jData["WaterHeater"]["E"],
            jData["WaterHeater"]["TT"],
            jData["WaterHeater"]["BT"],
            jData["WaterHeater"]["PA"]
            ))
        hdbconn.commit()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def handleTempSensor(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    #print "name       : ", jData["TempSensor"]["name"]
    #print "command    : ", jData["TempSensor"]["command"]
    #print "processor V: ", jData["TempSensor"]["voltage"]
    #print "room  T    : ", jData["TempSensor"]["temperature"]
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, 
            passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        #lprint ("recording tempsensor ", jData['TempSensor']['name'])
        hc.execute("insert into tempsensor(name,"
            "pvolt, temp, utime)"
            "values (%s, %s, %s, %s);",
            (jData["TempSensor"]["name"],
            jData["TempSensor"]["voltage"],
            jData["TempSensor"]["temperature"],
            dbTimeStamp()))
        hdbconn.commit()
        hdbconn.close()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
        hdbconn.close()
def updatePower():
    #print ('rpower %s, apower %s, pfactor %s, voltage %s, current %s, frequency %s' 
    #  %(rpower, apower, pfactor, voltage, current, frequency))
    #print "updating power in database"
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("insert into power (rpower, apower, pfactor, voltage, current, frequency, utime)"
            "values(%s,%s,%s,%s,%s,%s,%s);",
            (rpower, apower, pfactor, voltage, current, 
            frequency, dbTimeStamp()))
        hdbconn.commit()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def handleHouseFreezer(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    #print "temp       : ", jData["housefreezer"]["temperature"]
    #print "defroster  : ", jData["housefreezer"]["defroster"]
    #print "utime      : ", jData["housefreezer"]["utime"]
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        whichone = dbTimeStamp()
        hc.execute("insert into housefreezer (temperature, defroster, utime)"
            "values(%s,%s,%s);",
            (jData["housefreezer"]["temperature"],
            jData["housefreezer"]["defroster"],
            whichone))
        hc.execute("select watts from smartswitch where name = 'freezer';")
        watts = hc.fetchone()[0]
        hc.execute("update housefreezer set watts = %s"
            "where utime = %s;",
            (watts, whichone));
        hdbconn.commit()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
Exemple #50
0
def handleHouseFreezer(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    #print "temp       : ", jData["housefreezer"]["temperature"]
    #print "defroster  : ", jData["housefreezer"]["defroster"]
    #print "utime      : ", jData["housefreezer"]["utime"]
    try:
        hdbconn = mdb.connect(host=hdbHost,
                              user=hdbUser,
                              passwd=hdbPassword,
                              db=hdbName)
        hc = hdbconn.cursor()
        whichone = dbTimeStamp()
        hc.execute(
            "insert into housefreezer (temperature, defroster, utime)"
            "values(%s,%s,%s);",
            (jData["housefreezer"]["temperature"],
             jData["housefreezer"]["defroster"], whichone))
        hc.execute("select watts from smartswitch where name = 'freezer';")
        watts = hc.fetchone()[0]
        hc.execute("update housefreezer set watts = %s"
                   "where utime = %s;", (watts, whichone))
        hdbconn.commit()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
def checkTempSensors():
    sensors = {"Temp1":"Master BR", "Temp2":"Great Room", "Temp3":"Office", "Temp4":"Living Room", "Temp5":"Guest BR"}
    battLow = []
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        for key, value in sensors.iteritems():
            result = checkTempSensor(key, hc)
            if result is not None:
                k, v = result.items()[0]
                #print sensors[k],v
                battLow.append(sensors[k]+" battery is at "+v)
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def updateIotShadow():
    dbconn = mdb.connect(host=dbHost, user=dbUser, passwd=dbPassword, db=dbName)
    try:
        c = dbconn.cursor()
        c.execute("select reading from ftemperature where utime = "
                "(select max(utime) from ftemperature);")
        temperature = c.fetchone()[0]
        c.execute("select reading from barometer where utime = "
                "(select max(utime) from barometer);")
        barometer = c.fetchone()[0]
        c.execute ("select reading from humidity where utime = "
                "(select max(utime) from humidity);")
        humidity = c.fetchone()[0]
        c.execute("select speed from wind where utime = "
                "(select max(utime) from wind);")
        windSpeed = c.fetchone()[0]
        c.execute("select directionc from wind where utime = "
                "(select max(utime) from wind);")
        windDirectionC = c.fetchone()[0]
        directionStrings = {
        "N":"north",
        "NNE":"north northeast",
        "NE":"northeast",
        "ENE":"east northeast",
        "E":"east ",
        "ESE":"east southeast",
        "SE":"south east",
        "SSE":"south southeast",
        "S":"south",
        "SSW":"south southwest",
        "SW":"southwest",
        "WSW":"west southwest",
        "W":"west",
        "WNW":"west northwest",
        "NW":"northwest",
        "NNW":"north northwest"
        }
        directionString = directionStrings[windDirectionC]
        c.execute("SELECT reading, rdate FROM `raincounter` "
                "where rdate > date_sub(now(), interval 24 hour) "
                "ORDER BY `rdate` asc limit 1"
            )
        startCount = c.fetchone()[0]
        c.execute("select reading  from raincounter where rdate = "
                "(select max(rdate) from raincounter);")
        endCount = c.fetchone()[0]
        rainToday = str((float(endCount) - float(startCount)) * 0.01)
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
def on_Message(client, userdata, msg):
    # This is receiving messages from the local mqtt server
    # that (most likely) were originated from Amazon Alexa
    # Note that this isn't limited to Alexa only, they could have
    # come from any other process
    lprint(msg.topic, msg.payload)
    device = msg.payload.partition(' ')[0]
    newstate = msg.payload.partition(' ')[2]
    if device == "mbLight" :
        if newstate == 'on':
            switchOn("mbdrm")
        else:
            switchOff("mbdrm")
    else:
        lprint("alexa doesn't know about device " + device)
def on_Message(client, userdata, msg):
    # This is receiving messages from the local mqtt server
    # that (most likely) were originated from Amazon Alexa
    # Note that this isn't limited to Alexa only, they could have
    # come from any other process
    lprint(msg.topic, msg.payload)
    device = msg.payload.partition(' ')[0]
    newstate = msg.payload.partition(' ')[2]
    if device == "mbLight":
        if newstate == 'on':
            switchOn("mbdrm")
        else:
            switchOff("mbdrm")
    else:
        lprint("alexa doesn't know about device " + device)
Exemple #55
0
def updateXively():
    lprint("Updating Xively Legacy ")
    sys.stdout.flush()
    # Currently I have to use UTC for the time,
    # there's a bug somewhere in the library or
    # Xively.  It doesn't matter though because
    # it's easy to convert
    now = datetime.datetime.utcnow()
    # open the database
    try:
        wdbconn = mdb.connect(host=wdbHost,
                              user=wdbUser,
                              passwd=wdbPassword,
                              db=wdbName)
        wc = wdbconn.cursor()
    except mdb.Error, e:
        lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
Exemple #56
0
def handleTempSensor(data):
    try:
        jData = json.loads(data)
    except ValueError as err:
        lprint(err)
        lprint("The buffer:")
        lprint(str(msg.payload))
        return
    #print jData
    #print "name       : ", jData["TempSensor"]["name"]
    #print "command    : ", jData["TempSensor"]["command"]
    #print "processor V: ", jData["TempSensor"]["voltage"]
    #print "room  T    : ", jData["TempSensor"]["temperature"]
    try:
        hdbconn = mdb.connect(host=hdbHost, user=hdbUser, 
            passwd=hdbPassword, db=hdbName)
        hc = hdbconn.cursor()
        hc.execute("select count(*) from tempsensor where name = %s;", 
            (jData['TempSensor']['name'],))
        count = hc.fetchone()[0]
        if count == 0:
            lprint ("Adding new tempSensor")
            hc.execute("insert into tempsensor(name,"
                "pvolt, temp, utime)"
                "values (%s, %s, %s, %s);",
                (jData["TempSensor"]["name"],
                jData["TempSensor"]["voltage"],
                jData["TempSensor"]["temperature"],
                dbTimeStamp()))
        else:
            #lprint ("updating tempsensor ", jData['TempSensor']['name'])
            hc.execute("update tempsensor set " 
                "pvolt = %s,"
                "temp = %s,"
                "utime = %s where name = %s ;",
                (jData['TempSensor']['voltage'],
                jData['TempSensor']['temperature'],
                dbTimeStamp(), 
                jData['TempSensor']['name']
                ))
            hdbconn.commit()
            hdbconn.close()
    except mdb.Error, e:
        lprint ("Database Error %d: %s" % (e.args[0],e.args[1]))
        hdbconn.close()
Exemple #57
0
def sendCommand(actionName, whichOne, actionArguments):
    result = sendSoap(actionName, whichOne, actionArguments)
    if result is not None:
        return result
    # it failed, now we have to do something about it
    # first, get the switch entry to check for a port change
    for item in switches:
        if item["name"] == whichOne:
            thisOne = item
            break
    switchIp = item["ip"]
    switchPort = item["port"]
    # try to get the port number from the switch a few times
    for i in range(0, 3):  # Only try this three times
        lprint("Trying to recover the switch %s" % whichOne)
        # getPort doesn't use sendSoap, so this call won't recurs
        newEntry = getPort(switchIp)
        # if the port changed, try and get the new one
        if newEntry is not None:
            # fine, it's at least alive, grab the port number,
            # print something, and and stuff it in the database
            # if it didn't change this won't break it, but if
            # it did change, this will fix it.
            item["port"] = newEntry["port"]
            lprint("Switch", whichOne, "changed ip from", switchPort, "to",
                   newEntry["port"])
            dbconn = mdb.connect(host=dbHost,
                                 user=dbUser,
                                 passwd=dbPassword,
                                 db=dbName)
            c = dbconn.cursor()
            try:
                c.execute("update wemo "
                          "set port=%s where name = %s;",
                          (newEntry["port"], whichOne))
            except mdb.Error, e:
                lprint("Database Error %d: %s" % (e.args[0], e.args[1]))
            dbconn.commit()
            dbconn.close()
            # now try the command again
            # if it died completely it may have come back by now,
            # or if the port changed, this will try it one more time
            # it needs a limit this because this call will recurs
            result = sendSoap(actionName, whichOne, actionArguments)
            if result is not None:
                lprint("Switch recovered")
                return result
            time.sleep(1)  #give the switch time to catch its breath
        else:
            # this means the switch is not responding to HTML
            # so try the getPort again to see if it's back yet
            # There's no point in sending the soap command yet
            time.sleep(1)  #give the switch time to catch its breath
            continue
Exemple #58
0
def on_Message(client, userdata, msg):
    # This is receiving messages from the local mqtt server
    # that (most likely) were originated from Amazon Alexa
    # Note that this isn't limited to Alexa only, they could have
    # come from any other process
    lprint(msg.topic, msg.payload)
    device = msg.payload.partition(' ')[0]
    newstate = msg.payload.partition(' ')[2]
    if device == "eastPatioLight":
        if newstate == 'on':
            on("patio")
        else:
            off("patio")
    elif device == "outsideLights":
        if newstate == 'on':
            outsideLightsOn()
        else:
            outsideLightsOff()
    else:
        lprint("Don't know about " + device)
Exemple #59
0
def handleCommand(command):
    # Commands come in as something like 'reset all'
    #print command
    c = str(command[0]).split(' ') 
    #print repr(c)
    todo = c[0]
    what = c[1].strip(' ')
    # now I have a list like ['todo', 'what']
    lprint ("command is:",todo,what)
    if (todo == 'reset'):
        lprint ("This is where the reset happens")
        if (what == 'all'):
            lprint ("Doing a master reset")
            processes = ["monitorhouse", "houseevents", "wemocontrol",
                "updateoldxively", "watchappliance", "iriscontrol"]
            for process in processes:
                fixProcess(process)
        else:
            lprint ("Unimplemented process")
    else:
        lprint ("Unimplemented Command")
Exemple #60
0
def handleCommand(command):
    lprint(str(command))
    # the command comes in from php as something like
    # ('s:17:"AcidPump, pumpOff";', 2)
    # so command[0] is 's:17:"AcidPump, pumpOff'
    # then split it at the "  and take the second item
    try:
        c = str(command[0].split('\"')[1]).split(',')
    except IndexError:
        c = str(command[0]).split(' ')    #this is for something I sent from another process
    lprint(c)
    if (c[0] == 'OutsideLightsOn'):
        outsideLightsOn()
    elif (c[0] == 'OutsideLightsOff'):
        outsideLightsOff()
    elif (c[0] == 'fPorchToggle'):
        toggle("frontporch")
    elif(c[0] == 'garageToggle'):
        toggle("outsidegarage")
    elif (c[0] == 'cactusToggle'):
        toggle("cactusspot")
    elif (c[0] == 'patioToggle'):
        toggle("patio")
    elif (c[0] == 'patioOff'):
        off('patio');
    else:
        lprint("Weird command = " + str(c))