Exemple #1
0
  def on_message(self, message):
    global settemp

    # message is the PIN number you want to toggle
    pin = int(message)

    if pin<8:
      # read output state
      r_output = '{0:08b}'.format(pifacedigital.output_port.value)
      # toggle output
      pin_state = int(r_output[7-pin]);
      pfio.digital_write(pin, not pin_state)
      # FIXME! I need to check with the loop so I don't send twice ?
      # I think i fixed it when I separated no_timeout_loop? -Derek
      self.no_timeout_loop()
      

    if pin==10:
      settemp = settemp - 1 #Hard coded message to lower set temp
      self.no_timeout_loop()
      

    if pin==11:
      settemp = settemp + 1 #Hard coded message to raise set temp
      self.no_timeout_loop()
Exemple #2
0
def set_pin_value(pin_index, pin_value, board_index):
    L.l.info('Set piface pin {} value {} board {}'.format(pin_index, pin_value, board_index))
    pfio.digital_write(pin_num=pin_index, value=pin_value, hardware_addr=board_index)
    act_value = get_out_pin_value(pin_index=pin_index, board_index=board_index)
    if pin_value != act_value:
        L.l.warning("Piface set pin {} failed, actual value={}".format(pin_index, act_value))
    return act_value
Exemple #3
0
  def no_timeout_loop(self):
    global temperature_in_fahrenheit
    #need to do thermostat logic here: (so that it's responsive to a click)
    if temperature_in_fahrenheit<(settemp-.2):
      pfio.digital_write(2, 1)
       
    if temperature_in_fahrenheit>(settemp+.2):
      pfio.digital_write(2, 0)

    # read PiFace input/output state
    r_input = '{0:08b}'.format(pifacedigital.input_port.value)
    r_output = '{0:08b}'.format(pifacedigital.output_port.value)
    # obj -> javascript
    data = {"in": [], "out": [], "temp": []}

    for i in range(8):
      data['in'].append(r_input[7-i])
      data['out'].append(r_output[7-i])

    data['temp'].append(temperature_in_fahrenheit)
    data['temp'].append(settemp)

    # only send message if input/output changed
    if data != self.last_data:
      for client in self.clients:
        client.write_message(json.dumps(data))
    self.last_data = data
def on_message(mosq, obj, msg):
    """
    Handle incoming messages
    """
    if msg.topic == MONITOR_REFRESH:
        logging.debug("Refreshing the state of all monitored pins...")
        refresh()
        return

    topicparts = msg.topic.split("/")
    pin = int(topicparts[len(topicparts) - 1])
    value = int(msg.payload)
    logging.debug("Incoming message for pin %d -> %d" % (pin, value))

    if PFIO_MODULE:
        if value == 1:
            PFIO.digital_write(pin, 1)
        else:
            PFIO.digital_write(pin, 0)

    if GPIO_MODULE:
        if pin not in GPIO_OUTPUT_PINS:
            GPIO.setup(pin, GPIO.OUT, initial=GPIO.HIGH)
            GPIO_OUTPUT_PINS.append(pin)

        if value == 1:
            GPIO.output(pin, GPIO.LOW)
        else:
            GPIO.output(pin, GPIO.HIGH)
 def test_big_digital_read_write(self):
     pin = 0
     for i in range(1000):
         for test_value in (1, 0):
             pifacedigitalio.digital_write(pin, test_value)
             v = pifacedigitalio.digital_read(7 - pin)
             self.assertEqual(test_value, v)
Exemple #6
0
    def output(self, pin: str, value: Any) -> Literal[True]:
        super().output(pin, value)

        value = self._normalize(value)
        pifacedigitalio.digital_write(int(pin), value)
        self._outputs[pin] = value
        return True
Exemple #7
0
	def do_GET(self):
		try:
			#send HTTP 200 response code to client
			self.send_response(200)
			self.send_header('Content-type', 'text/html')
			self.end_headers()        	  
			#['', 'request', '0', 'off', '7', '', '']
			#parse data string with PiFace Board/Pin values
			datastring = str(self.path).split("/")
			if datastring[1] == "request":
				PiFace_Board  = int(datastring[2])
				status = datastring[3]
				status = string.lower(status)
				PiFace_Pin = int(datastring[4])
				#TODO Use RabbitMQ to send command to piface controller
				if PiFace_Board != "":
					if status == "on":
						pifacedigitalio.digital_write(PiFace_Pin, 1, PiFace_Board)
					elif status == "off":
						pifacedigitalio.digital_write(PiFace_Pin, 0, PiFace_Board)
			elif datastring[1] == "quit":
				status = "quit"
		
		except IOError:
			self.send_error(404,'File Not Found: ' + self.path)
def on_message(mosq, obj, msg):
    """
    Handle incoming messages
    """
    if msg.topic == MONITOR_REFRESH:
        logging.debug("Refreshing the state of all monitored pins...")
        refresh()
        return
        
    topicparts = msg.topic.split("/")
    pin = int(topicparts[len(topicparts) - 1])
    value = int(msg.payload)
    logging.debug("Incoming message for pin %d -> %d" % (pin, value))

    if PFIO_MODULE:
        if value == 1:
            PFIO.digital_write(pin, 1)
        else:
            PFIO.digital_write(pin, 0)

    if GPIO_MODULE:
        if pin not in GPIO_OUTPUT_PINS:
            GPIO.setup(pin, GPIO.OUT, initial=GPIO.HIGH)
            GPIO_OUTPUT_PINS.append(pin)

        if value == 1:
            GPIO.output(pin, GPIO.LOW)
        else:
            GPIO.output(pin, GPIO.HIGH)
Exemple #9
0
def netWrite(curpath, curfn, msg):
	if os.path.isdir(curpath): # has slash on end, ok? "/nas/sdrive/dpi"):
		pathAndFilename = curpath + curfn
		try:
			f2 = open(pathAndFilename, "w")
		except IOError:
			msg = "Could not open net file: " + pathAndFilename
			print (msg)
			logWrite(msg)
		else:
			msg = msg + "\n"
			try:
				f2.write(msg)
				f2.close()
			except IOError as e:
				print ("Error writing to net file: I/O error({0}): {1}".format(e.errno, e.strerror))
				logWrite("Error writing to net file: I/O error({0}): {1}".format(e.errno, e.strerror))

		p.digital_write(LED_WARN,0)
		#t#print ("LED_WARN off")	#t#

	else:
		print ("Cannot write to net log, path", curpath, "not available.")
		logWrite("Cannot write to net log, path" + " not available.")
		p.digital_write(LED_WARN,1)
Exemple #10
0
    def receive(self, sequence, command, *av):
        if command == "DigitalWrite":
            pin, value = av[0], av[1]
            pifacedigitalio.digital_write(pin, value and 1 or 0, self.board)
        elif command == "DigitalRead":
            pin = av[0]
            return pifacedigitalio.digital_read(pin, self.board)
        elif command == "DigitalListen":
            pin = av[0]
            self.listensd.setdefault(pin, set()).add(sequence)

            if self.listener:
                self.listener.deactivate()

            self.listener = pifacedigitalio.InputEventListener(chip=self.pfd)

            for pin in self.listensd.keys():
                self.listener.register(pin, pifacedigitalio.IODIR_ON, self._event)
                self.listener.register(pin, pifacedigitalio.IODIR_OFF, self._event)

            self.listener.activate()
            return ""
        else:
            raise KeyError("unknown command: %s" % command)
            
        print ("comm_piface.receive: seq=%s comm=%s" % ( sequence, command ), file=sys.stderr)
Exemple #11
0
 def Setup(self):
     """
     Description: Initialize PiFaceDigitalIO. Can be called without 
         creating an object. Should be called before attempts to 
         output or receive data. Should only be called once
     """
     pfio.init()
     pfio.digital_write(self.channel_out, 1)
 def test_digital_write(self):
     global pifacedigitals
     for pfd in pifacedigitals:
         for pin in range(8):
             pifacedigitalio.digital_write(pin, 1, pfd.hardware_addr)
             self.assertEqual(pfd.output_port.bits[pin].value, 1)
             pifacedigitalio.digital_write(pin, 0, pfd.hardware_addr)
             self.assertEqual(pfd.output_port.bits[pin].value, 0)
Exemple #13
0
	def laseron(self):
		if cherrypy.session['laser'] == 'off':
			pfio.digital_write(0,1)
			cherrypy.session['laser'] = 'on'
			return "Laser on!"
		else:
			pfio.digital_write(0,0)
			cherrypy.session['laser']  = 'off'
			return "Laser off!"
 def turnall_on(self):
     ledspacing = "....."
     status = ""
     for led in range (0,8,1):
         for board in range (0,4,1):
             pfio.digital_write(led,CLEDON,board)
             status = status + ledspacing + "LED " +str(led+1) + " ON" + ledspacing
         status = status + "\n"
     self.results_txt.delete(0.0, END)
     self.results_txt.insert(0.0, status)
 def on_message(self, message):
   # message is the PIN number you want to toggle
   pin = int(message)
   # read output state
   r_output = '{0:08b}'.format(pifacedigital.output_port.value)
   # toggle output
   pin_state = int(r_output[7-pin]);
   pfio.digital_write(pin, not pin_state)
   # FIXME! I need to check with the loop so I don't send twice ?
   self.timeout_loop()
Exemple #16
0
 def on_message(self, message):
     # message is the PIN number you want to toggle
     pin = int(message)
     # read output state
     r_output = '{0:08b}'.format(pifacedigital.output_port.value)
     # toggle output
     pin_state = int(r_output[7 - pin])
     pfio.digital_write(pin, not pin_state)
     # FIXME! I need to check with the loop so I don't send twice ?
     self.timeout_loop()
Exemple #17
0
 def turnall_off(self):
     ledOFF = ".................."
     status = ""
     for led in range(0, 8, 1):
         for board in range(0, 4, 1):
             pfio.digital_write(led, CLEDOFF, board)
             status = status + ledOFF
         status = status + "\n"
     self.results_txt.delete(0.0, END)
     self.results_txt.insert(0.0, status)
 def turnall_off(self):
     ledOFF=".................."
     status = ""
     for led in range (0,8,1):
         for board in range (0,4,1):
             pfio.digital_write(led,CLEDOFF,board)
             status = status + ledOFF
         status = status + "\n"
     self.results_txt.delete(0.0, END)
     self.results_txt.insert(0.0, status)
Exemple #19
0
 def turnall_on(self):
     ledspacing = "....."
     status = ""
     for led in range(0, 8, 1):
         for board in range(0, 4, 1):
             pfio.digital_write(led, CLEDON, board)
             status = status + ledspacing + "LED " + str(
                 led + 1) + " ON" + ledspacing
         status = status + "\n"
     self.results_txt.delete(0.0, END)
     self.results_txt.insert(0.0, status)
Exemple #20
0
    def set_output(self, pin, value, log_output = True):
        pin = int(pin)
        value = str(value).lower() in ['1', 'high', 'on']
        log_output = str(log_output).lower() in ['true', 'log', '1', 'on']

        if not pin in self.__OutputPins: return False
        if log_output: logger.debug("out(pin = %s, value = %s, log_output = %s)", pin, value, log_output)

        p.digital_write(pin, value)
        self.__OutputStatus[pin] = value
        return True
Exemple #21
0
def thermostat_control(furnace_value):
	global FuranceRunning, Furnace_Pin, Furnace_Board, Furnace_ID
	OnOff = {0:'off',1:'on'}
	pifacedigitalio.digital_write(Furnace_Pin, furnace_value, Furnace_Board)
	if DEBUG_LOG:
		logging("Action: Thermostat output on pin %s is set to %s." % (Furnace_Pin, OnOff[int(furnace_value)]))
	query = ("UPDATE `homepi`.`piface` SET `status`=%d WHERE `id`=%d;" % (furnace_value, Furnace_ID))
	DBQuery(2,query)
	FuranceRunning = bool(furnace_value)
	logging("Action: FuranceRunning has been set to %s." % (FuranceRunning))
	return
Exemple #22
0
def on_message_write_viessmannonoff(mosq, obj, msg):
    resptopic = "status/viessmann-onoff"
    try:
        if msg.payload.decode() == "disabled":
            p.digital_write(1, 1)
            resp = "disabled"
            client.publish(resptopic, resp, retain=True)
        else:
            p.digital_write(1, 0)
            resp = "enabled"
            client.publish(resptopic, resp, retain=True)
    except:
        print("GPIO error: could not set viessmann-onoff relay")
Exemple #23
0
    def SendMorse(self, msg):
        """
        Description: Transmit Morse message over channel_out
        msg (string): Morse code message to be transmitted. Should on contain:
            ' ', '•', or '-', An EOT morse char ('• • • - • -') is appended 
            before transmission. 
        """

        # add space to beginning of message to ensure data goes through
        # add  end transmission char to message
        msg += '• • • - • -'
        for c in msg:
            if c == '•':  # On for 1 count
                pfio.digital_write(self.channel_out, 0)
                time.sleep(1 * self.count)
            elif c == '-':  # On for 3 count
                pfio.digital_write(self.channel_out, 0)
                time.sleep(3 * self.count)
            elif c == ' ':  # 1 count for space
                time.sleep(1 * self.count)
            else:
                pass
            # set low at end of each loop
            pfio.digital_write(self.channel_out, 1)

        # set low before exit
        pfio.digital_write(self.channel_out, 1)
Exemple #24
0
def catepillarWalk(times, interval):
    i = 0
    # repeat times times ...
    while i < times:
        # turn on LED 0 to 7 one at a time with interval intervals ...
        for led in leds:
            pfio.digital_write(led, 1)
            sleep(interval)

        # turn off LED 0 to 7 one at a time with interval intervals ...
        for led in leds:
            pfio.digital_write(led, 0)
            sleep(interval)

        i += 1
Exemple #25
0
def catepillarWalk(times, interval):
   i = 0
   # repeat times times ...
   while i < times:
      # turn on LED 0 to 7 one at a time with interval intervals ...
      for led in leds:
         pfio.digital_write(led, 1)
         sleep(interval)
      
      # turn off LED 0 to 7 one at a time with interval intervals ...
      for led in leds:
         pfio.digital_write(led, 0)
         sleep(interval)
      
      i += 1
Exemple #26
0
    def set_output(self, pin, value, log_output = True):
        parsed_pin = doorpi.DoorPi().parse_string("!"+str(pin)+"!")
        if parsed_pin != "!"+str(pin)+"!":
            pin = parsed_pin

        pin = int(pin)
        value = str(value).lower() in HIGH_LEVEL
        if self._polarity is 1: value = not value
        log_output = str(log_output).lower() in HIGH_LEVEL

        if not pin in self._OutputPins: return False
        if log_output: logger.debug("out(pin = %s, value = %s, log_output = %s)", pin, value, log_output)

        p.digital_write(pin, value)
        self._OutputStatus[pin] = value
        return True
Exemple #27
0
def device_control(PiFace_ID,Pin_Value,AutoOff):
	global LightsOff
	OnOff = {0:'off',1:'on'}
	row = GetDevicebyID(PiFace_ID)
	if (row):
		#PiFace_ID = int(row[0])
		PiFace_Node = row[1]
		PiFace_Board = int(row[2])
		PiFace_Pin = int(row[3])
		PiFace_Status = int(row[4])
		Zone_Number = int(row[5])
		PiFace_Name = str(row[7])
	else:
		logging("Error: Invalid PiFace GetDevicebyID data at device_control.")
		return
	
	if int(PiFace_Status) != int(Pin_Value):
		pifacedigitalio.digital_write(PiFace_Pin, int(Pin_Value), PiFace_Board)
		Zone_Name = GetZoneName(Zone_Number)
		logging("Node: %s set output: %d-%s %s has been set to %s. | Board: %s Pin: %s."  % (PiFace_Node, PiFace_ID, PiFace_Name, Zone_Name, OnOff[int(Pin_Value)], PiFace_Board, PiFace_Pin))
		query = ("UPDATE `homepi`.`piface` SET `status`=%d WHERE `id`=%d ;" % (Pin_Value, PiFace_ID))
		DBQuery(2,query)
		
		#if device is a light then turn off in X mins
		if (int(PiFace_Status) == 0) and AutoOff:
			dt = datetime.timedelta(minutes=LightsOff)
			EventTime = datetime.datetime.now() + dt
			query = ("INSERT INTO `homepi`.`event_action` (`piface_id`, `value`, `datetime`) VALUES (%d, 0, '%s');" % (PiFace_ID, EventTime))
			DBQuery(2,query)
			logging("Action: %s %s will be set to off in %s minutes." % (PiFace_Name, Zone_Name, LightsOff))
		return 
		
	elif bool(PiFace_Status) and AutoOff:
		#Update Auto Off time
		#logging("Update AutoOff PiFace_ID=%d" % PiFace_ID)
		query = ("SELECT * FROM `homepi`.`event_action` WHERE `datetime` > now() AND `piface_id`=%d LIMIT 1;" % PiFace_ID)
		rows = DBQuery(1,query)
		if not (rows):
			return
		for row in rows:
			Mod_ID = int(row[0])
			dt = datetime.timedelta(minutes=LightsOff)
			EventTime = datetime.datetime.now() + dt
			query = ("UPDATE `homepi`.`event_action` SET `datetime`='%s' WHERE `id`=%d;" % (EventTime, Mod_ID))
			DBQuery(2,query)
				
	return
Exemple #28
0
    def run(self):
        global temperature_in_fahrenheit
        """ Method that runs forever """
        while True:
            
            #this is slow need to do it less
            sensor = W1ThermSensor()  
            temperature_in_fahrenheit = sensor.get_temperature(W1ThermSensor.DEGREES_F)
            temperature_in_fahrenheit = round(temperature_in_fahrenheit,1)
            #Thermostat logic
            if temperature_in_fahrenheit<(settemp-.2):
              pfio.digital_write(2, 1) #turn heater on
       
            if temperature_in_fahrenheit>(settemp+.2):
              pfio.digital_write(2, 0) #turn heater off
 
            time.sleep(self.interval) #this is interval time for the background fn
Exemple #29
0
def on_message(client, userdata, msg):
    value = 0

    if ("OFF" in str(msg.payload)):
        value = 0
        valuestr = "OFF"

    if ("ON" in str(msg.payload)):
        value = 1
        valuestr = "ON"

    if (msg.topic == "CMD/POWER1"):
        p.digital_write(0, value)
        print("Assigned value {} to topic CMD/POWER1".format(valuestr))

    if (msg.topic == "CMD/POWER2"):
        p.digital_write(1, value)
        print("Assigned value {} to topic CMD/POWER2".format(valuestr))
Exemple #30
0
    def set_output(self, pin, value, log_output=True):
        parsed_pin = doorpi.DoorPi().parse_string("!" + str(pin) + "!")
        if parsed_pin != "!" + str(pin) + "!":
            pin = parsed_pin

        pin = int(pin)
        value = str(value).lower() in HIGH_LEVEL
        if self._polarity is 1: value = not value
        log_output = str(log_output).lower() in HIGH_LEVEL

        if not pin in self._OutputPins: return False
        if log_output:
            logger.debug("out(pin = %s, value = %s, log_output = %s)", pin,
                         value, log_output)

        p.digital_write(pin, value)
        self._OutputStatus[pin] = value
        return True
Exemple #31
0
 def onOff(self, event):
     start_image = wx.Image('data/off.png')
     start_image.Rescale(50, 50)
     image = wx.BitmapFromImage(start_image)
     self.status.SetBitmap(image)
     self.cocheEstado.SetLabel("Estacionado")
     self.cocheEstadoVuelta.SetLabel("")
     piface.digital_write(0,0)
     piface.digital_write(1,0)
     piface.digital_write(2,0)
     piface.digital_write(3,0)
Exemple #32
0
 def onOff(self, event):
     start_image = wx.Image('data/off.png')
     start_image.Rescale(50, 50)
     image = wx.BitmapFromImage(start_image)
     self.status.SetBitmap(image)
     self.cocheEstado.SetLabel("Estacionado")
     self.cocheEstadoVuelta.SetLabel("")
     piface.digital_write(0, 0)
     piface.digital_write(1, 0)
     piface.digital_write(2, 0)
     piface.digital_write(3, 0)
Exemple #33
0
def setHeatingOnOrOff(onOrOff):
	global heatingChangeTimeUtc, heatingOnOrOff
	# run the change without checking, will take care of mis-matches
	heatingChangeTimeUtc = datetime.datetime.utcnow()

	p.digital_write(LED_HEATING,onOrOff) # 1 = on

	tempstr = "H#"
	# write to log: H#datetime#SW-ON
	tempstr += "%04u-%02u-%02uT" % (heatingChangeTimeUtc.year, heatingChangeTimeUtc.month, heatingChangeTimeUtc.day)
	tempstr += "%02u:%02u:%02uZ#" % (heatingChangeTimeUtc.hour, heatingChangeTimeUtc.minute, heatingChangeTimeUtc.second)
	if onOrOff == 1:
		tempstr += "SW-ON"
	else:
		tempstr += "SW-OFF"
	logWrite(tempstr)
	print (tempstr)
	# update global variables
	heatingOnOrOff = onOrOff
def send(char,pin_number):
	for c in morsetab[char]:
		if c == '.':
			p.digital_write(pin_number, 1)
			sleep(DELAY/3.0)
			p.digital_write(pin_number, 0)
			sleep(DELAY/3.0)
		elif c == '-':
			p.digital_write(pin_number, 1)
			sleep(DELAY)
			p.digital_write(pin_number, 0)
			sleep(DELAY)
	sleep(DELAY/3)
 def quadrant_on_off(self, quadrant, on_off):
     status = ""
     if quadrant == 1:
         startled = 4
         startboard = 0
     elif quadrant == 2 :
         startled = 4
         startboard = 2
     elif quadrant == 3 :
         startled = 0
         startboard = 2
     elif quadrant == 4 :
         startled = 0
         startboard = 0
     else :
         startled = 4
         startboard = 0
     for led in range (startled,startled+4,1):
         for board in range ( startboard, startboard+2, 1):
             pfio.digital_write ( led, on_off, board )
Exemple #36
0
 def quadrant_on_off(self, quadrant, on_off):
     status = ""
     if quadrant == 1:
         startled = 4
         startboard = 0
     elif quadrant == 2:
         startled = 4
         startboard = 2
     elif quadrant == 3:
         startled = 0
         startboard = 2
     elif quadrant == 4:
         startled = 0
         startboard = 0
     else:
         startled = 4
         startboard = 0
     for led in range(startled, startled + 4, 1):
         for board in range(startboard, startboard + 2, 1):
             pfio.digital_write(led, on_off, board)
Exemple #37
0
    def switchON(self, device):
        app.logger.info("Output ON" + str(device))
        if (app.brewapp_gpio == True):

            switch_name = self.getConfigValue(device, "switch", None)
            if switch_name is None:
                app.logger.warning("SWITCH NOT FOUND IN CONFIG")
                pass

            gpio = self.translateDeviceName(switch_name)

            if self.getConfigValue(device, "inverted", False):
                app.logger.warning("SWITCH ON - Inverted")
                piface.digital_write(gpio, 0)
            else:
                app.logger.warning("SWITCH ON - Not Inverted")
                piface.digital_write(gpio, 1)
            pass
        else:
            app.logger.warning(
                "GPIO TEST MODE ACTIVE. GPIO is not switched on" + str(device))
def pin_set (pin, value):
	if PFIO_MODULE:
		if value == 1:
			PFIO.digital_write(pin, 1)
		else:
			PFIO.digital_write(pin, 0)

	if GPIO_MODULE:
		if pin not in PIGPIO_OUTPUT_PINS:
			GPIO.setup(pin, GPIO.OUT, initial=GPIO.LOW)
			GPIO_OUTPUT_PINS.append(pin)

		if value == 1:
			GPIO.output(pin, GPIO.LOW)
		else:
			GPIO.output(pin, GPIO.HIGH)
			
	if PIGPIO_MODULE:
		if pin not in PIGPIO_OUTPUT_PINS:
			pi.set_mode(pin, pigpio.OUTPUT)
			pi.set_pull_up_down(pin, pigpio.PUD_DOWN)
			PIGPIO_OUTPUT_PINS.append(pin)
		
		pi.write(pin, value)	
Exemple #39
0
def evenOddAlternate(times, interval):
   i = 0
   # repeat times times ...
   while i < times:
      # flash the even numbered LEDs for an interval interval ...
      for led in leds:
         if not (led % 2):
            pfio.digital_write(led, 1)
      sleep(interval)
      for led in leds:
         if not (led % 2):
            pfio.digital_write(led, 0)
      # ... then flash the odd numbered LEDs for an interval interval
      for led in leds:
         if led % 2:
            pfio.digital_write(led, 1)
      sleep(interval)
      for led in leds:
         if led % 2:
            pfio.digital_write(led, 0)
      i += 1
Exemple #40
0
def evenOddAlternate(times, interval):
    i = 0
    # repeat times times ...
    while i < times:
        # flash the even numbered LEDs for an interval interval ...
        for led in leds:
            if not (led % 2):
                pfio.digital_write(led, 1)
        sleep(interval)
        for led in leds:
            if not (led % 2):
                pfio.digital_write(led, 0)
        # ... then flash the odd numbered LEDs for an interval interval
        for led in leds:
            if led % 2:
                pfio.digital_write(led, 1)
        sleep(interval)
        for led in leds:
            if led % 2:
                pfio.digital_write(led, 0)
        i += 1
    def play(self):
        working = True
        p.init()

        while working:
            S1 = p.digital_read(0)
            S2 = p.digital_read(3)

            if S1 == 1:
                # Send -1 to move player to the left
                msg = '-1'
                self.sock.sendto(msg, (self.UDP_IP, self.UDP_PORT))

                # Turn on the LED while the button is pressed
                p.digital_write(0, 1)

                # Wait until the button is let go before reading a new bit
                while p.digital_read(0) == 1:
                    pass

                # Turn off the LED
                p.digital_write(0, 0)

            if S2 == 1:
                # Send 1 to move player to the right
                msg = '1'
                self.sock.sendto(msg, (self.UDP_IP, self.UDP_PORT))

                # Turn on the LED while the button is pressed
                p.digital_write(3, 1)

                # Wait until the button is let go before reading a new bit
                while p.digital_read(3) == 1:
                    pass

                # Turn off the LED
                p.digital_write(3, 0)
Exemple #42
0
def main(*args):
    power = int()
    ## Cycle de démarrage de PC
    try:
        with open('state.txt','r') as state:
            power = int(state.read())
    except:
        print 'ERREUR STATE READ'
        
    if power == 0:
        pifacedigitalio.init()
        pifacedigitalio.digital_write(1,1)
        time.sleep(0.3)
        pifacedigitalio.digital_write(0,1)
        time.sleep(0.2)
        pifacedigitalio.digital_write(1,0)
        with open ('state.txt','w') as state:
            state.write('1')
    if power == 1:
        pifacedigitalio.init()
        with open ('state.txt','w') as state:
            state.write('0')       
Exemple #43
0
def w():
    dio.digital_write(0, 1)
def toggle_door():
    p.digital_write(0, 1)
    time.sleep(.5)
    p.digital_write(0, 0)
                # Reply to the HTTP packet.
                self.wfile.write("ERROR\n")

    def log_message(self, format, *args):
        return


def run(server_class=HTTPServer, handler_class=S, port=80):
    server_address = ('', port)
    httpd = server_class(server_address, handler_class)
    print 'Starting httpd...'
    httpd.serve_forever()


if __name__ == "__main__":
    from sys import argv

    signal.signal(signal.SIGINT, handler)
    signal.signal(signal.SIGILL, handler)
    signal.signal(signal.SIGSEGV, handler)

    # Init the PiFaceDigital IO library/hardware
    p.init()
    # set output for Garage Sense
    p.digital_write(7, 1)

    if len(argv) == 2:
        run(port=int(argv[1]))
    else:
        run()
Exemple #46
0
from time import sleep
import pifacedigitalio as p
p.init()
p.digital_write(0,1)
sleep(0.5)
p.digital_write(0,0)
sleep(0.5)
p.digital_write(0,1)
sleep(0.5)
p.digital_write(0,0)
sleep(0.025)
p.digital_write(1,1)
n1 = 4
sum1 = 0
counter1 = 1
n2 = 8
sum2 = 0
counter2 = 1
n3 = 32
sum3 = 0
counter3 = 1
n4 = 128
sum4 = 0
counter4 = 1
while counter1 <= n1:
    p.digital_write(3,0)
    p.digital_write(2,1)
    sleep(0.5)
    p.digital_write(2,0)
    p.digital_write(3,1)
    sleep(0.5)
Exemple #47
0
def exec_command(argv):
    global logger
    global pfd
    global running

    in_out_put = argv[1]

    if in_out_put == "led" or in_out_put == "output" or in_out_put == "relay" and (
            pin_number == 0 or pin_number == 1):
        in_out_put = "output"
    elif in_out_put == "input" or in_out_put == "switche" and (
            pin_number == 0 or pin_number == 1 or pin_number == 2
            or pin_number == 3):
        in_out_put = "input"
    #elif in_out_put == "stop":
    #running = False
    #return "stopped"
    else:
        error_msg = "Piface in or output name: " + in_out_put + " does not exist"
        logger.error(error_msg)
        return error_msg

    pin_number = int(argv[2])
    if not (0 <= pin_number < 8):
        error_msg = "Piface pin: " + str(pin_number) + " does not exist"
        logger.error(error_msg)
        return error_msg

    action = argv[3]

    if in_out_put == "output":
        if action == "on":
            pfio.digital_write(pin_number, 1)
            return ("switch on output " + str(pin_number))
        elif action == "off":
            pfio.digital_write(pin_number, 0)
            return ("switch off output " + str(pin_number))
        elif action == "status":
            if pfd.output_pins[pin_number].value == 1:
                return ("status of output " + str(pin_number) +
                        ": output is on")
            else:
                return ("status of output " + str(pin_number) +
                        ": output is off")
        elif action == "push":
            delayTime = 1
            if len(argv) == 5:
                delayTime = argv[4]
            pfio.digital_write(pin_number, 1)
            time.sleep(delayTime)
            pfio.digital_write(pin_number, 0)
            return ("push led " + str(pin_number))
        else:
            error_msg = "Error command: " + action + " does not exist for output"
            logger.error(error_msg)
            return (error_msg)
    elif in_out_put == "input":
        if action == "status":
            if pfd.input_pins[pin_number].value == 1:
                return ("status input " + str(pin_number) + ": input is on")
            else:
                return ("status input " + str(pin_number) + ": input is off")

        else:
            error_msg = "Error command: " + action + " does not exist for input"
            logger.error(error_msg)
            return (error_msg)
Exemple #48
0
#   PYTHONPATH=`pwd` python dooraction.py start
import sqlite3
import logging
import time
import os
from daemon import runner
import pycurl
import pifacedigitalio as piface

conn = sqlite3.connect('/var/sqlite/garagemon.db')

c = conn.cursor()
c.execute('SELECT command FROM dooraction WHERE completion_time is NULL')
command = c.fetchone()
#print command

c.execute('SELECT current_position FROM position')
status = c.fetchone()
#print status

if status != command:
	piface.init()
	piface.digital_write(0,1)
	time.sleep(1)
	piface.digital_write(0,0)
	## Set db completion_time




Exemple #49
0
def write_output(port, value):
    """Write a value to a PFIO."""
    import pifacedigitalio as PFIO
    PFIO.digital_write(port, value)
    def generate_random_LEDs(self,configno):
        """ Generate  random numbers """
        
        # First decide how may LEDs in which Columns to turn ON
        # generate random numbers for each column
        self.LEDs_in_column[0] = random.randint(1,8)
        self.LEDs_in_column[1] = random.randint(1,8)
        self.LEDs_in_column[2] = random.randint(1,8)
        self.LEDs_in_column[3] = random.randint(1,8)
        #now check they are all different
        while self.LEDs_in_column[1] == self.LEDs_in_column[0]:
            self.LEDs_in_column[1] = random.randint (1,8)
        while (self.LEDs_in_column[2] == self.LEDs_in_column[0] or
            self.LEDs_in_column[2] == self.LEDs_in_column[1]):
            self.LEDs_in_column[2] = random.randint(1,8)
        while (self.LEDs_in_column[3] == self.LEDs_in_column[0] or
        self.LEDs_in_column[3] == self.LEDs_in_column[1] or
        self.LEDs_in_column[3] == self.LEDs_in_column[2]):
            self.LEDs_in_column[3] = random.randint(1,8)

        # update the payer results table to show which column is the correct answer
        if (self.LEDs_in_column[0] > self.LEDs_in_column[1] and
            self.LEDs_in_column[0] > self.LEDs_in_column[2] and
            self.LEDs_in_column[0] > self.LEDs_in_column[3]):
            # then 1st column has most LEDs
            self.player_results[configno][C_correct_column] = 1
        elif (self.LEDs_in_column[1] > self.LEDs_in_column[0] and
            self.LEDs_in_column[1] > self.LEDs_in_column[2] and
            self.LEDs_in_column[1] > self.LEDs_in_column[3]):
            # then 2nd column has most LEDs
            self.player_results[configno][C_correct_column] = 2
        elif (self.LEDs_in_column[2] > self.LEDs_in_column[0] and
            self.LEDs_in_column[2] > self.LEDs_in_column[1] and
            self.LEDs_in_column[2] > self.LEDs_in_column[3]):
            # then 3rd column has most LEDs
            self.player_results[configno][C_correct_column] = 3    
        elif (self.LEDs_in_column[3] > self.LEDs_in_column[0] and
            self.LEDs_in_column[3] > self.LEDs_in_column[1] and
            self.LEDs_in_column[3] > self.LEDs_in_column[2]):
            # then 4th column has most LEDs
            self.player_results[configno][C_correct_column] = 4

        # now generate which LED numbers for each column
        # first set all LED numbers to unique negative numbers
        # so all off and all different
        for row in range (0,8):
            for column in range (0,4):
                self.random_LEDs [row][column] =-1 * row

        # now generate all the random LED nos
        for column in range (0,4) :
            # for each column generate  random LED numbers
            for row in range (0,self.LEDs_in_column[column]):
                self.random_LEDs[row][column]= random.randint(1,8)
                
            #now check the LED numbers in this column are all different
            if self.LEDs_in_column[column] >1:
                #While 2nd choice is same as first
                while self.random_LEDs [1][column] == self.random_LEDs [0][column]:
                    # change 2nd choice
                    self.random_LEDs [1][column] = random.randint (1,8)
 
            if self.LEDs_in_column[column] >2:
                #whilst 3rd choice is same as 1st or 2nd
                while (self.random_LEDs [2][column] == self.random_LEDs [0][column] or
                    self.random_LEDs [2][column] == self.random_LEDs [1][column]):
                    # change 3rd choice
                    self.random_LEDs [2][column] = random.randint(1,8)

            if self.LEDs_in_column[column] >3:
                #whilst 4th choice is same as 1st or 2nd or 3rd
                while (self.random_LEDs [3][column] == self.random_LEDs [0][column] or
                self.random_LEDs [3][column] == self.random_LEDs [1][column] or
                self.random_LEDs [3][column] == self.random_LEDs [2][column]):
                    # change 4th choice
                    self.random_LEDs [3][column] = random.randint(1,8)
    
            if self.LEDs_in_column[column] >4:
                #whilst 5th choice is same as 1st 2nd 3rd or 4th
                while (self.random_LEDs [4][column] == self.random_LEDs [0][column] or
                self.random_LEDs [4][column] == self.random_LEDs [1][column] or
                self.random_LEDs [4][column] == self.random_LEDs [2][column] or
                self.random_LEDs [4][column] == self.random_LEDs [3][column]):
                    #change 5th choice
                    self.random_LEDs [4][column] = random.randint(1,8)

            if self.LEDs_in_column[column] >5:
                # whilst 6th choice is same as 1st 2nd 3rd 4th or 6th
                while (self.random_LEDs [5][column] == self.random_LEDs [0][column] or
                self.random_LEDs [5][column] == self.random_LEDs [1][column] or
                self.random_LEDs [5][column] == self.random_LEDs [2][column] or
                self.random_LEDs [5][column] == self.random_LEDs [3][column] or
                self.random_LEDs [5][column] == self.random_LEDs [4][column]):
                    # change 6th choice
                    self.random_LEDs [5][column] = random.randint(1,8)

            if self.LEDs_in_column[column] >6:
                # whilst 7th choice is same as 1st 2nd 3rd 4th 5th or 6th
                while (self.random_LEDs [6][column] == self.random_LEDs [0][column] or
                self.random_LEDs [6][column] == self.random_LEDs [1][column] or
                self.random_LEDs [6][column] == self.random_LEDs [2][column] or
                self.random_LEDs [6][column] == self.random_LEDs [3][column] or
                self.random_LEDs [6][column] == self.random_LEDs [4][column] or
                self.random_LEDs [6][column] == self.random_LEDs [5][column]):
                    # change 7th choice
                    self.random_LEDs [6][column] = random.randint(1,8)
 
            if self.LEDs_in_column[column] ==8:
                # whilst 8th choice is same as 1st 2nd 3rd 4th 5th 6th or 7th
                while (self.random_LEDs [7][column] == self.random_LEDs [0][column] or
                self.random_LEDs [7][column] == self.random_LEDs [1][column] or
                self.random_LEDs [7][column] == self.random_LEDs [2][column] or
                self.random_LEDs [7][column] == self.random_LEDs [3][column] or
                self.random_LEDs [7][column] == self.random_LEDs [4][column] or
                self.random_LEDs [7][column] == self.random_LEDs [5][column] or
                self.random_LEDs [7][column] == self.random_LEDs [6][column]):
                    # change 8th choice
                    self.random_LEDs [7][column] = random.randint(1,8)
        
        # First make sure all LEDS are OFF 
        self.turnall_off()
        # wait one second
        sleep(1)
        # then turn on the chosen LEDs
        for board in range (0,4):
            for choice in range ( 0, self.LEDs_in_column[board]):
                pfio.digital_write ( self.random_LEDs[choice][board]-1, CLEDON, board )
 def turnall_off(self):
     # for each LED on each BOARD turn the led off
     for led in range (0,8,1):
         for board in range (0,4,1):
             pfio.digital_write(led,CLEDOFF,board)      
Exemple #52
0
def setAllOutputs(onOrOff):
	for jj in range(0, 8):
		p.digital_write(jj,onOrOff) # 1 = on
Exemple #53
0
def checkTimerzone():
	global timerZone
	global todaysTimesGMT
	global switchTemperature
	global oldYearDay
	global lastHourlyRun
	changesMade = 0
	# doesn't need to know if weekend, already taken into account
	# BUT does need to know if it's a new day, so might be weekend etc.
	setTimes()
	if oldYearDay != yearDay:
		print ("It's a new day!!")
		readFromIni(0); # read ini to pick up changes, ignore failure
		tempstr = "T1#%04u-%02u-%02uT%02u:%02u:%02uZ#NewDay:%u" % \
			(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second, yearDay)
		if isBST:
			tempstr += "#BST"
		else:
			tempstr += "#GMT"
		if isWeekend:
			tempstr += "#WE"
		else:
			tempstr += "#WD"

		setDailyTimes()
		lastHourlyRun  = 0	# skip midnight run
		if isHoliday:
			tempstr += "#IsHol:Y"
		else:
			tempstr += "#IsHol:n"
		if isVacation:
			tempstr += "#IsVac:Y"
		else:
			tempstr += "#IsVac:n"
		if isSchoolday:
			tempstr += "#IsSch:Y"
		else:
			tempstr += "#IsSch:n"
		logWrite(tempstr)

		setTodaysHeatingTimes()

		tempstr = "T2#%04u-%02u-%02uT%02u:%02u:%02uZ" % \
			(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
		tempstr += "#TodaysTimesGMT#%02u:%02u" % (todaysTimesGMT[0][0], todaysTimesGMT[0][1])
		if todaysTimesGMT[1][0] > -1:
			tempstr += "#%02u:%02u" % (todaysTimesGMT[1][0], todaysTimesGMT[1][1])
		else:
			tempstr += "#--"
		if todaysTimesGMT[2][0] > -1:
			tempstr += "#%02u:%02u" % (todaysTimesGMT[2][0], todaysTimesGMT[2][1])
		else:
			tempstr += "#--"
		tempstr += "#%02u:%02u" % (todaysTimesGMT[3][0], todaysTimesGMT[3][1])
		
		logWrite(tempstr)

	#print (todaysTimesGMT)

	if timerZone < 1:
		#check if on1 time is reached
		#print ("timerZone < 1 (", timerZone, ")")
		checkTime = datetime.datetime(utcDT.year, utcDT.month, utcDT.day, todaysTimesGMT[0][0], todaysTimesGMT[0][1])
		#print (" checkTime (1st entry in todaysTimesGMT):", checkTime)
		#print (" nowTime:", utcDT)
		diff = checkTime - utcDT
		#print (" diff(0):", diff)
		if utcDT > checkTime:
			if todaysTimesGMT[1][0] > todaysTimesGMT[0][0]:	# todaysTimesGMT[1][0] might be -1
				#print (" Changing to timerZone1 am on")
				tempstr = "T3#%04u-%02u-%02uT%02u:%02u:%02uZ#Timerzone Changed#1a-on" % \
					(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
				logWrite(tempstr)
				timerZone = 1
			else:	# it was -1, leave on allday
				#print (" Jumping to timerZone3 pm on")
				tempstr = "T3#%04u-%02u-%02uT%02u:%02u:%02uZ#Timerzone Changed#3p-on" % \
					(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
				logWrite(tempstr)
				timerZone = 3
			#either way, use 'on' temperature
			switchTemperature = switch_temperature_day
			changesMade += 1

	if timerZone == 1:
		#print ("timerZone = 1")
		# assumes that there is an off1 and on2
		checkTime = datetime.datetime(utcDT.year, utcDT.month, utcDT.day, todaysTimesGMT[1][0], todaysTimesGMT[1][1])
		#print (" checkTime (2nd entry in todaysTimesGMT):", checkTime)
		#print (" nowTime:", utcDT)
		diff = checkTime - utcDT
		#print (" diff(1):", diff)
		if utcDT > checkTime:
			#print (" Changing to timerZone2 am off")
			tempstr = "T3#%04u-%02u-%02uT%02u:%02u:%02uZ#Timerzone Changed#2a-off" % \
				(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
			logWrite(tempstr)
			timerZone = 2
			switchTemperature = switch_temperature_night
			changesMade += 1

	if timerZone == 2:
		#print ("timerZone = 2")
		# assumes that there is an off1 and on2
		checkTime = datetime.datetime(utcDT.year, utcDT.month, utcDT.day, todaysTimesGMT[2][0], todaysTimesGMT[2][1])
		#print (" checkTime (3rd entry in todaysTimesGMT):", checkTime)
		#print (" nowTime:", utcDT)
		diff = checkTime - utcDT
		#print (" diff(2):", diff)
		if utcDT > checkTime:
			#print (" Changing to timerZone3 pm on")
			tempstr = "T3#%04u-%02u-%02uT%02u:%02u:%02uZ#Timerzone Changed#3p-on" % \
				(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
			logWrite(tempstr)
			timerZone = 3
			switchTemperature = switch_temperature_day
			changesMade += 1

	if timerZone == 3:
		#print ("timerZone = 3")
		# assumes that there is an off1 and on2
		checkTime = datetime.datetime(utcDT.year, utcDT.month, utcDT.day, todaysTimesGMT[3][0], todaysTimesGMT[3][1])
		#print ("checkTime (3rd entry in todaysTimesGMT):", checkTime)
		#print (" nowTime:", utcDT)
		diff = checkTime - utcDT
		#print (" diff(3):", diff)
		if utcDT > checkTime:
			#print (" Changing to timerZone4 pm off")
			tempstr = "T3#%04u-%02u-%02uT%02u:%02u:%02uZ#Timerzone Changed#4p-off" % \
				(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
			logWrite(tempstr)
			timerZone = 4
			switchTemperature = switch_temperature_night
			changesMade += 1

	if timerZone == 4:
		#print ("timerZone = 4")
		# check when to flip to next day
		# just need to check when timerZone is 4 and it's after midnight. assumes ontime is > 00:59
		# don't care about date
		#print ("nowTime:", utcDT)
		if utcDT.hour == 0 and utcDT.minute > 1:
			#print (" Changing to timerZone0 am off")
			tempstr = "T3#%04u-%02u-%02uT%02u:%02u:%02uZ#Timerzone Changed#0a-off" % \
				(utcDT.year, utcDT.month, utcDT.day, utcDT.hour, utcDT.minute, utcDT.second)
			logWrite(tempstr)
			timerZone = 0
			switchTemperature = switch_temperature_night
			setTimes() # set day, weekend etc.
			changesMade += 1

	# timerZone and switchTemperature have been set
	if changesMade:
		print ("TimerZone changes made: timerZone:", timerZone, " switchTemp:", switchTemperature)

	# if don't do this here, the heating light comes on when the timer light is off
	if timerZone == 1 or timerZone == 3:
		p.digital_write(LED_TIMER, 1)
		#t#print("timerLED on")	#t#
	else:
		p.digital_write(LED_TIMER, 0)
		#t#print("timerLED off")	#t#
	oldYearDay = yearDay
Exemple #54
0
# ----------------------------

oled.init()
try:
    pfd.init()
    piface = True
except pfd.NoPiFaceDigitalDetectedError:
    piface = False

try:
    logging.debug("OLED: 'Running in rc.local'")
    oled.write_line(0, "Running in", 1)
    oled.write_line(1, "rc.local", 1)
    if piface:
        for x in range(3):
            pfd.digital_write(7, 1)
            time.sleep(0.5)
            pfd.digital_write(7, 0)
            time.sleep(0.5)
    else:
        time.sleep(3)

    logging.debug("OLED: Displaying code revision")
    git_rev = get_git_revision()
    oled.write_line(0, "Code revision:", 1)
    oled.write_line(1, git_rev, 1)
    time.sleep(2)

    logging.debug("OLED: Displaying model")
    model = get_model()
    model = model.replace(
Exemple #55
0
#!/usr/bin/python3
#
# flash the output LEDs one by one
#

from time import sleep
import pifacedigitalio as pfio

pfio.init()
try:
	while (True):
		for loop in range(0,7):
			print("flashing %d" % loop)
			pfio.digital_write(loop,1)
			sleep(1)
			pfio.digital_write(loop,0)
			sleep(1)

except KeyboardInterrupt:
	print("Cleaning up")
	for loop in range(0, 7):
		pfio.digital_write(loop, 0)

pfio.deinit()
def write_output(port, value):
    """Write a value to a PFIO."""
    PFIO.digital_write(port, value)
Exemple #57
0
import pifacedigitalio as p
from time import sleep
import os

fh = open("/tmp/pwm0.duty", "w")
fh.write("100")
fh.close
p.init()
duty=100.0
teller=0
while True:
	p.digital_write(6,1) #uit
	sleep((1.0-duty/100.0)/50)
	p.digital_write(6,0) #aan
	sleep((duty/100.0)/50)
	if teller > 100:
		duty_old=duty
		try:
  			with open("/tmp/pwm0.duty", "r") as fh:
		   		duty=int(fh.readline())
#				print("duty=%d"%duty)
				fh.close
				teller=0
		except:
  			print("oops")
  		if duty_old == duty:
  			while duty == 15:
  				try:
  					with open("/tmp/pwm0.duty", "r") as fh:
		   				duty=int(fh.readline())
#						print("duty=%d"%duty)
Exemple #58
0
con = mdb.connect('localhost', 'pi', '', 'baaskarrendb'); 
cur = con.cursor() 


 
while True:

   if p.digital_read(0)== True: 
		time.sleep(0.5)
		DebounceTeller += 1
		if runonce ==0 and DebounceTeller ==2 :
			runonce =1
			DebounceTeller =0
			print "teller is hoog "
			with con: 
				p.digital_write(7,1)
				cur.execute("SELECT verwerkt FROM opdrachten WHERE status='2'  LIMIT 1") #waarde van de verwerkte aantallen uit de Database halen 
				try:
					teller = cur.fetchone()[0] # casten naar int 
					teller +=1		# er een bij optellen
					print teller
					cur.execute("UPDATE opdrachten SET verwerkt=%s WHERE status='2' LIMIT 1 " % (teller)) # waarde wegschrijven naar de Database
					
					cur.execute("SELECT orderaantal FROM opdrachten WHERE status='2'  LIMIT 1") # ophalen van het totaal te verwerken opdrachten. 
					orderaantal = cur.fetchone()[0]
					print orderaantal
									
					if teller ==orderaantal : # kijken of de totaal aantal opdrachten berijkt is. 
						print "zijn gelijk "
						cur.execute("UPDATE opdrachten SET status=1 WHERE status='2' LIMIT 1") # wisselen van opdracht!!!	
						
def main():
	from time import sleep
	import pifacedigitalio as p
	p.init()
	speed = 1

	while(True):
		if p.digital_read(0):
			speed = 0.7
		elif p.digital_read(1):
			speed = 0.5
		elif p.digital_read(2):
			speed = 0.4
		elif p.digital_read(3):
			speed = 0.2
		elif p.digital_read(4):
			speed = 0.05
		
		print("Speed:" + str(speed))
		
		p.digital_write(0,1) #turn 0 on (green)
		p.digital_write(3,1) #turn 3 on (buzzer)
		sleep(speed)
		p.digital_write(3,0) #turn 3 off (buzzer)
		p.digital_write(0,0) #turn 0 off (green)
		p.digital_write(1,1) #turn 1 on (yellow)
		p.digital_write(3,1) #turn 3 on (buzzer)
		sleep(speed)
		p.digital_write(3,0) #turn 3 off (buzzer)
		p.digital_write(1,0) #turn 1 off (yellow)
		p.digital_write(2,1) #turn 2 on (red)
		p.digital_write(3,1) #turn 3 on (buzzer)
		sleep(speed)
		p.digital_write(3,0) #turn 3 off (buzzer)
		p.digital_write(2,0) #turn 2 off (red)
	
	return 0
Exemple #60
0
p.init()
# brief pause, then set all LEDs off??
resetAllOutputs()	# sets all outputs to off, doesn't change any variables

checkTimerzone()	# calls setTimes()

determineHeatingOnOff()

print ("About to start loop =============================")
while True:
	#print ("Looping: ------", utcDT)
	setTimes()

	if (utcDT.second % 15) == 0:		# reconsider this strategy, if the final time.sleep is > 1 sec
		#print ("15sec: +++++", utcDT.second)
		p.digital_write(LED_BLINK,1)
		checkTimerzone() #calls setTimes (again)
		determineHeatingOnOff()

		tempstr = "L#"
		tempstr += "%04u-%02u-%02uT" % (utcDT.year, utcDT.month, utcDT.day)
		tempstr += "%02u:%02u:%02uZ#" % (utcDT.hour, utcDT.minute, utcDT.second)
		tempstr += pitemp + "#"
		tempstr += "%.2f#" % DS18in.value
		tempstr += "%.2f#" % DS18out.value
		if timerZone == 1 or timerZone == 3:
			tempstr += "D#"
			p.digital_write(LED_TIMER, 1)
		else:
			tempstr += "N#"
			p.digital_write(LED_TIMER, 0)