Skip to content

Commit

Permalink
feat: remove bunch of unused custom components, use wallpanel to hide…
Browse files Browse the repository at this point in the history
… toolbar on mobile dashboard
  • Loading branch information
aronnebrivio committed Apr 7, 2023
1 parent dd130c1 commit be538ea
Show file tree
Hide file tree
Showing 40 changed files with 3,159 additions and 4,900 deletions.
4 changes: 2 additions & 2 deletions custom_components/pyscript/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,14 +109,14 @@ async def update_yaml_config(hass: HomeAssistant, config_entry: ConfigEntry) ->
# since they affect all scripts
#
config_save = {
param: config_entry.data.get(param, False) for param in {CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS}
param: config_entry.data.get(param, False) for param in [CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS]
}
if DOMAIN not in hass.data:
hass.data.setdefault(DOMAIN, {})
if CONFIG_ENTRY_OLD in hass.data[DOMAIN]:
old_entry = hass.data[DOMAIN][CONFIG_ENTRY_OLD]
hass.data[DOMAIN][CONFIG_ENTRY_OLD] = config_save
for param in {CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS}:
for param in [CONF_HASS_IS_GLOBAL, CONF_ALLOW_ALL_IMPORTS]:
if old_entry.get(param, False) != config_entry.data.get(param, False):
return True
hass.data[DOMAIN][CONFIG_ENTRY_OLD] = config_save
Expand Down
1 change: 1 addition & 0 deletions custom_components/pyscript/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"datetime",
"decimal",
"fractions",
"functools",
"homeassistant.const",
"isort",
"json",
Expand Down
84 changes: 52 additions & 32 deletions custom_components/pyscript/eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,10 @@ def get_name(self):
"""Return the function name."""
return self.name

def set_name(self, name):
"""Set the function name."""
self.name = name

async def eval_defaults(self, ast_ctx):
"""Evaluate the default function arguments."""
self.defaults = []
Expand All @@ -341,12 +345,16 @@ async def eval_defaults(self, ast_ctx):
for val in self.func_def.args.kw_defaults:
self.kw_defaults.append({"ok": bool(val), "val": None if not val else await ast_ctx.aeval(val)})

async def trigger_init(self):
async def trigger_init(self, trig_ctx, func_name):
"""Initialize decorator triggers for this function."""
trig_args = {}
trig_decs = {}
trig_ctx_name = trig_ctx.get_name()
self.logger = logging.getLogger(LOGGER_PATH + "." + trig_ctx_name)
self.global_ctx.set_logger_name(trig_ctx_name)
self.global_ctx_name = trig_ctx_name
got_reqd_dec = False
exc_mesg = f"function '{self.name}' defined in {self.global_ctx_name}"
exc_mesg = f"function '{func_name}' defined in {trig_ctx_name}"
trig_decorators_reqd = {
"event_trigger",
"mqtt_trigger",
Expand Down Expand Up @@ -439,7 +447,7 @@ async def trigger_init(self):
if dec_name == "service":
desc = self.doc_string
if desc is None or desc == "":
desc = f"pyscript function {self.name}()"
desc = f"pyscript function {func_name}()"
desc = desc.lstrip(" \n\r")
if desc.startswith("yaml"):
try:
Expand All @@ -449,7 +457,9 @@ async def trigger_init(self):
file_desc.close()
except Exception as exc:
self.logger.error(
"Unable to decode yaml doc_string for %s(): %s", self.name, str(exc),
"Unable to decode yaml doc_string for %s(): %s",
func_name,
str(exc),
)
raise exc
else:
Expand All @@ -466,7 +476,7 @@ async def pyscript_service_handler(call):
# use a new AstEval context so it can run fully independently
# of other instances (except for global_ctx which is common)
#
ast_ctx = AstEval(f"{self.global_ctx_name}.{func_name}", self.global_ctx)
ast_ctx = AstEval(f"{trig_ctx_name}.{func_name}", self.global_ctx)
Function.install_ast_funcs(ast_ctx)
func_args = {
"trigger_type": "service",
Expand All @@ -483,14 +493,14 @@ async def do_service_call(func, ast_ctx, data):

return pyscript_service_handler

for srv_name in dec_args if dec_args else [f"{DOMAIN}.{self.name}"]:
for srv_name in dec_args if dec_args else [f"{DOMAIN}.{func_name}"]:
if type(srv_name) is not str or srv_name.count(".") != 1:
raise ValueError(f"{exc_mesg}: @service argument must be a string with one period")
domain, name = srv_name.split(".", 1)
if name in (SERVICE_RELOAD, SERVICE_JUPYTER_KERNEL_START):
raise SyntaxError(f"{exc_mesg}: @service conflicts with builtin service")
Function.service_register(
self.global_ctx_name, domain, name, pyscript_service_factory(self.name, self)
trig_ctx_name, domain, name, pyscript_service_factory(func_name, self)
)
async_set_service_schema(Function.hass, domain, name, service_desc)
self.trigger_service.add(srv_name)
Expand All @@ -505,15 +515,15 @@ async def do_service_call(func, ast_ctx, data):
if not got_reqd_dec and len(trig_decs) > 0:
self.logger.error(
"%s defined in %s: needs at least one trigger decorator (ie: %s)",
self.name,
self.global_ctx_name,
func_name,
trig_ctx_name,
", ".join(sorted(trig_decorators_reqd)),
)
return

if len(trig_decs) == 0:
if len(self.trigger_service) > 0:
self.global_ctx.trigger_register(self)
trig_ctx.trigger_register(self)
return

#
Expand All @@ -535,15 +545,13 @@ async def do_service_call(func, ast_ctx, data):
got_trig = True
if not got_trig:
break
for dec_name in {"state_active", "time_active", "task_unique"}:
for dec_name in ["state_active", "time_active", "task_unique"]:
if dec_name in trig_decs:
trig_args[dec_name] = trig_decs[dec_name][0]

self.trigger.append(
self.global_ctx.get_trig_info(f"{self.global_ctx_name}.{self.name}", trig_args)
)
self.trigger.append(trig_ctx.get_trig_info(f"{trig_ctx_name}.{func_name}", trig_args))

if self.global_ctx.trigger_register(self):
if trig_ctx.trigger_register(self):
self.trigger_start()

def trigger_start(self):
Expand Down Expand Up @@ -574,7 +582,7 @@ async def eval_decorators(self, ast_ctx):
and isinstance(dec.func, ast.Name)
and dec.func.id in TRIG_SERV_DECORATORS
):
args = [await ast_ctx.aeval(arg) for arg in dec.args]
args = await ast_ctx.eval_elt_list(dec.args)
kwargs = {keyw.arg: await ast_ctx.aeval(keyw.value) for keyw in dec.keywords}
dec_trig.append([dec.func.id, args, kwargs if len(kwargs) > 0 else None])
elif isinstance(dec, ast.Name) and dec.id in TRIG_SERV_DECORATORS:
Expand All @@ -597,8 +605,8 @@ async def resolve_nonlocals(self, ast_ctx):
args.append(self.func_def.args.vararg.arg)
if self.func_def.args.kwarg:
args.append(self.func_def.args.kwarg.arg)
for i in range(len(self.func_def.args.kwonlyargs)):
args.append(self.func_def.args.kwonlyargs[i].arg)
for kwonlyarg in self.func_def.args.kwonlyargs:
args.append(kwonlyarg.arg)
nonlocal_names = set()
global_names = set()
var_names = set(args)
Expand Down Expand Up @@ -671,8 +679,8 @@ async def call(self, ast_ctx, *args, **kwargs):
if args is None:
args = []
kwargs = kwargs.copy() if kwargs else {}
for i in range(len(self.func_def.args.args)):
var_name = self.func_def.args.args[i].arg
for i, func_def_arg in enumerate(self.func_def.args.args):
var_name = func_def_arg.arg
val = None
if i < len(args):
val = args[i]
Expand All @@ -688,8 +696,8 @@ async def call(self, ast_ctx, *args, **kwargs):
f"{self.name}() missing {self.num_posn_arg - i} required positional arguments"
)
sym_table[var_name] = val
for i in range(len(self.func_def.args.kwonlyargs)):
var_name = self.func_def.args.kwonlyargs[i].arg
for i, kwonlyarg in enumerate(self.func_def.args.kwonlyargs):
var_name = kwonlyarg.arg
if var_name in kwargs:
val = kwargs[var_name]
del kwargs[var_name]
Expand Down Expand Up @@ -807,6 +815,10 @@ def get_name(self):
"""Return the function name."""
return self.func.get_name()

def set_name(self, name):
"""Set the function name."""
self.func.set_name(name)

def set_ast_ctx(self, ast_ctx):
"""Set the ast context."""
self.ast_ctx = ast_ctx
Expand Down Expand Up @@ -1115,18 +1127,23 @@ async def executor_wrap(*args, **kwargs):
for dec_func in dec_other:
func = await self.call_func(dec_func, None, func)
if isinstance(func, EvalFuncVar):
# set the function name back to its original instead of the decorator function we just called
func.set_name(name)
func = func.remove_func()
dec_trig += func.decorators
elif isinstance(func, EvalFunc):
func.set_name(name)
self.dec_eval_depth -= 1
if isinstance(func, EvalFunc):
func.decorators = dec_trig
if self.dec_eval_depth == 0:
func.trigger_stop()
await func.trigger_init()
await func.trigger_init(self.global_ctx, name)
func_var = EvalFuncVar(func)
func_var.set_ast_ctx(self)
else:
func_var = EvalFuncVar(func)
func_var.set_ast_ctx(self)
func_var.set_ast_ctx(self)
else:
func_var = func

Expand Down Expand Up @@ -1339,7 +1356,7 @@ async def recurse_assign(self, lhs, val):
"""Recursive assignment."""
if isinstance(lhs, ast.Tuple):
try:
vals = [*(val.__iter__())]
vals = [*(iter(val))]
except Exception:
raise TypeError("cannot unpack non-iterable object") # pylint: disable=raise-missing-from
got_star = 0
Expand All @@ -1361,7 +1378,8 @@ async def recurse_assign(self, lhs, val):
star_len = len(vals) - len(lhs.elts) + 1
star_name = lhs_elt.value.id
await self.recurse_assign(
ast.Name(id=star_name, ctx=ast.Store()), vals[val_idx : val_idx + star_len],
ast.Name(id=star_name, ctx=ast.Store()),
vals[val_idx : val_idx + star_len],
)
val_idx += star_len
else:
Expand Down Expand Up @@ -1678,16 +1696,16 @@ async def ast_cmpop_notin(self, arg0, arg1):
async def ast_boolop(self, arg):
"""Evaluate boolean operators and and or."""
if isinstance(arg.op, ast.And):
val = 1
val = True
for arg1 in arg.values:
this_val = await self.aeval(arg1)
if this_val == 0:
return 0
if not this_val:
return this_val
val = this_val
return val
for arg1 in arg.values:
val = await self.aeval(arg1)
if val != 0:
if val:
return val
return 0

Expand Down Expand Up @@ -1889,7 +1907,7 @@ async def call_func(self, func, func_name, *args, **kwargs):
# it is later garbage collected
#
inst_weak = weakref.ref(inst)
for name in inst.__dir__():
for name in dir(inst):
value = getattr(inst, name)
if type(value) is not EvalFuncVar:
continue
Expand Down Expand Up @@ -2210,12 +2228,14 @@ def completions(self, root):
words.add(name)
return words

async def eval(self, new_state_vars=None):
async def eval(self, new_state_vars=None, merge_local=False):
"""Execute parsed code, with the optional state variables added to the scope."""
self.exception = None
self.exception_obj = None
self.exception_long = None
if new_state_vars:
if not merge_local:
self.local_sym_table = {}
self.local_sym_table.update(new_state_vars)
if self.ast:
try:
Expand Down
2 changes: 1 addition & 1 deletion custom_components/pyscript/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ def notify_del(cls, event_type, queue):
async def update(cls, event_type, func_args):
"""Deliver all notifications for an event of the given type."""

_LOGGER.debug("event.update(%s, %s, %s)", event_type, vars, func_args)
_LOGGER.debug("event.update(%s, %s)", event_type, func_args)
if event_type in cls.notify:
for queue in cls.notify[event_type]:
await queue.put(["event", func_args])
4 changes: 4 additions & 0 deletions custom_components/pyscript/global_ctx.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,10 @@ def get_name(self) -> str:
"""Return the global context name."""
return self.name

def set_logger_name(self, name) -> None:
"""Set the global context logging name."""
self.logger = logging.getLogger(LOGGER_PATH + "." + name)

def get_global_sym_table(self) -> Dict[str, Any]:
"""Return the global symbol table."""
return self.global_sym_table
Expand Down
41 changes: 34 additions & 7 deletions custom_components/pyscript/jupyter_kernel.py
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,8 @@ def __init__(self, config, ast_ctx, global_ctx, global_ctx_name):
self.no_connect_timeout = self.config.get("no_connect_timeout", 30)
self.signature_schemes = {"hmac-sha256": hashlib.sha256}
self.auth = hmac.HMAC(
self.secure_key, digestmod=self.signature_schemes[self.config["signature_scheme"]],
self.secure_key,
digestmod=self.signature_schemes[self.config["signature_scheme"]],
)
self.execution_count = 1
self.engine_id = str(uuid.uuid4())
Expand Down Expand Up @@ -295,7 +296,13 @@ def new_header(self, msg_type):
}

async def send(
self, stream, msg_type, content=None, parent_header=None, metadata=None, identities=None,
self,
stream,
msg_type,
content=None,
parent_header=None,
metadata=None,
identities=None,
):
"""Send message to the Jupyter client."""
header = self.new_header(msg_type)
Expand Down Expand Up @@ -401,7 +408,10 @@ async def shell_handler(self, shell_socket, wire_msg):
"metadata": {},
}
await self.send(
self.iopub_socket, "execute_result", content, parent_header=msg["header"],
self.iopub_socket,
"execute_result",
content,
parent_header=msg["header"],
)

metadata = {
Expand Down Expand Up @@ -484,7 +494,11 @@ async def shell_handler(self, shell_socket, wire_msg):
"metadata": {},
}
await self.send(
shell_socket, "complete_reply", content, parent_header=msg["header"], identities=identities,
shell_socket,
"complete_reply",
content,
parent_header=msg["header"],
identities=identities,
)

elif msg["header"]["msg_type"] == "is_complete_request":
Expand Down Expand Up @@ -546,15 +560,26 @@ async def shell_handler(self, shell_socket, wire_msg):
elif msg["header"]["msg_type"] == "comm_info_request":
content = {"comms": {}}
await self.send(
shell_socket, "comm_info_reply", content, parent_header=msg["header"], identities=identities,
shell_socket,
"comm_info_reply",
content,
parent_header=msg["header"],
identities=identities,
)

elif msg["header"]["msg_type"] == "history_request":
content = {"history": []}
await self.send(
shell_socket, "history_reply", content, parent_header=msg["header"], identities=identities,
shell_socket,
"history_reply",
content,
parent_header=msg["header"],
identities=identities,
)

elif msg["header"]["msg_type"] in {"comm_open", "comm_msg", "comm_close"}:
# _LOGGER.debug(f"ignore {msg['header']['msg_type']} message ")
...
else:
_LOGGER.error("unknown msg_type: %s", msg["header"]["msg_type"])

Expand Down Expand Up @@ -752,7 +777,9 @@ async def start_one_server(self, callback):
except OSError:
self.avail_port += 1
_LOGGER.error(
"unable to find an available port from %d to %d", first_port, self.avail_port - 1,
"unable to find an available port from %d to %d",
first_port,
self.avail_port - 1,
)
return None, None

Expand Down
Loading

0 comments on commit be538ea

Please sign in to comment.