def __init__(self,
              override_signal=None,
              password_file_path="password.txt"):
     self.current_led = 0
     self.duration_buffer = ""
     self.keypad = Keypad()
     self.led_board = LEDBoard()
     self.password_file_path = password_file_path
     self.override_signal = override_signal
     self.input_buffer = []
     self.previous_input_buffer = []
     self.actions = {
         None: lambda s=None: None,
         "A1": self.boot,
         "A2": self.append_password_char,
         "A3": self.verify_login,
         "A4": self.boot,
         "A5": lambda s=None: None,
         "A6": self.next_entry,
         "A7": self.next_entry,
         "A8": self.validate_passcode_change,
         "A9": self.choose_led,
         "A10": self.append_duration_digit,
         "A11": self.apply_led_lighting,
         "A12": self.show_power_down,
     }
Example #2
0
def test_main():
    i2c = I2C(scl=Pin(5), sda=Pin(4), freq=400000)
    lcd = I2cLcd(i2c, DEFAULT_I2C_ADDR, 2, 16)
    pcf = PCF8574(i2c, ADDR)
    keymap = [
        '123A',
        '456B',
        '789C',
        '*0#D'
    ]
    charmap = {
        '1': '.1',    '2': 'abc2', '3': 'def3',
        '4': 'ghi4',  '5': 'jkl5', '6': 'mno6',
        '7': 'pqrs7', '8': 'tuv8', '9': 'wxyz9',
                      '0': '_0',
    }
    keypad = Keypad(pcf, keymap, charmap)

    lcd.clear()
    lcd.show_cursor()
    try:
        word = keypad.get_word(lcd)
        print("Got {} as input".format(word))
    except Exit:
        print('Received exit')

    lcd.clear()
    try:
        word = keypad.get_word(lcd, True)
        print("Got {} as input".format(word))
    except Exit:
        print('Received exit')
Example #3
0
 def __init__(self):
     self.__userAuthenticated = False
     self.__currentAccountNumber = 0
     self.__screen = Screen()
     self.__keypad = Keypad()
     self.__cashDispenser = CashDispenser()
     self.__depositSlot = DepositSlot()
     self.__bankDatabase = BankDatabase()
Example #4
0
 def __init(self):
     self.fsm = FSM(self)
     self.keypad = Keypad()
     self.led = LEDboard()
     self.file_name = "passord.txt"
     self.password_buffer = ""
     self.override_signal = None
     self.led_id = 0
     self.led_duration = 0
     self.Legal_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
Example #5
0
def init():
    global left_arm, right_arm, head, lights, display, footpedal, keypad
    left_arm = LazyServo(17, min_angle=90, max_angle=-90)
    right_arm = LazyServo(22)
    head = LazyServo(27)
    lights = NeoPixel(D18, 8)
    lights.fill((255, 0, 0))
    display = CountDisplay(23, 24)
    footpedal = Button(25)
    keypad = Keypad([9, 11, 10, 5], [6, 13, 19, 26])
    for row in keypad.keymap:
        for key in row:
            keypad.callbacks[key] = lambda: print(key)
Example #6
0
class KeypadTest(unittest.TestCase):
    def setUp(self):
        self.keypad = Keypad()

    # ULL
    # RRDDD
    # LURDL
    # UUUUD
    #
    # So, in this example, the bathroom code is 1985.
    def test_sample(self):
        self.assertEqual(self.keypad.executeRow('ULL'), '1')
        self.assertEqual(self.keypad.executeRow('RRDDD'), '9')
        self.assertEqual(self.keypad.executeRow('LURDL'), '8')
        self.assertEqual(self.keypad.executeRow('UUUUD'), '5')
class Input:
    def __init__(self):
        self.keypad = Keypad()

    def read(self):
        self.trial = ""
        char = self.keypad.read()
        while(char != "#"):
            self.trial += str(char)
            print(self.trial)
            char = self.keypad.read()
        return self.trial

    def get_input(self):
        return self.trial
Example #8
0
class Input:
    def __init__(self):
        self.keypad = Keypad()

    def read(self):
        self.trial = ""
        char = self.keypad.read()
        while (char != "#"):
            self.trial += str(char)
            print(self.trial)
            char = self.keypad.read()
        return self.trial

    def get_input(self):
        return self.trial
Example #9
0
def loop():
    mqtt = MQTTClient("umqtt_alarm",
                      MQTT_HOST,
                      port=1883,
                      user=MQTT_USER,
                      password=MQTT_PASSWORD)
    mqtt.connect()
    kp = Keypad(uart)
    pins = Pins([{
        "label": "hall",
        "value": 4
    }, {
        "label": "stairs",
        "value": 5
    }, {
        "label": "cellar",
        "value": 18
    }, {
        "label": "unassigned19",
        "value": 19
    }], [{
        "label": "unassigned21",
        "value": 21
    }, {
        "label": "unassigned22",
        "value": 22
    }, {
        "label": "unassigned23",
        "value": 23
    }])
    alarm = Alarm(kp, pins, mqtt)
    alarm.loop()
Example #10
0
File: fsm.py Project: ivhak/TDT4113
    def main_loop(self):
        '''
        Run the finite state machine. While the state is not the default
        state, get a signal and choose which action to perfom.
        '''
        for rule in RULES:
            self.add_rule(rule)

        self.agent = KPC()
        self.agent.read_pass()

        self.agent.led_board = LED()
        self.agent.led_board.setup()

        self.agent.keypad = Keypad()
        self.agent.keypad.setup()

        while self.state is not None:
            try:
                self.get_next_signal()
                self.run_rules()
            except KeyboardInterrupt:
                pass

        self.agent.exit_action()
def keypad_screen(keys_pressed):
    pin = Keypad(5, 2, 1, 6)
    tempback = 0
    if keys_pressed == 1:
        tempback = 1
    elif keys_pressed == 2:
        tempback = 2
    elif keys_pressed == 3:
        tempback = 3
    elif keys_pressed == 4:
        tempback = 4
        if pin.is_correct(key_list[0], key_list[1], key_list[2], key_list[3]):
            tempback = 5
        else:
            tempback = 6
    return tempback
 def __init__(self):
     self.keypad = Keypad()
     self.indicator = Indicator()
     self.server_interface = ServerInterface()
     self.command_code = None
     self.command_dictionary = {'1#': self.server_interface.arm_contacts, 
                                '2':  self.server_interface.arm_all_sensors
     }
Example #13
0
def loop():
    keypad = Keypad(keys,rowsPins,colsPins,ROWS,COLS)
    keypad.setDebounceTime(50)
    mcp.output(3,1) 
    lcd.begin(16,2) 
    while(True):
        lcd.clear()
        lcd.setCursor(0,0)
        # Create an object of the class MFRC522
        MIFAREReader = MFRC522.MFRC522()
        lcd.message('Scan card')  
        
        key = keypad.getKey()
        if(key != keypad.NULL):
            print ("You Pressed Key : %c "%(key) )
        
        sleep(.5)
Example #14
0
    def __init__(self):
        self.agent = KPC()  # Pointer to the KPC object
        self.keypad = Keypad()

        self.state = 1  # Initialize state of the FSM
        self.final_state = 7  #not a state, if we end up here we're outside the state machine
        self.rules = []
        self.curr_rules = []
Example #15
0
def listenForKeypadEvents():
    kp = Keypad()
    digit = None

    try:
        while True:
            if digit == None:
                digit = kp.getKey()  # blocking call
            else:
                print digit
                print("key pressed: " + digit)
                logger.info("Key pressed: " + digit)
                toggle_switch(digit)
                time.sleep(.4)
                digit = None
    except KeyboardInterrupt:
        print("Keyboard interrupt")
        GPIO.cleanup()
Example #16
0
 def __init__(self):
     """Initialiser, setting the initializer"""
     self.keypad = Keypad()
     self.LED = LED_board()
     self.passcode_buffer = ''
     self.digit = ''
     self.path_password = '******'
     self.override_signal = ''
     self.LED_id = ''
     self.LED_duration = ''
     self.new_pass = ''
     self.new_pass_check = ''
     f = open(self.path_password)
     try:
         self.password = f.read().strip()
     except IOError:
         print("Could not set password")
     finally:
         f.close()
Example #17
0
def main():
    """Main function"""

    print("START")
    keypad = Keypad()
    led_board = Led_board()
    kpc = KPC(keypad, led_board)
    fsm = FSM(kpc, keypad, led_board)
    fsm.add_rules()
    fsm.main_loop()
Example #18
0
 def __init__(self):
     self.keypad: Keypad = Keypad()
     self.led_board: LEDBoard = LEDBoard(keypad=self.keypad)
     self.password_path: str = "password.txt"
     self.override_signal: int or str or None = None
     self.password_buffer: str = ""
     self.password_buffer_old: str = ""
     self.current_signal = None
     self.led_id: int or None = None
     self.led_duration_sec: int or None = None
Example #19
0
    def __init__(self):
        print("[APP ] Initialized\n")
        self.d = Display()
        self.ds = DataStore()
        self.sett = AppSettings()
        self.keypad = Keypad()
        self.sensors = Sensors()
        self.lightc = LightController(self.ds, self.sett)
        self.condc = CondController(self.ds, self.sett)
        self.fanc = FanController(self.ds, self.sett)
        self.evc = EVController(self.ds, self.sett)
        self.screenMngr = ScreenManager(self.d, self.ds, self.sett,
                                        self.keypad)
        self.screenMngr.update()

        self.processStart = 0
        self.screensStart = 0
class AlarmClient:
    
    def __init__(self):
        self.keypad = Keypad()
        self.indicator = Indicator()
        self.server_interface = ServerInterface()
        self.command_code = None
        self.command_dictionary = {'1#': self.server_interface.arm_contacts, 
                                   '2':  self.server_interface.arm_all_sensors
        }


    def start(self):
        while not self.command_code in self.command_dictionary:
            print('a')
            self.command_code = self.keypad.get_command_code()
        print(self.command_code)
        print(self.command_dictionary[self.command_code])
        self.command_dictionary[self.command_code]()
Example #21
0
        soundfile_number(filename) for filename in os.listdir(audio_directory)
    ]
    if len(number) < max(len(number) for number in possible_numbers):
        return True
    return False


def invalid_dialplan(number):
    """Return True if number matches a forbidden sequence."""
    if number.startswith("0"): return True
    if "#" in number: return True
    if "*" in number: return True
    return False


keypad = Keypad(on_keydown)

hookswitch = Hookswitch(on_hook_up=on_handset_pickup,
                        on_hook_down=on_hangup,
                        pin=HOOKSWITCH_PIN)
hookswitch.run()

while (True):
    k = keypad.read_key()
    if (k == ''):
        log("key read cancelled")
        continue
    log(">> Key released => %s" % (k))
    if hookstate == Hookstate.OFF:
        tones.off()
    else:
Example #22
0
def go(operation='', field='chain', value='BTC'):
    import common
    from sram4 import viewfinder_buf
    print('2: Available RAM = {}'.format(gc.mem_free()))

    # Avalanche noise source
    from foundation import Noise
    common.noise = Noise()

    # Get the async event loop to pass in where needed
    common.loop = asyncio.get_event_loop()

    # System
    from foundation import System
    common.system = System()

    print('2.75: Available RAM = {}'.format(gc.mem_free()))
    # Initialize the keypad
    from keypad import Keypad
    common.keypad = Keypad()
    print('3: Available RAM = {}'.format(gc.mem_free()))

    # Initialize SD card
    from files import CardSlot
    CardSlot.setup()
    print('3.5: Available RAM = {}'.format(gc.mem_free()))

    # External SPI Flash
    from sflash import SPIFlash
    common.sf = SPIFlash()

    # Initialize NV settings
    from settings import Settings
    common.settings = Settings(common.loop)
    print('4: Available RAM = {}'.format(gc.mem_free()))

    # Initialize the display and show the splash screen
    from display import Display
    print("disp 1")
    common.dis = Display()
    print("disp 2")
    common.dis.set_brightness(common.settings.get('screen_brightness', 100))
    print("disp 3")
    common.dis.splash()
    print('5: Available RAM = {}'.format(gc.mem_free()))

    # Allocate buffers for camera
    from constants import VIEWFINDER_WIDTH, VIEWFINDER_HEIGHT, CAMERA_WIDTH, CAMERA_HEIGHT

    # QR buf is 1 byte per pixel grayscale
    import uctypes
    common.qr_buf = uctypes.bytearray_at(0x20000000,
                                         CAMERA_WIDTH * CAMERA_HEIGHT)
    # common.qr_buf = bytearray(CAMERA_WIDTH * CAMERA_HEIGHT)
    print('6: Available RAM = {}'.format(gc.mem_free()))

    # Viewfinder buf 1s 1 bit per pixel and we round the screen width up to 240
    # so it's a multiple of 8 bits.  The screen height of 303 minus 31 for the
    # header and 31 for the footer gives 241 pixels, which we round down to 240
    # to give one blank (white) line before the footer.
    common.viewfinder_buf = bytearray(
        (VIEWFINDER_WIDTH * VIEWFINDER_HEIGHT) // 8)
    print('7: Available RAM = {}'.format(gc.mem_free()))

    # Show REPL welcome message
    print("Passport by Foundation Devices Inc. (C) 2020.\n")

    print('8: Available RAM = {}'.format(gc.mem_free()))

    from foundation import SettingsFlash
    f = SettingsFlash()

    if operation == 'dump':
        print('Settings = {}'.format(common.settings.curr_dict))
        print('addr = {}'.format(common.settings.addr))
    elif operation == 'erase':
        f.erase()
    elif operation == 'set':
        common.settings.set(field, value)
    elif operation == 'stress':
        for f in range(35):
            print("Round {}:".format(f))
            print('  Settings = {}'.format(common.settings.curr_dict))
            common.settings.set('field_{}'.format(f), f)
            common.settings.save()

        print('\nFinal Settings = {}'.format(common.settings.curr_dict))

    # This "pa" object holds some state shared w/ bootloader about the PIN
    try:
        from pincodes import PinAttempt

        common.pa = PinAttempt()
        common.pa.setup(b'')
    except RuntimeError as e:
        print("Secure Element Problem: %r" % e)
    print('9: Available RAM = {}'.format(gc.mem_free()))

    # Setup the startup task
    common.loop.create_task(startup())

    run_loop()
Example #23
0
midi = MidiInput()
pg.display.init()

width = pg.display.Info().current_w
height = pg.display.Info().current_h
size = width, height

screen = pg.display.set_mode(size, pg.FULLSCREEN)
pg.mouse.set_visible(False)
background = (12, 12, 12)
screen.fill(background)
pg.display.update()

# inicjalizacja klawiatury
try:
    keypad = Keypad('img/piano.png', 'img/keys/', width, 24)
except:
    traceback.print_exc()
    exit = True

screen.blit(keypad, (keypad.offset, height - keypad.get_height()))
pg.display.update()

# rozpoczęcie działania
midi.start()

while not exit:
    for event in pg.event.get([pg.QUIT, pg.USEREVENT]):
        if event.type == pg.QUIT:
            exit = True
        elif event.type == pg.USEREVENT:
 def __init__(self):
     self.keypad = Keypad()
Example #25
0
		new_pin=pin_change['newpin']
		if pin.change_pin(config.decider_addr+config.door_name+'/change_pin',uid=uid,old_pin=old_pin,new_pin=new_pin):
			beep_door.ack()
		else:
			beep_door.nak()

ident_store=Identity_store()
door=Door(gpio(30),open_callback=on_door_open)
lock_control=lock_ctrl.Lock_ctrl(IO_open=gpio(95),IO_close=gpio(67),IO_latch=gpio(29))
lock_led=Edge_detect(gpio(23,active_low=True))
lock_led.start()

# set unused but connected gpios to output
gpio(66,'out')
gpio(68,'out')

keypad=Keypad(dev='/dev/ttyACM0',on_key=on_key)
keypad.start()

reader_door=NFCreader.NFCreader(dev='/dev/ttyS2',on_card=card_on_door)
reader_exit=NFCreader.NFCreader(dev='/dev/ttyS3',on_card=card_on_exit)
beep_door=beeper.Beeper(reader_door.beep)
beep_exit=beeper.Beeper(reader_exit.beep)

lock=Lock_behaviour(lock_control,door,lock_led,beep_exit)
decide=decider.Decider_http(addr=config.decider_addr+config.door_name+'/',opener=lock.open,closer=lock.close,ack=beep_door.ack,nak=beep_door.nak)

alarm=Message(addr=config.alarm_addr+config.door_name)
reader_exit.start()
reader_door.start()
Example #26
0
class KPC_Agent:

    def __init(self):
        self.fsm = FSM(self)
        self.keypad = Keypad()
        self.led = LEDboard()
        self.file_name = "passord.txt"
        self.password_buffer = ""
        self.override_signal = None
        self.led_id = 0
        self.led_duration = 0
        self.Legal_numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

    def init_passcode_entry(self):
        self.reset_agent()
        self.led.flash_LEDs()
        # flash

    def reset_agent(self):
        self.password_buffer = ""
        self.led_id = ""
        self.led_duration = ""
        self.override_signal = None

    def get_next_signal(self):
        if self.override_signal:
            result = self.override_signal
            self.override_signal = None
            return result
        else:
            return self.keypad.poll_buttons()

    def verify_login(self):
        if self.password_buffer == self.read_password(self.file_name): ##lese fra fil
            self.override_signal += "Y"
        else:
            self.override_signal+="N"
        self.init_passcode_entry()

    def add_next_digit(self, digit):
        if digit in self.Legal_numbers:
            self.password_buffer += digit

    def validate_password_change(self):
        validate = True
        if len(self.password_buffer)<4:
            validate = False
        for num in self.password_buffer:
            if num not in self.Legal_numbers:
                validate = False
        if validate:
            with open(self.file_name, "w+") as password_file:
                password_file.write(self.password_buffer)

    def read_password(self, file):
        with open(file) as password_file:
            password = password_file.read().strip()
            print(password)
            return password

    def light_one_led(self):
        self.led.lid_ldur(self.led_id, self.led_duration)

    def flash_leds(self):
        self.led.flash_LEDs()
Example #27
0
 def setUp(self):
     self.keypad = Keypad()
Example #28
0
import time
from keypad import Keypad

from machine import I2C, Pin
from pcf8574 import PCF8574

ADDR = 56
keymap = [
    '123A',
    '456B',
    '789C',
    '*0#D'
]
i2c = I2C(scl=Pin(5), sda=Pin(4), freq=40000000)
pcf = PCF8574(i2c, ADDR)
keypad = Keypad(pcf, keymap)

# print('rows cols = [{}, {}]'.format(keypad.rows, keypad.cols))
start = time.ticks_ms()
while time.ticks_diff(time.ticks_ms(), start) < 5000:
    key = keypad.getkey()
    if key is not None:
        print('Key pressed {}'.format(key))

del pcf
del i2c
del keypad
Example #29
0
from keypad import Keypad, Key
import time

from enum import IntEnum


class Mode(IntEnum):
    Teams = 0
    Sonos = 1
    Another = 2


keypad = Keypad(Mode)

actions = {
    Mode.Teams: {
        Key.KEY1: lambda: print("TK1"),
        Key.KEY2: lambda: print("TK2")
    },
    Mode.Sonos: {
        Key.KEY1: lambda: print("SK1"),
        Key.KEY3: lambda: print("TK3")
    }
}


def key_pressed(mode: Mode, key: Key):

    print("user defined")
    action = (actions.get(mode, {}).get(
        key, lambda: print(
Example #30
0
""" Continuously scan a Keypad Matrix and return the index of pressed key """
from keypad import Keypad
from time import sleep

LINES = ["X5", "X6", "X7", "X8"]
COLS = ["Y9", "Y10", "Y11", "Y12"]

k = Keypad(lines=LINES, cols=COLS)
while True:
    print(k.scan())
    sleep(0.5)
Example #31
0
 def __init__(self) -> None:
     self.keypad = Keypad()
     self.leds = LedDriver()
     self.override_signal = None
     self.entry_buffer = ""
     self.passcode = None
Example #32
0
class KpcAgent:
    """Keypad Controller Agent Class"""

    def __init__(self) -> None:
        self.keypad = Keypad()
        self.leds = LedDriver()
        self.override_signal = None
        self.entry_buffer = ""
        self.passcode = None

    def light_led(self, duration):
        """Light led from buffer"""
        led = int(self.entry_buffer)
        duration = int(duration)
        if 6 > led >= 0:
            self.light_one_led(led, duration)
        self.reset_buffer()

    def power_down(self):
        """Power down"""
        self.reset_buffer()
        self.leds.power_down()

    def wakeup(self):
        """Power up system"""
        self.leds.power_up()

    def reset_buffer(self):
        """Resets current entered passcode"""
        self.entry_buffer = ""

    def fsm_signal(self, signal):
        """Receive signal from FSM"""
        self.entry_buffer += signal

    def get_next_signal(self):
        """Get next signal from Keypad"""
        return_signal = None
        if self.override_signal:
            return_signal = self.override_signal
            self.override_signal = None
        else:
            return_signal = self.keypad.get_next_signal()
        return return_signal

    def verify_login(self):
        """Verify passcode"""
        print(self.entry_buffer)
        print(self.read_passcode())
        if self.entry_buffer == self.read_passcode():
            self.override_signal = "Y"
            self.twinkle_leds()
        else:
            self.override_signal = "N"
            self.flash_leds()
        self.entry_buffer = ""

    def validate_passcode_change(self):
        """Validate new passcode"""
        passcodes = self.entry_buffer.split('*')
        # if not re.search(r"[^\d]", self.passcode[0]):
        if passcodes[0] == passcodes[1] and len(passcodes[0]) >= 4:
            self.set_new_passcode(passcodes[0])
        else:
            self.twinkle_leds()
        self.reset_buffer()

    def set_new_passcode(self, new_passcode):
        """Sets new passcode"""
        with open('passcode.txt', 'w') as pass_file:
            pass_file.write(new_passcode)
            self.passcode = new_passcode

    def read_passcode(self):
        """Reads passcode from file"""
        if not self.passcode:
            with open('passcode.txt') as pass_file:
                self.passcode = pass_file.readline().strip()
        return self.passcode

    def light_one_led(self, led, duration):
        """Light specific LED"""
        self.leds.light_single(led, duration)

    def flash_leds(self):
        """Flash all LEDs"""
        self.leds.flash()

    def twinkle_leds(self):
        """Twinkle all LEDs"""
        self.leds.twinkle()

    def exit_action(self):
        """Power Down LEDs"""
        self.leds.power_down()
Example #33
0
    def __init__(self):
        self.rules = []
        self.state = fsm_states.INIT
        self.signal = None

        # Components:
        self.keypad = Keypad()
        self.ledboard = Ledboard()
        self.kpc = KPC(self.keypad, self.ledboard)

        # Setting up rules:
        # Init:
        self.add_rule(
            Rule(fsm_states.INIT, fsm_states.READ, any_signal,
                 self.kpc.init_password_entry))

        # Read:
        # On digits, simply add it to password
        self.add_rule(
            Rule(fsm_states.READ, fsm_states.READ, signal_is_digit,
                 self.kpc.add_signal_to_password_input))

        # On *, password is complete. Verify and write a overload signal to
        # memory
        self.add_rule(
            Rule(fsm_states.READ, fsm_states.VERIFY_READ, "*",
                 self.kpc.verify_login))
        # Else return to init
        self.add_rule(
            Rule(fsm_states.READ, fsm_states.INIT, any_signal,
                 self.kpc.reset_password_field))

        # Verify:
        # Verify password by getting a Y signal from the agent. Might change
        # action later?
        self.add_rule(
            Rule(fsm_states.VERIFY_READ, fsm_states.ACTIVE, "Y",
                 self.kpc.do_nothing))
        # ELse return to read
        self.add_rule(
            Rule(fsm_states.VERIFY_READ, fsm_states.INIT, any_signal,
                 self.kpc.reset_password_field))
        # TODO Er det ikke tilbake til init her? Er jo feil passord...

        # From Active to 1) SET_PW, 2) LED, 3) LOGOUT:
        change_password_button = 9
        # On ^this button, change state to set_pw
        self.add_rule(
            Rule(fsm_states.ACTIVE, fsm_states.SET_PW, change_password_button,
                 self.kpc.init_password_entry))
        # On a digit between 0 and 5, change state to LED and save which LED
        # that has been chosen
        self.add_rule(
            Rule(fsm_states.ACTIVE, fsm_states.LED,
                 signal_is_digit_between_0_and_5, self.kpc.set_led))
        # On "#", change state to logout
        self.add_rule(
            Rule(fsm_states.ACTIVE, fsm_states.LOGOUT, "#",
                 self.kpc.do_nothing))

        # 1) SET_PW:
        # On digit, add this to password        //TODO: HVORFOR TO HER?
        self.add_rule(
            Rule(fsm_states.SET_PW, fsm_states.SET_PW, signal_is_digit,
                 self.kpc.add_signal_to_password_input))
        self.add_rule(
            Rule(fsm_states.SET_PW, fsm_states.SET_PW, signal_is_digit,
                 self.kpc.add_signal_to_password_input))
        # On *, check if password is valid and write to memory if it is
        self.add_rule(
            Rule(fsm_states.SET_PW, fsm_states.VERIFY_PWCHANGE, "*",
                 self.kpc.verify_password_change))
        # Else, return to active    TODO: AGAIN STRANGE WITH THE ELSE-SENTENCE,
        # FROM METHOD IN KPC?
        self.add_rule(
            Rule(fsm_states.VERIFY_PWCHANGE, fsm_states.ACTIVE, any_signal,
                 self.kpc.do_nothing))

        # 2) LED:   TODO: ISNT LINE 74 UNNECESSARY, IS THE SAME IN LINE 59? BETTER WITH ADD_DURATION_DIGIT
        # On a digit between 0 and 5, change state to LED and save which LED
        # that has been chosen
        self.add_rule(
            Rule(fsm_states.LED, fsm_states.LED,
                 signal_is_digit_between_0_and_5, self.kpc.set_led))
        # On *, confirm LED TODO: MOST BE ADD_DURATION_DIGIT(SYMBOL) ON 74
        self.add_rule(
            Rule(fsm_states.LED, fsm_states.TIME, "*", self.kpc.do_nothing))

        # Time: TODO: JUST KIDDING, HERE IS TIME... BUT WHY THE DOUBLE UP OF SET_LED?
        # On digit, add that value to duration
        self.add_rule(
            Rule(fsm_states.TIME, fsm_states.TIME, signal_is_digit,
                 self.kpc.add_duration_digit))
        # On *, activate the chosen LED for the chosen amount of seconds
        self.add_rule(
            Rule(fsm_states.TIME, fsm_states.ACTIVE, "*",
                 self.kpc.activate_led))

        # Logout
        # On # logout completely and return to init phase
        self.add_rule(
            Rule(fsm_states.LOGOUT, fsm_states.INIT, "#",
                 self.kpc.power_down))  # CHANGED TO SHUTDOWN_FLASH HERE
        # Else, return to active TODO WHEN DOES THIS HAPPEN?
        self.add_rule(
            Rule(fsm_states.LOGOUT, fsm_states.LOGOUT, any_signal,
                 self.kpc.do_nothing))
Example #34
0
class ATM(object):
    'Represent an Automated Teller Machine'

    __userAuthenticated = False
    __currentAccountNumber = 0
    __screen = None
    __keypad = None
    __cashDispenser = None
    __depositSlot = None
    __bankDatabase = None

    __BALANCE_INQUIRY = 1
    __WITHDRAWAL = 2
    __DEPOSIT = 3
    __EXIT = 4

    def __init__(self):
        self.__userAuthenticated = False
        self.__currentAccountNumber = 0
        self.__screen = Screen()
        self.__keypad = Keypad()
        self.__cashDispenser = CashDispenser()
        self.__depositSlot = DepositSlot()
        self.__bankDatabase = BankDatabase()

    def run(self):
        while True:
            while not self.__userAuthenticated:
                self.__screen.displayMessageLine('\nWelcome!')
                self.__authenticateUser()
            self.__performTransactions()
            self.__userAuthenticated = False
            self.__currentAccountNumber = 0
            self.__screen.displayMessageLine('\nThank you! GoodBye!')

    def __authenticateUser(self):
        # self.__screen.displayMessage('\nPlease enter your account Number: ')
        accountNumber = self.__keypad.getInput(
            '\nPlease enter your account Number: ')
        # self.__screen.displayMessage('\nEnter your pin: ')
        pin = self.__keypad.getInput('\nEnter your pin: ')

        self.__userAuthenticated = self.__bankDatabase.authenticateUser(
            accountNumber, pin)
        if self.__userAuthenticated:
            self.__currentAccountNumber = accountNumber
        else:
            self.__screen.displayMessageLine(
                'Invalid account number or pin. Please Try again.')

    def __performTransactions(self):
        transaction = None
        userExited = False

        while not userExited:
            mainMenuSelection = self.__displayMainMenu()
            if self.__BALANCE_INQUIRY <= mainMenuSelection <= self.__DEPOSIT:
                transaction = self.createTransaction(mainMenuSelection)
                transaction.execute()
            elif mainMenuSelection == self.__EXIT:
                self.__screen.displayMessageLine('\nExiting the system...')
                userExited = True
            else:
                self.__screen.displayMessageLine(
                    '\nYou did not enter a valid selection. Try again.')

    def __displayMainMenu(self):
        self.__screen.displayMessageLine('\nMain menu:')
        self.__screen.displayMessageLine('1 - View my balance')
        self.__screen.displayMessageLine('2 - Withdraw cash')
        self.__screen.displayMessageLine('3 - Deposit funds')
        self.__screen.displayMessageLine('4 - Exit\n')
        # self.__screen.displayMessage('Enter a choice: ')
        return self.__keypad.getInput('Enter a choice: ')

    def createTransaction(self, type):
        transaction = None
        if type == self.__BALANCE_INQUIRY:
            transaction = BalanceInquiry(self.__currentAccountNumber,
                                         self.__screen, self.__bankDatabase)
        elif type == self.__WITHDRAWAL:
            transaction = Withdrawal(self.__currentAccountNumber, self.__screen, self.__bankDatabase, \
             self.__keypad, self.__cashDispenser)
        else:
            transaction = Deposit(self.__currentAccountNumber, self.__screen, self.__bankDatabase, \
             self.__keypad, self.__depositSlot)
        return transaction
    def __init__(self, pin: str = '123456'):
        # system starts disarmed, the '_' in front on the name indicates that this variable is supposed to be private
        # python does not have any other way to differentiate between public and private. This same annotation is also
        # used for private functions
        # The 'self' indicates that this variable is an instance variable much like 'this' is used in other languages.
        self.is_armed = False
        self.is_sensing = False  # is sensing is used to tell the system start looking for intruders
        # When arming a system, the system needs to give a delay in order to for the home owner to leave the house
        # without tripping the alarm system
        self._arm_time_delay = 5  # 1 * 60
        # setting to a default pin
        self._pin = pin
        self._user_pin_entry = ""
        self._user_first_key_entry_time = 0
        self._invalid_entry_count = 0

        # When user incorrectly enters in the pass code 4 times the system gets locked for 5min
        self.system_locked = False
        self._lock_time = 0
        self._lockout_duration = 10  # * 60  # currently set to 5 min but might consider less for testing
        self._pin_entry_max_timeout = 10  # Unit in seconds
        self._max_invalid_entry_before_system_lock = 4
        self.alarm_active = False

        # variable that tracks if a user modified the current state of the system
        # System needs to be running
        self._running = False
        # list to keep track of worker threads
        # DO NOT Create or start threads here!! Do it in the run method.
        self._threads = []

        # Setup logging for this module.
        self._logger = logging.getLogger('AlarmSystem')
        ch = logging.StreamHandler()
        ch.setLevel(logging.DEBUG)
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(threadName)s - %(levelname)s - %(message)s'
        )
        ch.setFormatter(formatter)
        self._logger.addHandler(ch)
        self._logger.setLevel(logging.DEBUG)
        # setting up tcp socket to receive
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        try:
            self._socket.bind(('127.0.0.1', 9090))
        except socket.error as e:
            self._logger.fatal('{}'.format(e))
            exit(1)

        # Create the sub system items that the main system will monitor and control
        self.keypad = Keypad()
        self.led = LED()
        self.event_queue = queue.Queue()
        # self.pir_sensor = PirSensor(self.event_queue)  # Turned off for now due to interference
        self.ultra_sonic_distance_sensor = UltraSonicDistanceSensor(
            self.event_queue)
        self.calendar = Calendar()
        self.watson = Watson()
        self.notifications = Notifications()

        # The web UI
        self._web_client = ui.create_app()
        self._web_process = Process(target=self._web_client.run,
                                    args=('0.0.0.0', 1234))