コード例 #1
0
ファイル: ButtonOff.py プロジェクト: molorane/smarthome
class ButtonOff(threading.Thread):
    def __init__(self, btnID):
        threading.Thread.__init__(self)
        self.lcd = LCD()
        self.dName = 'Button-Press'
        self.btnID = btnID
        GPIO.setup(self.btnID, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    def run(self):
        while True:
            if not GPIO.input(self.btnID):
                threading.Thread(target=self.beep).start()
                str = "Btn On Pressed!"
                self.lcd.print(str)
                print(str)
                threading.Thread(target=self.offOutSideLights).start()
                time.sleep(0.2)

    def buzzerOff(self):
        pin = 16
        GPIO.setup(pin, GPIO.OUT)
        GPIO.output(pin, False)
        self.updateStatus(0, 60)

    def offOutSideLights(self):
        conn = ConnectionDB()
        data = conn.getAllOutSideLights()
        devices = []
        for app in data:
            devices.append(app['conn_d_id'])

        macros = MacroCommand(devices, 'off', self.lcd, 'system')
        macros.execute()
コード例 #2
0
def sessie(hall=AH3661(26)):
    GPIO.setup(18, GPIO.OUT)
    while True:
        global stop
        stop = False

        uid, found = serialReadBadgeID()  # get BadgeID
        correctuid = datatodb.correct_badgeID(uid)  #  Check badgeID

        if found is True and correctuid is True:
            init_speed_distance()  # Standard values on LCD
            buzzer(True)  # when badged, buzz

            datatodb.create_session(uid,
                                    datetime.datetime.now())  # Create session

            hall.create_event()  # create event

            uid2, stop = serialReadBadgeID()  # get badgeID
            correctuid2 = datatodb.correct_badgeID(uid2)  # Check badgeID
            if found is stop and correctuid2 is True:
                buzzer(True)  # when badged, buzz

                eind = datetime.datetime.now()
                print("sessie is gedaan")
                datatodb.save_session(eind, round(hall.distance, 2))
                hall.remove_event()  # delete session
                lcd = LCD()
                lcd.stuur_instructie(1)
                break
        else:
            buzzer(False)  # when badged, buzz
            pass
コード例 #3
0
class Microprocessor(Receiver):
    in_0 = KeyboardPanel()
    out_0 = LCD()
    out_1 = Bell()
    out_2 = Lock()

    def __init__(self):
        self.olh = OpenLockHandler(self)
        self.clh = ClosedLockHandler(self)

        self.pkh = PassKeyHandler(self)
        self.ckh = CtrlKeyHandler(self)

        self.pkch = PassKeyChangeHandler(self)

        self.cbh = CallButtonHandler(self)
        self.pkah = PassKeyAcceptHandler(self.pkh, self)
        self.ckah = PassKeyAcceptHandler(self.ckh, self)

        self.cbh.set_next(self.clh).set_next(self.pkh).set_next(
            self.olh).set_next(self.ckh).set_next(self.ckh).set_next(self.pkch)

    def receive_signal(self, signal):
        signal = self.in_0.invoke()
        self.cbh.handle(signal)
        self.out_0.receive_signal(signal)

    def procedure(self):
        self.out_2.receive_signal(None)
        print(f"Lock: {self.out_2.state.info}")
コード例 #4
0
    def __init__(self):
        ''' Initialization code '''
        self.busy = False
        self.masterMode = False

        #Initialize system components
        self.rfidReader = RFIDReader()
        self.keypad = Keypad()
        self.lcd = LCD()
        self.doorLatch = DoorLatch()
        self.database = Database()

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.server_address = ('192.168.43.206', 8888)
        self.socket.bind(self.server_address)

        self.correct_pin = self.database.getCorrectPin()
        self.entered_pin = ""
コード例 #5
0
ファイル: WeatherStation.py プロジェクト: aznashwan/pi-sense
    def __init__(self, confpath="./example.conf"):
        """
            Instantiates a WeatherStation object and all of its individual
            components.

            @param: confpath - absolute path to configuration file.
                default = "./example.conf"
        """
        self.mode = None
        self.warnings = None
        self.params = {}
        self.leds = []
        self.ledpins = {}
        self.sensorpins = {}

        # read through the config file
        try:
            os.stat(confpath)
            self.__parseconfig(confpath)
        except FileNotFoundError:
            print("Config file %r not found." % confpath)
            sys.exit(-1)
        except AssertionError as e:
            print("The config file is missing the following sections: ", e)
            sys.exit(-1)
        except Exception as e:
            print("Error has occured whilst accessing config file:")
            print(e)
            sys.exit(-1)

        # set warnings
        gpio.setwarnings(self.warnings)

        # instantiate all components
        self.lcd = LCD(self.mode)
        self.sensor = SHT11(self.sensorpins["data"], self.sensorpins["clock"],
                self.mode)

        self.status_led = LED(self.ledpins["green"], self.mode)
        self.temperature_led = LED(self.ledpins["red"], self.mode)
        self.humidity_led = LED(self.ledpins["yellow"], self.mode)
        self.query_led = LED(self.ledpins["blue"], self.mode)
        self.leds = [self.status_led, self.temperature_led, self.humidity_led,
                self.query_led]

        # blink all LEDs
        for led in self.leds:
            led.blink(0.3)

        # write status to the screen
        self.__lcd_write("WEATHERSTATION", "OPERATIONAL")
コード例 #6
0
    def __init__(self, test=False):
        logging.getLogger().setLevel(logging.INFO)
        logging.info("Starting")

        if not test:
            from LCD import LCD
            from Reader import Reader
            from Keypad import Keypad

            self.lcd = LCD()
            self.reader = Reader()
            self.keypad = Keypad()
        else:
            from testLCD import TestLCD
            from testReader import TestReader
            from testKeypad import TestKeypad

            self.lcd = TestLCD()
            self.reader = TestReader()
            self.keypad = TestKeypad()
コード例 #7
0
ファイル: Keypad.py プロジェクト: bsparacino/badax-xbee
  def __init__(self, database):  
    self.pins = [RaspberryPi.GPIO0,
                 RaspberryPi.GPIO1,
                 RaspberryPi.GPIO2,
                 RaspberryPi.GPIO3,
                 RaspberryPi.GPIO4,
                 RaspberryPi.GPIO5,
                 RaspberryPi.GPIO6]
    self.active = 0
    pin0 = {RaspberryPi.GPIO1: '2',
            RaspberryPi.GPIO6: '5',
            RaspberryPi.GPIO5: '8',
            RaspberryPi.GPIO3: '0'}
    pin2 = {RaspberryPi.GPIO1: '1',
            RaspberryPi.GPIO6: '4',
            RaspberryPi.GPIO5: '7',
            RaspberryPi.GPIO3: '*'}
    pin4 = {RaspberryPi.GPIO1: '3',
            RaspberryPi.GPIO6: '6',
            RaspberryPi.GPIO5: '9',
            RaspberryPi.GPIO3: '#'}
    self.lookup = {RaspberryPi.GPIO0: pin0,
                   RaspberryPi.GPIO2: pin2,
                   RaspberryPi.GPIO4: pin4}
    self.message = ''
    self.password = ''
    self.typePassword = 0
      
    for i in range(3):
      GPIO.setup(self.pins[::2][i], GPIO.OUT, initial=GPIO.LOW)
      GPIO.setup(self.pins[1::2][i], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(self.pins[6], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    self.buzzer = Buzzer()
    self.lcd = LCD()
    self.database = database

    self.setup_callbacks()
    self.loop()
コード例 #8
0
def toon_start_info(lcd=LCD()):
    initLCD()
    lcd.stuur_tekst("Programma wordt gestart")
    time.sleep(2)

    lcd.stuur_instructie(1)
    lcd.stuur_tekst("IP adres wordt getoond in 3")
    time.sleep(1)

    lcd.stuur_instructie(0x4B | 0b10000000)
    lcd.stuur_tekst("2")
    time.sleep(1)

    lcd.stuur_instructie(0x4B | 0b10000000)
    lcd.stuur_tekst("1")
    time.sleep(1)

    lcd.stuur_instructie(1)
    lcd.stuur_tekst(str(get_ip_address()))  # Toon ip address op scherm
    time.sleep(5)

    lcd.stuur_instructie(1)
コード例 #9
0
#!/usr/bin/python

# https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_CharLCD

from LCD import LCD
from subprocess import * 
from time import sleep, strftime
from datetime import datetime

lcd = LCD()

cmd = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1"

lcd.begin(16,1)

def run_cmd(cmd):
        p = Popen(cmd, shell=True, stdout=PIPE)
        output = p.communicate()[0]
        return output.split('\n')[0]

while 1:
    lcd.clear()
    ipaddr = run_cmd(cmd)
    lcd.message(datetime.now().strftime('%b %d  %H:%M:%S\n'))
    lcd.message('IP %s' % ( ipaddr ) )
    sleep(1)
コード例 #10
0
ファイル: display-temp.py プロジェクト: kingkingyyk/PiTemp
import time
import requests
from LCD import LCD

URL = 'http://localhost:8000'
LCD_ADDRESS = 0x27
lcd = LCD(2, LCD_ADDRESS, True)
lcd.clear()
counter = 0

while True:
    try:
        data = requests.get(URL).json()
        temp_text = '{:.1f}C'.format(data['temperature'])
        hum_text = '{:.1f}%'.format(data['humidity'])
        counter = (counter + 1) % 11
        temp_c = 0
        while temp_c < counter:
            temp_text = ' '+temp_text
            hum_text = ' '+hum_text
            temp_c += 1
        lcd.clear()
        lcd.message(temp_text, 1)
        lcd.message(hum_text, 2)
    except:
        lcd.clear()
        lcd.message("Service", 1)
        lcd.message("Unavailable", 2)
    time.sleep(3)
コード例 #11
0
ファイル: WeatherStation.py プロジェクト: aznashwan/pi-sense
class WeatherStation(object):
    """
        Control class for the entire hardware setup.
        Contains:
            - 16x2 LCD
            - temperature & humidity sensor
            - green LED to indicate station is operational
            - blue LED to indicate sensors are currently being queried
            - red LED to indicate extreme temperature readings
            - yellow LED to indicate extreme humidity readings

        Example usage:
        >>> from WeatherStation import WeatherStation
        >>>
        >>> # for details about the config file, see "example.conf"
        >>> ws = WeatherStation("/absolute/path/to/config/file.conf")
        >>> ws.monitor(run_time=3600, frequency=5)
    """

    def __init__(self, confpath="./example.conf"):
        """
            Instantiates a WeatherStation object and all of its individual
            components.

            @param: confpath - absolute path to configuration file.
                default = "./example.conf"
        """
        self.mode = None
        self.warnings = None
        self.params = {}
        self.leds = []
        self.ledpins = {}
        self.sensorpins = {}

        # read through the config file
        try:
            os.stat(confpath)
            self.__parseconfig(confpath)
        except FileNotFoundError:
            print("Config file %r not found." % confpath)
            sys.exit(-1)
        except AssertionError as e:
            print("The config file is missing the following sections: ", e)
            sys.exit(-1)
        except Exception as e:
            print("Error has occured whilst accessing config file:")
            print(e)
            sys.exit(-1)

        # set warnings
        gpio.setwarnings(self.warnings)

        # instantiate all components
        self.lcd = LCD(self.mode)
        self.sensor = SHT11(self.sensorpins["data"], self.sensorpins["clock"],
                self.mode)

        self.status_led = LED(self.ledpins["green"], self.mode)
        self.temperature_led = LED(self.ledpins["red"], self.mode)
        self.humidity_led = LED(self.ledpins["yellow"], self.mode)
        self.query_led = LED(self.ledpins["blue"], self.mode)
        self.leds = [self.status_led, self.temperature_led, self.humidity_led,
                self.query_led]

        # blink all LEDs
        for led in self.leds:
            led.blink(0.3)

        # write status to the screen
        self.__lcd_write("WEATHERSTATION", "OPERATIONAL")


    def __parseconfig(self, confpath):
        """
            Parses the config file, registering all found values.
            In case a paricular value is not present, a fallback is provided.

            @param: confpath - path to the configuration file

            @return: none
        """
        parser = ConfigParser()
        parser.read(confpath)

        # check if all required sections are present:
        sections = parser.sections()
        expected = ["General", "Parameters", "Sensor", "LEDs"]
        assert sections >= expected, "%r" % expected - sections

        # get operations mode
        mode = parser["General"]["MODE"]
        if mode.lower() == "board":
            self.mode = gpio.BOARD
        else:
            self.mode = gpio.BCM

        # get warnings setting
        self.warnings = parser.getboolean("General", "WARNINGS", fallback=False)

        # get operational parameters
        parameters = parser["Parameters"]
        self.params["maxt"] = parameters.getfloat("MAX_TEMP", fallback=40.0)
        self.params["mint"] = parameters.getfloat("MIN_TEMP", fallback=20.0)
        self.params["maxh"] = parameters.getfloat("MAX_HUMID", fallback=70.0)
        self.params["minh"] = parameters.getfloat("MIN_HUMID", fallback=30.0)

        # get sensor pins
        sensorpins = parser["Sensor"]
        self.sensorpins["data"] = sensorpins.getint("DATA", fallback=27)
        self.sensorpins["clock"] = sensorpins.getint("CLOCK", fallback=4)

        # get led pins
        ledpins = parser["LEDs"]
        self.ledpins["green"] = ledpins.getint("GREEN", fallback=12)
        self.ledpins["red"] = ledpins.getint("RED", fallback=19)
        self.ledpins["yellow"] = ledpins.getint("YELLOW", fallback=20)
        self.ledpins["blue"] = ledpins.getint("BLUE", fallback=21)


    def monitor(self, run_time=600, frequency=1):
        """
            Lights the appropriate LEDs and displays the result on the LCD for
            a given ammount of time and at a specified frequency.

            @param run_time: Time to run in seconds.

            @param frequency: The frequency at which the update occurs.

            @return: None
        """
        self.status_led.on()

        start_time = time.time()
        end_time = start_time + run_time

        while time.time() <= end_time:
            # query the sensor
            self.query_led.on()
            try:
                temperature = self.sensor.temperature()
                humidity = self.sensor.humidity(temperature)
            except Exception:
                self.sensor.reset()
                time.sleep(1)
                continue
            self.query_led.off()

            # trigger appropriate LEDs
            self.__trigger_leds(humidity, temperature)

            # write values on the LCD
            self.__lcd_write("%.2f %s" % (temperature, "(C)"),
                    "%.2f %s" % (humidity, "(RH%)"))

            time.sleep(frequency)

        self.clear()
        self.__lcd_write("WEATHERSTATION", "OPERATIONAL")


    def __lcd_write(self, line1="", line2=""):
        """
            Centers and writes the two lines to the LCD.

            @param: line1 - what to write on the first line of the LCD.

            @param: line2 - what to write on the second line of the LCD.

            @return: None
        """
        self.lcd.writeline(line1.center(self.lcd.SCREENWIDTH, " "), line=1)
        self.lcd.writeline(line2.center(self.lcd.SCREENWIDTH, " "), line=2)


    def __trigger_leds(self, humidity, temperature):
        """
            Lights up the LEDs based on the current status.

            @param: humidity - current humidity reading.

            @param: temperature - current temperature reading.

            @return: None
        """

        if self.params["minh"] > humidity or self.params["maxh"] < humidity:
            self.humidity_led.on()
        else:
            self.humidity_led.off()

        if self.params["mint"] > temperature or self.params["maxt"] < temperature:
            self.temperature_led.on()
        else:
            self.temperature_led.off()


    def clear(self):
        """
            Turns off all LED's, clear the LCD, set sensor to idle.

            @param: None

            @return: None
        """
        for led in self.leds:
            led.off()

        self.sensor.reset()

        self.lcd.clear()


    def cleanup(self):
        """
            Turn off associated LED's, clear the LCD, cleanup all pins.
            This method is meant to be called after the instance of
            WeatherStation has done its job and is no longer required.
            After this method is called, this instance of WeatherStation is
            rendered useless.

            @param: None

            @return: None
        """
        self.clear()
        gpio.cleanup()
コード例 #12
0
ファイル: display.py プロジェクト: sandlbn/mpd_display
from LCD import LCD
from mpd import MPDClient
import time
import random

DISP_LEN = 20
lcd = LCD()  # params available for rPi revision, I2C Address, and backlight on/off
# lcd = LCD(2, 0x3F, True)

client = MPDClient()
client.connect("localhost", 6600)


def display_long_text(from_ch, txt):
    return txt[from_ch:]


def display_text(txt, prev_pos=0):
    if len(txt) > DISP_LEN:
        if prev_pos == 0:
            return display_long_text(prev_pos, txt), prev_pos+1
        elif DISP_LEN-1 == (len(txt)-prev_pos):
            return display_long_text(prev_pos, txt), 0
        else:
            return display_long_text(prev_pos, txt), prev_pos+1
    else:
        return txt, 0


def parse_audio(audio):
    d = audio.split(":")
コード例 #13
0
#!/usr/bin/python

# https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_CharLCD

from LCD import LCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime

lcd = LCD()

cmd = "ip addr show wlan0 | grep inet | awk '{print $2}' | cut -d/ -f1"

lcd.begin(16, 1)


def run_cmd(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    output = p.communicate()[0]
    return output.split('\n')[0]


while 1:
    lcd.clear()
    ipaddr = run_cmd(cmd)
    lcd.message(datetime.now().strftime('%b %d  %H:%M:%S\n'))
    lcd.message('IP %s' % (ipaddr))
    sleep(1)
コード例 #14
0
ファイル: tak.py プロジェクト: aike/20000YearsOrgel
        print light


# on Close Box
def suspend(number):
    global saved_number
    if number != saved_number:
        f = open('datafile.txt', 'w')
        f.write(str(number))
        saved_number = number
        f.close()


# on PowerON
def resume():
    num = 0
    try:
        f = open('datafile.txt', 'r')
        num = int(f.read())
        f.close()
    except:
        num = 0
    return num


tsl = TSL2561()
lcd = LCD()
start_number = resume()
target = liblo.Address('127.0.0.1', 12000)
tak(17, 10, 0)
コード例 #15
0
class SmartDoorLockSystem:
    ''' Smart Door Lock System Logic '''
    def __init__(self):
        ''' Initialization code '''
        self.busy = False
        self.masterMode = False

        #Initialize system components
        self.rfidReader = RFIDReader()
        self.keypad = Keypad()
        self.lcd = LCD()
        self.doorLatch = DoorLatch()
        self.database = Database()

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.server_address = ('192.168.43.206', 8888)
        self.socket.bind(self.server_address)

        self.correct_pin = self.database.getCorrectPin()
        self.entered_pin = ""

    def listen_for_messages(self):
        """
		Listen for incoming UDP messages

		Parameters
	    	----------
	    	None
		
		Returns
	    	-------
	    	None
		"""
        #Listen for incoming UDP messages and proces them accordingly using the enum defined in UDP.py
        while True:
            buf, address = self.socket.recvfrom(2048)
            if len(buf):
                UDP.processMessage(buf, self.doorLatch)

    def updateDoorStatusInApp(self):
        """
		Send a UDP message of the current doorState to the app on every iteration

		Parameters
	    	----------
	    	None
		
		Returns
	    	-------
	    	None
		"""
        #Setup the target of the UDP messages and the send the current door state
        host = "192.168.43.1"
        port = 8888
        target_address = (host, port)
        data = self.doorLatch.status
        self.socket.sendto(data.encode('utf-8'), target_address)

    def main(self):
        #Create a new thread to always listen for UDP messages
        t = Thread(target=self.listen_for_messages)
        t.daemon = True
        t.start()

        #Infinite Loop
        while True:
            #
            # RFID LOGIC
            #
            if (
                    self.busy != True
            ):  #self.busy variable is needed to prevent the logic loop from breaking
                #Scan for an RFID card every iteration
                tagID = self.rfidReader.grab_rfid_data()

                #If the tagID returned was nothing (no tag was scanned)
                if (tagID[0] != ""):  #tagID is a tuple
                    self.busy = True

                    #If a master tag was scanned, switch between normal mode and master mode
                    if (self.database.isMasterTag(tagID[0])):
                        if (self.masterMode):
                            self.lcd.setText('')
                            self.masterMode = False
                            time.sleep(1)
                        else:
                            self.lcd.setText('MASTER MODE')
                            self.masterMode = True
                            time.sleep(1)
                    #If a normal tag was scanned
                    else:
                        #If in master mode
                        if (self.masterMode):
                            #Remove the tag from the database if found
                            if (self.database.isTagInDatabase(tagID[0])):
                                if (self.database.removeTagFromDatabase(
                                        tagID[0])):
                                    self.lcd.setText('TAG DEACTIVATED', 2)
                                else:
                                    self.lcd.setText(
                                        'FAILED TO \nDEACTIVATE TAG', 2)
                            #Add the tag to the database if not found
                            else:
                                if (self.database.addTagToDatabase(tagID[0])):
                                    self.lcd.setText('TAG ACTIVATED', 2)
                                else:
                                    self.lcd.setText(
                                        'FAILED TO \nACTIVATE TAG', 2)
                        #If in normal mode
                        else:
                            #If the tag is in the database, unlock the door
                            if self.database.isTagInDatabase(tagID[0]):
                                self.doorLatch.unlockDoor()
                                self.lcd.setText('ACCESS GRANTED', 2)
                                time.sleep(3)
                                self.doorLatch.lockDoor()
                            #If the tag is NOT in the database, log the failed entry
                            else:
                                self.lcd.setText('ACCESS DENIED', 2)
                                self.database.logFailedAccess()
                #
                # KEYPAD LOGIC
                #

                #If a key was pressed on the keypad
                if (self.keypad.lastKeyPressed != ""):
                    self.busy = True
                    #Append the key to the pin being entered
                    self.entered_pin = self.entered_pin + self.keypad.lastKeyPressed
                    self.lcd.setText(self.entered_pin)

                    #Cancel pin entry if the '#' button is pressed on the keypad
                    if ((self.keypad.lastKeyPressed == '#')):
                        self.lcd.setText("Cancelled PIN \nEntry", 2)
                        self.entered_pin = ""
                        self.keypad.lastKeyPressed = ""

                    #If the '*' key is pressed, submit the entered keycode
                    if ((self.keypad.lastKeyPressed == '*')):
                        #If the entered pin is of the correct length
                        if ((len(self.entered_pin) - 1) == len(
                                self.correct_pin)):
                            #If the user entered the correct pin
                            if (self.entered_pin[:-1] == self.correct_pin):
                                #Update the system state
                                self.doorLatch.unlockDoor()
                                self.lcd.setText("ACCESS GRANTED", 2)
                                time.sleep(3)
                                self.doorLatch.lockDoor()
                                self.entered_pin = ""
                                self.keypad.lastKeyPressed = ""
                            #If the user entered the incorrect pin
                            else:
                                #Update the system state, and log the failed entry
                                self.lcd.setText("ACCESS DENIED", 2)
                                self.database.logFailedAccess()
                                self.entered_pin = ""
                                self.keypad.lastKeyPressed = ""
                        #If the user entered pin is longer than the correct pin
                        else:
                            self.lcd.setText("Invalid PIN \nFormat", 2)
                            self.entered_pin = ""
                            self.keypad.lastKeyPressed = ""

                    #If the user entered pin is shorter than the correct pin
                    elif (len(self.entered_pin) > len(self.correct_pin)):
                        #Flash LED
                        self.lcd.setText("Invalid PIN \nFormat", 2)
                        self.entered_pin = ""
                        self.keypad.lastKeyPressed = ""

                    #Clear the lastKeyPressed on every iteration
                    self.keypad.lastKeyPressed = ""

                #If the physical unlock button is pressed, update the system state
                if (Button.isUnlockButtonPressed()
                        and (self.doorLatch.status == "LOCKED")):
                    self.doorLatch.unlockDoor()
                    self.lcd.setText("DOOR UNLOCKED", 1)
                    self.entered_pin = ""
                    self.keypad.lastKeyPressed = ""

                #If the physical lock button is pressed, update the system state
                if (Button.isLockButtonPressed()
                        and (self.doorLatch.status == "UNLOCKED")):
                    self.doorLatch.lockDoor()
                    self.lcd.setText("DOOR LOCKED", 1)
                    self.entered_pin = ""
                    self.keypad.lastKeyPressed = ""

                #Flush the serial input on every iteration, to prevent a tag from being read multiple times
                self.rfidReader.ser.flushInput()
                #Reset the busy state to False
                self.busy = False

                #If in master mode, clearly display that this is the case
                if (self.masterMode):
                    self.lcd.setText('MASTER MODE')

                #Update the door status in app
                self.updateDoorStatusInApp()
コード例 #16
0
ファイル: spotipi.py プロジェクト: Phid/SpotiPi
#!/usr/bin/python

from LCD import LCD
from subprocess import *
from time import sleep, strftime
from datetime import datetime
from threading import Thread
import RPi.GPIO as GPIO
import urllib3
import threading
import signal 
import os
import sys

GPIO.setwarnings(0)
lcd = LCD()
lcd.begin(16,1)

class SpotiPi:
	keeprunning = True
	oldsong = ""
	songname = ""
	artist = ""
	ip = "192.168.1.4"
	http = urllib3.PoolManager()
	printit = 0
	lock = threading.RLock()
	def printSong(self):
		while(1):
			if self.keeprunning == True:
				with self.lock:
コード例 #17
0
ファイル: Infoscreen.py プロジェクト: Maerim/Infoscreen
def main():

	# create objects
	myLCD = LCD(CS1=17, CS2=7, E=15, RS=14, D0=27, D1=23, D2=24, D3=25, D4=8, D5=11, D6=9, D7=22, PWM=1) #PWM pin number is wiringPi numbering!
	myAM2302 = AM2302(pin=4)
	myCalendar = GoogleCalendar()

	# set the initial backlight flag
	if isNight():
		backlightNightFlag = 1
		myLCD.setBacklightPWM(BACKLIGHT_NIGHT_VALUE)
	else:
		backlightNightFlag = 0
		myLCD.setBacklightPWM(BACKLIGHT_DAY_VALUE)

	

	last_update = datetime.datetime.now() - datetime.timedelta(seconds=UPDATE_FREQUENCY_BUS)
	while(True):
	
		# dim backlight if its night
		if isNight():
			if backlightNightFlag == 0:
				backlightNightFlag = 1
				myLCD.setBacklightPWM(BACKLIGHT_NIGHT_VALUE)
		elif backlightNightFlag == 1:
			backlightNightFlag = 0
			myLCD.setBacklightPWM(BACKLIGHT_DAY_VALUE)
	 	
	 	
	 	# update bus/temp only every n secs
		if 	(datetime.datetime.now() - last_update).seconds >= UPDATE_FREQUENCY_BUS:
			# get bus
			next_bus_dict = get_next_bus()
			
			
			# update calendar data
			events = myCalendar.get_events()
			if len(events) > 1: # only display next 2 events
				running_string = events[0] + ' - ' + events[1]
			elif len(events) == 0: 
				running_string = 'No events scheduled'
			else: # only 1 event
				running_string = events[0]
			running_string_2 = running_string + ' - ' + running_string # double string to make it easier for running it over the screen
			running_index = 0
			
			display_next_buses(myLCD, next_bus_dict)
			
			temp, hum = myAM2302.get_data()
			display_room_climate_data(myLCD, temp, hum)
			log_room_climate_data('/home/pi/Infoscreen/room_climate.log', temp, hum)
			
			
			last_update = datetime.datetime.now()

		# print the running text for the calendar
		currently_displayed_string = running_string_2[running_index:running_index+16]
		myLCD.printString(currently_displayed_string,7)
		if running_index == len(running_string) + 2: #2=3-1, 3= number of characters in separator (' - ')
			running_index = 0
		else:
			running_index += 1

		sleep(0.3)
コード例 #18
0
ファイル: Infoscreen.py プロジェクト: Maerim/Infoscreen
def display_next_buses(LCD, bus_dict):
	for i in range(len(bus_dict['busNr'])):
		line_to_display = bus_dict['busNr'][i] + ': ' + bus_dict['timeToNextBus'][i] + ' min (' + bus_dict['delay'][i] + ')'
		LCD.printString(line_to_display, i)
コード例 #19
0
 def show_on_lcd(self):
     lcd = LCD()
     lcd.stuur_instructie(0x0C | 0b10000000)
     lcd.stuur_tekst(str(round(self.speed, 2)))
     lcd.stuur_instructie(0x4C | 0b10000000)
     lcd.stuur_tekst(str(round(self.distance, 2)))
     lcd.stuur_instructie(12)
コード例 #20
0
def initLCD(lcd=LCD()):
    lcd.stuur_instructie(56)  # 8-bit, 2 lines, character font 5x10
    lcd.stuur_instructie(12)  # display aan, cursor uit, cursor blink uit
    lcd.stuur_instructie(1)  # clear display en cursor home
コード例 #21
0
def init_speed_distance(lcd=LCD()):
    lcd.stuur_tekst("Snelheid:")
    lcd.stuur_instructie(0x40 | 0b10000000)
    lcd.stuur_tekst("Afstand:")
    lcd.stuur_instructie(12)
コード例 #22
0
ファイル: main.py プロジェクト: madmaddi/raspi-sensorkit
dht11Pin = 14
dht22Pin = 15

relaisPinOpen = 17
relaisPinClose = 27

ledPinRed = 23
ledPinGreen = 24

d11 = DHTSensor(dht11Pin, 'DHT11', True)
d22 = DHTSensor(dht22Pin, 'DHT22', True)

windowOpen = Relais(relaisPinOpen, 5)
windowClose = Relais(relaisPinClose, 5)

lcd = LCD()
ledRed = LED(ledPinRed)
ledGreen = LED(ledPinGreen)

dispatcher = Dispatcher(d11, d22, ledRed, ledGreen, lcd, windowOpen, windowClose, True)

#button = Button()
#button.run()

try:

    while True:
        dispatcher.main()
        time.sleep(delay)

except KeyboardInterrupt:
コード例 #23
0
ファイル: dht11test.py プロジェクト: r0se000/iot_Finalproject
import Adafruit_DHT
import sys, time
import MySQLdb
from blink import LED
from LCD import LCD
import warnings

warnings.filterwarnings("ignore")
db = MySQLdb.connect("localhost", "mine", "secret", "finalproject")
cur = db.cursor()
sensor = Adafruit_DHT.DHT11
pin = 4
id = 1
mid = 'r1'

while True:
    humid, temp = Adafruit_DHT.read_retry(sensor, pin)
    if humid is not None and temp is not None:
        print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temp, humid))
        LED(humid)
        time.sleep(5)
        now = time.strftime('%Y-%m-%d %H:%M:%S')
        cur.execute('insert into datain values(%s, %s, %s, %s, %s)',
                    (mid, temp, humid, now, id))
        db.commit()
        LCD(db)

    else:
        print('Failed to get reading. Try again!')
コード例 #24
0
ファイル: Infoscreen.py プロジェクト: Maerim/Infoscreen
def display_room_climate_data(LCD, temp, hum):
	LCD.printString('Temp: ' + str(round(temp,1)) + ' øC',4)
	LCD.printString('Hum:	 ' + str(round(hum,1)) + ' %',5)
コード例 #25
0
 def display1(self, str):
     lcd = LCD()
     lcd.print(str)
     del lcd
コード例 #26
0
ファイル: buttons.py プロジェクト: bsparacino/badax-xbee
    def start(self):

        # change these as desired - they're the pins connected from the
        # SPI port on the ADC to the Cobbler
        SPICLK = RaspberryPi.SPI_CE1          #CLK
        SPIMISO = RaspberryPi.SPI_CE0        #DOUT
        SPIMOSI = RaspberryPi.SPI_SCLK        #DIN
        SPICS = RaspberryPi.SPI_MISO        #CS

         
        # set up the SPI interface pins
        GPIO.setup(SPIMOSI, GPIO.OUT)
        GPIO.setup(SPIMISO, GPIO.IN)
        GPIO.setup(SPICLK, GPIO.OUT)
        GPIO.setup(SPICS, GPIO.OUT)
         
        # 10k trim pot connected to adc #0
        potentiometer_adc = 0;
         
        last_read = 0       # this keeps track of the last potentiometer value
        tolerance = 5       # to keep from being jittery we'll only change
                            # volume when the pot has moved more than 5 'counts'

        buzzer = Buzzer()
        lcd = LCD() 
        lcd.Blink()
        printed = False
        try:
            while True:
                # we'll assume that the pot didn't move
                trim_pot_changed = False
         
                # read the analog pin
                trim_pot = self.readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
                # how much has it changed since the last read?
                pot_adjust = abs(trim_pot - last_read)
         
                if DEBUG:
                        print "trim_pot:", trim_pot
                        print "pot_adjust:", pot_adjust
                        print "last_read", last_read
         
                if ( pot_adjust > tolerance ):
                       trim_pot_changed = True
         
                if DEBUG:
                        print "trim_pot_changed", trim_pot_changed
         
                if ( trim_pot_changed ):
                        value = trim_pot / 10.24           # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level
                        value = round(value)          # round out decimal value
                        value = int(value)            # cast volume as integer
                number = '';
                printedNumber = ''
                released = False
                if ( value != 60):
                    if (value >= 75 and value < 80):
                        number ='1'
                    elif (value >= 69 and value < 74):
                        number ='2'
                    elif (value >= 64 and value <= 70):
                        number ='3'
                    elif (value >= 0 and value <= 12):
                        number ='4'
                    elif (value >= 32 and value <= 37):
                        number ='5'
                    elif (value >= 38 and value <= 44):
                        number ='6'
                    elif (value >= 21 and value <= 26):
                        number ='7'
                    elif (value >= 83 and value <= 90):
                        number ='8'
                    elif (value >= 45 and value <= 51):
                        number ='9'
                    elif (value >= 54 and value <= 59):
                        number ='*'
                    elif (value >= 94 and value <= 100):
                        number ='0'
                    elif (value >= 50 and value <= 53):
                        number ='#'
                    else:
                        print "Dunno: ", value   
                
                if (value == 60):
                     released = True
                     printed = False

                if(number != printedNumber and not printed):
                    printedNumber = number
                    print number, value
                    lcd.message(number)
                    buzzer.beep(659, 125)
                    printed = True
                    time.sleep(0.1)

                    if(number == '*'):
                        self.typePassword = 1
                        self.password = ''
                    elif(number == '#' and self.typePassword == 1):
                        lcd.noBlink()
                        self.typePassword = 0
                        user = self.database.check_login(self.password)
                        print user

                        sleep_time = 1

                        if(user != 'Invalid Code'):
                            sleep_time = 5
                            self.led.show_status_light = 1
                            
                            system_status = self.database.system_status()
                            if(system_status == '1'):
                                self.sp.stop_timer()
                                self.sp.soundingAlarm = 0
                                self.database.system_disarm()
                                message = 'User '+user['first_name']+' '+user['last_name']+' disarmed the system'
                                print message
                                self.database.log(message)

                                print user['first_name']+' '+user['last_name']
                                user = '******'+user['first_name']+' '+user['last_name']
                            else:
                                self.database.system_arm()
                                user = user['first_name']+' '+user['last_name']+'\nArmed The System'
                                self.database.log(user)

                        time.sleep(0.5)
                        lcd.clear()
                        lcd.message(user)
                        self.message = ''
                        time.sleep(sleep_time)
                        lcd.clear()
                        lcd.Blink()
                    if(self.password == '1111'):
                        print 'play mario'
                        mario_thread = threading.Thread(target=self.play_song(),)
                        print 'die mario'
                        mario_thread.start()
                    elif(self.typePassword == 1):
                        if(number != '*'):
                            self.password += number

                time.sleep(0.01)
        except KeyboardInterrupt:
              GPIO.cleanup()
              print "\nKill"
コード例 #27
0
 def display2(self, str1, str2):
     lcd = LCD()
     lcd.printB(str1, str2)
     del lcd
コード例 #28
0
ファイル: web.py プロジェクト: speccy88/FlaskWebcam
# -*- coding: utf-8 -*-
from flask import Flask, render_template, request, jsonify
from LCD import LCD
import subprocess
import os

app = Flask(__name__)
lcd = LCD()
lcd.init(C=False, B=False)
lcd.clear()


@app.route("/")
def Index():
    return render_template("index.html")


@app.route("/api/LCD")
def _writeLCD():
    data = request.args
    lcd.clear()
    for i in range(4):
        lcd.moveLine(i)
        lcd.writeText(data["line" + str(i + 1)])
    subprocess.call(["fswebcam", "/home/pi/FlaskLCD/static/out.jpg"])
    return jsonify(data="success")


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000, debug=True)
コード例 #29
0
ファイル: Keypad.py プロジェクト: bsparacino/badax-xbee
class Keypad:
  
  def __init__(self, database):  
    self.pins = [RaspberryPi.GPIO0,
                 RaspberryPi.GPIO1,
                 RaspberryPi.GPIO2,
                 RaspberryPi.GPIO3,
                 RaspberryPi.GPIO4,
                 RaspberryPi.GPIO5,
                 RaspberryPi.GPIO6]
    self.active = 0
    pin0 = {RaspberryPi.GPIO1: '2',
            RaspberryPi.GPIO6: '5',
            RaspberryPi.GPIO5: '8',
            RaspberryPi.GPIO3: '0'}
    pin2 = {RaspberryPi.GPIO1: '1',
            RaspberryPi.GPIO6: '4',
            RaspberryPi.GPIO5: '7',
            RaspberryPi.GPIO3: '*'}
    pin4 = {RaspberryPi.GPIO1: '3',
            RaspberryPi.GPIO6: '6',
            RaspberryPi.GPIO5: '9',
            RaspberryPi.GPIO3: '#'}
    self.lookup = {RaspberryPi.GPIO0: pin0,
                   RaspberryPi.GPIO2: pin2,
                   RaspberryPi.GPIO4: pin4}
    self.message = ''
    self.password = ''
    self.typePassword = 0
      
    for i in range(3):
      GPIO.setup(self.pins[::2][i], GPIO.OUT, initial=GPIO.LOW)
      GPIO.setup(self.pins[1::2][i], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    GPIO.setup(self.pins[6], GPIO.IN, pull_up_down=GPIO.PUD_DOWN)

    self.buzzer = Buzzer()
    self.lcd = LCD()
    self.database = database

    self.setup_callbacks()
    self.loop()

  def setup_callbacks(self):
    for i in range(3):
      GPIO.add_event_detect(self.pins[1::2][i], GPIO.RISING,
                            callback=self.callback, bouncetime=200)
    GPIO.add_event_detect(self.pins[6], GPIO.RISING,
                          callback=self.callback, bouncetime=200)

  def callback(self, channel):
    if (GPIO.input(channel)):
      char = self.lookup[self.active][channel]
     #self.buzzer.beep(659, 125)
      print 'PRESS: ', char
      self.message += char
      self.lcd.clear()
      self.lcd.message(self.message)

      if(char == '*'):
        self.typePassword = 1
        self.password = ''
      elif(char == '#' and self.typePassword == 1):
        self.typePassword = 0
        user = self.database.check_login(self.password)
        sleep(0.5)
        self.lcd.clear()
        self.lcd.message(user)
        self.message = ''
        
        sleep(3)
        self.lcd.clear()
      elif(self.typePassword == 1):
        self.password += char

  def loop(self):
    while True:
      for i in range(3):
        self.active = self.pins[::2][i]
        GPIO.output(self.active, True)
        sleep(0.01)
        GPIO.output(self.active, False)
コード例 #30
0
ファイル: ButtonOff.py プロジェクト: molorane/smarthome
 def __init__(self, btnID):
     threading.Thread.__init__(self)
     self.lcd = LCD()
     self.dName = 'Button-Press'
     self.btnID = btnID
     GPIO.setup(self.btnID, GPIO.IN, pull_up_down=GPIO.PUD_UP)
コード例 #31
0
  display.write(get_date())
  now = datetime.datetime.now()
  sec = int(now.strftime("%S"))
  time.sleep(60-sec)
  display.clear_display()
  display.write(get_time())
  display.new_line()
  display.write(get_date())

def update():
  display.clear_display()
  display.write(get_time())
  display.new_line()
  display.write(get_date())
  
display = LCD(12, 16, 18, 22, 24, 26, 32, 36, 10, 8)

display.function_set()
display.init_cursor()
display.clear_display()

#start()

#while True:
  #time.sleep(60)
  #date = get_date()
  #time1 = get_time()
  #display.clear_display()
  #display.write(time1)
  #display.new_line()
  #display.write(date)