Exemple #1
0
def off():
    pifacedigital = pifacedigitalio.PiFaceDigital()
    pifacedigital.leds[2].toggle()
    return 'Success!\n'
def activate_listeners(listeners):
    for listener in listeners:
        listener.activate()
    print('Listeners active.')


def deactivate_listeners(listeners):
    for listener in listeners:
        listener.deactivate()
    print('Listeners deactivated.')


if __name__ == '__main__':
    NUM_INPUTS = 4

    board1 = pfio.PiFaceDigital(hardware_addr=0)
    # board2 = pfio.PiFaceDigital(hardware_addr=3)

    listeners = []
    for i in range(NUM_INPUTS):
        listener = pfio.InputEventListener(chip=board1)
        listeners.append(listener)

    for i in range(NUM_INPUTS):
        listeners[i].register(i, pfio.IODIR_ON, print)

    activate_listeners(listeners)

    msg = input('Press any key to stop.\n')

    deactivate_listeners(listeners)
Exemple #3
0
    def __init__(self,
                 arm_input=None,
                 armed_output=None,
                 active_output=None,
                 buzzer_output=None,
                 sounder_output=None,
                 strobe_output=None,
                 arm_delay=30,
                 alarm_delay=30,
                 alarm_duration=900,
                 normally_closed_inputs=None,
                 ignored_inputs=None):
        """
        Initialize the alarm's internal state and hardware (PiFace Digital).

        The `arm_input` pin allows an external device to arm/disarm the alarm. It's normally-open by default and,
        like all other inputs, can be set to normally-closed by including it in the `normally_closed_inputs` list.
        In this latter case, care must be taken to ensure the external device initializes before the alarm does,
        or the alarm may be inadvertently triggered.

        The `armed_output` and `active_output` pins can be used to (optionally) notify external devices that the
        alarm has been (respectively armed) or is currently sounding. The `armed_output` pin becomes low at the
        start of the arming grace period and remains so until the alarm is disarmed. The `active_output` pin is
        guaranteed to never be low unless the `armed_output` pin is also low.

        The `buzzer_output`, `sounder_output`, and `strobe_output` pins control the panel buzzer (for user feedback),
        external siren, and strobe light, respectively. These outputs are all optional and assumed to be active-low.

        The `arm_delay` parameter sets the amount of seconds to wait before unsealed (violated) inputs trigger
        the alarm once it has been armed. This should give the user enough time to leave the premises safely.

        The `alarm_delay` parameter sets the amount of seconds to wait before activating the alarm once one or more
        inputs become unsealed (violated) while armed. This should give the user enough time to disarm the alarm.

        Once triggered, the alarm will sound for `alarm_duration` seconds (unless it's disarmed), after which it will
        rearm itself automatically. The `alarm_delay` will be honored even if there are unsealed (violated) inputs at
        the moment `alarm_duration` expires.

        The `normally_closed_inputs` parameter can (optionally) be set to a list of input pin numbers that should be
        taken as unsealed (violated) when they are in a logical-high state instead of the default logical-low state.

        The `ignored_inputs` parameter can (optionally) be set to a list of input pin numbers whose state can never
        trigger the alarm. This list can also be set when the alarm is armed, reverting to whatever is set here when
        the alarm is disarmed (thus this parameter can be seen as the default list of ignored inputs).
        """

        log.debug("Alarm initialization starting...")

        self._state_lock = threading.Lock()
        self._armed = False
        self._sounding = False

        self._arm_input = arm_input
        self._armed_output = armed_output
        self._active_output = active_output
        self._buzzer_output = buzzer_output
        self._sounder_output = sounder_output
        self._strobe_output = strobe_output

        self._unsealed_inputs = set()
        self._ignored_inputs = set(ignored_inputs or [])
        self._default_ignored_inputs = self._ignored_inputs  # ...fallback on disarm.
        self._normally_closed_inputs = set(normally_closed_inputs or [])

        self._arm_delay = arm_delay
        self._alarm_delay = alarm_delay
        self._alarm_duration = alarm_duration

        self._pf = piface.PiFaceDigital()

        # Use a single "PortEventListener" for all inputs, instead of an "InputEventListener" for each input...
        self._listener = pifacecommon.interrupts.PortEventListener(
            pifacecommon.mcp23s17.GPIOB, self._pf, daemon=True)

        # Inputs won't trigger an interrupt until they change, must poll their initial state...
        for pin in range(NUM_HARDWARE_PINS):
            self._listener.register(pin, piface.IODIR_BOTH,
                                    self._input_change_handler)

            if self._arm_input is not None and pin == self._arm_input:
                continue

            high_state = bool(self._pf.input_pins[pin].value)
            normally_closed = pin in self._normally_closed_inputs

            if not high_state and normally_closed or high_state and not normally_closed:
                self._unsealed_inputs.add(pin)

        if self._unsealed_inputs:
            unsealed_inputs_str = ", ".join(
                str(pin) for pin in sorted(self._unsealed_inputs))
            log.info("These inputs are already unsealed on initialization: %s",
                     unsealed_inputs_str)

        self._listener.activate()

        # Feedback beeps must be asynchronous, or they'd mess timings...
        if self._buzzer_output is not None:
            self._buzzer_enabled = True
            self._buzzer_queue = queue.SimpleQueue()
            self._buzzer_thread = threading.Thread(
                target=type(self)._buzzer_daemon, args=[self], daemon=True)
            self._buzzer_thread.start()

        if self._arm_input is not None:
            high_state = bool(self._pf.input_pins[self._arm_input].value)
            normally_closed = self._arm_input in self._normally_closed_inputs

            if high_state ^ normally_closed:
                log.warning(
                    "AUTO-ARMING on initialization from arm input pin state..."
                )
                self.arm()

        self.beep(**BEEP_SEQUENCES["init"])
        log.info("Alarm initialized.")
Exemple #4
0
# by David Art [aka] adcomp <*****@*****.**>

import tornado.httpserver
import tornado.websocket
import tornado.ioloop
import tornado.web

import datetime
import json
import sys
import os

# PiFace module & init
import pifacedigitalio as pfio
pfio.init()
pifacedigital = pfio.PiFaceDigital()


class IndexHandler(tornado.web.RequestHandler):
    @tornado.web.asynchronous
    def get(self):
        self.render("index.html")


class WebSocketHandler(tornado.websocket.WebSocketHandler):

    clients = []
    last_data = None

    def open(self):
        self.connected = True
Exemple #5
0
 def __init__(self, highwayRelay=0, parkRelay=1):
     self.highwayRelay = highwayRelay
     self.parkRelay = parkRelay
     self.lightBoard = pifacedigitalio.PiFaceDigital()
Exemple #6
0
        if (last_sc['dateto']):
            res = requests.post(
                sc_url,
                data={
                    'dateFrom': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                    'patientId': 1
                })
            print(res)
            if (res.status_code == 200):
                print("Created new sleepcycle.")
            else:
                print(res.text)
        else:
            res = requests.put(
                sc_url + "/{}".format(last_sc['id']),
                data={'dateTo': datetime.now().strftime("%Y-%m-%d %H:%M:%S")})
            if (res.status_code == 200):
                print("Updated sleepcycle.")
            else:
                print(res.text)


pifacedigital = p.PiFaceDigital()
listener = p.InputEventListener(chip=pifacedigital)
listener.register(0, p.IODIR_FALLING_EDGE, toggle_input)
listener.register(1, p.IODIR_FALLING_EDGE, toggle_input)
listener.register(2, p.IODIR_FALLING_EDGE, toggle_input)
listener.register(3, p.IODIR_FALLING_EDGE, toggle_input)

listener.activate()
Exemple #7
0
def main():
    pfd = pifacedigitalio.PiFaceDigital()
    # Instruction sequence
    lst = []
    rounds = 0
    lost = False
    buttonPressed = False
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.settimeout(TIMEOUT)
    Print("Request server connection\n")
    for i in range(CONNECTION_ATTEMPTS + 1):
		
        if i == CONNECTION_ATTEMPTS:
            raise RuntimeError("Unable to connect to server")
		
        Print("Connection attempt " + str(i + 1))
		
		# Send emotion control ID to server
        Print("Sending...")
        Print("Data:\t" + binascii.hexlify(SIMON_ID))
        Print("IP:\t" + SERVER_IP)
        Print("Port:\t%d" % SERVER_PORT)
        s.sendto(SIMON_ID, (SERVER_IP, SERVER_PORT))
		
		# Attempt to receive a response from the server
        try:
            data, address = s.recvfrom(BUFFER_SIZE)
        except socket.timeout:
            Print("Timed out\n")
            continue
        s.settimeout(None)
        Print("\nPacket received")
        Print("Data:\t" + binascii.hexlify(data))
        Print("IP:\t" + address[0])
        Print("Port:\t%d" % address[1])
		# Check if message is actually from the server
        if data[0] == SERVER_ID:
            i = 6
        else:
			#raise RuntimeError("Unknown response")
            Print("Unknown response")
	
	while True:
		
		lost = False
		# Receive on port into buf
		print ("Waiting to receive")
		data, address = s.recvfrom(BUFFER_SIZE)
		
		# Assert received from server
		if data[0] != SERVER_ID:
			Print("Invalid response")
			continue
		
		# New empty list for new game
		buf = []
		
		for rounds in range(MAX_ROUNDS):
			if lost:
			    break
			buf.append(random.randint(0, 3))
			#print ("value in column %s" % (buf))
			# Test the user's memory
			for i in range (len(buf)):
			    pfd.output_pins[buf[i]].value = ON
			    time.sleep(0.5)
			    pfd.output_pins[buf[i]].value = OFF
			for k in range(len(buf)):
				# Wait until a button is pressed
				while not buttonPressed:
					buttonPressed = pfd.input_pins[0].value == ON or pfd.input_pins[1].value == ON or pfd.input_pins[2].value == ON or pfd.input_pins[3].value == ON
				buttonPressed = False
				# A button has been pressed
				
				# Check each button to find out which has been pressed
				# If the right one had been pressed then turn the light on briefly and continue
				if pfd.input_pins[(buf[k] + (-1) ** (buf[k] + 1)) % 4].value == 1:
					pfd.output_pins[buf[k]].value = 1;
					time.sleep(0.5)
					pfd.output_pins[buf[k]].value = 0;
					continue
				# If the wrong one has been pressed then flash the fail lights	
				else:
					print ("Better luck next time")
					failLights()
					lost = True
					rounds = 0
					break
			
				print ("Winner winner chicken dinner!")
				rounds = 0
				winLights()
#!/usr/bin/env python
"""
memoryGame.py
Simple memory game for use with pfio and the RaspberryPi interface (piface)

Objective of the game: You must remember an ever increasing sequence of flashes and input them correctly*

"""
from __future__ import print_function
from time import sleep  # for delays
import random  # for random sequence generation
import pifacedigitalio as pfio  # piface library

pfio.init()  # initialise pfio (sets up the spi transfers)

pfd = pfio.PiFaceDigital()  # create pifacedigital object

colours = ["Red", "Green", "Blue", "Yellow",
           "White"]  # colour names for printing to screen


def signifyTurn(turn):
    global screen_output

    sleep(0.4)
    pfd.output_port.value = 0xFF  # signify it is their turn by turning all the LEDs on then off
    sleep(0.3)
    pfd.output_port.value = 0x0

    if screen_output:
        if turn:
                event.chip.output_pins[event.pin_num].turn_on(
                )  # turn on outputs, comment out if you do not want to switch anything with the onboard outputs
            elif i['rest'] == 0:
                log.info(
                    'Setting off / closed / no-motion state for device %s',
                    i['description'])
                pz.set_off(i['domoticz_id'])
                event.chip.output_pins[event.pin_num].turn_off()
            else:
                log.error('invalid rest status detected, not 1 or 0')
    if noconfig == 0:
        log.warning(
            'Disconnected event detected but no action performed, looks like there is no config for board / pin: {}/{} .'
            .format(boardno, event.pin_num))


if __name__ == "__main__":
    #    listener.deactivate()
    pifacedigital0 = pifacedigitalio.PiFaceDigital(0)
    pifacedigital1 = pifacedigitalio.PiFaceDigital(1)

    listener0 = pifacedigitalio.InputEventListener(chip=pifacedigital0)
    listener1 = pifacedigitalio.InputEventListener(chip=pifacedigital1)
    for i in range(8):
        listener0.register(i, pifacedigitalio.IODIR_ON, connected0)
        listener1.register(i, pifacedigitalio.IODIR_ON, connected1)
        listener0.register(i, pifacedigitalio.IODIR_OFF, disconnected0)
        listener1.register(i, pifacedigitalio.IODIR_OFF, disconnected1)
    listener0.activate()
    listener1.activate()
Exemple #10
0
    def __init__(self):

        #Setup logging
        self.logger1 = log_handler.get_log_handler('door_controller_log.txt',
                                                   'info', 'door.IOHandler')

        self.logger1.info('Starting: InputOutputHandler')

        #Open config file
        self.logger1.debug('Getting config from: %s', CONFIG_FILE_NAME)
        config = get_config.get_config(CONFIG_FILE_NAME, True)

        #Parse inputs and outputs from config file
        self.inputs, self.outputs = parse_config(config)

        #Parse commands from config file in named tuple
        self.input_commands = InputCommands(
            toggle_door_cmd=config.get('Commands', 'toggle_door_cmd'),
            open_door_cmd=config.get('Commands', 'open_door_cmd'),
            close_door_cmd=config.get('Commands', 'close_door_cmd'),
            light_cmd=config.get('Commands', 'light_cmd'),
            control_wire=config.get('Commands', 'control_wire'),
            stop_cmd=config.get('Commands', 'stop_cmd'))

        #Lock status
        self.door_locked = False
        self.light_locked = False

        #Initialise PiFace and interrupts
        pifacedigitalio.init()
        self.pifacedigital = pifacedigitalio.PiFaceDigital()
        self.listener = pifacedigitalio.InputEventListener(
            chip=self.pifacedigital)

        #Output pins
        self.door_relay_pin = None
        self.led_status0_pin = None

        #Input pins
        self.door_status_pin = None

        #Queue to capture input events
        self.event_queue = pollable_queue.PollableQueue()

        #Queue to log events to
        self.logging_queue = pollable_queue.PollableQueue()

        #Instantiate logging module
        self.log_events = event_handler.EventHandler(
            self.logging_queue, self.input_commands.stop_cmd)

        #Log starting event
        self.logging_queue.put(self.__create_event_obj(INTERNAL, 'Starting'))

        #Dict to store interrupt functions about to be generated
        self.intrupt_funcs = {}

        #Generate dynamic functions to process interrupts
        for key in self.inputs:

            self.logger1.info('Processing Input: ' + key)
            piface_in = self.inputs[key]

            if piface_in.name == DOOR_STATUS_INPUT_NAME:
                self.logger1.info(
                    'Setting door status input to pin: {}'.format(
                        piface_in.pin))
                self.door_status_pin = piface_in.pin

            #Disable 10K pullup resistor on piface input pin
            if piface_in.disablepullup:
                self.logger1.info('Disabling pullup on input {}'.format(
                    piface_in.name))
                pifacedigitalio.digital_write_pullup(piface_in.pin, 0)

            #Create interrupt listener and associated function for falling edges
            if piface_in.falling:
                self.logger1.info(
                    'Creating Falling Edge Listener on input: {}'.format(
                        piface_in.name))
                #e_obj = self.__create_event_obj(piface_in.type, piface_in.name, 'Falling_Edge')
                self.intrupt_funcs[key + '_falling'] = getattr(
                    InterruptHandler(piface_in.type, piface_in.name,
                                     'Falling_Edge', self.event_queue),
                    'interrupt_function')
                self.listener.register(piface_in.pin,
                                       pifacedigitalio.IODIR_FALLING_EDGE,
                                       self.intrupt_funcs[key + '_falling'])

            #Create interrupt listener and associated function for rising edges
            if piface_in.rising:
                self.logger1.info(
                    'Creating Rising Edge Listener on input: {}'.format(
                        piface_in.name))
                #e_obj = self.__create_event_obj(piface_in.type, piface_in.name, 'Rising_Edge')
                self.intrupt_funcs[key + '_rising'] = getattr(
                    InterruptHandler(piface_in.type, piface_in.name,
                                     'Rising_Edge', self.event_queue),
                    'interrupt_function')
                self.listener.register(piface_in.pin,
                                       pifacedigitalio.IODIR_RISING_EDGE,
                                       self.intrupt_funcs[key + '_rising'])

        #Processing outputs
        for key in self.outputs:

            piface_out = self.outputs[key]

            #Set relay output pin on piface
            if piface_out.name == DOOR_RELAY_OUTPUT_NAME:
                self.logger1.info('Creating door relay on output: {}'.format(
                    piface_out.pin))
                self.door_relay_pin = piface_out.pin

            #Set status LED output pin on piface
            if piface_out.name == STATUS_LED_OUTPUT_NAME:
                self.logger1.info('Creating status LED on output: {}'.format(
                    piface_out.pin))
                self.led_status0_pin = piface_out.pin

        self.logger1.info('Starting worker threads')

        #Create threading events and clear them
        self.stop_event = threading.Event()
        self.operate_door = threading.Event()
        self.operate_light = threading.Event()

        self.stop_event.clear()
        self.operate_door.clear()
        self.operate_light.clear()

        #Start threads to process input events
        self.process_input_thread = threading.Thread(
            name='process_input_thread', target=self.__process_input)

        self.activate_door_thread = threading.Thread(
            name='act_door_thread', target=self.__door_activator)

        self.activate_light_thread = threading.Thread(
            name='act_light_thread', target=self.__light_activator)

        self.flash_led_thread = threading.Thread(
            name='flt', target=self.__flash_status_led)

        self.process_input_thread.start()
        self.activate_door_thread.start()
        self.activate_light_thread.start()
        self.flash_led_thread.start()

        self.check_relay_thread = None
        self.__check_relay_state()

        #Monitoring
        self.last_open_time = None
        self.last_closed_time = None
        self.last_status = None

        #Activate interrupts
        self.listener.activate()

        self.logger1.info('Initialisation of InputOutputHandler Complete')
Exemple #11
0
#!/usr/bin/env python

import pifacedigitalio as p

#init the piface board
#False means do not reinit the board again
#But you have to init it once!
pdf = p.PiFaceDigital(0, 0, 0, True)
Exemple #12
0
def main():
    output_pins, input_pins, relay_number, ldap_match_attr, ldap_owner_attr, ldap_server, ldap_port, ldap_base_dn, ldap_use_ssl, ldap_user, ldap_user_secret = read_config(
        "config.yml")
    pifacedigital = pifacedigitalio.PiFaceDigital()
    door = Door(pifacedigital, output_pins, input_pins, relay_number)
    door.open()
Exemple #13
0
''' An example application to toggle the LED's on a PiFace 
	Written by Tom Richardson 2013
	To run, type 'python pifaceexample.py'
		It will run on the Pi's local IP on port 8090
'''

import pifacedigitalio as p
from pimote import *

# Initialize PiFace
p.init()
pfd = p.PiFaceDigital()

class MyPhone(Phone):
	# Override to get messages sent from phone
	def buttonPressed(self, id, message, phoneId):
		global pfd
		global buttons
		
		j = 0
		# Loop through buttons
		for j in range(0, 8):
			if buttons[j].getId() == id:
				# Change the LED
				self.changeLed(pfd, j, buttons[j])

	#Used to turn an LED on or off depending on input
	def changeLed(self, pfd, led, b):
		if b.getValue():
			pfd.leds[led].turn_on()
		else:
Exemple #14
0
def lightsOn():
    pifacedigital = pifacedigitalio.PiFaceDigital()
    pifacedigital.leds[1].toggle()
    pifacedigital.leds[0].toggle()
black = 0, 0, 0

screen = pygame.display.set_mode(size)  #, pygame.FULLSCREEN)
rasp = pygame.image.load("Raspi_Colour_R.png")
raspberry = pygame.transform.scale(rasp, size)
rect = raspberry.get_rect()

font = pygame.font.Font(None, 60)
font2 = pygame.font.Font(None, 80)
text = font.render("Your score", 1, (200, 10, 10))

text = pygame.transform.rotate(text, -90)

p.init()  # initialise pfio (sets up the spi transfers)

pfd = p.PiFaceDigital()

pfd2 = p.PiFaceDigital(1)

leds = []

for i in range(8):
    leds.append(pfd.leds[i])

for i in range(8):
    leds.append(pfd2.leds[i])

scanText = font2.render("Scan your card", 1, (200, 10, 10))
scanText = pygame.transform.rotate(scanText, -90)
welcomeText = font2.render("Welcome", 1, (200, 10, 10))
welcomeText = pygame.transform.rotate(welcomeText, -90)
Exemple #16
0
def execute():
    print('Startup')

    input_count = 8
    output_count = 8

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

    r = redis.Redis(host='192.168.0.1', port=6379, db=0, decode_responses=True)
    p = r.pubsub(ignore_subscribe_messages=True)
    p.psubscribe('pfd.input', 'pfd.output.?')

    input_on = [None] * input_count
    input_off = [None] * input_count

    r.publish('services', 'pfd.on')
    systemd.daemon.notify('READY=1')
    print('Startup complete')

    try:
        for i in range(0, input_count):
            input_on[i] = lambda e, i=i: r.publish("pfd.input." + str(i),
                                                   "input." + str(i) + ".on")
            input_off[i] = lambda e, i=i: r.publish("pfd.input." + str(i),
                                                    "input." + str(i) + ".off")

            # Invoke it for initial state
            (input_off[i])(None)

            listener.register(i, pifacedigitalio.IODIR_FALLING_EDGE,
                              input_on[i])
            listener.register(i, pifacedigitalio.IODIR_RISING_EDGE,
                              input_off[i])

        listener.activate()

        for i in range(0, output_count):
            pfd.output_pins[i].turn_off()
            r.publish('pfd.output.' + str(i) + '.status',
                      'output.' + str(i) + '.on')

        for message in p.listen():
            if message['channel'] == 'pfd.input':
                if message['data'] == "*":
                    tgt_range = range(0, input_count)
                else:
                    try:
                        rangespec = int(message['data'])
                        if rangespec < 0 or rangespec > 7:
                            tgt_range = None
                        else:
                            tgt_range = range(rangespec, rangespec + 1)
                    except:
                        # Do nothing if can't parse
                        tgt_range = range(0, 0)
                for i in tgt_range:
                    if pfd.input_pins[i].value > 0:
                        (input_on[i])(None)
                    else:
                        (input_off[i])(None)
            elif message['channel'].startswith('pfd.output.'):
                output_id = int(message['channel'][-1])

                if output_id >= output_count or output_id < 0:
                    continue

                if message['data'] == 'on':
                    pfd.output_pins[output_id].turn_on()
                    r.publish('pfd.output.' + str(output_id) + '.status',
                              'output.' + str(output_id) + '.on')
                elif message['data'] == 'off':
                    pfd.output_pins[output_id].turn_off()
                    r.publish('pfd.output.' + str(output_id) + '.status',
                              'output.' + str(output_id) + '.off')
                elif message['data'] == '/':
                    pfd.output_pins[output_id].toggle()

                if message['data'] == '?' or message['data'] == '/':
                    pin_status = pfd.output_pins[output_id]
                    if pin_status.value:
                        r.publish('pfd.output.' + str(output_id) + '.status',
                                  'output.' + str(output_id) + '.on')
                    else:
                        r.publish('pfd.output.' + str(output_id) + '.status',
                                  'output.' + str(output_id) + '.off')
    except:
        p.close()

        listener.deactivate()
        pfd.deinit_board()

        r.publish('services', 'pfd.off')
        print("Goodbye")
    parser.add_argument("-b0",
                        "--board0",
                        help="test PiFace Digital board 0 (default)",
                        action="store_true")
    for i in range(1, 4):
        parser.add_argument("-b{}".format(i),
                            "--board{}".format(i),
                            help="test PiFace Digital board {}".format(i),
                            action="store_true")
    args = parser.parse_args()

    global pifacedigitals
    pifacedigitals = list()

    if args.board0 or not (args.board1 or args.board2 or args.board3):
        pifacedigitals.append(pifacedigitalio.PiFaceDigital(0))
        if args.board0:
            remove_arg("-b0", "--board0")

    if args.board1:
        pifacedigitals.append(pifacedigitalio.PiFaceDigital(1))
        remove_arg("-b1", "--board1")

    if args.board2:
        pifacedigitals.append(pifacedigitalio.PiFaceDigital(2))
        remove_arg("-b2", "--board2")

    if args.board3:
        pifacedigitals.append(pifacedigitalio.PiFaceDigital(3))
        remove_arg("-b3", "--board3")
Exemple #18
0
#!/usr/bin/env python

import pifacedigitalio as p

#init the piface board
#False means do not reinit the board again
#But you have to init it once!
pdf = p.PiFaceDigital(0, 0, 0, False)

pdf.output_pins[1].value = 1  #start engine
usb = 2
hdmi = 4
vga = 16
dvi = 32

cables = [0, vga, jack, hdmi, dvi, usb]

arguments = cgi.FieldStorage()

first = arguments['first'].value
second = arguments['second'].value
third = arguments['third'].value

but = cables[int(first)] + cables[int(second)] + cables[int(third)]

piface = p.PiFaceDigital()

piface.leds[0].turn_off()
piface.leds[1].turn_off()
piface.leds[0].turn_on()
piface.leds[1].turn_on()

portValue = piface.input_port.value
while but != portValue:
    portValue = piface.input_port.value
    time.sleep(0.25)

piface.leds[0].turn_off()
piface.leds[1].turn_off()

r = requests.get('http://192.168.123.242/webdispatcher/step1.php')
Exemple #20
0
#!/usr/bin/python3
# Head to head lockboard challenge script
# Writen by: Graph-X

import pifacedigitalio as pfd

board_one = [0, 1, 2]
board_two = [3, 4, 5]
player_one = 0
player_two = 0
pf = pfd.PiFaceDigital()


def reset(event):
    global board_one
    global board_two
    global player_one
    global player_two
    player_one = 0
    player_two = 0
    board_one = [0, 1, 2]
    board_two = [3, 4, 5]
    #turn off all the leds
    for i in range(0, 7):
        pfd.leds[i].turn_off()


#when a player wins turn on the correct LED
def player_win(player):
    if player == 1:
        #turn on led 6
Exemple #21
0
 def __init__(self):
     super().__init__()
     self._pifacedigital = pifacedigitalio.PiFaceDigital()
Exemple #22
0
#!/usr/bin/python

import time
import pifacedigitalio as p

pfio = p.PiFaceDigital()

p.init()

pfio.leds[7].turn_on()

while True:
    print p.digital_read(0)
    time.sleep(1)
Exemple #23
0
import socket, sys, time
from time import sleep
import pifacedigitalio as pfio
import time

pfd = pfio.PiFaceDigital()
pfio.init()

#Creating the socket to send the notification over. We will also receive a response from the server on this socket.
headlessPiSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
port = 5050
server_address = ('10.0.0.52', port)
headlessPiSocket.bind(server_address)
#Socket is set to be non-blocking, this is because we want to continously send notifications to server until we get a response.
#A response means the server received the packet.
headlessPiSocket.setblocking(0)
#Server information
serverPi = ('10.0.0.51', port)
#If input pins have this value it means they detected a fire
flameFound = 1

debugging = True

while (True):

    if (pfd.input_pins[6].value == flameFound
            or pfd.input_pins[7].value == flameFound):

        if (debugging):
            print("OMG FLAME DETECTED")
#!/usr/bin/python3
#
#Script that checks the status of the manual override on the door lock
#and updates slack if the door is manually unlocked
#
import time
import pifacedigitalio
from backports import configparser
import logging
from logging import config as logconfig
import slacker

if __name__ == '__main__':
    config = configparser.ConfigParser()
    config.read('bouncer.ini')
    logconfig.fileConfig('bouncer.ini')

    slack = slacker.Slacker(config['slack.com']['token'])
    pfd = pifacedigitalio.PiFaceDigital(init_board=False)

    if pfd.input_pins[3].value:
       slack.chat.post_message('#door', 'The forge door is manually held open at ' +time.strftime("%H:%M:%S") +' CST. This alert will repeat in 30 minutes')
       logging.info("Door is held open")
    else:
       logging.info("Door is normal")

    if pfd.input_pins[2].value:
       logging.info("Door is open")
    else:
       logging.info("Door is closed")
Exemple #25
0
def get_my_ip():
    """Returns this computers IP address as a string."""
    ip = subprocess.check_output(GET_IP_CMD, shell=True).decode('utf-8')[:-1]
    return ip.strip()


if __name__ == "__main__":
    # get the port
    if len(sys.argv) > 1:
        port = int(sys.argv[1])
    else:
        port = DEFAULT_PORT

    # set up PiFace Digital
    PiFaceWebHandler.pifacedigital = pifacedigitalio.PiFaceDigital()

    print("Starting simple PiFace web control at:\n\n"
          "\thttp://{addr}:{port}\n\n"
          "Change the output_port with:\n\n"
          "\thttp://{addr}:{port}?output_port=0xAA\n".format(addr=get_my_ip(),
                                                             port=port))

    # run the server
    server_address = ('', port)
    try:
        httpd = http.server.HTTPServer(server_address, PiFaceWebHandler)
        httpd.serve_forever()
    except KeyboardInterrupt:
        print('^C received, shutting down server')
        httpd.socket.close()
Exemple #26
0
    try:
        t1 = thd.Thread(target=run_general)
        t2 = thd.Thread(target=run_spi)
        t3 = thd.Thread(target=run_flask_api)
        t4 = thd.Thread(target=run_motor)
        t1.setDaemon(True)
        t2.setDaemon(True)
        t3.setDaemon(True)
        t3.setDaemon(True)
        t1.start()
        t2.start()
        t3.start()
        t4.start()

        pdio.init()
        pfd = pdio.PiFaceDigital()
        listener = pdio.InputEventListener(chip=pfd)
        listener.register(0, pdio.IODIR_FALLING_EDGE, read_data)
        #listener.register(1, pdio.IODIR_FALLING_EDGE, motor_down)
        #listener.register(2, pdio.IODIR_FALLING_EDGE, motor_up)
        listener.register(1, pdio.IODIR_FALLING_EDGE, set_LED_bool1)
        listener.register(2, pdio.IODIR_FALLING_EDGE, set_LED_bool2)
        #listener.register(6, pdio.IODIR_ON, switch_pressed)
        #listener.register(7, pdio.IODIR_OFF, switch_unpressed)
        listener.activate()

        set_sun_time()
        if (sun_down == False):
            gate_state = True

        while True:
import math
import time
from time import sleep
import datetime

import pifacedigitalio

pfd = pifacedigitalio.PiFaceDigital()  # creates a PiFace Digtal object

debounce_time_delay = 0.1

# Over pressure auto switch, for relief valve
over_p_auto_sw_state = 0
over_p_auto_sw_toggle = 0
over_p_auto_sw_filt = 0
over_p_auto_sw = 0
debounce_over_p_auto_falltimer = 0
debounce_over_p_auto_risetimer = 0

# Over pressure manual switch, for relief valve override
over_p_man_sw_state = 0
over_p_man_sw_toggle = 0
over_p_man_sw_filt = 0
over_p_man_sw = 0
debounce_over_p_man_falltimer = 0
debounce_over_p_man_risetimer = 0

# Under pressure auto switch, for relief valve
under_p_auto_sw_state = 0
under_p_auto_sw_toggle = 0
under_p_auto_sw_filt = 0
Exemple #28
0
import pifacedigitalio as pfio
from time import sleep
pfio.init()
piface = pfio.PiFaceDigital()
piface.output_pins[1].turn_on()  # this command does the same thing...
sleep(7)
piface.output_pins[1].turn_off()
sleep(1)
Exemple #29
0
#!/usr/bin/env python

import pifacedigitalio
pfd = pifacedigitalio.PiFaceDigital()

pfd.relays[0].value = 1
# turn on/set high the first relay
# pfd.relays[0].value = 0

Exemple #30
0
    # On va demander la valeur des compteurs avec un peu de retard expres
    timeCPT = time.time() + 11
    NextRefresh = time.time() + 40
    sendCPT = 0

    if (nodep):
        SimpleSend('&NODEP=pifacedigitalio')
        log(
            'Error',
            'Dependances pifacedigitalio introuvables. Veuillez les (re)installer. - '
            + str(errdep))
        sys.exit('Dependances pifacedigitalio introuvables. - ' + str(errdep))

    # set up PiFace Digital
    pifacedigital = pifacedigitalio.PiFaceDigital(int(boardId))
    #listener = pifacedigitalio.InputEventListener(chip=pifacedigital)

    # Toutes les entrees en impulsion
    # Init du Compteur  d'Impulsion
    CounterPinValue = {}
    PinNextSend = {}
    TempoPinHIGH = {}
    TempoPinLOW = {}
    Status_pins = {}
    Status_INPUTS = {}
    swtch = {}
    exit = 0
    SetAllLOW = 0
    SetAllHIGH = 0
    SetAllSWITCH = 0