Exemple #1
0
    def buildCube(self):
        #Creats a 4x4x4 array to store all the
        #LED objects and represent the cube
        #all the led pins are initially set to
        #1,1 which will be changed later
        LedArray = [[[LED(1, 1) for i in range(4)] for j in range(4)]
                    for k in range(4)]

        #A tripple nested for loop where z represents
        #what row (Height) we are on, and x and y are
        #the coordinate positions of the LED we are
        #currently creating.
        #
        #*Note: the commented number in each if
        #represents the GPIO of the row we are on.
        for x in range(4):
            for y in range(4):
                for z in range(4):
                    if (x == 0):
                        LedArray[x][y][z] = LED(24, self.colArray[y][z])
                        #24
                    elif (x == 1):
                        LedArray[x][y][z] = LED(23, self.colArray[y][z])
                        #23
                    elif (x == 2):
                        LedArray[x][y][z] = LED(18, self.colArray[y][z])
                        #18
                    elif (x == 3):
                        LedArray[x][y][z] = LED(21, self.colArray[y][z])
                        #21

        #return the created array of LED Objects
        return LedArray
Exemple #2
0
 def password_entered(self, correct, count_attempt=True):
     """
     Resets digit timeout and stores the time of entry. Also handles the attempts count and LEDs.
     """
     self.digit_timeout.reset()
     self.ignore_digits = True
     self.current_input = []
     if pi_leds_available:
         pi_leds.set_leds(0)
     self.access_log_append("code", correct)
     if correct:
         if PRINT_MSGS:
             print("Unlocked!")
         self.correct_clear_timeout.restart()
         self.incorrect_attempts = 0
         self.iface.flash_green_led()
         self.logger.log("password correct, attempts reset and LED pulsed")
     else:
         if count_attempt and USE_MAX_ATTEMPTS:
             self.incorrect_attempts += 1
             if PRINT_MSGS:
                 print("Incorrect, you have {} more tries left".format(
                     MAX_ATTEMPTS - self.incorrect_attempts))
         elif count_attempt and not USE_MAX_ATTEMPTS and PRINT_MSGS:
             print("Incorrect!")
         self.incorrect_clear_timeout.restart()
         self.iface.flash_red_led()
         if self.incorrect_attempts == MAX_ATTEMPTS:
             self.lockout()
         self.logger.log(
             "password incorrect, attempts: {}, LED pulsed".format(
                 self.incorrect_attempts))
Exemple #3
0
def turnOnOffLED(GPIOpin, LDR_DO):
    if LDR_DO == 1:
        print("Dark")
        LED.TurnOnLED(GPIOpin)
    else:
        print("light")
        LED.TurnOffLED(GPIOpin)
Exemple #4
0
class IOManager(object):
    def __init__(self):
        led = 11
        button = 13
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led, GPIO.OUT)

        self.__scanner = Scanner()
        self.__button = Button(button)
        self.__led = LED(led)
        self.__printer = Printer()
        #set up connections and variables for button, light, printer, and scanner
    def getButton(self):
        return self.__button.getButtonBool()

    def getScan(self):
        return self.__scanner.getInput()

    def setLight(self, value):
        self.__led.setValue(value)

    def blinkLight(self):
        self.__led.blink()
        
    def printReceipt(self, items):
        if items:
            self.__printer.printHeader()
            for item in items:
                self.__printer.printItem(item)
            self.__printer.printTotals(items)
            self.__printer.complete()
Exemple #5
0
def do_blink():
	onValue = request.forms.get('on')
	offValue = request.forms.get('off')
	if onValue and not offValue:
		LED.led_on(18)
	elif not onValue and offValue:
		LED.led_off(18)

	return html
Exemple #6
0
def action(selection):
    if (selection == 1):
        system("echo Shutdown selected!")
        LED.ON(10, 0, 0)
        system("shutdown now")
    elif (selection == 2):
        system("echo Restart selected!")
        LED.ON(10, 8, 0)
        system("reboot now")
async def display_message(ctx):
    # Check if there's any stored messages
    if len(messageBacklog) > 0:
        # Remove message from backlog
        msg = messageBacklog.pop(0)
        
        # Send message
        await ctx.send("Sending the following message: " + msg)
        LED.deconstruct_message(msg)
    else:
        await ctx.send("There are currently no messages to send!")
Exemple #8
0
def motion(GPIOnum):
    global counter

    if GPIO.input(GPIOnum):
        counter += 1
        LED.TurnOnLED(2)
        print("Motion detected{0}".format(counter))

    else:
        LED.TurnOffLED(2)
        print("Motion not detected")
Exemple #9
0
    def __init__(self, iface, logger, stdout, DEMO_MODE=False):
        self.DEMO_MODE = DEMO_MODE
        self.iface = iface  # store interface wrapper
        self.logger = logger  # store logger
        self.stdout = stdout  # store standard output

        if not self.DEMO_MODE:
            self.stdout.start_overwrite_output()

        # bind to digit recevied event
        self.iface.digit_received.bind(self.digit_received_handler)
        self._digit_timeout_time = None
        self.digit_timeout = Timeout(0.1)  # the digit timeout
        self.digit_timeout.elapsed.bind(self.digit_timeout_elapsed)

        self.password = []  # password store
        if os.path.isfile(PWORD_FILE):  # file exists, read and use
            with open(PWORD_FILE) as f:
                self.password = f.read().strip()  # reads and cleans up
            self.logger.log("password read as {}", self.password)
        else:
            self.password = DEFAULT_PWORD  # use default password
            self.logger.log("password defaulted to {}", self.password)
            with open(PWORD_FILE, "w") as f:
                f.write(self.password)  # write new password.txt
            self.logger.log("wrote new password file to {}", PWORD_FILE)

        self.access_log = open(ACCESS_LOG_FILE, "a+")
        self.access_log_append("startup", None)

        self.current_input = []  # current digit input
        self.locked_out = False  # whether the user is locked out
        # the locked out timeout (supposed to go from 59-0, but should output
        # each second)
        self.locked_timeout = Timeout(1)
        self.locked_timeout.elapsed.bind(self.locked_timeout_elapsed)
        self.incorrect_attempts = 0  # the number of incorrect attempts
        self.locked_time_left = 0  # the amount of time left for the user to be locked out
        self.ignore_digits = False
        self.correct_clear_timeout = Timeout(3)
        self.correct_clear_timeout.elapsed.bind(self.clear_timeout_elapsed)
        self.incorrect_clear_timeout = Timeout(1)
        self.incorrect_clear_timeout.elapsed.bind(self.clear_timeout_elapsed)
        self.cover_digit_timeout = Timeout(1)
        self.cover_digit_timeout.elapsed.bind(self.cover_digit_timeout_elapsed)

        if pi_leds_available:
            pi_leds.setup_leds()
        else:
            self.logger.logw(
                "unable to import LED lib, RPi LEDs will not be functional")
            self.logger.loge(_pi_leds_import_error)

        self.logger.log("code lock init complete")
Exemple #10
0
def motion(gpio_num):
    global count
    if gpio.input(gpio_num):
        if gpio.input(23):  # if dark
            count += 1
            LED.turnON(2)
            print('Motion detected {}.'.format(count))
            print('LDR is {}'.format(gpio.input(23)))
    else:
        LED.turnOFF(2)
        print('Motion not detected')
Exemple #11
0
def boot(duration):
    print("*[CUBE - BOOT]*")

    IO.setmode(IO.BCM)
    IO.setwarnings(0)

    ULTRASOUND.setup()
    PUMP.setup()
    LED.setup()

    LED.bootBlinking(duration)
    start()
Exemple #12
0
def boot():
    print("*[CUBE - BOOT]*")
    IO.setmode(IO.BCM)
    IO.setwarnings(0)
    ULTRASOUND.setup()
    PUMP.setup()
    LED.setup()

    duration = DATA.load_waitForInternetConnection() + BOOTING_EXTRATIME
    LED.bootBlinking(duration)

    start()
Exemple #13
0
 def digit_timeout_elapsed(self):
     """
     Handles the elapsed event of the digit timeout.
     """
     now = time.time()
     passed = now - self._digit_timeout_time
     self.logger.logd(
         "digit timeout: {} seconds have passed since last input", passed)
     if pi_leds_available:
         pi_leds.set_leds(max(0, min(passed / DIGIT_TIMEOUT_LENGTH, 1)))
     if passed >= DIGIT_TIMEOUT_LENGTH:
         self.password_entered(False, False)
         self.stdout.overwrite_text = ""
     else:
         self.digit_timeout.restart()
Exemple #14
0
	def setInstance(self, GPIO):
		if self.useSensor[0] :
			self.sensorTimerControl.append(DHT11.Control(self.all_pin[0], GPIO, self.topic,[0, 1]))
			self.sensorTimerControlIndex.append(0)
			self.sensorTimerControlIndex.append(1)
		if self.useSensor[1] :
			self.sensorDetectControl.append(Fire.Control(self.all_pin[1], GPIO, self.topic, 0))
			self.sensorDetectControlIndex.append(0)
		if self.useSensor[2] :
			self.sensorDetectControl.append(Shock.Control(self.all_pin[4], GPIO, self.topic, 1))
			self.sensorDetectControlIndex.append(1)
		if self.useSensor[3] :
			self.sensorDetectControl.append(IR.Control(self.all_pin[5], GPIO, self.topic, 2))
			self.sensorDetectControlIndex.append(2)
		if self.useSensor[4] :
			self.sensorDetectControl.append(Gas.Control(self.adc_pin[0], self.topic, 3))
			self.sensorDetectControlIndex.append(3)
		if self.useSensor[5] :
			self.sensorTimerControl.append(Cds.Control(self.all_pin[7], GPIO, self.topic, 2))
			self.sensorTimerControlIndex.append(2)
		if self.useSensor[6] :
			self.button_instance = Button.Control(self.all_pin[6], GPIO, self.topic)
		if self.useSensor[7] :
			self.led_instance = LED.LED(self.all_pin[2], self.all_pin[3], GPIO)
			self.led_instance.write(1)
		if self.useSensor[8] :
			self.sensorMoveControl.append(SG90.SG90(self.all_pin[8], self.all_pin[9], GPIO))
		if self.useSensor[9] :
			self.sensorTimerControl.append(PM2008M.Control(self.topic,[3, 4]))
			self.sensorTimerControlIndex.append(3)
			self.sensorTimerControlIndex.append(4)
    def __init__(self):
        #On prépare un fichier temporaire tant que le script est lancé
        #pid = str(os.getpid())
        #pidfile = "/tmp/controleur.pid"

        #try:
        #	#On teste si le fichier existe déja
        #	if os.path.isfile(pidfile):
        #		os.link(pidfile,"daemon_python")
        #	else:
        #		file(pidfile, 'w').write(pid)
        #		os.link(pidfile,"daemon_python")
        #except IOError as e:
        #	message = "I/O error("+str(e.errno)+"): "+str(e.strerror)
        #	print(message)
        #On effectue le vrai travail ici
        #On instancie les classes principales
        self.stop_event = threading.Event()
        self.surveillance_serveur = surveillance_serveur.Surveillance_serveur(
            self, self.stop_event)
        self.surveillance_serie = surveillance_serie.Surveillance_serie(
            self, self.stop_event)
        self.traitement = traitement.Traitement(self, self.stop_event)
        self.video = video.Video(self.stop_event)
        self.led = LED.LED(self.stop_event)

        #On met les threads en mode daemon, quand le controleur est tué, on tue tous les threads
        self.surveillance_serveur.daemon = True
        self.surveillance_serie.daemon = True
        self.traitement.daemon = True
        self.video.daemon = True
        self.led.daemon = True
Exemple #16
0
def led():
    while 1:
        config = loadConfig()
        debugPrint("Mode: " + config["mode"])
        if config["mode"] == "static":
            LED.fadeToRGB(float(config["static"]["red"]),
                          float(config["static"]["green"]),
                          float(config["static"]["blue"]), .25, True)
        elif config["mode"] == "breathing":
            for color in config["breathing"]:
                LED.fadeToRGB(float(color["red"]), float(color["green"]),
                              float(color["blue"]),
                              float(color["fadeDuration"]), True)
                sleep(float(color["timeout"]))
        elif config["mode"] == "disabled":
            sleep(1)
Exemple #17
0
    def initLEDs(self):
        hbox_led = QtGui.QHBoxLayout()
        hbox_cb = QtGui.QHBoxLayout()

        colors = ['r', 'a', 'y', 'g', 'b', 'p', 'r', 'a']
        for i in range(8):
            #self.relay_cb.append(Relay_QCheckBox(self, i+1, btn_name, 0, pow(2,i)))
            lbl = QtGui.QLabel("Relay " + str(i))
            lbl.setAlignment(QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter)
            lbl.setFixedHeight(20)
            lbl.setStyleSheet("QLabel { text-decoration:underline; \
                                        font-size:14px; \
                                        font-weight:bold; \
                                        color:rgb(255,255,255);}")

            self.leds.append(LED(i, 50, 'g'))
            vbox = QtGui.QVBoxLayout()
            vbox.addWidget(lbl)
            vbox.addWidget(self.leds[i])
            self.leds[i].setAlignment(QtCore.Qt.AlignCenter
                                      | QtCore.Qt.AlignVCenter)
            hbox_led.addLayout(vbox)
            #hbox_led.setAlignment(QtCore.Qt.AlignCenter|QtCore.Qt.AlignVCenter)
            hbox_led.setAlignment(QtCore.Qt.AlignCenter
                                  | QtCore.Qt.AlignVCenter)

        #hbox_led.addLayout(vbox_rx)
        self.led_fr.setLayout(hbox_led)
	def __init__ (self):
		'''
			A nice debugging aid - can print any simple or complex variable
		'''
		self.pp = pprint.PrettyPrinter(indent=4)

		'''
			Create the list of bits
		'''
		for bitNr in range(8):
			b = LED(self.BitNames[bitNr], self.BitPins[bitNr], bitNr, self.BitValues[bitNr], self.BitStates[bitNr], self.BitColors[bitNr], self.BitBlinkRates[bitNr], self.BitProcesses[bitNr], self.BitDescriptions[bitNr])

			b.status = self.ledStateString("On", "Off")

			self.Bits.append(b)

		return None
Exemple #19
0
 def __init__(self, car_name):
     self.car = Car(car_name)
     self.car.steering.turning_max = 50
     self.color = self.car.color_getter
     self.flag = True
     self.buzzer = Buzzer.Buzz()
     self.led = LED.Led()
     self.song = Buzzer_Elise.Elise()
Exemple #20
0
    def watchdog_mode_fnc(frame_image):

        gray = cv2.cvtColor(frame_image, cv2.COLOR_BGR2GRAY)
        gray = cv2.GaussianBlur(gray, (21, 21), 0)

        if avg is None:
            print("[INFO] starting background model...")
            avg = gray.copy().astype("float")
            rawCapture.truncate(0)
            return

        cv2.accumulateWeighted(gray, avg, 0.5)
        frameDelta = cv2.absdiff(gray, cv2.convertScaleAbs(avg))

        # threshold the delta image, dilate the thresholded image to fill
        # in holes, then find contours on thresholded image
        thresh = cv2.threshold(frameDelta, 5, 255, cv2.THRESH_BINARY)[1]
        thresh = cv2.dilate(thresh, None, iterations=2)
        cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                                cv2.CHAIN_APPROX_SIMPLE)
        cnts = imutils.grab_contours(cnts)
        #print('x')

        # loop over the contours
        for c in cnts:
            # if the contour is too small, ignore it
            if cv2.contourArea(c) < 5000:
                return

            # compute the bounding box for the contour, draw it on the frame,
            # and update the text
            (x, y, w, h) = cv2.boundingRect(c)
            cv2.rectangle(frame_image, (x, y), (x + w, y + h), (128, 255, 0),
                          1)
            text = "Occupied"
            motionCounter += 1
            #print(motionCounter)
            #print(text)
            LED.colorWipe(Color(255, 16, 0))
            lastMovtionCaptured = timestamp

        if (timestamp - lastMovtionCaptured).seconds >= 0.5:
            LED.colorWipe(Color(255, 255, 0))
Exemple #21
0
    def __init__(self):
        led = 11
        button = 13
        GPIO.setmode(GPIO.BOARD)
        GPIO.setup(led, GPIO.OUT)

        self.__scanner = Scanner()
        self.__button = Button(button)
        self.__led = LED(led)
        self.__printer = Printer()
Exemple #22
0
def webhook():
    global check
    data = request.get_json()

    if data["object"] == "page":
        for entry in data["entry"]:
            for msg_event in entry["messaging"]:
                sender_id = msg_event["sender"]["id"]

                if msg_event.get("message"):
                    message_text = msg_event["message"]["text"]
                    #print(message_text)
                    if message_text == "turn off led":
                        LED.Setup(2, "OUT")
                        LED.TurnOffLED(2)
                        send_msg("1447614532010378", "turn off led")

                    #print(message_text)
    log(data)
    return "ok", 200
Exemple #23
0
def main():
    try:
        loadConfig()
        ledProcess = multiprocessing.Process(target=led)
        # ledProcess.start()

        # lcdProcess = multiprocessing.Process(target=LCD)
        #lcdProcess.start()

        monDevice = multiprocessing.Process(target=MonitorDevice)
        monDevice.start()

        CGISocket.listen(5)

        print 'Listening.'

        subprocess.Popen(
            "sudo sh -c 'echo 1 > /sys/class/leds/led0/brightness'",
            shell=True)

        while 1:
            conn, add = CGISocket.accept()
            client(conn, add)

    except KeyboardInterrupt:
        print "\nGoodbye"
        subprocess.Popen(
            "sudo sh -c 'echo 0 > /sys/class/leds/led0/brightness'",
            shell=True)
        # ledProcess.terminate()
        LED.fadeToRGB(0, 0, 0, 0.005, False, True)
        try:
            carConnection.close()
        except:
            print colored("Failed to close carConnection", "red")

        os._exit(0)
    except Exception, e:
        print "Error!"
        print colored(str(e), "red")
        traceback.print_exc()
Exemple #24
0
def monitor_distance(LED, min_distance_m=0.1):
    '''Monitor distance using ultasonic module and change LED based on distance'''

    while True:
        current_distance = round(ultra.checkdist(), 2)
        if_debug_log("distance: " + str(current_distance))

        if current_distance > (2 * min_distance_m):
            #distance far, normal white LED
            LED.colorWipe(Color(255, 255, 255))
            if_debug_log("distance: " + str(current_distance) +
                         " --> normal, LED white")

        elif (current_distance > (min_distance_m) and current_distance <=
              (2 * min_distance_m)):
            #getting closer, LED yellow
            LED.colorWipe(Color(255, 255, 0))
            if_debug_log("distance: " + str(current_distance) +
                         " --> getting closer, LED yellow")

        elif current_distance <= min_distance_m:
            #too close, LED red
            LED.colorWipe(Color(255, 0, 0))
            if_debug_log("distance: " + str(current_distance) +
                         " --> too close, LED red")
Exemple #25
0
def server():
    gpio.setmode(gpio.BCM)
    LED.setup(21, 'out')

    server_socket = bt.BluetoothSocket(bt.RFCOMM)
    server_socket.bind(('', 3))
    server_socket.listen(1)

    conn_socket, address = server_socket.accept()
    try:
        while True:
            data = conn_socket.recv(1024)
            data = str(data, 'utf-8')
            print(data)
            if data == 'turn on':
                print('receive "{}"'.format(data))
                LED.turnON(21)
            elif data == 'turn off':
                print('receive "{}"'.format(data))
                LED.turnOFF(21)

            send_data = input()
            conn_socket.send(send_data)
    finally:
        conn_socket.close()
        server_socket.close()
        gpio.cleanup()
Exemple #26
0
def server():
    bind_ip = '192.168.10.33'
    bind_port = 8888

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind((bind_ip, bind_port))
    server_socket.listen(5)

    print('Listening on {}'.format((bind_ip, bind_port)))

    gpio.setmode(gpio.BCM)
    LED.setup(21, 'out')

    try:
        conn_socket, addr = server_socket.accept()
        print('Accept connection from {}'.format((addr[0], addr[1])))
        while True:
            data = conn_socket.recv(1024)
            data = str(data, 'utf-8')
            if data == 'turn on':
                LED.turnON(21)
            elif data == 'turn off':
                LED.turnOFF(21)
            print(data)

    finally:
        server_socket.close()
        conn_socket.close()
        gpio.cleanup()
Exemple #27
0
def mainLogic():
    LED.Blink(5, 5, 5, 1, 2, 3, 1100)
    while (True):
        GPIO.wait_for_edge(pin, GPIO.FALLING)
        sleep(softDebounce)  # Software button debounce
        count = 0
        while (True):
            LED.ON(ledMatrix[count][0], ledMatrix[count][1],
                   ledMatrix[count][2])
            isPressed = GPIO.wait_for_edge(pin,
                                           GPIO.FALLING,
                                           timeout=confirmTimeout)
            sleep(softDebounce)  # Software button debounce
            if (isPressed):
                count = (count + 1) % 3  # Makes sure the selection is 0-2
                if (
                        count == 0
                ):  # Goes back to start if all options got scrolled through
                    LED.OFF()
                    break
            else:  # Acts when a timeout occurs on non-zero selection
                LED.OFF()
                action(count)
                break
Exemple #28
0
def update():
    print("VOLUME - UPDATE")

    distanceFull = DATA.load_distanceFull()
    distanceEmpty = DATA.load_distanceEmpty()
    distance = DATA.load_distance()

    range = distanceEmpty - distanceFull

    percentage = 0.0

    if distance < distanceEmpty:
        diffFromEmpty = distanceEmpty - distance
        percentage = diffFromEmpty / range
        print("VOLUME - UPDATE - PERCENTAGE = [%.2f]" % percentage)

    volumeMax = DATA.load_volumeMax()
    volume = volumeMax * percentage
    print("VOLUME - UPDATE - VOLUME = [%d]" % volume)

    DATA.save_volume(volume)
    DATA.save_percentage(percentage)

    warningPercentage = DATA.load_warningPercentage()

    LED.setup()
    if percentage < warningPercentage:
        LED.red()

        shouldSend = DATA.load_shouldSend()
        print("********************************************************** SHOULD SEND = ")
        print(shouldSend)

        if shouldSend:
            print("********************************************************** SEND NOTIF")
    
            # sending = DATA.load_sending()
            # print("********************************************************** SENDING = ")
            # print(sending)
            # if not sending:
                # DATA.save_sending(1)
            
            # DATA.save_shouldSend(0)
            # APNS.sendNotification()
                
    else:
        if percentage > 0.5:
            print("********************************************************** SHOULD SEND SET TO 1")
            DATA.save_shouldSend(1)
        LED.blue()
Exemple #29
0
    def initTable(self):
        self.relay_table = Relay_Table(self.main_window)
        self.cb_group = QtGui.QButtonGroup()
        self.cb_group.setExclusive(False)
        for i in range(8):
            #cb = QtGui.QCheckBox("Relay " + str(i))
            cb = QtGui.QCheckBox("{:03d}".format(pow(2, i)))
            cb.setStyleSheet("QCheckBox {   font-size:14px; \
                                            background-color:rgb(0,0,0); \
                                            color:rgb(255,255,255) ; }")
            self.cb_group.addButton(cb, i)
            rb_on = QtGui.QRadioButton("ON")
            rb_on.setStyleSheet("QRadioButton { font-size:14px; \
                                                background-color:rgb(0,0,0); \
                                                color:rgb(255,255,255) ; }")
            rb_off = QtGui.QRadioButton("OFF")
            rb_off.setStyleSheet("QRadioButton { font-size:14px; \
                                                 background-color:rgb(0,0,0); \
                                                 color:rgb(255,255,255) ; }")
            rb_off.setChecked(True)

            self.relay_rb_on.append(rb_on)
            self.relay_rb_off.append(rb_off)
            self.relay_cb.append(cb)

            self.table_led.append(LED(i, 20, 'g'))
            self.relay_table.add_relay( self.cfg['relay']['map'][i], \
                                        self.table_led[i], \
                                        self.relay_cb[i], \
                                        self.relay_rb_on[i], \
                                        self.relay_rb_off[i] )

            self.relay_cb[i].clicked.connect(self.table_led[i].set_state)

        self.cb_group.buttonClicked.connect(self.cbClicked)

        grid = QtGui.QGridLayout()
        grid.addWidget(self.relay_table, 0, 0, 2, 2)
        grid.setSpacing(0)
        grid.setContentsMargins(0, 0, 0, 0)
        grid.setRowStretch(0, 1)
        self.table_fr.setLayout(grid)
Exemple #30
0
def init(s,l):
    global screen,led
    screen=s
    led=LED.create(l)
    ico['0']=load('img/0.pbm',25,64)
    ico['1']=load('img/1.pbm',25,64)
    ico['2']=load('img/2.pbm',25,64)
    ico['3']=load('img/3.pbm',25,64)
    ico['4']=load('img/4.pbm',25,64)
    ico['5']=load('img/5.pbm',25,64)
    ico['6']=load('img/6.pbm',25,64)
    ico['7']=load('img/7.pbm',25,64)
    ico['8']=load('img/8.pbm',25,64)
    ico['9']=load('img/9.pbm',25,64)
    ico['flash']=load('img/flash.pbm',3,64)
    ico['am']=load('img/am.pbm',25,32)
    ico['pm']=load('img/pm.pbm',25,32)
    ico['cycle']=load('img/cycle.pbm',25,32)
    ico['cycle_error']=load('img/cycle_error.pbm',25,32)
    ico['love']=load('img/love.pbm',25,32)
Exemple #31
0
    def __init__(self):
        super(DisplayOLEDSkill, self).__init__(name="DisplayOLEDSkill")
        self.myLEDs = LED.theLEDs()
        self.myDisplay = DISPLAY.theDisplay()
        self.myLEDs.start()
        self.myDisplay.start()

        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.bshutdown, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.brestart, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.bsleep1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.setup(self.bsleep1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
        GPIO.add_event_detect(self.bshutdown,
                              GPIO.RISING,
                              callback=self.button_shutdown)
        GPIO.add_event_detect(self.brestart,
                              GPIO.RISING,
                              callback=self.button_restart)
        GPIO.add_event_detect(self.bsleep1,
                              GPIO.RISING,
                              callback=self.button_stop_alarm)
Exemple #32
0
def main():

    rfid_reader = SimpleMFRC522.SimpleMFRC522()
    temp_sensor = Adafruit_DHT.DHT11
    temp_pin = 4  # Physical pin is 7
    init()  #initialize the GPIO pins
    dbh = DB_Helper.DB_Helper()

    try:
        while True:
            print "Please place the tag to the RFID reader."

            # Turn ON LED to indicate that RFID is ready for reading
            LED.ledON()

            # Get the RFID
            id, text = rfid_reader.read()
            print "RFID: " + str(id)
            LED.ledOFF()

            # Code for reading the DHT11 Humidity and Temperature Sensor
            humidity, temperature = Adafruit_DHT.read_retry(
                temp_sensor, temp_pin)
            print "Temp={0:0.1f}C Humidity={1:0.1f}%".format(
                temperature, humidity)

            #Fetch the TagId from db.tbl_Tag base on RFID
            tagId = dbh.getTagId(id)
            #Insert the temperature, humidity and RFID to Data table
            inserted = dbh.addEntry(tagId, temperature, humidity)

            # Turn ON the buzzer to indicate that data is sent to Database
            if inserted is True:
                ActiveBuzzer.beep()

    except KeyboardInterrupt:
        dbh.destroy()
        LED.ledOFF()
        cleanGPIO()
Exemple #33
0
import socket
import RPi.GPIO as GPIO
import LED
import sys

bind_ip = '192.168.1.11'
bind_port = 8888

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = (bind_ip,bind_port)
print('connect to {} port {}'.format(*server_address))
client.connect(server_address)

LED.Setup(14, 'OUT')
try:
    print('Accepted connection')
    while True:
        data = client.recv(1024)
        print(data)
        if data == b'turn on led':
            LED.TurnOnLED(14)
        else :
            LED.TurnOffLED(14)

except KeyboardInterrupt:
    client.close()
    GPIO.cleanup()

finally:
    server.close()
Exemple #34
0
#!/usr/bin/env python
#encoding=utf-8

from bottle import run, get, post, request
import LED

meta = '<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=yes">'

form = '''
<form action="/bright" method="post">
<input type="range" name="brightvalue" value="0" min="0" max="100">
<input type="submit" value="Bright">
</form>
'''
html = meta + form
led_instance = LED.led_brightness(18)

@get('/bright')
def bright():
	return html

@post('/bright')
def do_bright():
	sliderValue = request.forms.get('brightvalue')
	led_instance.duty(int(sliderValue))
	return '%s<br>%s' % (sliderValue, html)

run(host='192.168.18.101', port=8080, debug=True)
while continue_reading:
    
    # Scan for cards    
    (status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)

    # If a card is found
    if status == MIFAREReader.MI_OK:
        print "Card detected"
    
    # Get the UID of the card
    (status,uid) = MIFAREReader.MFRC522_Anticoll()

    # If we have the UID, continue
    if status == MIFAREReader.MI_OK:
        Buzzer.setup()
        LED.setup()
        Buzzer.beep()
        LED.led()

        # Print UID
        print "Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3])
        if uid[0]==150 and uid[1]==110 and uid[2]==1 and uid[3]==164:
            print "Welcom, Jason :)"

        if uid[0]==133 and uid[1]==94 and uid[2]==233 and uid[3]==171:
            print "Welcom, Lucy :)"
    
        # This is the default key for authentication
        key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
        
        # Select the scanned tag
Exemple #36
0
GPIO 11 UV_CLOCK
GPIO 10 UV_DOUT
GPIO 21 temperature_CLOCK
GPIO 20 temperature_DOUT
"""


def int16bit(b):
    return (ord(b[0]) << 8) + ord(b[1])


arduino = serial.Serial('/dev/ttyACM0', 9600)

pi = pigpio.pi()

led = LED.light(pi)

led.all_off()

pm25 = pmsA003.sensor('/dev/ttyUSB0')

dht = DHT22.sensor(pi, 4)

# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
while True:
Exemple #37
0
def slowBlink(led, numOfBlinks):
    for x in range(numOfBlinks):
        led.turnOn()
        time.sleep(slowBlinkDelay)
        led.turnOff()
        time.sleep(slowBlinkDelay)