示例#1
0
    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)
示例#2
0
    def test_add_trigger_to_scheduler(self):
        scheduler = Mock(wraps=BackgroundScheduler())
        lights = Lights(scheduler=scheduler)

        state = True
        hour = 10
        minute = 20
        lights.add_trigger(state, hour, minute)

        scheduler.add_job.assert_called_with(func=ANY, args=[state, "trigger"], end_date=ANY, trigger="cron",
                                             id=None, hour=hour, minute=minute, day_of_week=None)
示例#3
0
    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()
示例#4
0
    def test_add_trigger_to_scheduler_all_week(self):
        scheduler = Mock(wraps=BackgroundScheduler())
        lights = Lights(scheduler=scheduler)

        state = True
        hour = 10
        minute = 20
        repeat_weekday = True
        repeat_weekend = True
        lights.add_trigger(state, hour, minute, repeat_weekday, repeat_weekend)

        scheduler.add_job.assert_called_with(func=ANY, args=[state, "trigger"], end_date=None, trigger="cron",
                                             id=None, hour=hour, minute=minute,
                                             day_of_week=Lights.weekdays + "," + Lights.weekends)
示例#5
0
class LightsStoreTest(TestCase):

    def setUp(self):
        self.store = LightsStoreStub()
        self.lights = Lights(store=self.store)

    def test_should_add_trigger_to_store(self):
        self.store.add_trigger = MagicMock()
        self.lights.add_trigger(True, 10, 20)
        self.store.add_trigger.assert_called_with(ANY)

    def test_should_read_triggers_from_store(self):
        self.store.read_triggers = MagicMock()
        self.lights = Lights(store=self.store)
        self.store.read_triggers.assert_called_with()

    def test_should_remove_trigger_from_store(self):
        self.store.remove_trigger = MagicMock()
        self.lights.remove_trigger(job_id=TRIGGER.job_id)
        self.store.remove_trigger.assert_called_with(TRIGGER.job_id)

    def test_should_add_history_entry_to_store(self):
        self.store.add_entry = MagicMock()
        self.lights.set_state(True, "test")
        self.store.add_entry.assert_called_with(True, "test")

    def test_should_read_history_from_store(self):
        self.store.read_history = MagicMock()
        self.lights.get_history()
        self.store.read_history.assert_called_with()
示例#6
0
    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)]])
示例#7
0
    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)))
示例#8
0
    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
示例#9
0
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()
示例#10
0
class Controller:
    def __init__(self):
        self.root = "http://192.168.0.101/api/"
        self.usr = "******"
        self.login = self.root+ self.usr
        self.room = Lights(self.login)

    def get_scene(self, scene):
        filepath = './scenes/'+scene+'.json'

        with open(filepath) as json_file:
            settings = json.load(json_file)
        
        return settings

    def observe_lights(self):
        return self.room.updated_state()
    
    def control(self,scene):
        self.room.turn_on(scene)
示例#11
0
def make_changes(preset, force=False):
    # Better handle this.
    if (os.path.exists('/tmp/pyhueapi.disable') and not force): sys.exit(0)

    lights = Lights()
    for i in preset:
        # print i
        tmp = lights.get(i['id'])

        # print tmp
        if None == tmp: continue

        data = i
        data.pop('id')
        try:
            # tmp._print()
            tmp.bulkSetState(data)
            # tmp._print()
        except Exception, e:
            print "[Utils] Failed: %s" % e.message
            pass
示例#12
0
    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]
示例#13
0
    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)
示例#14
0
    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)
示例#15
0
    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)
示例#16
0
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
示例#17
0
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':
示例#18
0
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()

示例#19
0
 def test_should_read_triggers_from_store(self):
     self.store.read_triggers = MagicMock()
     self.lights = Lights(store=self.store)
     self.store.read_triggers.assert_called_with()
示例#20
0
 def __init__(self, mic):
     self.lights = Lights()
     self.therm = TempMonitor()
     self.door = Door(mic)
示例#21
0
class Dashboard(QWidget):
    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 refresh_lights(self):
        self.lights.refresh()
        self.set_light_on_status()

    def update_time(self):
        now = datetime.now()
        self.ui.set_text('clock-date',
                         f'{pretty_weekday(now)} {pretty_date_only_str(now)}')
        self.ui.set_text('clock-time', pretty_time_str(now))

    def interval(self, fn, ms):
        timer = QTimer(self)
        timer.timeout.connect(fn)
        timer.start(ms)

    def rebuild_weather(self):
        self.weather.refresh()
        self.update_weather_ui()

    def create_lights_ui(self):
        layout = self.ui.by_id('lights-box')

        def create_light_button(l):
            def on_click():
                self.lights.toggle(l['id'])
                self.set_light_on_status()

            button = QPushButton(l['name'])
            self.light_buttons[l['id']] = button
            button.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Expanding)

            button.clicked.connect(on_click)
            layout.addWidget(button)

        lights = self.lights.get_lights()
        if len(lights) is 0:
            self.ui.show('lights-error')
            self.ui.hide('lights-container')
        else:
            self.ui.hide('lights-error')
            self.ui.show('lights-container')

        for light in lights:
            create_light_button(light)

        self.set_light_on_status()

    def set_light_on_status(self):
        for light in self.lights.get_lights():
            button = self.light_buttons[light['id']]
            button.setProperty('light-on', light['on'])
            self.update_widget(button)

    def update_widget(self, widget):
        self.style().unpolish(widget)
        self.style().polish(widget)

    def update_weather_ui(self):
        def set_temp(id, weather_data, temp_attr):
            self.ui.set_text(id, weather_data[f'{temp_attr}-pretty'])
            self.ui.set_stylesheet(
                id, get_temp_color_stylesheet(weather_data[temp_attr]))

        self.ui.set_text('weather-box',
                         f"Weather for {self.weather.get_location_name()}")

        today = self.weather.get_todays_forecast()
        self.ui.set_text('updated-time',
                         f"last updated at {self.weather.get_updated_time()}")

        set_temp('current-temperature', today, 'temp')
        set_temp('today-low', today, 'low')
        set_temp('today-high', today, 'high')
        self.ui.set_text('current-conditions', f"{today['weather']}")
        self.ui.set_icon('current-icon', today['weather-icon'])
        self.connect_forecast_listener('today-details')

        if 'alerts' in today:
            self.ui.show('today-alert')
            alerts = today['alerts']
            self.ui.set_text(
                'today-alert',
                f'{len(alerts)} active alert{"s" if len(alerts) > 1 else ""}')
            self.connect_alert_listener('today-alert', alerts)
        else:
            self.ui.hide('today-alert')

        def set_precip_message(label_id, message):
            if message is not None:
                self.ui.set_text(label_id, message)
                self.ui.show(label_id)
            else:
                self.ui.hide(label_id)

        rain_msg, snow_msg = self.weather.get_upcoming_precip_message()
        set_precip_message('upcoming-rain', rain_msg)
        set_precip_message('upcoming-snow', snow_msg)

        # skip the current day
        for i, day in enumerate(self.weather.get_days()[1:]):
            self.ui.set_text(f'forecast-day-{i}', day['dt-pretty'])
            self.ui.set_text(f'forecast-day-{i}-conditions', day['weather'])
            self.connect_forecast_listener(f'forecast-day-{i}-details', day)
            set_temp(f'forecast-day-{i}-low', day, 'low')
            set_temp(f'forecast-day-{i}-high', day, 'high')
            self.ui.set_icon(f'forecast-day-{i}-icon', day['weather-icon'], 50)

            for precip in ['rain', 'snow']:
                label_id = f'forecast-day-{i}-precip-{precip}'
                set_precip_message(label_id, day[precip])

    def connect_alert_listener(self, id, alerts):
        def show_weather_alert():
            layout = QVBoxLayout()
            for alert in alerts:
                header = QLabel(alert['headline'])
                header.setWordWrap(True)
                header.setProperty('header', True)
                layout.addWidget(header)
                layout.addWidget(QLabel(f"{alert['description']}"))

            box = ScrollMessageBox('Weather Alert', layout)

        self.ui.on_click(id, show_weather_alert)

    def connect_forecast_listener(self, id, day=None):
        def show_forecast():
            periods = self.weather.get_periods_by_day(day)
            # if it's late in the day for the current day, we might not have any more information, show an alert instead
            if periods is None:
                alert = Alert(
                    'No more data',
                    "It is late and there is no more available data for today."
                )
                return

            layout = QHBoxLayout()
            ui = UIBuilder(
                layout, scale_template(periods_detail_template, len(periods)))

            for i, period in enumerate(periods):
                ui.set_text(f'time-{i}', pretty_time_str_short(period['dt']))
                ui.set_icon(f'icon-{i}', period['weather-icon'], 75)

                temp_id = f'temp-{i}'
                ui.set_text(temp_id, period['temp-pretty'])
                ui.by_id(temp_id).setStyleSheet(
                    get_temp_color_stylesheet(period['temp']))
                ui.set_text(f'conditions-{i}', period['weather'])

                def show_precip(precip_type):
                    precip = period[precip_type]
                    precip_id = f'{precip_type}-{i}'
                    if precip is not None:
                        ui.set_text(precip_id, precip)
                    else:
                        ui.hide(precip_id)

                for precip_type in ['rain', 'snow']:
                    show_precip(precip_type)

            pretty_day = day["dt-pretty"] if day is not None else "Today"
            dlg = ScrollMessageBox(f'Weather for {pretty_day}', layout)

        self.ui.on_click(id, show_forecast)
示例#22
0
 def __init__(self, ip):
     Lights.__init__(self, ip)
     self.nations = flags.FRAMES.keys()
     self.send('australia')
示例#23
0
 def ready(self):
     monome.Page.ready(self)
     Lights.ready(self)
示例#24
0
 def setUp(self):
     self.lights = Lights()
示例#25
0
文件: pages.py 项目: seabre/pymonome
 def __init__(self, manager):
     monome.Page.__init__(self, manager)
     Lights.__init__(self)
示例#26
0
 def __init__(self, ip):
     Lights.__init__(self, ip)
     self.nations = flags.FRAMES.keys()
     self.send('australia')
示例#27
0
 def ready(self):
     monome.Section.ready(self)
     Lights.ready(self)
示例#28
0
 def test_Slice(self):
     ws = WS2812(1, 8)
     lights = Lights(ws)
     self.assertEqual(len(lights), 8)
示例#29
0
 def ready(self):
     monome.Page.ready(self)
     Lights.ready(self)
示例#30
0
 def __init__(self, app):
     monome.Page.__init__(self, app)
     Lights.__init__(self)
示例#31
0
    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()
示例#32
0
 def __init__(self, manager):
     monome.Page.__init__(self, manager)
     Lights.__init__(self)
示例#33
0
class LightsSchedulerTest(TestCase):
    def setUp(self):
        self.lights = Lights()

    def test_starts_scheduler(self):
        mock = Mock()

        Lights(scheduler=mock)
        mock.start.assert_called_with()

    def test_add_trigger_to_scheduler(self):
        scheduler = Mock(wraps=BackgroundScheduler())
        lights = Lights(scheduler=scheduler)

        state = True
        hour = 10
        minute = 20
        lights.add_trigger(state, hour, minute)

        scheduler.add_job.assert_called_with(func=ANY, args=[state, "trigger"], end_date=ANY, trigger="cron",
                                             id=None, hour=hour, minute=minute, day_of_week=None)

    def test_add_trigger_to_scheduler_weekday(self):
        scheduler = Mock(wraps=BackgroundScheduler())
        lights = Lights(scheduler=scheduler)

        state = True
        hour = 10
        minute = 20
        repeat_weekday = True
        lights.add_trigger(state, hour, minute, repeat_weekday=repeat_weekday)

        scheduler.add_job.assert_called_with(func=ANY, args=[state, "trigger"], end_date=None, trigger="cron",
                                             id=None, hour=hour, minute=minute, day_of_week=Lights.weekdays)

    def test_add_trigger_to_scheduler_weekend(self):
        scheduler = Mock(wraps=BackgroundScheduler())
        lights = Lights(scheduler=scheduler)

        state = True
        hour = 10
        minute = 20
        repeat_weekend = True
        lights.add_trigger(state, hour, minute, repeat_weekend=repeat_weekend)

        scheduler.add_job.assert_called_with(func=ANY, args=[state, "trigger"], end_date=None, trigger="cron",
                                             id=None, hour=hour, minute=minute, day_of_week=Lights.weekends)

    def test_add_trigger_to_scheduler_all_week(self):
        scheduler = Mock(wraps=BackgroundScheduler())
        lights = Lights(scheduler=scheduler)

        state = True
        hour = 10
        minute = 20
        repeat_weekday = True
        repeat_weekend = True
        lights.add_trigger(state, hour, minute, repeat_weekday, repeat_weekend)

        scheduler.add_job.assert_called_with(func=ANY, args=[state, "trigger"], end_date=None, trigger="cron",
                                             id=None, hour=hour, minute=minute,
                                             day_of_week=Lights.weekdays + "," + Lights.weekends)

    def test_add_trigger_and_get_job(self):
        state = True
        hour = 10
        minute = 20
        self.lights.add_trigger(state, hour, minute)

        jobs = self.lights._scheduler.get_jobs()
        assert_that(jobs, has_length(1))

    def test_add_triggers_and_get_jobs(self):
        num = 5
        for i in range(num):
            self.lights.add_trigger(True, 10, 20)

        jobs = self.lights._scheduler.get_jobs()
        assert_that(jobs, has_length(num))

        triggers = self.lights.get_triggers()
        assert_that(triggers, has_length(num))

    def test_add_and_get_trigger(self):
        state = True
        hour = 10
        minute = 20
        now = int(time())
        self.lights.add_trigger(state, hour, minute)

        job_id = self.lights._scheduler.get_jobs()[0].id
        triggers = self.lights.get_triggers()
        assert_that(triggers, has_length(1))

        trigger = triggers[0]
        assert_that(trigger.job_id, is_(job_id))
        assert_that(trigger.state, is_(state))
        assert_that(trigger.hour, is_(hour))
        assert_that(trigger.minute, is_(minute))
        assert_that(trigger.next_run_time, is_(greater_than(now)))
        assert_that(trigger.repeat_weekday, is_(False))
        assert_that(trigger.repeat_weekend, is_(False))

    def test_add_and_get_trigger_with_update_run_time(self):
        next_run_time = datetime(year=2010, month=1, day=1, tzinfo=utc)
        expected_next_run_time = int(next_run_time.timestamp())

        self.lights.add_trigger(True, 10, 20)
        job_id = self.lights._scheduler.get_jobs()[0].id

        job = Mock()
        job.id = job_id
        job.next_run_time = next_run_time
        self.lights._scheduler.get_jobs = MagicMock(return_value=[job])

        triggers = self.lights.get_triggers()
        assert_that(triggers, has_length(1))

        trigger = triggers[0]
        assert_that(trigger.next_run_time, is_(expected_next_run_time))

    def test_add_no_repeat_has_end_date(self):
        self.lights.add_trigger(True, 10, 20)

        job = self.lights._scheduler.get_jobs()[0]
        assert_that(job.trigger.end_date, is_(not_none()))

    def test_remove_finished_jobs_from_trigger(self):
        self.lights.add_trigger(True, 10, 20)
        self.lights.add_trigger(True, 10, 20)

        jobs = self.lights._scheduler.get_jobs()
        removed_job_id = jobs[0].id
        keep_job_id = jobs[1].id

        self.lights._scheduler.remove_job(removed_job_id)
        jobs = self.lights._scheduler.get_jobs()
        assert_that(jobs, has_length(1))

        triggers = self.lights.get_triggers()
        assert_that(triggers, has_length(1))

        trigger = triggers[0]
        assert_that(trigger.job_id, is_(keep_job_id))

    def test_delete_trigger_from_triggers(self):
        self.lights.add_trigger(True, 10, 20)

        jobs = self.lights._scheduler.get_jobs()
        job_id = jobs[0].id
        triggers = self.lights.get_triggers()
        assert_that(triggers, has_length(1))

        self.lights.remove_trigger(job_id)

        triggers = self.lights.get_triggers()
        assert_that(triggers, is_(empty()))

    def test_delete_job_from_scheduler(self):
        self.lights.add_trigger(True, 10, 20)

        jobs = self.lights._scheduler.get_jobs()
        job_id = jobs[0].id
        assert_that(jobs, has_length(1))

        self.lights.remove_trigger(job_id)

        jobs = self.lights._scheduler.get_jobs()
        assert_that(jobs, is_(empty()))
示例#34
0
    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')
示例#35
0
 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)
        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()))
示例#37
0
 def setUp(self):
     self.store = LightsStoreStub()
     self.lights = Lights(store=self.store)
示例#38
0
        '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
	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()
示例#40
0
class InterfaceManager(object):
    def __init__(self, use_fictrac=True, use_pi=True, use_logging=True):
        self.use_fictrac = use_fictrac
        self.use_pi = use_pi
        self.use_logging = use_logging
        self.running = False
        self.outgoing_interfaces = []

        self.light_input_queue = queue.Queue()
        self.light_output_queue = queue.Queue()

    def _spin_incoming_interface(self):
        if self.use_fictrac:
            self.incoming_interface = FicTracInterface()
        else:
            self.incoming_interface = ReplayInterface()
        self.incoming_interface.connect()

    def _spin_outgoing_interfaces(self):
        if self.use_pi:
            self.outgoing_interfaces.append(RaspberryPiInterface())
        if self.use_logging:
            self.outgoing_interfaces.append(LoggingInterface())

        [interface.connect() for interface in self.outgoing_interfaces]

    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 run_interfaces(self):

        if self.incoming_interface.initialized == False:
            sys.exit()

        self.running = True
        a = time.time()
        try:
            while self.running:
                ret = self.incoming_interface.read()
                output = self.incoming_interface.clean()
                if ret == False:
                    break

                self.light_input_queue.put(
                    [output[i] for i in self.lights.selection_mask])

                self.lights.read_and_wrote.wait()
                updated = self.light_output_queue.get()
                self.lights.reset()

                [
                    interface.write(data)
                    for interface in self.outgoing_interfaces
                ]

        except KeyboardInterrupt:
            sys.exit()

    def safe_shutdown(self):
        light_controller.safe_shutdown()
        motor_controller.safe_shutdown()
        mfc_controller.safe_shutdown()
示例#41
0
from lights import Lights

lights = Lights()

for i in range(100):
    lights.iterate()

print(lights.count_on())
示例#42
0
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())
示例#43
0
 def __init__(self, splitter, size, offset):
     monome.Section.__init__(self, splitter, size, offset)
     Lights.__init__(self)
示例#44
0
#!/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:
示例#45
0
class LightsStateTest(TestCase):
    def setUp(self):
        self.lights = Lights()

    def test_state_starts_as_false(self):
        assert_that(self.lights.get_state(), is_(False))

    def test_set_and_return_state(self):
        self.lights.set_state(True, "test")
        assert_that(self.lights.get_state(), is_(True))

    def test_toggle_flips_state(self):
        assert_that(self.lights.get_state(), is_(False))

        self.lights.toggle("test")
        assert_that(self.lights.get_state(), is_(True))

    def test_set_state_does_not_change_if_less_than_bounce_duration(self):
        self.lights.set_state(True, "test")
        assert_that(self.lights.get_state(), is_(True))

        self.lights.set_state(False, "test")
        assert_that(self.lights.get_state(), is_(True))

    def test_set_state_changes_if_more_than_bounce_duration(self):
        with freeze_time(datetime.now()) as curr_time:
            self.lights.set_state(True, "test")
            assert_that(self.lights.get_state(), is_(True))

            curr_time.tick(delta=timedelta(seconds=90))

            self.lights.set_state(False, "test")
            assert_that(self.lights.get_state(), is_(False))

    def test_toggle_does_not_change_if_less_than_bounce_duration(self):
        self.lights.toggle("test")
        assert_that(self.lights.get_state(), is_(True))

        self.lights.toggle("test")
        assert_that(self.lights.get_state(), is_(True))

    def test_toggle_changes_if_more_than_bounce_duration(self):
        with freeze_time(datetime.now()) as curr_time:
            self.lights.toggle("test")
            assert_that(self.lights.get_state(), is_(True))

            curr_time.tick(delta=timedelta(seconds=90))

            self.lights.toggle("test")
            assert_that(self.lights.get_state(), is_(False))