def cleanup(signum, frame): """ Signal handler to ensure we disconnect cleanly in the event of a SIGTERM or SIGINT. """ # Cleanup our interface modules if PFIO_MODULE: logging.debug("Cleaning up PiFace.PFIO module") PFIO.deinit() if GPIO_MODULE: logging.debug("Cleaning up GPIO module") for pin in GPIO_OUTPUT_PINS: GPIO.output(pin, GPIO.HIGH) GPIO.cleanup() # Publish our LWT and cleanup the MQTT connection logging.info("Disconnecting from broker...") mqttc.publish(MQTT_LWT, "0", qos=0, retain=True) mqttc.disconnect() mqttc.loop_stop() # Exit from our application logging.info("Exiting on signal %d" % (signum)) sys.exit(signum)
def deinit(): # stop the gui global proc_comms_q_to_em proc_comms_q_to_em.put(('quit',)) global emulator emulator.join() pfio.deinit()
def destroy(self): logger.debug("destroy") # shutdown all output-pins for output_pin in self.__OutputPins: self.set_output(output_pin, 0, False) p.deinit() doorpi.DoorPi().event_handler.unregister_source(__name__, True)
def main(): global last_tweet_id last_tweet_id = 0 pifacedigitalio.init() robotchicken = RobotChicken() try: while True: say_latest_tweet(robotchicken) sleep(DELAY) except KeyboardInterrupt: pifacedigitalio.deinit()
def destroy(self): if self.is_destroyed: return logger.debug("destroy") # shutdown listener self.__listener.deactivate() # shutdown all output-pins for output_pin in self._OutputPins: self.set_output(output_pin, 0, False) p.deinit() doorpi.DoorPi().event_handler.unregister_source(__name__, True) self.__destroyed = True
#!/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 Main(): global HostName, Version, should_stop, HTTP_Port, db, Today global FuranceRunning, Thermostat_Temp, LightsOff, DELAY, Mode global Furnace_Pin, Furnace_Board, Furnace_ID global pfd, PiFace_Boards, PiFace_Inputs global Speaking, OnValue, OffValue global wunderground_api_key, wunderground_location HostName = socket.gethostname() Today = datetime.datetime.today().weekday() OnOff = {0:'off',1:'on'} OnValue = 1 OffValue = 0 Mode = 0 should_stop = False Speaking = False db = False StartupMsg = "HomePi Version %s | 2013-10-19 - 2016-6-26 Robert Dunmire III" % Version if DEBUG_LOG: print (StartupMsg) logging("##############################################################") logging(StartupMsg) logging("##############################################################") logging("Startup: HomePi Starting on node %s." % HostName) logging("Config: Attempting to init database connection.") query = ("SELECT piface.id, piface.board, piface.pin, piface.status FROM piface INNER JOIN devices ON piface.device=devices.id WHERE devices.name = 'thermostat';") row = DBQuery(0,query) #Thermostat Furnace_Pin = int(row[2]) Furnace_Board = int(row[1]) Furnace_ID = int(row[0]) FuranceRunning = bool(row[3]) Thermostat_Temp = GetConfig("thermostat_temp") LightsOff = int(GetConfig("LightsOff")) DELAY = int(GetConfig("Delay")) logging("Config: Poll delay = %d sec; Lights off delay = %d min." % (LightsOff,DELAY)) wunderground_api_key = GetConfig("wunderground_api_key") wunderground_location = GetConfig("wunderground_location") logging("Config: pifacedigitalio version = %s" % pfdioV.__version__) logging("Config: pifacecommon version = %s " % pfcV.__version__) # GPIOB is the input ports. Set up interrupts PiFace_Boards = int(GetConfig("piface_boards")) PiFace_Inputs = 8 NO_NC = {0:'NC',1:'NO'} ### for PiFace_Number in range(PiFace_Boards): pifacedigitalio.init(PiFace_Number) logging("Config: Init PiFace Board %s." % PiFace_Number) pfd = pifacedigitalio.PiFaceDigital(hardware_addr=PiFace_Number) listener = pifacedigitalio.InputEventListener(chip=pfd) for i in range(PiFace_Inputs): query = ("SELECT * FROM homepi.piface WHERE output=0 AND board=%d AND pin=%d AND node='%s';" % (PiFace_Number,i,HostName)) row = DBQuery(0,query) PiFace_Name = str(row[7]) if bool(row[10]): #Device is NC pifacedigitalio.IODIR_FALLING_EDGE pifacecommon.interrupts.IODIR_OFF listener.register(i, pifacedigitalio.IODIR_RISING_EDGE, event_interrupt, settle_time=0.1) else: #Device is NO IODIR_FALLING_EDGE listener.register(i, pifacedigitalio.IODIR_FALLING_EDGE, event_interrupt, settle_time=0.1) logging("Config: Node %s, PiFace Board %s, Input %s-%s is %s." % (HostName,PiFace_Number,i,PiFace_Name,NO_NC[int(row[10])])) pifacedigitalio.digital_write_pullup(i, 1, hardware_addr=PiFace_Number) ### logging("Thread: Starting listener for %d interrupts!" % (int(PiFace_Boards * PiFace_Inputs))) sleep(0.2) listener.activate() #HTTP Server tcp port 8888 http_thread = threading.Thread(name='http_server', target=HTTP_Server) http_thread.start() sleep(0.2) thermostat_control(OffValue) UpdateSunRiseSet() SetOccupiedZones("0/0") ModeCheck() logging("########### Starting Main() Events Loop! ###########") lastminute = int(GetMinute()) lasthour = int(GetHour()) hour = lasthour try: ##################### while not should_stop: minute = int(GetMinute()) if int(minute) != int(lastminute): lastminute = int(minute) ScheduledTask() event_check() zone_check() ModeCheck() CheckUsers() hour = int(GetHour()) if int(hour) != int(lasthour): lasthour = int(hour) hour_check() LightsOff = int(GetConfig("LightsOff")) DELAY = int(GetConfig("Delay")) thermostat_check() sleep(DELAY) ##################### except KeyboardInterrupt: logging("Quit: Stopping Main()") print("HomePi: Exiting...") pass else: pass try: listener.deactivate() pifacedigitalio.deinit() except: pass should_stop = True closeurl = urllib2.urlopen("http://127.0.0.1:8888/quit/0/").read() threading.Event() http_thread.join() print("HomePi: Quit!") sys.exit() return
# These rules apply, if door is closed (PIN_door == 1) if get_val(PIN_sensorA) == 1: return (True, 3, "Sensor A") if get_val(PIN_sensorB) == 1: return (True, 5, "Sensor B") return (False, 0, "Nothing") #pfd = pifacedigitalio.PiFaceDigital() #listener = pifacedigitalio.InputEventListener(chip=pifacedigitalio) #for i in range(8): listener.register(i, pifacedigitalio.IODIR_BOTH, iodir_on_pin), SETTLE_TIME) #listener.activate() try: log("Process is active.") while True: alarm, eventId, eventName = get_event() if alarm: log("ALERT: %s." % eventName) call(["./trigger.py", str(eventId)]) #sys.stdout.flush() # Not needed when using tmux time.sleep(0.1) # busy-waiting is stupid, but InputEventListener does not work on my PiFace except KeyboardInterrupt: log("KeyboardInterrupt!") except: log("Got unknown exception!?") log("Ending.") #listener.deactivate() pifacedigitalio.deinit() # disables interrupts and closes the file
for loopBoard in range (0,4,1): for loopLed in range (0,8,1): pfio.digital_write (loopLed, CLEDON, loopBoard); sleep (5); print ("Full Board Set LED Test Complete"); #============================================================== # Switch all LEDs off for loopBoard in range (0,4,1): for loopLed in range (0,8,1): pfio.digital_write (loopLed, CLEDOFF, loopBoard); #============================================================== pfio.deinit(); print (""); print ("Completion of all tests"); print (""); print ("============================="); print ("");
def tearDown(self): for listener in self.listeners: listener.deactivate() pifacedigitalio.deinit()
#!/usr/bin/python3 from time import sleep from random import randint, random import pifacecommon import pifacedigitalio DELAY = 1 # seconds try: pifacedigitalio.init() pifacedigital = pifacedigitalio.PiFaceDigital() while True: pifacedigital.leds[randint(0,2)].toggle() sleep(DELAY) except (KeyboardInterrupt): pifacedigitalio.deinit()
if set_time > 125: set_time /= 2 # reduce the allowed time #print ("Time left is: %s" %set_time) time_left = set_time # set the countdown time leds[current].turn_on() # turn the new light on time_left -=1 # decrement the time left to hit the current light pfd.output_port.all_off() # turn all lights off flash_lights() print("\nGame over!\n") print("Your score was: %s" %score) # print the player's final score screen.fill(black) screen.blit(yourscoreText,(50,20)) scoreText = font.render(str(score), 1, (200, 10, 10)) scoreText = pygame.transform.rotate(scoreText,-90) screen.blit(scoreText,(60+yourscoreText.get_width(),30+yourscoreText.get_width())) pygame.display.flip() sleep(5) pipassport.post_transaction(API_KEY, cardid, score) print("Sent transaction for {} {}".format(userinfo['first_name'], userinfo['last_name'])) p.deinit() # close the pfio
def cleanup_pfio(event): """Stuff to do before stopping.""" PFIO.deinit()
def tearDown(self): pifacedigitalio.deinit() # for digital write
def deinit(): p.deinit()
def tearDown(self): pifacedigitalio.deinit()
print(""); print ("Press External button 'Stop' on PiFace Digital board 0"); input_value = pfio.digital_read (CSWITCHSTOP, CSWITCHBOARDSTOP); if input_value == False: while input_value == False and count < CMAXCOUNT: input_value = pfio.digital_read (CSWITCHSTOP, CSWITCHBOARDSTOP); count = count + 1; if count == 0: print ("No PiFace Digital Board") elif count < CMAXCOUNT: print ("Stop Button Pressed"); else: print ("*** TIMEOUT"); #============================================================== print (""); print ("Individual External Switch Tests Complete"); print (""); pfio.deinit(); print ("============================="); print (""); print ("Completion of all tests"); print (""); print ("============================="); print ("");
def tearDown(self): pifacedigitalio.deinit() pifacecommon.core.read_bit = self.old_read_bit
dispatcher.map("/audio/trk/cue", osc_trkCue) dispatcher.map("/audio/trk/play", osc_trkPlay) dispatcher.map("/audio/trk/pause", osc_bgPause) dispatcher.map("/audio/trk/resume", osc_trkResume) dispatcher.map("/output", osc_output) dispatcher.map("/motor/exec", osc_motor) if args.serialport != "": sys.stdout.write("Serial port /dev/" + args.serialport + "\n") ser = EnhancedSerial("/dev/" + args.serialport, 38400, timeout=0.5) bgPath = os.path.join(soundPath, args.bgpath) logging.info("bgPath {0}".format(bgPath)) server = osc_server.ThreadingOSCUDPServer( (args.ip, args.port), dispatcher) logging.info("Serving on {}".format(server.server_address)) server_thread = threading.Thread(target=server.serve_forever) server_thread.start() client = udp_client.UDPClient(args.serverip, args.serverport) main() pif.deinit() pygame.quit() server.shutdown() if ser is not None: ser.close() logging.info('Goodbye')