def temperature_unit():
    counter = 0
    global config
    output_status = 0
    while True:
        counter = counter + 1
        temperature_value = temp.read_temperature()
        print "Temperature", temperature_value
        status = config["Devices_Settings"]["Temperature"][0]["Status"]
        Temp_Threshold = config["Devices_Settings"]["Temperature"][0][
            "Threshold_Value"]

        if counter > 10:
            counter = 0
            print "temperature log"
            write_temperature(temperature_value)

        if temperature_value > Temp_Threshold and output_status == 0 and status == 1:
            #call set alarm
            alarm_output = config["Triggers"][1]["Alarm_Output"]
            print alarm_output
            #triggers(alarm_output)s
            cl.Output(alarm_output, "Temperature 1", config, 0)
            output_status = 1
        if temperature_value < Temp_Threshold:
            output_status = 0
Example #2
0
def main():

    ##-------------------------------------------------------------------------
    ## Parse Command Line Arguments
    ##-------------------------------------------------------------------------
    ## create a parser object for understanding command-line arguments
    parser = argparse.ArgumentParser(description="Program description.")
    ## add flags
    parser.add_argument("-v",
                        "--verbose",
                        action="store_true",
                        dest="verbose",
                        default=False,
                        help="Be verbose! (default = False)")
    ## add arguments
    parser.add_argument("--input", type=str, dest="input", help="The input.")
    args = parser.parse_args()

    ##-------------------------------------------------------------------------
    ## Create logger object
    ##-------------------------------------------------------------------------
    logger = logging.getLogger('MyLogger')
    logger.setLevel(logging.DEBUG)
    ## Set up console output
    LogConsoleHandler = logging.StreamHandler()
    if args.verbose:
        LogConsoleHandler.setLevel(logging.DEBUG)
    else:
        LogConsoleHandler.setLevel(logging.INFO)
    LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s')
    LogConsoleHandler.setFormatter(LogFormat)
    logger.addHandler(LogConsoleHandler)
    ## Set up file output
    #     LogFileName = None
    #     LogFileHandler = logging.FileHandler(LogFileName)
    #     LogFileHandler.setLevel(logging.DEBUG)
    #     LogFileHandler.setFormatter(LogFormat)
    #     logger.addHandler(LogFileHandler)

    #     os.system('modprobe w1-gpio')
    #     os.system('modprobe w1-therm')

    ##-------------------------------------------------------------------------
    ## Read DS18B20 Temperature Sensors
    ##-------------------------------------------------------------------------
    temps = DS18B20.read()
    for temp in temps:
        logger.info('Temperature (DS18B20) = {:.1f} F'.format(temp))

    ##-------------------------------------------------------------------------
    ## Read DHT22 Temperature and Humidity Sensor
    ##-------------------------------------------------------------------------
    temp_DHT, humidity = DHT22.read()
    logger.info('Temperature (DHT22) = {:.1f} F'.format(temp_DHT))
    logger.info('Humidity (DHT22) = {:.0f} %'.format(humidity))
def main():

    ##-------------------------------------------------------------------------
    ## Parse Command Line Arguments
    ##-------------------------------------------------------------------------
    ## create a parser object for understanding command-line arguments
    parser = argparse.ArgumentParser(
             description="Program description.")
    ## add flags
    parser.add_argument("-v", "--verbose",
        action="store_true", dest="verbose",
        default=False, help="Be verbose! (default = False)")
    ## add arguments
    parser.add_argument("--input",
        type=str, dest="input",
        help="The input.")
    args = parser.parse_args()

    ##-------------------------------------------------------------------------
    ## Create logger object
    ##-------------------------------------------------------------------------
    logger = logging.getLogger('MyLogger')
    logger.setLevel(logging.DEBUG)
    ## Set up console output
    LogConsoleHandler = logging.StreamHandler()
    if args.verbose:
        LogConsoleHandler.setLevel(logging.DEBUG)
    else:
        LogConsoleHandler.setLevel(logging.INFO)
    LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s')
    LogConsoleHandler.setFormatter(LogFormat)
    logger.addHandler(LogConsoleHandler)
    ## Set up file output
#     LogFileName = None
#     LogFileHandler = logging.FileHandler(LogFileName)
#     LogFileHandler.setLevel(logging.DEBUG)
#     LogFileHandler.setFormatter(LogFormat)
#     logger.addHandler(LogFileHandler)

#     os.system('modprobe w1-gpio')
#     os.system('modprobe w1-therm')

    ##-------------------------------------------------------------------------
    ## Read DS18B20 Temperature Sensors
    ##-------------------------------------------------------------------------
    temps = DS18B20.read()
    for temp in temps:
        logger.info('Temperature (DS18B20) = {:.1f} F'.format(temp))
    
    ##-------------------------------------------------------------------------
    ## Read DHT22 Temperature and Humidity Sensor
    ##-------------------------------------------------------------------------
    temp_DHT, humidity = DHT22.read()
    logger.info('Temperature (DHT22) = {:.1f} F'.format(temp_DHT))
    logger.info('Humidity (DHT22) = {:.0f} %'.format(humidity))
    def _update_loop(self):
        """ Continue to read temps in a loop until asked to stop. """
        while self.is_on:
            # Start the conversion for the next loop
            logger.debug('Start Conversion on pin {}'.format(
                self._config['gpio']))
            DS.pinsStartConversion([self._config['gpio']])

            # Requires sleep for samples to appear
            sleep(self._config['sampling_seconds'])

            # We can average out the board temperature for this device, nice indicator.
            board_temps = 0
            count_board_ok = 0
            for sensor in self._sensors:
                temps = DS.readMax31850(False, self._config['gpio'], sensor)
                if temps is None:
                    continue

                # First we get our status, as we need to decide if this reading is going to be valid.
                status = self._do_status(temps, sensor)
                if status == Max31850Sensors.Status.OK:
                    # Good, then we get the temperature reported by the 1-wire device
                    logger.debug(
                        'Sensor {} reports a valid temperature as {}'.format(
                            sensor, temps[0]))
                    self._temps[sensor]['temp'] = temps[0]
                    self._temps[sensor]['status'] = status
                    board_temps += temps[1]
                    count_board_ok += 1
                else:
                    # This is not good then, whatever the case is, we can't trust this temp
                    logger.debug('Sensor {} reports an error as {}'.format(
                        sensor, status))
                    self._temps[sensor]['temp'] = None
                    self._temps[sensor]['status'] = status

            # Now we can get the mean of our board temps.
            if count_board_ok > 0:
                self._board_temp = board_temps / count_board_ok
Example #5
0
File: WRM.py Project: rickie95/WRM
def main(verbose=False):
    t_sensor = None
    screen = None
    thermostat = None
    scheduler = None

    try:
        t_sensor = D.TempSensor()
    except Exception as ex:
        print("Cannot reach the sensor, check wiring. Aborting..")
        print(ex)

    try:
        scheduler = Scheduler.SchedManager()
    except Exception as ex:
        print("A problem occurs while initialising Scheduler obj.")
        print(ex)

    # Create and init Screen
    if t_sensor is not None and scheduler is not None:
        try:
            thermostat = T.Thermostat(t_sensor, scheduler, verbose)
            screen = S.Screen(t_sensor, scheduler, verbose)
        except Exception as ex:
            print(ex)

        try:
            if thermostat is not None:
                thermostat.start()

            if screen is not None:
                #screen.setParam(t_sensor.get_temp(), 20, 1)
                screen.start()

            while True:
                time.sleep(1)
        except (Exception, KeyboardInterrupt) as ex:
            print("Exiting, raised exception.")
            print(ex)
            screen.stop()
            thermostat.stop()
            screen.join()
            thermostat.join()

    print("Everything ok.")
    if screen.is_alive():
        screen.stop()
        screen.join()
    if thermostat.is_alive():
        thermostat.stop()
        thermostat.join()
Example #6
0
    def makeSensor(self, model, pin, filepath, DEBUG=False):

        # Add in a new case for your sensor's model here

        if model == "DS18B20":
            if pin != 4:
                print "Error! This sensor should only be used on pin four!"
                self.lastSensor = None
                return
                # get sensor class
            import DS18B20

            # run static methods to get specific info from user in a list
            mySpecifics, customs, extras = DS18B20.specs()
            if DEBUG:
                print mySpecifics
                print customs
                print extras
                # instantiate with the list items returned
            temp = DS18B20.DS18B20(mySpecifics[0], 4, filepath)
            if DEBUG:
                print temp
                print type(temp)
            self.lastSensor = temp
            if len(customs) > 0:
                self.customs[temp.model] = customs
            if len(extras) > 0:
                self.extraPins[temp.model] = extras

        if model == "HC_SR501":
            import HC_SR501

            mySpecifics, customs, extras = HC_SR501.specs()
            temp = HC_SR501.HC_SR501(pin, mySpecifics[0], filepath)
            if DEBUG:
                print mySpecifics
                print customs
                print extras
                print temp
                print type(temp)
            self.lastSensor = temp
            if len(extras) > 0:
                self.extraPins[temp.model] = extras
            if len(customs) > 0:
                self.customs[temp.model] = customs

        if model == "HC_SR04":
            self.lastSensor = None
Example #7
0
 def updateSensors(self):
     for i in range(len(sensorTable)):
        x = i % nbSensorCol
        y = i // nbSensorCol
        Temp = ds.read(False,DS_PIN,sensorTable[i])
        if Temp is None:
           self.myrect[i].changeColor('black')
        else:
           T = Temp - minTemp;
           T = T * gainFactor;
           T = int(T)
           if T < 0 :
              T = 0
           if T >= len(self.colorTable):
              T = len(self.colorTable)-1
           self.myrect[i].changeColor(self.colorTable[T])
        self.myrect[i].changeTemp(Temp)
     self.root.after(1,self.startConversion)
Example #8
0
def main():

    logging.basicConfig(format="%(asctime)-15s %(message)s",
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    parser = argparse.ArgumentParser(description='Climate')
    parser.add_argument('-i', '--interval', help='reporting interval in seconds')
    parser.add_argument('-d', '--display_only', help='only display, no reporting', action="store_true")
    args = parser.parse_args()

    if args.interval:
        Registry.reporting_interval = int(args.interval)
    display_only = args.display_only

    # REST client.
    aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)

    # Adafruit IO Feeds.
    temperature_feed = aio.feeds('room-temperature')

    while True:

        try:
            temperature = DS18B20.get_temperature()

            if temperature is not None:
                logging.info('Temp={0:0.1f}*C Send readings={1}'.format(temperature, not display_only))
            else:
                logging.info('Failed to get readings, trying again in {} seconds'.format(Registry.reporting_interval))

            if not display_only:
                send_readings(aio, temperature, temperature_feed)

        #except Adafruit_IO.errors.ThrottlingError as ex:
        #    logging.info('Throttling occured - Caught exception: %s', ex.__class__.__name__)
        except Exception as ex:
            logging.info('Caught exception: %s', ex.__class__.__name__)
            traceback.print_exc()

        # Avoid flooding Adafruit IO
        time.sleep(Registry.reporting_interval)
Example #9
0
def main():
    print("\n\nStarting - {}".format(machine.reset_cause()))

    while True:
        try:
            # Establish WiFi connection here
            interface = WiFi.connect_wifi(Config.wifi_ssid, Config.wifi_pass)
            if interface:
                print('Connected: ', interface.ifconfig())

            # If we've got somewhere to write the data, read the sensors.
            # Deliberately do the DHT22 read last to maximise the chance of it having had long enough
            # to stabilise (only one read every 2 seconds)
            measurements = ''
            measurements += DS18B20.read_ds(Config.onewirePin, Config.location)
            measurements += DHT.read_dht(Config.dhtPin, Config.location)
            if measurements:
                print('\nSending to {}\n{}'.format(Config.database,
                                                   measurements))
                print('HTTP:{0}'.format(
                    Influx.send(Config.database, measurements)))
            else:
                print('No sensors read successfully.')

        except KeyboardInterrupt:
            print("Caught keyboard interrupt")
            enter_sleep = False

        except Exception as e:
            import sys
            print("Unexpected error ", e)
            sys.print_exception(e)
        finally:
            if Config.deep_sleep:
                print('Zzzz....')
                Deepsleep.deep_sleep(Config.sampleTime * 1000)

        # This will only be executed if Deepsleep is disabled
        print('Dozing....')
        time.sleep(Config.sampleTime)
Example #10
0
def update_outside_temperature():
    _log.info(
        TIMER_PRINT_MSG.format('Ažuriranje spoljne temperature i ta peći'))
    try:
        outside_weather = yahooweather.getCurrentTemp('petrovac, rs')
        blynk.virtual_write(4, outside_weather)
        _log.info(
            TIMER_PRINT_MSG.format(
                'Spoljna temperatura ažurirana {}°C'.format(outside_weather)))
    except:
        _log.error('Neuspelo ažuriranje spoljne temperature')

    try:
        ta_temp = round(ds.read(True, DS_DPIN, DS_ID), 1)
        _log.info('Očitana temperatura sa DS senzora: {}°C'.format(ta_temp))
        if ta_temp is not None:
            blynk.virtual_write(DS_VPIN, ta_temp)
            if ta_temp <= temperature:
                sendNotification('TA peć je prazna, uključite akumulaciju')
    except:
        _log.error('Došlo je do greške prilikom čitanja DS senzora')
        blynk.virtual_write(DS_VPIN, 0)
Example #11
0
 def __init__(self):
     self.logger = logging.getLogger(__name__)
     try:
         self.myOled = oled.Oled()
         self.myOled.writerow(1, "Starting up")
     except:
         self.logger.error('Oled failed init.')
         sys.exit(0)
     try:
         self.myUbidots = myubidots.Ubidots()
     except:
         self.myOled.writerow(1, "Ubidots failed init")
         self.logger.error('Ubidots failed init.')
         sys.exit(0)
     try:
         self.myDS = DS18B20.DS18B20()
     except:
         self.myOled.writerow(1, "Sensor init failed")
         self.logger.error('Sensor init failed.')
         sys.exit(0)
     self.myAlarm = alarm.Alarm()
     self.myOled.writerow(1, "Initialised     ")
    def initialise(self):
        self.off()

        self._sensors = DS.scan(self._config['gpio'])
        if len(self._sensors) == 0:
            msg = 'No temperature sensors found, cowardly exiting.'
            logger.error(msg)
            sys.exit(msg)

        logger.info('Found temperature sensors with ids {}'.format(
            self._sensors))

        # Preload reading with initial state.
        for sensor in self._sensors:
            self._temps[sensor] = {
                'temp': None,
                'status': Max31850Sensors.Status.UNKNOWN
            }

        self._update_thread = threading.Timer(0, self._update_loop)
        self._update_thread.daemon = True
        logger.info('Initialised Temperature sensors on gpio {}'.format(
            self._config['gpio']))
Example #13
0
    def __init__(self):
        self.logger = logging.getLogger(__name__)
        self.displaytype = keys.display
        self.cloud = keys.cloud
        if self.displaytype == 'oled':
            try:
                import oled
                self.display = oled.Oled()
                self.display.writerow(TITLE_ROW, "Starting up")
            except:
                self.logger.error('Oled failed init.')
                sys.exit(0)
        elif self.displaytype == 'uoled':
            try:
                import uoled
                print('Setting up uoled')
                self.display = uoled.Screen()
            except:
                print('Uoled failed init.')
                self.logger.error('Uoled failed init.')
                sys.exit(0)
        elif self.displaytype == 'uoledada':
            try:
                import uoledada
                print('Setting up uoledada')
                self.display = uoledada.Screen()
            except:
                print('Uoledada failed init.')
                self.logger.error('Uoledada failed init.')
                sys.exit(0)
        elif self.displaytype == 'uoledi2c':
            try:
                import uoledi2c
                print('Setting up uoledi2c')
                self.display = uoledi2c.Screen()
            except:
                print('Uoledi2c failed init.')
                self.logger.error('Uoledi2c failed init.')
                sys.exit(0)
        elif self.displaytype == '7seg':
            try:
                import sevenseg
                self.sevenseg = sevenseg.Sevenseg()
            except:
                self.logger.error('7seg failed init.')
                sys.exit(0)
        elif self.displaytype == 'tft':
            print("setting up newtft")
            try:
                import newtft  # note newtft based on latest adafruit lib
                self.display = newtft.Screen()
            except:
                self.logger.error('newtft failed init.')
                sys.exit(0)
        else:
            self.logger.error('No display specified.')
            print('No display specified')
            sys.exit(0)

        if self.cloud == 'none':
            try:
                import dummycloud
                self.myCloud = dummycloud.Mydummycloud()
                self.display.cloud_type = 'file'
                print('Using dummy cloud')
            except:
                self.display.newwriterow(1, "Dummycloud failed init")
                self.logger.error('Dummycloud failed init.')
                sys.exit(0)
        elif self.cloud == 'ubidots':
            try:
                import myubidots
                self.myCloud = myubidots.Myubidots()
                self.display.cloud_type = 'ubidots'
                print('Ubidots cloud')
            except:
                self.display.newwriterow(1, "Ubidots failed init")
                self.logger.error('Ubidots failed init.')
                sys.exit(0)
        elif self.cloud == 'beebotte':
            try:
                import mybeebotte
                self.myCloud = mybeebotte.Mybeebotte(no_sensors=2)
                self.display.cloud_type = 'beebotte'
                self.display.writerow(
                    CLOUD_ROW4,
                    keys.beebotte_variable + ' ' + keys.beebotte_variable2)
                print('Beebotte cloud')
            except:
                self.display.writerow(TITLE_ROW, "Beebotte failed init")
                self.logger.error('Beebotte failed init.')
                print("Beebotte failed init.", sys.exc_info()[0])
                sys.exit(0)
        else:
            self.logger.error('Cloud type not specified. Check keys file.')
            print('Cloud type not specified. Check keys file.')
            self.display.cloud_type = 'no cloud'
            sys.exit(0)
        self.cloud_error = False

        try:
            self.myDS = DS18B20.DS18B20()
        except:
            self.display.writerow(1, "Sensor init failed")
            self.logger.error('Sensor init failed.')
            sys.exit(0)
        self.myAlarm = alarm.Alarm()
        self.mySystem = system.System()
        hostname = self.mySystem.hostname()
        self.display.newwriterow(STATUS_ROW, 'Hostname:' + hostname)
        self.display.newwriterow(CLOUD_ROW, 'Cloud:' + self.cloud)
        self.log_counter = 0
        self.cloud_counter = 0
        self.display.newwriterow(TITLE_ROW, 'Thermometer')
        if BIG_TEXT == False:
            self.display.newwriterow(LABELS_ROW, 'Min    Now   Max  ')
Example #14
0
import time
import DS18B20 as DS

sensors = DS.scan(20)

try:
    while (True):
        DS.pinsStartConversion([20])
        time.sleep(0.75)
        for i in sensors:
            print("{:.3f}".format(DS.read(False, 20, i)), end=" ")
        print(" ")
except KeyboardInterrupt:
    quit()
Example #15
0
s = scheduler.SchedManager()

path = "/home/pi/wrm_app/control_panel/"


try:
	original = open(path+"log.txt", "r")
	copy = open(path+"n_log.txt", "w")
	file = original.read().splitlines()
	print(len(file))
	numb = min ( 30, len(file) )
	for count in range(1, numb+1):
		copy.write(file[count]+"\n")
	original.close()
	t = DS18B20.get_temp()
	t = round(t,1)
	settemp = s.get_reference_temp()
	timez = datetime.datetime.now()
	minut = timez.minute
	if minut < 10:
		s_min = "0"+str(minut)	
	if minut >= 10:
		s_min = str(minut)
	stringa = str(timez.hour) + ":" + s_min
	copy.write(stringa + "," + str(t) + "," + str(settemp)+"\n")
	copy.close()
	os.remove(path+"log.txt")
	os.rename(path+"n_log.txt", path+"log.txt")
#	time.sleep(1)
except KeyboardInterrupt:
Example #16
0
#!/usr/bin/python3

import DS18B20 as sensor
import time
import os.path
import pickle
from PiStatSettings import PiStatTemp

LOG_PERIOD = 5		# Log period in seconds.
TIME_OFFSET = .82	# Time offset for loop execution.

sensor.setup()

# Function that logs temp to a csv by day in the "temp_logs" sub directory.
def logTemp(temp):
	# Get timestamp and create log file name
	timestamp = time.time()
	day = time.strftime("%d")
	month = time.strftime("%m")
	filename = "tempLog_%s_%s.csv" %(month, day)

	# Creat subdirectory if it DNE
	subdirectory = "temp_logs"
	try:
		os.mkdir(subdirectory)
	except Exception:
		pass

	# Line to be written to log file
	line = str(timestamp) + "," + str(tempF) + "\n"
Example #17
0
 def setSensorResolution(self,resolution):
     for i in sensorTable:
        #check the resolution first
        res = ds.getResolution(DS_PIN,i)
        if res != resolution:
           ds.setResolution(DS_PIN,i,resolution)
Example #18
0
    def run(self):
        log('info', "Starting " + self.name)
        global eqLogic, JeedomIP, TempoPinLOW, TempoPinHIGH, exit, Status_pins, swtch, GPIO, SetAllLOW, SetAllHIGH, CounterPinValue, s, BootMode, SetAllSWITCH, SetAllPulseLOW, SetAllPulseHIGH, ProbeDelay, thread_1, thread_2, thread_tries1, bmp180, bmp280, bme280, bme680, bmp280b, bme280b, bme680b, gpioSET, sendPINMODE, busio, CptNextReArm, ReArmDelay
        s = socket.socket()  # Create a socket object
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #host = socket.gethostname() 	# Get local machine name
        try:
            s.bind(('', port))  # Bind to the port
        except:
            s.close()  # rate
            log('erreur',
                'Le port est peut-etre utilise. Nouvel essai dans 11s.')
            SimpleSend('&PORTISUSED=' + str(port))
            time.sleep(11)  # on attend un peu
            s = socket.socket()
            s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            try:
                s.bind(('', port))  # nouvel essai
            except:
                s.close()  # rate
                log(
                    'erreur',
                    'Le port est probablement utilise. Nouvel essai en mode auto dans 7s.'
                )
                SimpleSend('&PORTINUSE=' + str(port))
                time.sleep(7)  # on attend encore un peu
                s = socket.socket()
                s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
                portnew = 0
                try:
                    s.bind(('', 0))  # on essai en auto decouverte
                    addr, portnew = s.getsockname()
                    log('debug',
                        'Un port libre est disponible : ' + str(portnew))
                    SimpleSend('&PORTFOUND=' + str(portnew))
                except:
                    log(
                        'erreur',
                        'Impossible de trouver un port automatiquement. Veuillez en choisir un autre'
                    )
                    SimpleSend('&NOPORTFOUND=' + str(port))
                    s.close()
                    exit = 1
                    raise e

        s.listen(5)  # Now wait for client connection.
        while exit == 0:
            thread_1 = 1
            c, addr = s.accept()  # Establish connection with client.
            if exit == 1:
                break
            m = c.recv(1024)
            thread_tries1 = 0
            query = SimpleParse(m)
            if query:
                log('Requete', str(query))

                reponse = 'NOK'
                exit = 0
                RepStr = ''
                GPIOStr = ''

                if 'BootMode' in query:
                    q = query.index("BootMode")
                    BootMode = int(query[q + 1])
                    reponse = 'BMOK'

                if 'ConfigurePins' in query:
                    q = query.index("ConfigurePins")
                    Status_pins = query[q + 1]
                    sendPINMODE = 1

                    for i in range(0, 40):
                        #j=i+1
                        j = pin2gpio[i]
                        if Status_pins[i] == 'o' or Status_pins[
                                i] == 'y' or Status_pins[
                                    i] == 's' or Status_pins[
                                        i] == 'l' or Status_pins[
                                            i] == 'h' or Status_pins[
                                                i] == 'u' or Status_pins[
                                                    i] == 'v' or Status_pins[
                                                        i] == 'w':
                            GPIO.setup(j, GPIO.OUT)
                            GPIO.remove_event_detect(j)
                            GPIO.output(j, BootMode)
                            swtch[i + 1] = BootMode
                            GPIOStr += '&' + str(i + 1) + '=' + str(BootMode)
                        elif Status_pins[i] == 'p':
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                            GPIO.remove_event_detect(j)
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_inputs)
                            GPIOStr += '&IN_' + str(i + 1) + '=' + str(
                                GPIO.input(j))
                        elif Status_pins[i] == 'c':
                            k = i % 4
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                            GPIO.remove_event_detect(j)
                            if k == 1:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts1)
                            elif k == 2:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts2)
                            elif k == 3:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts3)
                            else:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts0)
                            time.sleep(0.1)
                        elif Status_pins[i] == 'G':
                            k = i % 4
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                            GPIO.remove_event_detect(j)
                            if k == 1:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts1)
                            elif k == 2:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts2)
                            elif k == 3:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts3)
                            else:
                                GPIO.add_event_detect(j,
                                                      GPIO.BOTH,
                                                      callback=toggle_cpts0)
                            time.sleep(0.1)
                        elif Status_pins[i] == 'n':
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                            GPIO.remove_event_detect(j)
                            GPIO.add_event_detect(j,
                                                  GPIO.RISING,
                                                  callback=toggle_inputs)
                        elif Status_pins[i] == 'q':
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                            GPIO.remove_event_detect(j)
                            GPIO.add_event_detect(j,
                                                  GPIO.FALLING,
                                                  callback=toggle_inputs)
                        elif Status_pins[i] == 'i':
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                            GPIO.remove_event_detect(j)
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_inputs)
                            GPIOStr += '&IN_' + str(i + 1) + '=' + str(
                                GPIO.input(j))
                        elif Status_pins[i] == 'd' or Status_pins[
                                i] == 'f':  # Sondes DHT(11,22)
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                            GPIO.remove_event_detect(j)
                        elif Status_pins[i] == 'b':  # Sondes DS18b20
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                            GPIO.remove_event_detect(j)
                            sensors[i] = DS.scan(pin2gpio[i])
                        elif Status_pins[
                                i] == 't':  #HC-SR04 Declencheur (Trigger pin)
                            GPIO.setup(j, GPIO.OUT)
                            GPIO.remove_event_detect(j)
                            GPIO.output(j, False)
                        elif Status_pins[
                                i] == 'z':  #HC-SR04 Distance (Echo pin)
                            GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                            GPIO.remove_event_detect(j)
                        elif Status_pins[i] == 'r':
                            bmp180 = BMP085.BMP085()
                        elif Status_pins[i] == 'A':
                            i2c = busio.I2C(board.SCL, board.SDA)
                            try:
                                bme280 = adafruit_bme280.Adafruit_BME280_I2C(
                                    i2c, 118)  # hex76 = 118
                            except:
                                bme280 = adafruit_bme280.Adafruit_BME280_I2C(
                                    i2c)  #hex77 default
                            bme280.sea_level_pressure = 1013.25
                        elif Status_pins[i] == 'D':
                            i2c = busio.I2C(board.SCL, board.SDA)
                            try:
                                bme280b = adafruit_bme280.Adafruit_BME280_I2C(
                                    i2c)  #hex77 default
                            except:
                                bme280b = adafruit_bme280.Adafruit_BME280_I2C(
                                    i2c, 118)  # hex76 = 118
                            bme280b.sea_level_pressure = 1013.25
                        elif Status_pins[i] == 'B':
                            i2c = busio.I2C(board.SCL, board.SDA)
                            try:
                                bme680 = adafruit_bme680.Adafruit_BME680_I2C(
                                    i2c, 118, debug=False)
                            except:
                                bme680 = adafruit_bme680.Adafruit_BME680_I2C(
                                    i2c, debug=False)
                            bme680.sea_level_pressure = 1013.25
                        elif Status_pins[i] == 'E':
                            i2c = busio.I2C(board.SCL, board.SDA)
                            try:
                                bme680b = adafruit_bme680.Adafruit_BME680_I2C(
                                    i2c, debug=False)
                            except:
                                bme680b = adafruit_bme680.Adafruit_BME680_I2C(
                                    i2c, 118, debug=False)
                            bme680b.sea_level_pressure = 1013.25
                        elif Status_pins[i] == 'C':
                            i2c = busio.I2C(board.SCL, board.SDA)
                            try:
                                bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(
                                    i2c, 118)
                            except:
                                bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(
                                    i2c)
                            bmp280.sea_level_pressure = 1013.25
                        elif Status_pins[i] == 'F':
                            i2c = busio.I2C(board.SCL, board.SDA)
                            try:
                                bmp280b = adafruit_bmp280.Adafruit_BMP280_I2C(
                                    i2c)
                            except:
                                bmp280b = adafruit_bmp280.Adafruit_BMP280_I2C(
                                    i2c, 118)
                            bmp280b.sea_level_pressure = 1013.25
                    reponse = 'C*K'
                    RepStr = '&REP=' + str(reponse) + GPIOStr
                    gpioSET = True

                if 'eqLogic' in query:
                    q = query.index("eqLogic")
                    eqLogic = query[q + 1]
                    reponse = 'EOK'
                    #SimpleSend('&REP=' + str(reponse))

                if 'JeedomIP' in query:
                    q = query.index("JeedomIP")
                    JeedomIP = query[q + 1]
                    reponse = 'IPOK'
                    #SimpleSend('&REP=' + str(reponse))

                if 'SetPinLOW' in query:
                    q = query.index("SetPinLOW")
                    u = int(query[q + 1])
                    reponse = 'SOK'
                    SetPin(u, 0, reponse)

                if 'SetPinHIGH' in query:
                    q = query.index("SetPinHIGH")
                    u = int(query[q + 1])
                    reponse = 'SOK'
                    SetPin(u, 1, reponse)

                if 'SetLOWpulse' in query:
                    q = query.index("SetLOWpulse")
                    u = int(query[q + 1])
                    q = query.index("tempo")
                    TempoPinLOW[u] = time.time() * 10 + int(query[q + 1])
                    reponse = 'SOK'
                    SetPin(u, 0, reponse)

                if 'SetHIGHpulse' in query:
                    q = query.index("SetHIGHpulse")
                    u = int(query[q + 1])
                    q = query.index("tempo")
                    TempoPinHIGH[u] = time.time() * 10 + int(query[q + 1])
                    reponse = 'SOK'
                    SetPin(u, 1, reponse)

                if 'SwitchPin' in query:
                    q = query.index("SwitchPin")
                    u = int(query[q + 1])
                    v = 1 - swtch[u]
                    reponse = 'SOK'
                    SetPin(u, v, reponse)

                if 'SetCPT' in query:
                    q = query.index("SetCPT")
                    u = int(query[q + 1])
                    q = query.index("ValCPT")
                    ValCPT = int(query[q + 1])
                    CounterPinValue[u] += ValCPT
                    reponse = 'SCOK'
                    RepStr = '&REP=' + str(reponse)

                if 'RazCPT' in query:
                    q = query.index("RazCPT")
                    u = int(query[q + 1])
                    q = query.index("ValCPT")
                    ValCPT = int(query[q + 1])
                    CounterPinValue[u] = ValCPT
                    reponse = 'SCOK'
                    RepStr = '&REP=' + str(reponse)

                if 'SetAllLOW' in query:
                    SetAllLOW = 1  # deport dans l'autre thread question de vitesse d'execution
                    reponse = 'SOK'

                if 'SetAllHIGH' in query:
                    SetAllHIGH = 1  # deport dans l'autre thread question de vitesse d'execution
                    reponse = 'SOK'

                if 'SetAllSWITCH' in query:
                    SetAllSWITCH = 1  # deport dans l'autre thread question de vitesse d'execution
                    reponse = 'SOK'

                if 'SetAllPulseLOW' in query:
                    RepStr = '&REP=SOK'
                    q = query.index("tempo")
                    for i in range(0, 40):
                        j = i + 1
                        if Status_pins[i] == 'o' or Status_pins[
                                i] == 's' or Status_pins[
                                    i] == 'l' or Status_pins[
                                        i] == 'h' or Status_pins[
                                            i] == 'u' or Status_pins[
                                                i] == 'v' or Status_pins[
                                                    i] == 'w':
                            swtch[j] = 0
                            GPIO.output(pin2gpio[i], 0)
                            TempoPinLOW[j] = time.time() * 10 + int(
                                query[q + 1])
                            RepStr += '&' + str(j) + '=0'
                    reponse = 'SOK'

                if 'SetAllPulseHIGH' in query:
                    RepStr = '&REP=SOK'
                    q = query.index("tempo")
                    for i in range(0, 40):
                        j = i + 1
                        if Status_pins[i] == 'o' or Status_pins[
                                i] == 's' or Status_pins[
                                    i] == 'l' or Status_pins[
                                        i] == 'h' or Status_pins[
                                            i] == 'u' or Status_pins[
                                                i] == 'v' or Status_pins[
                                                    i] == 'w':
                            swtch[j] = 1
                            GPIO.output(pin2gpio[i], 1)
                            TempoPinHIGH[j] = time.time() * 10 + int(
                                query[q + 1])
                            RepStr += '&' + str(j) + '=1'
                    reponse = 'SOK'

                if 'Trigger' in query:
                    q = query.index("Trigger")
                    u = int(query[q + 1])
                    q = query.index("Echo")
                    v = int(query[q + 1])
                    RepStr = GetDistance(u, v)
                    reponse = 'SOK'

                if 'SetLOWdoublepulse' in query:
                    q = query.index("SetLOWdoublepulse")
                    u = int(query[q + 1])
                    r = pin2gpio[u - 1]
                    q = query.index("tempclick")
                    v = float(query[q + 1]) / 10
                    q = query.index("temppause")
                    w = float(query[q + 1]) / 10
                    GPIO.output(r, 0)
                    time.sleep(v)
                    GPIO.output(r, 1)
                    time.sleep(w)
                    GPIO.output(r, 0)
                    time.sleep(v)
                    reponse = 'SOK'
                    SetPin(u, 1, reponse)

                if 'SetHIGHdoublepulse' in query:
                    q = query.index("SetHIGHdoublepulse")
                    u = int(query[q + 1])
                    r = pin2gpio[u - 1]
                    q = query.index("tempclick")
                    v = float(query[q + 1]) / 10
                    q = query.index("temppause")
                    w = float(query[q + 1]) / 10
                    GPIO.output(r, 1)
                    time.sleep(v)
                    GPIO.output(r, 0)
                    time.sleep(w)
                    GPIO.output(r, 1)
                    time.sleep(v)
                    reponse = 'SOK'
                    SetPin(u, 0, reponse)

                if 'CptDelay' in query:
                    q = query.index("CptDelay")
                    ReArmDelay = int(query[q + 1])
                    reponse = 'SCOK'

                if 'ProbeDelay' in query:
                    q = query.index("ProbeDelay")
                    ProbeDelay = int(query[q + 1])
                    reponse = 'SOK'

                if 'PING' in query:
                    if thread_2 == 1:
                        reponse = 'PINGOK'
                    else:
                        reponse = 'PINGKO'
                    RepStr = '&REP=' + str(reponse)

                if 'EXIT' in query:
                    exit = 1
                    reponse = 'EXITOK'

                if reponse != '':
                    c.send(reponse.encode('ascii'))
                    log('>> Reponse a la requete', str(reponse))
                    if RepStr != '':
                        SimpleSend(RepStr)

                if exit == 1:
                    break

            c.close()
            time.sleep(0.1)
        s.close()
        if exit == 1:
            try:
                GPIO.cleanup()
            except:
                pass
            sys.exit()
Example #19
0
data['DHT11'] = []
data['DS18B20'] = []
bu_path = os.path.dirname(os.path.abspath(__file__))

dt = datetime.datetime.now()
data['DHT11'].append({
    'date': dt.strftime('%d-%b-%Y'),
    'time': dt.strftime('%H:%M'),
    'tempr': DHT11.read_temp(),
    'humidity': DHT11.read_humidity()
})

data['DS18B20'].append({
    'date': dt.strftime('%d-%b-%Y'),
    'time': dt.strftime('%H:%M'),
    'tempr': DS18B20.read_temp()
})

headers = {
    'User-Agent':
    'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
    'Accept':
    'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
    'Accept-Encoding': 'none',
    'Accept-Language': 'en-US,en;q=0.8',
    'Connection': 'keep-alive',
    'content-type': 'application/json'
}

led.on()
Example #20
0
import sys
import time
import os
import datetime

# Get a list of temperature sensors and report their values every second.
# The W1 driver must be working.

sensors = []

devices = os.listdir("/sys/bus/w1/devices/")

for device in devices:
    if device[:2] == "28":
        print("Found device: %s" % device)
        sensors.append(DS18B20.DS18B20(device))

if not sensors:
    print("No sensors found in /sys/bus/w1/devices")
    sys.exit()
else:
    print("Found %s temperature sensors." % len(sensors))
    print()

try:
    print("Starting threads for %s sensors." % len(sensors))
    for sensor in sensors:
        print("Starting %s" % sensor.deviceID)
        sensor.start()

    while (True):
Example #21
0
    if sensor['door_open'].enable:
        try:
            pi.set_mode(sensor['door_open'].ref, pigpio.INPUT)
            sensor_value['door_open'] = pi.read(sensor['door_open'].ref)
            logger.info('Reading value from door sensor... OK')

        except ValueError:
            logger.warning('Failed to read door sensor ({value_error})'.format(
                value_error=ValueError))

    #-------------------------------------------------------------------
    # Get outside temperature
    #-------------------------------------------------------------------
    if sensor['outside_temp'].enable:
        try:
            out_sensor = DS18B20.DS18B20(sensor['outside_temp'].ref,
                                         s.W1_DEVICE_PATH)
            sensor_value['outside_temp'] = out_sensor.get_temp()

            if sensor_value['outside_temp'] > 900:
                logger.warning('Failed to read DS18B20 sensor (temp > 900)')
                sensor_value['outside_temp'] = 'U'
            else:
                logger.info('Reading value from DS18B20 sensor... OK')

        except Exception, e:
            logger.warning(
                'Failed to read DS18B20 ({value_error})'.format(value_error=e),
                exc_info=True)

    #-------------------------------------------------------------------
    # Add data to RRD
Example #22
0
    def dimdisplay(self, brightness):
        # max brightness=255
        try:
            bus.write_byte_data(sevensegaddress, brightnesscontrol, brightness)
        except IOError:
            self.ioerrorcount = self.ioerrorcount + 1

##The start of the real code ##
if __name__ == "__main__":
    logging.basicConfig(filename=LOGFILE, filemode='w', level=logging.WARNING)
    logging.warning(datetime.datetime.now().strftime('%d %b %H:%M') +
                    ". Running 7seg class as a standalone app")

    print "Running 7seg class as a standalone app"
    my7seg = Sevenseg()
    myDS = DS18B20.DS18B20()
    myDots = myubidots.Ubidots()
    time.sleep(2)  #let the board settle down
    i = 0
    while True:
        if my7seg.updateclock() == 0:
            my7seg.dimdisplay(defaultbrightness)
            time.sleep(3)
            temp = myDS.read_temp()
            #			logging.info("Temperature:"+str(temp))
            my7seg.write_temp(temp)
            if i > 5:  # every 2 mins
                myDots.write(temp)
                i = 0
            i += 1
        time.sleep(17)
Example #23
0
import DS18B20 as ds
import time

sensor = [
    '28-0117C19740FF', '28-0117C1AFC0FF', '28-0217C11EE0FF', '28-0217C12228FF',
    '28-0117C17354FF', '28-0217C1129CFF', '28-0117C14282FF', '28-0117C19E86FF',
    '28-0117C140A6FF', '28-0217C1426EFF', '28-0217C1283EFF', '28-0117C1747EFF',
    '28-0117C1757EFF', '28-0217C10009FF', '28-0117C16769FF', '28-0117C17799FF',
    '28-0217C13A79FF', '28-0217C0FD79FF', '28-0117C16F35FF', '28-0117C17A75FF',
    '28-0217C1B8CDFF', '28-0117C17B2DFF', '28-0217C14203FF', '28-0117C16783FF',
    '28-0217C0FB8BFF', '28-0217C0FCEBFF', '28-0217C1B35BFF', '28-0117C190E7FF',
    '28-0117C19757FF', '28-0217C1146FFF'
]

ds.pinsStartConversion([21])
time.sleep(0.75)
for i in range(len(sensor)):
    print("{}- {} : {} 'C".format(i + 1, sensor[i],
                                  ds.read(False, 21, sensor[i])))
Example #24
0
    return t1.day != t2.day


def is_new_month(t1, t2):
    return t1.month != t2.month


# Raspberry Pi pin configuration:
RST = 27
DC = 25
BL = 18
bus = 0
device = 0
onewire = 4

sensors = DS.scan(onewire)

# 240x240 display with hardware SPI:
disp = ST7789.ST7789(SPI.SpiDev(bus, device), RST, DC, BL)

# Initialize library.
disp.Init()

# Clear display.
disp.clear()

# Setup interrupts
pinput = 5
GPIO.setup(pinput, GPIO.IN, GPIO.PUD_UP)
#GPIO.setup(pinput,GPIO.IN,GPIO.PUD_DOWN)
#GPIO.add_event_detect(pinput,GPIO.RISING,callback=callback_edgedown,bouncetime=1)
Example #25
0
    def run(self):
        log('info', "Starting " + self.name)
        global TempoPinLOW, TempoPinHIGH, exit, swtch, GPIO, SetAllLOW, SetAllHIGH, Status_pins, sendCPT, timeCPT, s, NextRefresh, CounterPinValue, SetAllSWITCH, SetAllPulseLOW, SetAllPulseHIGH, PinNextSend, ProbeDelay, thread_1, thread_2, thread_tries2, bmp180, bmp280, bme280, bme680, bmp280b, bme280b, bme680b, sendPINMODE, CptNextReArm, ReArmDelay

        while exit == 0:
            thread_2 = 1
            pinStr = ''
            for i in range(1, 41):
                if TempoPinHIGH[i] != 0 and TempoPinHIGH[i] < int(
                        time.time() * 10):
                    TempoPinHIGH[i] = 0
                    swtch[i] = 0
                    GPIO.output(pin2gpio[i - 1], 0)
                    pinStr += '&' + str(i) + '=0'
                elif TempoPinLOW[i] != 0 and TempoPinLOW[i] < int(
                        time.time() * 10):
                    TempoPinLOW[i] = 0
                    swtch[i] = 1
                    GPIO.output(pin2gpio[i - 1], 1)
                    pinStr += '&' + str(i) + '=1'
            if pinStr != '':
                SimpleSend(pinStr)

            thread_tries2 = 0
            if SetAllLOW == 1:
                pinStr = '&REP=SOK'
                for i in range(0, 40):
                    j = i + 1
                    if Status_pins[i] == 'o' or Status_pins[
                            i] == 's' or Status_pins[i] == 'l' or Status_pins[
                                i] == 'h' or Status_pins[
                                    i] == 'u' or Status_pins[
                                        i] == 'v' or Status_pins[i] == 'w':
                        swtch[j] = 0
                        GPIO.output(pin2gpio[i], 0)
                        pinStr += '&' + str(j) + '=0'
                SetAllLOW = 0
                SimpleSend(pinStr)

            if SetAllHIGH == 1:
                pinStr = '&REP=SOK'
                for i in range(0, 40):
                    j = i + 1
                    if Status_pins[i] == 'o' or Status_pins[
                            i] == 's' or Status_pins[i] == 'l' or Status_pins[
                                i] == 'h' or Status_pins[
                                    i] == 'u' or Status_pins[
                                        i] == 'v' or Status_pins[i] == 'w':
                        swtch[j] = 1
                        GPIO.output(pin2gpio[i], 1)
                        pinStr += '&' + str(j) + '=1'
                SetAllHIGH = 0
                SimpleSend(pinStr)

            if SetAllSWITCH == 1:
                pinStr = '&REP=SOK'
                for i in range(0, 40):
                    j = i + 1
                    if Status_pins[i] == 'o' or Status_pins[
                            i] == 's' or Status_pins[i] == 'l' or Status_pins[
                                i] == 'h' or Status_pins[
                                    i] == 'u' or Status_pins[
                                        i] == 'v' or Status_pins[i] == 'w':
                        if swtch[j] == 0:
                            swtch[j] = 1
                            GPIO.output(pin2gpio[i], 1)
                            pinStr += '&' + str(j) + '=1'
                        else:
                            swtch[j] = 0
                            GPIO.output(pin2gpio[i], 0)
                            pinStr += '&' + str(j) + '=0'
                SetAllSWITCH = 0
                SimpleSend(pinStr)

            # On envoi le nombre d'impulsions connu si il n'y en a pas eu dans les 10s depuis le dernier envoi
            pinStr = ''
            for i in range(0, 40):
                j = i + 1
                if (Status_pins[i] == 'c' or Status_pins[i] == 'G'
                    ) and PinNextSend[j] < time.time() and PinNextSend[j] != 0:
                    pinStr += '&' + str(j) + '=' + str(CounterPinValue[j])
                    PinNextSend[j] = 0
            if pinStr != '':
                SimpleSend(pinStr)

            # Essai : ReArm compteur si bloqué (toutes les heures)
            if CptNextReArm < time.time():
                CptNextReArm = time.time() + ReArmDelay
                for i in range(0, 40):
                    if Status_pins[i] == 'c' or Status_pins[i] == 'G':
                        GPIO.remove_event_detect(pin2gpio[i])
                time.sleep(7)
                for i in range(0, 40):
                    j = pin2gpio[i]
                    if Status_pins[i] == 'c':
                        k = i % 4
                        GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_UP)
                        if k == 1:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts1)
                        elif k == 2:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts2)
                        elif k == 3:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts3)
                        else:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts0)
                    elif Status_pins[i] == 'G':
                        k = i % 4
                        GPIO.setup(j, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
                        if k == 1:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts1)
                        elif k == 2:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts2)
                        elif k == 3:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts3)
                        else:
                            GPIO.add_event_detect(j,
                                                  GPIO.BOTH,
                                                  callback=toggle_cpts0)

            # Renvois des sondes toutes les 300s par defaut
            if NextRefresh < time.time():
                NextRefresh = time.time() + (60 * ProbeDelay
                                             )  #300s environ par defaut
                pinStr = ''
                pinDHT = 0
                for i in range(0, 40):
                    j = i + 1
                    if Status_pins[i] == 'd':  #DHT 11
                        if pinDHT:
                            time.sleep(
                                2
                            )  # si une sonde vient d'etre lue on attends un peu pour la suivante.
                        humidity, temperature = Adafruit_DHT.read(
                            Adafruit_DHT.DHT11, pin2gpio[i])
                        if humidity is not None and temperature is not None:
                            temperature = round(float(temperature), 2)
                            humidity = round(float(humidity), 2)
                            pinStr += '&' + str(j) + '=' + str(
                                temperature * 100)
                            pinStr += '&' + str(1000 + j) + '=' + str(
                                humidity * 100)
                            pinDHT = 1
                    elif Status_pins[i] == 'f':  #DHT 22
                        if pinDHT:
                            time.sleep(2)
                        humidity, temperature = Adafruit_DHT.read(
                            Adafruit_DHT.DHT22, pin2gpio[i])
                        if humidity is not None and temperature is not None:
                            temperature = round(float(temperature), 2)
                            humidity = round(float(humidity), 2)
                            pinStr += '&' + str(j) + '=' + str(
                                temperature * 100)
                            pinStr += '&' + str(1000 + j) + '=' + str(
                                humidity * 100)
                            pinDHT = 1
                    elif Status_pins[i] == 'b':  # ds18b20
                        sensors[i] = DS.scan(pin2gpio[i])
                        DS.pinsStartConversion([pin2gpio[i]])
                        time.sleep(1)
                        try:
                            k = sensors[i][0]
                            pinStr += '&' + str(j) + '=' + str(
                                DS.read(False, pin2gpio[i], k) * 100)
                            pinStr2 = ''
                            for k in sensors[i]:
                                pinStr2 += '"' + str(k) + '":"' + str(
                                    DS.read(False, pin2gpio[i], k) *
                                    100) + '",'
                            if pinStr2 != '':
                                pinStr += '&DS18list_' + str(
                                    j) + '={' + pinStr2[:-1] + '}'
                        except:
                            pass
                    elif Status_pins[i] == 'r':  # BMP085/180
                        if pinDHT:
                            time.sleep(2)
                        temperature = bmp180.read_temperature()
                        pressure = bmp180.read_pressure()
                        pinStr += '&' + str(j) + '=' + str(temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(pressure)
                        pinDHT = 1
                    elif Status_pins[i] == 'A':  # BME280
                        if pinDHT:
                            time.sleep(2)
                        pinStr += '&' + str(j) + '=' + str(bme280.temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(
                            bme280.pressure)
                        pinStr += '&' + str(2000 + j) + '=' + str(
                            bme280.humidity)
                        pinDHT = 1
                    elif Status_pins[i] == 'D':  # BME280
                        if pinDHT:
                            time.sleep(2)
                        pinStr += '&' + str(j) + '=' + str(bme280b.temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(
                            bme280b.pressure)
                        pinStr += '&' + str(2000 + j) + '=' + str(
                            bme280b.humidity)
                        pinDHT = 1
                    elif Status_pins[i] == 'B':  # BME680
                        if pinDHT:
                            time.sleep(2)
                        pinStr += '&' + str(j) + '=' + str(bme680.temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(
                            bme680.pressure)
                        pinStr += '&' + str(2000 + j) + '=' + str(
                            bme680.humidity)
                        pinStr += '&' + str(3000 + j) + '=' + str(bme680.gas)
                        pinDHT = 1
                    elif Status_pins[i] == 'E':  # BME680
                        if pinDHT:
                            time.sleep(2)
                        pinStr += '&' + str(j) + '=' + str(bme680b.temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(
                            bme680b.pressure)
                        pinStr += '&' + str(2000 + j) + '=' + str(
                            bme680b.humidity)
                        pinStr += '&' + str(3000 + j) + '=' + str(bme680b.gas)
                        pinDHT = 1
                    elif Status_pins[i] == 'C':  # BMP280
                        if pinDHT:
                            time.sleep(2)
                        pinStr += '&' + str(j) + '=' + str(bmp280.temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(
                            bmp280.pressure)
                        pinDHT = 1
                    elif Status_pins[i] == 'F':  # BMP280
                        if pinDHT:
                            time.sleep(2)
                        pinStr += '&' + str(j) + '=' + str(bmp280b.temperature)
                        pinStr += '&' + str(1000 + j) + '=' + str(
                            bmp280b.pressure)
                        pinDHT = 1
                pinDHT = 0
                if pinStr != '':
                    SimpleSend(pinStr)

            #on reclame la valeur des compteurs
            if sendCPT == 0 and timeCPT < time.time():
                if JeedomIP != '' and eqLogic != '':
                    sendCPT = 1
                    if sendPINMODE == 0:
                        pinStr = '&PINMODE=1'
                        sendPINMODE = 1
                    else:
                        pinStr = ''
                    for i in range(1, 41):
                        if Status_pins[i - 1] == 'c' or Status_pins[i -
                                                                    1] == 'G':
                            pinStr += '&CPT_' + str(i) + '=' + str(i)
                    if pinStr != '':
                        SimpleSend(pinStr)
            time.sleep(0.1)
        s.close()
        try:
            GPIO.cleanup()
        except:
            pass
        sys.exit()
Example #26
0
 def startConversion(self):
     #start sensor conversion
     ds.pinsStartConversion([DS_PIN])
     self.root.after(sensordelay[self.resolution],self.updateSensors)
Example #27
0

def format_measurement(num):
    if num is None:
        return None
    else:
        return round(float(num), 2)


database.check_failed_data_handling()

try:

    # Measuring temperature and humidity
    humidity, temperature = DHT22.take_measurements()
    windchill_temperature = DS18B20.take_measurements()

    # Measuring luminosity
    full_spectrum, infrared, visible = TSL2561.take_measurements()

    # Measuring air pressure and altitude
    pressure, altitude = BMP180.take_measurements()

    database.store_in_database(format_measurement(temperature),
                               format_measurement(windchill_temperature),
                               format_measurement(humidity),
                               format_measurement(full_spectrum),
                               format_measurement(infrared),
                               format_measurement(visible),
                               format_measurement(pressure),
                               format_measurement(altitude))
Example #28
0
#!/usr/bin/env python3
import DS18B20 as ds
import datetime as dt
import time

sensorPin = 20

print("Scan sensors on pin {} ".format(sensorPin), end="")
time1 = dt.datetime.now()
sensorsId = ds.scan(sensorPin)
delta_t = dt.datetime.now() - time1
print(" ... {} second.  Found {} sensors.".format(delta_t.total_seconds(),
                                                  len(sensorsId)))

print("Send start of conversion commands for all sensors on pin {}.".format(
    sensorPin),
      end="")
time2 = dt.datetime.now()
ds.pinsStartConversion([sensorPin])
delta_t = dt.datetime.now() - time2
print(" ... {} second".format(delta_t.total_seconds()))

print("wait 0.75 seconds")
time.sleep(1.0)

print("Read all sensors", end="")
time2 = dt.datetime.now()
temperature = []
for s in sensorsId:
    value = ds.read(False, sensorPin, s)
    temperature.append(value)
Example #29
0
def main(args):
    #     temp_high = 42.0
    #     temp_low = 38.0
    status = 'unknown'

    GPIO.setmode(GPIO.BCM)
    GPIO.setup(23, GPIO.OUT)

    ##-------------------------------------------------------------------------
    ## Create logger object
    ##-------------------------------------------------------------------------
    logger = logging.getLogger('MyLogger')
    logger.setLevel(logging.DEBUG)
    ## Set up console output
    LogConsoleHandler = logging.StreamHandler()
    if args.verbose:
        LogConsoleHandler.setLevel(logging.DEBUG)
    else:
        LogConsoleHandler.setLevel(logging.INFO)
    LogFormat = logging.Formatter('%(asctime)23s %(levelname)8s: %(message)s')
    LogConsoleHandler.setFormatter(LogFormat)
    logger.addHandler(LogConsoleHandler)
    ## Set up file output
    now = datetime.datetime.now()
    DateString = '{}'.format(now.strftime('%Y%m%d'))
    TimeString = '{} HST'.format(now.strftime('%H:%M:%S'))
    LogFileName = os.path.join('/', 'var', 'log', 'Kegerator',
                               'Log_{}.txt'.format(DateString))
    LogFileHandler = logging.FileHandler(LogFileName)
    LogFileHandler.setLevel(logging.DEBUG)
    LogFileHandler.setFormatter(LogFormat)
    logger.addHandler(LogFileHandler)

    ##-------------------------------------------------------------------------
    ## Get Temperature and Humidity Values
    ##-------------------------------------------------------------------------
    logger.info('#### Reading Temperature and Humidity Sensors ####')
    temperatures_F = []

    try:
        logger.debug('Reading DHT22')
        DHT = DHT22.DHT22(pin=18)
        DHT.read()
        logger.debug('  Temperature = {:.3f} F, Humidity = {:.1f} %'.format(
            DHT.temperature_F, DHT.humidity))
        temperatures_F.append(DHT.temperature_F)
        RH = DHT.humidity
        AH = humidity.relative_to_absolute_humidity(DHT.temperature_C,
                                                    DHT.humidity)
        logger.debug('  Absolute Humidity = {:.2f} g/m^3'.format(AH))
    except:
        RH = float('nan')
        AH = float('nan')

    logger.debug('Reading DS18B20')
    sensor = DS18B20.DS18B20()
    sensor.read()
    for temp in sensor.temperatures_C:
        logger.debug('  Temperature = {:.3f} F'.format(temp * 9. / 5. + 32.))
        temperatures_F.append(temp * 9. / 5. + 32.)

    ##-------------------------------------------------------------------------
    ## Record Values to Table
    ##-------------------------------------------------------------------------
    datafile = os.path.join('/', 'var', 'log', 'Kegerator',
                            '{}.txt'.format(DateString))
    logger.debug(
        "Preparing astropy table object for data file {}".format(datafile))
    if not os.path.exists(datafile):
        logger.info("Making new astropy table object")
        SummaryTable = table.Table(names=('date', 'time', 'AmbTemp', 'KegTemp', 'KegTemp1', 'KegTemp2', 'KegTemp3', 'RH', 'AH', 'status'), \
                                   dtype=('S10',  'S12',  'f4',      'f4',      'f4',       'f4',       'f4',       'f4', 'f4', 'S8') )
    else:
        logger.debug(
            "Reading astropy table object from file: {0}".format(datafile))
        try:
            SummaryTable = ascii.read(
                datafile,
                guess=False,
                header_start=0,
                data_start=1,
                Reader=ascii.basic.Basic,
                converters={
                    'date': [ascii.convert_numpy('S10')],
                    'time': [ascii.convert_numpy('S12')],
                    'AmbTemp': [ascii.convert_numpy('f4')],
                    'KegTemp': [ascii.convert_numpy('f4')],
                    'KegTemp1': [ascii.convert_numpy('f4')],
                    'KegTemp2': [ascii.convert_numpy('f4')],
                    'KegTemp3': [ascii.convert_numpy('f4')],
                    'hum': [ascii.convert_numpy('f4')],
                    'AH': [ascii.convert_numpy('f4')],
                    'status': [ascii.convert_numpy('S11')],
                })
        except:
            logger.critical("Failed to read data file: {0} {1} {2}".format(
                sys.exc_info()[0],
                sys.exc_info()[1],
                sys.exc_info()[2]))

    ##-------------------------------------------------------------------------
    ## Turn Kegerator Relay On or Off Based on Temperature
    ##-------------------------------------------------------------------------
    temperatures_F.sort()
    ambient_temperature = temperatures_F.pop()
    assert ambient_temperature > max(temperatures_F)
    logger.info('Ambient Temperature = {:.1f}'.format(ambient_temperature))
    for temp in temperatures_F:
        logger.info('Kegerator Temperatures = {:.1f} F'.format(temp))
    temperature = np.median(temperatures_F)
    logger.info('Median Temperature = {:.1f} F'.format(temperature))
    if temperature > temp_high:
        status = 'On'
        logger.info(
            'Temperature {:.1f} is greater than {:.1f}.  Turning freezer {}.'.
            format(temperature, temp_high, status))
        GPIO.output(23, True)
    elif temperature < temp_low:
        status = 'Off'
        logger.info(
            'Temperature {:.1f} is less than {:.1f}.  Turning freezer {}.'.
            format(temperature, temp_low, status))
        GPIO.output(23, False)
    else:
        if len(SummaryTable) > 0:
            status = SummaryTable['status'][-1]
        else:
            status = 'unknown'
        logger.info(
            'Temperature if {:.1f}.  Taking no action.  Status is {}'.format(
                temperature, status))

    ##-------------------------------------------------------------------------
    ## Add row to data table
    ##-------------------------------------------------------------------------
    logger.debug("Writing new row to data table.")
    while len(temperatures_F) < 4:
        temperatures_F.append(float('nan'))
    SummaryTable.add_row((DateString, TimeString, ambient_temperature, temperature, \
                          temperatures_F[0], temperatures_F[1], temperatures_F[2], \
                          RH, AH, status))
    ## Write Table to File
    logger.debug("  Writing new data file.")
    ascii.write(SummaryTable, datafile, Writer=ascii.basic.Basic)

    ##-------------------------------------------------------------------------
    ## Log to Carriots
    ##-------------------------------------------------------------------------
    logger.info('Sending Data to Carriots')
    logger.debug('  Creating Device object')
    Device = Carriots.Client(device_id="kegerator@joshwalawender")
    logger.debug('  Reading api key')
    Device.read_api_key_from_file(
        file=os.path.join(os.path.expanduser('~joshw'), '.carriots_api'))
    data_dict = {'Temperature': temperature, \
                 'Status': status
                 }
    logger.debug('  Data: {}'.format(data_dict))
    Device.upload(data_dict)

    logger.info('Done')
Example #30
0
    while (1):
        if (Monitoring.ConnectDB(DB_config, debug)):
            #uruchomienie LM393
            GPIO.output(GPIO_LM393, ENABLE)
            sensors = Monitoring.GetSensors(debug)
            if (sensors):
                for sensor in sensors:
                    if (debug):
                        print "%s [DEBUG]Obsługa czyjnika %s" % (
                            datetime.now(), sensor['name'])
                    if sensor['model'] == "PFC8591":
                        device = PFC8591.PFC8591(debug)
                    elif sensor['model'] == "BMP085":
                        device = BMP085.BMP085(debug)
                    elif sensor['model'] == "DS18B20":
                        device = DS18B20.DS18B20(debug)
                    elif sensor['model'] == "GPIOSTATUS":
                        device = GPIOSTATUS.GPIOSTATUS(debug)
                    elif sensor['model'] == "CPUTEMP":
                        device = CPUTEMP.CPUTEMP(debug)
                    else:
                        device = 0

                    if (device):
                        if (device.SetOptions(sensor['options'])):
                            value = device.ReadValue()
                            if (value is not False):
                                if (Monitoring.SaveValueIsDifferent(
                                        sensor['id'], value, sensor['delta'],
                                        debug) is False):
                                    print "%s [ERROR]Błąd zapisu wartości do bazy" % datetime.now(
    year = now.year
    """
    # 1ヶ月のデータログ
    if month == next_month:
        print "LOG DATA SAVE during Month("+str(year)+"_"+str(month)+"_date_log.csv)"
        dld.to_csv("./"+str(year)+"_"+str(month)+"_date_log.csv", index=False)
        gyo_d = 0
        dld = initialize_dld()
        next_month += 1
        if next_month == 13:
            next_month = 1
        """
    # 1分毎のデータログ
    if sec == 10:
        # 水温の取得
        wtemp = DS18B20.main()
        # 室温、湿度、気圧の取得
        temp, humid, press = bme.Bme280(0x76, 1).get_data()
        # 臭気の取得
        gas = gas_detect(PIN_BASE, SPI_CH)
        if 60 > gas:
            gas_state = "良好"
        elif 150 > gas >= 60:
            gas_state = "そろそろ水換え"
        else:
            gas_state = "要水換え"

        # 基準値
        GOOD = 60
        BAD = 150
        # 良好
Example #32
0
# Import Libraries
import time
import DHT11
import DS18B20
import led

while True:
    try:
        led.on()
        print 'DS18B20:', DS18B20.read_temp(), '*C'
        print 'DHT11: {0}*C, {1}%'.format(DHT11.read_temp(),
                                          DHT11.read_humidity())
        led.off()
        time.sleep(2)
    except KeyboardInterrupt:
        print '\nStoped by user'
        break
	print  bcolors.HEADER + "RPI Weather Station v1.5" + bcolors.ENDC
	print "Database version : %s" % ver
	print sys_date

	GPIO.output(26,True) #Turn LED ON, while reading DHT2 sensors
	
	# ------------------------------ DHT22 read ------------------------
	print bcolors.OKBLUE + "DHT22 data:" + bcolors.ENDC
	temperature_1,humidity_1 = read_dht22(13)
	temperature_2,humidity_2 = None, None # currently DHT22 conneter to 19 pin is disconneted
	
	# ------------------------------ DS18B20 read ------------------------
	print bcolors.OKBLUE + "DS18B20 data:" + bcolors.ENDC
	try:
		oneWire = DS18B20.read_temp()
		if (oneWire != None):
			temperature_3 = round(float(DS18B20.read_temp()),1)
			print "DS18B20.read_temp()= %s" %(temperature_3)
		else: print "No data from DS18B20 :("
	except (RuntimeError, TypeError, NameError):
			temperature_3 = None
			print "No data from DS18B20 :("
	
	# -------------------------- BMP085 read -------------------------------
	print bcolors.OKBLUE + "BMP085 data:" + bcolors.ENDC
	temperature_4 = bmp.readTemperature()
	pressure = bmp.readPressure()

	print "Temperature: %.2f C" % temperature_4
	print "Pressure:    %.2f hPa" % (pressure / 100.0)
Example #34
0
#import os
#import glob
#import RPi.GPIO as io
import DS18B20

DS18B20.init()
thermometers = DS18B20.discover()
print thermometers

print DS18B20.read_temp_c(thermometers[0])