def test_denormalize_brightness() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight._denormalize_brightness(100) == 255 assert backlight._denormalize_brightness(50) == 128 assert backlight._denormalize_brightness(0) == 0
def test_constructor() -> None: with pytest.raises(TypeError): Backlight(board_type="foo") # type: ignore[arg-type] assert not _EMULATOR_SYSFS_TMP_FILE_PATH.exists() with pytest.raises(RuntimeError): Backlight(backlight_sysfs_path=":emulator:")
def __init__(self, rootPath): super().__init__() self.rootPath = rootPath self.__server = WebSocketServer(self) self.__server.start() self.__relay = PyRelay() self.__temp = PyTemp() self.__temp self.__temp.start() self.__stats_tab_index = 0 self.__buttons_tab_index = 1 self.enable_gui_switch = True self.timer = QTimer() self.timer.timeout.connect(self.__timer_tick) try: self.backlight = Backlight() except: self.fakeBacklightSysfs = FakeBacklightSysfs() self.fakeBacklightSysfs.__enter__() self.backlight = Backlight( backlight_sysfs_path=self.fakeBacklightSysfs.path) self.initUI() self.enable_screensaver()
def test_set_value() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight._set_value( "brightness", 0) is None # type: ignore[func-returns-value] assert backlight._get_value("brightness") == 0
def test_normalize_brightness() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight._normalize_brightness(255) == 100 assert backlight._normalize_brightness(128) == 50 assert backlight._normalize_brightness(0) == 0
def set_brighness_level(self, level): """ Change screen brightness to value givin as parameter """ backlight = Backlight() backlight.brightness = level
async def resolve(self): sysfs_path = self.request_context.config.backlight_sysfs_path if not sysfs_path: return False backlight = Backlight(sysfs_path) with backlight.fade(self.args.fade_duration or 0): backlight.brightness = self.args.brightness return True
def test_fade() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight.fade_duration == 0 backlight.fade_duration = 0.1 assert backlight.fade_duration == 0.1 with backlight.fade(duration=0.5) as _val: assert _val is None assert backlight.fade_duration == 0.5 assert backlight.fade_duration == 0.1
def decrease_brightness(self, start_hour, finish_hour): print('start hour {}'.format(start_hour), flush=True) print('finish hour {}'.format(finish_hour), flush=True) print('decreasing brightness', flush=True) if finish_hour > start_hour: bl = Backlight() is_on = bl.power diff = finish_hour - start_hour half_hour_diff = diff * 2 if is_on: print('is on', flush=True) brightness = 50 for x in range(half_hour_diff): print('brightness at {}'.format(brightness), flush=True) if brightness < 10: bl.power = False # turn off the display else: if brightness == 10: brightness = 11 # 11 is the min brightness with bl.fade(duration=3): bl.brightness = brightness # bl.set_brightness(brightness, smooth=True, duration=3) brightness = brightness - 10 print('sleeping 30 minutes...', flush=True) time.sleep(60 * 30) elif finish_hour == start_hour: bl = Backlight() bl.power = False else: raise Exception( 'the finish hour should be bigger than the start hour')
async def _control(self): config = self._config.auto_backlight backlight = Backlight(self._config.backlight_sysfs_path) i2c = busio.I2C(board.SCL, board.SDA) veml7700 = adafruit_veml7700.VEML7700(i2c) backlight.fade_duration = config.fade_duration while True: light = veml7700.light rel_light = min(1, light / config.light_max) brightness = round(exponential_ease_out(min(1, rel_light)) * 100) limited_brightness = max(config.brightness_min, brightness) backlight.brightness = limited_brightness logger.debug("light: %s, rel_light: %s, brightness: %s, limited_brightness: %s", light, rel_light, brightness, limited_brightness) await asyncio.sleep(config.refresh)
def __init__(self, config_path): # Load the configuration. self._config = configparser.ConfigParser() if len(self._config.read(config_path)) == 0: raise RuntimeError( 'Failed to find configuration file at {0}, is the application properly installed?' .format(config_path)) self._mqttbroker = self._config.get('mqtt', 'broker') self._mqttuser = self._config.get('mqtt', 'user') self._mqttpassword = self._config.get('mqtt', 'password') self._mqttconnectedflag = False self._mqtt_state_topic = self._config.get('mqtt', 'state_topic') self._mqtt_command_topic = self._config.get('mqtt', 'command_topic') self._mqtt_brightness_state_topic = self._config.get( 'mqtt', 'brightness_state_topic') self._mqtt_brightness_command_topic = self._config.get( 'mqtt', 'brightness_command_topic') self._mqtt_clientid = self._config.get('mqtt', 'clientid') self._console_output = self._config.getboolean('misc', 'debug') # initalise backlight object try: self._backlight = Backlight() self._backlight.fade_duration = self._config.getfloat( 'backlight', 'fade_duration') except: self._print( "Could not initialise backlight component. Are you running this on a RPi?" ) exit(1)
def main_app(self): while True: try: bl = Backlight() now = pendulum.now() print('Current time is {0}'.format( now.to_day_datetime_string()), flush=True) difference = now.diff(self.last_check, False).in_hours() if difference > 10: self.check_for_sunset_sunrise(day=now) hour = now.hour seconds_to_sleep = 600 if self.wake_time is not None and self.sleep_time is not None: if (now > self.wake_time) and (now < self.sleep_time): print('It\'s time to wake up!', flush=True) bl.power = True bl.brightness = 50 # lets always sleep 10 minutes instead # seconds_to_sleep = self.calculate_sleep_time_in_seconds(now_time=now, later_time=self.sleep_time) print('program sleeping for {0} minutes'.format( seconds_to_sleep / 60), flush=True) elif now >= self.sleep_time: print('Night time!', flush=True) self.decrease_brightness(hour, 22) # we check for tomorrow instead of today self.check_for_sunset_sunrise(day=now.add(days=1)) # lets always sleep 10 minutes instead # seconds_to_sleep = self.calculate_sleep_time_in_seconds(now_time=now, later_time=self.wake_time) print('Sleeping {0} seconds'.format(seconds_to_sleep), flush=True) time.sleep(seconds_to_sleep) else: # re initialize because times are NONE self.check_for_sunset_sunrise(day=now) except Exception as e: print('Error running main_app : {0}'.format(e))
def __init__(self): self.contador = 0 self.th1 = Thread(target=self.reader) self.th2 = Thread(target=self.counter) self.th1.start() self.th2.start() self.mut = Semaphore(1) self.back = Backlight()
async def resolve(self): sysfs_path = self.request_context.config.backlight_sysfs_path if not sysfs_path: return 0 backlight = Backlight(sysfs_path) return backlight.brightness
def _set_brightness(self, brightness): try: disp_type = self._display_type if self._runtime_system.is_target_system: if disp_type == DISP_TYPE_WAVESHARE_5_LCD: pwm_val = brightness * 10 # actually 1023 is max pin = self._waveshare_brightness_pin os.system("gpio -g pwm " + str(pin) + " " + str(pwm_val)) elif disp_type == DISP_TYPE_RPI: backlight = Backlight() backlight.fade_duration = 0.5 backlight.brightness = brightness else: os.system("vcgencmd display_power 0") # save set value self._brightness = brightness except Exception as error: self._logger.error( "Display: Cannot set display brightness to %i: %s", brightness, str(error))
def __init__(self, backlight_sysfs_path: Path) -> None: QMainWindow.__init__(self) self.backlight = Backlight(backlight_sysfs_path) self.screenshot = QPixmap(get_image_path("raspbian.png")) self.image_display_on = load_display_image( get_image_path("display_on.png")) self.image_display_off = load_display_image( get_image_path("display_off.png")) widget = QWidget() checkbox_layout = QBoxLayout(QBoxLayout.LeftToRight) main_layout = QBoxLayout(QBoxLayout.TopToBottom) brightness_slider_label = QLabel("Brightness", widget) self.live_screen_checkbox = QCheckBox("Show live screen", widget) self.live_screen_checkbox.stateChanged.connect(self.update_screen) self.power_checkbox = QCheckBox("Power", widget) self.power_checkbox.stateChanged.connect(self.write_power_change) self.brightness_slider = QSlider(Qt.Horizontal, widget) self.brightness_slider.valueChanged.connect( self.write_brightness_change) self.brightness_slider.setSingleStep(1) self.brightness_slider.setMinimum(0) self.brightness_slider.setMaximum(100) self.screen_image = QLabel() checkbox_layout.addWidget(self.power_checkbox) checkbox_layout.addWidget(self.live_screen_checkbox) main_layout.addLayout(checkbox_layout) main_layout.addWidget(brightness_slider_label) main_layout.addWidget(self.brightness_slider) main_layout.addWidget(self.screen_image) widget.setLayout(main_layout) self.thread = FileWatcherThread(self, backlight_sysfs_path) self.thread.file_changed.connect(self.update_widgets) self.thread.start() self.timer = QTimer(self) self.timer.setInterval(100) self.timer.timeout.connect(self.update_screen) self.timer.start() self.update_widgets("bl_power") self.update_widgets("brightness") self.setCentralWidget(widget) self.setWindowTitle('Raspberry Pi 7" display backlight emulator') self.setWindowIcon(QIcon(get_image_path("icon.png")))
def test_set_brightness() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) backlight.brightness = 50 assert backlight.brightness == 50 backlight.brightness = 0 assert backlight.brightness == 0 with pytest.raises(TypeError): backlight.brightness = "foo" with pytest.raises(TypeError): backlight.brightness = True with pytest.raises(ValueError): backlight.brightness = 101 with pytest.raises(ValueError): backlight.brightness = -1
def test_set_fade_duration() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) backlight.fade_duration = 0.5 assert backlight.fade_duration == 0.5 backlight.fade_duration = 1 assert backlight.fade_duration == 1 with pytest.raises(ValueError): backlight.fade_duration = -1 with pytest.raises(TypeError): backlight.fade_duration = "foo" with pytest.raises(TypeError): backlight.fade_duration = True
def test_set_power() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) backlight.power = False assert backlight.power is False backlight.power = True assert backlight.power is True with pytest.raises(TypeError): backlight.power = "foo" with pytest.raises(TypeError): backlight.power = 1
def fadeTo(brightPercent, durationSeconds): backlight = Backlight() with backlight.fade(duration=durationSeconds): backlight.brightness = brightPercent
def openSettings(): global settingsWindow global brightnessSlider global roomIdString global roomId global urlLabel settingsWindow = tk.Tk() settingsWindow.attributes("-fullscreen", True) settingsWindow.configure(bg="black") settingsWindow.columnconfigure(0, weight=3) settingsWindow.columnconfigure(1, weight=9) settingsWindow.columnconfigure(2, weight=4) settingsWindow.rowconfigure((0, 1, 2, 3, 4, 5, 6, 7), weight=1) brightnessLabel = tk.Label(settingsWindow, bg="black", fg="white", font=mediumFontBold, text="Brightness") brightnessLabel.grid(row=2, column=0) brightnessSlider = tk.Scale(settingsWindow, from_=5, to=100, orient=tk.HORIZONTAL, fg=blue, bg="black", bd=0, highlightthickness=0, font=smallFont, width=40, sliderrelief=tk.FLAT, highlightcolor=blue, command=changeBrightness) brightnessSlider.set(Backlight().brightness) brightnessSlider.grid(row=2, column=1, padx=10, sticky="NSEW") roomLabel = tk.Label(settingsWindow, font=mediumFontBold, fg="white", bg="black", text="Room ID") roomLabel.grid(row=4, column=0) roomIdString = tk.StringVar() roomId = tk.Entry(settingsWindow, font=mediumFontBold, textvariable=roomIdString) roomId.grid(row=4, column=1, sticky="EW", padx=10) urlLabel = tk.Label(settingsWindow, bg="black", fg="white", font=smallFont) urlLabel.grid(row=6, column=0, columnspan=2) updateRoomId() setBtn = tk.Button(settingsWindow, text="Set", bg=green, activebackground=green, fg="black", relief=tk.FLAT, font=mediumFont, command=setRoomId) setBtn.grid(row=5, column=1) backBtn = tk.Button(settingsWindow, text="Back", bg=green, activebackground=green, relief=tk.FLAT, font=mediumFont, command=back) backBtn.grid(row=0, column=0, sticky="NW") updateBtn = tk.Button(settingsWindow, text="Update", bg=purple, activebackground=purple, relief=tk.FLAT, font=largeFont, command=update) updateBtn.grid(row=0, column=2, rowspan=2, sticky="NSEW") rebootBtn = tk.Button(settingsWindow, text="Reboot", bg=red, activebackground=red, relief=tk.FLAT, font=largeFont, command=reboot) rebootBtn.grid(row=6, column=2, rowspan=2, sticky="NSEW") shutDownBtn = tk.Button(settingsWindow, text="Shut Down", bg=red, activebackground=red, relief=tk.FLAT, font=largeFont, command=shutDown) shutDownBtn.grid(row=4, column=2, rowspan=2, sticky="NSEW") quitBtn = tk.Button(settingsWindow, text="Quit", bg=red, activebackground=red, relief=tk.FLAT, font=largeFont, command=close) quitBtn.grid(row=2, column=2, rowspan=2, sticky="NSEW") settingsWindow.mainloop()
def test_get_power() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight.power is True
def test_get_fade_duration() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight.fade_duration == 0
def test_get_brightness() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight.brightness == 100
import socket from rpi_backlight import Backlight backlight = Backlight() UDP_IP = '' UDP_PORT = 50007 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind((UDP_IP, UDP_PORT)) while True: data, addr = sock.recvfrom(1024) if data == b'display_on': backlight.power = True if data == b'display_off': backlight.power = False if data == b'display_low': backlight.brightness = 10 oder 25 if data == b'display_medium': backlight.brightness = 30 oder 50 if data == b'display_high': backlight.brightness = 100 oder 75
def __init__(self, cfg: dict) -> None: super().__init__() bell_config = MqttStringConfig(**cfg['bell']) door_list = [] for door, d_cfg in cfg['doors'].items(): print(f"new_door: {door}") new_door = Door(door_id=door, name=d_cfg['name'], command_topic=d_cfg['command_topic'], state_topic=d_cfg['state_topic']) # new_door.set_relay() door_list.append(new_door) doors_config = DoorsConfig(doors=door_list) print(cfg['garage']) garage_config = MqttStringConfig(**cfg['garage']) mode_config = MqttStringConfig(**cfg['mode']) self.kelvin = kelvin_rgb_to_kivy() self.azure = get_color_from_hex('#f0ffff') self.theme_cls = ThemeManager() self.theme_cls.primary_palette = "Blue" self.theme_cls.primary_hue = "500" self.theme_cls.accent_palette = "Yellow" self.theme_cls.accent_palette_hue = "500" self.theme_cls.theme_style = "Light" self.doors_config = doors_config self.bell_config = bell_config self.garage_config = garage_config self.mode_config = mode_config self.backlight = Backlight() ## GUI ## self.gui = ScreenManager(transition=NoTransition()) try: self.screens = config.screens except AttributeError: self.screens = None else: for screen in self.screens: print(f'New screen: {screen}') try: import_statemet = self.screens[screen][ "import"] + ' as NewScreen' print(import_statemet) exec(import_statemet) except Exception as e: print(e) else: screen_kwargs = {} screen_kwargs.update({'name': screen}) # screen_kwargs.update({'controller':self}) # screen_kwargs.update({'sub':self.screens[screen].get("sub", None)}) # screen_kwargs.update({'memory':kwargs.get(screen,None)}) print(f'SCREEN NAME IS: {screen}') print(f'with kwargs: {screen_kwargs}') self.screens[screen]["object"] = eval('NewScreen')( **screen_kwargs) self.gui.add_widget(self.screens[screen]["object"]) self.change_screen(self.gui.screen_names[0])
def __init__(self): logger.debug('Initializing Backlight()') self.backlight = Backlight() logger.info('Backlight starting brightness is %d', self.backlight.brightness)
def changeBrightness(event): brightness = brightnessSlider.get() Backlight().brightness = brightness
import glob import sys from ft5406 import Touchscreen, TS_PRESS, TS_RELEASE, TS_MOVE from math import floor from subprocess import call from subprocess import check_output import subprocess as SP from rpi_backlight import Backlight screenState = "/home/pi/pi-tablet_retropie/assets/currentDisplayMode" PNGVIEWPATH = "/home/pi/pi-tablet_retropie/assets/pngview/" ICONPATH = "/home/pi/pi-tablet_retropie/assets/icons" brightLast = "" volumeLast = "" layerList = [] backlight = Backlight() def read_and_emulate_mouse(event, touch): global startX global startY global startTime global shouldRun global brightLast global volumeLast global killid global layerList if event == TS_RELEASE: os.system("sudo kill " + "$(ps aux | grep '[p]ngview' | awk '{print $2}')") layerList = []
def test_set_value() -> None: with FakeBacklightSysfs() as backlight_sysfs: backlight = Backlight(backlight_sysfs_path=backlight_sysfs.path) assert backlight._set_value("brightness", 0) is None assert backlight._get_value("brightness") == 0