desktop building?
This commit is contained in:
76
modules/home/programs/waybar/scripts/hass.nix
Executable file
76
modules/home/programs/waybar/scripts/hass.nix
Executable file
@@ -0,0 +1,76 @@
|
||||
{ config, lib, namespace, pkgs, ... }:
|
||||
let
|
||||
cfg = config.mjallen.programs.waybar;
|
||||
|
||||
pythonEnv = pkgs.python3.withPackages (ps: [
|
||||
pkgs.${namespace}.homeassistant-api
|
||||
]);
|
||||
|
||||
waybar-hass = pkgs.writeScriptBin "waybar-hass" ''
|
||||
#!${pythonEnv}/bin/python
|
||||
"""run with the special python"""
|
||||
|
||||
import argparse
|
||||
import time
|
||||
import json
|
||||
from homeassistant_api import WebsocketClient
|
||||
|
||||
HASS_URL = 'ws://homeassistant.local:8123/api/websocket'
|
||||
|
||||
parser = argparse.ArgumentParser(prog='hass python wrapper')
|
||||
parser.add_argument('--toggle_light')
|
||||
parser.add_argument('--get_light')
|
||||
args = parser.parse_args()
|
||||
|
||||
def load_key():
|
||||
"""Read the api key"""
|
||||
token_path = "/run/secrets/desktop/hass_token"
|
||||
with open(token_path, "r") as key_file:
|
||||
key = key_file.readline()
|
||||
return key
|
||||
|
||||
def get_light_state(client, light):
|
||||
"""Get light status"""
|
||||
light_entity = client.get_entity(entity_id=light)
|
||||
state = light_entity.get_state()
|
||||
if state.state == 'on':
|
||||
return ""
|
||||
return ""
|
||||
|
||||
def toggle_light(client, light):
|
||||
"""Toggle light status"""
|
||||
lights = client.get_domain("light")
|
||||
lights.toggle(entity_id=light)
|
||||
time.sleep(0.5)
|
||||
light_entity = client.get_entity(entity_id=light)
|
||||
state = light_entity.get_state()
|
||||
if state.state == 'on':
|
||||
return ""
|
||||
return ""
|
||||
|
||||
def main():
|
||||
"""Main"""
|
||||
token = load_key()
|
||||
status = "err"
|
||||
|
||||
with WebsocketClient(HASS_URL, token) as client:
|
||||
# toggle a light
|
||||
if args.toggle_light is not None:
|
||||
status = toggle_light(client=client, light=args.toggle_light)
|
||||
# get the current light status
|
||||
if args.get_light is not None:
|
||||
status = get_light_state(client=client, light=args.get_light)
|
||||
|
||||
print(json.dumps({ "text": status }))
|
||||
|
||||
main()
|
||||
|
||||
'';
|
||||
in
|
||||
{
|
||||
imports = [ ../options.nix ];
|
||||
|
||||
config = lib.mkIf cfg.enable {
|
||||
home.packages = [ waybar-hass ];
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user