def run(self): while True: print("\tVersion: %s" % self.this_version) print("\tDevice : %s exist" % base.get_device_num()) self.display() self.get_num() if (self.input is 0): continue elif (self.input is 1): led.Led(led.Led.led_menu_array).run() elif (self.input is 2): wifi.Wifi(wifi.Wifi.wifi_menu_array).run() elif (self.input is 3): alexa.Alexa().run() elif (self.input is 4): bt.Bt(bt.Bt.bt_menu_array).run() elif (self.input is 5): development.Development().run() elif (self.input is 6): fastboot_all.FastbootImage().run() elif (self.input is 7): os.system('adb reboot') os._exit(0) elif (self.input is 8): os._exit(0) else: print("error") continue
def main(): d = 0 lcd.ecrireMessage("Bonjour", 3) lcd.clearEcran() t = capteurTemperature.MesurerH() day = int(time.strftime("%d")) - 1 while True: #demande prise de frequence cardiaque if d == 0: if bouton.etatBt2() == 1: d = 1 t = time.time() l = lcd.Lcd( "Placer le capteur de frequence cardiaque et appuyer de nouveau sur le bouton 2", 120) l.start() time.sleep(3) if d == 1: if bouton.etatBt2() == 1 and t + 120 > time.time(): l.stop() l.join() prise(2, 4) d = 0 if t + 120 <= time.time(): l.stop() l.join() d = 0 #demande de frequence cardiaque quotidienne if day != time.strftime("%d") and int(time.strftime("%H")) >= 8: lcd.ecrireMessage("Bonjour", 3) lcd.clearEcran() day = time.strftime("%d") freqQ = False while freqQ == False: ecran = lcd.Lcd( "C est l heure de prendre votre frequence cardiaque! (appuyer sur le bouton 1)", 60) buzz = buzzer.Buzzer(10, 0) #on modifiera le 0 plus tard ledr = led.Led(60, 0.5) bt1 = bouton.Button1(60) ecran.start() bt1.start() buzz.start() ledr.start() ret = bt1.join() if ret == True: ecran.stop() ledr.stop() buzz.stop() prise(2, 4) freqQ = True ecran.join() ledr.join() buzz.join() t.join()
def __init__(self): self.evt = event.Event() self.camera = camera.Camera() #actuator class self.uploader = uploader.Uploader() #actuator class self.led = led.Led() self.motion = motion_sensor.MotionSensor() #sencor class self.sonic = sonic_sensor.SonicSensor() #sensor class self.motion.event_handlers += self.camera.shutter self.motion.event_handlers += self.uploader.execute self.sonic.evt += self.camera.shutter self.sonic.evt += self.uploader.execute
def __init__(self, app, var_status_leds): self._app = app self.config = config.Config() self.led = led.Led(var_status_leds) self.conexao = conexao.Conexao() self.var_status_leds = var_status_leds self.verificar_se_temos_led()
def _get_leds(args): # args = ["GetLeds"] with open(INVENTORY_FILE, "rb") as f: objects = [x.strip() for x in f.readlines()] leds_name = [] for object_name in objects: if _check_object_type(object_name) == "led": try: KNOWN_LEDS[object_name] = led.Led(object_name, WORLD_RANGE["X"][0], WORLD_RANGE["Y"][0]) cf_logger.info("Led '{}' added".format(object_name)) leds_name.append(object_name) except Exception as e: cf_logger.exception( "Failed to create Led named: {}".format(object_name)) return "FATAL" return "$".join(leds_name)
def run(self): buzz = buzzer.Buzzer(10,0) #on modifiera le 0 plus tard ecran = lcd.Lcd("Hydratez-vous et appuyer sur le bouton 1!",20) ledr = led.Led(20,0.5) bt1 = bouton.Button1(20) bt1.start() buzz.start() ecran.start() ledr.start() self.ret = bt1.join() if self.ret == True: ecran.stop() ledr.stop() buzz.stop() ecran.join() ledr.join() buzz.join()
def run(drones): print "init node" rospy.init_node('land') print "starting" listener = tf.TransformListener() cfs = [] leds = [] for drone_name in drones: if drone_name[:9] == "crazyflie": cf = crazyflie.Crazyflie(drone_name, listener) cfs.append(cf) cf.setParam("commander/enHighLevel", 1) elif drone_name[:3] == "led": ld = led.Led(drone_name, 0, 0) leds.append(ld) while True: pos_list = [] for cf in cfs: pos_list.append("{} is at {}".format(cf.prefix, cf.position())) for ld in leds: pos_list.append("{} is at {}".format(ld.prefix, ld.getPosition())) print "\n".join(pos_list)
def __init__(self, config, verbose=0): self.verbose = verbose # ------------------------------------------------------------------------------------------------------------ # self.exit = False self.config = config # ------------------------------------------------------------------------------------------------------------ # # Initialise required services if self.config['pinout']['led'] is None: self.led = led.MockLed() else: self.led = led.Led(self.config['pinout']['led']) self.wifi = WiFi(self.config, verbose=self.verbose) self.device_id = self.wifi.device_id() self.messaging = Messaging(self.config, self.device_id) if self.config['pinout']['ultrasound'] is None: self.water_level = MockWaterLevel() else: self.water_level = WaterLevel(self.config, verbose=self.verbose) if self.config['pinout']['flow_meter'] is None: self.flow_rate = MockFlowRate() else: self.flow_rate = FlowRateFallingEdge(self.config, verbose=self.verbose) # ------------------------------------------------------------------------------------------------------------ # if self.verbose: print('<{} with id {}>'.format(self.config['device']['name'], self.device_id)) print(self.led) print(self.wifi) print(self.messaging) print(self.water_level) print(self.flow_rate) # Application ready feedback --------------------------------------------------------------------------------- # self.led.on(poll=True) time.sleep(2) self.led.off(poll=True) # ------------------------------------------------------------------------------------------------------------ # if self.wifi.connected(): self.on_wifi_connected()
def init_notes(colors, led_hndl): pitch_count = 88 names = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] # 21 is the MIDI pitch for the first piano key (A0) notes = [] white_x = 50 black_x = 110 for i in range(pitch_count): if i < 60 or i > 76: coord = (0, 0, 0, 0) else: if len(names[i % 12]) == 1: # White note coord = (white_x, 50, 100, 500) white_x += 110 else: coord = (black_x, 50, 90, 250) if names[i % 12] in ['D#', 'A#']: black_x += 110 black_x += 110 curr = note.Note(names[i % 12] + str((i + 9) // 12), 21 + i, led.Led(led_hndl[i % 2]), coord) notes.append(curr) return notes
def main(): try: stt = streaming.StreamingSTT( # replace with speech to text credentials username '9d28bb42-fd0f-4126-ac66-2d0882fbe7f8', # replace with speech to text credentials password 'Gixj8klOaqK4') except: fatalFailure() try: tts = textToSpeech.TextToSpeech( # replace with text to speech credentials username '6fa627fb-384e-4586-9a72-185b70c1f09a', # replace with text to speech credentials password 'zQYWSqHEA7dm') except: fatalFailure() try: convo = conversation.Conversation( # replace with conversation credentials username 'bdce62cf-d7f7-4cbc-8b0b-dee6950d1c01', # replace with conversation credentials password 'K5Cmn1aJ3He8', # replace with workspace ID. '0c3cdb7b-3258-457e-a3b7-1b1236fea9c4') except: fatalFailure() # replace with robot name name = 'Bonnie' servo_obj = servo.Servo() servoP = servoProcess.ServoProcess(servo_obj) led_obj = led.Led() ledP = ledProcess.LedProcess(led_obj) music_obj = music.Music("/home/pi/tj-python/resources/music.wav") musicP = musicProcess.MusicProcess(music_obj) time.sleep(.5) ledP.red() time.sleep(.5) ledP.green() time.sleep(.5) ledP.blue() time.sleep(.5) ledP.rainbowCycle(.0001, 99999999999999) # tts.speak("Hello, just a moment while I boot up") servoP.wave(3) """l = led.Led() le = ledProcess.LedProcess(l) print('sleeping') time.sleep(3) print('done sleeping, Lets Strobe') le.strobe() #le.customColor(255,0,0) print('sleeping') time.sleep(3) print('kill in 2') time.sleep(2) le.customColor(255,0,0) #le.stop() print('dead') """ tts.speak('Hello my name is ' + name + ' I am the CBU admissions bot') while True: ledP.blue() try: phrase = stt.get_phrase() except: ledP.red() ledP.orange() if (name in phrase) or ('bunny' in phrase) or ('body' in phrase) or ( 'Bani' in phrase): response = convo.sendMessage(phrase) ledP.green() #response = response.upper() if '~' in response: print('Command Found') if '~RED' in response: ledP.red() response = response.replace('~RED', '', 1) if '~ORANGE' in response: ledP.orange() response = response.replace('~ORANGE', '', 1) if '~YELLOW' in response: ledP.yellow() response = response.replace('~YELLOW', '', 1) if '~GREEN' in response: ledP.green() response = response.replace('~GREEN', '', 1) if '~BLUE' in response: print('Its Blue') ledP.blue() response = response.replace('~BLUE', '', 1) if '~PURPLE' in response: ledP.purple() response = response.replace('~PURPLE', '', 1) if '~PINK' in response: ledP.pink() response = response.replace('~PINK', '', 1) if '~WHITE' in response: ledP.white() response = response.replace('~WHITE', '', 1) if '~RAINBOW' in response: ledP.rainbow() response = response.replace('~RAINBOW', '', 1) if '~RAINBOWCYCLE' in response: ledP.rainbowCycle() response = response.replace('~RAINBOWCYCLE', '', 1) if '~MUSICPLAY' in response: musicP.play() response = response.replace('~MUSICPLAY', '', 1) if '~MUSICSTOP' in response: musicP.stop() response = response.replace('~MUSICSTOP', '', 1) if '~LEDOFF' in response: ledP.off() response = response.replace('~LEDOFF', '', 1) if '~ARMSTOP' in response: servoP.stop() response = response.replace('~ARMSTOP', '', 1) if '~ARMUP' in response: servoP.armUp() response = response.replace('~ARMUP', '', 1) if '~ARMDOWN' in response: servoP.armDown() response = response.replace('~ARMDOWN', '', 1) if '~DANCE' in response: servoP.wave(10) ledP.rainbowCycle(1, 50) response = response.replace('~DANCE', '', 1) if '~ARMANGLE' in response: response = response.replace('~ARMANGLE', '', 1) param = int(response.split("~", 1)[0]) response = response.split("~", 1)[1] servoP.angle(param) if '~ARMWAVECOUNT' in response: response = response.replace('~ARMWAVECOUNTARMANGLE', '', 1) param = int(response.split("~", 1)[0]) response = response.split("~", 1)[1] servoP.wave(param) if '~ARMWAVE' in response: servoP.wave(2) response = response.replace('~ARMWAVE', '', 1) if response == '': response = 'awkward silence' ledP.pink() tts.speak(response)
sats = 0 if isinstance(dot.satellites, list): i = 0 j = 0 for sat in dot.satellites: if sat['used']: i += 1 j += 1 sats_used = i sats = j f['sats'] = sats f['sats_used'] = sats_used led = led.Led(5, 25, led.BRIGHT_HIGHEST) led.Clear() influxdb = InfluxDBClient('localhost', 8086, 'root', 'root', 'gps') influxdb.create_database('gps') shiftpi.startup_mode(shiftpi.LOW, True) gps = agps3.GPSDSocket() dot = agps3.Dot() gps.connect() gps.watch() for n in gps: if n: dot.unpack(n)
lcd.clear() lcd.puts("PRESS TO START") Led_one.off() Led_two.off() GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) joy = joystick.Joystick() joy.start() lcd = character_lcd.CharLcd() Led_one = led.Led(1) Led_two = led.Led(2) while (1): clear(joy, lcd, Led_one, Led_two) while (joy.start_flag == 0): pass lcd.clear() lcd.puts("STARTED") time.sleep(5) if (joy.counter % 2 == 0): Led_one.on()
def main(): #Attempts at handling segementation faults and pipe faults signal.signal(signal.SIGPIPE, sig_handler) signal.signal(signal.SIGSEGV, sig_handler) #Creation of the LED object and Process led_obj = led.Led() ledP = ledProcess.LedProcess(led_obj) #Creation of the error handler and it passed the LED process so it can refrence it errorHandle = errorHandler.errorHandler(ledP) config = configparser.ConfigParser() #This pulls in all of the credentials from the config files #If one of these fails to pull in a fatal error is called try: config.read('/home/pi/SeniorProjectBioloid/config.cfg') sttUser = config.get('Bioloid Credentials', 'sttUser') sttPw = config.get('Bioloid Credentials', 'sttPassword') ttsUser = config.get('Bioloid Credentials', 'ttsUser') ttsPw = config.get('Bioloid Credentials', 'ttsPassword') convoUser = config.get('Bioloid Credentials', 'convoUser') convoPw = config.get('Bioloid Credentials', 'convoPassword') convoWorkSpace = config.get('Bioloid Credentials', 'convoWorkSpace') # configuration for timeout options timeoutWarning = float( config.get('Bioloid Information', 'timeoutWarning')) timeoutShutdown = float( config.get('Bioloid Information', 'timeoutShutdown')) soundsLike = config.get('Bioloid Information', 'soundsLike') except: errorHandle.fatalError(1) homophones = soundsLike.split(",") #Start Creating the Watson servicesself. #If one of them fails then it gives an erro #the credentials can be changed in the config file try: stt = streaming.StreamingSTT(sttUser, sttPw) except: errorHandle.fatalError(2) try: tts = textToSpeech.TextToSpeech(ttsUser, ttsPw) except: errorHandle.fatalError(3) try: convo = conversation.Conversation(convoUser, convoPw, convoWorkSpace) except: errorHandle.fatalError(4) #Starts up the Visual recogniton abilites. try: vr = vis.VisualRecognition() except: errorHandle.fatalError(5) #Creates the bioloid so we cna control the motors try: bioloid = bio.Bioloid() except: errorHandle.fatalError(6) #bioloid.doLookUp() #say = vr.viewObjects() #tts.speak(say, False) #say = vr.viewFaces() #tts.speak(say, False) #bioloid.doIdle(False) #Gets the name of the robot from the Config File name = config.get('Bioloid Information', 'name') #This allows to see if the robot has been inactive lastActiveTime = time.time() activeTimeCheck = True # This boolean differentiates between inactivity for 60 or 120 seconds. #bioloid.doBow() #Kind of a hello works to know TTS is working. tts.speak('Hello my name is ' + name + ' I am a big robot!') # bioloid.doPushUp(2) while True: if all([ time.time() - lastActiveTime > timeoutWarning, activeTimeCheck == True ]): bioloid.doSit() tts.speak( "I have been inactive for 1 minute. After another minute, I will shut down" ) activeTimeCheck = False if all([ time.time() - lastActiveTime > timeoutShutdown, activeTimeCheck == False ]): bioloid.doSit() tts.speak("Shutting down now.") call("sudo shutdown -h now", shell=True) """ if(lastActiveTime - time.time() > 60): #if it is inactive for 1 min then it powers down. #Go home tts.speak("I have been inactive for 1 minute. After another minute, I will shut down") """ bioloid.doListen() try: phrase = stt.get_phrase() print(phrase) except: errorHandle.error() if (name in phrase) or (checkForName(homophones, phrase)): lastActiveTime = time.time( ) #if its name is heard then we can assume it is active activeTimeCheck = True try: response = convo.sendMessage(phrase) except: print("The Response was blank") if '~' in response: response = processCommand(response, bioloid) else: bioloid.doIdle(False) tts.speak(response)
from flask import Flask, render_template, request, url_for import led cervena = led.Led(18) modra = led.Led(17) biela = led.Led(27) app = Flask(__name__) ## Here comes the magic ## @app.route('/led', methods=['POST']) def led(): re = request.get_json('led').get('led') if re == 'blue': modra.toggle() elif re == 'red': cervena.toggle() elif re == 'white': biela.toggle() return '', 204 @app.route('/') def index(): return render_template('index.html') if __name__ == "__main__":
import sys, pygame, os, game, led import screenobjects from gravsensor.adxl345 import adxl345 pygame.init() pygame.joystick.init() pygame.mouse.set_visible(0) game = game.Settings() #Initiate the LED led = led.Led() led.setColor(game.COLORS_TO_EYES[1]) # Used to manage how fast the screen updates clock = pygame.time.Clock() joysticks = [ pygame.joystick.Joystick(x) for x in range(pygame.joystick.get_count()) ] # Get count of joysticks joystick_count = pygame.joystick.get_count() print("Number of joysticks: {}".format(joystick_count)) #Setup the accelorometer accel = adxl345() #Check the joystick is plugged in and initiate it try: pygame.joystick.Joystick(0) except NameError:
import vcnl4010 import led import servo import util # Custom util functions import servoController import jsonEncoder import networkUtil # Custom Network functions (WIFI + MQTT) from umqtt.simple import MQTTClient # Entry Point Indication util.dots() # Setup led green = led.Led(13) red = led.Led(15) # Setup i2c Bus i2c = machine.I2C(-1, machine.Pin(5), machine.Pin(4)) util.msg('i2c bus created') # Instantiate Temperature sensor #Address of TMP007 Temperature Sensor temp007Address = 64 tempSensor = temp007.Temp007(i2c, temp007Address) util.msg('Temp007 instantiated, name: tempSensor') # Instantiate Proximity sensor #Address of VCNL4010 Proximity Sensor proxAddress = 19
def __init__(self, exit_callback=None, is_show_video=True): self.exit_callback = exit_callback self.is_show_video = is_show_video print("[INFO] Recog Started | " "exit_callback: " + str(exit_callback) + " | Show Video: " + str(is_show_video)) print("[INFO] Loading encodings.pickle") self.data = pickle.loads( open(os.getcwd() + "/encodings.pickle", "rb").read()) print("[INFO] Loading Cascade Classifier") self.detector = cv2.CascadeClassifier( os.getcwd() + "/haarcascade_frontalface_default.xml") self.unlock = Unlock.Unlock() self.current_state = 0 self.needed_password = "" self.perfect_face_counter = 0 self.frame_label = "" self.led = led.Led() # initialize the video stream and allow the camera sensor to warm up print("[INFO] starting video stream...") vs = cv2.VideoCapture(0) self.vs = vs time.sleep(2.0) self.recognizeFaceInit() # start the FPS counter fps = FPS().start() # loop over frames from the video file stream while True: # grab the frame from the threaded video stream and resize it # to 500px (to speedup processing) ret, frame = vs.read() frame = imutils.resize(frame, width=500) self.frame = frame if self.current_state == self.STATE_RECOGNIZING_FACE: self.recognizeFaceUpdate() elif self.current_state == self.STATE_RECONGNIZING_QR: self.recognizeQRUpdate() elif self.current_state == self.STATE_UNLOCKING_DOOR: self.unlockDoorUpdate() if (self.is_show_video): cv2.putText(frame, self.frame_label, (12, 20), cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.6, (0, 255, 0), 1) # display the image to our screen cv2.imshow("Frame", self.frame) key = cv2.waitKey(1) & 0xFF # if the `q` key was pressed, break from the loop if key == ord("q"): cv2.destroyAllWindows() vs.release() if self.exit_callback is not None: self.exit_callback() break elif key & 0xFF == 27: break # update the FPS counter fps.update() # stop the timer and display FPS information fps.stop() print("[INFO] elasped time: {:.2f}".format(fps.elapsed())) print("[INFO] approx. FPS: {:.2f}".format(fps.fps())) # do a bit of cleanup cv2.destroyAllWindows() vs.release()
import led import time l = led.Led(18) l.toggle() time.sleep(1) l.toggle()
self.state = self.co2 self.buzzer.turn_off() if self.sensor_service.get_co2() < self.co2_threshold: self.alarm_muted = True self.state = self.co2 self.buzzer.turn_off() disp = grove_4_digit_display.Grove( 16, 17, brightness=grove_4_digit_display.BRIGHT_HIGHEST) button = button.Button(pin=5, double_press_threshold=0.4) service = thingSpeakService.ThingSpeakService(channel=THING_SPEAK_CHANNEL, api_key=THING_SPEAK_API_KEY) buzzer = buzzer.Buzzer(12) servo = servo.Servo(pin=18, min=0, max=5000) rot_sensor = rotation.RotationSensor(pin=4, min=0, max=5000) led_actuator = led.Led(6) SM = StateMachine(button=button, display=disp, sensor_service=service, buzzer=buzzer, rotation_sensor=rot_sensor, servo=servo, led=led_actuator) try: while True: SM.run() except KeyboardInterrupt: disp.show(" ")
def __init__(self, servo_pin=params.kit_servo_pin): self.servo_pin = servo_pin self.l = led.Led()