Esempio n. 1
0
def navigate():
	'''
		Function will call exploration() function to move robot, but will keep
		track of previous moves
	'''

	# Test output
	print("Navigating ...")

	# Create motor and buzzer objects
	motor = Motor()
	buzzer = Buzzer()

	# Beep to indicate begining of navigate step
	buzzer.play(4)

	try:
		# Enter the exploration loop
		for i in xrange(params.p['MAX_ITER']):

			# Execute explore function and save results
			explore(motor, buzzer)

			# Wait between moves
			time.sleep(params.p['WAIT_TIME'])
	except Exception:
		pass
	finally:
		motor.stop_bot()
Esempio n. 2
0
def captureInfoCam():
    GPIO.setwarnings(False) # Ignore warning for now
    GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
                    
    subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/image.jpg', '-1'], shell=True)

    #Azure
    face_uri = "https://raspberrycp.cognitiveservices.azure.com/vision/v1.0/analyze?visualFeatures=Faces&language=en"
    pathToFileInDisk = r'/home/pi/Desktop/image.jpg'
    with open( pathToFileInDisk, 'rb' ) as f:
        data = f.read()
        
    headers = { "Content-Type": "application/octet-stream" ,'Ocp-Apim-Subscription-Key': '7e9cfbb244204fb994babd6111235269'}
    try:
        response = requests.post(face_uri, headers=headers, data=data)
        faces = response.json()
        
        #pprint(faces)
        age = faces['faces'][0].get('age')
        gender = faces['faces'][0].get('gender')
        
        datosUsuario = [age, gender]
        return datosUsuario
    except requests.exceptions.ConnectionError:
        return None
    except IndexError:
        buzzer=Buzzer(13)
        buzzer.buzz(seconds=0.5)
        return None
    else:
        return datosUsuario
Esempio n. 3
0
def main(args):
    global pisugar, paper, ui
    buzzer = Buzzer(pin=16)

    buzzer.play(sound=buzzer.alert, blocking=False, repeat=100)

    ui.build = buildCustomUI
    ui.start()

    vbeacon.startScanning()
    vbeacon.startAdvertising()
    print("--------------------------\nDEBUG 1: " +
          (str)(vbeacon.isAdvertising) + "\n-----------------------")

    done = False
    while not done:
        try:
            beaconsNearby = vbeacon.getNearbyBeacons()

            print("-------------------------------------")
            print(f" {len(beaconsNearby)} beacons nearby")
            print("-------------------------------------")

            for beacon in beaconsNearby:
                print(f"{beacon}")

            time.sleep(1.0)
        except KeyboardInterrupt:
            done = True

    vbeacon.stopAdvertising()
    vbeacon.stopScanning()
Esempio n. 4
0
    def __init__(self):
        super().__init__()

        #initialization
        self.CLASSES = [
            "background", "aeroplane", "bicycle", "bird", "boat", "bottle",
            "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse",
            "motorbike", "person", "pottedplant", "sheep", "sofa", "train",
            "tvmonitor"
        ]
        self.COLORS = np.random.uniform(0, 255, size=(len(self.CLASSES), 3))

        # python3 pi_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
        self.args = {
            "prototxt": "MobileNetSSD_deploy.prototxt.txt",
            "model": "MobileNetSSD_deploy.caffemodel",
            "confidence": 0
        }

        #load serialized model from disk (neural network model)
        print("[INFO] loading model...")
        #IDK
        self.net = cv2.dnn.readNetFromCaffe(self.args["prototxt"],
                                            self.args["model"])

        #init input queue (frames), output queues (detections) + list of actual
        #detections returned by child process
        self.inputQueue = Queue(
            maxsize=1)  #populated by parent, processed by child
        self.outputQueue = Queue(
            maxsize=1
        )  #populated by child, processed by parent (output from processing input)
        self.detections = None

        #construct child process *independent* from main process of execution
        print("[INFO] starting process...")
        p = Process(target=self.classify_frame,
                    args=(
                        self.net,
                        self.inputQueue,
                        self.outputQueue,
                    ))
        p.daemon = True
        p.start()

        # init video stream, allow camera warmup + init FPS counter
        print("[INFO] starting stream...")
        # cap=cv2.VideoCapture(0)
        # vs = VideoStream(usePiCamera=True).start()
        time.sleep(1.0)
        self.fps = FPS().start()
        self.area = 0
        self.my_priority_queue = PriorityQueue(maxsize=0)

        self.buzzer = Buzzer()
Esempio n. 5
0
def main():
    try:
        os.nice(-15)
    except OSError:
        print("Process priority could not be decreased!")

    EntryHR = OuterHandReader.OHandReader(12, 18, 1)
    print("Entry Hand Reader Initialized!")
    ExitHR = ExitHandReader.ExitHandReader(32, 31)
    print("Exit Hand Reader Initialized!")
    MD = MaskDetector.MaskDetector(headless=False)
    print("Mask Detector Initialized!")
    door = Door()
    print("Door Initialized!")
    B = Buzzer(33)

    while True:
        controller.STATE = controller.DORMANT
        while controller.STATE == controller.DORMANT:
            if (ExitHR.read()):
                controller.STATE = controller.UNLOCKED
                print("The door is unlocked!")
                B.positiveresponse()
                door.exit()
                sleep(1)
            sleep(0.1)

        controller.STATE = controller.VERIFICATION
        print("Verification state")
        MD.start_display()
        while controller.STATE == controller.VERIFICATION:
            result = EntryHR.read()
            if (HAND_APPROVED == result):
                print("Checking face mask.")
                result = MD.last_label()
                if result == "Mask":
                    print("Greetings. The door is unlocked.")
                    #controller.STATE = controller.UNLOCKED
                    B.positiveresponse()
                    door.entrance()
                elif result == "Improper Mask":
                    print(
                        "Please wear your mask properly. When you do, have your hand measured again. Thank you!"
                    )
                    B.ringwarning()
                else:
                    print(
                        "You do not have a mask on! Please leave the door front area!"
                    )
                    B.ringerror()
                    #controller.STATE = controller.LOCKED

        sleep(5)
Esempio n. 6
0
	def __init__(self):
		threading.Thread.__init__(self)
		self.shutdown_flag = threading.Event()
		self.motor = Motorcontroller()
		self.buzzer = Buzzer()
		self.xbee = Xbee()
		self.decoder = Decoder()
		self.servo1 = 96
		self.servo2 = 75
		self.joycalc = Joystick()
		self.motor.setServo1(self.servo1)
		self.motor.setServo2(self.servo2)
		self.lastSavedTime = 0
Esempio n. 7
0
    def __init__(self, database, sensorProcess, led):

        self.database = database
        self.buzzer = Buzzer()
        self.sp = sensorProcess
        self.password = ''
        self.typePassword = 0
        self.led = led
Esempio n. 8
0
    def __connect_buzzer(self, key, name):
        """
        Interface de connexion de manette
        :param key: avec quelle key sera stockée le buzzer dans self.buzzers
        :param name: le nom qui sera affiché à l'écran
        """

        # Si on a déjà un Buzzer du même nom, on le récupère
        buzzer_en_attente = None
        if key in self.buzzers:
            buzzer_en_attente = self.buzzers[key]
        else:
            buzzer_en_attente = Buzzer(key, dummy=self.dummy)

        # Démarre la connexion de façon asynchrone
        buzzer_en_attente.async_wait()

        # Ouvre une fenêtre
        win = WindowHelper.Instance()
        win.new_page('Page de connexion', WIN_WIDTH, WIN_HEIGHT ,label='connect_buzzer', bg='white')
        win.go_to('connect_buzzer')

        win.import_template('wiimote_connexion')
        win.edit_text('text_connexion_team', 'Télécommande {}'.format(name))  # à modifier

        win.refresh()

        # Variable d'execution
        vars = {
            'buzzer_en_attente': buzzer_en_attente,
            'self': self
        }

        # Attend que la manette soit connectée
        def waiting_connection(pg, win, vars, event):
            if event.type == pg.KEYDOWN and event.key == pg.K_d:
                vars['buzzer_en_attente'].dummy = True

        def before_fun(pg, win, vars):
            return vars['buzzer_en_attente'].connected

        win.event(before_fun=before_fun, event_fun=waiting_connection, vars=vars)  # On attend que quelqu'un appuie sur un bouton

        # Stocke le nouveau buzzer
        self.buzzers[key] = buzzer_en_attente
Esempio n. 9
0
	def __init__(self, led):
		self.database = database = Database()
		self.timeout = 60
		self.timeout_thread = threading.Thread(target=self.start_timer_process, args=(self.timeout,))
		self.soundingAlarm = 0
		self.buzzer = Buzzer()
		self.led = led
		self.led_status_thread = threading.Thread(target=self.led.status_light)
		self.led_status_thread.start()
		self.sensor = None
Esempio n. 10
0
    def __init__(self):
        self.advertLoop = None
        self.advertiser = None
        self.ad_manager = None
        self.advertThread = None

        self.scanThread = None
        self.scanExit = True
        self.scanMutex = threading.Lock()
        self.beaconList = {}

        self.company_id = 0x004c
        self.beacon_type = [0x02, 0x15]
        self.uuid = uuid.UUID('{2f234454-cf6d-4a0f-adf2-f4911ba9ffa6}')
        self.tx_power = [0xb3]
        self.major = 0
        self.minor = 0

        self.deviceSettings = {}
        self.pisugar = PiSugar2()
        self.buzzer = Buzzer(16)
Esempio n. 11
0
 def __init__(self, config):
     self.__config = config
     self.__navegador = Navegador(self.__config)
     self.__sensorDeObjetos = SensorDeObjetos(
         config.DomoPatronAReconocer, config.DomoCamaraId,
         config.DomoMostrarEnVentanaReconocimiento,
         config.DomoFotogramasXCaptura)
     self.__testigoLuminoso = Led()
     self.__testigoSonoro = Buzzer()
     if self.__config.DomoMostrarEnVentanaCentrado:
         cv.NamedWindow(self.__windowName, 1)
     self.__debugMode = self.__config.DomoDebugMode
Esempio n. 12
0
def navigate(room, new_area):

    # initialize room.current_area if it does not exsist
    if not room.current_area:
        room.current_area = Area()

    # Test output
    print "Navigating (moving to a known area) ..."

    # Beep to indicate begining of navigate step
    buzzer = Buzzer()
    buzzer.play(4)

    # Make sure a path exsists between the two areas
    if room.current_area not in new_area.previous:
        print "No path between nodes"
        return

    # Get move required to travel between areas
    move = new_area.moves_performed[room.current_area.name]

    # TODO: moves_performed will just be the latest move performed between the two areas
    # Need to find a way to find the "best" move between them

    # Execute motion primitives between nodes
    for (direction, amount) in move.primitives:
        print "Moving" + str(direction) + " " + str(amount)
        # moveBot(direction, amount, params.p['MOTOR_PWR'])

    # Get final position by summing initial position and delta
    move.final_pos = [init + delt for init, delt in zip(move.initial_pos, move.delta)]

    # TODO: put a kalman filter on the movement. Use camera and sonar as
    # truth? Not sure here

    # TODO: figure out what area you are in by looking at pictures
    new_area.localize

    # Add move to new area's dictionary of moves
    new_area.moves_performed[room.current_area.name] = move
Esempio n. 13
0
    def detected(self, pin):
        settings = DbClass().getDataFromDatabase('settings')[0]
        print("motion detected")

        if settings[1]:
            print('start recording')

            if settings[4]:
                print('led')
                LedLamp().flikker_bg(5)

            if settings[3]:
                print('alarm')
                Buzzer().alarm_bg(5)

            if settings[5]:
                print('email send')
Esempio n. 14
0
def explore(room):  # Move to a new area, returns area object

    # initialize room.current_area if it does not exsist
    if not room.current_area:
        room.current_area = Area()

    # Test output
    print "Exploring (moving to a new location) ..."

    # Beep to indicate begining of explore step
    buzzer = Buzzer()
    buzzer.play(5)

    # Create new area and move objects
    new_area = Area()
    move = Move()

    # Make sure move is set as a real move (performed by robot)
    move.type = "Real"

    # Link it to the previous object
    new_area.previous.append(room.current_area.name)

    # Initial position set to position of previous area
    move.initial_pos = room.current_area.pos

    # Vector of movement used
    move = get_move_vector(move)

    # Break down movement vector into motion primitives that robot can execute
    move.getMotionPlan()

    for (direction, amount) in move.primitives:
        print "Moving " + str(direction) + " " + str(amount)
        # moveBot(direction, amount, params.p['MOTOR_PWR'])

    # Get final position by summing initial position and delta
    move.final_pos = [init + delt for init, delt in zip(move.initial_pos, move.delta)]

    # TODO: put a kalman filter on the movement. Use camera and sonar as
    # truth? Not sure here

    # # Test print
    # print "Describing move in explore function"
    move.describe()

    # Update location of new area to final position of move
    new_area.pos = move.final_pos

    # Add move to new area's dictionary of moves
    new_area.moves_performed[room.current_area.name] = move

    # Redirect current area to this new_area
    room.current_area = new_area

    # Localize bot in new area
    # new_area.localize

    # # Test print
    # print "Describing new_area in explore function"
    # new_area.describe()

    # Append new_area to room
    room.areas.append(new_area)

    # Return updated room object
    return room
Esempio n. 15
0
import RPi.GPIO as GPIO  # Importing RPi library to use the GPIO pins
from time import *  # Used for sleep method
from bluetooth import *  # Imports libraries that supports Bluetooth
from AlphaBot import AlphaBot
from Buzzer import Buzzer
from Rgb import Rgb
from Temperature import Temperature
import instructions  # Methods where String commands are translated into separate instructions

# ----------------------------------------- INITIALIZATION -------------------------------------------------------------

Ab = AlphaBot(
)  # Instance of AlphaBot created    | delivers EcliBot movement methods
b = Buzzer(
    23)  # Instance of Buzzer created      | buzzer can be switched on/off
t = Temperature(
    11,
    18)  # Instance of Temperature created | temperature can be red from sensor
rgb = Rgb(
    5, 19, 16
)  # Instance of Rgb created         | LED diode can turns red, green, blue, or off

commands = []  # List designed for storing instructions for EcliBot
step = 0  # Counter, used for keeping track the number of Strings received

GPIO.setmode(
    GPIO.BCM)  # Referring to the pins by the "Broadcom SOC channel" number
GPIO.setwarnings(False)  # Disable warnings

# ----------------------------------------- CUSTOMIZED MOVE METHODS ----------------------------------------------------
Esempio n. 16
0
 def __init__(self):
     self.fire_detected = False
     self.buzzer = Buzzer()
     self.adc = MCP3008()
Esempio n. 17
0
from time import sleep

#configurations
distance_threshold = 20  #in CM
blink_beep_speed = Speed.FAST

#variables
picture_taken = False

#objects
sensor = UltrasonicSensor(19, 26)
email = Email()
camera = Camera()
grn_led = LED(13)
red_led = LED(6)
buzzer = Buzzer(5)


#methods
def blink_red():
    red_led.blink(5, blink_beep_speed)


def blink_green():
    grn_led.blink(5, blink_beep_speed)


def beep_buzzer():
    buzzer.beep(5, blink_beep_speed)

Esempio n. 18
0
    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"
Esempio n. 19
0
class Buttons:

    def __init__(self, database, sensorProcess, led):

        self.database = database
        self.buzzer = Buzzer()
        self.sp = sensorProcess
        self.password = ''
        self.typePassword = 0
        self.led = led

        #buttons_thread = threading.Thread(target=self.start,)
        #buttons_thread.start()
        #self.start()
     
    # read SPI data from MCP3008 chip, 8 possible adc's (0 thru 7)
    def readadc(self, adcnum, clockpin, mosipin, misopin, cspin):
            if ((adcnum > 7) or (adcnum < 0)):
                    return -1
            GPIO.output(cspin, True)
     
            GPIO.output(clockpin, False)  # start clock low
            GPIO.output(cspin, False)     # bring CS low
     
            commandout = adcnum
            commandout |= 0x18  # start bit + single-ended bit
            commandout <<= 3    # we only need to send 5 bits here
            for i in range(5):
                    if (commandout & 0x80):
                            GPIO.output(mosipin, True)
                    else:
                            GPIO.output(mosipin, False)
                    commandout <<= 1
                    GPIO.output(clockpin, True)
                    GPIO.output(clockpin, False)
     
            adcout = 0
            # read in one empty bit, one null bit and 10 ADC bits
            for i in range(12):
                    GPIO.output(clockpin, True)
                    GPIO.output(clockpin, False)
                    adcout <<= 1
                    if (GPIO.input(misopin)):
                            adcout |= 0x1
     
            GPIO.output(cspin, True)
            
            adcout >>= 1       # first bit is 'null' so drop it
            return adcout
     
    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"

    def play_song(self):
        print 'boo'
        self.buzzer.mario()
Esempio n. 20
0
class vBeacon():

    #-------------------------------------------------------------------------
    #  Initializer
    #-------------------------------------------------------------------------
    def __init__(self):
        self.advertLoop = None
        self.advertiser = None
        self.ad_manager = None
        self.advertThread = None

        self.scanThread = None
        self.scanExit = True
        self.scanMutex = threading.Lock()
        self.beaconList = {}

        self.company_id = 0x004c
        self.beacon_type = [0x02, 0x15]
        self.uuid = uuid.UUID('{2f234454-cf6d-4a0f-adf2-f4911ba9ffa6}')
        self.tx_power = [0xb3]
        self.major = 0
        self.minor = 0

        self.deviceSettings = {}
        self.pisugar = PiSugar2()
        self.buzzer = Buzzer(16)

    #-------------------------------------------------------------------------
    #  Advertiser registration callback
    #-------------------------------------------------------------------------
    def register_ad_cb(self):
        return

    #-------------------------------------------------------------------------
    #  Advertiser registration error callback
    #-------------------------------------------------------------------------
    def register_ad_error_cb(self, error):
        print('Failed to register advertisement: ' + str(error))
        self.advertLoop.quit()

    #-------------------------------------------------------------------------
    #  Find adaptor
    #-------------------------------------------------------------------------
    def find_adapter(self, bus):
        remote_om = dbus.Interface(bus.get_object(BLUEZ_SERVICE_NAME, '/'),
                                   DBUS_OM_IFACE)
        objects = remote_om.GetManagedObjects()

        for o, props in objects.items():
            if LE_ADVERTISING_MANAGER_IFACE in props:
                return o
        return None

    #-------------------------------------------------------------------------
    #  Given a beacon return device ID string by concatenating
    #  major and minor in a 4 byte value
    #-------------------------------------------------------------------------
    def _deviceKey(self, beacon):
        key = hex(beacon['major']) + hex(beacon['minor'])
        return key

    #-------------------------------------------------------------------------
    #  Return device ID which is concatenation of major and minor in hex
    #-------------------------------------------------------------------------
    def deviceId(self):
        id = hex(self.major) + hex(self.minor)
        return id

    #-------------------------------------------------------------------------
    #  Stop advertisement
    #-------------------------------------------------------------------------
    def stopAdvert(self):
        self.advertLoop.quit()

        self.advertThread.join()
        self.ad_manager.UnregisterAdvertisement(self.advertiser)
        dbus.service.Object.remove_from_connection(self.advertiser)

        self.advertiser = None
        self.advertLoop = None
        print('Stopped advertising')

    #-------------------------------------------------------------------------
    #
    #  Start advertisement for 'timeout' seconds
    #
    #     timeout = 0, continuous advertisement
    #     timeout > 0, stop advertisement after 'timeout' seconds
    #
    #-------------------------------------------------------------------------
    def startAdvert(self):

        if self.advertiser is not None:
            return False

        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        bus = dbus.SystemBus()
        adapter = self.find_adapter(bus)
        if not adapter:
            print('LEAdvertisingManager1 interface not found')
            return

        adapter_props = dbus.Interface(
            bus.get_object(BLUEZ_SERVICE_NAME, adapter),
            "org.freedesktop.DBus.Properties")
        adapter_props.Set("org.bluez.Adapter1", "Powered", dbus.Boolean(1))
        self.ad_manager = dbus.Interface(
            bus.get_object(BLUEZ_SERVICE_NAME, adapter),
            LE_ADVERTISING_MANAGER_IFACE)

        self.advertiser = Advertisement(bus, 0, 'peripheral')
        self.advertiser.add_manufacturer_data(
            self.company_id, self.beacon_type + list(self.uuid.bytes) +
            [self.major / 256, self.major % 256] +
            [self.minor / 256, self.minor % 256] + self.tx_power)

        self.advertLoop = GLib.MainLoop()

        self.ad_manager.RegisterAdvertisement(
            self.advertiser.get_path(), {},
            reply_handler=self.register_ad_cb,
            error_handler=self.register_ad_error_cb)

        self.advertThread = threading.Thread(target=self.advertLoop.run)
        self.advertThread.setDaemon(True)
        self.advertThread.start()
        print("Start advertising")
        return True

    #-------------------------------------------------------------------------
    #  Scan loop
    #-------------------------------------------------------------------------
    def _scanLoop(self):

        #Set bluetooth device. Default 0.
        dev_id = 0
        try:
            sock = bluez.hci_open_dev(dev_id)
        except:
            print("Error accessing bluetooth")

        ScanUtility.hci_enable_le_scan(sock)

        self.scanExit = False

        self.scanMutex.acquire()
        self.beaconList = {}
        self.scanMutex.release()

        while not self.scanExit:
            beacons = ScanUtility.parse_events(sock, 10)

            currTime = datetime.datetime.now()

            self.scanMutex.acquire()
            for beacon in beacons:
                if beacon['type'] == 'iBeacon':
                    if beacon['uuid'] == str(self.uuid):
                        self.beaconList[self._deviceKey(beacon)] = (currTime,
                                                                    beacon)
                '''
          elif beacon['type'] == 'Overflow':
            if beacon['uuid'] == '2f234454-cf6d-4a0f-adf2-f4911ba9ffa6':
              print("Overflow:-------------")
              print(beacon)
              print("")
          '''
            self.scanMutex.release()

    #-------------------------------------------------------------------------
    #  Stop scanning
    #-------------------------------------------------------------------------
    def stopScanning(self):
        self.scanExit = True
        self.scanThread.join()
        print("Stopped scanning")

    #-------------------------------------------------------------------------
    #  Start scanning
    #-------------------------------------------------------------------------
    def startScanning(self):
        self.scanThread = threading.Thread(target=self._scanLoop)
        self.scanThread.setDaemon(True)
        self.scanThread.start()
        print("Start scanning")

    #-------------------------------------------------------------------------
    #  Wake after function
    #-------------------------------------------------------------------------
    def setWakeAfter(self, seconds):
        now = datetime.datetime.now()
        res = self.pisugar.set_rtc_alarm(now + datetime.timedelta(0, seconds),
                                         [1, 1, 1, 1, 1, 1, 1])

    #-------------------------------------------------------------------------
    #  Sleep function
    #-------------------------------------------------------------------------
    def gotoSleep(self):
        self.pisugar.force_shutdown()

    #-------------------------------------------------------------------------
    #  Check social distancing
    #-------------------------------------------------------------------------
    def checkSocialDistancing(self, dist):
        print("Checking social distance...")
        now = datetime.datetime.now()

        inViolation = False

        self.scanMutex.acquire()
        for key in self.beaconList:
            (t, b) = self.beaconList[key]
            if (b['rssi'] > dist):
                inViolation = True
        self.scanMutex.release()

        if inViolation:
            print("Social distance violation!!!")
            self.buzzer.play(sound=self.buzzer.alert, repeat=0)

    #-------------------------------------------------------------------------
    #  Run the App
    #-------------------------------------------------------------------------
    def runApp(self, settings):

        with open(settings) as f:
            self.deviceSettings = json.load(f)

        self.uuid = uuid.UUID(self.deviceSettings['uuid'])
        self.major = self.deviceSettings['major']
        self.minor = self.deviceSettings['minor']
        self.name = self.deviceSettings['name']
        self.org = self.deviceSettings['org']
        self.onTime = self.deviceSettings['onTime']
        self.wakeTime = self.deviceSettings['wakeTime']
        self.socialDist = self.deviceSettings['socialDist']

        print(f"uuid={str(self.uuid)}")

        self.startAdvert()
        self.startScanning()

        done = False
        seconds = 0

        while not done:

            time.sleep(1.0)
            seconds = seconds + 1

            # Report to backend
            # Log to file

            self.checkSocialDistancing(self.socialDist)

            if seconds >= self.onTime:
                break

        print("Shutting down....")
        self.stopScanning()
        self.stopAdvert()

        print(f"Wake after {self.wakeTime - seconds}")
Esempio n. 21
0
class SensorProcess():

	def __init__(self, led):
		self.database = database = Database()
		self.timeout = 60
		self.timeout_thread = threading.Thread(target=self.start_timer_process, args=(self.timeout,))
		self.soundingAlarm = 0
		self.buzzer = Buzzer()
		self.led = led
		self.led_status_thread = threading.Thread(target=self.led.status_light)
		self.led_status_thread.start()
		self.sensor = None

	def trip_sensor(self,sensorId):
		self.cancelTimer = 0

		status = self.database.system_status()
		print 'system status '+status

		if(status=='1'):

			sensor = self.database.get_sensor(sensorId)
			self.sensor = sensor	

			if(sensor and sensor['status']):

				if(self.soundingAlarm == 0):
					self.buzzer.beep(659, 125)

				message = "Sensor Tripped: "+sensor['title']
				self.database.log(message)

				print 'tripped sensor: '+sensor['title']
				print sensor['type'] 
				if(sensor['type'] == 'Door'):
					self.start_timer()
					print 'sensor type: Door'

				elif(sensor['type'] == 'Window'):
					print 'sensor type: Window'
					# sound alarm
					print 'BEEP'
					self.alert()

				elif(sensor['type'] == 'Room'):
					print 'sensor type: Room'
					# sound alarm
					print 'BEEP'
					self.alert()
			else:
				print 'sensor not found'
		else:
			self.buzzer.beep(800, 20)
			time.sleep(0.1)
			self.buzzer.beep(800, 20)

	def start_timer(self):
		print 'trying to start timer'		

		if(self.timeout_thread.isAlive()==False):
			try:
				print 'START TIMER'
				self.timeout_thread = threading.Thread(target=self.start_timer_process, args=(self.timeout,))
				self.timeout_thread.start()
			except:
				print 'Trouble with t1 synchronizer'				
		
	def start_timer_process(self,timeout):
		self.cancelTimer = 0
		
		timeout = timeout*10
		while timeout > 0:

			if(timeout % 4 == 0):
				self.buzzer.beep(800, 25)

			# correct code entered
			if self.cancelTimer:
				break
			# sleep
			else:
				print(timeout)
				timeout -=1

				# need a small time otherwise it takes too long to stop the timer
				time.sleep(0.1)

		# send alerts
		if(self.cancelTimer == 0):
			self.alert()

	def stop_timer(self):
		print 'STOP TIMER'
		self.cancelTimer = 1

	def alert(self):
		print 'sending alerts'

		if(self.soundingAlarm == 0):

			self.alarmSound_thread = threading.Thread(target=self.sound_alarm)
			self.alarmSound_thread.start()

			users = self.database.get_users()		

			client = TwilioRestClient("ACc4cb12c713e1483cb661100848c562b8", "c829b7d4169070c10e5121f0a55180af")

			for user in users:
				
				if(user['alert'] == 0):
					continue;

				message = self.sensor['title']+' Sensor Tripped'
				client.sms.messages.create(to=user['phone'], from_="+15855981936", body=message)

				SUBJECT = "BADAX Alerts"
				TO = user['email']
				FROM = "*****@*****.**"
				BODY = string.join((
				        "From: %s" % FROM,
				        "To: %s" % TO,
				        "Subject: %s" % SUBJECT ,
				        "",
				        message
				        ), "\r\n")
				mailServer = smtplib.SMTP('smtp.gmail.com')
				mailServer.starttls()
				mailServer.login('*****@*****.**', 'sourfarm39')
				mailServer.sendmail(FROM, [TO], BODY)
				mailServer.quit()

	def sound_alarm(self):
		self.led.show_status_light = 0
		if(self.soundingAlarm == 0):
			self.soundingAlarm = 1
			while(self.soundingAlarm):
				self.buzzer.beep(800, 100)
				time.sleep(0.1)
Esempio n. 22
0
if __name__ == "__main__":
    now_Thread = 0
    flags = [False, False, False, False, False, False, False, False, False]
    thread_flags = [False, False, False, False, False]
    GPIO.cleanup()
    sensing_Rover = Sensing_Rover()

    pcf8591 = Pcf8591(0x48)
    gas = Gas(pcf8591, ain=2)
    thermister = Thermistor(pcf8591, ain=1)
    tracking = Tracking(32)
    photoresister = Photoresister(pcf8591, ain=0)
    ultra = HcSr04(trigpin=38, echopin=40)
    queue = queue.Queue()
    rgbLed = RgbLed(16, 18, 22)
    buzzer = Buzzer(35)
    laser = Laser(37)
    lcd = Lcd1602(0x27)

    pca9685 = Pca9685()
    dc_left = DC(11, 12, pca9685)
    dc_right = DC(13, 15, pca9685)
    channel_left = 5
    channel_right = 4
    set_speed = 80

    sv = Sg90(pca9685, 0)  # 5~90도   (default = 12도, 줄어들면 LOWER, 커지면 HIGHER)
    sh = Sg90(pca9685, 1)  # 12~170도   (default = 90도, 줄어들면 RIGHT, 커지면 LEFT)
    sw = Sg90(pca9685, 14)  # 50~130도   (default = 90도, 줄어들면 LEFT, 커지면 RIGHT)
    su = Sg90(pca9685, 15)  # 40~120도   (default = 80도, 줄어들면 RIGHT, 커지면 LEFT)
Esempio n. 23
0
#----------------------------
# Imported Modules
#----------------------------
import gesture as ges
from OLED import OLED
from Buzzer import Buzzer
import time

#----------------------------
# Globals
#----------------------------
ledHeader = "getFlag();\n"
display = OLED()
audio = Buzzer()
display.clear()
display.resetCursor()
display.write(ledHeader)
audio.connected()
time.sleep(1)
#----------------------------
# Print Initialization to LED
#----------------------------
buzz = [0]
buzzfinal = [4]
microsec = [16]
for i in range(0, 3):
    message = ledHeader + "Starting\n\t\t\t" + str(3 - i)
    display.clear()
    display.resetCursor()
    display.write(message)
    audio.play(buzz, microsec)
Esempio n. 24
0
    inputQueue,
    outputQueue,
))
p.daemon = True
p.start()

#init video stream, allow camera warmup + init FPS counter
print("[INFO] starting stream...")
#cap=cv2.VideoCapture(0)
vs = VideoStream(usePiCamera=True).start()
time.sleep(1.0)
fps = FPS().start()
area = 0
my_priority_queue = PriorityQueue(maxsize=0)

buzzer = Buzzer()
# playRightBuzzer = threading.Thread(target=buzzer.playRightBuzzer, args=())
# lightLeftLED = threading.Thread(target=buzzer.lightLeftLED, args=())
# closeBuzzer = threading.Thread(target=buzzer.closeBuzzer, args=())
# closeLED = threading.Thread(target=buzzer.closeLED, args=())

# def danger(isTrue):
# if (isTrue):
# playRightBuzzer.start()
# lightLeftLED.start()
# else:
# closeBuzzer.start()
# closeLED.start()

#loop over frames of vid stream
while True:
Esempio n. 25
0
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() 
printed = False
try:
    while True:
        # we'll assume that the pot didn't move
        trim_pot_changed = False
 
        # read the analog pin
        trim_pot = 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
Esempio n. 26
0
import RPi.GPIO as GPIO
import time
from flask_socketio import SocketIO, send, emit
from Led import Led
from Buzzer import Buzzer

# //Initialisation de notre GPIO 17 pour recevoir un signal
# //Contrairement à nos LEDs avec lesquelles on envoyait un signal

lightblue = Led(24)
lightred = Led(18)
buzzer = Buzzer(22)


class Mouvement():
    def __init__(self, broche):
        GPIO.setmode(GPIO.BCM)
        GPIO.setwarnings(False)
        self.broche = broche
        GPIO.setup(broche, GPIO.IN)

    def mouvement_loop(self, socketio):
        currentstate = 0
        previousstate = 0
        lightblue.on()
        while True:
            currentstate = GPIO.input(self.broche)
            if currentstate == 1 and previousstate == 0:
                previousstate = 1
                lightblue.off()
                lightred.light_blink()
 def run(self):
     Buzzer()
Esempio n. 28
0
class ObjectDetector():
    def __init__(self):
        super().__init__()

        #initialization
        self.CLASSES = [
            "background", "aeroplane", "bicycle", "bird", "boat", "bottle",
            "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse",
            "motorbike", "person", "pottedplant", "sheep", "sofa", "train",
            "tvmonitor"
        ]
        self.COLORS = np.random.uniform(0, 255, size=(len(self.CLASSES), 3))

        # python3 pi_object_detection.py --prototxt MobileNetSSD_deploy.prototxt.txt --model MobileNetSSD_deploy.caffemodel
        self.args = {
            "prototxt": "MobileNetSSD_deploy.prototxt.txt",
            "model": "MobileNetSSD_deploy.caffemodel",
            "confidence": 0
        }

        #load serialized model from disk (neural network model)
        print("[INFO] loading model...")
        #IDK
        self.net = cv2.dnn.readNetFromCaffe(self.args["prototxt"],
                                            self.args["model"])

        #init input queue (frames), output queues (detections) + list of actual
        #detections returned by child process
        self.inputQueue = Queue(
            maxsize=1)  #populated by parent, processed by child
        self.outputQueue = Queue(
            maxsize=1
        )  #populated by child, processed by parent (output from processing input)
        self.detections = None

        #construct child process *independent* from main process of execution
        print("[INFO] starting process...")
        p = Process(target=self.classify_frame,
                    args=(
                        self.net,
                        self.inputQueue,
                        self.outputQueue,
                    ))
        p.daemon = True
        p.start()

        # init video stream, allow camera warmup + init FPS counter
        print("[INFO] starting stream...")
        # cap=cv2.VideoCapture(0)
        # vs = VideoStream(usePiCamera=True).start()
        time.sleep(1.0)
        self.fps = FPS().start()
        self.area = 0
        self.my_priority_queue = PriorityQueue(maxsize=0)

        self.buzzer = Buzzer()

    def execute(self, ImageQueue):
        while True:
            #grab frame from threaded vidstream, resize + dimensions!!
            # frame = vs.read()
            # frame = cv2.rotate(frame,cv2.ROTATE_180)
            # #ret, frame = cap.read()
            # frame = imutils.resize(frame, width=400)
            if ImageQueue.empty():
                continue

            frame = ImageQueue.get()
            (fH, fW) = frame.shape[:2]

            #if input queue IS empty, give current frame to classify
            if self.inputQueue.empty():
                self.inputQueue.put(frame)
            #if output queue IS NOT empty, grab detections
            if not self.outputQueue.empty():
                self.detections = self.outputQueue.get()

            #check to see if detections are not None (if None, draw detections on frame)
            if self.detections is not None:
                #ret, img=cap.read()
                #loop over detections
                for i in np.arange(0, self.detections.shape[2]):
                    # extract the confidence (i.e., probability) associated
                    # with the prediction
                    confidence = self.detections[0, 0, i, 2]

                    # filter out weak detections by ensuring the `confidence`
                    # is greater than the minimum confidence
                    if confidence < self.args["confidence"]:
                        continue

                    # otherwise, extract the index of the class label from
                    # the `detections`, then compute the (x, y)-coordinates
                    # of the bounding box for the object
                    idx = int(self.detections[0, 0, i, 1])
                    dims = np.array([fW, fH, fW, fH])
                    box = self.detections[0, 0, i, 3:7] * dims
                    # if (idx==15) and confidence * 100 > 90:
                    # try:
                    # areaBef = ((endY-startY)*(endX-startX))
                    # except:
                    # areaBef = -99;
                    (startX, startY, endX, endY) = box.astype("int")

                    # only run once
                    if self.area == 0 and idx == 15 and confidence * 100 > 80:
                        self.area = -(endY - startY) * (endX - startX)
                        self.my_priority_queue.put(self.area)
                        continue

                    if idx == 5 or idx == 6 or idx == 7 or idx == 9 or idx == 15:
                        # draw the prediction on the frame
                        label = "{}: {:.2f}%".format(self.CLASSES[idx],
                                                     confidence * 100)
                        cv2.rectangle(frame, (startX, startY), (endX, endY),
                                      self.COLORS[idx], 2)
                        y = startY - 15 if startY - 15 > 15 else startY + 15
                        cv2.putText(frame, label, (startX, y),
                                    cv2.FONT_HERSHEY_SIMPLEX, 0.5,
                                    self.COLORS[idx], 2)
                        if (idx == 15) and confidence * 100 > 80:
                            current_area = -(endY - startY) * (endX - startX)
                            # self.my_priority_queue.put(current_area)

                            largest_area = self.my_priority_queue.get()
                            print("The ratio of largest area is {}".format(
                                largest_area / (300 * 300)))

                            if (-current_area > -largest_area
                                    and -current_area > 300 * 300 / 3):
                                print("Danger!!")
                                self.buzzer.execute("playRightBuzzer")
                                self.buzzer.execute("lightLeftLED")
                                #print("last area is {}".format(current_area))
                                self.area = 0

                            elif (-current_area < -largest_area
                                  and -largest_area > 300 * 300 / 3):
                                print("less Danger!!")
                                self.buzzer.execute("lightLeftLED")
                                #print("last area is {}".format(largest_area))
                                self.area = 0
                                self.my_priority_queue.put(current_area)

                            elif (-current_area > -largest_area
                                  and -current_area < 300 * 300 / 3):
                                self.my_priority_queue.put(largest_area)

                            else:
                                #print("last area is {}".format(largest_area))
                                #print("current area is {}".format(current_area))
                                #print("different area is {}".format(largest_area - current_area))
                                self.my_priority_queue.put(current_area)
                                # my_priority_queue.put(current_area)

                            # if (((endY-startY)*(endX-startX))) > 45000 and (areaBef != -99) and (((endY-startY)*(endX-startX))/(areaBef) > 1.2):
                            # print("RUN!!!")
                            # print(self.CLASSES[idx])
                            # print ("end: " + str((endY-startY)*(endX-startX)))
                            # print ("beg: " + str(areaBef))

                    # cv2.imshow("Frame", frame)
                    cv2.waitKey(5)
                    key = cv2.waitKey(5)

                    # if the `q` key was pressed, break from the loop
                    if key == ord("q"):
                        break

                    # update the FPS counter
                    self.fps.update()
            time.sleep(0.3)

    def classify_frame(self, net, inputQueue, outputQueue):
        while True:
            #check if frame present in input queue
            if not inputQueue.empty():
                #grab frame from input queue, resize, + construct blob from it
                frame = inputQueue.get()
                frame = cv2.resize(frame, (300, 300))
                blob = cv2.dnn.blobFromImage(
                    frame, 0.007843, (300, 300),
                    127.5)  #image, scalefactor, size, mean)

                #set blob as input to deep learning obj (net) + obtain detections
                net.setInput(blob)
                detections = net.forward()

                #write detections to output queue
                outputQueue.put(detections)

    def __del__(self):
        # stop the timer and display FPS information
        self.fps.stop()
        print("[INFO] elapsed time: {:.2f}".format(self.fps.elapsed()))
        print("[INFO] approx. FPS: {:.2f}".format(self.fps.fps()))

        # do a bit of cleanup
        cv2.destroyAllWindows()
Esempio n. 29
0
    def setup(self):
        
        try:

            # Iterate over the joystick devices.
            print('Available devices:')

            for fn in os.listdir('/dev/input'):
                if fn.startswith('js'):
                    print(('  /dev/input/%s' % (fn)))

            # We'll store the states here.
            axis_states = {}
            button_states = {}

            # These constants were borrowed from linux/input.h
            axis_names = {
                0x00 : 'x',
                0x01 : 'y',
                0x02 : 'z',
                0x03 : 'rx',
                0x04 : 'ry',
                0x05 : 'rz',
                0x06 : 'trottle',
                0x07 : 'rudder',
                0x08 : 'wheel',
                0x09 : 'gas',
                0x0a : 'brake',
                0x10 : 'hat0x',
                0x11 : 'hat0y',
                0x12 : 'hat1x',
                0x13 : 'hat1y',
                0x14 : 'hat2x',
                0x15 : 'hat2y',
                0x16 : 'hat3x',
                0x17 : 'hat3y',
                0x18 : 'pressure',
                0x19 : 'distance',
                0x1a : 'tilt_x',
                0x1b : 'tilt_y',
                0x1c : 'tool_width',
                0x20 : 'volume',
                0x28 : 'misc',
            }
                    
            button_names = {
                0x120 : 'trigger',
                0x121 : 'thumb',
                0x122 : 'thumb2',
                0x123 : 'top',
                0x124 : 'top2',
                0x125 : 'pinkie',
                0x126 : 'base',
                0x127 : 'base2',
                0x128 : 'base3',
                0x129 : 'base4',
                0x12a : 'base5',
                0x12b : 'base6',
                0x12f : 'dead',
                0x130 : 'a',
                0x131 : 'b',
                0x132 : 'c',
                0x133 : 'x',
                0x134 : 'y',
                0x135 : 'z',
                0x136 : 'tl',
                0x137 : 'tr',
                0x138 : 'tl2',
                0x139 : 'tr2',
                0x13a : 'select',
                0x13b : 'start',
                0x13c : 'mode',
                0x13d : 'thumbl',
                0x13e : 'thumbr',
                
                0x220 : 'dpad_up',
                0x221 : 'dpad_down',
                0x222 : 'dpad_left',
                0x223 : 'dpad_right',
                
                # XBox 360 controller uses these codes.
                0x2c0 : 'dpad_left',
                0x2c1 : 'dpad_right',
                0x2c2 : 'dpad_up',
                0x2c3 : 'dpad_down',
            }
                    
            axis_map = []
            button_map = []
                    
            # Open the joystick device.
            fn = '/dev/input/js0'
            if self.DEBUG==True:
                print(('Opening %s...' % fn))
            jsdev = open(fn, 'rb')
            
            # Get the device name.
            #buf = bytearray(63)
            buf = array.array('B', [0] * 64)
            ioctl(jsdev, 0x80006a13 + (0x10000 * len(buf)), buf) # JSIOCGNAME(len)
            js_name = buf.tostring().rstrip(b'\x00').decode('utf-8')
            if self.DEBUG==True:
                print(('Device name: %s' % js_name))
                    
            # Get number of axes and buttons.
            buf = array.array('B', [0])
            ioctl(jsdev, 0x80016a11, buf) # JSIOCGAXES
            num_axes = buf[0]
            
            buf = array.array('B', [0])
            ioctl(jsdev, 0x80016a12, buf) # JSIOCGBUTTONS
            num_buttons = buf[0]
                    
            # Get the axis map.
            buf = array.array('B', [0] * 0x40)
            ioctl(jsdev, 0x80406a32, buf) # JSIOCGAXMAP
                    
            for axis in buf[:num_axes]:
                axis_name = axis_names.get(axis, 'unknown(0x%02x)' % axis)
                axis_map.append(axis_name)
                axis_states[axis_name] = 0.0
                        
            # Get the button map.
            buf = array.array('H', [0] * 200)
            ioctl(jsdev, 0x80406a34, buf) # JSIOCGBTNMAP
                        
            for btn in buf[:num_buttons]:
                btn_name = button_names.get(btn, 'unknown(0x%03x)' % btn)
                button_map.append(btn_name)
                button_states[btn_name] = 0


            # Print out the values
            if self.DEBUG==True:
                print(('%d axes found: %s' % (num_axes, ', '.join(axis_map))))
                print(('%d buttons found: %s' % (num_buttons, ', '.join(button_map))))


            ## CONFIGURE ANALOGUE JOYSTICK "DEAD-ZONES"
            # use these values to increase/decrease the deadzones on the analogues
            pdz=0.100 # Positve Deadzone
            ndz=-0.100 # Negative Deadzone

            ## Init the DCmotors class
            if self.DEBUG==True:
                print("Creating New DC Motor Class...")
            dcm = DCMotors()
            # set speeds up here | use to set speed for DC Motors in the program
            dcm_speed_0=0
            dcm_speed_1=10
            dcm_speed_2=20
            dcm_speed_3=30
            dcm_speed_4=40
            dcm_speed_5=50
            # set initial speeds here
            dcm_initial_speed_x = dcm_speed_1 # Turning (Left/Right)
            dcm_initial_speed_y = dcm_speed_2 # Movement (Forward/Backward)
            # use initial speed values to set the initial Pulse Width Modulation values
            dcm.setPWMAX(dcm_initial_speed_x) # Turning (Left Wheel)
            dcm.setPWMBX(dcm_initial_speed_x) # Turning (Right Wheel)
            dcm.setPWMAY(dcm_initial_speed_y) # Moving Forward/Backward (Left Wheel)
            dcm.setPWMBY(dcm_initial_speed_y) # Moving Forward/Backward (Right Wheel)
            # store "last known" speeds here (starts with the 'initial speed' values)
            dcm_last_known_speed_x=dcm_initial_speed_x # Turning (Left/Right)
            dcm_last_known_speed_y=dcm_initial_speed_y # Movement (Forward/Backward)
            # store the "current" speeds here
            dcm_current_speed_x=dcm_initial_speed_x # Turning (Left/Right)
            dcm_current_speed_y=dcm_initial_speed_y # Movement (Forward/Backward)

            ## Init the PCA9685 class (Servo Motors)
            if self.DEBUG==True:
                print("Creating New Instance Of PCA9685 Class...")
            pwm=PCA9685(0x40, debug=True) # leave these aguments as is, do not change.
            pwm.setPWMFreq(50) #set the frequency | must be 50, do not chnage this!
            #set the initial servo pulses, which "center" the servos before we begin
            pwm.setServoPulse(0,1500) #horizontal | note: the channel (0) is for horizontal
            pwm.setServoPulse(1,1500) #vertical | note: the channel (1) is for vertical
            vslv=1500 # Vertical Servo Last Value | store the last known value for the vertical servo's 'Servo Pulse' | set to 1500 (center) before the main loop starts
            hslv=1500 # Horizontal Servo Last Value | store the last known value for the horizontal servo's 'Servo Pulse' | set to 1500 (center) before the main loop starts
            sspa=700 # Servo Stopping Point A | set the stopping point for the servo's here
            sspb=2300 # Servo Stopping Point B | set the stopping point for the servo's here
            sss=10 # Servo Step Size | set the size of the servo steps here (larger steps will make it move faster)

            ## Init the Buzzer class
            bzr=Buzzer()
            
            # Main event loop
            while True:
                evbuf = jsdev.read(8)
                if evbuf:
                    time, value, type, number = struct.unpack('IhBB', evbuf)
                            
                    if type & 0x80:
                        if self.DEBUG==True:
                            print("(initial)")
                                
                    if type & 0x01:
                        button = button_map[number]
                        if button:
                            button_states[button] = value
                            if value:
                                if self.DEBUG==True:
                                    print(("%s pressed" % (button)))
                            else:
                                if self.DEBUG==True:
                                    print(("%s released" % (button)))

                            ###############################################################
                            # BUTTONS [TRIANGLE, SQUARE, CROSS, CIRCLE] | MISC. FUNCTIONS #
                            ###############################################################
                            if value:

                                ################################
                                # CIRCLE | RECENTER THE SERVOS #
                                ################################
                                if button == "b":
                                    
                                    print("CIRCLE Pushed... Centering Servos Now ^_^)")
                                    # set the servo pulse to the center positions/values for the vertical and horizontal servos
                                    pwm.setServoPulse(0,1500)
                                    pwm.setServoPulse(1,1500)
                                    # make sure the vertical & horizontal servo's last known value is reset to the 'center' position to prevent "jumping behaviour" when panning again
                                    vslv=1500
                                    hslv=1500

                                ##############################################
                                # SQUARE | RESET SPEEDS | TURNING & MOVEMENT #
                                ##############################################
                                elif button == "y":

                                    print("SQUARE Pushed... Resetting Speeds Now ^_^")
                                    ## reset speed code here...
                                    dcm.setPWMAX(dcm_initial_speed_x) # set Pulse Width Modulation For Motor A To Initial Value (Turning Speed)
                                    dcm.setPWMBX(dcm_initial_speed_x) # set Pulse Width Modulation For Motor B To Initial Value (Turning Speed)
                                    dcm.setPWMAY(dcm_initial_speed_y) # set Pulse Width Modulation For Motor A To Initial Value (Movement Speed)
                                    dcm.setPWMBX(dcm_initial_speed_y) # set Pulse Width Modulation For Motor B To Initial Value (Movement Speed)
                                    dcm_last_known_speed_x=dcm_initial_speed_x # update last known movement speed to the initial value (Turning Speed)
                                    dcm_last_known_speed_y=dcm_initial_speed_y # update last known movement speed to the initial value (Movement Speed)

                                #####################
                                # TRIANGLE | BUZZER #
                                #####################
                                elif button == "x":

                                    print("TRIANGLE Pushed... Buzzing Now ^_^")
                                    bzr.ezbuzz() 

                                #############################################################
                                ## speed control (DC Motors) | MOVEMENT (FORWARD/BACKWARD) ##
                                #############################################################

                                ## SLOW DOWN (top left trigger)
                                elif button == "tl":

                                    print ("Top Left Trigger Pushed... Decreasing Speed now...")

                                    # if speed is zero, do nothing... cant slow down any more than that can we..
                                    if dcm_last_known_speed_y == dcm_speed_0:
                                        print("Speed is already 0, we cant go any lower bro...")

                                    # else if speed is 1, slow down to 0
                                    elif dcm_last_known_speed_y == dcm_speed_1:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_0)
                                        dcm.setPWMAY(dcm_speed_0)
                                        dcm.setPWMBY(dcm_speed_0)
                                        dcm_last_known_speed_y=dcm_speed_0 # update last known speed value to the updated one

                                    # else if speed is 2, slow down to 1
                                    elif dcm_last_known_speed_y == dcm_speed_2:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_1)
                                        dcm.setPWMAY(dcm_speed_1)
                                        dcm.setPWMBY(dcm_speed_1)
                                        dcm_last_known_speed_y=dcm_speed_1 # update last known speed value to the updated one
                                        
                                    # else if speed is 3, slow down to 2
                                    elif dcm_last_known_speed_y == dcm_speed_3:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_2)
                                        dcm.setPWMAY(dcm_speed_2)
                                        dcm.setPWMBY(dcm_speed_2)
                                        dcm_last_known_speed_y=dcm_speed_2 # update last known speed value to the updated one

                                    # else if speed is 4, slow down to 3
                                    elif dcm_last_known_speed_y == dcm_speed_4:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_3)
                                        dcm.setPWMAY(dcm_speed_3)
                                        dcm.setPWMBY(dcm_speed_3)
                                        dcm_last_known_speed_y=dcm_speed_3 # update last known speed value to the updated one

                                    # else if speed is 5, slow down to 4
                                    elif dcm_last_known_speed_y == dcm_speed_5:
                                        print("Slowing Down Turning Speed to: ",dcm_speed_4)
                                        dcm.setPWMAY(dcm_speed_4)
                                        dcm.setPWMBY(dcm_speed_4)
                                        dcm_last_known_speed_y=dcm_speed_4 # update last known speed value to the updated one
                                    
                                ## SPEED UP (top left trigger)
                                elif button == "tr":

                                    print ("Top Right Trigger Pushed... Increasing Speed now...")

                                    # if speed is 0, speed up to 1..
                                    if dcm_last_known_speed_y == dcm_speed_0:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_1)
                                        dcm.setPWMAY(dcm_speed_1)
                                        dcm.setPWMBY(dcm_speed_1)
                                        dcm_last_known_speed_y=dcm_speed_1 # update last known speed value to the updated one

                                    # else if speed is 1, speed up to 2
                                    elif dcm_last_known_speed_y == dcm_speed_1:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_2)
                                        dcm.setPWMAY(dcm_speed_2)
                                        dcm.setPWMBY(dcm_speed_2)
                                        dcm_last_known_speed_y=dcm_speed_2 # update last known speed value to the updated one

                                    # else if speed is 2, speed up to 3
                                    elif dcm_last_known_speed_y == dcm_speed_2:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_3)
                                        dcm.setPWMAY(dcm_speed_3)
                                        dcm.setPWMBY(dcm_speed_3)
                                        dcm_last_known_speed_y=dcm_speed_3 # update last known speed value to the updated one

                                    # else if speed is 3, speed up to 4
                                    elif dcm_last_known_speed_y == dcm_speed_3:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_4)
                                        dcm.setPWMAY(dcm_speed_4)
                                        dcm.setPWMBY(dcm_speed_4)
                                        dcm_last_known_speed_y=dcm_speed_4 # update last known speed value to the updated one

                                    # else if speed is 4, speed up to 5
                                    elif dcm_last_known_speed_y == dcm_speed_4:
                                        print("Speeding Up Turning Speed to: ",dcm_speed_5)
                                        dcm.setPWMAY(dcm_speed_5)
                                        dcm.setPWMBY(dcm_speed_5)
                                        dcm_last_known_speed_y=dcm_speed_5 # update last known speed value to the updated one

                                    # else if speed is 5, this is our max, so we wont go any higher...
                                    elif dcm_last_known_speed_y == dcm_speed_5:
                                        print("Speed is already 5, we cant go any higher bro... Maybe consider making a 'Temp Power Boost' function using a different button... L3 maybe? ;)")
                                        
                            else:
                                print(("%s released" % (button))) # this gets fired EVERYTIME a button is "released"
                                        
                    if type & 0x02:
                        axis = axis_map[number]
                        if axis:
                            fvalue = value / 32767.0
                            axis_states[axis] = fvalue
                            if self.DEBUG==True:
                                print(("%s: %.3f" % (axis, fvalue)))

                            ####################################
                            # LEFT ANALOGUE | DC MOTOR CONTROL #
                            ####################################
                            
                            ## forward
                            if axis == "y" and fvalue < ndz:
                                dcm.forward()
                                if self.DEBUG==True:
                                    print("Moving Forward...")
                            elif axis == "y" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")

                            ## backward
                            elif axis == "y" and fvalue > pdz:
                                dcm.backward()
                                if self.DEBUG==True:
                                    print("Moving Backward...")
                            elif axis == "y" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")

                            ## left
                            elif axis == "x" and fvalue < ndz:
                                dcm.left()
                                if self.DEBUG==True:
                                    print("Turning Left")
                            elif axis == "x" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")
                                
                            ## right
                            elif axis == "x" and fvalue > pdz:
                                dcm.right()
                                if self.DEBUG==True:
                                    print("Turning Right")
                            elif axis == "x" and fvalue == 0:
                                dcm.stop()
                                if self.DEBUG==True:
                                    print("Stopping...")

                            ########################################
                            # RIGHT ANALOGUE | SERVO MOTOR CONTROL #
                            ########################################

                            ## up
                            if axis == "ry" and fvalue > pdz:
                                if vslv > sspa and vslv <= sspb: #make sure we are between a reasonable range
                                    vslv=vslv-sss # decrement our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Up...")
                                        print("vslv:",vslv)
                                    pwm.setServoPulse(1,vslv)
                                    
                            ## down
                            elif axis == "ry" and fvalue < ndz:
                                if vslv >= sspa and vslv < sspb: #make sure we are between a reasonable range
                                    vslv=vslv+sss # increment our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Down...")
                                        print("vslv:",vslv)
                                    pwm.setServoPulse(1,vslv)

                            ## left
                            elif axis == "rx" and fvalue < ndz:
                                if hslv >= sspa and hslv < sspb: #make sure we are between a reasonable range
                                    hslv=hslv+sss # decrement our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Left...")
                                        print("hslv:",hslv)
                                    pwm.setServoPulse(0,hslv)
                                
                            ## right
                            elif axis == "rx" and fvalue > pdz:
                                if hslv > sspa and hslv <= sspb: #make sure we are between a reasonable range
                                    hslv=hslv-sss # increment our servo pulse
                                    if self.DEBUG==True:
                                        print("Panning Servo Right...")
                                        print("hslv:",hslv)
                                    pwm.setServoPulse(0,hslv)

                            ############################################################
                            # HAT DIRECTIONAL BUTTONS | DC MOTOR TURNING SPEED CONTROL #
                            ############################################################

                            ### DOWN BUTTON
                            ## SLOW DOWN
                            if axis == "hat0y" and fvalue == 1:

                                print("hat0y (UP) Pushed...")
                                
                                # if speed is zero, do nothing... cant slow down any more than that can we..
                                if dcm_last_known_speed_x == dcm_speed_0:
                                    print("Speed is already 0, we cant go any lower bro...")

                                # else if speed is 1, slow down to 0
                                elif dcm_last_known_speed_x == dcm_speed_1:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_0)
                                    dcm.setPWMAX(dcm_speed_0)
                                    dcm.setPWMBX(dcm_speed_0)
                                    dcm_last_known_speed_x=dcm_speed_0 # update last known speed value to the updated one

                                # else if speed is 2, slow down to 1
                                elif dcm_last_known_speed_x == dcm_speed_2:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_1)
                                    dcm.setPWMAX(dcm_speed_1)
                                    dcm.setPWMBX(dcm_speed_1)
                                    dcm_last_known_speed_x=dcm_speed_1 # update last known speed value to the updated one

                                # else if speed is 3, slow down to 2
                                elif dcm_last_known_speed_x == dcm_speed_3:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_2)
                                    dcm.setPWMAX(dcm_speed_2)
                                    dcm.setPWMBX(dcm_speed_2)
                                    dcm_last_known_speed_x=dcm_speed_2 # update last known speed value to the updated one

                                # else if speed is 4, slow down to 3
                                elif dcm_last_known_speed_x == dcm_speed_4:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_3)
                                    dcm.setPWMAX(dcm_speed_3)
                                    dcm.setPWMBX(dcm_speed_3)
                                    dcm_last_known_speed_x=dcm_speed_3 # update last known speed value to the updated one

                                # else if speed is 5, slow down to 4
                                elif dcm_last_known_speed_x == dcm_speed_5:
                                    print("Slowing Down Turning Speed to: ",dcm_speed_4)
                                    dcm.setPWMAX(dcm_speed_4)
                                    dcm.setPWMBX(dcm_speed_4)
                                    dcm_last_known_speed_x=dcm_speed_4 # update last known speed value to the updated one

                            
                            ### UP BUTTON
                            ## SPEED UP
                            elif axis == "hat0y" and fvalue == -1:

                                print ("hat0y (DOWN) Pushed... Increasing Speed now...")

                                # if speed is 0, speed up to 1..
                                if dcm_last_known_speed_x == dcm_speed_0:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_1)
                                    dcm.setPWMAX(dcm_speed_1)
                                    dcm.setPWMBX(dcm_speed_1)
                                    dcm_last_known_speed_x=dcm_speed_1 # update last known speed value to the updated one

                                # else if speed is 1, speed up to 2
                                elif dcm_last_known_speed_x == dcm_speed_1:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_2)
                                    dcm.setPWMAX(dcm_speed_2)
                                    dcm.setPWMBX(dcm_speed_2)
                                    dcm_last_known_speed_x=dcm_speed_2 # update last known speed value to the updated one

                                # else if speed is 2, speed up to 3
                                elif dcm_last_known_speed_x == dcm_speed_2:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_3)
                                    dcm.setPWMAX(dcm_speed_3)
                                    dcm.setPWMBX(dcm_speed_3)
                                    dcm_last_known_speed_x=dcm_speed_3 # update last known speed value to the updated one

                                # else if speed is 3, speed up to 4
                                elif dcm_last_known_speed_x == dcm_speed_3:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_4)
                                    dcm.setPWMAX(dcm_speed_4)
                                    dcm.setPWMBX(dcm_speed_4)
                                    dcm_last_known_speed_x=dcm_speed_4 # update last known speed value to the updated one

                                # else if speed is 4, speed up to 5
                                elif dcm_last_known_speed_x == dcm_speed_4:
                                    print("Speeding Up Turning Speed to: ",dcm_speed_5)
                                    dcm.setPWMAX(dcm_speed_5)
                                    dcm.setPWMBX(dcm_speed_5)
                                    dcm_last_known_speed_x=dcm_speed_5 # update last known speed value to the updated one

                                # else if speed is 5, this is our max, so we wont go any higher...
                                elif dcm_last_known_speed_x == dcm_speed_5:
                                    print("Speed is already 5, we cant go any higher bro... Maybe consider making a 'Temp Power Boost' function using a different button... L3 maybe? ;)")
                                
                            
        except KeyboardInterrupt:
            print("Program stopped by user...")

        except Exception:
            traceback.print_exc()
            
        finally:
            if self.DEBUG==True:
                print("Setup process complete")
Esempio n. 30
0
class Buttons:
    # button 4
    button4 = Button(14)

    # button 3
    button3 = Button(15)

    # button 2
    button2 = Button(18)

    # button 1
    button1 = Button(23)

    mode = "view"

    alarm = None

    prev_pushed = -1
    screen = None

    sound = Buzzer()

    alarm_puzzle = None

    cur_time = None

    def __init__(self):
        self.cur_time = Time.Time()

        self.screen = SevenSegDriver.SevenSegDrive(
            TimeToArray.time_to_array(self.cur_time.get_time()))

        self.cur_time.subscribe_to_time_change(self.screen)

        self.make_alarm()

        self.mode = "view"

        t = Thread(target=self.poll_buttons())
        t.start()

    def make_alarm(self):
        cur_time_e = self.cur_time.get_time().time()
        alarm_time = datetime.time(cur_time_e.hour,
                                   (cur_time_e.minute + 1) % 60, 0)

        print("New Alarm for ", alarm_time)

        if self.alarm is not None:
            self.alarm.unsubscribe(self)

        self.alarm = Alarm.Alarm(alarm_time)
        self.alarm.willRing = True

        self.alarm_puzzle = AlarmPuzzle.alarm_puzzle()

        self.alarm.subscribe(self)

        self.cur_time.subscribe_to_time_change(self.alarm)

    def notify(self, alarm):
        pass
        print("mode is alarm now")
        self.mode = "alarm"
        self.screen.set_mode("alarm", self.alarm_puzzle)

    def poll_buttons(self):
        while True:
            time.sleep(.1)

            if self.mode == "alarm":
                if self.sound.sound is True and self.sound.buzzing is False:
                    self.sound.start()

                # self.screen.set_mode("alarm", self.alarm_puzzle)

                if self.button1.is_pressed:
                    if self.prev_pushed != 1:
                        self.alarm_puzzle.input(1)
                        self.prev_pushed = 1
                        print("1")
                elif self.button2.is_pressed:
                    if self.prev_pushed != 2:
                        self.alarm_puzzle.input(2)
                        self.prev_pushed = 2
                        print("2")
                elif self.button3.is_pressed:
                    if self.prev_pushed != 3:
                        self.alarm_puzzle.input(3)
                        self.prev_pushed = 3
                        print("3")
                elif self.button4.is_pressed:
                    if self.prev_pushed != 4:
                        self.alarm_puzzle.input(4)
                        self.prev_pushed = 4
                        print("4")
                else:
                    self.prev_pushed = -1

                if self.alarm_puzzle.is_solved():
                    self.mode = "view"
                    self.screen.mode = "view"

            if self.mode is "view":
                self.sound.stop()
                if not (self.button1.is_pressed and self.button2.is_pressed):
                    if self.button1.is_pressed:
                        # self.mode = 'change_time'
                        self.make_alarm()
                        print("Button 1 view mode")

                    if self.button2.is_pressed:
                        # self.mode = 'change_alarm'
                        print("Button 2 view mode")
Esempio n. 31
0
POS_CHAVE = 23
RELE = 24

######### State Machine Variables ##########
current_state = 0
passwd = "33"
codigo_veiculo = "33"
codigo_motorista = ""
codigo_linha = ""
date_time = []
############################################

######### Instances of the Modules #########
lcd = Lcd()
keypad = Keypad()
buzzer = Buzzer()
gprs = GPRS("179.188.3.201", 9091)
#gprs = GPRS()
############################################

############ Rfid variables  ###############
CARDS = ["[154, 99, 3, 197, 63]", "[151, 25, 214, 53, 109]"]
KEYCHAINS = ["[213, 1, 9, 136, 85]", "[5, 214, 17, 136, 74]"]

DRIVERS_ID = [100, 101]
LINE_ID = [222, 223]

RFID_PRESENT = True
if RFID_PRESENT:
    rfid = Rfid()
lock = Lock()
Esempio n. 32
0
#----------------------------
# Imported Modules
#----------------------------
import gesture as ges
from OLED import OLED
from Buzzer import Buzzer
import time

#----------------------------
# Globals
#----------------------------
ledHeader = "getFlag();\n"
display = OLED()
audio = Buzzer()
display.clear()
display.resetCursor()
display.write(ledHeader)
audio.connected()
time.sleep(1)
#----------------------------
# Print Initialization to LED
#----------------------------
buzz = [ 0 ]
buzzfinal = [ 4 ]
microsec = [ 16 ]
for i in range (0, 3):
    message = ledHeader + "Starting\n\t\t\t" + str(3 - i)
    display.clear()
    display.resetCursor()
    display.write(message)
    audio.play(buzz, microsec)
Esempio n. 33
0
        logger.debug(msg.topic + ": '" + str(msg.payload) + "'")
    except:
        logger.info("Error!")


mqtt.on_connect = on_connect
mqtt.on_disconnect = on_disconnect
mqtt.on_message = on_message
mqtt.will_set(SERVICE_NAME + "/state/status", "OFF", 1, True)
mqtt.reconnect_delay_set(min_delay=1, max_delay=60)
mqtt.connect(BROKER_ADDRESS, BROKER_PORT, 60)  # connect to broker
mqtt.publish(SERVICE_NAME + "/state/status", "ON", 1, True)

# Modules
pixels = Pixels(mqtt, SERVICE_NAME, DEBUG)
buzzer = Buzzer(mqtt, SERVICE_NAME, DEBUG)
cameraServo = CameraServo(mqtt, SERVICE_NAME, DEBUG)
infrared_receiver = InfraredReceiver(mqtt, SERVICE_NAME, DEBUG)
infrared_sensor = InfraredSensor(mqtt, SERVICE_NAME, DEBUG)
joystick = Joystick(mqtt, SERVICE_NAME, DEBUG)
obstacle_avoidance = ObstacleAvoidance(mqtt, SERVICE_NAME, DEBUG)
trSensor = TRSensor(mqtt, SERVICE_NAME, 5, DEBUG)
ultrasonic = Ultrasonic(mqtt, SERVICE_NAME, DEBUG)
wheels = Wheels(mqtt, SERVICE_NAME, DEBUG)

# Setup IR Sensor
infrared_receiver.buzzer = buzzer
infrared_receiver.camera_servo = cameraServo
infrared_receiver.pixels = pixels
infrared_receiver.wheels = wheels
Esempio n. 34
0
class Serialcom(threading.Thread):

	def __init__(self):
		threading.Thread.__init__(self)
		self.shutdown_flag = threading.Event()
		self.motor = Motorcontroller()
		self.buzzer = Buzzer()
		self.xbee = Xbee()
		self.decoder = Decoder()
		self.servo1 = 96
		self.servo2 = 75
		self.joycalc = Joystick()
		self.motor.setServo1(self.servo1)
		self.motor.setServo2(self.servo2)
		self.lastSavedTime = 0


	def run(self):
		print('Thread #%s started' % self.ident)
		self.motor.timeout(1)
		while not self.shutdown_flag.is_set():
			rcvdata = self.xbee.read()
			self.decoder.decode(rcvdata)
			self.motor.recalCommand()
			currenttime = time.time()
			if currenttime - self.lastSavedTime > 1.0:
				self.lastSavedTime = time.time()
				self.xbee.sendBat(self.decoder.getRfrating())
			if self.decoder.getStatus() and self.decoder.checkCRC():
				if self.decoder.getJoyStickPB1() == 0:
					self.motor.EmergyStop()
					self.buzzer.beep(300)

				elif self.decoder.getJoystickM1() > 248 and self.decoder.getJoystickM2() > 248:
					self.joycalc.calculateReg(255)
					self.motor.Motor1MC2(255 - self.joycalc.cor1)
					self.motor.Motor2MC2(255 - self.joycalc.cor2)

				elif (abs(self.decoder.getJoystickM1() - self.decoder.getJoystickM2()) <= 3) and (self.decoder.getJoystickM1() > 50):
					self.joycalc.calculateReg(self.decoder.getJoystickM1())
					self.motor.Motor1MC2(self.decoder.getJoystickM1() - self.joycalc.cor1)
					self.motor.Motor2MC2(self.decoder.getJoystickM1() - self.joycalc.cor2)
					#print "drive forward without full speed"
				else:
					self.motor.Motor1MC2(self.decoder.getJoystickM1())
					self.motor.Motor2MC2(self.decoder.getJoystickM2())
					#print "other speeds"

				if self.decoder.getJoystickPB2() == 0:
					self.servo1 = 96
					self.motor.setServo1(self.servo1)
					self.buzzer.beep(300)

				elif self.decoder.getJoystickVRX2() > 1000:
					if(self.servo1 > 0):
						self.servo1 = self.servo1 - 1
						self.motor.setServo1(self.servo1)
				elif self.decoder.getJoystickVRX2() < 24:
					if(self.servo1 < 180):
						self.servo1 = self.servo1 + 1
						self.motor.setServo1(self.servo1)

				if self.decoder.getJoystickPB2() == 0:
					self.servo2 = 75
					self.motor.setServo2(self.servo2)

				elif self.decoder.joystick_VRY2 > 1000:
					if(self.servo2 > 0):
						self.servo2 = self.servo2 - 1
						self.motor.setServo2(self.servo2)
				elif self.decoder.getJoystickVRY2() < 24:
					if(self.servo2 < 180):
						self.servo2 = self.servo2 + 1
						self.motor.setServo2(self.servo2)

			time.sleep(0.001)

		# ... Clean shutdown code here ...
		self.xbee.close()
		self.motor.close()
		print('Thread #%s stopped' % self.ident)
Esempio n. 35
0
import RPi.GPIO as GPIO
import time
from LED import LED
from Knop import Knop
from Buzzer import Buzzer

GPIO.setmode(GPIO.BCM)

# knop1_ingedrukt = 1
# knop2_ingedrukt = 1
# knop3_ingedrukt = 1
# knop4_ingedrukt = 1

led = LED(25)
buzzer = Buzzer(23)
buttons = [21, 20, 16, 12]

# GPIO.setup(led,GPIO.OUT)
# GPIO.setup(buzzer,GPIO.OUT)

# p = GPIO.PWM(buzzer,261)

knop1 = Knop(buttons[0])
knop2 = Knop(buttons[1])
knop3 = Knop(buttons[2])
knop4 = Knop(buttons[3])
# GPIO.add_event_detect(button, GPIO.RISING, actie, 400)

# def led_knipperen():
#     GPIO.output(led,GPIO.HIGH)
#     time.sleep(0.5)
Esempio n. 36
0
class Alarm:

    gas_threshold = 1000
    smoke_threshold = 2000
    temperature_threshold = 55

    def __init__(self):
        self.fire_detected = False
        self.buzzer = Buzzer()
        self.adc = MCP3008()

    async def connect_azure(self):
        conn_str = "HostName=Smartfire.azure-devices.net;DeviceId=smartfire-1;SharedAccessKey=sFQIzn79jON2ZBpL3iiBHScmIBXMXf57bA5PFM69ie8="
        self.device_client = IoTHubDeviceClient.create_from_connection_string(
            conn_str)
        await self.device_client.connect()

    async def start(self):
        await self.connect_azure()
        await self.start_alarm()

    async def start_alarm(self):
        while True:
            humidity, temperature = self.get_dht11_data()
            mq3_data = self.get_mq3_data()
            mq9_data = self.get_mq9_data()
            await self.save_measurements(temperature, humidity, mq3_data,
                                         mq9_data)
            sleep(4)

            if ((mq3_data > Alarm.gas_threshold
                 or mq9_data > Alarm.smoke_threshold
                 or temperature > Alarm.temperature_threshold)
                    and not self.fire_detected):
                self.fire_detected = True
                self.buzzer.start()

            else:
                self.fire_detected = False
                self.buzzer.stop()

    async def save_measurements(self, temperature, humidity, mq3_data,
                                mq9_data):
        print("saving saving measurements")

        gas_percentage = self.convert_percentage(mq3_data, 350, 1000)
        co_percentage = self.convert_percentage(mq3_data, 990, 5000)

        data = {
            'device_id': 1,
            'event': "measurement",
            'temperature': float(temperature),
            'gas_percentage': gas_percentage,
            'co_percentage': co_percentage,
            'is_fire': 1 if self.fire_detected else 0,
            'humidity': float(humidity)
        }

        json_body = json.dumps(data)
        await self.device_client.send_message(json_body)

        twin = await self.device_client.get_twin()
        self.handle_twin(twin)

        await self.device_client.disconnect()

    def handle_twin(self, twin):
        if (not self.fire_detected):
            if ('desired' in twin):
                desired = twin['desired']
                if ('is_fire' in desired):
                    if desired['is_fire'] == 1:
                        self.buzzer.start()
                    elif desired['is_fire'] == 0:
                        self.buzzer.stop()

    def convert_percentage(self, number, min, max):
        percentage = round(((number - min) / (max - min)) * 100, 2)
        if percentage > 100:
            percentage = 100
        elif percentage < 0:
            percentage = 0
        return float(percentage)

    def get_dht11_data(self):
        return Adafruit_DHT.read_retry(11, 4)

    def get_mq3_data(self):
        return self.adc.read(0)

    def get_mq9_data(self):
        return self.adc.read(1)
Esempio n. 37
0
    HAND_APPROVED = 1
    HAND_DENIED = 0
    NOT_HAND = 2
    MAX_PEOPLE = 2

    restart_button = 40
    gpio.setmode(gpio.BOARD)
    gpio.setup(restart_button, gpio.IN, pull_up_down=gpio.PUD_UP)
    gpio.add_event_detect(restart_button,
                          gpio.RISING,
                          callback=restart,
                          bouncetime=200)

    ExitHR = ExitHandReader.ExitHandReader(32, 31)
    print("Exit Hand Reader Initialized!")

    door = Door()
    print("Door Initialized!")
    B = Buzzer(33)
    print("Buzzer Initialized!")
    PC = PeopleCounter.PeopleCounter(23, 24, 21, 22, func=door.close)
    print("People Counter Initialized!")
    EntryHR = OuterHandReader.OHandReader(12, 18, 1, _get_state=PC._get_state)
    print("Entry Hand Reader Initialized!")
    MD = MaskDetector.MaskDetector(headless=False)
    print("Mask Detector Initialized!")
    opsign = sign.sign()

    main()
Esempio n. 38
0
from Buzzer import Buzzer
import time

buzz1 = Buzzer(24)
buzz1.on()
time.sleep(1)
buzz1.off()
time.sleep(1)
buzz1.toggle()
if buzz1.is_on():
    print("on")
elif buzz1.is_off():
    print("off")
time.sleep(1)
buzz1.toggle()
if buzz1.is_on():
    print("on")
elif buzz1.is_off():
    print("off")
time.sleep(1)
buzz1.beep()
time.sleep(5)
buzz1.beep(2, 20)
time.sleep(5)