Ejemplo n.º 1
0
def sensors():
    final_ret = dict()
    ###########DHT-11#############################DATA-PIN = 20
    humidity, temperature = Adafruit_DHT.read_retry(11,20)
    print("DHT done")
    #print("H = "+str(humidity)+" T = "+str(temperature))
    ##############################################
    ##############DS18b20##########################DATA-PIN = 04
    body_temperature = probetemp.read_temp()
    print("DS18B20 done")
    ##########################################
    #############MQ-135##########################DATA-PIN = 1(analog)
    mq = MQ()
    perc = mq.MQPercentage()
    print("MQ135 done")
    '''sys.stdout.write("\r")
    sys.stdout.write("\033[K")
    sys.stdout.write("LPG: %g ppm, CO: %g ppm, Smoke: %g ppm" % (perc["GAS_LPG"], perc["CO"], perc["SMOKE"]))
    sys.stdout.write("\n")
    sys.stdout.flush()'''
    ####################################################
    ##############Pulse Sensor#######################DATA-PIN = 0(analog)
    p = Pulsesensor()
    p.startAsyncBPM()
    while True:
        #bpm = p.BPM
        bpm = random.randint(50,70)
        if bpm > 0:
            #print("BPM: %d" % bpm)
            p.stopAsyncBPM()
            break
        else:
            #print("No Heartbeat found")
            time.sleep(1)
    print("Pulse done")    
    ######################################
    ###################GPS####################
    gps = GPSget()
    #########################################
    final_ret["ambient_temp"] = temperature
    final_ret["humidity"] = humidity
    final_ret["body_temp"] = body_temperature
    final_ret["LPG"] = perc["GAS_LPG"]
    final_ret["CO"] = perc["CO"]
    final_ret["Smoke"] = perc["SMOKE"]
    final_ret["Pulse"] = int(bpm)
    final_ret["loc_lat"] = gps[0]
    final_ret["loc_lng"] = gps[1]

    return final_ret
def menu():
    global direction
    global submenu
    global main_menu
    global DAC0_status

    if direction == "up":
        submenu = submenu - 1
    elif direction == 'down':
        submenu = submenu + 1
    elif direction == "right":
        main_menu = main_menu + 1
        submenu = 1
    elif direction == "left":
        main_menu = main_menu - 1
        submenu = 1

    if main_menu == 12:
        main_menu = 1
    if main_menu == 0:
        main_menu = 11

    temp, pressure = bmp.get_temperature_and_pressure()  #BMP280 code line

    #Information
    if main_menu == 1:
        Temp_C, Temp_F = RTC.getTemp()  #ds3231 code line

        if submenu == 4:
            submenu = 1
        if submenu == 0:
            submenu = 3

        if submenu == 1:
            oled("<  1.Time   >", time.strftime('%X'))
        if submenu == 2:
            oled("<  1.Date   >", time.strftime('%x'))
        elif submenu == 3:
            oled("<  1.RTC Temp >", (str(round(Temp_C, 2)) + " C"),
                 (str(round(Temp_F, 2)) + " F"))

    # Sensor data
    elif main_menu == 2:

        if submenu == 3:
            submenu = 1
        if submenu == 0:
            submenu = 2

        if submenu == 1:
            oled("< 2. BMP280 >", "Temperature", (str(round(temp, 2)) + " C"))
        elif submenu == 2:
            oled("< 2. BMP280 >", "Pressure", round(pressure, 2))

    # Device info
    elif main_menu == 3:

        if submenu == 5:
            submenu = 1
        if submenu == 0:
            submenu = 4

        if submenu == 1:
            oled("< 3.Rpi Info >", "CPU Temperature=",
                 (add_module.getCPUtemperature() + " C"))
        elif submenu == 2:
            oled("< 3.Rpi Info >", "Free RAM",
                 (str(int(add_module.getRAMinfo()[2]) / 1024) + " MB"))
        elif submenu == 3:
            oled("< 3.Rpi Info >", "CPU Usage",
                 (str(add_module.getCPUuse()) + " %"))
        elif submenu == 4:
            oled("< 3.Rpi Info >", "Disk Usage", add_module.getDiskSpace()[3])
    # IP Address
    elif main_menu == 4:

        if submenu == 3:
            submenu = 1
        if submenu == 0:
            submenu = 2

        if submenu == 1:
            oled("< 4. Rpi IP's >", "WLAN0",
                 add_module.get_ip_address('wlan0'))
        elif submenu == 2:
            oled("< 4. Rpi IP's >", "ETH0", add_module.get_ip_address('eth0'))

    #Finance
    elif main_menu == 5:

        if submenu == 3:
            submenu = 1
        if submenu == 0:
            submenu = 2

        if submenu == 1:
            oled("< 5. Exch Rate >", "Dolar / TL",
                 DovizKurlari().DegerSor("USD", 4))
        elif submenu == 2:
            oled("< 5. Exch Rate >", "Euro / TL",
                 DovizKurlari().DegerSor("EUR", 4))

    #DAC0, LED1, and ADC0 through ADC3
    elif main_menu == 6:

        if submenu == 6:
            submenu = 1
        if submenu == 0:
            submenu = 5

        if submenu == 1:
            oled("< 6. DAC0/LED1 >", "Turn On/OFF", "Press Button")
            if GPIO.input(KEY) == 0:
                if DAC0_status == 0:
                    GPIO.output(
                        LED1, GPIO.HIGH)  #Turns on LED1 to indicate DAC0 is on
                    ADC.write(255)  #Turns on DAC0
                    DAC0_status = 1
                    time.sleep(.25)
                else:
                    GPIO.output(
                        LED1,
                        GPIO.LOW)  #Turns off LED1 to indicate DAC0 is off
                    ADC.write(0)  #Turns off DAC0
                    DAC0_status = 0
                    time.sleep(.25)

        elif submenu == 2:
            oled("< 6. DAC0/LED1 >", "Ain0",
                 (str(round(ADC.read(0), 2)) + " Volts"))  #PCF8591 code line

        elif submenu == 3:
            oled("< 6. DAC0/LED1 >", "Ain1",
                 (str(round(ADC.read(1), 2)) + " Volts"))  #PCF8591 code line

        elif submenu == 4:
            oled("< 6. DAC0/LED1 >", "Ain2",
                 (str(round(ADC.read(2), 2)) + " Volts"))  #PCF8591 code line

        elif submenu == 5:
            oled("< 6. DAC0/LED1 >", "Ain3",
                 (str(round(ADC.read(3), 2)) + " Volts"))  #PCF8591 code line

    #System
    elif main_menu == 7:

        if submenu == 5:
            submenu = 1
        if submenu == 0:
            submenu = 4

        elif submenu == 1:
            oled("< 7. System >", "Close App", "Press Button")
            if GPIO.input(KEY) == 0:
                sys.exit()
        elif submenu == 2:
            oled("< 7. System >", "Restart", "Press Button")
            if GPIO.input(KEY) == 0:
                os.popen('sudo reboot')
        elif submenu == 3:
            oled("< 7. System >", "Halt System", "Press Button")
            if GPIO.input(KEY) == 0:
                os.popen('sudo halt')
        elif submenu == 4:
            oled("< 7. System >", "App Update", "Press Button")
            if GPIO.input(KEY) == 0:
                oled("< 7. System >", "Update ...")
                os.popen('sudo apt-get update')
                oled("< 7. System >", "Upgrade ...")
                os.popen('sudo apt-get upgrade -y')
                oled("< 7. System >", "Completed")

    #Additional sensors
    elif main_menu == 8:
        temp_c, temp_f = OneWire.read_temp()  #ds18b20 code line
        f = OneWire.read_rom()  #ds18b20 code line

        if submenu == 3:
            submenu = 1
        if submenu == 0:
            submenu = 2

        if submenu == 1:
            oled("< 8. Sensors >", f, (str(round(temp_c, 2)) + " C"))
        elif submenu == 2:
            oled("< 8. Sensors >", f, (str(round(temp_f, 2)) + " F"))

    # IRM readings
    elif main_menu == 9:

        if submenu == 2:
            submenu = 1
        if submenu == 0:
            submenu = 1

        if submenu == 1:
            IRM_key = IRM.irm_key()
            oled("< 9. IRM >", "Readings",
                 IRM_key)  #This is not catching all the button presses.
            #The issue is the structure of this program would need to change to handle the timing.
            #Running a thread does not improve program response to sensor input. To improve the
            #response to the sensor input the program needs to be restructured/shortened.

    #USB2UART TX Test
    elif main_menu == 10:
        oled("< 10. USB2UART >", "Run TX test", "Press Button"
             )  #This is to test the transmission from the Pi to a PC.
        if GPIO.input(KEY) == 0:
            ser.write("Test line\r\n".encode())
            oled("< 10. USB2UART >", "Test line sent", "View results")
            time.sleep(2)

    #USB2UART RX Test
    elif main_menu == 11:
        oled("< 11. USB2UART >", "Run RX test",
             "Press Button")  #This is to test the
        #transmission from the PC to a Pi. No more than a small word, due to the OLED size.
        if GPIO.input(KEY) == 0:
            flush_input()  #Calls the function to clear the
            #terminal keyboard buffer before the desired input is collected.
            oled("< 11. USB2UART >", "Button Pressed", "Starting test")
            ser.write("Type something\r\n".encode())
            out = USB2UART.readData()
            oled("< 11. USB2UART >", "You wrote:", str(out))
            ser.write("You wrote: ".encode() + str(out).encode() +
                      "\r\n".encode())
            time.sleep(2)

    else:
        print("something went wrong")

    return (submenu)
Ejemplo n.º 3
0
def get_data():
    temp = read_temp()
    return jsonify({"value": temp, "name": 'ходц╕й'})
Ejemplo n.º 4
0
with open("weather.csv", "a") as csv:
  temp_sensors = ds18b20.get_devices()

  header = '# time, co2, humidity, int_temp'

  sensor_ids = []
  for sensor_id, sensor_name in temp_sensors.iteritems():
    header += ', %s' % sensor_name
    sensor_ids.append(sensor_id)

  print header
  csv.write(header + "\n")
  sht = sht31.SHT31()
  co2_sensor = k30.K30()

  while True:
    current_time = datetime.datetime.now()
    (int_temp, humidity) = sht.get_temp_and_humidity()

    co2 = co2_sensor.get_ppm()
    data_line = "%s, %d, %f, %f" % (current_time, co2, humidity, int_temp)

    for sensor_id in sensor_ids:
      data_line += ", " + ds18b20.read_temp(sensor_id)
      time.sleep(.1)

    print data_line
    csv.write(data_line+"\n")
    time.sleep(4)
Ejemplo n.º 5
0
from decouple import config  #for reading environment variables

deviceFile1, deviceFile2 = OneW_init()
interval = 10

sid = config('TWILIO_ACCOUNT_SID')
token = config('TWILIO_AUTH_TOKEN')

Freezer_1 = TempEvent(30, 'upper', 'Freezer 1')
Freezer_2 = TempEvent(30, 'upper', 'Freezer 2')

while True:
    try:
        t = datetime.datetime.now()

        tCel_1 = read_temp(deviceFile1)
        #       print(str(tCel_1))
        tCel_2 = read_temp(deviceFile2)
        #       print(str(tCel_2))

        #if (Freezer_1.EvalTemperature( read_temp(deviceFile1), t) ):
        if (Freezer_1.EvalTemperature(tCel_1, t)):
            Freezer_1.Announce(t, sid, token)

        if (Freezer_2.EvalTemperature(tCel_2, t)):
            Freezer_2.Announce(t, sid, token)

        #time.sleep(300)
        for i in range(
                1,
                interval):  #prevent system hang by waiting range(30) seconds
Ejemplo n.º 6
0
#! /usr/bin/env python

import transmit_msg
import ds18b20
from pprint import pprint

messages = ds18b20.read_temp()
pprint(messages)
if len(messages) > 0:
    res = transmit_msg.send(messages)
    print("message sent to mongo" + str(res))
Ejemplo n.º 7
0
        with open(db_file, 'w') as f:
            f.write(json.dumps(db, indent=4))


# set wait times
loop_pause = 5
record_pause = 30
write_pause = record_pause
counter = 1
timing = {
    'loop_start': time.time(),
    'record_start': time.time(),
    'write_start': time.time()
}
# Clear the temperature buffer
curr_temp = temp.read_temp()
GPIO.setmode(output_type)
GPIO.setup(output_chan, GPIO.OUT)

while True:
    time.sleep(loop_pause)
    db = read_db()
    if db['running'] == 1:

        print('Checking temperature...')
        curr_temp = temp.read_temp()

        lower = curr_temp < db['set_point'] - db['set_range']
        exceed = curr_temp > db['set_point'] + db['set_range']
        if lower:
            GPIO.output(output_chan, 1)
Ejemplo n.º 8
0
    def apploop(self):
        while True:
            #defs_common.logtoconsole("app loop")

            ##########################################################################################
            # read ds18b20 temperature sensor
            #
            # we support multiple probes, so work from the probe dictionary and get data
            # for each
            ##########################################################################################
            # read data from the temperature probes
            if (int(round(time.time() * 1000)) -
                    self.AppPrefs.ds18b20_SamplingTimeSeed
                ) > self.AppPrefs.ds18b20_SamplingInterval:
                for p in self.AppPrefs.tempProbeDict:
                    try:
                        timestamp = datetime.now()
                        dstempC = float(
                            ds18b20.read_temp(
                                self.AppPrefs.tempProbeDict[p].probeid, "C"))
                        dstempF = defs_common.convertCtoF(float(dstempC))
                        dstempF = float(dstempF)
                        tempData = str(dstempC) + "," + str(dstempF)

                        if str(self.AppPrefs.temperaturescale) == str(
                                defs_common.SCALE_F):
                            broadcasttemp = str("%.1f" % dstempF)
                        else:
                            broadcasttemp = str("%.1f" % dstempC)

                        #self.tempProbeDict[p].lastLogTime = self.ds18b20_LastLogTimeDict


# json_body = [
# {
# "measurement": "probevalues",
# "tags": {
# "appuid": self.AppPrefs.appuid,
# "probeid": "ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid
# },
# "time": datetime.utcnow(),
# "fields": {
# "value": float(dstempC),
# }
# }
# ]

                        if (int(round(time.time() * 1000)) -
                                int(self.AppPrefs.tempProbeDict[p].lastLogTime)
                            ) > self.AppPrefs.ds18b20_LogInterval:
                            # log and broadcast temperature value
                            defs_common.logprobedata(
                                "ds18b20_" +
                                self.AppPrefs.tempProbeDict[p].probeid + "_",
                                tempData)
                            defs_common.logtoconsole(
                                "***Logged*** [ds18b20_" +
                                self.AppPrefs.tempProbeDict[p].probeid + "] " +
                                self.AppPrefs.tempProbeDict[p].name +
                                str(" = {:.1f}".format(dstempC)) + " C | " +
                                str("{:.1f}".format(dstempF)) + " F",
                                fg="CYAN",
                                style="BRIGHT")
                            self.logger.info(
                                str("***Logged*** [ds18b20_" +
                                    self.AppPrefs.tempProbeDict[p].probeid +
                                    "] " +
                                    self.AppPrefs.tempProbeDict[p].name +
                                    str(" = {:.1f}".format(dstempC)) +
                                    " C | " + str("{:.1f}".format(dstempF))) +
                                " F")
                            # log to InfluxDB
                            # self.WriteDataInfluxDB(json_body)
                            self.WriteProbeDataInfluxDB(
                                "ds18b20_" +
                                self.AppPrefs.tempProbeDict[p].probeid,
                                dstempC)
                            #self.broadcastProbeStatus("ds18b20", "ds18b20_" + self.AppPrefs.tempProbeDict[p].probeid, str(broadcasttemp), self.AppPrefs.tempProbeDict[p].name)

                            #self.ds18b20_LastLogTimeDict = int(round(time.time()*1000))
                            self.AppPrefs.tempProbeDict[p].lastLogTime = int(
                                round(time.time() * 1000))

                            #self.AppPrefs.tempProbeDict[p].lastTemperature = dstempC
                            self.AppPrefs.tempProbeDict[
                                p].lastTemperature = broadcasttemp
                        else:
                            self.logger.info(
                                str("[ds18b20_" +
                                    self.AppPrefs.tempProbeDict[p].probeid +
                                    "] " +
                                    self.AppPrefs.tempProbeDict[p].name +
                                    str(" = {:.1f}".format(dstempC)) +
                                    " C | " + str("{:.1f}".format(dstempF))) +
                                " F")

                            # broadcast temperature value
                            # self.MQTTclient.publish("reefberrypi/demo",str(dstempC))
                            self.broadcastProbeStatus(
                                "ds18b20", "ds18b20_" +
                                str(self.AppPrefs.tempProbeDict[p].probeid),
                                str(broadcasttemp),
                                self.AppPrefs.tempProbeDict[p].name)
                            self.AppPrefs.tempProbeDict[
                                p].lastTemperature = broadcasttemp
                    except Exception as e:
                        defs_common.logtoconsole(
                            str("<<<Error>>> Can not read ds18b20_" +
                                self.AppPrefs.tempProbeDict[p].probeid +
                                " temperature data!"),
                            fg="WHITE",
                            bg="RED",
                            style="BRIGHT")
                        self.logger.error(
                            "<<<Error>>> Can not read ds18b20_" +
                            self.AppPrefs.tempProbeDict[p].probeid +
                            " temperature data!")
                        self.logger.error(e)
                # record the new sampling time
                self.AppPrefs.ds18b20_SamplingTimeSeed = int(
                    round(time.time() * 1000))  # convert time to milliseconds

            ################################################################################################################
            # read dht11 temperature and humidity sensor
            #
            # these sensors are slow to refresh and should not be read more
            # than once every second or two (ie: dht_SamplingInterval = 3000ms or 5000ms for 3s or 5s) would be safe
            ################################################################################################################
            if self.AppPrefs.DHT_Sensor.get("enabled") == "True":
                if (int(round(time.time() * 1000)) -
                        self.AppPrefs.DHT_Sensor.get("dht11_samplingtimeseed")
                    ) > int(
                        self.AppPrefs.DHT_Sensor.get(
                            "dht11_samplinginterval")):
                    # let's read the dht11 temp and humidity data
                    result = self.dht_sensor.read()
                    if result.is_valid():
                        temp_c = result.temperature
                        temp_f = defs_common.convertCtoF(float(temp_c))
                        temp_f = float(temp_f)
                        hum = result.humidity
                        timestamp = datetime.now()

                        if str(self.AppPrefs.temperaturescale) == str(
                                defs_common.SCALE_F):
                            broadcasttemp = str("%.1f" % temp_f)
                        else:
                            broadcasttemp = str("%.1f" % temp_c)

                        if (int(round(time.time() * 1000)) - self.AppPrefs.
                                DHT_Sensor.get("dht11_lastlogtime")) > int(
                                    self.AppPrefs.DHT_Sensor.get(
                                        "dht11_loginterval")):
                            tempData = str(
                                "{:.1f}".format(temp_c)) + "," + str(temp_f)

                            # log and broadcast temperature value
                            defs_common.logprobedata("dht_t_", tempData)
                            defs_common.logtoconsole(
                                "***Logged*** [dht_t] " +
                                self.AppPrefs.DHT_Sensor.get(
                                    "temperature_name") +
                                " = %.1f C" % temp_c + " | %.1f F" % temp_f,
                                fg="CYAN",
                                style="BRIGHT")
                            self.logger.info(
                                str("***Logged*** [dht_t] " +
                                    self.AppPrefs.DHT_Sensor.get(
                                        "temperature_name") +
                                    " = %.1f C" % temp_c +
                                    " | %.1f F" % temp_f))
                            self.broadcastProbeStatus(
                                "dht", "dht_t", str(broadcasttemp),
                                self.AppPrefs.DHT_Sensor.get(
                                    "temperature_name"))

                            # json_body = [
                            # {
                            # "measurement": "probevalues",
                            # "tags": {
                            # "appuid": self.AppPrefs.appuid,
                            # "probeid": "dht_t"
                            # },
                            # "time": datetime.utcnow(),
                            # "fields": {
                            # "value": float(temp_c),
                            # }
                            # }
                            # ]

                            # log to InfluxDB
                            # self.WriteDataInfluxDB(json_body)
                            self.WriteProbeDataInfluxDB("dht_t", temp_c)

                            # log and broadcast humidity value
                            defs_common.logprobedata("dht_h_",
                                                     "{:.0f}".format(hum))
                            defs_common.logtoconsole(
                                "***Logged*** [dht_h] " +
                                self.AppPrefs.DHT_Sensor.get("humidity_name") +
                                " = %d %%" % hum,
                                fg="CYAN",
                                style="BRIGHT")
                            self.logger.info(
                                str("***Logged*** [dht_h] " +
                                    self.AppPrefs.DHT_Sensor.get(
                                        "humidity_name") + " = %d %%" % hum))
                            self.broadcastProbeStatus(
                                "dht", "dht_h", str(hum),
                                self.AppPrefs.DHT_Sensor.get("humidity_name"))
                            # json_body = [
                            # {
                            # "measurement": "probevalues",
                            # "tags": {
                            # "appuid": self.AppPrefs.appuid,
                            # "probeid": "dht_h"
                            # },
                            # "time": datetime.utcnow(),
                            # "fields": {
                            # "value": float(hum),
                            # }
                            # }
                            # ]
                            # log to InfluxDB
                            # self.WriteDataInfluxDB(json_body)
                            self.WriteProbeDataInfluxDB("dht_h", hum)

                            self.AppPrefs.DHT_Sensor[
                                "dht11_lastlogtime"] = int(
                                    round(time.time() * 1000))
                        else:
                            self.logger.info(
                                str("[dht_t] " + self.AppPrefs.DHT_Sensor.get(
                                    "temperature_name") +
                                    " = %.1f C" % temp_c +
                                    " | %.1f F" % temp_f))
                            self.logger.info(
                                str("[dht_h] " + self.AppPrefs.DHT_Sensor.get(
                                    "humidity_name") + " = %d %%" % hum))

                            # broadcast humidity value
                            self.broadcastProbeStatus(
                                "dht", "dht_h", str(hum),
                                self.AppPrefs.DHT_Sensor.get("humidity_name"))
                            # broadcast temperature value
                            self.broadcastProbeStatus(
                                "dht", "dht_t", str(broadcasttemp),
                                self.AppPrefs.DHT_Sensor.get(
                                    "temperature_name"))

                        # record the new sampling time
                        self.AppPrefs.DHT_Sensor[
                            "dht11_samplingtimeseed"] = int(
                                round(time.time() *
                                      1000))  # convert time to milliseconds

            ##########################################################################################
            # read each of the 8 channels on the mcp3008
            # channels (0-7)
            ##########################################################################################
            # only read the data at every ph_SamplingInterval (ie: 500ms or 1000ms)
            if (int(round(time.time() * 1000)) -
                    self.AppPrefs.dv_SamplingTimeSeed
                ) > self.AppPrefs.dv_SamplingInterval:
                # for x in range (0,8):
                for ch in self.AppPrefs.mcp3008Dict:
                    if self.AppPrefs.mcp3008Dict[ch].ch_enabled == "True":
                        #defs_common.logtoconsole(str(self.mcp3008Dict[ch].ch_num) + " " + str(self.mcp3008Dict[ch].ch_name) + " " + str(self.mcp3008Dict[ch].ch_enabled) + " " + str(len(self.mcp3008Dict[ch].ch_dvlist)))
                        dv = mcp3008.readadc(
                            int(self.AppPrefs.mcp3008Dict[ch].ch_num),
                            GPIO_config.SPICLK, GPIO_config.SPIMOSI,
                            GPIO_config.SPIMISO, GPIO_config.SPICS)

                        self.AppPrefs.mcp3008Dict[ch].ch_dvlist.append(dv)
                        #self.logger.info(str(self.mcp3008Dict[ch].ch_num) + " " + str(self.mcp3008Dict[ch].ch_name) + " " + str(self.mcp3008Dict[ch].ch_dvlist))
                    # once we hit our desired sample size of ph_numsamples (ie: 120)
                    # then calculate the average value
                    if len(self.AppPrefs.mcp3008Dict[ch].ch_dvlist) >= int(
                            self.AppPrefs.mcp3008Dict[ch].ch_numsamples):
                        # The probes may pick up noise and read very high or
                        # very low values that we know are not good values. We are going to use numpy
                        # to calculate the standard deviation and remove the outlying data that is
                        # Sigma standard deviations away from the mean.  This way these outliers
                        # do not affect our results
                        self.logger.info(
                            "mcp3008 ch" +
                            str(self.AppPrefs.mcp3008Dict[ch].ch_num) +
                            " raw data " +
                            str(self.AppPrefs.mcp3008Dict[ch].ch_name) + " " +
                            str(self.AppPrefs.mcp3008Dict[ch].ch_dvlist))
                        dv_FilteredCounts = numpy.array(
                            self.AppPrefs.mcp3008Dict[ch].ch_dvlist)
                        dv_FilteredMean = numpy.mean(dv_FilteredCounts, axis=0)
                        dv_FlteredSD = numpy.std(dv_FilteredCounts, axis=0)
                        dv_dvlistfiltered = [
                            x for x in dv_FilteredCounts
                            if (x > dv_FilteredMean -
                                float(self.AppPrefs.mcp3008Dict[ch].ch_sigma) *
                                dv_FlteredSD)
                        ]
                        dv_dvlistfiltered = [
                            x for x in dv_dvlistfiltered
                            if (x < dv_FilteredMean +
                                float(self.AppPrefs.mcp3008Dict[ch].ch_sigma) *
                                dv_FlteredSD)
                        ]

                        self.logger.info(
                            "mcp3008 ch" +
                            str(self.AppPrefs.mcp3008Dict[ch].ch_num) +
                            " filtered " +
                            str(self.AppPrefs.mcp3008Dict[ch].ch_name) + " " +
                            str(dv_dvlistfiltered))

                        # calculate the average of our filtered list
                        try:
                            dv_AvgCountsFiltered = int(
                                sum(dv_dvlistfiltered) /
                                len(dv_dvlistfiltered))
                            # delete this line
                            print("{:.2f}".format(dv_AvgCountsFiltered))
                        except:
                            # need to revisit this error handling. Exception thrown when all
                            dv_AvgCountsFiltered = 1
                            # values were 1023
                            print("Error collecting data")

                        # self.mcp3008Dict[ch].ch_dvlist.clear()  ## delete  this line

                        if self.AppPrefs.mcp3008Dict[ch].ch_type == "pH":
                            # bug, somtimes value is coming back high, like really high, like 22.0.  this is an impossible
                            # value since max ph is 14.  need to figure this out later, but for now, lets log this val to aid in
                            # debugging
                            orgval = dv_AvgCountsFiltered

                            # convert digital value to ph
                            lowCal = self.AppPrefs.mcp3008Dict[ch].ch_ph_low
                            medCal = self.AppPrefs.mcp3008Dict[ch].ch_ph_med
                            highCal = self.AppPrefs.mcp3008Dict[ch].ch_ph_high

                            dv_AvgCountsFiltered = ph_sensor.dv2ph(
                                dv_AvgCountsFiltered, ch, lowCal, medCal,
                                highCal)
                            dv_AvgCountsFiltered = float(
                                "{:.2f}".format(dv_AvgCountsFiltered))

                            if dv_AvgCountsFiltered > 14:
                                self.logger.error("Invalid PH value: " +
                                                  str(dv_AvgCountsFiltered) +
                                                  " " + str(orgval) + " " +
                                                  str(dv_dvlistfiltered))
                                defs_common.logtoconsole(
                                    "Invalid PH value: " +
                                    str(dv_AvgCountsFiltered) + " " +
                                    str(orgval) + " " + str(dv_dvlistfiltered),
                                    fg="RED",
                                    style="BRIGHT")

                        # if enough time has passed (ph_LogInterval) then log the data to file
                        # otherwise just print it to console
                        timestamp = datetime.now()
                        if (int(round(time.time() * 1000)) -
                                self.AppPrefs.mcp3008Dict[ch].LastLogTime
                            ) > self.AppPrefs.dv_LogInterval:
                            # sometimes a high value, like 22.4 gets recorded, i need to fix this, but for now don't log that
                            # if ph_AvgFiltered < 14.0:
                            #RBP_commons.logprobedata(config['logs']['ph_log_prefix'], "{:.2f}".format(ph_AvgFiltered))
                            # log data to InfluxDB
                            self.WriteProbeDataInfluxDB(
                                "mcp3008_ch" +
                                str(self.AppPrefs.mcp3008Dict[ch].ch_num),
                                "{:.2f}".format(dv_AvgCountsFiltered))
                            defs_common.logprobedata(
                                "mcp3008_ch" +
                                str(self.AppPrefs.mcp3008Dict[ch].ch_num) +
                                "_", "{:.2f}".format(dv_AvgCountsFiltered))
                            print(
                                timestamp.strftime(Fore.CYAN + Style.BRIGHT +
                                                   "%Y-%m-%d %H:%M:%S") +
                                " ***Logged*** dv = " +
                                "{:.2f}".format(dv_AvgCountsFiltered) +
                                Style.RESET_ALL)
                            self.AppPrefs.mcp3008Dict[ch].LastLogTime = int(
                                round(time.time() * 1000))
                        else:
                            print(
                                timestamp.strftime("%Y-%m-%d %H:%M:%S") +
                                " dv = " +
                                "{:.2f}".format(dv_AvgCountsFiltered))

                        self.broadcastProbeStatus(
                            "mcp3008", "mcp3008_ch" +
                            str(self.AppPrefs.mcp3008Dict[ch].ch_num),
                            str(dv_AvgCountsFiltered),
                            str(self.AppPrefs.mcp3008Dict[ch].ch_name))
                        self.AppPrefs.mcp3008Dict[ch].lastValue = str(
                            dv_AvgCountsFiltered)
                        # clear the list so we can populate it with new data for the next data set
                        self.AppPrefs.mcp3008Dict[ch].ch_dvlist.clear()
                        # record the new sampling time
                        self.AppPrefs.dv_SamplingTimeSeed = int(
                            round(time.time() *
                                  1000))  # convert time to milliseconds

            ##########################################################################################
            # pause to slow down the loop, otherwise CPU usage spikes as program is busy waiting
            ##########################################################################################
            time.sleep(.5)
Ejemplo n.º 9
0
#! /usr/bin/env python

import transmit_msg
import ds18b20
from pprint import pprint
 
messages = ds18b20.read_temp()
pprint(messages)
if len(messages) > 0:
    res = transmit_msg.send(messages)
    print ("message sent to mongo" + str(res))
Ejemplo n.º 10
0
from datetime import datetime
from ds18b20 import read_temp
from thingspeak import post_thingspeak
from display import show_lines
from dotenv import load_dotenv
load_dotenv()

temp_c = read_temp()
print('C=%3.3f' % temp_c)

# send to IOT platform
post_thingspeak(temp_c)

# display on local LCD in this format:
# Line 1: Now: 17:25:40
# Line 2: T1 = 23.7 C
display_data = []
display_data.append(datetime.now().strftime('Now: %H:%M:%S'))
temp_c = str(round(temp_c * 10) / 10)
display_data.append('T1 = ' + temp_c + ' C')
show_lines(display_data)
Ejemplo n.º 11
0
with open("weather.csv", "a") as csv:
    temp_sensors = ds18b20.get_devices()

    header = '# time, co2, humidity, int_temp'

    sensor_ids = []
    for sensor_id, sensor_name in temp_sensors.iteritems():
        header += ', %s' % sensor_name
        sensor_ids.append(sensor_id)

    print header
    csv.write(header + "\n")
    sht = sht31.SHT31()
    co2_sensor = k30.K30()

    while True:
        current_time = datetime.datetime.now()
        (int_temp, humidity) = sht.get_temp_and_humidity()

        co2 = co2_sensor.get_ppm()
        data_line = "%s, %d, %f, %f" % (current_time, co2, humidity, int_temp)

        for sensor_id in sensor_ids:
            data_line += ", " + ds18b20.read_temp(sensor_id)
            time.sleep(.1)

        print data_line
        csv.write(data_line + "\n")
        time.sleep(4)
Ejemplo n.º 12
0
def get_val2():
    return str(ds18b20.read_temp('28-00000471c98d'))
Ejemplo n.º 13
0
def get_val():
    return str(ds18b20.read_temp('28-00000677f123'))