def test_Slice_sliced_rval(self): ws = WS2812(1, 8) lights = Lights(ws) # Fill the lattice with a recognizable pattern for i, p in enumerate(tg(len(lights), 0)): lat = lights.lattice[i] for j, c in enumerate(p): lat[j] = c sls = lights[:2] # A sliced Lights has the correct length self.assertEqual(len(sls), 2) # A sliced Lights refers to the same lattice, not a copy self.assertIs(sls.lattice, lights.lattice) # A sliced Lights iterates over the correct lattice points self.assertEqual(list(sls), [bytearray(v) for v in tg(2,0)]) # A Lights can be sliced non-trivially and iterate over the # correct lattice points sls = lights[-2:-6:-2] self.assertEqual(len(sls), 2) self.assertEqual(list(sls), [bytearray(v) for v in [(18,19,20), (12,13,14)]])
def test_Slice_sliced_lval(self): ws = WS2812(1, 8) lights = Lights(ws) # Fill the lattice with a recognizable pattern for i, p in enumerate(tg(len(lights), 0)): lat = lights.lattice[i] for j, c in enumerate(p): lat[j] = c ref = lights.lattice[:] sls = lights[-2:-6:-2] # A Lights is indexable by an int for writing sls[1] = (10, 9, 8) self.assertEqual(list(sls), [bytearray(v) for v in [(18,19,20), (10,9,8)]]) # A Lights is indexable by a slice for writing sls[:] = [b'foo', b'bar'] self.assertEqual(list(sls), [bytearray(v) for v in [b'foo', b'bar']]) # The writes happen in the right place self.assertEqual([lights[6], lights[4]], [bytearray(v) for v in [b'foo', b'bar']]) # Other places don't get written self.assertEqual(list((i, lights[i]) for i in range(len(lights)) if i not in (6,4)), list((i, t) for i, t in enumerate(tg(len(lights), 0)) if i not in (6,4)))
def __init__(self): super().__init__() self.lights = Lights() self.weather = Weather() self.setObjectName('top-level') with open('ui.txt') as file: raw_ui = file.read() raw_ui += scale_template(forecast_day_template, 5) self.ui = UIBuilder(self, raw_ui) self.update_time() # set the time immediately self.light_buttons = {} self.create_lights_ui() self.weather_box = None self.update_weather_ui() self.weather_update_timeout = 1000 * 300 # five minutes, weather reports only update every 10 minutes self.light_refresh_timeout = 1000 * 10 self.interval(self.update_time, 1000) self.interval(self.rebuild_weather, self.weather_update_timeout) # poll every so often just in case the lights are changed elsewhere self.interval(self.refresh_lights, self.light_refresh_timeout) self.setStyleSheet(default_styles) self.setWindowTitle('Overseer Dashboard') self.show() # can be run using 'start_fullscreen.sh' for touch screens if 'fullscreen' in sys.argv: self.showFullScreen() else: self.setMinimumWidth(800) self.setMinimumHeight(480)
def setUp(self): #logging.basicConfig(level=logging.INFO) self.ws = WS2812(1, 8) self.lights = lights = Lights(self.ws) # Fill the lattice with a recognizable pattern for i, c in enumerate(tg(len(lights), 0)): p = lights.lattice[i] for j, v in enumerate(c): p[j] = v
def main(): remote = Remote() lights = Lights() lights_on_command = LightsOnCommand(lights) lights_off_command = LightsOffCommand(lights) remote.set_command(lights_on_command) remote.pressButton() remote.set_command(lights_off_command) remote.pressButton()
def setUp(self): #logging.basicConfig(level=logging.INFO) self.ws = WS2812(1, 8) self.lights = lights = Lights(self.ws) # Fill the lattice with a recognizable pattern for i, p in enumerate(tg(len(lights), 0)): lat = lights.lattice[i] for j, c in enumerate(p): lat[j] = c self.sls = lights[-2:-6:-2]
def __init__(self, modes): GPIO.setmode( GPIO.BCM) #set up to use gpio port numbers (instead of pin #s) self.buttons = Buttons() self.optos = Optos() self.lights = Lights() self.outlets = Outlets() self.sounds = Sounds() self.clock = Countdown(12) self.modes = modes self.last_time = time.localtime()
def setUp(self): #logging.basicConfig(level=logging.INFO) ws = self.ws = WS2812(1, 8) lights = self.lights = Lights(ws) # Fill the lattice with a recognizable pattern for i, p in enumerate(tg(len(lights), 0)): lat = lights.lattice[i] for j, c in enumerate(p): lat[j] = c # The leds are all clear self.assertEqual(sum(sum(c) for c in ws), 0) self.gear = Gear(lights=lights)
def main(): lights = Lights(3) button = False voice_rec_thread = OrderingRecording(pyaudio.PyAudio(), menu_keywords) print('ready') while True: state = GPIO.input(BUTTON) if not state and not button: voice_rec_thread.start() button = True if state and button: lights.change(255, 0, 0) voice_rec_thread.stop() voice_rec_thread.join(5) voice_rec_thread = OrderingRecording(pyaudio.PyAudio(), menu_keywords) lights.change(0, 0, 0) button = False
def __init__(self, write_fun=None, config={}): self.config = config if write_fun is None: @coroutine def write(self, *args): print(*args) self.write = write else: self.write = write_fun self.act_led = pyb.LED(3) self.err_led = pyb.LED(1) self.pkt_led = pyb.LED(2) self.pots = [0] * 4 self.percolator = \ Percolator(WS2812(spi_bus=config['leds'].get('spi'), led_count=config['leds'].get('qty'))) self.percolator.bingo = self.bingo self.ws_rings = WS2812(2, 2 * 7 + 45) self.ring_lights = Lights(self.ws_rings) self.feed_rollers = [ Jewel7(lights=self.ring_lights[0:7]), Jewel7(lights=self.ring_lights[7:14]) ] self.rr = RingRamp(lights=self.ring_lights[14:], circumference=60, \ bottom=7, \ g=-40.0, ball_check_fun = self.ball_check) # self.zap_balls = False self.set_brightness(31)
def acc(self): if not self.key_manager.check_key(self.key): # if the key is wrong returns error return self.build(self.error, "Wrong key") try: self.check_parameters() except Exception as e: return self.build(self.error, e.message) if self.get: pin = self.get_pin() if pin == 'A1': voltage = self.bridge.get(pin) return self.build(self.ok, str(get_celsius(voltage))) value = self.bridge.get(pin) return self.build(self.ok, str(value)) Lights(self.bridge).light_set(self.get_pin(), self.value) return self.build(self.ok, self.value)
def handle(self, data): now = "=TIMESTAMP_TO_DATE(INDIRECT(\"A\" & ROW()))" data.append(now) print('send the following to the sheet: %s' % data) self.sheet.append_values(data) # enable garbage collection gc.enable() print('garbage collection threshold: ' + str(gc.threshold())) # load configuration for a file config = Config('main.conf', 'key.json') # initialize an interface to LEDs lights = Lights(config.get('wifi_led_pid'), config.get('error_led_pid'), config.get('high_co2_led_pin')) lights.off() # create an instance of ServiceAccount class # which then is going to be used to obtain an OAuth2 token # for writing data to a sheet sa = ServiceAccount() sa.email(config.get('google_service_account_email')) sa.scope('https://www.googleapis.com/auth/spreadsheets') sa.private_rsa_key(config.private_rsa_key()) # create an instance of Spreadsheet which is used to write data to a sheet spreadsheet = Spreadsheet() spreadsheet.set_service_account(sa) spreadsheet.set_id(config.get('google_sheet_id')) spreadsheet.set_range('A:A')
def getRequestResponse(self): if self.command == RequestHandler.HEARTBEAT: self.setData({ 'serverType': self.player.getServerType(), 'irRemote': config.USES_IR_REMOTE }) elif self.command == RequestHandler.PLAY_PAUSE: self.player.playPause() elif self.command == RequestHandler.NEXT: self.player.next() elif self.command == RequestHandler.PREVIOUS: self.player.previous() elif self.command == RequestHandler.SEEK_FORWARD: self.player.seekForward() elif self.command == RequestHandler.SEEK_BACKWARD: self.player.seekBackward() elif self.command == RequestHandler.SKIP_TITLE_SEQUENCE: self.player.skipTitleSequence() elif self.command == RequestHandler.VOLUME_UP: self.player.volumeUp() elif self.command == RequestHandler.VOLUME_DOWN: self.player.volumeDown() elif self.command == RequestHandler.FULLSCREEN: self.player.fullScreen() elif self.command == RequestHandler.TOGGLE_CONTROLS: self.player.toggleControls() elif self.command == RequestHandler.RANDOM_SETTINGS: self.setData(Shows(self.mountPoint).getShowCategories()) elif self.command == RequestHandler.ALL_SHOWS: self.setData(Shows(self.mountPoint).getAllShows()) elif self.command == RequestHandler.LAST_PLAYLIST: playlist = self.player.getPlaylist() playlistExists = playlist.playlistExists() if playlistExists: self.player.playPlaylist() self.setSuccess(playlistExists) self.setData(playlist.getFormattedShows()) elif self.command == RequestHandler.CURRENT_PLAYLIST or self.command == RequestHandler.CURRENT_PLAYLIST_SELECTION: playlist = self.player.getPlaylist() self.setSuccess(playlist.playlistExists()) self.setData(playlist.getFormattedShows()) elif self.command == RequestHandler.RANDOM: filePaths = self.getRandom() if self.success and filePaths: self.playRandom(filePaths) elif self.command == RequestHandler.FOREIGN_RANDOM: if 'localhost' == config.CONNECTION_TYPE: filePaths = self.getRandom() if self.success and filePaths: self.setData(filePaths) else: self.setSuccess(False) elif self.command == RequestHandler.BROWSE: self.browse() elif self.command == RequestHandler.PLAY: self.play(Player.PLAY) elif self.command == RequestHandler.ENQUEUE: self.play(Player.ENQUEUE) elif self.command == RequestHandler.INSERT_AT: self.insertAt() elif self.command == RequestHandler.PLAY_AT: self.playAt() elif self.command == RequestHandler.FOREIGN_UPDATE_PLAY_TIME: if 'localhost' == config.CONNECTION_TYPE: self.__checkAndUpdateFilePaths() else: self.setSuccess(False) elif self.command == RequestHandler.QUIT: self.player.quit() #TV commands, handled seperatly elif self.command == RequestHandler.TV_VOLUME_UP: if not config.USES_IR_REMOTE: raise CommandNotSupported( 'No support for IR commands on this server') IRRemote.sendCommand(IRRemote.VOLUME_UP) elif self.command == RequestHandler.TV_VOLUME_DOWN: if not config.USES_IR_REMOTE: raise CommandNotSupported( 'No support for IR commands on this server') IRRemote.sendCommand(IRRemote.VOLUME_DOWN) elif self.command == RequestHandler.TV_MUTE: if not config.USES_IR_REMOTE: raise CommandNotSupported( 'No support for IR commands on this server') IRRemote.sendCommand(IRRemote.MUTE) elif self.command == RequestHandler.TV_POWER: if not config.USES_IR_REMOTE: raise CommandNotSupported( 'No support for IR commands on this server') IRRemote.sendCommand(IRRemote.POWER) elif self.command == RequestHandler.TV_SOURCE: if not config.USES_IR_REMOTE: raise CommandNotSupported( 'No support for IR commands on this server') IRRemote.sendCommand(IRRemote.SOURCE) #BT commads, handled seperatly elif self.command == RequestHandler.HARDWARE_BUTTON_PRESS: if not config.IS_BLUETOOTH_SERVER: raise CommandNotSupported( 'Cannot send Bluetooth commands on a non Bluetooth server') BluetoothServer.QUEUE.put(BluetoothServer.HARDWARE_BUTTON_PRESS) elif self.command == RequestHandler.HARDWARE_BUTTON_PRESS_AND_HOLD: if not config.IS_BLUETOOTH_SERVER: raise CommandNotSupported( 'Cannot send Bluetooth commands on a non Bluetooth server') BluetoothServer.QUEUE.put( BluetoothServer.HARDWARE_BUTTON_PRESS_AND_HOLD) elif self.command == RequestHandler.LIGHTS_RGB: if not config.IS_BLUETOOTH_SERVER: raise CommandNotSupported( 'Cannot send Bluetooth commands on a non Bluetooth server') lights = Lights(self.postVars.get('red', 0), self.postVars.get('green', 0), self.postVars.get('blue', 0)) command = lights.buildString() if not command: raise CommandNotSupported( 'All colors must be between 255 and 0') queueCommand = BluetoothServer.LIGHTS_RGB + command BluetoothServer.QUEUE.put(queueCommand) #If we have made it this far, we don't know how to handle this command as we should just raise our exception else: raise InvalidRequest('Unknown request command') return self.respond()
from lights import Lights import os import time from threading import Thread from subprocess import call l = Lights(39) def fan(arg): call(["sudo", "./uhubctl", "-p", "2", "-a", arg]) def lightsPattern(): for i in range(2): if i%2 == 0: l.fillEach((100,0,0), 0.05) else: l.fillEach((0,0,100), 0.05) def lightsOff(): l.fillEach((0,0,0), 0.05) print("Options\n-----------------\n0. Fan Off\n1. Fan on\n2. Lights going\n3. Lights red\n4. Lights Blue\n5. Lights off\n---------------------\n") while True: option = input("Enter option: ") if option == '0': fan('0') elif option == '1': fan('1') elif option == '2':
from lights import RGB from lights import Lights import time colors = RGB(255, 255, 255) #Create an RGB object myLights = Lights(12, colors, 0.1, 0, 0) #Create a light object time.sleep(3) colors.setRed(255) colors.setGreen(0) colors.setBlue(0) myLights.setColor()
'start': { 'color_x': 0, 'color_y': 0, 'level': 100, 'devices': [DEVICE] }, 'start': { 'color_x': 0, 'color_y': 0, 'level': 100, 'devices': [DEVICE] } } } light_api = Lights() def find_setting(ev): wordlist = ev['description'].split() smallcaps = map(lambda x: x.lower(), wordlist) for word in smallcaps: if word in KEYWORD_SETTING_MAP: return KEYWORD_SETTING_MAP[word] return DEFAULT_SETTING def call_light(lc, dt): ''' lc light call
from lights import RGB from lights import Lights import time dayColor = RGB(255, 255, 255) #Create a day RGB object (default color white light) nightColor = RGB(255, 0, 0) #Create a night RGB object (default color red light) myLights = Lights(dayColor, 0.1) #Create a light object time.sleep(3) myLights.setColor(nightColor)
def success_lights(wm): sleep(0.2) lights = Lights(wm).auto() sleep(2)
def test_Slice(self): ws = WS2812(1, 8) lights = Lights(ws) self.assertEqual(len(lights), 8)
from lights import Lights lights = Lights() for corner in ((0, 0), (0, 99), (99, 0), (99, 99)): lights.state[corner] = 'X' for i in range(100): lights.iterate() print(lights.count_on())
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ # Domotics lights module test, turn on and then off with a delay of 0.1 sec on pin 13. # - # @author giuliobosco # @version 1.0 (2019-04-12 - 2019-04-12) import sys sys.path.insert(0, '/usr/lib/python2.7/bridge') from time import sleep from bridgeclient import BridgeClient as bridgeclient from lights import Lights # class test lights = Lights(bridgeclient()) lights.lightOn() sleep(0.1) lights.lightOff()
from camera import Camera from model import Geometry from warp import Warp from render import Render BATCH_SIZE = 10 NUM_WARPS = 5 num_vertices = 100 num_faces = 150 num_lights = 1 base_model = Geometry(vertices=np.random.randn(num_vertices, 3), faces=np.random.randint(0, num_vertices, size=[num_faces, 3])) lights = Lights(positions=np.random.randn(num_lights, 3), intensities=np.random.randn(num_lights, 3)) camera = Camera(eye=np.random.randn(1, 3), center=np.random.randn(1, 3), world_up=np.random.randn(1, 3)) trans = Transform(batch_size=BATCH_SIZE) warp_params = Input(shape=[NUM_WARPS, 1]) warped_vertices = Warp(num_warps=NUM_WARPS)( [K.identity(base_model.vertices), warp_params]) world_coords = trans(warped_vertices) colors = K.constant(np.random.randn(BATCH_SIZE, num_vertices, 3)) rendered = Render(512, 512)([world_coords, base_model.faces], base_model.calculate_normals(world_coords), colors, [camera.eye, camera.center, camera.world_up], [lights.positions, lights.intensities])
logging.warning('** - lights off time: ' + str(lightsOffDateTime)) job = self.scheduler.add_job(self.lightsOff, misfire_grace_time=86400, trigger='date', next_run_time=str(lightsOffDateTime), args=[config, Dusk(config)]) logging.warning("scheduled job added: %s" % job) def lightsOff(self, config, dusk): # Turn the lights off logging.warning('********** Lights Off *************') self.lights.switch('one', False) # Look up tomorrow's dusktime tomorrow = date.today() + timedelta(days=1) tomorrowDuskDateTime = dusk.getDuskTime(tomorrow) logging.warning('** - dusk time at: ' + str(tomorrowDuskDateTime)) # Schedule to turn the lights on at the next dusktime job = self.scheduler.add_job(self.lightsOn, misfire_grace_time=86400, trigger='date', next_run_time=str(tomorrowDuskDateTime), args=[config]) logging.warning("scheduled job added: %s" % job) if __name__ == "__main__": LightSchedule(Lights(Config())).main(Config(), Dusk(Config()))
@app.route('/frame', methods=['GET']) def get_frame(): return jsonify(lights.get_state()) def command_handler(cmd, write_frame): (name, payload) = cmd if cmd == "frame": write_frame(payload["frame"]) elif cmd == "loop": while True: if cmd["id"] != atomic_int.value: break for frame in payload["frames"]: duration = frame["duration"] pixels = frame["pixels"] write_frame(pixels) time.sleep(duration) elif cmd == "singleshot": for frame in payload["frames"]: duration = frame["duration"] pixels = frame["pixels"] write_frame(pixels) time.sleep(duration) if __name__ == "__main__": with Lights(command_handler) as lights: app.run(host='0.0.0.0')
if __name__ == "__main__": # error checks to see if the argument given was a number and not a string if len(sys.argv) > 1: if not sys.argv[1].isdigit(): print("please enter a number or leave the argument blank") exit() # initialise the light set LightSet = [] # if argument wasn't passed, the list is of length 20 otherwise the argument maxSet = int(sys.argv[1]) if len(sys.argv) > 1 else 20 # fills the list with the order of Colour list and turns them on for 1 second for i in range(0, maxSet): LightSet.append(Lights(Colours[i % 7])) LightSet[i].toggleState() printLight(LightSet[i], i + 1) time.sleep(1) # Goes through the list of lights and turns them off for i in range(0, maxSet): LightSet[i].toggleState() printLight(LightSet[i], i + 1) index = 0 while True: try: # user can enter commands for the program while its running string = input("Enter command: ")
import time from adafruit_crickit import crickit from adafruit_seesaw.neopixel import NeoPixel num_pixels = 75 ######################### sample_format = pyaudio.paFloat32 # 16 bits per sample channels = 1 fs = 48000 seconds = 3 counter = 1 ######################### # The following line sets up a NeoPixel strip on Seesaw pin 20 for Feather lights = Lights(num_pixels) # Audio recording parameters, set for our USB mic. RATE = 48000 #if you change mics - be sure to change this :) chunk = CHUNK = int(RATE / 10) # Record in chunks of 1024 samples # chunk = CHUNK = 10 # Record in chunks of 1024 samples # CHUNK = int(RATE / 10) # 100ms # CHUNK = 1024 credential_path = "/home/pi/Desktop/gcp_credentials.json" #replace with your file name! os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = credential_path client = speech.SpeechClient() sentiment_client = language.LanguageServiceClient()
def _spin_hardware_channels(self): self.lights = Lights(self.light_input_queue, self.light_output_queue) self.motor = Lights(self.light_input_queue, self.light_output_queue) self.mfcs = Lights(self.light_input_queue, self.light_output_queue)
def activate_alert(self): # Turn on lights # Play alert playsound(self.alarm_sound, block=False) all_lights = Lights() all_lights.flicker_lights(16, "on")
#!/usr/bin/env python import logging from button import Button from lights import Lights from open_ocd import OpenOCD from tel_con import TelCon if __name__ == '__main__': logging.basicConfig(format="%(asctime)s:" + logging.BASIC_FORMAT) logger = logging.getLogger() logger.setLevel(logging.DEBUG) while True: try: with Lights(logger.getChild('lights')) as light: with Button(logger.getChild('button')) as button: button.wait_for_button_press() light.busy() try: with OpenOCD(logger.getChild('openocd')) as openOCD: with TelCon(logger.getChild('telcon')) as telcon: telcon.halt() telcon.erase() telcon.load() light.busyOff() light.success() except Exception: logging.warn("Provisioning failed") light.busyOff() light.failed() except Exception:
def __init__(self, mic): self.lights = Lights() self.therm = TempMonitor() self.door = Door(mic)