def __init__(self): print('Loading the ForkPi database...') self.db = ForkpiDB() print('Loading options...') attempt_limit = self.load_option('attempt_limit') lockout_time = self.load_option('lockout_time_minutes') self.lockout_table = LockoutTable(attempt_limit, lockout_time) self.keypad_timeout = self.load_option('keypad_timeout_seconds') self.max_transaction_time = self.load_option( 'max_transaction_time_seconds') self.lock_release_time = self.load_option('lock_release_time_seconds') print('Loading (F)ingerprint Scanner...') self.fingerprint_thread = FingerprintThread(lambda: ForkpiDB()) print('Loading (O)LED...') self.led = OLED() print('Loading (R)FID Reader...') self.rfid_thread = RfidThread() print('Loading (K)eypad...') self.keypad_thread = KeypadThread() print('Connecting to (dummy) door lock...') self.door_lock = DoorLock() # maps RFID UIDs to incorrect streak and remaining lockout time self.transaction_timer = self.new_timer() # start polling for cards and fingers self.rfid_thread.start() self.fingerprint_thread.start() self.keypad_thread.start()
def __init__(self, revision=1): # Connect to the display on /dev/i2c-1 self.dis = OLED(revision) Graphics.clearLine = self._clearLine Font.print_string = _print_string # Start communication self.dis.begin() # Start basic initialization self.dis.initialize() # Do additional configuration self.dis.set_memory_addressing_mode(0) self.dis.set_column_address(0, 127) # Eight pages self.dis.set_page_address(0, 7) self.dis.set_scan_direction(0) self.dis.set_inverse_display(False) # Black on white self.clear() self.stop_scroll() # Set font scale to 1 self.f = Font(1) return
def __init__(self): print('Loading the ForkPi database...') self.db = ForkpiDB() print('Loading options...') attempt_limit = self.load_option('attempt_limit') lockout_time = self.load_option('lockout_time_minutes') self.lockout_table = LockoutTable(attempt_limit, lockout_time) self.keypad_timeout = self.load_option('keypad_timeout_seconds') self.max_transaction_time = self.load_option('max_transaction_time_seconds') self.lock_release_time = self.load_option('lock_release_time_seconds') print('Loading (F)ingerprint Scanner...') self.fingerprint_thread = FingerprintThread(lambda: ForkpiDB()) print('Loading (O)LED...') self.led = OLED() print('Loading (R)FID Reader...') self.rfid_thread = RfidThread() print('Loading (K)eypad...') self.keypad_thread = KeypadThread() print('Connecting to (dummy) door lock...') self.door_lock = DoorLock() # maps RFID UIDs to incorrect streak and remaining lockout time self.transaction_timer = self.new_timer() # start polling for cards and fingers self.rfid_thread.start() self.fingerprint_thread.start() self.keypad_thread.start()
class Aplicacion(): def __init__(self): root = Tk() root.geometry('480x320') # root.configure(bg = BG_COLOR) root.title('Synth GUI') # root.attributes("-fullscreen", True) self.oled = OLED(root) #self.oled.pack(fill=X) self.oled.pack() frame = ttk.Frame(root) frame.pack(side=BOTTOM, fill=X) ttk.Button(frame, text='aux').pack(side=LEFT) ttk.Button(frame, text='up').pack(side=LEFT) ttk.Button(frame, text='down').pack(side=LEFT) ttk.Button(frame, text='sel').pack(side=LEFT) ttk.Button(frame, text='quit', command=root.destroy).pack(side=LEFT) try: # Create server server = liblo.ServerThread(4001) self.oled.add_osc_methods(server) # Register a fallback for unhandled messages server.add_method(None, None, self.fallback) # Start server server.start() except liblo.ServerError as err: print(err) sys.exit() root.mainloop() def fallback(self, path, args, types, src): print("got unknown message '%s' from '%s'" % (path, src.url)) for a, t in zip(args, types): print("argument of type '%s': %s" % (t, a))
def __init__(self): root = Tk() root.geometry('480x320') # root.configure(bg = BG_COLOR) root.title('Synth GUI') # root.attributes("-fullscreen", True) self.oled = OLED(root) #self.oled.pack(fill=X) self.oled.pack() frame = ttk.Frame(root) frame.pack(side=BOTTOM, fill=X) ttk.Button(frame, text='aux').pack(side=LEFT) ttk.Button(frame, text='up').pack(side=LEFT) ttk.Button(frame, text='down').pack(side=LEFT) ttk.Button(frame, text='sel').pack(side=LEFT) ttk.Button(frame, text='quit', command=root.destroy).pack(side=LEFT) try: # Create server server = liblo.ServerThread(4001) self.oled.add_osc_methods(server) # Register a fallback for unhandled messages server.add_method(None, None, self.fallback) # Start server server.start() except liblo.ServerError as err: print(err) sys.exit() root.mainloop()
class Oled: dis = None f = None # Font fontsize = 0 scale = 1 width = 20 lines = 4 scroll_line = 0 scroll_speed = 0.01 def __init__(self, revision=1): # Connect to the display on /dev/i2c-1 self.dis = OLED(revision) Graphics.clearLine = self._clearLine Font.print_string = _print_string # Start communication self.dis.begin() # Start basic initialization self.dis.initialize() # Do additional configuration self.dis.set_memory_addressing_mode(0) self.dis.set_column_address(0, 127) # Eight pages self.dis.set_page_address(0, 7) self.dis.set_scan_direction(0) self.dis.set_inverse_display(False) # Black on white self.clear() self.stop_scroll() # Set font scale to 1 self.f = Font(1) return # Clear display def clear(self, update=False): self.dis.clear(update) # Top display routine def out(self, line, text, interrupt): if len(text) > self.width: self._scroll(line, text, interrupt) else: self._out(line, text) return # Scroll line - interrupt() breaks out routine if True def _scroll(self, line, text, interrupt): ilen = len(text) skip = False # Display only for the width of the LCD self._out(line, text[0:self.width + 1], no_interrupt) self.dis.update() # Small delay before scrolling if not skip: for i in range(0, 10): time.sleep(self.scroll_speed) if interrupt(): skip = True break # Now scroll the message if not skip: for i in range(0, ilen - self.width + 1): self._out(line, text[i:i + self.width], interrupt) self.dis.update() if interrupt(): skip = True break else: time.sleep(self.scroll_speed) # Small delay before exiting if not skip: for i in range(0, 10): time.sleep(self.scroll_speed) if interrupt(): break return # Text out def _out(self, line_number, text="", interrupt=no_interrupt): self.clearLine(line_number) nChars = fontLineLengths[self.scale - 1] linePos = (line_number - 1) * 8 try: self.f.print_string(0, linePos, text[:nChars]) except Exception as e: print e print "Bad string", text # Update Oled screen def update(self): self.dis.update() # Smooth Olimex scroll def scroll(self, line): # Make horizontal scroll page = line * 2 - 2 self.scroll_line = line self._scroll(page) # Smooth scroll page (Only one at a time) def _smooth_scroll(self, page, speed=6): self.dis.deactivate_scroll() self.dis.vertical_and_horizontal_scroll_setup(self.dis.LEFT_SCROLL, page, page, speed, 0) #self.dis.horizontal_scroll_setup(self.dis.LEFT_SCROLL, page, page, speed) self.dis.activate_scroll() # Deactivate smooth scroll def stop_scroll(self): self.dis.deactivate_scroll() # Set font only if it is different from before def setFont(self, fontsize): if fontsize < 1: fontsize = 1 if fontsize > 9: fontsize = 9 if fontsize != self.scale: self.scale = int(fontsize) self.f = Font(self.scale) # Draw line def line(self, x0, y0, x1, y1): Graphics.draw_line(x0, y0, x1, y1) # Draw volume slider (1, 100) def drawHorizontalSlider(self, size, lineNumber): pos = ((lineNumber - 1) * 8) + 1 if size > 100: size = 100 elif size < 0: size = 0 width = int(127 * size / 100) self.clearPage(int(pos / 8)) for x in range(1, 6): self._clearLine(0, pos + x, 127, pos + x) Graphics.draw_line(0, pos + x, width, pos + x) self.drawRectangle(0, pos + 1, 127, pos + 6, False) self.dis.update() # Width and line parameters def getWidth(): return self.width def getLines(): return self.lines def setWidth(self, notused): return self.width # Has color def hasColor(self): return False # Clear line (Line 1 is double size font) def clearLine(self, line): page = (line - 1) self.clearPage(page) if line == 1: self.clearPage(page + 1) # This routine clears a page (0-7) def clearPage(self, page): x0 = 0 y0 = page * 8 x1 = 127 y1 = y0 for x in range(0, 8): Graphics.clearLine(x0, y0 + x, x1, y1) return # Clear text line Graphics class override def _clearLine(self, x0, y0, x1, y1): dx = x1 - x0 dy = y1 - y0 D = 2 * dy - dx Graphics.draw_pixel(x0, y0, on=False) y = y0 for x in range(x0 + 1, x1 + 1): if D > 0: y += 1 Graphics.draw_pixel(x, y, on=False) D += (2 * dy - 2 * dx) else: Graphics.draw_pixel(x, y, on=False) D += 2 * dy return # Set Scroll line speed - Best values are 0.05 and 1.0 # Limit to between 0.05 and 1.0 def setScrollSpeed(self, speed): if speed < 0.01: speed = 0.01 elif speed > 0.4: speed = 0.4 self.scroll_speed = speed return # Flip OLED display vertically def flip_display_vertically(self, flip): # flip is True or False if flip: self.dis.set_scan_direction(1) self.dis.set_segment_remap(remap=True) else: self.dis.set_scan_direction(0) self.dis.set_segment_remap(remap=False) return # Draw line def drawLine(self, x0, y0, x1, y1): self._draw_line(x0, y0, x1, y1) """ Alternative line routine using Bresenham's line algorithm. The Olimex draw_line routine is not working for vertical lines. See https://rosettacode.org/wiki/Bitmap/Bresenham%27s_line_algorithm#Python """ def _draw_line(self, x0, y0, x1, y1): dx = abs(x1 - x0) dy = abs(y1 - y0) x, y = x0, y0 sx = -1 if x0 > x1 else 1 sy = -1 if y0 > y1 else 1 if dx > dy: err = dx / 2.0 while x != x1: #self.set(x, y) Graphics.draw_pixel(x, y, True) err -= dy if err < 0: y += sy err += dx x += sx else: err = dy / 2.0 while y != y1: #self.set(x, y) Graphics.draw_pixel(x, y, True) err -= dx if err < 0: x += sx err += dy y += sy #self.set(x, y) Graphics.draw_pixel(x, y, True) # Draw rectangle def drawRectangle(self, x0, y0, x1, y1, fill): self._draw_line(x0, y0, x1, y0) # Top line self._draw_line(x0, y1, x1, y1) # Bottom line self._draw_line(x0, y0, x0, y1) # Left line self._draw_line(x1, y0, x1, y1) # Right line if fill: for i in range(1, y1 - y0): self._draw_line(x0, y0 + i, x1, y0 + i) # Draw Circle def drawCircle(self, x0, y0, r, fill): Graphics.draw_circle(x0, y0, r) if fill: for i in range(1, r): Graphics.draw_circle(x0, y0, i) # Draw image location at x,y def drawImage(self, bitmap, x, y): dir = os.path.dirname(__file__) img = Image.open(dir + '/' + bitmap) w = img.size[0] h = img.size[1] try: for i in range(0, w): for j in range(0, h): xy = (i, j) if img.getpixel(xy): Graphics.draw_pixel(i + x, j + y, False) else: Graphics.draw_pixel(i + x, j + y, True) except: pass def drawSplash(self, bitmap, delay): self.drawImage(bitmap, 35, 0) self.dis.update() time.sleep(delay) self.clear() return
LED_BLUE = 27 def btn_press(channel): print('button pressed') def btn_hold(channel): print('button held') def btn_release(channel): print('button released') oled = OLED() rgb = RGBLED(LED_RED, LED_GREEM, LED_BLUE) btn = Button(BTN_PIN_GROUNDED, debounce_time=0.2, on_press=btn_press, on_hold=btn_hold, on_release=btn_release, hold_repeat=True) print('Waiting for button press. Testing button press.') oled.display(['TESTING', 'Press Button', 'TESTING']) btn.wait_for_release() print('Waiting for button hold. Testing button hold.') oled.display(['TESTING', 'Hold Button', 'TESTING']) btn.wait_for_release()
# task3a.py import time from machine import Pin from oled import OLED from rotary_irq_esp import RotaryIRQ oled = OLED() oled.init_display() r = RotaryIRQ(pin_num_clk=23, pin_num_dt=19, min_val=-100, max_val=100, reverse=True, range_mode=RotaryIRQ.RANGE_BOUNDED) val_old = r.value() while True: val_new = r.value() if val_old != val_new: val_old = val_new oled.draw_text(32, 32, "{:4d}".format(val_new), size=2, space=2) oled.display() time.sleep_ms(20)
class UPS: def __init__(self): self.bat = Battery() self.pisys = Pisys() self.oled = OLED() self.key = Key(self.keyCallback, self.shutdown) self.haha = 1 def getTime(self): time = datetime.datetime.now() time = time.strftime('%m/%d %H:%M:%S') return time def show1(self): self.oled.drawRectangle() self.oled.drawText(line=0, str='Time:' + self.getTime()) self.oled.drawText(line=8, str='IP:' + self.pisys.getIP()) self.oled.drawText(line=16, str=self.pisys.getMemUsage()) self.oled.drawText(line=25, str=self.pisys.getDisk()) self.oled.display() def show2(self): self.oled.drawRectangle() self.oled.drawText(line=0, str='Time:' + self.getTime()) self.oled.drawText(line=8, str='CPUTemp:%.2f' % self.pisys.getCpuTemp()) self.oled.drawText(line=16, str=self.pisys.getCPULoad()) self.oled.drawText(line=25, str='Vbat:%.2fV' % self.bat.getVoltage()) self.oled.display() def shutdown(self): self.oled.drawRectangle() self.oled.drawText(line=0, str='Time:' + self.getTime()) self.oled.drawText(line=8, str='Shutdown....') self.oled.display() time.sleep(3) self.oled.clear() os.system('sudo shutdown now') os._exit() def shutdown_lowbat(self): self.oled.drawRectangle() self.oled.drawText(line=0, str='Time:' + self.getTime()) self.oled.drawText(line=8, str='Low battery') self.oled.drawText(line=16, str='Shutdown....') self.oled.display() time.sleep(3) self.oled.clear() os.system('sudo shutdown now') os._exit() def keyCallback(*arg): # self.keyEvent(arg[1]) global whichShow if arg[1] == 1: #tap whichShow = whichShow + 1 if whichShow > 2: whichShow = 1 elif arg[1] == 2: #long press arg[2]() while True: pass
def __init__(self): self.bat = Battery() self.pisys = Pisys() self.oled = OLED() self.key = Key(self.keyCallback, self.shutdown) self.haha = 1
elif map_screen_to_name( active_screen_num ) == 'restart_screen' and hold_disp_ticks > get_screen_hold_action_time( active_screen_num): logging.info(f'Restart hold time reached') oled.display(['Restarting', 'Raspberry Pi', 'Now']) subprocess.Popen('sudo reboot now', shell=True) time.sleep(1) # wait so the shutdown screen stays while processing cmd # *** END BUTTON FUNCTIONS *** rgb = RGBLED(LED_RED, LED_GREEM, LED_BLUE) rgb.set_colour('green') oled = OLED() btn = Button(BTN_PIN_GROUNDED, debounce_time=0.2, on_press=btn_press, on_hold=btn_hold, on_release=btn_release, hold_repeat=True) def main(): global needs_update, active_screen_num try: while True: try: # Constantly check for screen update
import httplib #Son para el display from oled import OLED from oled import Font from oled import Graphics def internet_off(): conn = httplib.HTTPConnection("www.google.com") try: conn.request("HEAD", "/") return False except: return True dis = OLED(1) # Start display dis.begin() # Start basic initialization dis.initialize() # Do additional configuration dis.set_memory_addressing_mode(0) dis.set_column_address(0, 127) dis.set_page_address(0, 7) while True: sensorth = 4 gas_sensor = 1
def main(): try: # init UDP socket UDP_IP = '' # recieve from all IPs UDP_PORT = 8008 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT)) print('Bind UDP socket on %d' % UDP_PORT) # init control object for OLED display oled = OLED(rst=24, i2c_addr=0x3C) oled.on() # turn on display # set font face and size """ for font face you can use the path of your ttf file(just with name if in current dir) or you can use truetype fonts in /usr/share/fonts/truetype """ oled.set_text_style('FreeMono.ttf', fontsize=20, position=(10, 10)) print('OLED init finished') # --- recieve loop --- while True: data, addr = sock.recvfrom(1024) oled.display_text(data) # display text on OLED except KeyboardInterrupt: print('\nKeyboardInterrupt, exit') oled.off() # turn off display exit(0) finally: # turn off display oled = OLED(rst=24, i2c_addr=0x3C) oled.off() exit(0)
from oled import OLED # load oled module from flash memory oled = OLED() # Instantiate an OLED object oled.poweron() oled.init_display() # initialise the OLED display # Simple Hello world message oled.draw_text(0, 0, 'Hello World!') # each character is 6x8 pixels oled.display() # flush display# Write your code here :-)
from time import time, sleep from random import randint, choice from gpiozero import RGBLED, Button, Buzzer from colorzero import Color from exercise import Exercise from challenge import Challenge from all_activities import exercises from oled import OLED #define inputs and outputs led = RGBLED(red=17, green=27, blue=22) button = Button(4, pull_up=False) buzzer = Buzzer(18) oled = OLED() oled.clear_image() ''' Cycle through different modes using button. Hold button down for more than 2 seconds and the LED will turn green and the displayed mode will be selected. NORMAL - regular minute timing LIGHTNING - reduces minutes into seconds for fast activity draw Called from main and result passed into generate_rand_time ''' def select_mode(): select = False modes = ["LIGHTNING", "NORMAL"]
from wlan_manager import wifi from utils import * ## https://github.com/loboris/MicroPython_ESP32_psRAM_LoBo/tree/master/MicroPython_BUILD/components/micropython/esp32/modules ## https://github.com/peterhinch/micropython-async/blob/master/TUTORIAL.md#71-why-scheduling ## https://github.com/peterhinch/Micropython-scheduler ## https://github.com/micropython/micropython/tree/master/ports/esp32/modules def printD(message, end='\n'): if settings.DEBUG: print(message, end=end) oled = OLED() oled.welcome() wlan = wifi(debug=settings.DEBUG) wlan.static_network(ip='192.168.0.111', gateway='192.168.0.1') if not wlan.do_connect(settings.WLAN_SSID, settings.WLAN_PASSWD): printD("Could not initialize the network connection.") oled.clear() oled.text("Could not initialize network.", 0, 5) wlan.access_point(password=settings.WLAN_AP_PASS, authmode=3) oled.clear() oled.text("WLAN IP", 0, 5) oled.text(str(wlan.ipadd), 0, 15)
class SpoonPi: def __init__(self): print('Loading the ForkPi database...') self.db = ForkpiDB() print('Loading options...') attempt_limit = self.load_option('attempt_limit') lockout_time = self.load_option('lockout_time_minutes') self.lockout_table = LockoutTable(attempt_limit, lockout_time) self.keypad_timeout = self.load_option('keypad_timeout_seconds') self.max_transaction_time = self.load_option( 'max_transaction_time_seconds') self.lock_release_time = self.load_option('lock_release_time_seconds') print('Loading (F)ingerprint Scanner...') self.fingerprint_thread = FingerprintThread(lambda: ForkpiDB()) print('Loading (O)LED...') self.led = OLED() print('Loading (R)FID Reader...') self.rfid_thread = RfidThread() print('Loading (K)eypad...') self.keypad_thread = KeypadThread() print('Connecting to (dummy) door lock...') self.door_lock = DoorLock() # maps RFID UIDs to incorrect streak and remaining lockout time self.transaction_timer = self.new_timer() # start polling for cards and fingers self.rfid_thread.start() self.fingerprint_thread.start() self.keypad_thread.start() def new_timer(self): # ends a pending transaction after a timer if the current self.factors are not enough to be authenticated # call the function `deny_then_end_transaction` after `max_transaction_time` seconds have elapsed return Timer(self.max_transaction_time, self.deny_then_end_transaction, kwargs={'reason': 'insufficient credentials'}) def load_option(self, name): value, default = self.db.fetch_option(name) if value.isdigit() and value != default: print(' custom : {} = {}'.format(name, value)) return int(value) else: print(' default: {} = {}'.format(name, default)) return int(default) def allow_access(self, names, *args, **kwargs): assert len(args) == 0 if 'pin' in kwargs.keys(): # convert pin to asterisks so pin is not exposed in the logs kwargs['pin'] = '*' * len(kwargs['pin']) names = ', '.join(names) print("> Allowed %s" % names) self.db.log_allowed(names=names, **kwargs) self.door_lock.unlock() self.led.clear_then_puts("Access\n granted") time.sleep(self.lock_release_time) self.door_lock.lock() def deny_access(self, reason, led_message="Access\n denied", *args, **kwargs): assert len(args) == 0 print("> %s" % led_message.replace('\n ', ' '), kwargs) self.db.log_denied(reason=reason, **kwargs) self.led.clear_then_puts(led_message) time.sleep(0.5) def single_factor_authentication(self, *args, **kwargs): assert len(args) == 0 assert len(kwargs.keys()) == 1 is_authorized, names = self.db.authenticate(pin='', **kwargs) if is_authorized: self.allow_access(names=names, pin='', **kwargs) return is_authorized def two_factor_authentication(self, *args, **kwargs): assert len(args) == 0 assert len(kwargs) == 2 use_lockout_table = False if 'pin' in kwargs and 'rfid_uid' in kwargs: use_lockout_table = True if use_lockout_table: rfid_uid = kwargs['rfid_uid'] is_locked_out, time_left = self.lockout_table.get_lockout(rfid_uid) if is_locked_out: self.deny_access(reason="locked out", led_message="Locked out\n for %sm" % time_left, **kwargs) return False is_authorized, names = self.db.authenticate(**kwargs) if is_authorized: self.allow_access(names=names, **kwargs) if use_lockout_table: self.lockout_table.reset_streak(rfid_uid) else: self.deny_access(reason='invalid key pair', **kwargs) if use_lockout_table: self.lockout_table.failed_attempt(rfid_uid) return is_authorized def pin_authentication(self): ''' Returns (pin, timeout) where pin = the pin entered (string) timeout = whether the keypad timed out (boolean) ''' pin = '' self.led.clear_then_puts("Enter PIN:\n") # First key that triggered this pin authentication key = self.keypad_thread.get_key() while True: if key is None: # timed out! return pin, True elif key.isdigit(): pin += str(key) self.led.puts('*') elif key == '*': # backspace pin = pin[:-1] self.led.puts('\b') elif key == '#': # enter return pin, False key = self.keypad_thread.getch(timeout=self.keypad_timeout) def start_transaction_timer(self): self.transaction_timer = self.new_timer() self.transaction_timer.start() def stop_transaction_timer(self): self.transaction_timer.cancel() def deny_then_end_transaction(self, reason): self.deny_access(reason=reason, **self.factors) self.end_transaction() def end_transaction(self): self.is_transacting = False self.stop_transaction_timer() def new_transaction(self): self.is_transacting = True self.factors = dict() self.led.clear_then_puts("Swipe, scan,\nor push key") self.rfid_thread.start_polling() self.fingerprint_thread.start_polling() self.keypad_thread.start_polling() while self.is_transacting: if self.rfid_thread.tag_swiped: self.stop_transaction_timer() self.rfid_thread.stop_polling() self.factors['rfid_uid'] = self.rfid_thread.get_rfid_uid() self.lockout_table.update_timers() if self.single_factor_authentication( rfid_uid=self.factors['rfid_uid']): # single factor succeeded; end transaction self.end_transaction() elif len(self.factors) == 1: # single factor failed; wait for another factor self.led.clear_then_puts("RFID tag\n swiped!") self.start_transaction_timer() else: # len(self.factors) == 2 self.two_factor_authentication(**self.factors) self.end_transaction() elif self.fingerprint_thread.finger_scanned: self.stop_transaction_timer() self.fingerprint_thread.stop_polling() self.factors[ 'fingerprint_matches'] = self.fingerprint_thread.get_matches( ) if self.single_factor_authentication( fingerprint_matches=self.factors['fingerprint_matches'] ): # single factor succeeded; end transaction self.end_transaction() elif len(self.factors) == 1: # single factor failed; wait for another factor self.led.clear_then_puts("Finger\n scanned!") self.start_transaction_timer() else: # len(self.factors) == 2 self.two_factor_authentication(**self.factors) self.end_transaction() elif self.keypad_thread.key_pressed: self.stop_transaction_timer() self.keypad_thread.stop_polling() self.factors['pin'], timed_out = self.pin_authentication() if timed_out: self.deny_then_end_transaction(reason='keypad timeout') # pin was entered correctly elif len(self.factors) == 1: # wait for another factor self.led.clear_then_puts("PIN\n entered!") self.start_transaction_timer() else: # len(self.factors) == 2 self.stop_transaction_timer() self.two_factor_authentication(**self.factors) self.end_transaction()
bitmap = 'bitmaps/raspberry-pi-logo.bmp' # Draw image location at x,y def drawImage(bitmap, x, y): img = Image.open(bitmap) w = img.size[0] h = img.size[1] try: for i in range(0, w): for j in range(0, h): xy = (i, j) if img.getpixel(xy): Graphics.draw_pixel(i + x, j + y, False) else: Graphics.draw_pixel(i + x, j + y, True) except: pass # Initialize library. dis = OLED(1) dis.begin() # Clear display. dis.clear() drawImage(bitmap, 35, 0) dis.update() sys.exit(0)
class SpoonPi: def __init__(self): print('Loading the ForkPi database...') self.db = ForkpiDB() print('Loading options...') attempt_limit = self.load_option('attempt_limit') lockout_time = self.load_option('lockout_time_minutes') self.lockout_table = LockoutTable(attempt_limit, lockout_time) self.keypad_timeout = self.load_option('keypad_timeout_seconds') self.max_transaction_time = self.load_option('max_transaction_time_seconds') self.lock_release_time = self.load_option('lock_release_time_seconds') print('Loading (F)ingerprint Scanner...') self.fingerprint_thread = FingerprintThread(lambda: ForkpiDB()) print('Loading (O)LED...') self.led = OLED() print('Loading (R)FID Reader...') self.rfid_thread = RfidThread() print('Loading (K)eypad...') self.keypad_thread = KeypadThread() print('Connecting to (dummy) door lock...') self.door_lock = DoorLock() # maps RFID UIDs to incorrect streak and remaining lockout time self.transaction_timer = self.new_timer() # start polling for cards and fingers self.rfid_thread.start() self.fingerprint_thread.start() self.keypad_thread.start() def new_timer(self): # ends a pending transaction after a timer if the current self.factors are not enough to be authenticated # call the function `deny_then_end_transaction` after `max_transaction_time` seconds have elapsed return Timer(self.max_transaction_time, self.deny_then_end_transaction, kwargs={'reason':'insufficient credentials'}) def load_option(self, name): value, default = self.db.fetch_option(name) if value.isdigit() and value != default: print(' custom : {} = {}'.format(name, value)) return int(value) else: print(' default: {} = {}'.format(name, default)) return int(default) def allow_access(self, names, *args, **kwargs): assert len(args) == 0 if 'pin' in kwargs.keys(): # convert pin to asterisks so pin is not exposed in the logs kwargs['pin'] = '*' * len(kwargs['pin']) names = ', '.join(names) print("> Allowed %s" % names) self.db.log_allowed(names=names, **kwargs) self.door_lock.unlock() self.led.clear_then_puts("Access\n granted") time.sleep(self.lock_release_time) self.door_lock.lock() def deny_access(self, reason, led_message="Access\n denied", *args, **kwargs): assert len(args) == 0 print("> %s" % led_message.replace('\n ', ' '), kwargs) self.db.log_denied(reason=reason, **kwargs) self.led.clear_then_puts(led_message) time.sleep(0.5) def single_factor_authentication(self, *args, **kwargs): assert len(args) == 0 assert len(kwargs.keys()) == 1 is_authorized, names = self.db.authenticate(pin='', **kwargs) if is_authorized: self.allow_access(names=names, pin='', **kwargs) return is_authorized def two_factor_authentication(self, *args, **kwargs): assert len(args) == 0 assert len(kwargs) == 2 use_lockout_table = False if 'pin' in kwargs and 'rfid_uid' in kwargs: use_lockout_table = True if use_lockout_table: rfid_uid = kwargs['rfid_uid'] is_locked_out, time_left = self.lockout_table.get_lockout(rfid_uid) if is_locked_out: self.deny_access( reason="locked out", led_message="Locked out\n for %sm" % time_left, **kwargs ) return False is_authorized, names = self.db.authenticate(**kwargs) if is_authorized: self.allow_access(names=names, **kwargs) if use_lockout_table: self.lockout_table.reset_streak(rfid_uid) else: self.deny_access(reason='invalid key pair', **kwargs) if use_lockout_table: self.lockout_table.failed_attempt(rfid_uid) return is_authorized def pin_authentication(self): ''' Returns (pin, timeout) where pin = the pin entered (string) timeout = whether the keypad timed out (boolean) ''' pin = '' self.led.clear_then_puts("Enter PIN:\n") # First key that triggered this pin authentication key = self.keypad_thread.get_key() while True: if key is None: # timed out! return pin, True elif key.isdigit(): pin += str(key) self.led.puts('*') elif key == '*': # backspace pin = pin[:-1] self.led.puts('\b') elif key == '#': # enter return pin, False key = self.keypad_thread.getch(timeout=self.keypad_timeout) def start_transaction_timer(self): self.transaction_timer = self.new_timer() self.transaction_timer.start() def stop_transaction_timer(self): self.transaction_timer.cancel() def deny_then_end_transaction(self, reason): self.deny_access(reason=reason, **self.factors) self.end_transaction() def end_transaction(self): self.is_transacting = False self.stop_transaction_timer() def new_transaction(self): self.is_transacting = True self.factors = dict() self.led.clear_then_puts("Swipe, scan,\nor push key") self.rfid_thread.start_polling() self.fingerprint_thread.start_polling() self.keypad_thread.start_polling() while self.is_transacting: if self.rfid_thread.tag_swiped: self.stop_transaction_timer() self.rfid_thread.stop_polling() self.factors['rfid_uid'] = self.rfid_thread.get_rfid_uid() self.lockout_table.update_timers() if self.single_factor_authentication(rfid_uid=self.factors['rfid_uid']): # single factor succeeded; end transaction self.end_transaction() elif len(self.factors) == 1: # single factor failed; wait for another factor self.led.clear_then_puts("RFID tag\n swiped!") self.start_transaction_timer() else: # len(self.factors) == 2 self.two_factor_authentication(**self.factors) self.end_transaction() elif self.fingerprint_thread.finger_scanned: self.stop_transaction_timer() self.fingerprint_thread.stop_polling() self.factors['fingerprint_matches'] = self.fingerprint_thread.get_matches() if self.single_factor_authentication(fingerprint_matches=self.factors['fingerprint_matches']): # single factor succeeded; end transaction self.end_transaction() elif len(self.factors) == 1: # single factor failed; wait for another factor self.led.clear_then_puts("Finger\n scanned!") self.start_transaction_timer() else: # len(self.factors) == 2 self.two_factor_authentication(**self.factors) self.end_transaction() elif self.keypad_thread.key_pressed: self.stop_transaction_timer() self.keypad_thread.stop_polling() self.factors['pin'], timed_out = self.pin_authentication() if timed_out: self.deny_then_end_transaction(reason='keypad timeout') # pin was entered correctly elif len(self.factors) == 1: # wait for another factor self.led.clear_then_puts("PIN\n entered!") self.start_transaction_timer() else: # len(self.factors) == 2 self.stop_transaction_timer() self.two_factor_authentication(**self.factors) self.end_transaction()
from oled import OLED from oled import Font from oled import Graphics # Connect to the display on /dev/i2c-0 dis = OLED(0) # Start communication dis.begin() # Start basic initialization dis.initialize() # Do additional configuration dis.set_memory_addressing_mode(0) dis.set_column_address(0, 127) dis.set_page_address(0, 7) # Clear display dis.clear() # Set font scale x2 f = Font(2) # Print some large text f.print_string(6, 0, "OLIMEX LTD") # Change font to 5x7 f.scale = 1 f.print_string(0, 24, "MOD-OLED-128x64") f.print_string(0, 32, "olimex.com")
from oled import OLED from oled import Graphics from PIL import Image import sys # Connect to the display on /dev/i2c-1 dis = OLED(1) # Start communication dis.begin() # Start basic initialization dis.initialize() # Do additional configuration dis.set_memory_addressing_mode(0) dis.set_column_address(0, 127) dis.set_page_address(0, 7) # Clear display dis.clear() files = [ "CLOWN1.BMP", "CLOWN2.BMP", "CLOWN3.BMP", "CLOWN4.BMP", "CLOWN5.BMP", "CLOWN6.BMP", "CLOWN7.BMP", "CLOWN8.BMP" ] while True: for file in files: img = Image.open("clowns/" + file)