def make_packet_plan(self, starting_snake_length=None): L, H, D = self.light_dimensions packets = [] if self.macro_mode == 0: colors_rgb = [ Lights.rgb_from_color(x) for x in self.current_colors ] if self.select_mode == 0: # blocks packet = Lights.get_blocks_packet(colors_rgb, self.light_dimensions) packets.append(packet) # for i in range(L): # packets.append(Lights.shift_packet(packet, i, right=True)) elif self.select_mode == 1: # alternating packet = Lights.get_alternating_packet(colors_rgb, self.light_dimensions, self.segment_size) packets.append(packet) # for i in range(len(colors_rgb)): # for j in range(self.segment_size): # packets.append(Lights.shift_packet(packet, i * self.segment_size + j + 1, right=True)) elif self.macro_mode == 1: # chase game kwargs = {} if self.chase_game is not None: kwargs['is_3d'] = self.chase_game.is_3d kwargs['num_enemies'] = self.chase_game.num_enemies kwargs[ 'wall_density_divisor_index'] = self.chase_game.wall_density_divisor_index self.chase_game = ChaseGame(self.logger, self.light_dimensions, self.light_sender, gui=self.gui, **kwargs) self.chase_game.make_new_game() packets.append(self.chase_game.draw_game_board()) elif self.macro_mode == 2: # snake game if self.snake_game is not None: self.snake_game = SnakeGame.create_new(self.snake_game, self.light_dimensions) else: self.snake_game = SnakeGame(self.logger, self.light_dimensions, self.light_sender, gui=self.gui) self.snake_game.make_new_game( starting_snake_length=starting_snake_length) packets.append(self.snake_game.draw_game_board()) return PacketPlan(packets)
def cozmo_program(robot: cozmo.robot.Robot): f = Face(robot) f.find_person() d = Drive(robot) weather = Weather(f.city) weather.set_outfit() welcome = Welcome(robot) welcome.hello(weather.w, weather.outfit, f.city, f.name) e = input() if e == "exit": robot.say_text("Goodbye") else: l = Lights() l.set_lights(d, weather.number) d.find(weather.number)
def update_lights(self): # grab the current index for all active plans and merge those plans together # if there are no active plans left, then set to black if self.current_packet_plans: packets_to_merge = [x.get_current_packet() for x in self.current_packet_plans] try: packet = Lights.merge_packets(packets_to_merge, self.light_dimensions) except IndexError: self.logger.warning('Index error when merging packets, likely due to light dimensions being reallocated. Setting to black for now and expecting it to fix itself next time around') packet = Lights.make_whole_string_packet((0, 0, 0), self.light_dimensions) else: packet = Lights.make_whole_string_packet((0, 0, 0), self.light_dimensions) # invoke light updater self.light_sender.set_lights(self.name, packet)
def __init__(self): self.datapoints = [] self.measured_value = 0 # TODO Rufe den Konstruktor von MTTFCalculator (s. Datei MTTF) # auf und speichere das Objekt in der Instanzvariable "self.mttf_calculator". # Tipp: Konstruktoren werden mit "Klassenname()" aufgerufen. # Ein Beispiel ist die Definition von "self.rule_checker" weiter unten. self.estimated_value = self.ask_for_estimated_value() # TODO Rufe die von dir erstelle Methode auf, die nach der Standardabweichung fragt # und speichere das Ergebnis in "self.standard_deviation". # Tipp: Schau dir die Definition vom Erwartungswert ("estimated_value") an. self.rule_checker = WesternDigitalRuleChecker(self.estimated_value, self.standard_deviation) self.lights = Lights(17, 27, 22)
def main(): parser = argparse.ArgumentParser() parser.add_argument( "--input", "-i", help="Parameter required to provide input to the program", action="store_true") parser.add_argument("filename", help="Complete path for the file") args = parser.parse_args() filePath = args.filename if args.input: count = "" if filePath.startswith("http:"): response = requests.get(filePath) with open('input.txt', 'w') as fout: fout.writelines(response.text) fout.close() filePath = 'input.txt' with open(filePath) as fin: L = int(fin.readline()) if L > 0: _lights = Lights(L) regex = re.compile( ".*(turn on|turn off|switch)\s*([+-]?\d+)\s*,\s*([+-]?\d+)\s*through\s*([+-]?\d+)\s*,\s*([+-]?\d+).*" ) for i in fin.readlines(): result = regex.search(i) if result != None: method = str(result.group(1)) # print(method.strip()) l1 = int(result.group(2)) l2 = int(result.group(3)) l3 = int(result.group(4)) l4 = int(result.group(5)) if l1 < 0: l1 = 0 if l3 < 0: l3 = 0 if l2 > L: l2 = L - 1 if l4 > L: l4 = L - 1 _lights.runCmd(method, l1, l2, l3, l4) count = _lights.counts() print(count)
def run_lights(self): self.current_packet_plan = Lights.make_interlude_packet_plan( self.light_dimensions) self.current_packet_plan_index = 0 self.last_motion_step_time = datetime.now() # invoke light updater self.light_sender.set_lights( self.name, self.current_packet_plan[self.current_packet_plan_index])
def on_button_pressed(self, button): super().on_button_pressed(button) # when a drum is hit, light up in that color color = self.get_friendly_button_name(button) self.logger.info(f"{color} press") if color in ['red', 'yellow', 'blue', 'green', 'orange']: L, H, D = self.light_dimensions if self.mode == 0: # Make the pulse plan and multiply by the appropriate dimming mask packet_plan = Lights.make_pulse_packet_plan( color_rgb=Lights.rgb_from_color(color), light_dimensions=self.light_dimensions ) packet_plan = Lights.apply_dim_plan(packet_plan, [self.color_masks[color]]*len(packet_plan)) self.current_packet_plans.append(PacketPlan(packet_plan, time_delay=self.time_delay)) elif self.mode == 1: try: for starting_point in self.color_spread_map[color]["starts"]: packet_plan = Lights.make_meteor_packet_plan( color_rgb=Lights.rgb_from_color(color), light_dimensions=self.light_dimensions, start_pixel=starting_point, pulse_size=self.color_spread_map[color]["pulse"] ) self.current_packet_plans.append(PacketPlan(packet_plan, time_delay=self.time_delay)) except KeyError: self.logger.error('Error finding color starting point for mode 1. Skipping for now and will try again next time') elif color == 'plus': self.mode = 0 if self.mode == 1 else self.mode + 1 self.light_sender.write_log_entry(self.name, f"mode_{self.mode}_active") elif color == 'minus': self.mode = 1 if self.mode == 0 else self.mode - 1 self.light_sender.write_log_entry(self.name, f"mode_{self.mode}_active")
def run(): print("Tap your magic band!") rfid_reader = RFIDReader() lights = Lights() if rfid_reader.read() == True: lights.turn_on() time.sleep(2) lights.turn_off()
def update_lights(self): # invoke light updater new_packet = self.main_packet_plan.get_current_packet() if self.temp_packet_plans: packets_to_merge = [new_packet] + [ x.get_current_packet() for x in self.temp_packet_plans ] try: new_packet = Lights.merge_packets(packets_to_merge, self.light_dimensions) except IndexError: self.logger.warning( 'Index error when merging packets, likely due to light dimensions being reallocated. Skipping merge and using main packet instead and expecting it to fix itself next time around' ) self.light_sender.set_lights(self.name, new_packet)
def draw_game_board(self): L, H, D = self.light_dimensions packet = Lights.make_whole_string_packet( Lights.rgb_from_color('white'), self.light_dimensions, scale_value=0.05) snake_colors = Lights.make_gradient_colors( len(self.snake), Lights.rgb_from_color('green'), Lights.rgb_from_color('yellow')) for s, item in enumerate(self.snake): k, j, i = item packet[i][j][k] = snake_colors[s] k, j, i = self.target packet[i][j][k] = Lights.rgb_from_color('teal') return packet
def __init__(self, controller, logger, name, light_dimensions, light_sender, gui): super().__init__(controller, logger, name, light_dimensions, light_sender, gui) self.select_mode = 0 self.selector_position = None self.dim_ratio = None self.motion_direction_list = ['right', 'up', 'forward', 'left', 'down', 'backward'] self.motion_direction_index = 0 self.current_colors = [] self.current_motion_colors = [] self.main_packet_plan = PacketPlan([Lights.make_whole_string_packet((0, 0, 0), self.light_dimensions)]) for button in controller.buttons: button.when_pressed = self.on_button_pressed button.when_released = self.on_button_released for axis in controller.axes: if self.get_friendly_axis_name(axis.name) == 'selector': # initialize selector switch _, self.selector_position = self.get_axis_details(axis) self.main_packet_plan.time_delay = self.get_time_delay_from_selector_position(self.selector_position) axis.when_moved = self.on_axis_moved
def draw_game_board(self): L, H, D = self.light_dimensions packet = Lights.make_whole_string_packet( Lights.rgb_from_color('white'), self.light_dimensions, scale_value=0.1) for wall in self.walls: k, j, i = wall packet[i][j][k] = Lights.rgb_from_color('yellow') k, j, i = self.target_pixel packet[i][j][k] = Lights.rgb_from_color('green') k, j, i = self.chase_pixel packet[i][j][k] = Lights.rgb_from_color('blue') for enemy in self.enemies: k, j, i = enemy packet[i][j][k] = Lights.rgb_from_color('red') return packet
def next_moving_step(self, current_time): pulse_plan = None if (current_time - self.last_motion_step_time ).total_seconds() >= self.speed_time_delay: hit_boundary, hit_self, hit_target = self.move_one_step() self.last_motion_step_time = current_time # if hit boundary, pulse red and start the game over by making a new board if hit_boundary: pulse_plan = PacketPlan(Lights.make_pulse_packet_plan( Lights.rgb_from_color('red'), self.light_dimensions, frames=6), time_delay=0.05) self.make_new_game() # if hit snake, pulse orange and start the game over by making a new board elif hit_self: pulse_plan = PacketPlan(Lights.make_pulse_packet_plan( Lights.rgb_from_color('orange'), self.light_dimensions, frames=6), time_delay=0.05) self.make_new_game() # if caught the next bite, quick pulse green and make a new target elif hit_target: pulse_plan = PacketPlan(Lights.make_pulse_packet_plan( Lights.rgb_from_color('green'), self.light_dimensions, frames=3), time_delay=0.05) self.target = self.make_target() # draw the board packet = self.draw_game_board() return packet, pulse_plan
def next_moving_step(self, current_time, left=None, right=None, forward=None, backward=None, desired_height=None): pulse_plan = None if not self.is_3d: forward = False backward = False if left or right or forward or backward or self.chase_pixel[ 1] + 1 != desired_height: reached_target, hit_walls, hit_enemy = self.move_chase_pixel( left=left, right=right, forward=forward, backward=backward, height_val=desired_height) if hit_enemy: # make a brand new game board self.logger.info(f'Hit enemy at location: {self.chase_pixel}') self.chase_pixel = (0, 0, 0) self.make_new_game(chase_position=self.chase_pixel) packet = self.draw_game_board() pulse_plan = PacketPlan(Lights.make_pulse_packet_plan( Lights.rgb_from_color('red'), self.light_dimensions, frames=6), time_delay=0.05) return packet, pulse_plan if reached_target: # make a new game board but keep the chase pixel and the enemies in current locations self.logger.info( f'Reached target at location: {self.chase_pixel}') self.make_new_game(chase_position=self.chase_pixel, create_new_enemies=False) packet = self.draw_game_board() pulse_plan = PacketPlan(Lights.make_pulse_packet_plan( Lights.rgb_from_color('green'), self.light_dimensions, frames=6), time_delay=0.05) return packet, pulse_plan if (current_time - self.last_motion_step_time_enemy ).total_seconds() >= self.enemy_time_delay: self.last_motion_step_time_enemy = current_time any_hit_target = False new_enemies = [] for enemy in self.enemies: if not any_hit_target: # if an earlier one hit the target, then don't check the next ones, just keep them where they are new_enemy, enemy_reached_target, enemy_hit_walls = self.move_enemy_pixel( enemy) if enemy_reached_target: # this means the enemy moved onto the chase pixel and we should flash red and make a new game board any_hit_target = True self.chase_pixel = (0, 0, 0) self.make_new_game(chase_position=self.chase_pixel) packet = self.draw_game_board() pulse_plan = PacketPlan(Lights.make_pulse_packet_plan( Lights.rgb_from_color('red'), self.light_dimensions, frames=6), time_delay=0.05) return packet, pulse_plan else: # just keep the enemy where it is as the starting point for next time since a different one hit the target new_enemy = enemy # add the enemy back to the list new_enemies.append(new_enemy) self.enemies = new_enemies packet = self.draw_game_board() return packet, pulse_plan
def run_lights(self, color_list, mode=0): L, H, D = self.light_dimensions num_colors = len(color_list) if num_colors == 0: packet_plan = PacketPlan([Lights.make_whole_string_packet((0, 0, 0), self.light_dimensions)]) else: colors_rgb = [Lights.rgb_from_color(x) for x in color_list] if mode == 0: # lights form 1 block of each color that was pressed packet_plan = PacketPlan([Lights.get_blocks_packet(colors_rgb, self.light_dimensions)]) elif mode == 1: # lights alternate statically with each color that was pressed pixel by pixel packet_plan = PacketPlan([Lights.get_alternating_packet(colors_rgb, self.light_dimensions)]) else: # moving modes packets = [] motion_dirs = self.motion_direction_list[self.motion_direction_index].split('_') dir_kw_args = {x: True for x in motion_dirs} if mode == 2: # the lights in the string scroll perpetually in the same pattern as mode 1 packet = Lights.get_blocks_packet(colors_rgb, self.light_dimensions) for i in range(L): packets.append(Lights.shift_packet(packet, i, **dir_kw_args)) elif mode == 3: # the lights in the string scroll perpetually in the same pattern as mode 0 packet = Lights.get_alternating_packet(colors_rgb, self.light_dimensions) for i in range(len(colors_rgb)): packets.append(Lights.shift_packet(packet, i, **dir_kw_args)) elif mode == 4: # the lights wipe on and off, in color blocks like in mode 0 packet = Lights.get_blocks_packet(colors_rgb, self.light_dimensions) packets = Lights.make_wipe_plan(packet, motion_dirs[0]) elif mode == 5: # the lights wipe on and off, alternating like in mode 1 packet = Lights.get_alternating_packet(colors_rgb, self.light_dimensions) packets = Lights.make_wipe_plan(packet, motion_dirs[0]) packet_plan = PacketPlan(packets, is_repeating=True, time_delay=self.get_time_delay_from_selector_position(self.selector_position)) self.main_packet_plan = packet_plan # check whammy position and dim accordingly new_packet = self.dim_packet(self.main_packet_plan.get_current_packet(), self.dim_ratio) # invoke light updater self.light_sender.set_lights(self.name, new_packet)
class QASystem: def __init__(self): self.datapoints = [] self.measured_value = 0 # TODO Rufe den Konstruktor von MTTFCalculator (s. Datei MTTF) # auf und speichere das Objekt in der Instanzvariable "self.mttf_calculator". # Tipp: Konstruktoren werden mit "Klassenname()" aufgerufen. # Ein Beispiel ist die Definition von "self.rule_checker" weiter unten. self.estimated_value = self.ask_for_estimated_value() # TODO Rufe die von dir erstelle Methode auf, die nach der Standardabweichung fragt # und speichere das Ergebnis in "self.standard_deviation". # Tipp: Schau dir die Definition vom Erwartungswert ("estimated_value") an. self.rule_checker = WesternDigitalRuleChecker(self.estimated_value, self.standard_deviation) self.lights = Lights(17, 27, 22) def ask_for_estimated_value(self): """Asks for the estimated value and returns the user input""" #TODO Erstelle eine Eingabeaufforderung die nach dem Erwartungswert fragt und gebe diesen zurueck. # Achte darauf, dass das Ergebnis eine Gleitkommazahl ist. # Das "pass" kann hier geloscht werden, wenn du deinen Code einfuegst. pass # TODO Erstelle eine Methode, die den Nutzer um die Standardabweichung # bittet und diese als Gleitkommazahl zurueckgibt. # Tipp: Schau dir die Definition von der ask_for_estimated_value-Funktion an. def handle_input(self, value): """Wird aufgerufen, wenn ein neuer Messpunkt eingegeben wurde""" self.measured_value = value self.datapoints.append(self.measured_value) if (not self.rule_checker.check_rule_1(self.datapoints)): print("Rule 1 failed") # TODO Wenn diese Regel nicht eingehalten wird, # ist das Werkstueck nicht nutzbar. Zeige dies mit der roten Lampe an. self.handle_error() elif (not self.rule_checker.check_rule_2(self.datapoints)): print("Rule 2 failed") self.handle_error() elif (not self.rule_checker.check_rule_3(self.datapoints)): print("Rule 3 failed") self.handle_error() # TODO Vervollstaendige die if-Abfrage um einen Test fuer die 4. Regel. else: #Datapoint is good self.lights.turn_green_light_on() def handle_error(self): """Diese Methode wird aufgerufen, wenn ein Fehler festgestellt wurde.""" # TODO Stelle sicher, dass die Lampen in der richtigen Konfiguration leuchten. # Welche Lampen sind evenutell noch auszuschalten, welche eventuell anzuschalten? # TODO Berechne den alten MTTF # TODO Haenge die Anzahl der erfolgreich produzierten Stuecke an die failures Liste (mttf-Objekt) an. # TODO Berechne die neue MTTF. self.mttf_calculator.write_to_file() # TODO Gebe die alte und neue MTTF ueber die Konsole aus. self.datapoints = [] self.measured_value = 0 # TODO Frage den Nutzer, ob die Produktion fortgesetzt werden soll. # Wenn ja, soll die Ampel entsprechend zurueckgesetzt werden. # Wenn nein, soll der Nutzer wieder gefragt werden. # Tipp: "while(true):" erstellt eine Endlosschleife. # Die Ausfuehrung einer Schleife kann mit dem Befehl "break" beendet werden. while (True): if (eingabe == "ja"): self.lights.turn
import json from Lights import Lights, LightStates from TV import TV, TVStates from flask import Flask, render_template, current_app, request from flask_ask import Ask, statement app = Flask(__name__) ask = Ask(app, '/remote/') light_thread = Lights(1, "Lights-1", 1) light_thread.start() tv_thread = TV(2, "Tv-1", 2) tv_thread.start() @ask.launch def launch(): message = "Hello Kaylie. I am the Alexa Remote. " \ "You can ask me to power on or off the tv, turn volume up or down, and change inputs. " \ "What would you like to do?" return statement(message) @ask.intent('TVPowerOn') def power_on(): if tv_thread.power_tv(True): message = "TV has been turned on" else: message = "TV is already on" return statement(message)
__author__ = 'sander' from Lights import Lights str = "get light kitchen" print(str.split(" ")) test = Lights() print(test.get_lights())
import numpy as np import sys, time import signal import Utils as u from Process import Processor from Trigger import Trigger from Parse import Parser import config haveLeds = config.device == "mypi" proc = Processor() parser = Parser() if haveLeds: from Lights import Lights led = Lights() led.stop() tr = Trigger(verbose=True, led=led, AMBIENT_MULT = 1.9) else: tr = Trigger(verbose=True) # proc.processTrainingSet(basedir="sounds/train/", signalword="oknavsa", savedir="data/") # proc.processTrainingSet(basedir="16khz/", signalword="oknavsa", savedir="data/") proc.loadTrainData("data/imagedata_15_15.npy") #if not in this range, we want to not fingerprint it to save time and trouble lower,upper = proc.getKeywordDurationRange() tr.setParams({"MIN_WORD_TIME": lower, "MAX_WORD_TIME": upper}) tr.setParams({"THRESHOLD": 150}) # tr.getAmbientLevels(duration=0.7)
def next_moving_step(self, current_time): # determine when a sequence should be shifted right = False left = False up = False down = False forward = False backward = False changed = False enemy_changed = False # handle current temp packet plans indexes_to_remove = [] for i, packet_plan in enumerate(self.temp_packet_plans): is_advanced, is_ended = packet_plan.advance_packet_plan( current_time) if is_advanced: changed = True if is_ended: indexes_to_remove.append(i) indexes_to_remove.sort(reverse=True) for ind in indexes_to_remove: try: self.temp_packet_plans.pop(ind) except IndexError: pass if self.macro_mode == 0: # if direction is not None, that means some control is engaged so we want motion # if the current_time is greater than the last motion time by at least the time_delay amount, then we need to do a motion step if self.wheel_direction is not None and ( current_time - self.last_motion_step_time_wheel ).total_seconds() >= self.wheel_time_delay: self.last_motion_step_time_wheel = current_time if self.wheel_direction == 'right': right = True else: left = True changed = True # gas pedal behavior changes between macro modes as does paddle shifter behavior # in mode 0, it controls the speed of motion and the reverse button controls direction up or down # in mode 1, it controls height above the bottom, with gravity pulling the pixel back down when the gas pedal is released if self.macro_mode == 0: if self.gas_direction is not None and ( current_time - self.last_motion_step_time_gas ).total_seconds() >= self.gas_time_delay: self.last_motion_step_time_gas = current_time up = True changed = True if self.brake_direction is not None and ( current_time - self.last_motion_step_time_brake ).total_seconds() >= self.brake_time_delay: self.last_motion_step_time_brake = current_time down = True changed = True if self.paddle_direction is not None and ( current_time - self.last_motion_step_time_paddle ).total_seconds() >= self.paddle_time_delay: self.last_motion_step_time_paddle = current_time if self.paddle_direction == 'forward': forward = True else: backward = True changed = True if changed: # shift the sequence packet = Lights.shift_packet( self.main_packet_plan.get_current_packet(), 1, left=left, right=right, up=up, down=down, forward=forward, backward=backward) self.main_packet_plan = PacketPlan([packet]) self.main_packet_plan.last_motion_step_time = current_time self.update_lights() elif self.macro_mode == 1 and self.chase_game is not None: if self.wheel_direction is not None and ( current_time - self.last_motion_step_time_wheel ).total_seconds() >= self.wheel_time_delay: self.last_motion_step_time_wheel = current_time if self.wheel_direction == 'right': right = True else: left = True H = self.light_dimensions[1] desired_height = round(self.current_gas_value * H) if self.paddle_click_direction is not None: if self.paddle_click_direction == 'forward': forward = True else: backward = True self.paddle_click_direction = None # for chase game, we always need to call out because there might be enemy movement even if no controller input packet, pulse_plan = self.chase_game.next_moving_step( current_time, left=left, right=right, forward=forward, backward=backward, desired_height=desired_height) if pulse_plan is not None: self.temp_packet_plans.append(pulse_plan) if packet is not None: self.main_packet_plan = PacketPlan([packet]) self.main_packet_plan.last_motion_step_time = current_time self.update_lights() elif self.macro_mode == 2 and self.snake_game is not None: # for snake game, just call out to the game and let it decide what to do since all direction input is asynchronously set packet, pulse_plan = self.snake_game.next_moving_step(current_time) if pulse_plan is not None: self.temp_packet_plans.append(pulse_plan) if packet is not None: self.main_packet_plan = PacketPlan([packet]) self.main_packet_plan.last_motion_step_time = current_time self.update_lights()
__author__ = 'sander' from Lights import Lights str = "get light kitchen" print(str.split(" ")) test = Lights() print(test.get_lights())