Exemple #1
0
async def traffic():
    rx = 0
    tx = 0
    rxd = 0
    txd = 0
    rxdc = {}
    txdc = {}
    rxdf = 'rx'
    txdf = 'tx'
    while True:
        data = psutil.net_io_counters()

        if rx:
            rxd = round((data.bytes_recv - rx) / 1024, 2)
            rxdf = "{:07}".format(rxd)
            rxdc = colorize(rxd)

        if tx:
            txd = round((data.bytes_sent - tx) / 1024, 2)
            txdf = "{:06}".format(txd)
            txdc = colorize(txd)

        rx = data.bytes_recv
        tx = data.bytes_sent

        yield fmt("{} {}".format(fmt(rxdf, colors=rxdc), fmt(txdf, colors=txdc)))
        await sleep(2)
Exemple #2
0
async def mpd():
    try:
        await client.connect(config["host"], config["port"])
        await client.password(config["password"])

        # >>>>>
        status = await client.status()
        if status["state"] == "play":
            colors = {'fg': 'green'}
        elif status["state"] == "pause":
            colors = {'fg': 'grey'}
        elif status["state"] == "stop":
            colors = {'fg': 'grey'}

        currentsong = await client.currentsong()
        if "title" in currentsong:
            title = currentsong["title"]
        else:
            title = ""

        yield fmt("{}".format(title), colors=colors, pad="")
        # <<<<<

    except Exception as e:
        print("MPD Connection failed: {}".format(e), file=sys.stderr)
        raise e

    while True:
        try:
            async for x in client.idle():
                logger.info(x)
                if "player" in x: # ['player', 'mixer']
                    try:
                        #await sleep(1)

                        # >>>>>
                        status = await client.status()
                        if status["state"] == "play":
                            colors = {'fg': 'green'}
                        elif status["state"] == "pause":
                            colors = {'fg': 'grey'}
                        elif status["state"] == "stop":
                            colors = {'fg': 'grey'}

                        currentsong = await client.currentsong()
                        if "title" in currentsong:
                            title = currentsong["title"]

                        yield fmt("{}".format(title), colors=colors)
                        # <<<<<

                    except Exception as e:
                        raise e
        except Exception as e:
            raise e
Exemple #3
0
async def sensors():
    t = [0.0, 0.0]
    while True:
        with open('/sys/class/hwmon/hwmon0/temp1_input', 'r', encoding="utf-8") as p:
            t[0] = float(p.read())/1000 # mainboard temperature?

        with open('/sys/class/hwmon/hwmon0/temp2_input', 'r', encoding="utf-8") as p:
            t[1] = float(p.read())/1000 # overall cpu temperature?

        yield fmt("{} {}".format(fmt(t[0], colors=colorize(t[0])), fmt(t[1], colors=colorize(t[1]))))
        await sleep(2)
Exemple #4
0
async def bitcoin():
    while True:
        res = await get_request(url)
        if res:
            val = res['EUR']['15m']
            yield fmt(val, colors=colorize(val))
            await sleep(900)
Exemple #5
0
async def load():
    while True:
        out = []
        for loadavg in psutil.getloadavg():
            #out.append(fmt(str(loadavg), colors=gradient(loadavg), pad=""))
            out.append(fmt(str(loadavg), pad=""))
        yield " ".join(out)
        await sleep(2)
Exemple #6
0
async def meta():
    while True:
        pid = os.getpid()
        py = psutil.Process(pid)
        # print(pid)
        mem = py.memory_info()[0]  #/2.**30 memory use in GB...I think
        cpu = py.cpu_percent()
        # print(pid, cpu, mem)

        yield fmt("{}:{}".format(str(cpu), bytes2human(round(mem, 2))),
                  colors={'fg': 'grey'})
        await sleep(2)
Exemple #7
0
async def openweathermap():
    URL = "https://api.openweathermap.org/data/2.5/weather?id={}&appid={}&units=metric".format(
        settings["city_id"], settings["openweathermap_api_key"])

    while True:
        try:
            data = await get_request(URL)
        except JSONDecodeError as e:
            print(e)

        if data:
            try:
                temperature = data["main"]["temp"]
                summary = data["weather"][0]["description"].title()
            except (NameError, KeyError) as e:
                yield fmt("ERROR:{}".format(e))
                print(e)
                await sleep(90)
                continue

            yield fmt("{} {}".format(summary, temperature))

        await sleep(90)
Exemple #8
0
async def gpu():
    nvmlInit()
    handle = nvmlDeviceGetHandleByIndex(0)

    while True:
        temperature = nvmlDeviceGetTemperature(handle, 0)
        threshold = nvmlDeviceGetTemperatureThreshold(handle, 0)
        gpu = nvmlDeviceGetUtilizationRates(handle).gpu
        mem = nvmlDeviceGetUtilizationRates(handle).memory
        yield fmt("{:02}C {:02}% {:02}%".format(temperature, gpu, mem),
                  colors=fire(temperature, threshold),
                  pad="")
        await sleep(1)

    nvmlShutdown()  # FIXME
Exemple #9
0
async def cpu():
    while True:
        val = psutil.cpu_percent()
        yield fmt("{:04}%".format(val), colors=fire(val), pad="")
        await sleep(2)
Exemple #10
0
async def pulseaudio():
    p = Pulse('HELLO_FROM_BAR_PULSEAUDIO')

    states = {
        'idle': {
            'colors': {
                'fg': 'grey'
            }
        },
        'invalid': {
            'colors': {
                'fg': 'black',
                'bg': 'red'
            }
        },
        'running': {
            'colors': {
                'fg': 'white'
            }
        },
        'suspended': {
            'colors': {
                'fg': 'grey'
            }
        }
    }

    while True:
        out = []

        try:
            for source in p.sink_input_list()[1:]:
                index = source.index
                volume = int(float(source.volume.value_flat) * 100)

                actions = [
                    Action(
                        1,
                        "pactl set-sink-input-volume {} 100%".format(index)),
                    Action(
                        2,
                        "pactl set-sink-input-mute {} toggle".format(index)),
                    Action(3, "pavucontrol&".format()),
                    Action(
                        4,
                        "pactl set-sink-input-volume {} +10%".format(index)),
                    Action(
                        5,
                        "pactl set-sink-input-volume {} -10%".format(index)),
                ]

                if source.mute == 1:
                    colors = {'fg': 'grey'}
                else:
                    colors = fire(volume)

                out.append(fmt(volume, colors=colors, actions=actions, pad=""))

        except Exception as e:
            pass
        #except pulsectl.pulsectl.PulseOperationFailed as e:
        #    if e == 158:
        #        pass

        #for sink in p.sink_list():

        #    if sink.description == 'Built-in Audio Analog Stereo':
        #        colors = {'fg': 'yellow'}
        #    elif sink.description == 'PCM2902 Audio Codec Analog Stereo':
        #        colors = {'fg': 'cyan'}
        #    else:
        #        colors = {'fg': 'white'}

        #    # sink_state = sink
        #    # print(sink_state)

        #    volume = int(float(sink.volume.value_flat) * 100)

        #    actions = [
        #        Action(1, "pactl set-sink-volume {} 100%".format(sink.index)),
        #        Action(2, "pactl set-sink-mute {} toggle".format(sink.index)),
        #        Action(3, "pavucontrol&".format()),
        #        Action(4, "pactl set-sink-volume {} +10%".format(sink.index)),
        #        Action(5, "pactl set-sink-volume {} -10%".format(sink.index)),
        #    ]

        #    if sink.mute == 1:
        #        colors = {'fg': 'grey'}
        #    else:
        #        colors = fire(volume)

        #    out.append(fmt(volume, colors=colors, actions=actions, pad=""))

        # yield fmt(list(map(lambda x: str(x).strip(), out)))

        yield fmt(" ".join(out))
        await sleep(0.5)
Exemple #11
0
async def mem():
    while True:
        val = psutil.virtual_memory()[2] # used ram %
        yield fmt("{}%".format(val), colors=fire(val))
        await sleep(2)
Exemple #12
0
def bspwm_fmt(line, **block):

    out = []

    if not line[0] == 'W':
        raise ValueError("bspc report prefix unknown")

    line = line.rstrip()[1:]
    items = line.split(':')

    if not line:
        return fmt("")

    for item in items:

        actions = []

        t = item[0]  # type  pylint: disable=invalid-name
        v = item[1:]  # value pylint: disable=invalid-name

        if not v:
            continue

        if match('[fFoOuU]', t):
            actions = [
                Action(1, "bspc desktop -f {0}".format(v)),
                Action(3, "bspc node -d {0}".format(v)),
                Action(4, "bspc desktop -f next"),
                Action(5, "bspc desktop -f prev"),
            ]

            # pad desktop clickables to make them more easily clickable
            pad = ' '

        # - - - - - - - - - -

        if block['settings']['show_monitor']:
            if t == 'm':
                # unfocused monitor
                out.append(fmt(v))
            elif t == 'M':
                # focused monitor
                out.append(fmt(v))

        if t == 'f':
            # free unfocused desktop
            out.append(fmt(v, pad=pad, actions=actions, colors={'fg': 'grey'}))
        elif t == 'F':
            # free focused desktop
            out.append(
                fmt(v, pad=pad, actions=actions, colors={'fg': 'bwhite'}))
        elif t == 'o':
            # occupied unfocused desktop
            out.append(
                fmt(v, pad=pad, actions=actions, colors={'fg': 'magenta'}))
        elif t == 'O':
            # occupied focused desktop
            out.append(
                fmt(
                    v,
                    pad=pad,
                    actions=actions,
                    colors={
                        'fg': 'bred',
                        #'bg': 'blue',
                        'rev': False
                    }))
        elif t == 'u':
            # urgent unfocused desktop
            out.append(fmt(v, pad=pad, actions=actions, colors={'fg': 'red'}))
        elif t == 'U':
            # urgent focused desktop
            out.append(fmt(v, pad=pad, actions=actions, colors={'fg': 'red'}))

        if match('[LTG]', t):
            colors = {'fg': 'grey'}

        if block['settings']['show_desktop_layout']:
            if t == 'L':
                # pad between desktops and stuff
                #out.append(' ')
                # desktop layout
                out.append(
                    fmt(v,
                        colors={
                            'bg': 'blue',
                            'fg': 'yellow'
                        },
                        actions=[Action(1, 'bspc desktop -l next')]))

        if block['settings']['show_node_state']:
            if t == 'T':
                # node state
                out.append(fmt(v, colors={'bg': 'blue', 'fg': 'yellow'}))

        if block['settings']['show_node_flags']:
            if t == 'G':
                # node flags
                out.append(fmt(v, colors={'bg': 'blue', 'fg': 'yellow'}))

        # - - - - - - - - - -

    #debug(" ".join(out))
    return fmt("".join(out))
Exemple #13
0
async def empty():
    while True:
        yield fmt("")
        await sleep(1)