Beispiel #1
0
import time
import string
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522 as rc
#from tem import testHDC1080 as hdc
import LED as l
import stu_management1
#from detectpeople import detectPeople as dt

go_out = rc.SimpleMFRC522(bus=0, device=1)
come_back = rc.SimpleMFRC522(bus=1, device=2)
#tem_hum = hdc.TempHum()
led = l.Led()
#detect_people = dt.DetectPeople()

while True:
    read_go_out = go_out.read()
    read_come_back = come_back.read()
    #read_detect = detect_people.detect()
    if read_go_out[0]:
        if read_go_out[1] == 1:
            led.red()
        else:
            led.green()
            #print(read_go_out[1].strip())
            print(f'uid:{read_go_out[0]}\nnum:{read_go_out[1]}\ngo out',
                  time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            #print(f'temperature:{read_temhum[0]}\nhumidity:{read_temhum[1]}%')
            stu_management1.add_rfid(1, read_go_out[1].strip(), read_go_out[0])
    if read_come_back[0]:
        if read_come_back[1] == 1:
Beispiel #2
0
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import requests

r = SimpleMFRC522()

try:
    id, slug = r.read()
    print(slug)
    url = 'http://0:8000/api/commit/{}'.format(id)
    print(url)
    req = requests.get(url)
    print(req.text)
finally:
    GPIO.cleanup()
Beispiel #3
0
def irrigate():
    # print("in irrigation")
    pot_count = 0

    # print ("reading")
    # while(pot_count < 2):

    while (pot_count < 24):
        GPIO.cleanup()
        reader = SimpleMFRC522()
        print("the Pot_count is: " + str(pot_count))
        global count, count2
        try:
            print(" Waiting to read ")
            id, rfid = reader.read()
            print(rfid)
        finally:
            print("cleaned")
            GPIO.cleanup()
        time.sleep(1)
        try:
            if (int(rfid) > 0 and int(rfid) < 25):
                pot_count = pot_count + 1
                GPIOsetup()
                print("Read pot: " + rfid)
                try:
                    w = int(rfid)
                except ValueError:
                    print("not transformable int")
                print("coneverted")
                if (w != 2):
                    water = ((w - 2) + 24) % 24
                else:
                    water = 4
                print("Water pot number  " + str(water))
                time.sleep(5)
                db = MySQLdb.connect(
                    host="localhost",  # your host, usually localhost
                    user="******",  # your username
                    passwd="iqp2020",  # your password
                    db="mydb")
                cur = db.cursor(MySQLdb.cursors.DictCursor)
                try:
                    query = "SELECT * from Carousel where barrel_num = %s"
                    cur.execute(query, [str(water)])
                    result = cur.fetchall()
                    for r in result:
                        q = (r['Water_Liters'])
                        ec = (r['Water_ec'])
                        print("The amount is " + str(q) + " and the ec " +
                              str(ec))
                finally:
                    db.close()
                print("ready to water")
                count = 0
                count2 = 0
                if (ec == 2.3):
                    print(str(water) + " ec 2.3")
                    while (count / (60 * 7.5) < q):
                        print(count / (60 * 7.5))
                        irrigate_open(ec)
                    #time.sleep(3)
                    print("calling the close function")
                    irrigate_close(ec)
                elif (ec == 0.0):
                    while (count2 / (60 * 7.5) < q):
                        print(count2 / (60 * 7.5))
                        irrigate_open(ec)
                    print("calling the close function")
                    irrigate_close(ec)
        except ValueError:
            print(" Not a number ")
    def initHardwares(self):

        try:
            if hasattr(self, 'press_motor'):
                self.press_motor.close()

            if hasattr(self, 'conveyor_motor'):
                self.conveyor_motor.close()

            if hasattr(self, 'distance_sensor1'):
                self.distance_sensor1.close()
                print("distance sensor 1 close")

            if hasattr(self, 'distance_sensor2'):
                self.distance_sensor2.close()
                print("distance sensor 2 close")

        except Exception as e:
            print("error:", e)

        try:
            self.press_motor = Motor(name='press_motor', pin_factory=factory)

            self.setButton(self.ui.btn_press_motor_forward_on,
                           function=self.press_motor.forward)
            self.setButton(self.ui.btn_press_motor_backward_on,
                           function=self.press_motor.backward)
            self.setButton(self.ui.btn_press_motor_off,
                           function=self.press_motor.stop)
        except Exception as e:
            print("error:", e)
            ErrorLog.writeToFile(
                str(e) + ' In press_motor initHardwares Method')

        try:

            # normal
            # self.conveyor_motor = Motor(name='conveyor_motor', pin_factory=factory)

            # red relay
            self.conveyor_motor = Motor(name='conveyor_motor',
                                        pin_factory=factory,
                                        active_high=True)

            self.conveyor_motor_time_2 = float(
                DataBase.select('conveyor_motor_time_2'))

            self.setButton(self.ui.btn_conveyor_motor_forward_on,
                           function=self.conveyor_motor.forward)
            self.setButton(self.ui.btn_conveyor_motor_backward_on,
                           function=self.conveyor_motor.backward)
            self.setButton(self.ui.btn_conveyor_motor_off,
                           function=self.conveyor_motor.stop)
        except Exception as e:
            print("error:", e)
            ErrorLog.writeToFile(
                str(e) + ' In conveyor_motor initHardwares Method')

        try:
            distance_sensor1_trig_port = int(
                DataBase.select('distance_sensor1_trig_port'))
            distance_sensor1_echo_port = int(
                DataBase.select('distance_sensor1_echo_port'))
            distance_sensor1_threshold_distance = float(
                DataBase.select('distance_sensor1_threshold_distance'))
            self.distance_sensor1 = DistanceSensor(
                distance_sensor1_echo_port,
                distance_sensor1_trig_port,
                max_distance=1,
                threshold_distance=distance_sensor1_threshold_distance / 100,
                pin_factory=factory)
            self.distance_sensor1.when_in_range = self.distanceSensor1WhenInRange
            self.distance_sensor1.when_out_of_range = self.distanceSensor1WhenOutOfRange
            print('distance sensor 1 ready')
        except Exception as e:
            print("error:", e)
            ErrorLog.writeToFile(
                str(e) + ' In distance_sensor1 initHardwares Method')

        try:
            distance_sensor2_trig_port = int(
                DataBase.select('distance_sensor2_trig_port'))
            distance_sensor2_echo_port = int(
                DataBase.select('distance_sensor2_echo_port'))
            distance_sensor2_threshold_distance = float(
                DataBase.select('distance_sensor2_threshold_distance'))
            self.distance_sensor2 = DistanceSensor(
                distance_sensor2_echo_port,
                distance_sensor2_trig_port,
                max_distance=1,
                threshold_distance=distance_sensor2_threshold_distance / 100,
                pin_factory=factory)
            self.distance_sensor2.when_in_range = self.distanceSensor2WhenInRange
            self.distance_sensor2.when_out_of_range = self.distanceSensor2WhenOutOfRange
            print('distance sensor 2 ready')
        except Exception as e:
            print("error:", e)
            ErrorLog.writeToFile(
                str(e) + ' In distance_sensor2 initHardwares Method')

        try:
            if not hasattr(self, 'rfid_sensor'):
                self.rfid_sensor = SimpleMFRC522()
                print('RFID sensor ready')
        except Exception as e:
            print("error:", e)
            ErrorLog.writeToFile(
                str(e) + ' In rfid_sensor initHardwares Method')
Beispiel #5
0
def main():

    #program start

    directory = '/media/pi/BILLYUSB1/'

    LOG_FILENAME = '/tmp/bplay_%s.log' % time.strftime(
        '%Y-%m-%d %H:%M:%S', time.localtime(time.time())).replace(
            " ", "_").replace(":", "")
    logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)
    #logging.basicConfig(level=logging.DEBUG)

    reader = SimpleMFRC522()

    logging.info(
        "\n\n\n***** %s Begin Player****\n\n\n" %
        time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

    current_movie_id = 111111222222

    playerOB = ""

    try:
        while True:

            isPlay = isplaying()
            logging.debug(
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                + " Movie Playing: %s" % isPlay)

            if not isPlay:

                current_movie_id = 555555555555

            start_time = time.time()
            logging.debug('start_time0: %s' % start_time)

            logging.debug(
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                + " Waiting for ID to be scanned")

            temp_time = time.time()
            logging.info(
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                + " #READER BEFORE %s" % temp_time)
            idd, movie_name = reader.read()

            temp_time = time.time() - temp_time
            logging.info(
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                + " #READER AFTER - ELAPSED TIME %s" % temp_time)

            logging.debug(
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                + " + ID: %s" % idd)
            logging.debug(
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                + " + Movie Name: %s" % movie_name)

            movie_name = movie_name.rstrip()

            if current_movie_id != idd:

                logging.info(
                    time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(time.time())) + ' New Movie')
                logging.info(
                    time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(time.time())) +
                    " - ID: %s" % idd)
                logging.info(
                    time.strftime('%Y-%m-%d %H:%M:%S',
                                  time.localtime(time.time())) +
                    " - Name: %s" % movie_name)
                #this is a check in place to prevent omxplayer from restarting video if ID is left over the reader.
                #better to use id than movie_name as there can be a problem reading movie_name occasionally

                if movie_name.endswith(('.mp4', '.avi', '.m4v', '.mkv')):
                    current_movie_id = idd  #we set this here instead of above bc it may mess up on first read
                    logging.info(
                        time.strftime('%Y-%m-%d %H:%M:%S',
                                      time.localtime(time.time())) +
                        " playing: omxplayer %s" % movie_name)

                    playerOB = playmovie(movie_name, directory, playerOB)

                elif 'folder' in movie_name:
                    current_movie_id = idd
                    movie_directory = movie_name.replace('folder', "")

                    try:

                        movie_name = random.choice(
                            glob.glob(
                                os.path.join(directory + movie_directory,
                                             '*')))
                        movie_name = movie_name.replace(directory, "")
                        direc = directory
                    except IndexError:
                        movie_name = 'videonotfound.mp4'
                        direc = 'home/pi/Videos/'

                    logging.info(
                        time.strftime('%Y-%m-%d %H:%M:%S',
                                      time.localtime(time.time())) +
                        " randomly selected: omxplayer %s" % movie_name)
                    playerOB = playmovie(movie_name, direc, playerOB)

            else:

                end_time = time.time()
                elapsed_time = end_time - start_time

                logging.debug('end_time: %s' % end_time)
                logging.debug('start_time1: %s' % start_time)

                isPlay = isplaying()

                if isPlay:

                    if elapsed_time > 0.6 and elapsed_time < 8:
                        #pause, unpause movie
                        logging.info(
                            time.strftime('%Y-%m-%d %H:%M:%S',
                                          time.localtime(time.time())) +
                            " PLAY/PAUSE %s" % elapsed_time)
                        playerOB.play_pause()

    except KeyboardInterrupt:
        GPIO.cleanup()
        print("\nAll Done")
Beispiel #6
0
 def __init__(self):
     self.reader = SimpleMFRC522()
 def __init__(self, handler_function):
     self.RC522 = SimpleMFRC522()
     self.parser = SerialParser(handler=handler_function)
Beispiel #8
0
 def __init__(self):
     self.reader = SimpleMFRC522()
     super().__init__()
import serial

ser = serial.Serial(
        port='/dev/ttyS0', #Replace ttyS0 with ttyAM0 for Pi1,Pi2,Pi0
        baudrate = 9600,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=1
)

i = 0

try:
	while i < 5:
       		reader = SimpleMFRC522(0, 0)
		id, text = reader.read()
		t1 = datetime.now().time()
		time1 = (t1.hour*60 + t1.minute)*60+t1.second
		ser.write("The time from reader 3 and id %ld  is %d\n"%(id,time1))
		print ("Data from R3 is sent\n")
		time.sleep(0.1)
		reader1 = SimpleMFRC522(0, 1)
		id1,text1 = reader1.read()
		t2 = datetime.now().time()
		time2 = (t2.hour*60 + t2.minute)*60+t2.second
		ser.write("The time from reader 4 and id %ld is %d\n"%(id1,time2))
		print ("Data from R4 is sent\n")
		time.sleep(0.1)
		i += 1
finally:
Beispiel #10
0
import sys
import RPi.GPIO as gpio
from mfrc522 import SimpleMFRC522
import time
CardRead = SimpleMFRC522()

load1 = 13

gpio.setmode(gpio.BOARD)
#gpio.setmode(gpio.BCM)
gpio.setwarnings(False)
gpio.setup(load1, gpio.OUT)

#idlist = '31389199508', '49048004155'

print('Card Scanning')
print('for Cancel Press ctrl+c')

try:
    while True:

        id, text = CardRead.read()
        print(id)
        print(text)
        if id == 31389199508:
            if gpio.input(load1):
                gpio.output(load1, gpio.LOW)
                print('Un-Lock')
                time.sleep(5)
                gpio.output(load1, gpio.HIGH)
                print('Lock')
Beispiel #11
0
#!/usr/bin/env python3

import logging
import logging.handlers
import argparse
import sys
import time
import soco
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

# Defaults
LOG_FILENAME = "/var/log/sonosctl/controller.log"
LOG_LEVEL = logging.DEBUG
SPEAKER_NAME = "Playroom"
READER = SimpleMFRC522()
OLDCARDID = ""

# Define and parse command line arguments
parser = argparse.ArgumentParser(description="RFID Sonos Controller")
parser.add_argument("-f",
                    "--logfile",
                    help="file to write log to (default '" + LOG_FILENAME +
                    "')")
parser.add_argument("-l",
                    "--loglevel",
                    help="log level (DEBUG, ERROR, WARNING, INFO)")
parser.add_argument("-s",
                    "--speaker",
                    help="speaker to be used as output device")
Beispiel #12
0
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522

reader = SimpleMFRC522.SimpleMFRC522(bus=0, device=1)

try:
    text = input('New data:')
    print("Now place your tag to write")
    reader.write(text)
    print("Written")
finally:
    GPIO.cleanup()
 def __init__(self):
     #creates an instance of a simple MFRC522 class
     self.reader = SimpleMFRC522()
     self.slow_down = 0.5
Beispiel #14
0
 def __init__(self):
     self.device = SimpleMFRC522()
     self.logger = config.log.getLogger(__name__)
     self.logger.info("Lector de tarjetas montado")
Beispiel #15
0
 def Read(self):
     reader = SimpleMFRC522()
     id, text = reader.read()
     print(id)
     print(text)
Beispiel #16
0
from PIL import Image, ImageTk
import linecache

#for doorbell sound
from playsound import playsound

#for sending emails
import email, smtplib, ssl
from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

#init global variables
camera = PiCamera()  #name of the camera
reader = SimpleMFRC522()  #name of the RFID reader
prevcount = 0  #start or stop call
speakcount = 0  #decide who is speaking (microphone activation)
password = "******"  #default password, if no password file is available
pwd = ""  #variable for the matrix keypad password input

IsHome = 0  #For the Away - Home button
CallAct = 0  #determine if call is active

expression = ""  #used for password changing in settings menu

#file locations
pwfile = "/home/pi/mems/files/passwords"  #for the password(s)
rffile = "/home/pi/mems/files/IDs"  #for RFID numbers
picfile = "/home/pi/mems/files/picfile"  #folder of the taken pictures
Beispiel #17
0
 def Write(self,T):
     reader = SimpleMFRC522()
     text = T
     reader.write(text)
     print("Written")
def Lector():
    ssl_private_key_filepath = '/home/pi/Desktop/Semana i/reto-iot-en-supermercado-2019-los-chocoflanes/Datasets/KeyAlmacen/demo_private.pem'
    root_cert_filepath = '/home/pi/Desktop/Semana i/reto-iot-en-supermercado-2019-los-chocoflanes/Datasets/KeyAlmacen/roots.pem'
    device_id = 'Almacen'
    #Mandar llamar función del lector
    reader = SimpleMFRC522()
    print("Acerque el tag al sensor")
    try:
        #Inicializar arreglos necesarios
        headers = []
        ids = []
        cant = []
        arrTemp = []
        filedata = []

        print("Saca el producto")
        id, productSelect = reader.read()
        productSelect = productSelect.strip()
        if productSelect:
            GPIO.output(outputMov, True)
            time.sleep(0.5)
            GPIO.output(outputMov, False)

        #Leer archivo de almacén
        with open(almacen, "r") as file:
            header = file.readline()
            for line in file:
                if len(line) > 1:
                    row = line.split(',')
                    filedata.append(row)
                    idProd = row[0]
                    cantProd = int(row[-1])

                    ids.append(idProd)
                    cant.append(cantProd)
                    arrTemp.append(idProd)

        for var in filedata:
            usertoCloud(ssl_private_key_filepath,
                        root_cert_filepath,
                        device_id,
                        product_list=var)

        #Si el producto seleccionado está en el almacén
        if productSelect in ids:
            arrTemp.index(productSelect)
            arrTemp.remove(productSelect)
            index = ids.index(productSelect)
            if cant[index] > 0:
                cant[index] = cant[index] - 1

        else:
            arrTemp.append(productSelect)
            index = ids.index(productSelect)
            cant[index] = cant[index] + 1

        filedata[index][2] = (str(cant[index]))

        with open(almacen, 'w') as file:
            file.write(header)
            for line in filedata:
                file.write(",".join(line))
                file.write("\n")

        file.close()
        return productSelect

    except KeyboardInterrupt:
        pass
import RPi.GPIO as GPIO
import sys
import socket
import signal
from mfrc522 import SimpleMFRC522
import time
import datetime

GPIO.setmode(GPIO.BOARD)
GPIO.setup(8,GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
GPIO.setwarnings(False)

simulation_time = 7
current_simulation_time = 0

reader = SimpleMFRC522()

rfid_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 9000
rfid_socket.bind(('0.0.0.0', port))
rfid_socket.listen(5)

#Gestión de interrupciones
def handler(signum,frame):
    print("\nPrograma Terminado")
    GPIO.cleanup()
    conection.close()
    exit()

#Simulamos la apertura de puertas con un interruptor en el GPIO
def puertas_abiertas():
Beispiel #20
0
def main():

    import RPi.GPIO as GPIO
    import time
    import mysql.connector
    from datetime import datetime
    from mfrc522 import SimpleMFRC522

    reader = SimpleMFRC522()
    try:
        id, text = reader.read()
        #print(id)

    finally:
        GPIO.cleanup()

    mydb = mysql.connector.connect(host="localhost",
                                   user="******",
                                   passwd="PI",
                                   database="Club_door")

    #print(mydb)

    mycursor = mydb.cursor()

    mycursor.execute("select rfid_code from access_list")

    myresult = mycursor.fetchall()

    for row in myresult:
        #    print(row)

        #from datetime import datetime
        # datetime object containing current date and time
        now = datetime.now()
    a = now.strftime("%Y-%m-%d")
    b = now.strftime("%H:%M:%S")
    #print(a)
    RFID_ID = id
    if (RFID_ID in row):
        print("access granted")
        mycursor = mydb.cursor()
        sql = "INSERT INTO access_log (rfid_presented, rfid_presented_date,rfid_presented_time, rfid_granted) VALUES (%s,%s,%s,%s)"
        val = (RFID_ID, a, b, "granted")
        mycursor.execute(sql, val)

        mydb.commit()

        print(mycursor.rowcount, "record inserted.")
        time.sleep(2)
        main()
    else:
        print("access denied")
        mycursor = mydb.cursor()
        sql = "INSERT INTO access_log (rfid_presented, rfid_presented_date,rfid_presented_time, rfid_granted) VALUES (%s,%s,%s,%s)"
        val = (RFID_ID, a, b, "denied")
        mycursor.execute(sql, val)

        mydb.commit()

        print(mycursor.rowcount, "record inserted.")
        time.sleep(2)
        main()