Пример #1
0
 def connect(self):
     if self.connection_failed or self.is_connected:
         return
     try:
         self.client = OpenRGBClient(port=self.port)
         self.device = self.client.get_devices_by_type(self.device_type)[0]
         self.led_names = [
             self.device.data.leds[x].name
             for x in range(len(self.device.data.leds))
         ]
         self.is_connected = True
         self.vim.vars['openrgb_led_names'] = self.led_names
     except:
         self.connection_failed = True
         self.vim.vars['openrgb_connection_failed'] = True
         self.vim.command(
             'echom "[vim-openrgb] cannot connect to openrgb server"')
Пример #2
0
def initRGB():
    global keyb
    global cli
    global keyboard_leds
    global keyboard_zone
    global led_count
    cli = OpenRGBClient()
    print(cli)
    keyb = cli.get_devices_by_type(DeviceType.KEYBOARD)[0]
    print(keyb)
    keyb.set_mode('direct')
    keyboard_leds = keyb.zones[0].leds
    led_count = len(keyboard_leds)
    keyboard_zone = keyb.zones[0]
    print(f'Keyboard Zone Type: {keyboard_zone.type}')
    #assert keyboard_zone.type == ZoneType.LINEAR
    return keyboard_leds
Пример #3
0
def _try_connect(_host, _port, _client_id):
    """Check if we can connect."""
    try:
        conn = OpenRGBClient(_host, _port, name=_client_id)
        conn.comms.stop_connection()
    except OSError as exc:
        raise CannotConnect from exc

    return True
Пример #4
0
class Backend():
    def __init__(self, settings : dict):
        ip = "127.0.0.1"
        port = 6742
        retry_sleep = 5
        retries = 3
        if settings:
            ip = settings.get("ip_address", ip)
            port = settings.get("port", port)
            retry_sleep = settings.get("retry_sleep", retry_sleep)
            retries = settings.get("retries", retries)
        logger.info("Using OpenRGB backend at {}:{}".format(ip, port))
        while not hasattr(self, "client") and retries > 0:
            try:
                logger.debug("Trying to connect to OpenRGB server")
                self.client = OpenRGBClient(ip, port, name="RGBmon")
            except ConnectionRefusedError as e:
                logger.warning("Could not connect to OpenRGB server: {}".format(e))
                retries -= 1
                if not retries > 0:
                    raise
                time.sleep(retry_sleep)


    def get_led_list(self, config : dict) -> List[openrgb.orgb.LED]:
        led_config = config["leds"]
        led_list = []
        logger.debug("Retrieving led list from OpenRGB backend")
        for led_entry in led_config:
            device_type = get_device_type(led_entry["type"])
            devices = self.client.get_devices_by_type(DeviceType(device_type))

            device_list = list(map(create_device, range(len(devices))))
            if "devices" in led_entry:
                device_list = led_entry["devices"]
            for device in device_list:
                # Get the device
                device_id = device["id"]
                orgb_device = devices[device_id]

                # Set the target mode
                orgb_device.set_mode(led_entry["mode"])

                # Check if it requires specific zones and add LEDs
                if "zones" in device:
                    for zone_id in device["zones"]:
                        led_list.extend(reversed(orgb_device.zones[zone_id].leds))
                else:
                    led_list.extend(reversed(orgb_device.leds))
        if not led_list:
            logger.warning("Could not find any LEDs for backend request.")
        return led_list

    def apply(self, leds_colors : List[Tuple[int, openrgb.orgb.LED]]):
        for led, color in leds_colors:
            r, g, b = color
            led.set_color(RGBColor(r, g, b), fast=True)
Пример #5
0
def initRGB():
    # Getting this script ready to be run as a service. Waiting for the sdk to start.
    while True:
        try:
            print("trying to connect")
            cli = OpenRGBClient()
            break
        except ConnectionRefusedError:
            sleep(5)
            continue
    try:
        cooler = cli.get_devices_by_type(DeviceType.COOLER)[0]
    except IndexError:
        cooler = False
    try:
        gpu = cli.get_devices_by_type(DeviceType.GPU)[0]
    except IndexError:
        gpu = False
    # right_ram, left_ram = cli.get_devices_by_type(DeviceType.DRAM)

    # right_ram.clear()
    # left_ram.clear()


    # To make sure the devices are in the right mode, and to work around a problem
    #   where the gpu won't change colors until switched out of static mode and
    #   then back into static mode.
    if cooler:
        cooler.set_mode(0)  # Direct mode
    if gpu:
        gpu.set_mode(1)  # Anything would work, this is breathing in my setup
        sleep(.1)
        gpu.set_mode(0)  # Static mode.  My GPU doesn't have a direct mode.
        try:
            nvmlInit()
            handle = nvmlDeviceGetHandleByIndex(0)
        except:
            gpu, handle = False, False
    else:
        handle = False
    return cooler, gpu, handle
Пример #6
0
 def __init__(self, settings : dict):
     ip = "127.0.0.1"
     port = 6742
     retry_sleep = 5
     retries = 3
     if settings:
         ip = settings.get("ip_address", ip)
         port = settings.get("port", port)
         retry_sleep = settings.get("retry_sleep", retry_sleep)
         retries = settings.get("retries", retries)
     logger.info("Using OpenRGB backend at {}:{}".format(ip, port))
     while not hasattr(self, "client") and retries > 0:
         try:
             logger.debug("Trying to connect to OpenRGB server")
             self.client = OpenRGBClient(ip, port, name="RGBmon")
         except ConnectionRefusedError as e:
             logger.warning("Could not connect to OpenRGB server: {}".format(e))
             retries -= 1
             if not retries > 0:
                 raise
             time.sleep(retry_sleep)
Пример #7
0
#//////////////////////////////////////////////////////////////////////////////////////////////////////////
# GLOBAL DEFINES
#//////////////////////////////////////////////////////////////////////////////////////////////////////////
#HEIGHT         = 1920   #now using image.size[1] dynamically
#WIDTH          = 1200   #now using image.size[0] dynamically
LOOP_INTERVAL = 0.05  # how often we calculate screen colour (in seconds)
DURATION = 3  # how long it takes bulb to switch colours (in seconds)
DECIMATE = 100  # sample only 1% of pixels to speed up
K_MEANS = 3  # number of clusters to calculate (returns average color if 1 and dominant color if >1)

XSCREENCAPTURE = True  # Set to true if on X11, else false
X_RES = 2560  # Screen pixel in x direction
Y_RES = 1440  # screen pixel in y direction

client = OpenRGBClient(
)  #will only work if you use default ip/port for OpenRGB server. This is an easy fix, read the documentation if need be https://openrgb-python.readthedocs.io/en/latest/

Dlist = client.devices

if XSCREENCAPTURE:
    # Use X11 display manager for screen capture
    import ctypes
    from PIL import Image
    LibName = 'prtscn.so'  # has to be compiled previously from prtscrn.c
    AbsLibPath = os.getcwd(
    ) + os.path.sep + LibName  # assuming prtscrn.so lives in the same dir
    grab = ctypes.CDLL(AbsLibPath)

    def grab_screen(x1, y1, x2, y2):
        w, h = x2 - x1, y2 - y1
        size = w * h
Пример #8
0
#!/usr/bin/env python3

# Happy belated 4th of July!

from openrgb import OpenRGBClient
from openrgb.utils import RGBColor
from time import sleep

cli = OpenRGBClient()

offsets = [(0, 1, 2), (1, 2, 0), (2, 0, 1)]

while True:
    for offset in offsets:
        for device in cli.devices:
            # Setting every third color red
            for x in range(offset[0], len(device.colors), 3):
                device.colors[x] = RGBColor(255, 0, 0)
            # Setting every third color white
            for x in range(offset[1], len(device.colors), 3):
                device.colors[x] = RGBColor(255, 255, 255)
            # Setting every third color blue
            for x in range(offset[2], len(device.colors), 3):
                device.colors[x] = RGBColor(0, 0, 255)
        cli.show()  # Updates all devices
        sleep(.5)
Пример #9
0
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor, DeviceType
import sys

client = OpenRGBClient()

ram = client.get_devices_by_name('corsair', False)

for r in ram:
    r.set_mode("static")

def setAll(color):
    for d in client.devices:
        d.set_color(color)

c = input("")
def num(s):
    try:
        return int(s)
    except ValueError:
        try:
            return float(s)
        except ValueError:
            return None

while c != "quit":
    cs = c.split()
    if cs[0] == "set_all":
        rgb = cs[1].split(",")
        try:
            setAll(RGBColor(num(rgb[0]), num(rgb[1]), num(rgb[2])))
Пример #10
0
    #print(str(current_temp))

#def on_message(client, userdata, message):
#    print("Received message '" + str(message.payload) + "' on topic '"
#        + message.topic + "' with QoS " + str(message.qos))

def on_connect(client, userdata, flags, rc):
    print("Connection Status: " + str(rc))
    mclnt.subscribe("hah/#")
    mclnt.message_callback_add("hah/set_temperature", set_temp)
    mclnt.message_callback_add("hah/temperature", update_temp)
    mclnt.publish('hah/heater_state', payload="OFF")
    

mclnt = mqtt.Client(client_id="")
orgbclnt = OpenRGBClient('localhost', 6742, 'Heating at Home Client')
orgbclnt.clear()

#mclnt.on_message = on_message
mclnt.on_connect = on_connect

mclnt.connect(BROKER_HOST, BROKER_PORT)
mclnt.loop_start()


while(True):
    if heating == True:
        print("Heating On. Current Temp: " + str(current_temp) + " Temperature Setting: " + str(temp_setting))
        if current_temp > (temp_setting + 1):
            heating = False
            for device in orgbclnt.devices:
Пример #11
0
class OpenRGBNvim(object):
    """interface with OpenRGB"""
    def __init__(self, vim):
        self.vim = vim
        self.port = 6742
        self.device_type = DeviceType.KEYBOARD
        self.is_connected = False
        self.connection_failed = False
        self.led_names = []
        self.prev_vim_mode = ''
        self.th_cnt = 0
        # vim variables
        self.vim.vars['openrgb_connection_failed'] = False
        self.vim.vars['openrgb_led_names'] = []
        self.mode_dict = self.vim.vars['openrgb_mode_dict']

    def vim_color_to_rgb(self, vim_color):
        r = eval("0x" + vim_color[1:3])
        g = eval("0x" + vim_color[3:5])
        b = eval("0x" + vim_color[5:7])
        return (r, g, b)

    def vim_color_to_rgb_color(self, vim_color):
        return RGBColor(*self.vim_color_to_rgb(vim_color))

    def get_complementary_rgb_colors(self, vim_color, nb_colors):
        crgbs = []
        (r, g, b) = self.vim_color_to_rgb(vim_color)
        (h, s, v) = colorsys.rgb_to_hsv(r, g, b)
        cs = max(s, 0.7)
        cv = max(v, 128)
        for i in range(nb_colors):
            j = i - 1
            if j < 0:
                delta = 0
            else:
                h_step = 0.25 / (nb_colors // 2)
                sign = (-1, 1)[j % 2]
                delta = sign * ((j // 2) + 1) * h_step
            ch = (h + 0.5 + delta) % 1.0
            (cr, cg, cb) = (int(x) for x in colorsys.hsv_to_rgb(ch, cs, cv))
            crgbs.append(RGBColor(cr, cg, cb))
        return crgbs

    def led_names_to_ids(self, names):
        ids = []
        for name in names:
            ids.append(self.led_names.index(name))
        return ids

    def connect(self):
        if self.connection_failed or self.is_connected:
            return
        try:
            self.client = OpenRGBClient(port=self.port)
            self.device = self.client.get_devices_by_type(self.device_type)[0]
            self.led_names = [
                self.device.data.leds[x].name
                for x in range(len(self.device.data.leds))
            ]
            self.is_connected = True
            self.vim.vars['openrgb_led_names'] = self.led_names
        except:
            self.connection_failed = True
            self.vim.vars['openrgb_connection_failed'] = True
            self.vim.command(
                'echom "[vim-openrgb] cannot connect to openrgb server"')

    @pynvim.function('OpenRGBSync', sync=True)
    def sync(self, args):
        pass

    @pynvim.function('OpenRGBChangeColor')
    def change_color(self, args):
        self.th_cnt += 1
        my_th_cnt = self.th_cnt
        vim_color = args[0]
        led_names = args[1] if len(args) > 1 else [[]]
        led_vim_colors = args[2] if len(args) > 2 else []
        force = args[3] if len(args) > 3 else False
        # fill led_rgb_colors
        led_rgb_colors = []
        if len(led_names):
            if len(led_vim_colors):
                led_rgb_colors = [
                    self.vim_color_to_rgb_color(vim_color)
                    for vim_color in led_vim_colors
                ]
            else:
                # choose led_rgb_colors automatically
                led_rgb_colors = self.get_complementary_rgb_colors(
                    vim_color, len(led_names))
        self.connect()
        if self.is_connected:
            # main color
            rgb_color = self.vim_color_to_rgb_color(vim_color)
            for c in range(len(self.device.colors)):
                self.device.colors[c] = rgb_color
            # led colors
            for i, rgb_color in enumerate(led_rgb_colors):
                for c in self.led_names_to_ids(led_names[i]):
                    self.device.colors[c] = rgb_color
            # show only most recent thread
            if my_th_cnt >= self.th_cnt:
                self.device.show(fast=True, force=force)
        self.th_cnt -= 1

    @pynvim.function('OpenRGBChangeColorFromMode')
    def change_color_from_mode(self, args):
        vim_mode = args[0]
        force = args[1] if len(args) > 1 else False
        if not force and vim_mode == self.prev_vim_mode:
            return
        self.prev_vim_mode = vim_mode
        d = self.mode_dict.get(vim_mode, self.mode_dict['default'])
        self.change_color(
            [d['main_color'], d['led_names'], d['led_colors'], force])
Пример #12
0
def loop(interval: float, mod_aura: int):
    """
    Sets cooler color in a loop. Takes time of day and CPU temperature into account.
    :param interval: Time between cycles in seconds.
    :param mod_aura: How many kraken cycles pass between each aura cycle.
    :return:
    """
    # init sensors
    sensors.init()

    # init openrgb client
    client = OpenRGBClient()
    kraken = client.get_devices_by_type(
        DeviceType.LEDSTRIP)[0]  # weird type for a COOLER, I know
    ring = kraken.zones[1]
    logo = kraken.zones[2]
    aura = client.get_devices_by_type(DeviceType.MOTHERBOARD)[0]
    aura.zones[1].resize(120)

    # count kraken cycles
    count = 0

    while True:
        # calculate ring color based on CPU temperature
        ring_hex_color = get_color()
        r, g, b = hex_to_rgb(ring_hex_color)

        # calculate brightness
        brightness = get_kraken_brightness()

        # apply brightness
        r *= brightness
        g *= brightness
        b *= brightness

        # round to int
        r, g, b = validate_color(r, g, b)

        # set kraken ring color
        ring.set_color(RGBColor(r, g, b))

        # read logo color
        logo_hex_color = KRAKEN_LOGO_COLOR
        r, g, b = hex_to_rgb(logo_hex_color)

        # calculate logo brightness
        brightness = get_kraken_brightness()

        # apply brightness
        r *= brightness
        g *= brightness
        b *= brightness

        # round to int
        r, g, b = validate_color(r, g, b)

        # set logo color
        logo.set_color(RGBColor(r, g, b))

        # set aura color if needed
        if count % mod_aura == 0:
            set_aura_color(aura)
            count = 0

        # sleep for a predefined amount of time
        if interval < 0:
            return
        time.sleep(interval)
        count += 1
Пример #13
0
from flask import Flask
from flask_restful import Resource, Api, reqparse
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor
import dataclasses

app = Flask(__name__)
api = Api(app)
cli = OpenRGBClient(name="openrgb-rest")

parser = reqparse.RequestParser()
parser.add_argument('red', type=int)
parser.add_argument('green', type=int)
parser.add_argument('blue', type=int)
parser.add_argument('mode', type=int)


class Device(Resource):
    def get(self, device_id: int = -1):
        if device_id == -1:
            return [dataclasses.asdict(dev.data) for dev in cli.devices]
        else:
            return dataclasses.asdict(cli.devices[device_id].data)

    def put(self, device_id: int = -1):
        args = parser.parse_args()
        if device_id == -1:
            if any(c is None
                   for c in (args['red'], args['blue'], args['green'])):
                return args, 400
            cli.set_color(RGBColor(args['red'], args['green'], args['blue']))
Пример #14
0
#!/usr/bin/env python3
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor, DeviceType
import sensors
from time import sleep
from py3nvml.py3nvml import nvmlInit, nvmlDeviceGetHandleByIndex, nvmlDeviceGetTemperature, NVML_TEMPERATURE_GPU
# import psutil

cli = OpenRGBClient()
nvmlInit()

cooler = cli.get_devices_by_type(DeviceType.DEVICE_TYPE_COOLER)[0]
gpu = cli.get_devices_by_type(DeviceType.DEVICE_TYPE_GPU)[0]
# right_ram, left_ram = cli.get_devices_by_type(DeviceType.DEVICE_TYPE_DRAM)

handle = nvmlDeviceGetHandleByIndex(0)


def temp_to_color(temp: int) -> (int, int):
    if temp < 40:
        return 0, 255
    elif temp < 70:
        return int((temp - 40) * 8), int((70 - temp) * 8)
    elif temp >= 70:
        return 255, 0


# right_ram.clear()
# left_ram.clear()

try:
Пример #15
0
#!/usr/bin/env python3
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor
import time

client = OpenRGBClient()

print(client)

print(client.devices)

client.off()

while True:
    for x in range(360):
        client.set_color(RGBColor.fromHSV(x, 100, 100), fast=True)
        time.sleep(.05)
Пример #16
0

def setMode(devices: list[Device], mode: str):
    for device in devices:
        device.set_mode(mode)


def setColor(devices: list[Device], color: RGBColor):
    for device in devices:
        device.set_color(color)


if len(sys.argv) < 2:
    sys.exit(1)

client = OpenRGBClient()
dram = client.get_devices_by_type(DeviceType.DRAM)
mobo_led = client.get_devices_by_type(DeviceType.MOTHERBOARD)

if sys.argv[1] == "off":
    setMode(dram, "off")
    setMode(mobo_led, "off")
elif sys.argv[1] == "on":
    setMode(dram, "rainbow")
    setMode(mobo_led, "rainbow")
elif sys.argv[1] == "dim":
    color = RGBColor(75, 10, 140)
    setMode(dram, "breathing")
    setMode(mobo_led, "direct")
    setColor(dram, color)
    setColor(mobo_led, color)
Пример #17
0
#!/usr/bin/env python3
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor, DeviceType, ZoneType
from time import sleep

cli = OpenRGBClient()

keyboard = cli.get_devices_by_type(DeviceType.KEYBOARD)[0]
keys_zone = [z for z in keyboard.zones if z.type == ZoneType.MATRIX][0]

while True:
    for color in (RGBColor(255, 0, 0), RGBColor(0, 255, 0), RGBColor(0, 0, 255), RGBColor(0, 0, 0)):
        for x in range(len(keys_zone.leds)):
            keys_zone.set_color(color, end=(x + 1))
            sleep(.3)
# -*- coding: utf-8 -*-
"""
Created on Fri Apr  8 01:25:06 2022

@author: Bharath
"""

from Asus_argb_ambient_lighting import get_split_screen_colors

# https://openrgb-python.readthedocs.io/en/latest/pages/advanced.html
from openrgb import OpenRGBClient
from openrgb.utils import RGBColor, DeviceType
import numpy as np
import time

client = OpenRGBClient()

client.clear()  # Turns everything off

motherboard = client.get_devices_by_type(DeviceType.MOTHERBOARD)[0]
add = client.get_devices_by_type(DeviceType.MOTHERBOARD)[1]
add.leds[20].set_color(RGBColor(0, 255, 0))

cols = []
nleds = 41

split_cols = get_split_screen_colors()

EN = [0, 5]
ES = [5, 10]
SE = [10, 16]
Пример #19
0
#import wmi
import winstats

maxtemp = 100
mintemp = 30
maxperf = 125
minperf = 95

ledstripsize = 19

red = RGBColor(255, 0, 0)
blue = RGBColor(0, 0, 255)
zonenumber = 0
#myColorList = red, blue, red, blue, red, blue, red, red, blue, blue, red, blue, red, blue

cli = OpenRGBClient()
print(cli)
mobo = cli.get_devices_by_type(DeviceType.MOTHERBOARD)[0]
print(mobo)
mobo.set_mode('direct')
mobo.zones[zonenumber].resize(ledstripsize)
print(mobo.zones[zonenumber])

myLeds = mobo.zones[zonenumber].leds
for i in myLeds:
    i.set_color(red)

step = ((maxperf - minperf) / len(myLeds))

while True:
    procperf = winstats.get_perf_data(
 def construct_instance(cls, *args, **kwargs):
     return OpenRGBClient(*args, **kwargs)
Пример #21
0
async def async_setup_entry(hass, entry):
    """Set up OpenRGB platform."""

    config = {}
    for key, value in entry.data.items():
        config[key] = value
    for key, value in entry.options.items():
        config[key] = value
    if entry.options:
        hass.config_entries.async_update_entry(entry, data=config, options={})

    _LOGGER.debug("Initializing OpenRGB entry (%s)", config)

    undo_listener = entry.add_update_listener(_update_listener)

    try:
        orgb = OpenRGBClient(
            config[CONF_HOST],
            config[CONF_PORT],
            name=config[CONF_CLIENT_ID],
        )
    except ConnectionError as err:
        _LOGGER.error("Connection error during integration setup. Error: %s",
                      err)
        raise ConfigEntryNotReady
    except:
        _LOGGER.debug("Connection error during integration setup.")
        raise ConfigEntryNotReady
    autolog(">>>")

    _LOGGER.info("Initialized OpenRGB entry (%s)", config)

    def connection_recovered():
        autolog("<<<")
        if not hass.data[DOMAIN][entry.entry_id]["online"]:
            _LOGGER.info(
                "Connection reestablished to OpenRGB SDK Server at %s:%i",
                config[CONF_HOST],
                config[CONF_PORT],
            )

        hass.data[DOMAIN][entry.entry_id]["online"] = True
        async_dispatcher_send(hass, SIGNAL_UPDATE_ENTITY)
        autolog(">>>")

    def connection_failed():
        autolog("<<<")
        if hass.data[DOMAIN][entry.entry_id]["online"]:
            hass.data[DOMAIN][entry.entry_id][ORGB_DATA].disconnect()
            _LOGGER.warn(
                "Connection lost to OpenRGB SDK Server at %s:%i",
                config[CONF_HOST],
                config[CONF_PORT],
            )

        hass.data[DOMAIN][entry.entry_id]["online"] = False
        async_dispatcher_send(hass, SIGNAL_UPDATE_ENTITY)
        autolog(">>>")

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        "ha_dev_unique_id":
        f'{DOMAIN}_{entry.data[CONF_HOST]}_{entry.data[CONF_PORT]}',
        "online": True,
        ORGB_DATA: orgb,
        ORGB_TRACKER: None,
        ENTRY_IS_SETUP: set(),
        "entities": {},
        "pending": {},
        "devices": {},
        "unlistener": undo_listener,
        "connection_failed": connection_failed,
        "connection_recovered": connection_recovered,
    }

    # Initial device load
    async def async_load_devices(device_list):
        autolog("<<<")

        device_type_list = {}

        for device in device_list:
            ha_type = "light"
            if ha_type not in device_type_list:
                device_type_list[ha_type] = []
            device_type_list[ha_type].append(device)

            entity_id = orgb_entity_id(device)
            device_unique_id = device.metadata.serial
            # Some devices don't have a serial defined, so fall back to OpenRGB id
            if not device_unique_id:
                device_unique_id = entity_id

            if entity_id not in hass.data[DOMAIN][entry.entry_id]["devices"]:
                hass.data[DOMAIN][entry.entry_id]["devices"][entity_id] = []

            # Stores the entire device as an entity
            if device_unique_id not in hass.data[DOMAIN][
                    entry.entry_id]["entities"]:
                hass.data[DOMAIN][
                    entry.entry_id]["entities"][device_unique_id] = None

            if CONF_ADD_LEDS in config and config[CONF_ADD_LEDS]:
                # Stores each LED of the device as an entity
                for led in device.leds:
                    led_unique_id = f"{device_unique_id}_led_{led.id}"
                    if led_unique_id not in hass.data[DOMAIN][
                            entry.entry_id]["entities"]:
                        hass.data[DOMAIN][
                            entry.entry_id]["entities"][led_unique_id] = None

        for ha_type, dev_ids in device_type_list.items():
            config_entries_key = f"{ha_type}.openrgb"

            if config_entries_key not in hass.data[DOMAIN][
                    entry.entry_id][ENTRY_IS_SETUP]:
                hass.data[DOMAIN][entry.entry_id]["pending"][ha_type] = dev_ids
                hass.async_create_task(
                    hass.config_entries.async_forward_entry_setup(
                        entry, "light"))
                hass.data[DOMAIN][entry.entry_id][ENTRY_IS_SETUP].add(
                    config_entries_key)
            else:
                async_dispatcher_send(hass, ORGB_DISCOVERY_NEW.format("light"),
                                      entry.entry_id, device_list)

        autolog(">>>")

    def _get_updated_devices():
        autolog("<<<")
        if hass.data[DOMAIN][entry.entry_id]["online"]:
            try:
                orgb.update()
                return orgb.devices
            except OSError:
                autolog(">>>exception")
                hass.data[DOMAIN][entry.entry_id]["connection_failed"]()
                return None
        else:
            hass.data[DOMAIN][entry.entry_id]["connection_failed"]()
            autolog(">>>")
            return None

    device_list = await hass.async_add_executor_job(_get_updated_devices)
    _LOGGER.debug("hass device list: %s", device_list)
    if device_list is not None:
        await async_load_devices(device_list)

    async def async_poll_devices_update(event_time):
        autolog("<<<")
        _LOGGER.debug("hass data: %s", hass.data[DOMAIN])

        if not hass.data[DOMAIN][entry.entry_id]["online"]:
            # try to reconnect
            try:
                hass.data[DOMAIN][entry.entry_id][ORGB_DATA].connect()
                hass.data[DOMAIN][entry.entry_id]["connection_recovered"]()
            except OSError:
                hass.data[DOMAIN][entry.entry_id]["connection_failed"]()
                return

        device_list = await hass.async_add_executor_job(_get_updated_devices)
        if device_list is None:
            return

        await async_load_devices(device_list)

        _LOGGER.debug("hass data newlist: %s", device_list)

        newlist_ids = []
        for device in device_list:
            newlist_ids.append(orgb_entity_id(device))
        for dev_id in list(hass.data[DOMAIN][entry.entry_id]["devices"]):
            # Clean up stale devices, or alert them that new info is available.
            if dev_id not in newlist_ids:
                async_dispatcher_send(hass, SIGNAL_DELETE_ENTITY, dev_id)

                for led_id in hass.data[DOMAIN][
                        entry.entry_id]["devices"][dev_id]:
                    async_dispatcher_send(hass, SIGNAL_DELETE_ENTITY, led_id)

                hass.data[DOMAIN][entry.entry_id]["devices"].pop(dev_id)
            else:
                async_dispatcher_send(hass, SIGNAL_UPDATE_ENTITY, dev_id)

                for led_id in hass.data[DOMAIN][
                        entry.entry_id]["devices"][dev_id]:
                    async_dispatcher_send(hass, SIGNAL_UPDATE_ENTITY, led_id)

        autolog(">>>")

    hass.data[DOMAIN][
        entry.entry_id][ORGB_TRACKER] = async_track_time_interval(
            hass, async_poll_devices_update, TRACK_INTERVAL)

    hass.services.async_register(DOMAIN, SERVICE_PULL_DEVICES,
                                 async_poll_devices_update)

    async def async_force_update(call):
        """Force all devices to pull data."""
        async_dispatcher_send(hass, SIGNAL_UPDATE_ENTITY)

    hass.services.async_register(DOMAIN, SERVICE_FORCE_UPDATE,
                                 async_force_update)

    return True
Пример #22
0
#!/usr/bin/env python3

from openrgb import OpenRGBClient
from openrgb.utils import RGBColor, DeviceType

import psutil

client = OpenRGBClient()

cooler = client.get_devices_by_type(DeviceType.COOLER)[0]
cpu_led = cooler.zones[2].leds[0]

while True:
    current_temp = int(psutil.sensors_temperatures()['k10temp'][-1].current)

    min_temp = 35
    max_temp = 65

    min_hue = 0         #Red
    max_hue = 120       #Green
    
    step = max_hue / (max_temp - min_temp)
    
    offset = current_temp - min_temp
    current_hue = max_hue - (offset * step)

    if current_hue < min_hue:
        current_hue = min_hue

    cpu_led.set_color(RGBColor.fromHSV(current_hue, 100, 100))
Пример #23
0
#!/usr/bin/env python3

from openrgb import OpenRGBClient
from openrgb.utils import RGBColor, DeviceType

import psutil

client = OpenRGBClient()
ram = client.get_devices_by_type(DeviceType.DRAM)

while True:
    ram_use = int(psutil.virtual_memory()[2])
    loops = int((ram_use / 20) + 1)
    colour = 5 - loops

    for i in range(4, -1, -1):
        if loops > 0:
            ram[1].leds[x].set_color(RGBColor.fromHSV(colour * 24, 100, 100))
            ram[3].leds[x].set_color(RGBColor.fromHSV(colour * 24, 100, 100))
            ram[0].leds[x].set_color(RGBColor.fromHSV(colour * 24, 100, 100))
            ram[2].leds[x].set_color(RGBColor.fromHSV(colour * 24, 100, 100))
        else:
            ram[1].leds[x].set_color(RGBColor(0, 0, 0))
            ram[3].leds[x].set_color(RGBColor(0, 0, 0))
            ram[0].leds[x].set_color(RGBColor(0, 0, 0))
            ram[2].leds[x].set_color(RGBColor(0, 0, 0))
        loops = loops - 1