1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
|
from __future__ import annotations
import sys
import typing
import logging
import argparse
import jsonschema
import coloredlogs
import zigpy_znp.types as t
import zigpy_znp.logger as log
LOG_LEVELS = [logging.INFO, logging.DEBUG, log._TRACE]
OPEN_COORDINATOR_BACKUP_SCHEMA = {
"$schema": "http://json-schema.org/draft-07/schema#",
"$id": "https://github.com/zigpy/open-coordinator-backup/schema.json",
"type": "object",
"properties": {
"metadata": {
"type": "object",
"properties": {
"format": {
"type": "string",
"pattern": "^zigpy/open-coordinator-backup$",
},
"version": {"type": "integer", "minimum": 1, "maximum": 1},
"source": {"type": "string", "pattern": "^(.*?)+@(.*?)$"},
"internal": {"type": "object"},
},
"required": ["version", "source"],
},
"stack_specific": {
"type": "object",
"properties": {
"zstack": {
"type": "object",
"properties": {
"tclk_seed": {"type": "string", "pattern": "[a-fA-F0-9]{32}"},
},
}
},
},
"coordinator_ieee": {"type": "string", "pattern": "[a-fA-F0-9]{16}"},
"pan_id": {"type": "string", "pattern": "[a-fA-F0-9]{4}"},
"extended_pan_id": {"type": "string", "pattern": "[a-fA-F0-9]{16}"},
"nwk_update_id": {"type": "integer", "minimum": 0, "maximum": 255},
"security_level": {"type": "integer", "minimum": 0, "maximum": 7},
"channel": {"type": "integer", "minimum": 11, "maximum": 26},
"channel_mask": {
"type": "array",
"items": {"type": "integer", "minimum": 11, "maximum": 26},
},
"network_key": {
"type": "object",
"properties": {
"key": {"type": "string", "pattern": "[a-fA-F0-9]{32}"},
"sequence_number": {"type": "integer", "minimum": 0, "maximum": 255},
"frame_counter": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295,
},
},
"required": ["key", "sequence_number", "frame_counter"],
},
"devices": {
"type": "array",
"items": {
"type": "object",
"properties": {
"nwk_address": {
"type": ["string", "null"],
"pattern": "[a-fA-F0-9]{4}",
},
"ieee_address": {"type": "string", "pattern": "[a-fA-F0-9]{16}"},
"is_child": {"type": "boolean"},
"link_key": {
"type": "object",
"properties": {
"key": {"type": "string", "pattern": "[a-fA-F0-9]{16}"},
"tx_counter": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295,
},
"rx_counter": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295,
},
},
"required": ["key", "tx_counter", "rx_counter"],
},
},
"required": ["nwk_address", "ieee_address"],
},
},
},
"required": [
"metadata",
"coordinator_ieee",
"pan_id",
"extended_pan_id",
"nwk_update_id",
"security_level",
"channel",
"channel_mask",
"network_key",
"devices",
],
}
def validate_backup_json(backup: t.JSONType) -> None:
jsonschema.validate(backup, schema=OPEN_COORDINATOR_BACKUP_SCHEMA)
class CustomArgumentParser(argparse.ArgumentParser):
def parse_args(self, args: typing.Sequence[str] | None = None, namespace=None):
args = super().parse_args(args, namespace)
# Since we're running as a CLI tool, install our own log level and color logger
log.TRACE = log._TRACE
logging.addLevelName(log.TRACE, "TRACE")
# But still allow the user to configure verbosity
verbosity = args.verbosity
log_level = LOG_LEVELS[min(max(0, verbosity), len(LOG_LEVELS) - 1)]
# coloredlogs uses "spam" for level 5, not "trace"
level_styles = coloredlogs.DEFAULT_LEVEL_STYLES.copy()
level_styles["trace"] = level_styles["spam"]
logging.getLogger().setLevel(log_level)
coloredlogs.install(
fmt=(
"%(asctime)s.%(msecs)03d"
" %(hostname)s"
" %(name)s"
" %(levelname)s %(message)s"
),
level=log_level,
level_styles=level_styles,
)
return args
class UnclosableFile:
"""
Wraps a file object so that every operation but "close" is proxied.
"""
def __init__(self, f):
self.f = f
def close(self):
return
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
return
def __getattr__(self, name):
return getattr(self.f, name)
class ClosableFileType(argparse.FileType):
"""
Allows `FileType` to always be closed properly, even with stdout and stdin.
"""
def __call__(self, string):
f = super().__call__(string)
if f not in (sys.stdin, sys.stdout, sys.stdin.buffer, sys.stdout.buffer):
return f
return UnclosableFile(f)
def setup_parser(description: str) -> argparse.ArgumentParser:
"""
Creates an ArgumentParser that sets up a logger with a configurable verbosity
and a positional serial port argument.
"""
parser = CustomArgumentParser(
description=description,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
)
parser.add_argument(
"-v",
"--verbose",
dest="verbosity",
action="count",
default=0,
help="increases verbosity",
)
parser.add_argument("serial", type=str, help="Serial port path")
return parser
|