예제 #1
0
def processWeatherSenseTB(sLine):
    # weathersense protocol 16
    state = json.loads(sLine)
    myProtocol = state['weathersenseprotocol']

    if (config.SWDEBUG):
        sys.stdout.write('Processing WeatherSense Lightning data'+'\n')
        sys.stdout.write('This is the raw data: ' + sLine + '\n')

    if (config.MQTT_Enable == True):
        mqtt_publish_single(sLine, "WSLightning")

    if (config.enable_MySQL_Logging == True):
        # open mysql database
        # write log
        # commit
        # close
        try:
            myTEST = ""
            myTESTDescription = ""

            con = mdb.connect(
                "localhost",
                "root",
                config.MySQL_Password,
                "WeatherSenseWireless"
            )

            cur = con.cursor()
            batteryPower =  float(state["batterycurrent"])* float(state["batteryvoltage"])/1000.0
            loadPower  =  float(state["loadcurrent"])* float(state["loadvoltage"])/1000.0
            solarPower =  float(state["solarpanelcurrent"])* float(state["solarpanelvoltage"])/1000.0
            batteryCharge = util.returnPercentLeftInBattery(state["batteryvoltage"], 4.2) 

            fields = "deviceid, protocolversion, softwareversion, weathersenseprotocol,irqsource, previousinterruptresult, lightninglastdistance, sparebyte, lightningcount, interruptcount,  batteryvoltage, batterycurrent, loadvoltage, loadcurrent, solarvoltage, solarcurrent, auxa, batterycharge, messageID, batterypower, loadpower, solarpower, test, testdescription"
            values = "%d, %d, %d, %d, %d, %d, %d, %d,%d, %d,%6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f,%6.2f,%6.2f,%d,%6.2f, %6.2f, %6.2f,\'%s\', \'%s\'" % (
            state["deviceid"], state["protocolversion"], state["softwareversion"], state["weathersenseprotocol"],
            state['irqsource'], state['previousinterruptresult'], state['lightninglastdistance'], state['sparebyte'],
            state['lightningcount'], state['interruptcount'],
            state["batteryvoltage"], state["batterycurrent"], state["loadvoltage"], state["loadcurrent"],
            state["solarpanelvoltage"], state["solarpanelcurrent"], state["auxa"], batteryCharge, state["messageid"],
            batteryPower, loadPower, solarPower, myTEST, myTESTDescription)
            query = "INSERT INTO TB433MHZ (%s) VALUES(%s )" % (fields, values)
            # print("query=", query)
            cur.execute(query)
            con.commit()
        except mdb.Error as e:
            traceback.print_exc()
            print("Error %d: %s" % (e.args[0], e.args[1]))
            con.rollback()
            # sys.exit(1)

        finally:
            cur.close()
            con.close()

            del cur
            del con

    return
예제 #2
0
def processINFOMessage(msg):

    myJSON = json.loads(msg.payload)

    if (config.enable_MySQL_Logging == True):
        # open mysql database
        # write log
        # commit
        # close
        try:
            myTEST = ""
            myTESTDescription = ""
            print("in INFO with SQL")

            con = mdb.connect("localhost", "root", config.MySQL_Password,
                              "WeatherSenseWireless")

            cur = con.cursor()
            batteryPower = float(myJSON["batterycurrent"]) * float(
                myJSON["batteryvoltage"])
            loadPower = float(myJSON["loadcurrent"]) * float(
                myJSON["loadvoltage"])
            solarPower = float(myJSON["solarpanelcurrent"]) * float(
                myJSON["solarpanelvoltage"])
            batteryCharge = util.returnPercentLeftInBattery(
                float(myJSON["batteryvoltage"]), 4.2)
            #print("batteryChange=", batteryCharge)
            fields = "cameraid, messageid, softwareversion, messagetype, rssi, internaltemperature, internalhumidity, batteryvoltage, batterycurrent, loadvoltage, loadcurrent, solarvoltage, solarcurrent,  batterypower, loadpower, solarpower, gndrreboots, batterycharge"
            values = "'%s', %s, %s, %s, %s, %s, %s,    %s, %s, %s, %s, %s, %s,  %s, %s, %s, %s, %d " % (
                myJSON["id"], myJSON["messageid"], myJSON["softwareversion"],
                myJSON["messagetype"], myJSON["currentrssi"],
                myJSON["internaltemperature"], myJSON["internalhumidity"],
                myJSON["batteryvoltage"], myJSON["batterycurrent"],
                myJSON["loadvoltage"], myJSON["loadcurrent"],
                myJSON["solarpanelvoltage"], myJSON["solarpanelcurrent"],
                batteryPower, loadPower, solarPower, myJSON["gndrreboots"],
                batteryCharge)

            query = "INSERT INTO SkyCamSensors (%s) VALUES(%s )" % (fields,
                                                                    values)
            #print(query)
            cur.execute(query)
            con.commit()
        except:
            traceback.print_exc()
            con.rollback()
            # sys.exit(1)

        finally:
            cur.close()
            con.close()

            del cur
            del con
예제 #3
0
def readWXLink(block1, block2, stringblock1, stringblock2, block1_orig,
               block2_orig):
    if (config.SWDEBUG):
        print("Starting readWXLink")
    # oldblock1 = block1
    # oldblock2 = block2
    try:
        if ((len(block1) > 0) and (len(block2) > 0)):
            # check crc for errors - don't update data if crc is bad
            if (config.SWDEBUG):
                print("block1 length=", len(block1))
                print("block2 length=", len(block2))
            #get crc from data
            receivedCRC = struct.unpack('H', str(block2[29:31]))[0]
            #swap bytes for receivedCRC
            receivedCRC = (((receivedCRC) >> 8) |
                           ((receivedCRC & 0xFF) << 8)) & 0xFFFF
            if (config.SWDEBUG):
                print("ReversedreceivedCRC= %x" % receivedCRC)
                print("length of stb1+sb2=", len(stringblock1 + stringblock2))
                print(''.join('{:02x}'.format(ord(x)) for x in stringblock1))
                print(''.join('{:02x}'.format(ord(x)) for x in stringblock2))
            calculatedCRC = crcCalc.calculate(block1 + block2[0:27])

            if (config.SWDEBUG):
                print("calculatedCRC = %x " % calculatedCRC)

                # check for start bytes, if not present, then invalidate CRC

            if (block1[0] != 0xAB) or (block1[1] != 0x66):
                calculatedCRC = receivedCRC + 1

            if (receivedCRC == calculatedCRC):
                if (config.SWDEBUG):
                    print("Good CRC Recived")

                # read protocol
                protocol_byte = block1[2]
                #protocol_byte = struct.unpack('B', str(block1[2:2]))[0]
                protocol_ID = protocol_byte / 10
                protocol_software_version = protocol_byte - protocol_ID * 10
                if (config.SWDEBUG):
                    print("protocol_ID = ", protocol_ID)
                    print("protocol_software_version = ",
                          protocol_software_version)

                # if protocol_ID == 3, then
                # use if:  SolarMAX_Present == False or Dual_MAX_WXLink == True
                if ((protocol_ID == WXLINKPROTOCOLID)
                        and ((config.SolarMAX_Present == False) or
                             (config.Dual_MAX_WXLink
                              == True))):  # 3 is the WXLink Protocol
                    print("protocol %d - WXLink received " % WXLINKPROTOCOLID)
                    currentWindSpeed = struct.unpack('f', str(block1[9:13]))[0]

                    currentWindGust = 0.0  # not implemented in Solar WXLink version

                    totalRain = struct.unpack('l', str(block1[17:21]))[0]

                    if (config.SWDEBUG):
                        print("Rain Total=\t%0.2f in") % (totalRain / 25.4)
                        print("Wind Speed=\t%0.2f MPH") % (currentWindSpeed /
                                                           1.6)

                    currentWindDirection = struct.unpack(
                        'H', str(block1[7:9]))[0]
                    if (config.SWDEBUG):
                        print("Wind Direction=\t\t\t %i Degrees" %
                              currentWindDirection)

                    # now do the AM2315 Temperature
                    temperature = struct.unpack('f', str(block1[25:29]))[0]
                    if (config.SWDEBUG):
                        print("OTFloat=%x%x%x%x" %
                              (block1[25], block1[26], block1[27], block1[28]))
                    elements = [block1[29], block1[30], block1[31], block2[0]]
                    outHByte = bytearray(elements)
                    humidity = struct.unpack('f', str(outHByte))[0]
                    if (config.SWDEBUG):
                        print("AM2315 from WXLink temperature: %0.1fC" %
                              temperature)
                        print("AM2315 from WXLink humidity: %0.1f%%" %
                              humidity)

                    # now read the SunAirPlus Data from WXLink

                    WXbatteryVoltage = struct.unpack('f', str(block2[1:5]))[0]
                    WXbatteryCurrent = -struct.unpack('f', str(block2[5:9]))[0]
                    WXloadCurrent = struct.unpack('f', str(block2[9:13]))[0]
                    WXsolarPanelVoltage = struct.unpack(
                        'f', str(block2[13:17]))[0]
                    WXsolarPanelCurrent = struct.unpack(
                        'f', str(block2[17:21]))[0]

                    WXbatteryPower = WXbatteryVoltage * (WXbatteryCurrent /
                                                         1000)

                    WXsolarPower = WXsolarPanelVoltage * (WXsolarPanelCurrent /
                                                          1000)

                    WXloadPower = 5.0 * (WXloadCurrent / 1000)

                    WXbatteryCharge = util.returnPercentLeftInBattery(
                        WXbatteryVoltage, 4.19)

                    state.WXbatteryVoltage = WXbatteryVoltage
                    state.WXbatteryCurrent = WXbatteryCurrent
                    state.WXloadCurrent = WXloadCurrent
                    state.WXsolarVoltage = WXsolarPanelVoltage
                    state.WXsolarCurrent = WXsolarPanelCurrent
                    state.WXbatteryPower = WXbatteryPower
                    state.WXsolarPower = WXsolarPower
                    state.WXloadPower = WXloadPower
                    state.WXbatteryCharge = WXbatteryCharge

                    auxA = struct.unpack('f', str(block2[21:25]))[0]
                    # now set state variables

                    if (config.SWDEBUG):
                        print("WXLink batteryVoltage = %6.2f" %
                              WXbatteryVoltage)
                        print("WXLink batteryCurrent = %6.2f" %
                              WXbatteryCurrent)
                        print("WXLink loadCurrent = %6.2f" % WXloadCurrent)
                        print("WXLink solarPanelVoltage = %6.2f" %
                              WXsolarPanelVoltage)
                        print("WXLink solarPanelCurrent = %6.2f" %
                              WXsolarPanelCurrent)
                        print("WXLink auxA = %6.2f" % auxA)

                    # message ID
                    MessageID = struct.unpack('l', str(block2[25:29]))[0]
                    print("WXLink Message ID %i" % MessageID)

                    if (config.WXLink_LastMessageID != MessageID):
                        config.WXLink_Data_Fresh = True
                        config.WXLink_LastMessageID = MessageID
                        if (config.SWDEBUG):
                            print("WXLink_Data_Fresh set to True")

                # use protocol 8 if SolarMAX_Present == True
                # if (((protocol_ID == 8) or (protocol_ID == 10))and (config.SolarMAX_Present)):
                if ((protocol_ID == SOLARMAXPROTOCOL) and
                    (config.SolarMAX_Present)):  # 3 is the WXLink Protocol
                    ############################
                    ############################
                    ############################
                    ############################
                    #print("protocol 8 or 9 - SolarMAX received")
                    print("protocol " + str(protocol_ID) +
                          " SolarMAX received")
                    #print("protocol "+str(SOLARMAXPROTOCOL)+ " SolarMAX received")
                    ############################
                    ############################
                    ############################
                    ############################

                    # now do the inside Temperature in the SolarMAX
                    SolarMaxInsideTemperature = struct.unpack(
                        'f', str(block1[25:29]))[0]
                    if (config.SWDEBUG):
                        print("SMOTFloat=%x%x%x%x" %
                              (block1[25], block1[26], block1[27], block1[28]))
                    elements = [block1[29], block1[30], block1[31], block2[0]]
                    outHByte = bytearray(elements)
                    SolarMaxInsideHumidity = struct.unpack('f',
                                                           str(outHByte))[0]
                    if (config.SWDEBUG):
                        print(
                            "ITemperature from SolarMAX temperature: %0.1fC" %
                            SolarMaxInsideTemperature)
                        print("IHumidity from SolarMAX humidity: %0.1f%%" %
                              SolarMaxInsideHumidity)

                    # now read the SolarMax Data from packet

                    SolarMaxloadVoltage = struct.unpack(
                        'f', str(block1[21:25]))[0]

                    SolarMaxbatteryVoltage = struct.unpack(
                        'f', str(block2[1:5]))[0]
                    SolarMaxbatteryCurrent = -struct.unpack(
                        'f', str(block2[5:9]))[0]
                    SolarMaxloadCurrent = struct.unpack(
                        'f', str(block2[9:13]))[0]
                    SolarMaxsolarPanelVoltage = struct.unpack(
                        'f', str(block2[13:17]))[0]
                    SolarMaxsolarPanelCurrent = -struct.unpack(
                        'f', str(block2[17:21]))[0]

                    SolarMaxbatteryPower = SolarMaxbatteryVoltage * (
                        SolarMaxbatteryCurrent / 1000)

                    SolarMaxsolarPower = SolarMaxsolarPanelVoltage * (
                        SolarMaxsolarPanelCurrent / 1000)

                    SolarMaxloadPower = SolarMaxloadVoltage * (
                        SolarMaxloadCurrent / 1000)

                    SolarMaxbatteryCharge = util.returnPercentLeftInBattery(
                        SolarMaxbatteryVoltage, 4.19)

                    state.batteryVoltage = SolarMaxbatteryVoltage
                    state.batteryCurrent = SolarMaxbatteryCurrent
                    state.loadCurrent = SolarMaxloadCurrent
                    state.loadVoltage = SolarMaxloadVoltage
                    state.solarVoltage = SolarMaxsolarPanelVoltage
                    state.solarCurrent = SolarMaxsolarPanelCurrent
                    state.batteryPower = SolarMaxbatteryPower
                    state.solarPower = SolarMaxsolarPower
                    state.loadPower = SolarMaxloadPower
                    state.batteryCharge = SolarMaxbatteryCharge
                    state.SolarMaxInsideTemperature = SolarMaxInsideTemperature
                    state.SolarMaxInsideHumidity = SolarMaxInsideHumidity

                    auxA = struct.unpack('f', str(block2[21:25]))[0]
                    # now set state variables

                    if (config.SWDEBUG):
                        print("SolarMax batteryVoltage = %6.2f" %
                              SolarMaxbatteryVoltage)
                        print("SolarMax batteryCurrent = %6.2f" %
                              SolarMaxbatteryCurrent)
                        print("SolarMax loadVoltage = %6.2f" %
                              SolarMaxloadVoltage)
                        print("SolarMax loadCurrent = %6.2f" %
                              SolarMaxloadCurrent)
                        print("SolarMax solarPanelVoltage = %6.2f" %
                              SolarMaxsolarPanelVoltage)
                        print("SolarMax solarPanelCurrent = %6.2f" %
                              SolarMaxsolarPanelCurrent)
                        print("SolarMax auxA = %6.2f" % auxA)

                    # message ID
                    MessageID = struct.unpack('l', str(block2[25:29]))[0]
                    print("SolarMax Message ID %i" % MessageID)
                    if (config.SolarMAX_Present == True):
                        if (config.USEBLYNK):
                            if (config.WXLink_Data_Fresh == True):
                                if (config.SWDEBUG):
                                    if (state.InternetIsUp):
                                        updateBlynk.blynkStatusTerminalUpdate(
                                            "SolarMAX ID# %d received" %
                                            config.WXLink_LastMessageID)
                            entry = time.strftime(
                                "%Y-%m-%d %H:%M:%S") + ": %i \n" % (MessageID)
                            state.SolarMAXLastReceived = entry
                            if (state.InternetIsUp):
                                updateBlynk.blynkSolarMAXLine(
                                    entry, protocol_ID)

                if ((protocol_ID == WXLINKPROTOCOLID) or (protocol_ID == 8)
                        or (protocol_ID == 10)):
                    # if ((protocol_ID == WXLINKPROTOCOLID) or (protocol_ID == SOLARMAXPROTOCOL) ):
                    pass
                else:
                    if (config.SWDEBUG):
                        print(
                            "unknown or non-configured protocol received.  Protocol = ",
                            protocol_ID)
                    return []
            else:
                print("Bad CRC Received")
                return []
        else:
            return []

        # return list
        if ((protocol_ID == WXLINKPROTOCOLID) and
            ((config.SolarMAX_Present == False) or
             (config.Dual_MAX_WXLink == True))):  # 3 is the WXLink Protocol
            returnList = []
            returnList.append(protocol_ID)
            returnList.append(block1_orig)
            returnList.append(block2_orig)
            returnList.append(currentWindSpeed)
            returnList.append(currentWindGust)
            returnList.append(totalRain)
            returnList.append(currentWindDirection)
            returnList.append(temperature)
            returnList.append(humidity)
            returnList.append(WXbatteryVoltage)
            returnList.append(WXbatteryCurrent)
            returnList.append(WXloadCurrent)
            returnList.append(WXsolarPanelVoltage)
            returnList.append(WXsolarPanelCurrent)
            returnList.append(auxA)
            returnList.append(MessageID)
        else:
            returnList = []  # protocol 8 - SolarMAX
            returnList.append(protocol_ID)

        return returnList
    except Exception as e:
        if (config.SWDEBUG):
            print(traceback.format_exc())
        print("LoRa Packet Decode Failure - probably short block receive")
        print("e=", e)
        return []
예제 #4
0
def processWeatherSenseAfterShock(sLine):

    # weathersense protocol 18
    state = json.loads(sLine)
    myProtocol = state['weathersenseprotocol']
    if (config.SWDEBUG):
        sys.stdout.write("processing AfterShock Data\n")
        sys.stdout.write('This is the raw data: ' + sLine + '\n')

    if (config.MQTT_Enable == True):
        mqtt_publish_single(sLine, "WSAfterShock")


    if (config.enable_MySQL_Logging == True):
        # open mysql database
        # write log
        # commit
        # close
        try:
            myTEST = ""
            myTESTDescription = ""

            con = mdb.connect(
                    "localhost",
                    "root",
                    config.MySQL_Password,
                    "WeatherSenseWireless"
            )

            cur = con.cursor()
            batteryPower =  float(state["batterycurrent"])* float(state["batteryvoltage"])
            loadPower  =  float(state["loadcurrent"])* float(state["loadvoltage"])
            solarPower =  float(state["solarpanelcurrent"])* float(state["solarpanelvoltage"])
            batteryCharge = util.returnPercentLeftInBattery(state["batteryvoltage"], 4.2)

            fields = "deviceid, protocolversion, softwareversion, weathersenseprotocol, eqcount, finaleq_si, finaleq_pga, instanteq_si, instanteq_pga, batteryvoltage, batterycurrent, loadvoltage, loadcurrent, solarvoltage, solarcurrent, auxa, solarpresent, aftershockpresent, keepalivemessage, lowbattery, batterycharge, messageID, batterypower, loadpower, solarpower, test, testdescription"
            values = "%d, %d, %d, %d, %d,%6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f,%6.2f,%6.2f, %d, %d, %d, %d,%d,%6.2f, %6.2f, %6.2f,\'%s\', \'%s\'" % (
            state["deviceid"], state["protocolversion"], state["softwareversion"], state["weathersenseprotocol"],
            state['eqcount'], state['finaleq_si'], state['finaleq_pga'], state['instanteq_si'],
            state['instanteq_pga'], 
            state["batteryvoltage"], state["batterycurrent"], state["loadvoltage"], state["loadcurrent"],
            state["solarpanelvoltage"], state["solarpanelcurrent"], state["auxa"],state["solarpresent"],state["aftershockpresent"],state["keepalivemessage"],state["lowbattery"],     batteryCharge, state["messageid"],
            batteryPower, loadPower, solarPower, myTEST, myTESTDescription)
            query = "INSERT INTO AS433MHZ (%s) VALUES(%s )" % (fields, values)
            # print("query=", query)
            cur.execute(query)
            con.commit()
        except mdb.Error as e:
            traceback.print_exc()
            print("Error %d: %s" % (e.args[0], e.args[1]))
            con.rollback()
            # sys.exit(1)

        finally:
            cur.close()
            con.close()

            del cur
            del con

    return
예제 #5
0
def processWeatherSenseRadiation(sLine):
    # WeatherSense Protocol 19
    state = json.loads(sLine)
    myProtocol = state['weathersenseprotocol']
    if (config.SWDEBUG):
        sys.stdout.write("processing Radiation Data\n")
        sys.stdout.write('This is the raw data: ' + sLine + '\n')

    if (config.MQTT_Enable == True):
        mqtt_publish_single(sLine, "WSRadiation")


    if (config.enable_MySQL_Logging == True):
        # open mysql database
        # write log
        # commit
        # close
        try:

            con = mdb.connect(
                    "localhost",
                    "root",
                    config.MySQL_Password,
                    "WeatherSenseWireless"
            )
            
            # calculate Radiation 24 Hour
            timeDelta = datetime.timedelta(days=1)
            now = datetime.datetime.now()
            before = now - timeDelta
            before = before.strftime('%Y-%m-%d %H:%M:%S')
            query = "SELECT uSVh, TimeStamp FROM RAD433MHZ WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % (before)

            cur = con.cursor()
            cur.execute(query)
            myRADRecords = cur.fetchall()
            myRADTotal = 0.0
            if (len(myRADRecords) > 0):
                for i in range(0, len(myRADRecords)):
                    myRADTotal = myRADTotal + myRADRecords[i][0]

                RAD24Hour = (myRADTotal + float(state['uSVh'])) / (len(myRADRecords) + 1)
            else:
                RAD24Hour = 0.0

            batteryPower =  float(state["batterycurrent"])* float(state["batteryvoltage"])
            loadPower  =  float(state["loadcurrent"])* float(state["loadvoltage"])
            solarPower =  float(state["solarpanelcurrent"])* float(state["solarpanelvoltage"])
            batteryCharge = util.returnPercentLeftInBattery(state["batteryvoltage"], 4.2)

            fields = "uSVh24Hour, deviceid, protocolversion, softwareversion, weathersenseprotocol, CPM, nSVh, uSVh, batteryvoltage, batterycurrent, loadvoltage, loadcurrent, solarvoltage, solarcurrent, auxa, solarpresent, radiationpresent, keepalivemessage, lowbattery, batterycharge, messageID, batterypower, loadpower, solarpower "
            values = "%6.2f, %d, %d, %d, %d, %d,%d,  %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %d, %d, %d,%d,%d,%6.2f, %d,%6.2f, %6.2f, %6.3f" % ( RAD24Hour, state["deviceid"], state["protocolversion"], state["softwareversion"], state["weathersenseprotocol"],
            state['CPM'], state['nSVh'], state['uSVh'], 
            state["batteryvoltage"], state["batterycurrent"], state["loadvoltage"], state["loadcurrent"],
            state["solarpanelvoltage"], state["solarpanelcurrent"], state["auxa"],state["solarpresent"],state["radBoardPresent"],state["keepalivemessage"],state["lowbattery"],     batteryCharge, state["messageid"],
            batteryPower, loadPower, solarPower )
            query = "INSERT INTO RAD433MHZ (%s) VALUES(%s )" % (fields, values)
            # print("query=", query)
            cur.execute(query)
            con.commit()
        except mdb.Error as e:
            traceback.print_exc()
            print("Error %d: %s" % (e.args[0], e.args[1]))
            con.rollback()
            # sys.exit(1)

        finally:
            cur.close()
            con.close()

            del cur
            del con
            
            CPM = state['CPM']
            uSVh = state['uSVh']
            # update web maps
            updateWeb.update_SafeCast(CPM, uSVh)
            updateWeb.update_RadMon(CPM)
            updateWeb.update_GMCMap(CPM, uSVh)

            



    return
예제 #6
0
def processSolarMAX(sLine):
    myState = json.loads(sLine)

    if (config.SWDEBUG):
        sys.stdout.write('Processing SolarMAX2 data'+'\n')
        sys.stdout.write('This is the raw data: ' + sLine + '\n')

    # only accept SolarMAX2 Protocols (8,10,11)
    myProtocol = myState['weathersenseprotocol']
    if ((myProtocol == 8) or (myProtocol == 10) or (myProtocol == 11)):

        if (config.MQTT_Enable == True):
            mqtt_publish_single(sLine, "WSSolarMAX")

        if (config.enable_MySQL_Logging == True):
            # open mysql database
            # write log
            # commit
            # close
            try:
                myTEST = ""
                myTESTDescription = ""

                con = mdb.connect(
                    "localhost",
                    "root",
                    config.MySQL_Password,
                    "WeatherSenseWireless"
                )

                cur = con.cursor()
                batteryPower =  float(myState["batterycurrent"])* float(myState["batteryvoltage"])/1000.0
                loadPower  =  float(myState["loadcurrent"])* float(myState["loadvoltage"])/1000.0
                solarPower =  float(myState["solarpanelcurrent"])* float(myState["solarpanelvoltage"])/1000.0
                batteryCharge = util.returnPercentLeftInBattery(myState["batteryvoltage"], 4.2)

                fields = "deviceid, protocolversion, softwareversion, weathersenseprotocol, batteryvoltage, batterycurrent, loadvoltage, loadcurrent, solarvoltage, solarcurrent, auxa, internaltemperature,internalhumidity, batterycharge, messageID, batterypower, loadpower, solarpower, test, testdescription"
                values = "%d, %d, %d, %d, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f,%6.2f,%6.2f,%d,%6.2f, %6.2f, %6.2f,\'%s\', \'%s\'" % (
                myState["deviceid"], myState["protocolversion"], myState["softwareversion"], myState["weathersenseprotocol"],
                myState["batteryvoltage"], myState["batterycurrent"], myState["loadvoltage"], myState["loadcurrent"],
                myState["solarpanelvoltage"], myState["solarpanelcurrent"], myState["auxa"], myState["internaltemperature"],
                myState["internalhumidity"], batteryCharge, myState["messageid"], batteryPower, loadPower, solarPower,
                myTEST, myTESTDescription)
                query = "INSERT INTO SolarMax433MHZ (%s) VALUES(%s )" % (fields, values)
                cur.execute(query)
                con.commit()
                
                # update state values 
                state.batteryVoltage = float(myState["batteryvoltage"])
                state.batteryCurrent = float(myState["batterycurrent"])
                state.solarVoltage = float(myState["solarpanelvoltage"])
                state.solarCurrent = float(myState["solarpanelcurrent"])
                state.loadVoltage = float(myState["loadvoltage"])
                state.loadCurrent = float(myState["loadcurrent"])
                state.batteryPower = batteryPower 
                state.solarPower = solarPower
                state.loadPower = loadPower
                state.batteryCharge = batteryCharge
                state.SolarMaxInsideTemperature = float(myState["internaltemperature"])
                state.SolarMaxInsideHumidity = float(myState["internalhumidity"]) 
                state.SolarMAXLastReceived = myState["time"] 



            except mdb.Error as e:
                traceback.print_exc()
                print("Error %d: %s" % (e.args[0], e.args[1]))
                con.rollback()
                # sys.exit(1)

            finally:
                cur.close()
                con.close()

                del cur
                del con

    return
예제 #7
0
def processWeatherSenseAQI(sLine):
    # weathersense protocol 15
    state = json.loads(sLine)
    myProtocol = state['weathersenseprotocol']

    if (config.SWDEBUG):
        sys.stdout.write('Processing WeatherSense Air Quality data'+'\n')
        sys.stdout.write('This is the raw data: ' + sLine + '\n')

    if (config.MQTT_Enable == True):
        mqtt_publish_single(sLine, "WSAQI")

    if (config.enable_MySQL_Logging == True):
        # open mysql database
        # write log
        # commit
        # close
        try:
            myTEST = ""
            myTESTDescription = ""

            con = mdb.connect(
                "localhost",
                "root",
                config.MySQL_Password,
                "WeatherSenseWireless"
            )

            cur = con.cursor()
            batteryPower =  float(state["batterycurrent"])* float(state["batteryvoltage"])/1000.0
            loadPower  =  float(state["loadcurrent"])* float(state["loadvoltage"])/1000.0
            solarPower =  float(state["solarpanelcurrent"])* float(state["solarpanelvoltage"])/1000.0
            batteryCharge = util.returnPercentLeftInBattery(state["batteryvoltage"], 4.2)
 
            # calculate AQI 24 Hour
            timeDelta = datetime.timedelta(days=1)
            now = datetime.datetime.now()
            before = now - timeDelta
            before = before.strftime('%Y-%m-%d %H:%M:%S')
            query = "SELECT AQI, TimeStamp FROM AQI433MHZ WHERE (TimeStamp > '%s') ORDER BY TimeStamp " % (before)

            cur.execute(query)
            myAQIRecords = cur.fetchall()
            myAQITotal = 0.0
            if (len(myAQIRecords) > 0):
                for i in range(0, len(myAQIRecords)):
                    myAQITotal = myAQITotal + myAQIRecords[i][0]

                AQI24Hour = (myAQITotal + float(state['AQI'])) / (len(myAQIRecords) + 1)
            else:
                AQI24Hour = 0.0


            # HOTFIX for AQI problem from the wireless AQI sensor
            # recalculate AQI from RAW values and write in database

            myaqi = aqi.to_aqi([
                (aqi.POLLUTANT_PM25, state['PM2.5A']),
                (aqi.POLLUTANT_PM10, state['PM10A'])
                ])
            if (myaqi > 500):
                myaqi = 500
            print("myaqi=", myaqi)
            state['AQI'] = myaqi

            fields = "deviceid, protocolversion, softwareversion, weathersenseprotocol, PM1_0S, PM2_5S, PM10S, PM1_0A, PM2_5A, PM10A, AQI, AQI24Hour, batteryvoltage, batterycurrent, loadvoltage, loadcurrent, solarvoltage, solarcurrent, auxa, batterycharge, messageID, batterypower, loadpower, solarpower, test, testdescription"
            values = "%d, %d, %d, %d, %d, %d, %d, %d, %d,%d, %d, %6.2f,%6.2f, %6.2f, %6.2f, %6.2f, %6.2f, %6.2f,%6.2f,%6.2f,%d,%6.2f, %6.2f, %6.2f,\'%s\', \'%s\'" % (
            state["deviceid"], state["protocolversion"], state["softwareversion"], state["weathersenseprotocol"],
            state['PM1.0S'], state['PM2.5S'], state['PM10S'], state['PM1.0A'], state['PM2.5A'], state['PM10S'],
            state['AQI'], AQI24Hour,
            state["batteryvoltage"], state["batterycurrent"], state["loadvoltage"], state["loadcurrent"],
            state["solarpanelvoltage"], state["solarpanelcurrent"], state["auxa"], batteryCharge, state["messageid"],
            batteryPower, loadPower, solarPower, myTEST, myTESTDescription)
            query = "INSERT INTO AQI433MHZ (%s) VALUES(%s )" % (fields, values)
            cur.execute(query)
            con.commit()
        except mdb.Error as e:
            traceback.print_exc()
            print("Error %d: %s" % (e.args[0], e.args[1]))
            con.rollback()
            # sys.exit(1)

        finally:
            cur.close()
            con.close()

            del cur
            del con

    return