code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
from __future__ import unicode_literals import hashlib import six import sqlalchemy as sa from ziggurat_foundations.models.base import get_db_session from ziggurat_foundations.models.services import BaseService from ziggurat_foundations.permissions import ( ALL_PERMISSIONS, ANY_PERMISSION, PermissionTuple, resource_permissions_for_users, ) from ziggurat_foundations.utils import generate_random_string __all__ = ["UserService"] class UserService(BaseService): @classmethod def get(cls, user_id, db_session=None): """ Fetch row using primary key - will use existing object in session if already present :param user_id: :param db_session: :return: """ db_session = get_db_session(db_session) return db_session.query(cls.model).get(user_id) @classmethod def permissions(cls, instance, db_session=None): """ returns all non-resource permissions based on what groups user belongs and directly set ones for this user :param instance: :param db_session: :return: """ db_session = get_db_session(db_session, instance) query = db_session.query( cls.models_proxy.GroupPermission.group_id.label("owner_id"), cls.models_proxy.GroupPermission.perm_name.label("perm_name"), sa.literal("group").label("type"), ) query = query.filter( cls.models_proxy.GroupPermission.group_id == cls.models_proxy.UserGroup.group_id ) query = query.filter( cls.models_proxy.User.id == cls.models_proxy.UserGroup.user_id ) query = query.filter(cls.models_proxy.User.id == instance.id) query2 = db_session.query( cls.models_proxy.UserPermission.user_id.label("owner_id"), cls.models_proxy.UserPermission.perm_name.label("perm_name"), sa.literal("user").label("type"), ) query2 = query2.filter(cls.models_proxy.UserPermission.user_id == instance.id) query = query.union(query2) groups_dict = dict([(g.id, g) for g in instance.groups]) return [ PermissionTuple( instance, row.perm_name, row.type, groups_dict.get(row.owner_id) if row.type == "group" else None, None, False, True, ) for row in query ] @classmethod def resources_with_perms( cls, instance, perms, resource_ids=None, resource_types=None, db_session=None ): """ returns all resources that user has perms for (note that at least one perm needs to be met) :param instance: :param perms: :param resource_ids: restricts the search to specific resources :param resource_types: :param db_session: :return: """ # owned entities have ALL permissions so we return those resources too # even without explicit perms set # TODO: implement admin superrule perm - maybe return all apps db_session = get_db_session(db_session, instance) query = db_session.query(cls.models_proxy.Resource).distinct() group_ids = [gr.id for gr in instance.groups] # if user has some groups lets try to join based on their permissions if group_ids: join_conditions = ( cls.models_proxy.GroupResourcePermission.group_id.in_(group_ids), cls.models_proxy.Resource.resource_id == cls.models_proxy.GroupResourcePermission.resource_id, cls.models_proxy.GroupResourcePermission.perm_name.in_(perms), ) query = query.outerjoin( (cls.models_proxy.GroupResourcePermission, sa.and_(*join_conditions)) ) # ensure outerjoin permissions are correct - # dont add empty rows from join # conditions are - join ON possible group permissions # OR owning group/user query = query.filter( sa.or_( cls.models_proxy.Resource.owner_user_id == instance.id, cls.models_proxy.Resource.owner_group_id.in_(group_ids), cls.models_proxy.GroupResourcePermission.perm_name != None, ) # noqa ) else: # filter just by username query = query.filter(cls.models_proxy.Resource.owner_user_id == instance.id) # lets try by custom user permissions for resource query2 = db_session.query(cls.models_proxy.Resource).distinct() query2 = query2.filter( cls.models_proxy.UserResourcePermission.user_id == instance.id ) query2 = query2.filter( cls.models_proxy.Resource.resource_id == cls.models_proxy.UserResourcePermission.resource_id ) query2 = query2.filter( cls.models_proxy.UserResourcePermission.perm_name.in_(perms) ) if resource_ids: query = query.filter( cls.models_proxy.Resource.resource_id.in_(resource_ids) ) query2 = query2.filter( cls.models_proxy.Resource.resource_id.in_(resource_ids) ) if resource_types: query = query.filter( cls.models_proxy.Resource.resource_type.in_(resource_types) ) query2 = query2.filter( cls.models_proxy.Resource.resource_type.in_(resource_types) ) query = query.union(query2) query = query.order_by(cls.models_proxy.Resource.resource_name) return query @classmethod def groups_with_resources(cls, instance): """ Returns a list of groups users belongs to with eager loaded resources owned by those groups :param instance: :return: """ return instance.groups_dynamic.options( sa.orm.eagerload(cls.models_proxy.Group.resources) ) @classmethod def resources_with_possible_perms( cls, instance, resource_ids=None, resource_types=None, db_session=None ): """ returns list of permissions and resources for this user :param instance: :param resource_ids: restricts the search to specific resources :param resource_types: restricts the search to specific resource types :param db_session: :return: """ perms = resource_permissions_for_users( cls.models_proxy, ANY_PERMISSION, resource_ids=resource_ids, resource_types=resource_types, user_ids=[instance.id], db_session=db_session, ) for resource in instance.resources: perms.append( PermissionTuple( instance, ALL_PERMISSIONS, "user", None, resource, True, True ) ) for group in cls.groups_with_resources(instance): for resource in group.resources: perms.append( PermissionTuple( instance, ALL_PERMISSIONS, "group", group, resource, True, True ) ) return perms @classmethod def gravatar_url(cls, instance, default="mm", **kwargs): """ returns user gravatar url :param instance: :param default: :param kwargs: :return: """ # construct the url hash = hashlib.md5(instance.email.encode("utf8").lower()).hexdigest() if "d" not in kwargs: kwargs["d"] = default params = "&".join( [ six.moves.urllib.parse.urlencode({key: value}) for key, value in kwargs.items() ] ) return "https://secure.gravatar.com/avatar/{}?{}".format(hash, params) @classmethod def set_password(cls, instance, raw_password): """ sets new password on a user using password manager :param instance: :param raw_password: :return: """ # support API for both passlib 1.x and 2.x hash_callable = getattr( instance.passwordmanager, "hash", instance.passwordmanager.encrypt ) password = hash_callable(raw_password) if six.PY2: instance.user_password = password.decode("utf8") else: instance.user_password = password cls.regenerate_security_code(instance) @classmethod def check_password(cls, instance, raw_password, enable_hash_migration=True): """ checks string with users password hash using password manager :param instance: :param raw_password: :param enable_hash_migration: if legacy hashes should be migrated :return: """ verified, replacement_hash = instance.passwordmanager.verify_and_update( raw_password, instance.user_password ) if enable_hash_migration and replacement_hash: if six.PY2: instance.user_password = replacement_hash.decode("utf8") else: instance.user_password = replacement_hash return verified @classmethod def generate_random_pass(cls, chars=7): """ generates random string of fixed length :param chars: :return: """ return cls.generate_random_string(chars) @classmethod def regenerate_security_code(cls, instance): """ generates new security code :param instance: :return: """ instance.security_code = cls.generate_random_string(64) @staticmethod def generate_random_string(chars=7): """ :param chars: :return: """ return generate_random_string(chars) @classmethod def by_id(cls, user_id, db_session=None): """ fetch user by user id :param user_id: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query.filter(cls.model.id == user_id) query = query.options(sa.orm.eagerload("groups")) return query.first() @classmethod def by_user_name(cls, user_name, db_session=None): """ fetch user by user name :param user_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query.filter( sa.func.lower(cls.model.user_name) == (user_name or "").lower() ) query = query.options(sa.orm.eagerload("groups")) return query.first() @classmethod def by_user_name_and_security_code(cls, user_name, security_code, db_session=None): """ fetch user objects by user name and security code :param user_name: :param security_code: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query.filter( sa.func.lower(cls.model.user_name) == (user_name or "").lower() ) query = query.filter(cls.model.security_code == security_code) return query.first() @classmethod def by_user_names(cls, user_names, db_session=None): """ fetch user objects by user names :param user_names: :param db_session: :return: """ user_names = [(name or "").lower() for name in user_names] db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query.filter(sa.func.lower(cls.model.user_name).in_(user_names)) # q = q.options(sa.orm.eagerload(cls.groups)) return query @classmethod def user_names_like(cls, user_name, db_session=None): """ fetch users with similar names using LIKE clause :param user_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query.filter( sa.func.lower(cls.model.user_name).like((user_name or "").lower()) ) query = query.order_by(cls.model.user_name) # q = q.options(sa.orm.eagerload('groups')) return query @classmethod def by_email(cls, email, db_session=None): """ fetch user object by email :param email: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter( sa.func.lower(cls.model.email) == (email or "").lower() ) query = query.options(sa.orm.eagerload("groups")) return query.first() @classmethod def by_email_and_username(cls, email, user_name, db_session=None): """ fetch user object by email and username :param email: :param user_name: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model).filter(cls.model.email == email) query = query.filter( sa.func.lower(cls.model.user_name) == (user_name or "").lower() ) query = query.options(sa.orm.eagerload("groups")) return query.first() @classmethod def users_for_perms(cls, perm_names, db_session=None): """ return users hat have one of given permissions :param perm_names: :param db_session: :return: """ db_session = get_db_session(db_session) query = db_session.query(cls.model) query = query.filter( cls.models_proxy.User.id == cls.models_proxy.UserGroup.user_id ) query = query.filter( cls.models_proxy.UserGroup.group_id == cls.models_proxy.GroupPermission.group_id ) query = query.filter(cls.models_proxy.GroupPermission.perm_name.in_(perm_names)) query2 = db_session.query(cls.model) query2 = query2.filter( cls.models_proxy.User.id == cls.models_proxy.UserPermission.user_id ) query2 = query2.filter( cls.models_proxy.UserPermission.perm_name.in_(perm_names) ) users = query.union(query2).order_by(cls.model.id) return users
ziggurat-foundations
/ziggurat_foundations-0.9.1.tar.gz/ziggurat_foundations-0.9.1/ziggurat_foundations/models/services/user.py
user.py
from __future__ import unicode_literals import importlib import logging from pyramid.security import remember, forget from ziggurat_foundations.models.base import get_db_session from ziggurat_foundations.models.services.user import UserService CONFIG_KEY = "ziggurat_foundations" log = logging.getLogger(__name__) class ZigguratSignInSuccess(object): def __contains__(self, other): return True def __init__(self, headers, came_from, user): self.headers = headers self.came_from = came_from self.user = user class ZigguratSignInBadAuth(object): def __contains__(self, other): return False def __init__(self, headers, came_from): self.headers = headers self.came_from = came_from class ZigguratSignOut(object): def __contains__(self, other): return True def __init__(self, headers): self.headers = headers def includeme(config): settings = config.registry.settings sign_in_path = settings.get("%s.sign_in.sign_in_pattern" % CONFIG_KEY, "/sign_in") sign_out_path = settings.get( "%s.sign_in.sign_out_pattern" % CONFIG_KEY, "/sign_out" ) session_provider_callable_config = settings.get( "%s.session_provider_callable" % CONFIG_KEY ) signin_came_from_key = settings.get( "%s.sign_in.came_from_key" % CONFIG_KEY, "came_from" ) signin_username_key = settings.get("%s.sign_in.username_key" % CONFIG_KEY, "login") signin_password_key = settings.get( "%s.sign_in.password_key" % CONFIG_KEY, "password" ) if not session_provider_callable_config: def session_provider_callable(request): return get_db_session() else: if callable(session_provider_callable_config): session_provider_callable = session_provider_callable_config else: parts = session_provider_callable_config.split(":") _tmp = importlib.import_module(parts[0]) session_provider_callable = getattr(_tmp, parts[1]) endpoint = ZigguratSignInProvider( settings=settings, session_getter=session_provider_callable, signin_came_from_key=signin_came_from_key, signin_username_key=signin_username_key, signin_password_key=signin_password_key, ) config.add_route( "ziggurat.routes.sign_in", sign_in_path, use_global_views=True, factory=endpoint.sign_in, ) config.add_route( "ziggurat.routes.sign_out", sign_out_path, use_global_views=True, factory=endpoint.sign_out, ) class ZigguratSignInProvider(object): def __init__(self, *args, **kwargs): for k, v in kwargs.items(): setattr(self, k, v) def sign_in(self, request): came_from = request.params.get(self.signin_came_from_key, "/") db_session = self.session_getter(request) user = UserService.by_user_name( request.params.get(self.signin_username_key), db_session=db_session ) if user is None: # if no result, test to see if email exists user = UserService.by_email( request.params.get(self.signin_username_key), db_session=db_session ) if user: password = request.params.get(self.signin_password_key) if UserService.check_password(user, password): headers = remember(request, user.id) return ZigguratSignInSuccess( headers=headers, came_from=came_from, user=user ) headers = forget(request) return ZigguratSignInBadAuth(headers=headers, came_from=came_from) def sign_out(self, request): headers = forget(request) return ZigguratSignOut(headers=headers) def session_getter(self, request): raise NotImplementedError()
ziggurat-foundations
/ziggurat_foundations-0.9.1.tar.gz/ziggurat_foundations-0.9.1/ziggurat_foundations/ext/pyramid/sign_in.py
sign_in.py
import contextlib import subprocess import sys import sysconfig import textwrap from typing import TextIO from pydust import config PYVER_MINOR = ".".join(str(v) for v in sys.version_info[:2]) PYVER_HEX = f"{sys.hexversion:#010x}" PYINC = sysconfig.get_path("include") PYLIB = sysconfig.get_config_var("LIBDIR") def zig_build(argv: list[str], build_zig="build.zig"): generate_build_zig(build_zig) subprocess.run( [sys.executable, "-m", "ziglang", "build", "--build-file", build_zig] + argv, check=True, ) def generate_build_zig(build_zig_file): """Generate the build.zig file for the current pyproject.toml. Initially we were calling `zig build-lib` directly, and this worked fine except it meant we would need to roll our own caching and figure out how to convince ZLS to pick up our dependencies. It's therefore easier, at least for now, to generate a build.zig in the project root and add it to the .gitignore. This means ZLS works as expected, we can leverage zig build caching, and the user can inspect the generated file to assist with debugging. """ conf = config.load() with open(build_zig_file, "w+") as f: b = Writer(f) b.writeln('const std = @import("std");') b.writeln() # We choose to ship Pydust source code inside our PyPi package. This means the that once the PyPi package has # been downloaded there are no further requests out to the internet. # # As a result of this though, we need some way to locate the source code. We can't use a reference to the # currently running pydust, since that could be inside a temporary build env which won't exist later when the # user is developing locally. Therefore, we defer resolving the path until the build.zig is invoked by shelling # out to Python. # # We also want to avoid creating a pydust module (and instead prefer anonymous modules) so that we can populate # a separate pyconf options object for each Python extension module. b.write( """ fn getPydustRootPath(allocator: std.mem.Allocator) ![]const u8 { const includeResult = try std.process.Child.exec(.{ .allocator = allocator, .argv = &.{ "python", "-c", \\\\import os \\\\import pydust \\\\print(os.path.join(os.path.dirname(pydust.__file__), 'src', 'pydust.zig'), end='') \\\\ }, }); allocator.free(includeResult.stderr); return includeResult.stdout; } """ ) b.writeln() with b.block("pub fn build(b: *std.Build) void"): b.write( """ const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const test_step = b.step("test", "Run library tests"); const pydust = getPydustRootPath(b.allocator) catch @panic("Failed to locate Pydust source code"); """ ) for ext_module in conf.ext_modules: # TODO(ngates): fix the out filename for non-limited modules assert ext_module.limited_api, "Only limited_api is supported for now" # For each module, we generate some options, a library, as well as a test runner. with b.block(): b.write( f""" // For each Python ext_module, generate a shared library and test runner. const pyconf = b.addOptions(); pyconf.addOption([:0]const u8, "module_name", "{ext_module.libname}"); pyconf.addOption(bool, "limited_api", {str(ext_module.limited_api).lower()}); pyconf.addOption([:0]const u8, "hexversion", "{PYVER_HEX}"); const lib{ext_module.libname} = b.addSharedLibrary(.{{ .name = "{ext_module.libname}", .root_source_file = .{{ .path = "{ext_module.root}" }}, .main_pkg_path = .{{ .path = "{conf.root}" }}, .target = target, .optimize = optimize, }}); configurePythonInclude(pydust, lib{ext_module.libname}, pyconf); // Install the shared library within the source tree const install{ext_module.libname} = b.addInstallFileWithDir( lib{ext_module.libname}.getEmittedBin(), .{{ .custom = ".." }}, // Relative to project root: zig-out/../ "{ext_module.install_path}", ); b.getInstallStep().dependOn(&install{ext_module.libname}.step); const test{ext_module.libname} = b.addTest(.{{ .root_source_file = .{{ .path = "{ext_module.root}" }}, .main_pkg_path = .{{ .path = "{conf.root}" }}, .target = target, .optimize = optimize, }}); configurePythonRuntime(pydust, test{ext_module.libname}, pyconf); const run_test{ext_module.libname} = b.addRunArtifact(test{ext_module.libname}); test_step.dependOn(&run_test{ext_module.libname}.step); """ ) b.write( f""" // Option for emitting test binary based on the given root source. This can be helpful for debugging. const debugRoot = b.option( []const u8, "debug-root", "The root path of a file emitted as a binary for use with the debugger", ); if (debugRoot) |root| {{ const pyconf = b.addOptions(); pyconf.addOption([:0]const u8, "module_name", "debug"); pyconf.addOption(bool, "limited_api", false); pyconf.addOption([:0]const u8, "hexversion", "{PYVER_HEX}"); const testdebug = b.addTest(.{{ .root_source_file = .{{ .path = root }}, .main_pkg_path = .{{ .path = "{conf.root}" }}, .target = target, .optimize = optimize, }}); configurePythonRuntime(pydust, testdebug, pyconf); const debugBin = b.addInstallBinFile(testdebug.getEmittedBin(), "debug.bin"); b.getInstallStep().dependOn(&debugBin.step); }} """ ) b.write( f""" fn configurePythonInclude( pydust: []const u8, compile: *std.Build.CompileStep, pyconf: *std.Build.Step.Options, ) void {{ compile.addAnonymousModule("pydust", .{{ .source_file = .{{ .path = pydust }}, .dependencies = &.{{.{{ .name = "pyconf", .module = pyconf.createModule() }}}}, }}); compile.addIncludePath(.{{ .path = "{PYINC}" }}); compile.linkLibC(); compile.linker_allow_shlib_undefined = true; }} fn configurePythonRuntime( pydust: []const u8, compile: *std.Build.CompileStep, pyconf: *std.Build.Step.Options ) void {{ configurePythonInclude(pydust, compile, pyconf); compile.linkSystemLibrary("python{PYVER_MINOR}"); compile.addLibraryPath(.{{ .path = "{PYLIB}" }}); }} """ ) class Writer: def __init__(self, fileobj: TextIO) -> None: self.f = fileobj self._indent = 0 @contextlib.contextmanager def indent(self): self._indent += 4 yield self._indent -= 4 @contextlib.contextmanager def block(self, text: str = ""): self.write(text) self.writeln(" {") with self.indent(): yield self.writeln() self.writeln("}") self.writeln() def write(self, text: str): if "\n" in text: text = textwrap.dedent(text).strip() + "\n\n" self.f.write(textwrap.indent(text, self._indent * " ")) def writeln(self, text: str = ""): self.write(text) self.f.write("\n") if __name__ == "__main__": generate_build_zig("test.build.zig")
ziggy-pydust
/ziggy_pydust-0.2.1.tar.gz/ziggy_pydust-0.2.1/pydust/buildzig.py
buildzig.py
# zignal This is a python audio signal processing library. Python 2 is no longer supported, the last version to support python 2 is 0.2.0 ## Example usage >>> import zignal >>> >>> x = zignal.Sinetone(fs=44100, f0=997, duration=0.1, gaindb=-20) >>> print(x) ======================================= classname : Sinetone sample rate : 44100.0 [Hz] channels : 1 duration : 0.100 [s] datatype : float64 samples per ch : 4410 data size : 0.034 [Mb] has comment : no peak : [ 0.1] RMS : [ 0.0707] crestfactor : [ 1.4147] -----------------:--------------------- frequency : 997.0 [Hz] phase : 0.0 [deg] -----------------:--------------------- >>> x.fade_out(millisec=10) >>> x.convert_to_float(targetbits=32) >>> x.write_wav_file("sinetone.wav") >>> x.plot() >>> x.plot_fft() >>> >>> f = zignal.filters.biquads.RBJ(filtertype="peak", gaindb=-6, f0=997, Q=0.707, fs=96000) >>> print(f) ======================================= classname : RBJ sample rate : 96000.0 [Hz] feedforward (B) : [ 0.96949457 -1.87369167 0.90819329] feedback (A) : [ 1. -1.87369167 0.87768787] number of zeros : 2 number of poles : 2 minimum phase? : Yes -----------------:--------------------- stable? : Yes type : peak gain : -6.00 [dB] f0 : 997.0 [Hz] Q : 0.7070 >>> f.plot_mag_phase() >>> f.plot_pole_zero() >>> See the examples folder for more examples. ## Requirements This library relies on numpy, scipy, matplotlib and optionally pyaudio (and nose for unit testing). It is recommended to create a virtual environment and let pip install the dependencies automatically. python3 -m venv <name-of-virtualenv> . <name-of-virtualenv>/bin/activate pip install zignal Optionally, to be able to use a soundcard, first install the python development headers and the portaudio development files. On debian/ubuntu, sudo apt install python3-dev portaudio19-dev then run pip install zignal[sndcard] which will automatically build the portaudio library and then pyaudio. ## Local development Create a python3 virtualenv and install from the requirements.txt file to make the zignal library editable. Note that the python development headers (python3-dev) and portaudio19-dev must be installed first. python3 -m venv zignaldev . zignaldev/bin/activate pip install -r requirements.txt ## Design goals 1. Readability over efficiency. This is a python library for development and understanding of audio signal processing. 2. The initial goal is to write the functionality in pure python, with the use of numpy, scipy and matplotlib. See rule 1. If efficiency becomes an issue a c/c++ library might be implemented but the pure python code must remain the default choice. 3. Design for non real-time processing. Functionality to do real-time processing can be added if it does not break rule 1. 4. Self documentation. The code should aim to be well documented, in the source code itself.
zignal
/zignal-0.6.0.tar.gz/zignal-0.6.0/README.md
README.md
# zignor-python Ziggurat normal random number generator ported to Python ## Requirement `NumPy` installation is required. Python 3 compatible. ## Installation To install, run `python setup.py install` or you can install from PyPI: `pip install zignor` If you are running Windows and don't have MSVC compiler installed, a pre-built distribution on Python 3.5 is given in `dist` folder. ## Usage It will automatically import `NumPy`, so you can just use ``` import zignor zignor.randn(10) ``` or ``` zignor.randn(3, 5) ``` to generate a matrix of 3 by 5. ## More functions This module includes two implementations. One is an slightly modified implementation of the original Ziggurat method ([http://www.jstatsoft.org/article/downloadSuppFile/v005i08/rnorrexp.c](http://www.jstatsoft.org/article/downloadSuppFile/v005i08/rnorrexp.c)). It uses SHR3 as the RNG for uniform distribution. This is the code behind `zignor.randn()` and `zignor.rnor()` method, and it is the faster of the two. We also included a `zignor.rexp()` for generation exponential distribution. The other implementation is the VIZIGNOR implementation by Doornik, J.A. It improves the original method and uses MWC8222 RNG to enable the method to pass some more tests. This method can be called by `zignor.zignor()`. ## References 1. G. Marsaglia and W.W. Tsang: The Ziggurat Method for Generating Random Variables. *Journal of Statistical Software*, vol. 5, no. 8, pp. 1–7, 2000. 2. Doornik, J.A. (2005), "An Improved Ziggurat Method to Generate Normal Random Samples", mimeo, Nuffield College, University of Oxford.
zignor
/zignor-0.1.8.zip/zignor-0.1.8/README.md
README.md
import enum import zigpy.config import zigpy.types as t class Repr: def __repr__(self) -> str: r = "<%s " % (self.__class__.__name__,) r += " ".join(["%s=%s" % (f, getattr(self, f, None)) for f in vars(self)]) r += ">" return r class Timeouts: SREQ = 6000 reset = 30000 default = 10000 class AddressMode(t.uint8_t, enum.Enum): ADDR_NOT_PRESENT = 0 ADDR_GROUP = 1 ADDR_16BIT = 2 ADDR_64BIT = 3 ADDR_BROADCAST = 15 class LedMode(t.uint8_t, enum.Enum): Off = 0 On = 1 Blink = 2 Flash = 3 Toggle = 4 class ZnpVersion(t.uint8_t, enum.Enum): zStack12 = 0 zStack3x0 = 1 zStack30x = 2 class CommandType(t.uint8_t, enum.Enum): POLL = 0 SREQ = 1 AREQ = 2 SRSP = 3 class Subsystem(t.uint8_t, enum.Enum): RESERVED = 0 SYS = 1 MAC = 2 NWK = 3 AF = 4 ZDO = 5 SAPI = 6 UTIL = 7 DEBUG = 8 APP = 9 APP_CNF = 15 GREENPOWER = 21 class ParameterType(t.uint8_t, enum.Enum): UINT8 = 0 UINT16 = 1 UINT32 = 2 IEEEADDR = 3 BUFFER = 4 BUFFER8 = 5 BUFFER16 = 6 BUFFER18 = 7 BUFFER32 = 8 BUFFER42 = 9 BUFFER100 = 10 LIST_UINT8 = 11 LIST_UINT16 = 12 LIST_ROUTING_TABLE = 13 LIST_BIND_TABLE = 14 LIST_NEIGHBOR_LQI = 15 LIST_NETWORK = 16 LIST_ASSOC_DEV = 17 INT8 = 18 def is_buffer(type): return ( type == ParameterType.BUFFER or type == ParameterType.BUFFER8 or type == ParameterType.BUFFER16 or type == ParameterType.BUFFER18 or type == ParameterType.BUFFER32 or type == ParameterType.BUFFER42 or type == ParameterType.BUFFER100 ) class NetworkOptions(Repr): networkKey: t.KeyData panID: t.PanId extendedPanID: t.ExtendedPanId channelList: t.Channels def __init__(self, config: zigpy.config.SCHEMA_NETWORK) -> None: self.networkKeyDistribute = False self.networkKey = config[zigpy.config.CONF_NWK_KEY] or ( zigpy.config.cv_key([1, 3, 5, 7, 9, 11, 13, 15, 0, 2, 4, 6, 8, 10, 12, 13]) ) self.panID = config[zigpy.config.CONF_NWK_PAN_ID] or t.PanId(0x1A62) self.extendedPanID = config[zigpy.config.CONF_NWK_EXTENDED_PAN_ID] or ( t.ExtendedPanId([0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD, 0xDD]) ) self.channelList = ( config[zigpy.config.CONF_NWK_CHANNELS] or t.Channels.from_channel_list([11]) )
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/types.py
types.py
from zigpy_cc.types import Subsystem, CommandType, ParameterType name = "name" ID = "ID" request = "request" response = "response" parameterType = "parameterType" type = "type" Definition = { Subsystem.SYS: [ { name: "resetReq", ID: 0, type: CommandType.AREQ, request: [{name: "type", parameterType: ParameterType.UINT8}], }, { name: "ping", ID: 1, type: CommandType.SREQ, request: [], response: [{name: "capabilities", parameterType: ParameterType.UINT16}], }, { name: "version", ID: 2, type: CommandType.SREQ, request: [], response: [ {name: "transportrev", parameterType: ParameterType.UINT8}, {name: "product", parameterType: ParameterType.UINT8}, {name: "majorrel", parameterType: ParameterType.UINT8}, {name: "minorrel", parameterType: ParameterType.UINT8}, {name: "maintrel", parameterType: ParameterType.UINT8}, {name: "revision", parameterType: ParameterType.UINT32}, ], }, { name: "setExtAddr", ID: 3, type: CommandType.SREQ, request: [{name: "extaddress", parameterType: ParameterType.IEEEADDR}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "getExtAddr", ID: 4, type: CommandType.SREQ, request: [], response: [{name: "extaddress", parameterType: ParameterType.IEEEADDR}], }, { name: "ramRead", ID: 5, type: CommandType.SREQ, request: [ {name: "address", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], }, { name: "ramWrite", ID: 6, type: CommandType.SREQ, request: [ {name: "address", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "osalNvItemInit", ID: 7, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT16}, {name: "initlen", parameterType: ParameterType.UINT8}, {name: "initvalue", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "osalNvRead", ID: 8, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT16}, {name: "offset", parameterType: ParameterType.UINT8}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], }, { name: "osalNvWrite", ID: 9, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT16}, {name: "offset", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "osalStartTimer", ID: 10, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT8}, {name: "timeout", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "osalStopTimer", ID: 11, type: CommandType.SREQ, request: [{name: "id", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "random", ID: 12, type: CommandType.SREQ, request: [], response: [{name: "value", parameterType: ParameterType.UINT16}], }, { name: "adcRead", ID: 13, type: CommandType.SREQ, request: [ {name: "channel", parameterType: ParameterType.UINT8}, {name: "resolution", parameterType: ParameterType.UINT8}, ], response: [{name: "value", parameterType: ParameterType.UINT16}], }, { name: "gpio", ID: 14, type: CommandType.SREQ, request: [ {name: "operation", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.UINT8}, ], response: [{name: "value", parameterType: ParameterType.UINT8}], }, { name: "stackTune", ID: 15, type: CommandType.SREQ, request: [ {name: "operation", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.INT8}, ], response: [{name: "value", parameterType: ParameterType.UINT8}], }, { name: "setTime", ID: 16, type: CommandType.SREQ, request: [ {name: "utc", parameterType: ParameterType.UINT32}, {name: "hour", parameterType: ParameterType.UINT8}, {name: "minute", parameterType: ParameterType.UINT8}, {name: "second", parameterType: ParameterType.UINT8}, {name: "month", parameterType: ParameterType.UINT8}, {name: "day", parameterType: ParameterType.UINT8}, {name: "year", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "getTime", ID: 17, type: CommandType.SREQ, request: [], response: [ {name: "utc", parameterType: ParameterType.UINT32}, {name: "hour", parameterType: ParameterType.UINT8}, {name: "minute", parameterType: ParameterType.UINT8}, {name: "second", parameterType: ParameterType.UINT8}, {name: "month", parameterType: ParameterType.UINT8}, {name: "day", parameterType: ParameterType.UINT8}, {name: "year", parameterType: ParameterType.UINT16}, ], }, { name: "osalNvDelete", ID: 18, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "osalNvLength", ID: 19, type: CommandType.SREQ, request: [{name: "id", parameterType: ParameterType.UINT16}], response: [{name: "length", parameterType: ParameterType.UINT16}], }, { name: "setTxPower", ID: 20, type: CommandType.SREQ, request: [{name: "level", parameterType: ParameterType.UINT8}], response: [{name: "txpower", parameterType: ParameterType.UINT8}], }, { name: "jammerParameters", ID: 21, type: CommandType.SREQ, request: [ {name: "jmrcntievents", parameterType: ParameterType.UINT16}, {name: "jmrhinoiselvl", parameterType: ParameterType.UINT8}, {name: "jmrdetectperiod", parameterType: ParameterType.UINT32}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "snifferParameters", ID: 22, type: CommandType.SREQ, request: [{name: "param", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "zdiagsInitStats", ID: 23, type: CommandType.SREQ, request: [], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "zdiagsClearStats", ID: 24, type: CommandType.SREQ, request: [{name: "clearnv", parameterType: ParameterType.UINT8}], response: [{name: "sysclock", parameterType: ParameterType.UINT32}], }, { name: "zdiagsGetStats", ID: 25, type: CommandType.SREQ, request: [{name: "attributeid", parameterType: ParameterType.UINT16}], response: [{name: "attributevalue", parameterType: ParameterType.UINT32}], }, { name: "zdiagsRestoreStatsNv", ID: 26, type: CommandType.SREQ, request: [], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "zdiagsSaveStatsToNv", ID: 27, type: CommandType.SREQ, request: [], response: [{name: "sysclock", parameterType: ParameterType.UINT32}], }, { name: "osalNvReadExt", ID: 28, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT16}, {name: "offset", parameterType: ParameterType.UINT16}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], }, { name: "osalNvWriteExt", ID: 29, type: CommandType.SREQ, request: [ {name: "id", parameterType: ParameterType.UINT16}, {name: "offset", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT16}, {name: "value", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nvCreate", ID: 48, type: CommandType.SREQ, request: [ {name: "sysid", parameterType: ParameterType.UINT8}, {name: "itemid", parameterType: ParameterType.UINT16}, {name: "subid", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT32}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nvDelete", ID: 49, type: CommandType.SREQ, request: [ {name: "sysid", parameterType: ParameterType.UINT8}, {name: "itemid", parameterType: ParameterType.UINT16}, {name: "subid", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nvLength", ID: 50, type: CommandType.SREQ, request: [ {name: "sysid", parameterType: ParameterType.UINT8}, {name: "itemid", parameterType: ParameterType.UINT16}, {name: "subid", parameterType: ParameterType.UINT16}, ], response: [{name: "len", parameterType: ParameterType.UINT8}], }, { name: "nvRead", ID: 51, type: CommandType.SREQ, request: [ {name: "sysid", parameterType: ParameterType.UINT8}, {name: "itemid", parameterType: ParameterType.UINT16}, {name: "subid", parameterType: ParameterType.UINT16}, {name: "offset", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], }, { name: "nvWrite", ID: 52, type: CommandType.SREQ, request: [ {name: "sysid", parameterType: ParameterType.UINT8}, {name: "itemid", parameterType: ParameterType.UINT16}, {name: "subid", parameterType: ParameterType.UINT16}, {name: "offset", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nvUpdate", ID: 53, type: CommandType.SREQ, request: [ {name: "sysid", parameterType: ParameterType.UINT8}, {name: "itemid", parameterType: ParameterType.UINT16}, {name: "subid", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nvCompact", ID: 54, type: CommandType.SREQ, request: [{name: "threshold", parameterType: ParameterType.UINT16}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "resetInd", ID: 128, type: CommandType.AREQ, request: [ {name: "reason", parameterType: ParameterType.UINT8}, {name: "transportrev", parameterType: ParameterType.UINT8}, {name: "productid", parameterType: ParameterType.UINT8}, {name: "majorrel", parameterType: ParameterType.UINT8}, {name: "minorrel", parameterType: ParameterType.UINT8}, {name: "hwrev", parameterType: ParameterType.UINT8}, ], }, { name: "osalTimerExpired", ID: 129, type: CommandType.AREQ, request: [{name: "id", parameterType: ParameterType.UINT8}], }, { name: "jammerInd", ID: 130, type: CommandType.AREQ, request: [{name: "jammerind", parameterType: ParameterType.UINT8}], }, ], Subsystem.MAC: [ { name: "resetReq", ID: 1, type: CommandType.SREQ, request: [{name: "setdefault", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "init", ID: 2, type: CommandType.SREQ, request: [], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "startReq", ID: 3, type: CommandType.SREQ, request: [ {name: "starttime", parameterType: ParameterType.UINT32}, {name: "panid", parameterType: ParameterType.UINT16}, {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "channelpage", parameterType: ParameterType.UINT8}, {name: "beaconorder", parameterType: ParameterType.UINT8}, {name: "superframeorder", parameterType: ParameterType.UINT8}, {name: "pancoordinator", parameterType: ParameterType.UINT8}, {name: "batterylifeext", parameterType: ParameterType.UINT8}, {name: "coordrealignment", parameterType: ParameterType.UINT8}, {name: "realignkeysource", parameterType: ParameterType.BUFFER}, {name: "realignsecuritylevel", parameterType: ParameterType.UINT8}, {name: "realignkeyidmode", parameterType: ParameterType.UINT8}, {name: "realignkeyindex", parameterType: ParameterType.UINT8}, {name: "beaconkeysource", parameterType: ParameterType.BUFFER}, {name: "beaconsecuritylevel", parameterType: ParameterType.UINT8}, {name: "beaconkeyidmode", parameterType: ParameterType.UINT8}, {name: "beaconkeyindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "syncReq", ID: 4, type: CommandType.SREQ, request: [ {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "channelpage", parameterType: ParameterType.UINT8}, {name: "trackbeacon", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "dataReq", ID: 5, type: CommandType.SREQ, request: [ {name: "destaddressmode", parameterType: ParameterType.UINT8}, {name: "destaddress", parameterType: ParameterType.IEEEADDR}, {name: "destpanid", parameterType: ParameterType.UINT16}, {name: "srcaddressmode", parameterType: ParameterType.UINT8}, {name: "handle", parameterType: ParameterType.UINT8}, {name: "txoption", parameterType: ParameterType.UINT8}, {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "power", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, {name: "msdulength", parameterType: ParameterType.UINT8}, {name: "msdu", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "associateReq", ID: 6, type: CommandType.SREQ, request: [ {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "channelpage", parameterType: ParameterType.UINT8}, {name: "coordaddressmode", parameterType: ParameterType.UINT8}, {name: "coordaddress", parameterType: ParameterType.IEEEADDR}, {name: "coordpanid", parameterType: ParameterType.UINT16}, {name: "capabilityinformation", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "disassociateReq", ID: 7, type: CommandType.SREQ, request: [ {name: "deviceaddressmode", parameterType: ParameterType.UINT8}, {name: "deviceaddress", parameterType: ParameterType.IEEEADDR}, {name: "devicepanid", parameterType: ParameterType.UINT16}, {name: "disassociatereason", parameterType: ParameterType.UINT8}, {name: "txindirect", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "getReq", ID: 8, type: CommandType.SREQ, request: [{name: "attribute", parameterType: ParameterType.UINT8}], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER16}, ], }, { name: "setReq", ID: 9, type: CommandType.SREQ, request: [ {name: "attribute", parameterType: ParameterType.UINT8}, {name: "attributevalue", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "scanReq", ID: 12, type: CommandType.SREQ, request: [ {name: "scanchannels", parameterType: ParameterType.UINT32}, {name: "scantype", parameterType: ParameterType.UINT8}, {name: "scanduration", parameterType: ParameterType.UINT8}, {name: "channelpage", parameterType: ParameterType.UINT8}, {name: "maxresults", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "pollReq", ID: 13, type: CommandType.SREQ, request: [ {name: "coordaddressmode", parameterType: ParameterType.UINT8}, {name: "coordaddress", parameterType: ParameterType.IEEEADDR}, {name: "coordpanid", parameterType: ParameterType.UINT16}, {name: "keysource", parameterType: ParameterType.BUFFER}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "purgeReq", ID: 14, type: CommandType.SREQ, request: [{name: "msduhandle", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "setRxGainReq", ID: 15, type: CommandType.SREQ, request: [{name: "mode", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "securityGetReq", ID: 48, type: CommandType.SREQ, request: [ {name: "attribute", parameterType: ParameterType.UINT8}, {name: "index1", parameterType: ParameterType.UINT8}, {name: "index2", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "securitySetReq", ID: 49, type: CommandType.SREQ, request: [ {name: "attribute", parameterType: ParameterType.UINT8}, {name: "attributevalue", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "associateRsp", ID: 80, type: CommandType.SREQ, request: [ {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "assocshortaddress", parameterType: ParameterType.UINT16}, {name: "assocstatus", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "orphanRsp", ID: 81, type: CommandType.SREQ, request: [ {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "assocshortaddress", parameterType: ParameterType.UINT16}, {name: "associatedmember", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "syncLossInd", ID: 128, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "panid", parameterType: ParameterType.UINT16}, {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "channelpage", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], }, { name: "associateInd", ID: 129, type: CommandType.AREQ, request: [ {name: "deviceextendedaddress", parameterType: ParameterType.IEEEADDR}, {name: "capabilities", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], }, { name: "associateCnf", ID: 130, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "deviceshortaddress", parameterType: ParameterType.UINT16}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], }, { name: "beaconNotifyInd", ID: 131, type: CommandType.AREQ, request: [ {name: "bsn", parameterType: ParameterType.UINT8}, {name: "timestamp", parameterType: ParameterType.UINT32}, {name: "coordinatoraddressmode", parameterType: ParameterType.UINT8}, { name: "coordinatorextendedaddress", parameterType: ParameterType.IEEEADDR, }, {name: "panid", parameterType: ParameterType.UINT16}, {name: "superframespec", parameterType: ParameterType.UINT16}, {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "gtspermit", parameterType: ParameterType.UINT8}, {name: "linkquality", parameterType: ParameterType.UINT8}, {name: "securityfailure", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, {name: "pendingaddrspec", parameterType: ParameterType.UINT8}, {name: "addresslist", parameterType: ParameterType.BUFFER32}, {name: "sdulength", parameterType: ParameterType.UINT8}, {name: "nsdu", parameterType: ParameterType.BUFFER}, ], }, { name: "dataCnf", ID: 132, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "handle", parameterType: ParameterType.UINT8}, {name: "timestamp", parameterType: ParameterType.UINT32}, {name: "timestamp2", parameterType: ParameterType.UINT16}, ], }, { name: "dataInd", ID: 133, type: CommandType.AREQ, request: [ {name: "srcaddrmode", parameterType: ParameterType.UINT8}, {name: "srcaddr", parameterType: ParameterType.IEEEADDR}, {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "dstaddr", parameterType: ParameterType.IEEEADDR}, {name: "timestamp", parameterType: ParameterType.UINT32}, {name: "timestamp2", parameterType: ParameterType.UINT16}, {name: "srcpanid", parameterType: ParameterType.UINT16}, {name: "dstpanid", parameterType: ParameterType.UINT16}, {name: "linkquality", parameterType: ParameterType.UINT8}, {name: "correlation", parameterType: ParameterType.UINT8}, {name: "rssi", parameterType: ParameterType.UINT8}, {name: "dsn", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, {name: "length", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], }, { name: "disassociateInd", ID: 134, type: CommandType.AREQ, request: [ {name: "extendedaddress", parameterType: ParameterType.IEEEADDR}, {name: "disassociatereason", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], }, { name: "disassociateCnf", ID: 135, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "deviceaddrmode", parameterType: ParameterType.UINT8}, {name: "deviceaddr", parameterType: ParameterType.IEEEADDR}, {name: "devicepanid", parameterType: ParameterType.UINT16}, ], }, { name: "orphanInd", ID: 138, type: CommandType.AREQ, request: [ {name: "extendedaddr", parameterType: ParameterType.IEEEADDR}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], }, { name: "pollCnf", ID: 139, type: CommandType.AREQ, request: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "scanCnf", ID: 140, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ed", parameterType: ParameterType.UINT8}, {name: "scantype", parameterType: ParameterType.UINT8}, {name: "channelpage", parameterType: ParameterType.UINT8}, {name: "unscannedchannellist", parameterType: ParameterType.UINT32}, {name: "resultlistcount", parameterType: ParameterType.UINT8}, {name: "resultlistmaxlength", parameterType: ParameterType.UINT8}, {name: "resultlist", parameterType: ParameterType.BUFFER}, ], }, { name: "commStatusInd", ID: 141, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "srcaddrmode", parameterType: ParameterType.UINT8}, {name: "srcaddr", parameterType: ParameterType.IEEEADDR}, {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "dstaddr", parameterType: ParameterType.IEEEADDR}, {name: "devicepanid", parameterType: ParameterType.UINT16}, {name: "reason", parameterType: ParameterType.UINT8}, {name: "keysource", parameterType: ParameterType.BUFFER8}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "keyidmode", parameterType: ParameterType.UINT8}, {name: "keyindex", parameterType: ParameterType.UINT8}, ], }, { name: "startCnf", ID: 142, type: CommandType.AREQ, request: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "rxEnableCnf", ID: 143, type: CommandType.AREQ, request: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "purgeCnf", ID: 144, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "handle", parameterType: ParameterType.UINT8}, ], }, ], Subsystem.AF: [ { name: "register", ID: 0, type: CommandType.SREQ, request: [ {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "appprofid", parameterType: ParameterType.UINT16}, {name: "appdeviceid", parameterType: ParameterType.UINT16}, {name: "appdevver", parameterType: ParameterType.UINT8}, {name: "latencyreq", parameterType: ParameterType.UINT8}, {name: "appnuminclusters", parameterType: ParameterType.UINT8}, {name: "appinclusterlist", parameterType: ParameterType.LIST_UINT16}, {name: "appnumoutclusters", parameterType: ParameterType.UINT8}, {name: "appoutclusterlist", parameterType: ParameterType.LIST_UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "dataRequest", ID: 1, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "destendpoint", parameterType: ParameterType.UINT8}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "transid", parameterType: ParameterType.UINT8}, {name: "options", parameterType: ParameterType.UINT8}, {name: "radius", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "dataRequestExt", ID: 2, type: CommandType.SREQ, request: [ {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "dstaddr", parameterType: ParameterType.IEEEADDR}, {name: "destendpoint", parameterType: ParameterType.UINT8}, {name: "dstpanid", parameterType: ParameterType.UINT16}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "transid", parameterType: ParameterType.UINT8}, {name: "options", parameterType: ParameterType.UINT8}, {name: "radius", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT16}, {name: "data", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "dataRequestSrcRtg", ID: 3, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "destendpoint", parameterType: ParameterType.UINT8}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "transid", parameterType: ParameterType.UINT8}, {name: "options", parameterType: ParameterType.UINT8}, {name: "radius", parameterType: ParameterType.UINT8}, {name: "relaycount", parameterType: ParameterType.UINT8}, {name: "relaylist", parameterType: ParameterType.LIST_UINT16}, {name: "len", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "delete", ID: 4, type: CommandType.SREQ, request: [{name: "endpoint", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "interPanCtl", ID: 16, type: CommandType.SREQ, request: [ {name: "cmd", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "dataStore", ID: 17, type: CommandType.SREQ, request: [ {name: "index", parameterType: ParameterType.UINT16}, {name: "length", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "dataRetrieve", ID: 18, type: CommandType.SREQ, request: [ {name: "timestamp", parameterType: ParameterType.UINT32}, {name: "index", parameterType: ParameterType.UINT16}, {name: "length", parameterType: ParameterType.UINT8}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "length", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], }, { name: "apsfConfigSet", ID: 19, type: CommandType.SREQ, request: [ {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "framedelay", parameterType: ParameterType.UINT8}, {name: "windowsize", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "apsfConfigGet", ID: 20, type: CommandType.SREQ, request: [{name: "endpoint", parameterType: ParameterType.UINT8}], response: [ {name: "framedelay", parameterType: ParameterType.UINT8}, {name: "windowsize", parameterType: ParameterType.UINT8}, {name: "nomean", parameterType: ParameterType.UINT8}, ], }, { name: "dataConfirm", ID: 128, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "transid", parameterType: ParameterType.UINT8}, ], }, { name: "incomingMsg", ID: 129, type: CommandType.AREQ, request: [ {name: "groupid", parameterType: ParameterType.UINT16}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "dstendpoint", parameterType: ParameterType.UINT8}, {name: "wasbroadcast", parameterType: ParameterType.UINT8}, {name: "linkquality", parameterType: ParameterType.UINT8}, {name: "securityuse", parameterType: ParameterType.UINT8}, {name: "timestamp", parameterType: ParameterType.UINT32}, {name: "transseqnumber", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "data", parameterType: ParameterType.BUFFER}, ], }, { name: "incomingMsgExt", ID: 130, type: CommandType.AREQ, request: [ {name: "groupid", parameterType: ParameterType.UINT16}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "srcaddrmode", parameterType: ParameterType.UINT8}, {name: "srcaddr", parameterType: ParameterType.IEEEADDR}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "srcpanid", parameterType: ParameterType.UINT16}, {name: "dstendpoint", parameterType: ParameterType.UINT8}, {name: "wasbroadcast", parameterType: ParameterType.UINT8}, {name: "linkquality", parameterType: ParameterType.UINT8}, {name: "securityuse", parameterType: ParameterType.UINT8}, {name: "timestamp", parameterType: ParameterType.UINT32}, {name: "transseqnumber", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT16}, {name: "data", parameterType: ParameterType.BUFFER}, ], }, { name: "reflectError", ID: 131, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "transid", parameterType: ParameterType.UINT8}, {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "dstaddr", parameterType: ParameterType.UINT16}, ], }, ], Subsystem.ZDO: [ { name: "nwkAddrReq", ID: 0, type: CommandType.SREQ, request: [ {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "reqtype", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "ieeeAddrReq", ID: 1, type: CommandType.SREQ, request: [ {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "reqtype", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nodeDescReq", ID: 2, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "powerDescReq", ID: 3, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "simpleDescReq", ID: 4, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, {name: "endpoint", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "activeEpReq", ID: 5, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "matchDescReq", ID: 6, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, {name: "profileid", parameterType: ParameterType.UINT16}, {name: "numinclusters", parameterType: ParameterType.UINT8}, {name: "inclusterlist", parameterType: ParameterType.LIST_UINT16}, {name: "numoutclusters", parameterType: ParameterType.UINT8}, {name: "outclusterlist", parameterType: ParameterType.LIST_UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "complexDescReq", ID: 7, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "userDescReq", ID: 8, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "endDeviceAnnce", ID: 10, type: CommandType.SREQ, request: [ {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "capability", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "userDescSet", ID: 11, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddrofinterest", parameterType: ParameterType.UINT16}, {name: "descriptor_len", parameterType: ParameterType.UINT8}, {name: "userdescriptor", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "serverDiscReq", ID: 12, type: CommandType.SREQ, request: [{name: "servermask", parameterType: ParameterType.UINT16}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "endDeviceBindReq", ID: 32, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "localcoord", parameterType: ParameterType.UINT16}, {name: "localieee", parameterType: ParameterType.IEEEADDR}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "profileid", parameterType: ParameterType.UINT16}, {name: "numinclusters", parameterType: ParameterType.UINT8}, {name: "inclusterlist", parameterType: ParameterType.LIST_UINT16}, {name: "numoutclusters", parameterType: ParameterType.UINT8}, {name: "outclusterlist", parameterType: ParameterType.LIST_UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "bindReq", ID: 33, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "srcaddr", parameterType: ParameterType.IEEEADDR}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "dstaddress", parameterType: ParameterType.IEEEADDR}, {name: "dstendpoint", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "unbindReq", ID: 34, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "srcaddr", parameterType: ParameterType.IEEEADDR}, {name: "srcendpoint", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "dstaddress", parameterType: ParameterType.IEEEADDR}, {name: "dstendpoint", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "setLinkKey", ID: 35, type: CommandType.SREQ, request: [ {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "linkkey", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "removeLinkKey", ID: 36, type: CommandType.SREQ, request: [{name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "getLinkKey", ID: 37, type: CommandType.SREQ, request: [{name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "linkkeydata", parameterType: ParameterType.BUFFER16}, ], }, { name: "nwkDiscoveryReq", ID: 38, type: CommandType.SREQ, request: [ {name: "scanchannels", parameterType: ParameterType.UINT32}, {name: "scanduration", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "joinReq", ID: 39, type: CommandType.SREQ, request: [ {name: "logicalchannel", parameterType: ParameterType.UINT8}, {name: "panid", parameterType: ParameterType.UINT16}, {name: "extendedpanid", parameterType: ParameterType.IEEEADDR}, {name: "chosenparent", parameterType: ParameterType.UINT16}, {name: "parentdepth", parameterType: ParameterType.UINT8}, {name: "stackprofile", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtNwkDiscReq", ID: 48, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "scanchannels", parameterType: ParameterType.UINT32}, {name: "scanduration", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtLqiReq", ID: 49, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "startindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtRtgReq", ID: 50, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "startindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtBindReq", ID: 51, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "startindex", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtLeaveReq", ID: 52, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "deviceaddress", parameterType: ParameterType.IEEEADDR}, {name: "removechildrenRejoin", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtDirectJoinReq", ID: 53, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "deviceaddr", parameterType: ParameterType.IEEEADDR}, {name: "capinfo", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtPermitJoinReq", ID: 54, type: CommandType.SREQ, request: [ {name: "addrmode", parameterType: ParameterType.UINT8}, {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "duration", parameterType: ParameterType.UINT8}, {name: "tcsignificance", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "mgmtNwkUpdateReq", ID: 55, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "dstaddrmode", parameterType: ParameterType.UINT8}, {name: "channelmask", parameterType: ParameterType.UINT32}, {name: "scanduration", parameterType: ParameterType.UINT8}, {name: "scancount", parameterType: ParameterType.UINT8}, {name: "nwkmanageraddr", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "msgCbRegister", ID: 62, type: CommandType.SREQ, request: [{name: "clusterid", parameterType: ParameterType.UINT16}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "msgCbRemove", ID: 63, type: CommandType.SREQ, request: [{name: "clusterid", parameterType: ParameterType.UINT16}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "startupFromApp", ID: 64, type: CommandType.SREQ, request: [{name: "startdelay", parameterType: ParameterType.UINT16}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "autoFindDestination", ID: 65, type: CommandType.AREQ, request: [{name: "endpoint", parameterType: ParameterType.UINT8}], }, { name: "nwkAddrRsp", ID: 128, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "startindex", parameterType: ParameterType.UINT8}, {name: "numassocdev", parameterType: ParameterType.UINT8}, {name: "assocdevlist", parameterType: ParameterType.LIST_ASSOC_DEV}, ], }, { name: "ieeeAddrRsp", ID: 129, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "startindex", parameterType: ParameterType.UINT8}, {name: "numassocdev", parameterType: ParameterType.UINT8}, {name: "assocdevlist", parameterType: ParameterType.LIST_ASSOC_DEV}, ], }, { name: "nodeDescRsp", ID: 130, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, { name: "logicaltype_cmplxdescavai_userdescavai", parameterType: ParameterType.UINT8, }, {name: "apsflags_freqband", parameterType: ParameterType.UINT8}, {name: "maccapflags", parameterType: ParameterType.UINT8}, {name: "manufacturercode", parameterType: ParameterType.UINT16}, {name: "maxbuffersize", parameterType: ParameterType.UINT8}, {name: "maxintransfersize", parameterType: ParameterType.UINT16}, {name: "servermask", parameterType: ParameterType.UINT16}, {name: "maxouttransfersize", parameterType: ParameterType.UINT16}, {name: "descriptorcap", parameterType: ParameterType.UINT8}, ], }, { name: "powerDescRsp", ID: 131, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, { name: "currentpowermode_avaipowersrc", parameterType: ParameterType.UINT8, }, { name: "currentpowersrc_currentpowersrclevel", parameterType: ParameterType.UINT8, }, ], }, { name: "simpleDescRsp", ID: 132, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "profileid", parameterType: ParameterType.UINT16}, {name: "deviceid", parameterType: ParameterType.UINT16}, {name: "deviceversion", parameterType: ParameterType.UINT8}, {name: "numinclusters", parameterType: ParameterType.UINT8}, {name: "inclusterlist", parameterType: ParameterType.LIST_UINT16}, {name: "numoutclusters", parameterType: ParameterType.UINT8}, {name: "outclusterlist", parameterType: ParameterType.LIST_UINT16}, ], }, { name: "activeEpRsp", ID: 133, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "activeepcount", parameterType: ParameterType.UINT8}, {name: "activeeplist", parameterType: ParameterType.LIST_UINT8}, ], }, { name: "matchDescRsp", ID: 134, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "matchlength", parameterType: ParameterType.UINT8}, {name: "matchlist", parameterType: ParameterType.BUFFER}, ], }, { name: "complexDescRsp", ID: 135, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "complexlength", parameterType: ParameterType.UINT8}, {name: "complexdesclist", parameterType: ParameterType.BUFFER}, ], }, { name: "userDescRsp", ID: 136, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "userlength", parameterType: ParameterType.UINT8}, {name: "userdescriptor", parameterType: ParameterType.BUFFER}, ], }, { name: "userDescConf", ID: 137, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, ], }, { name: "serverDiscRsp", ID: 138, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "servermask", parameterType: ParameterType.UINT16}, ], }, { name: "endDeviceBindRsp", ID: 160, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "bindRsp", ID: 161, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "unbindRsp", ID: 162, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "mgmtNwkDiscRsp", ID: 176, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "networkcount", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, {name: "networklistcount", parameterType: ParameterType.UINT8}, {name: "networklist", parameterType: ParameterType.LIST_NETWORK}, ], }, { name: "mgmtLqiRsp", ID: 177, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "neighbortableentries", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, {name: "neighborlqilistcount", parameterType: ParameterType.UINT8}, { name: "neighborlqilist", parameterType: ParameterType.LIST_NEIGHBOR_LQI, }, ], }, { name: "mgmtRtgRsp", ID: 178, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "routingtableentries", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, {name: "routingtablelistcount", parameterType: ParameterType.UINT8}, { name: "routingtablelist", parameterType: ParameterType.LIST_ROUTING_TABLE, }, ], }, { name: "mgmtBindRsp", ID: 179, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "bindingtableentries", parameterType: ParameterType.UINT8}, {name: "startindex", parameterType: ParameterType.UINT8}, {name: "bindingtablelistcount", parameterType: ParameterType.UINT8}, { name: "bindingtablelist", parameterType: ParameterType.LIST_BIND_TABLE, }, ], }, { name: "mgmtLeaveRsp", ID: 180, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "mgmtDirectJoinRsp", ID: 181, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "mgmtNwkUpdateNotify", ID: 184, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, {name: "scanchannels", parameterType: ParameterType.UINT32}, {name: "totaltransmissions", parameterType: ParameterType.UINT16}, {name: "transmissionfailures", parameterType: ParameterType.UINT16}, {name: "channelcount", parameterType: ParameterType.UINT8}, {name: "energyvalues", parameterType: ParameterType.LIST_UINT8}, ], }, { name: "mgmtPermitJoinRsp", ID: 182, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "stateChangeInd", ID: 192, type: CommandType.AREQ, request: [{name: "state", parameterType: ParameterType.UINT8}], }, { name: "endDeviceAnnceInd", ID: 193, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "capabilities", parameterType: ParameterType.UINT8}, ], }, { name: "matchDescRspSent", ID: 194, type: CommandType.AREQ, request: [ {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "numinclusters", parameterType: ParameterType.UINT8}, {name: "inclusterlist", parameterType: ParameterType.LIST_UINT16}, {name: "numoutclusters", parameterType: ParameterType.UINT8}, {name: "outclusterlist", parameterType: ParameterType.LIST_UINT16}, ], }, { name: "statusErrorRsp", ID: 195, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "srcRtgInd", ID: 196, type: CommandType.AREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "relaycount", parameterType: ParameterType.UINT8}, {name: "relaylist", parameterType: ParameterType.LIST_UINT16}, ], }, { name: "beacon_notify_ind", ID: 197, type: CommandType.AREQ, request: [ {name: "beaconcount", parameterType: ParameterType.UINT8}, {name: "beaconlist", parameterType: ParameterType.BUFFER}, # FIXME ], }, { name: "joinCnf", ID: 198, type: CommandType.AREQ, request: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "deviceaddress", parameterType: ParameterType.UINT16}, {name: "parentaddress", parameterType: ParameterType.UINT16}, ], }, { name: "nwkDiscoveryCnf", ID: 199, type: CommandType.AREQ, request: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "concentratorIndCb", ID: 200, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "pktCost", parameterType: ParameterType.UINT8}, ], }, { name: "leaveInd", ID: 201, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "request", parameterType: ParameterType.UINT8}, {name: "removechildren", parameterType: ParameterType.UINT8}, {name: "rejoin", parameterType: ParameterType.UINT8}, ], }, { name: "setRejoinParametersReq", ID: 204, type: CommandType.SREQ, request: [ {name: "backoffduration", parameterType: ParameterType.UINT32}, {name: "scanduration", parameterType: ParameterType.UINT32}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "msgCbIncoming", ID: 255, type: CommandType.AREQ, request: [ {name: "srcaddr", parameterType: ParameterType.UINT16}, {name: "wasbroadcast", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "securityuse", parameterType: ParameterType.UINT8}, {name: "seqnum", parameterType: ParameterType.UINT8}, {name: "macdstaddr", parameterType: ParameterType.UINT16}, {name: "msgdata", parameterType: ParameterType.BUFFER}, # FIXME ], }, { name: "endDeviceTimeoutReq", ID: 13, type: CommandType.SREQ, request: [ {name: "parentaddr", parameterType: ParameterType.UINT16}, {name: "reqrimeout", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "sendData", ID: 40, type: CommandType.SREQ, request: [ {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "transseq", parameterType: ParameterType.UINT8}, {name: "cmd", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT8}, {name: "buf", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "nwkAddrOfInterestReq", ID: 41, type: CommandType.SREQ, request: [ {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "cmd", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "secAddLinkKey", ID: 66, type: CommandType.SREQ, request: [ {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "linkkey", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "secEntryLookupExt", ID: 67, type: CommandType.SREQ, request: [{name: "extaddr", parameterType: ParameterType.IEEEADDR}], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ami", parameterType: ParameterType.UINT16}, {name: "keynvid", parameterType: ParameterType.UINT16}, {name: "authenticateoption", parameterType: ParameterType.UINT8}, ], }, { name: "secDeviceRemove", ID: 68, type: CommandType.SREQ, request: [{name: "extaddr", parameterType: ParameterType.IEEEADDR}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extRouteDisc", ID: 69, type: CommandType.SREQ, request: [ {name: "dstAddr", parameterType: ParameterType.UINT16}, {name: "options", parameterType: ParameterType.UINT8}, {name: "radius", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extRouteCheck", ID: 70, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "rtstatus", parameterType: ParameterType.UINT8}, {name: "options", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extRemoveGroup", ID: 71, type: CommandType.SREQ, request: [ {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "groupid", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extRemoveAllGroup", ID: 72, type: CommandType.SREQ, request: [{name: "endpoint", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extFindAllGroupsEndpoint", ID: 73, type: CommandType.SREQ, request: [{name: "endpoint", parameterType: ParameterType.UINT8}], response: [ {name: "groups", parameterType: ParameterType.UINT8}, {name: "grouplist", parameterType: ParameterType.LIST_UINT16}, ], }, { name: "extFindGroup", ID: 74, type: CommandType.SREQ, request: [ {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "groupid", parameterType: ParameterType.UINT16}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "groupid", parameterType: ParameterType.UINT16}, {name: "namelen", parameterType: ParameterType.UINT8}, {name: "groupname", parameterType: ParameterType.BUFFER}, ], }, { name: "extAddGroup", ID: 75, type: CommandType.SREQ, request: [ {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "groupid", parameterType: ParameterType.UINT16}, {name: "namelen", parameterType: ParameterType.UINT8}, {name: "groupname", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extCountAllGroups", ID: 76, type: CommandType.SREQ, request: [], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extRxIdle", ID: 77, type: CommandType.SREQ, request: [ {name: "setflag", parameterType: ParameterType.UINT8}, {name: "setvalue", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extUpdateNwkKey", ID: 78, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "keyseqnum", parameterType: ParameterType.UINT8}, {name: "key", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extSwitchNwkKey", ID: 79, type: CommandType.SREQ, request: [ {name: "dstaddr", parameterType: ParameterType.UINT16}, {name: "keyseqnum", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "extNwkInfo", ID: 80, type: CommandType.SREQ, request: [], response: [ {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "devstate", parameterType: ParameterType.UINT8}, {name: "panid", parameterType: ParameterType.UINT16}, {name: "parentaddr", parameterType: ParameterType.UINT16}, {name: "extendedpanid", parameterType: ParameterType.IEEEADDR}, {name: "parentextaddr", parameterType: ParameterType.IEEEADDR}, {name: "channel", parameterType: ParameterType.UINT8}, ], }, { name: "extSecApsRemoveReq", ID: 81, type: CommandType.SREQ, request: [ {name: "parentaddr", parameterType: ParameterType.UINT16}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "extaddr", parameterType: ParameterType.IEEEADDR}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "forceConcentratorChange", ID: 82, type: CommandType.SREQ, request: [], response: [], }, { name: "extSetParams", ID: 83, type: CommandType.SREQ, request: [{name: "usemulticast", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "tcDeviceInd", ID: 202, type: CommandType.AREQ, request: [ {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "parentaddr", parameterType: ParameterType.UINT16}, ], }, { name: "permitJoinInd", ID: 203, type: CommandType.AREQ, request: [{name: "duration", parameterType: ParameterType.UINT8}], }, ], Subsystem.SAPI: [ {name: "systemReset", ID: 9, type: CommandType.AREQ, request: []}, { name: "startRequest", ID: 0, type: CommandType.SREQ, request: [], response: [], }, { name: "bindDevice", ID: 1, type: CommandType.SREQ, request: [ {name: "action", parameterType: ParameterType.UINT8}, {name: "commandid", parameterType: ParameterType.UINT16}, {name: "destination", parameterType: ParameterType.IEEEADDR}, ], response: [], }, { name: "allowBind", ID: 2, type: CommandType.SREQ, request: [{name: "timeout", parameterType: ParameterType.UINT8}], response: [], }, { name: "sendDataRequest", ID: 3, type: CommandType.SREQ, request: [ {name: "destination", parameterType: ParameterType.UINT16}, {name: "commandid", parameterType: ParameterType.UINT16}, {name: "handle", parameterType: ParameterType.UINT8}, {name: "txoptions", parameterType: ParameterType.UINT8}, {name: "radius", parameterType: ParameterType.UINT8}, {name: "payloadlen", parameterType: ParameterType.UINT8}, {name: "payloadvalue", parameterType: ParameterType.BUFFER}, ], response: [], }, { name: "readConfiguration", ID: 4, type: CommandType.SREQ, request: [{name: "configid", parameterType: ParameterType.UINT8}], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "configid", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], }, { name: "writeConfiguration", ID: 5, type: CommandType.SREQ, request: [ {name: "configid", parameterType: ParameterType.UINT8}, {name: "len", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "getDeviceInfo", ID: 6, type: CommandType.SREQ, request: [{name: "param", parameterType: ParameterType.UINT8}], response: [ {name: "param", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.BUFFER8}, ], }, { name: "findDeviceRequest", ID: 7, type: CommandType.SREQ, request: [{name: "searchKey", parameterType: ParameterType.IEEEADDR}], response: [], }, { name: "permitJoiningRequest", ID: 8, type: CommandType.SREQ, request: [ {name: "destination", parameterType: ParameterType.UINT16}, {name: "timeout", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "startConfirm", ID: 128, type: CommandType.AREQ, request: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "bindConfirm", ID: 129, type: CommandType.AREQ, request: [ {name: "commandid", parameterType: ParameterType.UINT16}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "allowBindConfirm", ID: 130, type: CommandType.AREQ, request: [{name: "source", parameterType: ParameterType.UINT16}], }, { name: "sendDataConfirm", ID: 131, type: CommandType.AREQ, request: [ {name: "handle", parameterType: ParameterType.UINT8}, {name: "status", parameterType: ParameterType.UINT8}, ], }, { name: "findDeviceConfirm", ID: 133, type: CommandType.AREQ, request: [ {name: "searchtype", parameterType: ParameterType.UINT8}, {name: "searchkey", parameterType: ParameterType.UINT16}, {name: "result", parameterType: ParameterType.IEEEADDR}, ], }, { name: "receiveDataIndication", ID: 135, type: CommandType.AREQ, request: [ {name: "source", parameterType: ParameterType.UINT16}, {name: "command", parameterType: ParameterType.UINT16}, {name: "len", parameterType: ParameterType.UINT16}, {name: "data", parameterType: ParameterType.BUFFER}, ], }, ], Subsystem.UTIL: [ { name: "getDeviceInfo", ID: 0, type: CommandType.SREQ, request: [], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "shortaddr", parameterType: ParameterType.UINT16}, {name: "devicetype", parameterType: ParameterType.UINT8}, {name: "devicestate", parameterType: ParameterType.UINT8}, {name: "numassocdevices", parameterType: ParameterType.UINT8}, {name: "assocdeviceslist", parameterType: ParameterType.LIST_UINT16}, ], }, { name: "getNvInfo", ID: 1, type: CommandType.SREQ, request: [], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "ieeeaddr", parameterType: ParameterType.IEEEADDR}, {name: "scanchannels", parameterType: ParameterType.UINT32}, {name: "panid", parameterType: ParameterType.UINT16}, {name: "securitylevel", parameterType: ParameterType.UINT8}, {name: "preconfigkey", parameterType: ParameterType.BUFFER16}, ], }, { name: "setPanid", ID: 2, type: CommandType.SREQ, request: [{name: "panid", parameterType: ParameterType.UINT16}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "setChannels", ID: 3, type: CommandType.SREQ, request: [{name: "channels", parameterType: ParameterType.UINT32}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "setSeclevel", ID: 4, type: CommandType.SREQ, request: [{name: "securitylevel", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "setPrecfgkey", ID: 5, type: CommandType.SREQ, request: [{name: "preconfigkey", parameterType: ParameterType.BUFFER}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "callbackSubCmd", ID: 6, type: CommandType.SREQ, request: [ {name: "subsystemid", parameterType: ParameterType.UINT16}, {name: "action", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "keyEvent", ID: 7, type: CommandType.SREQ, request: [ {name: "keys", parameterType: ParameterType.UINT8}, {name: "shift", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "timeAlive", ID: 9, type: CommandType.SREQ, request: [], response: [{name: "seconds", parameterType: ParameterType.UINT32}], }, { name: "ledControl", ID: 10, type: CommandType.SREQ, request: [ {name: "ledid", parameterType: ParameterType.UINT8}, {name: "mode", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "testLoopback", ID: 16, type: CommandType.SREQ, request: [{name: "data", parameterType: ParameterType.BUFFER}], response: [{name: "data", parameterType: ParameterType.BUFFER}], }, { name: "dataReq", ID: 17, type: CommandType.SREQ, request: [{name: "securityuse", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "srcMatchEnable", ID: 32, type: CommandType.SREQ, request: [], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "srcMatchAddEntry", ID: 33, type: CommandType.SREQ, request: [ {name: "addressmode", parameterType: ParameterType.UINT8}, {name: "address", parameterType: ParameterType.IEEEADDR}, {name: "panid", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "srcMatchDelEntry", ID: 34, type: CommandType.SREQ, request: [ {name: "addressmode", parameterType: ParameterType.UINT8}, {name: "address", parameterType: ParameterType.IEEEADDR}, {name: "panid", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "srcMatchCheckSrcAddr", ID: 35, type: CommandType.SREQ, request: [ {name: "addressmode", parameterType: ParameterType.UINT8}, {name: "address", parameterType: ParameterType.IEEEADDR}, {name: "panid", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "srcMatchAckAllPending", ID: 36, type: CommandType.SREQ, request: [{name: "option", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "srcMatchCheckAllPending", ID: 37, type: CommandType.SREQ, request: [], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.UINT8}, ], }, { name: "addrmgrExtAddrLookup", ID: 64, type: CommandType.SREQ, request: [{name: "extaddr", parameterType: ParameterType.IEEEADDR}], response: [{name: "nwkaddr", parameterType: ParameterType.UINT16}], }, { name: "addrmgrNwkAddrLookup", ID: 65, type: CommandType.SREQ, request: [{name: "nwkaddr", parameterType: ParameterType.UINT16}], response: [{name: "extaddr", parameterType: ParameterType.IEEEADDR}], }, { name: "apsmeLinkKeyDataGet", ID: 68, type: CommandType.SREQ, request: [{name: "extaddr", parameterType: ParameterType.IEEEADDR}], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "seckey", parameterType: ParameterType.BUFFER16}, {name: "txfrmcntr", parameterType: ParameterType.UINT32}, {name: "rxfrmcntr", parameterType: ParameterType.UINT32}, ], }, { name: "apsmeLinkKeyNvIdGet", ID: 69, type: CommandType.SREQ, request: [{name: "extaddr", parameterType: ParameterType.IEEEADDR}], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "linkkeynvid", parameterType: ParameterType.UINT16}, ], }, { name: "assocCount", ID: 72, type: CommandType.SREQ, request: [ {name: "startrelation", parameterType: ParameterType.UINT8}, {name: "endrelation", parameterType: ParameterType.UINT8}, ], response: [{name: "count", parameterType: ParameterType.UINT16}], }, { name: "assocFindDevice", ID: 73, type: CommandType.SREQ, request: [{name: "number", parameterType: ParameterType.UINT8}], response: [{name: "device", parameterType: ParameterType.BUFFER18}], }, { name: "assocGetWithAddress", ID: 74, type: CommandType.SREQ, request: [ {name: "extaddr", parameterType: ParameterType.IEEEADDR}, {name: "nwkaddr", parameterType: ParameterType.UINT16}, ], response: [{name: "device", parameterType: ParameterType.BUFFER18}], }, { name: "apsmeRequestKeyCmd", ID: 75, type: CommandType.SREQ, request: [{name: "partneraddr", parameterType: ParameterType.IEEEADDR}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "zclKeyEstInitEst", ID: 128, type: CommandType.SREQ, request: [ {name: "taskid", parameterType: ParameterType.UINT8}, {name: "seqnum", parameterType: ParameterType.UINT8}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "addrmode", parameterType: ParameterType.UINT8}, {name: "extaddr", parameterType: ParameterType.IEEEADDR}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "zclKeyEstSign", ID: 129, type: CommandType.SREQ, request: [ {name: "inputlen", parameterType: ParameterType.UINT8}, {name: "input", parameterType: ParameterType.BUFFER}, ], response: [ {name: "status", parameterType: ParameterType.UINT8}, {name: "key", parameterType: ParameterType.BUFFER42}, ], }, {name: "syncReq", ID: 224, type: CommandType.AREQ, request: []}, { name: "zclKeyEstablishInd", ID: 225, type: CommandType.AREQ, request: [ {name: "taskid", parameterType: ParameterType.UINT8}, {name: "event", parameterType: ParameterType.UINT8}, {name: "status", parameterType: ParameterType.UINT8}, {name: "waittime", parameterType: ParameterType.UINT8}, {name: "suite", parameterType: ParameterType.UINT16}, ], }, { name: "gpioSetDirection", ID: 20, type: CommandType.SREQ, request: [ {name: "port", parameterType: ParameterType.UINT8}, {name: "bit", parameterType: ParameterType.UINT8}, {name: "direction", parameterType: ParameterType.UINT8}, ], response: [ {name: "oldp0dir", parameterType: ParameterType.UINT8}, {name: "oldp1dir", parameterType: ParameterType.UINT8}, {name: "oldp2dir", parameterType: ParameterType.UINT8}, {name: "p0dir", parameterType: ParameterType.UINT8}, {name: "p1dir", parameterType: ParameterType.UINT8}, {name: "p2dir", parameterType: ParameterType.UINT8}, ], }, { name: "gpioRead", ID: 21, type: CommandType.SREQ, request: [], response: [ {name: "p0", parameterType: ParameterType.UINT8}, {name: "p1", parameterType: ParameterType.UINT8}, {name: "p2", parameterType: ParameterType.UINT8}, {name: "p0dir", parameterType: ParameterType.UINT8}, {name: "p1dir", parameterType: ParameterType.UINT8}, {name: "p2dir", parameterType: ParameterType.UINT8}, ], }, { name: "gpioWrite", ID: 22, type: CommandType.SREQ, request: [ {name: "port", parameterType: ParameterType.UINT8}, {name: "bit", parameterType: ParameterType.UINT8}, {name: "value", parameterType: ParameterType.UINT8}, ], response: [ {name: "oldp0", parameterType: ParameterType.UINT8}, {name: "oldp1", parameterType: ParameterType.UINT8}, {name: "oldp2", parameterType: ParameterType.UINT8}, {name: "p0", parameterType: ParameterType.UINT8}, {name: "p1", parameterType: ParameterType.UINT8}, {name: "p2", parameterType: ParameterType.UINT8}, {name: "p0dir", parameterType: ParameterType.UINT8}, {name: "p1dir", parameterType: ParameterType.UINT8}, {name: "p2dir", parameterType: ParameterType.UINT8}, ], }, { name: "srngGen", ID: 76, type: CommandType.SREQ, request: [], response: [{name: "outrng", parameterType: ParameterType.BUFFER100}], }, { name: "bindAddEntry", ID: 77, type: CommandType.SREQ, request: [ {name: "addrmode", parameterType: ParameterType.UINT8}, {name: "dstaddr", parameterType: ParameterType.IEEEADDR}, {name: "dstendpoint", parameterType: ParameterType.UINT8}, {name: "numclusterids", parameterType: ParameterType.UINT8}, {name: "clusterids", parameterType: ParameterType.LIST_UINT16}, ], response: [ {name: "srcep", parameterType: ParameterType.UINT8}, {name: "dstgroupmode", parameterType: ParameterType.UINT8}, {name: "dstidx", parameterType: ParameterType.UINT16}, {name: "dstep", parameterType: ParameterType.UINT8}, {name: "numclusterids", parameterType: ParameterType.UINT8}, {name: "clusterids", parameterType: ParameterType.BUFFER8}, ], }, ], Subsystem.DEBUG: [ { name: "setThreshold", ID: 0, type: CommandType.SREQ, request: [ {name: "componentid", parameterType: ParameterType.UINT8}, {name: "threshold", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "msg", ID: 128, type: CommandType.AREQ, request: [ {name: "length", parameterType: ParameterType.UINT8}, {name: "string", parameterType: ParameterType.BUFFER}, ], }, ], Subsystem.APP: [ { name: "msg", ID: 0, type: CommandType.SREQ, request: [ {name: "appendpoint", parameterType: ParameterType.UINT8}, {name: "destaddress", parameterType: ParameterType.UINT16}, {name: "destendpoint", parameterType: ParameterType.UINT8}, {name: "clusterid", parameterType: ParameterType.UINT16}, {name: "msglen", parameterType: ParameterType.UINT8}, {name: "message", parameterType: ParameterType.BUFFER}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "userTest", ID: 1, type: CommandType.SREQ, request: [ {name: "srcep", parameterType: ParameterType.UINT8}, {name: "commandid", parameterType: ParameterType.UINT16}, {name: "param1", parameterType: ParameterType.UINT16}, {name: "param2", parameterType: ParameterType.UINT16}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "zllTlInd", ID: 129, type: CommandType.AREQ, request: [ {name: "nwkaddr", parameterType: ParameterType.UINT16}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "profileid", parameterType: ParameterType.UINT16}, {name: "deviceid", parameterType: ParameterType.UINT16}, {name: "version", parameterType: ParameterType.UINT8}, ], }, ], Subsystem.APP_CNF: [ { name: "bdbStartCommissioning", ID: 5, type: CommandType.SREQ, request: [{name: "mode", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "bdbSetChannel", ID: 8, type: CommandType.SREQ, request: [ {name: "isPrimary", parameterType: ParameterType.UINT8}, {name: "channel", parameterType: ParameterType.UINT32}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, { name: "bdbComissioningNotifcation", ID: 128, type: CommandType.AREQ, request: [{name: "status", parameterType: ParameterType.UINT8}], response: [{name: "status", parameterType: ParameterType.UINT8}], }, ], Subsystem.GREENPOWER: [ { name: "secReq", ID: 3, type: CommandType.SREQ, request: [ {name: "applicationID", parameterType: ParameterType.UINT8}, {name: "srcID", parameterType: ParameterType.UINT32}, {name: "gdpIeeeAddr", parameterType: ParameterType.IEEEADDR}, {name: "endpoint", parameterType: ParameterType.UINT8}, {name: "gpdfSecurityLevel", parameterType: ParameterType.UINT8}, {name: "gpdfSecurityFrameCounter", parameterType: ParameterType.UINT8}, {name: "dgpStubHandle", parameterType: ParameterType.UINT8}, ], response: [{name: "status", parameterType: ParameterType.UINT8}], }, ], }
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/definition.py
definition.py
import asyncio import logging from typing import Any, Dict import serial import serial.tools.list_ports import serial_asyncio from serial.tools.list_ports_common import ListPortInfo from zigpy_cc.config import CONF_DEVICE_BAUDRATE, CONF_DEVICE_PATH, CONF_FLOW_CONTROL import zigpy_cc.types as t LOGGER = logging.getLogger(__name__) DataStart = 4 SOF = 0xFE PositionDataLength = 1 PositionCmd0 = 2 PositionCmd1 = 3 MinMessageLength = 5 MaxDataSize = 250 """ 0451: Texas Instruments 1a86:7523 QinHeng Electronics HL-340 USB-Serial adapter used in zzh - https://electrolama.com/projects/zig-a-zig-ah/ """ usb_regexp = "0451:|1a86:7523" class Parser: def __init__(self) -> None: self.buffer = b"" def write(self, b: int): self.buffer += bytes([b]) if SOF == self.buffer[0]: if len(self.buffer) > MinMessageLength: dataLength = self.buffer[PositionDataLength] fcsPosition = DataStart + dataLength frameLength = fcsPosition + 1 if len(self.buffer) >= frameLength: frameBuffer = self.buffer[0:frameLength] self.buffer = self.buffer[frameLength:] frame = UnpiFrame.from_buffer(dataLength, fcsPosition, frameBuffer) return frame else: LOGGER.debug("drop char") self.buffer = b"" return None class UnpiFrame(t.Repr): def __init__( self, command_type: int, subsystem: int, command_id: int, data: bytes, length=None, fcs=None, ): self.command_type = t.CommandType(command_type) self.subsystem = t.Subsystem(subsystem) self.command_id = command_id self.data = data self.length = length self.fcs = fcs @classmethod def from_buffer(cls, length, fcs_position, buffer): subsystem = buffer[PositionCmd0] & 0x1F command_type = (buffer[PositionCmd0] & 0xE0) >> 5 command_id = buffer[PositionCmd1] data = buffer[DataStart:fcs_position] fcs = buffer[fcs_position] checksum = cls.calculate_checksum(buffer[1:fcs_position]) if checksum == fcs: return cls(command_type, subsystem, command_id, data, length, fcs) else: LOGGER.warning("Invalid checksum: 0x%s, data: 0x%s", checksum, buffer) return None @staticmethod def calculate_checksum(values): checksum = 0 for value in values: checksum ^= value return checksum def to_buffer(self): length = len(self.data) cmd0 = ((self.command_type << 5) & 0xE0) | (self.subsystem & 0x1F) res = bytes([SOF, length, cmd0, self.command_id]) res += self.data fcs = self.calculate_checksum(res[1:]) return res + bytes([fcs]) class Gateway(asyncio.Protocol): _transport: serial_asyncio.SerialTransport def __init__(self, api, connected_future=None): self._parser = Parser() self._connected_future = connected_future self._api = api self._transport = None self._open = False def connection_made(self, transport: serial_asyncio.SerialTransport): """Callback when the uart is connected""" LOGGER.debug("Connection made") self._open = True self._transport = transport if self._connected_future: self._connected_future.set_result(True) def close(self): self._open = False self._transport.close() def write(self, data): self._transport.write(data) def send(self, frame: UnpiFrame): """Send data, taking care of escaping and framing""" data = frame.to_buffer() LOGGER.debug("Send: %s", data) self._transport.write(data) def data_received(self, data): """Callback when there is data received from the uart""" found = False for b in data: frame = self._parser.write(b) if frame is not None: found = True LOGGER.debug("Frame received: %s", frame) self._api.data_received(frame) if not found: LOGGER.info("Bytes received: %s", data) def connection_lost(self, exc): if self._open: LOGGER.error("Serial port closed unexpectedly: %s", exc) self._api.connection_lost() def detect_port() -> ListPortInfo: devices = list(serial.tools.list_ports.grep(usb_regexp)) if len(devices) < 1: raise serial.SerialException("Unable to find TI CC device using auto mode") if len(devices) > 1: raise serial.SerialException( "Unable to select TI CC device, multiple devices found: {}".format( ", ".join(map(lambda d: str(d), devices)) ) ) return devices[0] async def connect(config: Dict[str, Any], api, loop=None) -> Gateway: if loop is None: loop = asyncio.get_event_loop() connected_future = loop.create_future() protocol = Gateway(api, connected_future) port, baudrate = config[CONF_DEVICE_PATH], config[CONF_DEVICE_BAUDRATE] if port == "auto": device = detect_port() LOGGER.info("Auto select TI CC device: %s", device) port = device.device xonxoff, rtscts = False, False if config[CONF_FLOW_CONTROL] == "hardware": xonxoff, rtscts = False, True elif config[CONF_FLOW_CONTROL] == "software": xonxoff, rtscts = True, False LOGGER.debug("Connecting on port %s with boudrate %d", port, baudrate) _, protocol = await serial_asyncio.create_serial_connection( loop, lambda: protocol, url=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=xonxoff, rtscts=rtscts, ) await connected_future protocol.write(b"\xef") await asyncio.sleep(1) return protocol
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/uart.py
uart.py
from zigpy.profiles import zha from zigpy.types import BroadcastAddress from zigpy_cc import uart from zigpy_cc.buffalo import Buffalo, BuffaloOptions from zigpy_cc.definition import Definition from zigpy_cc.types import CommandType, ParameterType, Subsystem, AddressMode BufferAndListTypes = [ ParameterType.BUFFER, ParameterType.BUFFER8, ParameterType.BUFFER16, ParameterType.BUFFER18, ParameterType.BUFFER32, ParameterType.BUFFER42, ParameterType.BUFFER100, ParameterType.LIST_UINT16, ParameterType.LIST_ROUTING_TABLE, ParameterType.LIST_BIND_TABLE, ParameterType.LIST_NEIGHBOR_LQI, ParameterType.LIST_NETWORK, ParameterType.LIST_ASSOC_DEV, ParameterType.LIST_UINT8, ] class ZpiObject: def __init__( self, command_type, subsystem, command: str, command_id, payload, parameters, sequence=None, ): self.command_type = CommandType(command_type) self.subsystem = Subsystem(subsystem) self.command = command self.command_id = command_id self.payload = payload self.parameters = parameters self.sequence = sequence def is_reset_command(self): return (self.command == "resetReq" and self.subsystem == Subsystem.SYS) or ( self.command == "systemReset" and self.subsystem == Subsystem.SAPI ) def to_unpi_frame(self): data = Buffalo(b"") for p in self.parameters: value = self.payload[p["name"]] data.write_parameter(p["parameterType"], value, {}) return uart.UnpiFrame( self.command_type, self.subsystem, self.command_id, data.buffer ) @classmethod def from_command(cls, subsystem, command, payload): cmd = next(c for c in Definition[subsystem] if c["name"] == command) parameters = ( cmd["response"] if cmd["type"] == CommandType.SRSP else cmd["request"] ) return cls(cmd["type"], subsystem, cmd["name"], cmd["ID"], payload, parameters) @classmethod def from_unpi_frame(cls, frame): cmd = next( c for c in Definition[frame.subsystem] if c["ID"] == frame.command_id ) parameters = ( cmd["response"] if frame.command_type == CommandType.SRSP else cmd["request"] ) payload = cls.read_parameters(frame.data, parameters) return cls( frame.command_type, frame.subsystem, cmd["name"], cmd["ID"], payload, parameters, ) @classmethod def from_cluster( cls, nwk, profile, cluster, src_ep, dst_ep, sequence, data, *, radius=30, addr_mode=None ): if profile == zha.PROFILE_ID: subsystem = Subsystem.AF if addr_mode is None: cmd = next(c for c in Definition[subsystem] if c["ID"] == 1) else: cmd = next(c for c in Definition[subsystem] if c["ID"] == 2) else: subsystem = Subsystem.ZDO cmd = next(c for c in Definition[subsystem] if c["ID"] == cluster) name = cmd["name"] parameters = ( cmd["response"] if cmd["type"] == CommandType.SRSP else cmd["request"] ) if name == "dataRequest": payload = { "dstaddr": int(nwk), "destendpoint": dst_ep, "srcendpoint": src_ep, "clusterid": cluster, "transid": sequence, "options": 0, "radius": radius, "len": len(data), "data": data, } elif name == "dataRequestExt": payload = { "dstaddrmode": addr_mode, "dstaddr": nwk, "destendpoint": dst_ep, "dstpanid": 0, "srcendpoint": src_ep, "clusterid": cluster, "transid": sequence, "options": 0, "radius": radius, "len": len(data), "data": data, } elif name == "mgmtPermitJoinReq": addrmode = ( AddressMode.ADDR_BROADCAST if nwk == BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR else AddressMode.ADDR_16BIT ) payload = cls.read_parameters( bytes([addrmode]) + nwk.to_bytes(2, "little") + data[1:], parameters ) else: # TODO # assert sequence == data[0] payload = cls.read_parameters( nwk.to_bytes(2, "little") + data[1:], parameters ) return cls( cmd["type"], subsystem, name, cmd["ID"], payload, parameters, sequence ) @classmethod def read_parameters(cls, data: bytes, parameters): # print(parameters) buffalo = Buffalo(data) res = {} length = None start_index = None for p in parameters: options = BuffaloOptions() name = p["name"] param_type = p["parameterType"] if param_type in BufferAndListTypes: if isinstance(length, int): options.length = length if param_type == ParameterType.LIST_ASSOC_DEV: if isinstance(start_index, int): options.startIndex = start_index res[name] = buffalo.read_parameter(name, param_type, options) # For LIST_ASSOC_DEV, we need to grab the start_index which is # right before the length start_index = length # When reading a buffer, assume that the previous parsed parameter # contains the length of the buffer length = res[name] return res def __repr__(self) -> str: command_type = CommandType(self.command_type).name subsystem = Subsystem(self.subsystem).name return "{} {} {} tsn: {} {}".format( command_type, subsystem, self.command, self.sequence, self.payload )
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/zpi_object.py
zpi_object.py
from collections.abc import Iterable import zigpy.types from zigpy_cc.exception import TODO from zigpy_cc.types import AddressMode, ParameterType class BuffaloOptions: def __init__(self) -> None: self.startIndex = None self.length = None class Buffalo: def __init__(self, buffer, position=0) -> None: self.position = position self.buffer = buffer self._len = len(buffer) def __len__(self) -> int: return len(self.buffer) def write_parameter(self, type, value, options): if type == ParameterType.UINT8: self.write(value) elif type == ParameterType.UINT16: self.write(value, 2) elif type == ParameterType.UINT32: self.write(value, 4) elif type == ParameterType.IEEEADDR: if isinstance(value, Iterable): for i in value: self.write(i) else: self.write(value, 8) elif type == ParameterType.BUFFER: self.buffer += value elif type == ParameterType.LIST_UINT8: for v in value: self.write(v) elif type == ParameterType.LIST_UINT16: for v in value: self.write(v, 2) elif type == ParameterType.LIST_NEIGHBOR_LQI: for v in value: self.write_neighbor_lqi(v) else: raise TODO( "write %s, value: %s, options: %s", ParameterType(type), value, options ) def write(self, value, length=1, signed=False): self.buffer += value.to_bytes(length, "little", signed=signed) def write_neighbor_lqi(self, value): for i in value["extPanId"]: self.write(i) for i in value["extAddr"]: self.write(i) self.write(value["nwkAddr"], 2) self.write( value["deviceType"] | (value["rxOnWhenIdle"] * 4) | (value["relationship"] * 16) ) self.write(value["permitJoin"]) self.write(value["depth"]) self.write(value["lqi"]) def read_parameter(self, name, type, options): if type == ParameterType.UINT8: res = self.read_int() if name.endswith("addrmode"): res = AddressMode(res) elif type == ParameterType.UINT16: res = self.read_int(2) if ( name.endswith("addr") or name.endswith("address") or name.endswith("addrofinterest") ): res = zigpy.types.NWK(res) elif type == ParameterType.UINT32: res = self.read_int(4) elif type == ParameterType.IEEEADDR: res = self.read_ieee_addr() elif ParameterType.is_buffer(type): type_name = ParameterType(type).name length = int(type_name.replace("BUFFER", "") or options.length) res = self.read(length) elif type == ParameterType.INT8: res = self.read_int(signed=True) else: # list types res = [] if type == ParameterType.LIST_UINT8: for i in range(0, options.length): res.append(self.read_int()) elif type == ParameterType.LIST_UINT16: for i in range(0, options.length): res.append(self.read_int(2)) elif type == ParameterType.LIST_NEIGHBOR_LQI: for i in range(0, options.length): res.append(self.read_neighbor_lqi()) else: raise TODO("read type %d", type) return res def read_int(self, length=1, signed=False): return int.from_bytes(self.read(length), "little", signed=signed) def read(self, length=1): if self.position + length > self._len: raise OverflowError res = self.buffer[self.position : self.position + length] self.position += length return res def read_ieee_addr(self): return zigpy.types.EUI64(self.read(8)) def read_neighbor_lqi(self): item = dict() item["extPanId"] = self.read_ieee_addr() item["extAddr"] = self.read_ieee_addr() item["nwkAddr"] = zigpy.types.NWK(self.read_int(2)) value1 = self.read_int() item["deviceType"] = value1 & 0x03 item["rxOnWhenIdle"] = (value1 & 0x0C) >> 2 item["relationship"] = (value1 & 0x70) >> 4 item["permitJoin"] = self.read_int() & 0x03 item["depth"] = self.read_int() item["lqi"] = self.read_int() return item
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/buffalo.py
buffalo.py
import asyncio import logging from typing import Any, Dict, Optional import serial import zigpy.exceptions from zigpy_cc import uart from zigpy_cc.config import CONF_DEVICE_PATH, SCHEMA_DEVICE from zigpy_cc.definition import Definition from zigpy_cc.exception import CommandError from zigpy_cc.types import CommandType, Repr, Subsystem, Timeouts from zigpy_cc.uart import Gateway from zigpy_cc.zpi_object import ZpiObject LOGGER = logging.getLogger(__name__) COMMAND_TIMEOUT = 2 class Matcher(Repr): def __init__(self, command_type, subsystem, command, payload): self.command_type = command_type self.subsystem = subsystem self.command = command self.payload = payload class Waiter(Repr): def __init__( self, waiter_id: int, command_type: int, subsystem: int, command: str, payload, timeout: int, sequence, ): self.id = waiter_id self.matcher = Matcher(command_type, subsystem, command, payload) self.future = asyncio.get_event_loop().create_future() self.timeout = timeout self.sequence = sequence async def wait(self): return await asyncio.wait_for(self.future, self.timeout / 1000) def set_result(self, result) -> None: if self.future.cancelled(): LOGGER.warning("Waiter already cancelled: %s", self) elif self.future.done(): LOGGER.warning("Waiter already done: %s", self) else: self.future.set_result(result) def match(self, obj: ZpiObject): matcher = self.matcher if ( matcher.command_type != obj.command_type or matcher.subsystem != obj.subsystem or matcher.command != obj.command ): return False if matcher.payload: for f, v in matcher.payload.items(): if v != obj.payload[f]: return False return True class API: _uart: Optional[Gateway] def __init__(self, device_config: Dict[str, Any]): self._config = device_config self._lock = asyncio.Lock() self._waiter_id = 0 self._waiters: Dict[int, Waiter] = {} self._app = None self._proto_ver = None self._uart = None @property def protocol_version(self): """Protocol Version.""" return self._proto_ver @classmethod async def new(cls, application, config: Dict[str, Any]) -> "API": api = cls(config) await api.connect() api.set_application(application) return api def set_application(self, app): self._app = app async def connect(self): assert self._uart is None self._uart = await uart.connect(self._config, self) def close(self): if self._uart: self._uart.close() self._uart = None def connection_lost(self): self._app.connection_lost() async def request( self, subsystem, command, payload, waiter_id=None, expected_status=None ): obj = ZpiObject.from_command(subsystem, command, payload) return await self.request_raw(obj, waiter_id, expected_status) async def request_raw(self, obj: ZpiObject, waiter_id=None, expected_status=None): async with self._lock: return await self._request_raw(obj, waiter_id, expected_status) async def _request_raw(self, obj: ZpiObject, waiter_id=None, expected_status=None): if expected_status is None: expected_status = [0] LOGGER.debug("--> %s", obj) frame = obj.to_unpi_frame() if obj.command_type == CommandType.SREQ: timeout = ( 20000 if obj.command == "bdbStartCommissioning" or obj.command == "startupFromApp" else Timeouts.SREQ ) waiter = self.wait_for( CommandType.SRSP, obj.subsystem, obj.command, {}, timeout ) self._uart.send(frame) result = await waiter.wait() if ( result and "status" in result.payload and result.payload["status"] not in expected_status ): if waiter_id is not None: self._waiters.pop(waiter_id).set_result(result) raise CommandError( result.payload["status"], "SREQ '{}' failed with status '{}' (expected '{}')".format( obj.command, result.payload["status"], expected_status ), ) else: return result elif obj.command_type == CommandType.AREQ and obj.is_reset_command(): waiter = self.wait_for( CommandType.AREQ, Subsystem.SYS, "resetInd", {}, Timeouts.reset ) # TODO clear queue, requests waiting for lock self._uart.send(frame) return await waiter.wait() else: if obj.command_type == CommandType.AREQ: self._uart.send(frame) return None else: LOGGER.warning("Unknown type '%s'", obj.command_type) raise Exception("Unknown type '{}'".format(obj.command_type)) def create_response_waiter(self, obj: ZpiObject, sequence=None): if obj.command_type == CommandType.SREQ and obj.command.startswith( "dataRequest" ): payload = { "transid": obj.payload["transid"], } return self.wait_for(CommandType.AREQ, Subsystem.AF, "dataConfirm", payload) if obj.command_type == CommandType.SREQ and obj.command.endswith("Req"): rsp = obj.command.replace("Req", "Rsp") for cmd in Definition[obj.subsystem]: if rsp == cmd["name"]: payload = {"srcaddr": obj.payload["dstaddr"]} return self.wait_for( CommandType.AREQ, Subsystem.ZDO, rsp, payload, sequence=sequence ) LOGGER.warning("no response cmd configured for %s", obj.command) return None def wait_for( self, command_type: CommandType, subsystem: Subsystem, command: str, payload=None, timeout=Timeouts.default, sequence=None, ): waiter = Waiter( self._waiter_id, command_type, subsystem, command, payload, timeout, sequence, ) self._waiters[waiter.id] = waiter self._waiter_id += 1 def callback(): if not waiter.future.done() or waiter.future.cancelled(): LOGGER.warning( "No response for: %s %s %s %s", command_type.name, subsystem.name, command, payload, ) try: self._waiters.pop(waiter.id) except KeyError: LOGGER.warning("Waiter not found: %s", waiter) asyncio.get_event_loop().call_later(timeout / 1000 + 0.1, callback) return waiter def data_received(self, frame): try: obj = ZpiObject.from_unpi_frame(frame) except Exception as e: LOGGER.error("Error while parsing frame: %s", frame) raise e for waiter_id in list(self._waiters): waiter = self._waiters.get(waiter_id) if waiter.match(obj): self._waiters.pop(waiter_id) waiter.set_result(obj) if waiter.sequence: obj.sequence = waiter.sequence break LOGGER.debug("<-- %s", obj) if self._app is not None: self._app.handle_znp(obj) try: getattr(self, "_handle_%s" % (obj.command,))(obj) except AttributeError: pass async def version(self): version = await self.request(Subsystem.SYS, "version", {}) # todo check version self._proto_ver = version.payload return version.payload def _handle_version(self, data): LOGGER.debug("Version response: %s", data.payload) def _handle_getDeviceInfo(self, data): LOGGER.info("Device info: %s", data.payload) def _handle_srcRtgInd(self, data): pass @classmethod async def probe(cls, device_config: Dict[str, Any]) -> bool: """Probe port for the device presence.""" api = cls(SCHEMA_DEVICE(device_config)) try: await asyncio.wait_for(api._probe(), timeout=COMMAND_TIMEOUT) return True except ( asyncio.TimeoutError, serial.SerialException, zigpy.exceptions.ZigbeeException, ) as exc: LOGGER.debug( "Unsuccessful radio probe of '%s' port", device_config[CONF_DEVICE_PATH], exc_info=exc, ) finally: api.close() return False async def _probe(self) -> None: """Open port and try sending a command""" await self.connect() await self.version()
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/api.py
api.py
from zigpy.types import enum16 class NvItemsIds(enum16): EXTADDR = 1 BOOTCOUNTER = 2 STARTUP_OPTION = 3 START_DELAY = 4 NIB = 33 DEVICE_LIST = 34 ADDRMGR = 35 POLL_RATE = 36 QUEUED_POLL_RATE = 37 RESPONSE_POLL_RATE = 38 REJOIN_POLL_RATE = 39 DATA_RETRIES = 40 POLL_FAILURE_RETRIES = 41 STACK_PROFILE = 42 INDIRECT_MSG_TIMEOUT = 43 ROUTE_EXPIRY_TIME = 44 EXTENDED_PAN_ID = 45 BCAST_RETRIES = 46 PASSIVE_ACK_TIMEOUT = 47 BCAST_DELIVERY_TIME = 48 NWK_MODE = 49 CONCENTRATOR_ENABLE = 50 CONCENTRATOR_DISCOVERY = 51 CONCENTRATOR_RADIUS = 52 CONCENTRATOR_RC = 54 NWK_MGR_MODE = 55 SRC_RTG_EXPIRY_TIME = 56 ROUTE_DISCOVERY_TIME = 57 NWK_ACTIVE_KEY_INFO = 58 NWK_ALTERN_KEY_INFO = 59 ROUTER_OFF_ASSOC_CLEANUP = 60 NWK_LEAVE_REQ_ALLOWED = 61 NWK_CHILD_AGE_ENABLE = 62 DEVICE_LIST_KA_TIMEOUT = 63 BINDING_TABLE = 65 GROUP_TABLE = 66 APS_FRAME_RETRIES = 67 APS_ACK_WAIT_DURATION = 68 APS_ACK_WAIT_MULTIPLIER = 69 BINDING_TIME = 70 APS_USE_EXT_PANID = 71 APS_USE_INSECURE_JOIN = 72 COMMISSIONED_NWK_ADDR = 73 APS_NONMEMBER_RADIUS = 75 APS_LINK_KEY_TABLE = 76 APS_DUPREJ_TIMEOUT_INC = 77 APS_DUPREJ_TIMEOUT_COUNT = 78 APS_DUPREJ_TABLE_SIZE = 79 DIAGNOSTIC_STATS = 80 BDBNODEISONANETWORK = 85 SECURITY_LEVEL = 97 PRECFGKEY = 98 PRECFGKEYS_ENABLE = 99 SECURITY_MODE = 100 SECURE_PERMIT_JOIN = 101 APS_LINK_KEY_TYPE = 102 APS_ALLOW_R19_SECURITY = 103 IMPLICIT_CERTIFICATE = 105 DEVICE_PRIVATE_KEY = 106 CA_PUBLIC_KEY = 107 KE_MAX_DEVICES = 108 USE_DEFAULT_TCLK = 109 RNG_COUNTER = 111 RANDOM_SEED = 112 TRUSTCENTER_ADDR = 113 LEGACY_NWK_SEC_MATERIAL_TABLE_START = 117 # Valid for <= Z-Stack 3.0.x EX_NWK_SEC_MATERIAL_TABLE = 7 # Valid for >= Z-Stack 3.x.0 USERDESC = 129 NWKKEY = 130 PANID = 131 CHANLIST = 132 LEAVE_CTRL = 133 SCAN_DURATION = 134 LOGICAL_TYPE = 135 NWKMGR_MIN_TX = 136 NWKMGR_ADDR = 137 ZDO_DIRECT_CB = 143 SCENE_TABLE = 145 MIN_FREE_NWK_ADDR = 146 MAX_FREE_NWK_ADDR = 147 MIN_FREE_GRP_ID = 148 MAX_FREE_GRP_ID = 149 MIN_GRP_IDS = 150 MAX_GRP_IDS = 151 OTA_BLOCK_REQ_DELAY = 152 SAPI_ENDPOINT = 161 SAS_SHORT_ADDR = 177 SAS_EXT_PANID = 178 SAS_PANID = 179 SAS_CHANNEL_MASK = 180 SAS_PROTOCOL_VER = 181 SAS_STACK_PROFILE = 182 SAS_STARTUP_CTRL = 183 SAS_TC_ADDR = 193 SAS_TC_MASTER_KEY = 194 SAS_NWK_KEY = 195 SAS_USE_INSEC_JOIN = 196 SAS_PRECFG_LINK_KEY = 197 SAS_NWK_KEY_SEQ_NUM = 198 SAS_NWK_KEY_TYPE = 199 SAS_NWK_MGR_ADDR = 200 SAS_CURR_TC_MASTER_KEY = 209 SAS_CURR_NWK_KEY = 210 SAS_CURR_PRECFG_LINK_KEY = 211 LEGACY_TCLK_TABLE_START = 257 # Valid for <= Z-Stack 3.0.x LEGACY_TCLK_TABLE_END = 511 # Valid for <= Z-Stack 3.0.x EX_TCLK_TABLE = 4 # Valid for >= Z-Stack 3.0.x APS_LINK_KEY_DATA_START = 513 APS_LINK_KEY_DATA_END = 767 DUPLICATE_BINDING_TABLE = 768 DUPLICATE_DEVICE_LIST = 769 DUPLICATE_DEVICE_LIST_KA_TIMEOUT = 770 ZNP_HAS_CONFIGURED_ZSTACK1 = 3840 ZNP_HAS_CONFIGURED_ZSTACK3 = 96 class Common: devStates = { "HOLD": 0, "INIT": 1, "NWK_DISC": 2, "NWK_JOINING": 3, "NWK_REJOIN": 4, "END_DEVICE_UNAUTH": 5, "END_DEVICE": 6, "ROUTER": 7, "COORD_STARTING": 8, "ZB_COORD": 9, "NWK_ORPHAN": 10, "INVALID_REQTYPE": 128, "DEVICE_NOT_FOUND": 129, "INVALID_EP": 130, "NOT_ACTIVE": 131, "NOT_SUPPORTED": 132, "TIMEOUT": 133, "NO_MATCH": 134, "NO_ENTRY": 136, "NO_DESCRIPTOR": 137, "INSUFFICIENT_SPACE": 138, "NOT_PERMITTED": 139, "TABLE_FULL": 140, "NOT_AUTHORIZED": 141, "BINDING_TABLE_FULL": 142, } logicalChannels = { "NONE": 0, "CH11": 11, "CH12": 12, "CH13": 13, "CH14": 14, "CH15": 15, "CH16": 16, "CH17": 17, "CH18": 18, "CH19": 19, "CH20": 20, "CH21": 21, "CH22": 22, "CH23": 23, "CH24": 24, "CH25": 25, "CH26": 26, } channelMask = { "CH11": 2048, "CH12": 4096, "CH13": 8192, "CH14": 16384, "CH15": 32768, "CH16": 65536, "CH17": 131072, "CH18": 262144, "CH19": 524288, "CH20": 1048576, "CH21": 2097152, "CH22": 4194304, "CH23": 8388608, "CH24": 16777216, "CH25": 33554432, "CH26": 67108864, "CH_ALL": 134215680, }
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/zigbee/common.py
common.py
from zigpy.types import ExtendedPanId, Channels from zigpy_cc.types import ZnpVersion from zigpy_cc.zigbee.common import NvItemsIds class Items: @staticmethod def znpHasConfiguredInit(version): return { "id": NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK1 if version == ZnpVersion.zStack12 else NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK3, "len": 0x01, "initlen": 0x01, "initvalue": b"\x00", } @staticmethod def znpHasConfigured(version): return { "id": NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK1 if version == ZnpVersion.zStack12 else NvItemsIds.ZNP_HAS_CONFIGURED_ZSTACK3, "offset": 0x00, "len": 0x01, "value": b"\x55", } @staticmethod def panID(panID): return { "id": NvItemsIds.PANID, "len": 0x02, "offset": 0x00, "value": bytes([panID & 0xFF, (panID >> 8) & 0xFF]), } @staticmethod def extendedPanID(extendedPanID: ExtendedPanId): return { "id": NvItemsIds.EXTENDED_PAN_ID, "len": 0x08, "offset": 0x00, "value": extendedPanID.serialize(), } @staticmethod def channelList(channelList: Channels): return { "id": NvItemsIds.CHANLIST, "len": 0x04, "offset": 0x00, "value": channelList.serialize(), } @staticmethod def networkKeyDistribute(distribute): return { "id": NvItemsIds.PRECFGKEYS_ENABLE, "len": 0x01, "offset": 0x00, "value": b"\x01" if distribute else b"\x00", } @staticmethod def networkKey(key): return { # id/configid is used depending if SAPI or SYS command is executed "id": NvItemsIds.PRECFGKEY, "configid": NvItemsIds.PRECFGKEY, "len": 0x10, "offset": 0x00, "value": bytes(key), } @staticmethod def startupOption(value): return { "id": NvItemsIds.STARTUP_OPTION, "len": 0x01, "offset": 0x00, "value": bytes([value]), } @staticmethod def logicalType(value): return { "id": NvItemsIds.LOGICAL_TYPE, "len": 0x01, "offset": 0x00, "value": bytes([value]), } @staticmethod def zdoDirectCb(): return { "id": NvItemsIds.ZDO_DIRECT_CB, "len": 0x01, "offset": 0x00, "value": b"\x01", } @staticmethod def tcLinkKey(): return { "id": NvItemsIds.LEGACY_TCLK_TABLE_START, "offset": 0x00, "len": 0x20, # ZigBee Alliance Pre-configured TC Link Key - 'ZigBeeAlliance09' "value": bytes( [ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x5A, 0x69, 0x67, 0x42, 0x65, 0x65, 0x41, 0x6C, 0x6C, 0x69, 0x61, 0x6E, 0x63, 0x65, 0x30, 0x39, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, ] ), }
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/zigbee/nv_items.py
nv_items.py
import asyncio import logging import os from zigpy.zcl.clusters.general import Ota from zigpy.zcl.clusters.security import IasZone, IasWd from zigpy_cc.api import API from zigpy_cc.const import Constants from zigpy_cc.types import NetworkOptions, Subsystem, ZnpVersion, CommandType from zigpy_cc.exception import CommandError from zigpy_cc.zigbee.backup import Restore from zigpy_cc.zigbee.common import Common from .nv_items import Items LOGGER = logging.getLogger(__name__) class Endpoint: def __init__(self, **kwargs) -> None: self.endpoint = None self.appdeviceid = 0x0005 self.appdevver = 0 self.appnuminclusters = 0 self.appinclusterlist = [] self.appnumoutclusters = 0 self.appoutclusterlist = [] self.latencyreq = Constants.AF.networkLatencyReq.NO_LATENCY_REQS for key, value in kwargs.items(): setattr(self, key, value) Endpoints = [ Endpoint(endpoint=1, appprofid=0x0104), Endpoint(endpoint=2, appprofid=0x0101), Endpoint(endpoint=3, appprofid=0x0106), Endpoint(endpoint=4, appprofid=0x0107), Endpoint(endpoint=5, appprofid=0x0108), Endpoint(endpoint=6, appprofid=0x0109), Endpoint(endpoint=8, appprofid=0x0104), Endpoint( endpoint=11, appprofid=0x0104, appdeviceid=0x0400, appnumoutclusters=2, appoutclusterlist=[IasZone.cluster_id, IasWd.cluster_id], ), # TERNCY: https://github.com/Koenkk/zigbee-herdsman/issues/82 Endpoint(endpoint=0x6E, appprofid=0x0104), Endpoint(endpoint=12, appprofid=0xC05E), Endpoint( endpoint=13, appprofid=0x0104, appnuminclusters=1, appinclusterlist=[Ota.cluster_id], ), # Insta/Jung/Gira: OTA fallback EP (since it's buggy in firmware 10023202 # when it tries to find a matching EP for OTA - it queries for ZLL profile, # but then contacts with HA profile) Endpoint(endpoint=47, appprofid=0x0104), Endpoint(endpoint=242, appprofid=0xA1E0), ] async def validate_item( znp: API, item, message, subsystem=Subsystem.SYS, command="osalNvRead", expected_status=None, ): result = await znp.request(subsystem, command, item, None, expected_status) if result.payload["value"] != item["value"]: msg = "Item '{}' is invalid, got '{}', expected '{}'".format( message, result.payload["value"], item["value"] ) LOGGER.debug(msg) raise AssertionError(msg) else: LOGGER.debug("Item '%s' is valid", message) async def needsToBeInitialised(znp: API, version, options): try: await validate_item( znp, Items.znpHasConfigured(version), "hasConfigured", expected_status=[0, 2], ) await validate_item(znp, Items.channelList(options.channelList), "channelList") await validate_item( znp, Items.networkKeyDistribute(options.networkKeyDistribute), "networkKeyDistribute", ) if version == ZnpVersion.zStack3x0: await validate_item(znp, Items.networkKey(options.networkKey), "networkKey") else: await validate_item( znp, Items.networkKey(options.networkKey), "networkKey", Subsystem.SAPI, "readConfiguration", ) try: await validate_item(znp, Items.panID(options.panID), "panID") await validate_item( znp, Items.extendedPanID(options.extendedPanID), "extendedPanID" ) except AssertionError as e: if version == ZnpVersion.zStack30x or version == ZnpVersion.zStack3x0: # When the panID has never been set, it will be [0xFF, 0xFF]. result = await znp.request( Subsystem.SYS, "osalNvRead", Items.panID(options.panID) ) LOGGER.debug("PANID: %s", result.payload["value"]) if result.payload["value"] == bytes([0xFF, 0xFF]): LOGGER.debug("Skip enforcing panID because a random panID is used") else: raise e return False except AssertionError as e: LOGGER.debug("Error while validating items: %s", e) return True async def boot(znp: API): result = await znp.request(Subsystem.UTIL, "getDeviceInfo", {}) if result.payload["devicestate"] != Common.devStates["ZB_COORD"]: LOGGER.debug("Start ZNP as coordinator...") started = znp.wait_for( CommandType.AREQ, Subsystem.ZDO, "stateChangeInd", {"state": 9}, 60000 ) await znp.request( Subsystem.ZDO, "startupFromApp", {"startdelay": 100}, None, [0, 1] ) await started.wait() LOGGER.info("ZNP started as coordinator") else: LOGGER.info("ZNP is already started as coordinator") async def registerEndpoints(znp: API): LOGGER.debug("Register endpoints...") active_ep_response = znp.wait_for(CommandType.AREQ, Subsystem.ZDO, "activeEpRsp") asyncio.create_task( znp.request( Subsystem.ZDO, "activeEpReq", {"dstaddr": 0, "nwkaddrofinterest": 0} ) ) active_ep = await active_ep_response.wait() for endpoint in Endpoints: if endpoint.endpoint in active_ep.payload["activeeplist"]: LOGGER.debug("Endpoint '%s' already registered", endpoint.endpoint) else: LOGGER.debug("Registering endpoint '%s'", endpoint.endpoint) await znp.request(Subsystem.AF, "register", vars(endpoint)) async def initialise(znp: API, version, options: NetworkOptions): await znp.request(Subsystem.SYS, "resetReq", {"type": Constants.SYS.resetType.SOFT}) await znp.request(Subsystem.SYS, "osalNvWrite", Items.startupOption(0x02)) await znp.request(Subsystem.SYS, "resetReq", {"type": Constants.SYS.resetType.SOFT}) await znp.request( Subsystem.SYS, "osalNvWrite", Items.logicalType(Constants.ZDO.deviceLogicalType.COORDINATOR), ) await znp.request( Subsystem.SYS, "osalNvWrite", Items.networkKeyDistribute(options.networkKeyDistribute), ) await znp.request(Subsystem.SYS, "osalNvWrite", Items.zdoDirectCb()) await znp.request( Subsystem.SYS, "osalNvWrite", Items.channelList(options.channelList) ) await znp.request(Subsystem.SYS, "osalNvWrite", Items.panID(options.panID)) await znp.request( Subsystem.SYS, "osalNvWrite", Items.extendedPanID(options.extendedPanID) ) if version == ZnpVersion.zStack30x or version == ZnpVersion.zStack3x0: await znp.request( Subsystem.SYS, "osalNvWrite", Items.networkKey(options.networkKey) ) # Default link key is already OK for Z-Stack 3 ('ZigBeeAlliance09') await znp.request( Subsystem.APP_CNF, "bdbSetChannel", {"isPrimary": 0x1, "channel": options.channelList}, ) await znp.request( Subsystem.APP_CNF, "bdbSetChannel", {"isPrimary": 0x0, "channel": 0x0} ) started = znp.wait_for( CommandType.AREQ, Subsystem.ZDO, "stateChangeInd", {"state": 9}, 60000 ) await znp.request(Subsystem.APP_CNF, "bdbStartCommissioning", {"mode": 0x04}) try: await started.wait() except Exception: raise Exception( "Coordinator failed to start, probably the panID is already in use, " "try a different panID or channel" ) await znp.request(Subsystem.APP_CNF, "bdbStartCommissioning", {"mode": 0x02}) else: await znp.request( Subsystem.SAPI, "writeConfiguration", Items.networkKey(options.networkKey) ) await znp.request(Subsystem.SYS, "osalNvWrite", Items.tcLinkKey()) # expect status code 9 (= item created and initialized) await znp.request( Subsystem.SYS, "osalNvItemInit", Items.znpHasConfiguredInit(version), None, [0, 9], ) await znp.request(Subsystem.SYS, "osalNvWrite", Items.znpHasConfigured(version)) async def addToGroup(znp: API, endpoint: int, group: int): result = await znp.request( Subsystem.ZDO, "extFindGroup", {"endpoint": endpoint, "groupid": group}, None, [0, 1], ) if result.payload["status"] == 1: await znp.request( Subsystem.ZDO, "extAddGroup", { "endpoint": endpoint, "groupid": group, "namelen": 0, "groupname": bytes([]), }, ) async def start_znp( znp: API, version, options: NetworkOptions, greenPowerGroup: int, backupPath="" ): result = "resumed" try: await validate_item( znp, Items.znpHasConfigured(version), "hasConfigured", expected_status=[0, 2], ) hasConfigured = True except (AssertionError, CommandError): hasConfigured = False if backupPath and os.path.exists(backupPath) and not hasConfigured: LOGGER.debug("Restoring coordinator from backup") await Restore(znp, backupPath, options) result = "restored" elif await needsToBeInitialised(znp, version, options): LOGGER.debug("Initialize coordinator") await initialise(znp, version, options) if version == ZnpVersion.zStack12: # zStack12 allows to restore a network without restoring a backup # (as long as the network key, panID and channel don't change). # If the device has not been configured yet we assume that this is the case. # If we always return 'reset' # the controller clears the database on a reflash of the stick. result = "reset" if hasConfigured else "restored" else: result = "reset" await boot(znp) await registerEndpoints(znp) # Add to required group to receive greenPower messages. await addToGroup(znp, 242, greenPowerGroup) if result == "restored": # Write channel list again, otherwise it doesnt seem to stick. await znp.request( Subsystem.SYS, "osalNvWrite", Items.channelList(options.channelList) ) return result
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/zigbee/start_znp.py
start_znp.py
import asyncio import logging from asyncio.locks import Semaphore from typing import Any, Dict, Optional import zigpy.application import zigpy.config import zigpy.device import zigpy.types import zigpy.util from zigpy.profiles import zha from zigpy.types import BroadcastAddress from zigpy.zdo.types import ZDOCmd from zigpy_cc import __version__, types as t from zigpy_cc.api import API from zigpy_cc.config import CONF_DEVICE, CONFIG_SCHEMA, SCHEMA_DEVICE from zigpy_cc.exception import TODO, CommandError from zigpy_cc.types import NetworkOptions, Subsystem, ZnpVersion, LedMode, AddressMode from zigpy_cc.zigbee.start_znp import start_znp from zigpy_cc.zpi_object import ZpiObject LOGGER = logging.getLogger(__name__) CHANGE_NETWORK_WAIT = 1 SEND_CONFIRM_TIMEOUT = 60 PROTO_VER_WATCHDOG = 0x0108 REQUESTS = { "nwkAddrReq": (ZDOCmd.NWK_addr_req, 0), "ieeeAddrReq": (ZDOCmd.IEEE_addr_req, 0), "matchDescReq": (ZDOCmd.Match_Desc_req, 2), "endDeviceAnnceInd": (ZDOCmd.Device_annce, 2), "mgmtLqiRsp": (ZDOCmd.Mgmt_Lqi_rsp, 2), "mgmtPermitJoinReq": (ZDOCmd.Mgmt_Permit_Joining_req, 3), "mgmtPermitJoinRsp": (ZDOCmd.Mgmt_Permit_Joining_rsp, 2), "nodeDescRsp": (ZDOCmd.Node_Desc_rsp, 2), "activeEpRsp": (ZDOCmd.Active_EP_rsp, 2), "simpleDescRsp": (ZDOCmd.Simple_Desc_rsp, 2), "bindRsp": (ZDOCmd.Bind_rsp, 2), } IGNORED = ( "bdbComissioningNotifcation", "dataConfirm", "leaveInd", "resetInd", "srcRtgInd", "stateChangeInd", "tcDeviceInd", ) class ControllerApplication(zigpy.application.ControllerApplication): _semaphore: Semaphore _api: Optional[API] SCHEMA = CONFIG_SCHEMA SCHEMA_DEVICE = SCHEMA_DEVICE probe = API.probe def __init__(self, config: Dict[str, Any]): super().__init__(config=zigpy.config.ZIGPY_SCHEMA(config)) self._api = None self.discovering = False self.version = {} async def shutdown(self): """Shutdown application.""" self._api.close() def connection_lost(self): asyncio.create_task(self.reconnect()) async def reconnect(self): while True: if self._api is not None: self._api.close() await asyncio.sleep(5) try: await self.startup(True) break except Exception as e: LOGGER.info("Failed to reconnect: %s", e) pass async def startup(self, auto_form=False): """Perform a complete application startup""" LOGGER.info("Starting zigpy-cc version: %s", __version__) self._api = await API.new(self, self._config[CONF_DEVICE]) try: await self._api.request(Subsystem.SYS, "ping", {"capabilities": 1}) except CommandError as e: raise Exception("Failed to connect to the adapter(%s)", e) self.version = await self._api.version() concurrent = 16 if self.version["product"] == ZnpVersion.zStack3x0 else 2 LOGGER.debug("Adapter concurrent: %d", concurrent) self._semaphore = asyncio.Semaphore(concurrent) ver = ZnpVersion(self.version["product"]).name LOGGER.info("Detected znp version '%s' (%s)", ver, self.version) if auto_form: await self.form_network() data = await self._api.request(Subsystem.UTIL, "getDeviceInfo", {}) self._ieee = data.payload["ieeeaddr"] self._nwk = data.payload["shortaddr"] # add coordinator self.devices[self._ieee] = Coordinator(self, self._ieee, self._nwk) async def permit_with_key(self, node, code, time_s=60): raise TODO("permit_with_key") async def force_remove(self, dev: zigpy.device.Device): """Forcibly remove device from NCP.""" LOGGER.warning("FORCE REMOVE %s", dev) async def form_network(self, channel=15, pan_id=None, extended_pan_id=None): LOGGER.info("Forming network") LOGGER.debug("Config: %s", self.config) options = NetworkOptions(self.config[zigpy.config.CONF_NWK]) LOGGER.debug("NetworkOptions: %s", options) backupPath = "" status = await start_znp( self._api, self.version["product"], options, 0x0B84, backupPath ) LOGGER.info("ZNP started, status: %s", status) self.set_led(LedMode.Off) async def mrequest( self, group_id, profile, cluster, src_ep, sequence, data, *, hops=0, non_member_radius=3 ): """Submit and send data out as a multicast transmission. :param group_id: destination multicast address :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param sequence: transaction sequence number of the message :param data: Zigbee message payload :param hops: the message will be delivered to all nodes within this number of hops of the sender. A value of zero is converted to MAX_HOPS :param non_member_radius: the number of hops that the message will be forwarded by devices that are not members of the group. A value of 7 or greater is treated as infinite :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ LOGGER.debug( "multicast %s", ( group_id, profile, cluster, src_ep, sequence, data, hops, non_member_radius, ), ) try: obj = ZpiObject.from_cluster( group_id, profile, cluster, src_ep or 1, 0xFF, sequence, data, addr_mode=AddressMode.ADDR_GROUP, ) waiter_id = None waiter = self._api.create_response_waiter(obj, sequence) if waiter: waiter_id = waiter.id async with self._semaphore: await self._api.request_raw(obj, waiter_id) """ As a group command is not confirmed and thus immediately returns (contrary to network address requests) we will give the command some time to 'settle' in the network. """ await asyncio.sleep(0.2) except CommandError as ex: return ex.status, "Couldn't enqueue send data multicast: {}".format(ex) return 0, "message send success" @zigpy.util.retryable_request async def request( self, device, profile, cluster, src_ep, dst_ep, sequence, data, expect_reply=True, use_ieee=False, ): LOGGER.debug( "request %s", ( device.nwk, profile, cluster, src_ep, dst_ep, sequence, data, expect_reply, use_ieee, ), ) try: obj = ZpiObject.from_cluster( device.nwk, profile, cluster, src_ep, dst_ep, sequence, data ) waiter_id = None if expect_reply: waiter = self._api.create_response_waiter(obj, sequence) if waiter: waiter_id = waiter.id async with self._semaphore: await self._api.request_raw(obj, waiter_id) except CommandError as ex: return ex.status, "Couldn't enqueue send data request: {}".format(ex) return 0, "message send success" async def broadcast( self, profile, cluster, src_ep, dst_ep, grpid, radius, sequence, data, broadcast_address=zigpy.types.BroadcastAddress.RX_ON_WHEN_IDLE, ): LOGGER.debug( "broadcast %s", ( profile, cluster, src_ep, dst_ep, grpid, radius, sequence, data, broadcast_address, ), ) try: obj = ZpiObject.from_cluster( broadcast_address, profile, cluster, src_ep, dst_ep, sequence, data, radius=radius, addr_mode=AddressMode.ADDR_16BIT, ) async with self._semaphore: await self._api.request_raw(obj) """ As a broadcast command is not confirmed and thus immediately returns (contrary to network address requests) we will give the command some time to 'settle' in the network. """ await asyncio.sleep(0.2) except CommandError as ex: return ( ex.status, "Couldn't enqueue send data request for broadcast: {}".format(ex), ) return 0, "broadcast send success" async def permit_ncp(self, time_s=60): assert 0 <= time_s <= 254 payload = { "addrmode": AddressMode.ADDR_BROADCAST, "dstaddr": BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR, "duration": time_s, "tcsignificance": 0, } async with self._semaphore: await self._api.request(Subsystem.ZDO, "mgmtPermitJoinReq", payload) def handle_znp(self, obj: ZpiObject): if obj.command_type != t.CommandType.AREQ: return frame = obj.to_unpi_frame() nwk = obj.payload["srcaddr"] if "srcaddr" in obj.payload else None ieee = obj.payload["ieeeaddr"] if "ieeeaddr" in obj.payload else None profile_id = zha.PROFILE_ID src_ep = 0 dst_ep = 0 lqi = 0 rssi = 0 if obj.subsystem == t.Subsystem.ZDO and obj.command == "endDeviceAnnceInd": nwk = obj.payload["nwkaddr"] LOGGER.info("New device joined: 0x%04x, %s", nwk, ieee) self.handle_join(nwk, ieee, 0) obj.sequence = 0 if obj.command in IGNORED: return if obj.subsystem == t.Subsystem.ZDO and obj.command == "mgmtPermitJoinRsp": self.set_led(LedMode.On) if obj.subsystem == t.Subsystem.ZDO and obj.command == "permitJoinInd": self.set_led(LedMode.Off if obj.payload["duration"] == 0 else LedMode.On) return if obj.subsystem == t.Subsystem.ZDO and obj.command in REQUESTS: if obj.sequence is None: return LOGGER.debug("REPLY for %d %s", obj.sequence, obj.command) cluster_id, prefix_length = REQUESTS[obj.command] tsn = bytes([obj.sequence]) data = tsn + frame.data[prefix_length:] elif obj.subsystem == t.Subsystem.AF and ( obj.command == "incomingMsg" or obj.command == "incomingMsgExt" ): # ZCL commands cluster_id = obj.payload["clusterid"] src_ep = obj.payload["srcendpoint"] dst_ep = obj.payload["dstendpoint"] data = obj.payload["data"] lqi = obj.payload["linkquality"] else: LOGGER.warning( "Unhandled message: %s %s %s", t.CommandType(obj.command_type), t.Subsystem(obj.subsystem), obj.command, ) return try: if ieee: device = self.get_device(ieee=ieee) else: device = self.get_device(nwk=nwk) except KeyError: LOGGER.warning( "Received frame from unknown device: %s", ieee if ieee else nwk ) return device.radio_details(lqi, rssi) LOGGER.info("handle_message %s", obj.command) self.handle_message(device, profile_id, cluster_id, src_ep, dst_ep, data) def set_led(self, mode: LedMode): if self.version["product"] != ZnpVersion.zStack3x0: try: loop = asyncio.get_event_loop() loop.create_task( self._api.request( Subsystem.UTIL, "ledControl", {"ledid": 3, "mode": mode} ) ) except Exception as ex: LOGGER.warning("Can't set LED: %s", ex) class Coordinator(zigpy.device.Device): """ todo add endpoints? @see zStackAdapter.ts - getCoordinator """ @property def manufacturer(self): return "Texas Instruments" @property def model(self): return "ZNP Coordinator"
zigpy-cc
/zigpy_cc-0.5.2-py3-none-any.whl/zigpy_cc/zigbee/application.py
application.py
from __future__ import annotations import collections import hashlib import json import logging import pathlib import subprocess import click import zigpy.types as t from zigpy.ota.image import ElementTagId, HueSBLOTAImage, parse_ota_image from zigpy.ota.validators import validate_ota_image from zigpy.types.named import _hex_string_to_bytes from zigpy.util import convert_install_code as zigpy_convert_install_code from zigpy_cli.cli import cli from zigpy_cli.common import HEX_OR_DEC_INT LOGGER = logging.getLogger(__name__) def convert_install_code(text: str) -> t.KeyData: code = _hex_string_to_bytes(text) key = zigpy_convert_install_code(code) if key is None: raise ValueError(f"Invalid install code: {text!r}") return key @cli.group() def ota(): pass @ota.command() @click.argument("files", nargs=-1, type=pathlib.Path) def info(files): for f in files: if not f.is_file(): continue try: image, rest = parse_ota_image(f.read_bytes()) except Exception as e: LOGGER.warning("Failed to parse %s: %s", f, e) continue if rest: LOGGER.warning("Image has trailing data %s: %r", f, rest) print(f) print(f"Type: {type(image)}") print(f"Header: {image.header}") if hasattr(image, "subelements"): print(f"Number of subelements: {len(image.subelements)}") try: result = validate_ota_image(image) except Exception as e: LOGGER.warning("Image is invalid %s: %s", f, e) else: print(f"Validation result: {result}") print() @ota.command() @click.argument("input", type=click.File("rb")) @click.argument("output", type=click.File("wb")) def dump_firmware(input, output): image, _ = parse_ota_image(input.read()) if isinstance(image, HueSBLOTAImage): output.write(image.data) else: for subelement in image.subelements: if subelement.tag_id == ElementTagId.UPGRADE_IMAGE: output.write(subelement.data) break else: LOGGER.warning("Image has no UPGRADE_IMAGE subelements") @ota.command() @click.pass_context @click.option("--ota-url-root", type=str, default=None) @click.option("--output", type=click.File("w"), default="-") @click.argument("files", nargs=-1, type=pathlib.Path) def generate_index(ctx, ota_url_root, output, files): if ctx.parent.parent.params["verbose"] == 0: cli.callback(verbose=1) ota_metadata = [] for f in files: if not f.is_file(): continue LOGGER.info("Parsing %s", f) contents = f.read_bytes() try: image, rest = parse_ota_image(contents) except Exception as e: LOGGER.error("Failed to parse: %s", e) continue if rest: LOGGER.error("Image has trailing data: %r", rest) continue try: validate_ota_image(image) except Exception as e: LOGGER.error("Image is invalid: %s", e) if ota_url_root is not None: url = f"{ota_url_root.rstrip('/')}/{f.name}" else: url = None metadata = { "binary_url": url, "file_version": image.header.file_version, "image_type": image.header.image_type, "manufacturer_id": image.header.manufacturer_id, "changelog": "", "checksum": f"sha3-256:{hashlib.sha3_256(contents).hexdigest()}", } if image.header.hardware_versions_present: metadata["min_hardware_version"] = image.header.minimum_hardware_version metadata["max_hardware_version"] = image.header.maximum_hardware_version LOGGER.info("Writing %s", f) ota_metadata.append(metadata) json.dump(ota_metadata, output, indent=4) output.write("\n") @ota.command() @click.pass_context @click.option( "--add-network-key", "network_keys", type=t.KeyData.convert, multiple=True ) @click.option( "--add-install-code", "install_codes", type=convert_install_code, multiple=True ) @click.option("--fill-byte", type=HEX_OR_DEC_INT, default=0xAB) @click.option( "--output-root", type=click.Path(file_okay=False, dir_okay=True, path_type=pathlib.Path), required=True, ) @click.argument("files", nargs=-1, type=pathlib.Path) def reconstruct_from_pcaps( ctx, network_keys, install_codes, fill_byte, output_root, files ): for code in install_codes: print(f"Using key derived from install code: {code}") network_keys = ( [ # ZigBeeAlliance09 t.KeyData.convert("5A:69:67:42:65:65:41:6C:6C:69:61:6E:63:65:30:39"), # Z2M default t.KeyData.convert("01:03:05:07:09:0B:0D:0F:00:02:04:06:08:0A:0C:0D"), ] + list(network_keys) + list(install_codes) ) keys = "\n".join( [f'"{k}","Normal","Network Key {i + 1}"' for i, k in enumerate(network_keys)] ) packets = [] for f in files: proc = subprocess.run( [ "tshark", "-o", f"uat:zigbee_pc_keys:{keys}", "-r", str(f), "-T", "json", ], capture_output=True, ) obj = json.loads(proc.stdout) packets.extend(p["_source"]["layers"] for p in obj) ota_sizes = {} ota_chunks = collections.defaultdict(set) for packet in packets: if "zbee_zcl" not in packet: continue # Ignore non-OTA packets if packet["zbee_aps"]["zbee_aps.cluster"] != "0x0019": continue if ( packet.get("zbee_zcl", {}) .get("Payload", {}) .get("zbee_zcl_general.ota.status") == "0x00" ): zcl = packet["zbee_zcl"]["Payload"] image_version = zcl["zbee_zcl_general.ota.file.version"] image_type = zcl["zbee_zcl_general.ota.image.type"] image_manuf_code = zcl["zbee_zcl_general.ota.manufacturer_code"] image_key = (image_version, image_type, image_manuf_code) if "zbee_zcl_general.ota.image.size" in zcl: image_size = int(zcl["zbee_zcl_general.ota.image.size"]) ota_sizes[image_key] = image_size elif "zbee_zcl_general.ota.image.data" in zcl: offset = int(zcl["zbee_zcl_general.ota.file.offset"]) data = bytes.fromhex( zcl["zbee_zcl_general.ota.image.data"].replace(":", "") ) ota_chunks[image_key].add((offset, data)) unknown_sizes = set() for key in ota_chunks: if key in ota_sizes: continue unknown_sizes.add(key) ota_sizes[key] = max(offset + len(data) for offset, data in ota_chunks[key]) LOGGER.error( "Image size for %s not captured, assuming size %s", key, ota_sizes[key] ) for image_key, image_size in ota_sizes.items(): image_version, image_type, image_manuf_code = image_key print( f"Constructing image type={image_type}, version={image_version}" f", manuf_code={image_manuf_code}: {image_size} bytes" ) buffer = [None] * image_size for offset, chunk in sorted(ota_chunks[image_key]): current_value = buffer[offset : offset + len(chunk)] if ( all(c is not None for c in buffer[offset : offset + len(chunk)]) and current_value != chunk ): LOGGER.error( f"Inconsistent {len(chunk)} bytes starting at offset" f" 0x{offset:08X}: was {current_value}, now {chunk}" ) buffer[offset : offset + len(chunk)] = chunk missing_indices = [o for o, v in enumerate(buffer) if v is None] missing_ranges = [] # For readability, combine the list of missing indices into a list of ranges if missing_indices: start = missing_indices[0] count = 0 for i in missing_indices[1:]: if i == start + count + 1: count += 1 else: missing_ranges.append((start, count + 1)) start = i count = 0 if count > 0: missing_ranges.append((start, count + 1)) for start, count in missing_ranges: LOGGER.error( f"Missing {count} bytes starting at offset 0x{start:08X}:" f" filling with 0x{fill_byte:02X}" ) buffer[start : start + count] = [fill_byte] * count filename = output_root / ( f"ota_t{image_type}_m{image_manuf_code}_v{image_version}" f"{'_unk_size' if image_key in unknown_sizes else ''}" f"{'_partial' if missing_ranges else ''}.ota" ) output_root.mkdir(exist_ok=True) filename.write_bytes(bytes(buffer)) info.callback([filename])
zigpy-cli
/zigpy_cli-1.0.4-py3-none-any.whl/zigpy_cli/ota.py
ota.py
from __future__ import annotations import asyncio import collections import importlib import importlib.util import itertools import json import logging import click import zigpy.state import zigpy.types import zigpy.zdo import zigpy.zdo.types from zigpy_cli.cli import cli, click_coroutine from zigpy_cli.const import RADIO_LOGGING_CONFIGS, RADIO_TO_PACKAGE, RADIO_TO_PYPI LOGGER = logging.getLogger(__name__) @cli.group() @click.pass_context @click.argument("radio", type=click.Choice(list(RADIO_TO_PACKAGE.keys()))) @click.argument("port", type=str) @click.option("--baudrate", type=int, default=None) @click.option("--database", type=str, default=None) @click_coroutine async def radio(ctx, radio, port, baudrate=None, database=None): # Setup logging for the radio verbose = ctx.parent.params["verbose"] logging_configs = RADIO_LOGGING_CONFIGS[radio] logging_config = logging_configs[min(verbose, len(logging_configs) - 1)] for logger, level in logging_config.items(): logging.getLogger(logger).setLevel(level) module = RADIO_TO_PACKAGE[radio] + ".zigbee.application" # Catching just `ImportError` masks dependency errors and is annoying if importlib.util.find_spec(module) is None: raise click.ClickException( f"Radio module for {radio!r} is not installed." f" Install it with `pip install {RADIO_TO_PYPI[radio]}`." ) # Import the radio library radio_module = importlib.import_module(module) # Start the radio app_cls = radio_module.ControllerApplication config = app_cls.SCHEMA( { "device": {"path": port}, "backup_enabled": False, "startup_energy_scan": False, "database_path": database, "use_thread": False, } ) if baudrate is not None: config["device"]["baudrate"] = baudrate app = app_cls(config) ctx.obj = app ctx.call_on_close(radio_cleanup) @click.pass_obj @click_coroutine async def radio_cleanup(app): try: await app.shutdown() except RuntimeError: LOGGER.warning("Caught an exception when shutting down app", exc_info=True) @radio.command() @click.pass_obj @click_coroutine async def info(app): await app.connect() await app.load_network_info(load_devices=False) print(f"PAN ID: 0x{app.state.network_info.pan_id:04X}") print(f"Extended PAN ID: {app.state.network_info.extended_pan_id}") print(f"Channel: {app.state.network_info.channel}") print(f"Channel mask: {list(app.state.network_info.channel_mask)}") print(f"NWK update ID: {app.state.network_info.nwk_update_id}") print(f"Device IEEE: {app.state.node_info.ieee}") print(f"Device NWK: 0x{app.state.node_info.nwk:04X}") print(f"Network key: {app.state.network_info.network_key.key}") print(f"Network key sequence: {app.state.network_info.network_key.seq}") print(f"Network key counter: {app.state.network_info.network_key.tx_counter}") @radio.command() @click.option("-z", "--zigpy-format", is_flag=True, type=bool, default=False) @click.option( "--i-understand-i-can-update-eui64-only-once-and-i-still-want-to-do-it", is_flag=True, type=bool, default=False, ) @click.argument("output", type=click.File("w"), default="-") @click.pass_obj @click_coroutine async def backup( app, zigpy_format, i_understand_i_can_update_eui64_only_once_and_i_still_want_to_do_it, output, ): await app.connect() backup = await app.backups.create_backup(load_devices=True) if i_understand_i_can_update_eui64_only_once_and_i_still_want_to_do_it: backup.network_info.stack_specific.setdefault("ezsp", {})[ "i_understand_i_can_update_eui64_only_once_and_i_still_want_to_do_it" ] = True if zigpy_format: obj = backup.as_dict() else: obj = backup.as_open_coordinator_json() output.write(json.dumps(obj, indent=4) + "\n") @radio.command() @click.argument("input", type=click.File("r")) @click.option("-c", "--frame-counter-increment", type=int, default=5000) @click.pass_obj @click_coroutine async def restore(app, frame_counter_increment, input): obj = json.load(input) backup = zigpy.backups.NetworkBackup.from_dict(obj) await app.connect() await app.backups.restore_backup(backup, counter_increment=frame_counter_increment) @radio.command() @click.pass_obj @click_coroutine async def form(app): await app.connect() await app.form_network() @radio.command() @click.pass_obj @click_coroutine async def reset(app): await app.connect() await app.reset_network_info() @radio.command() @click.pass_obj @click.option("-t", "--join-time", type=int, default=250) @click_coroutine async def permit(app, join_time): await app.startup(auto_form=True) await app.permit(join_time) await asyncio.sleep(join_time) @radio.command() @click.pass_obj @click.option("-n", "--num-scans", type=int, default=-1) @click_coroutine async def energy_scan(app, num_scans): await app.startup() LOGGER.info("Running scan...") # We compute an average over the last 5 scans channel_energies = collections.defaultdict(lambda: collections.deque([], maxlen=5)) for scan in itertools.count(): if num_scans != -1 and scan > num_scans: break results = await app.energy_scan( channels=zigpy.types.Channels.ALL_CHANNELS, duration_exp=2, count=1 ) for channel, energy in results.items(): energies = channel_energies[channel] energies.append(energy) total = 0xFF * len(energies) print(f"Channel energy (mean of {len(energies)} / {energies.maxlen}):") print("------------------------------------------------") print(" ! Different radios compute channel energy differently") print() print(" + Lower energy is better") print(" + Active Zigbee networks on a channel may still cause congestion") print(" + TX on 26 in North America may be with lower power due to regulations") print(" + Zigbee channels 15, 20, 25 fall between WiFi channels 1, 6, 11") print(" + Some Zigbee devices only join networks on channels 15, 20, and 25") print(" + Current channel is enclosed in [square brackets]") print("------------------------------------------------") for channel, energies in channel_energies.items(): count = sum(energies) asterisk = "*" if channel == 26 else " " if channel == app.state.network_info.channel: bracket_open = "[" bracket_close = "]" else: bracket_open = " " bracket_close = " " print( f" - {bracket_open}{channel:>02}{asterisk}{bracket_close}" + f" {count / total:>7.2%} " + "#" * int(100 * count / total) ) print() @radio.command() @click.pass_obj @click.option("-c", "--channel", type=int) @click_coroutine async def change_channel(app, channel): await app.startup() LOGGER.info("Current channel is %s", app.state.network_info.channel) await app.move_network_to_channel(channel)
zigpy-cli
/zigpy_cli-1.0.4-py3-none-any.whl/zigpy_cli/radio.py
radio.py
from __future__ import annotations import asyncio import logging import pathlib import re import sqlite3 import subprocess import tempfile import click import zigpy.appdb from zigpy_znp.zigbee.application import ControllerApplication from zigpy_cli.cli import cli LOGGER = logging.getLogger(__name__) DB_V_REGEX = re.compile(r"(?:_v\d+)?$") @cli.group() def db(): pass def sqlite3_split_statements(sql: str) -> list[str]: """ Splits SQL into a list of statements. """ statements = [] statement = "" chunks = sql.strip().split(";") chunks_with_delimiter = [s + ";" for s in chunks[:-1]] + [chunks[-1]] for chunk in chunks_with_delimiter: statement += chunk if sqlite3.complete_statement(statement): statements.append(statement.strip()) statement = "" if statement: LOGGER.warning("Incomplete data remains after splitting SQL: %r", statement) return statements def sqlite3_recover(path: pathlib.Path) -> str: """ Recovers the contents of an SQLite database as valid SQL. """ return subprocess.check_output(["sqlite3", str(path), ".recover"]).decode("utf-8") def get_table_versions(cursor) -> dict[str, str]: tables = {} cursor.execute("SELECT name FROM sqlite_master WHERE type='table'") for (name,) in cursor: # The regex will always return a match match = DB_V_REGEX.search(name) assert match is not None tables[name] = match.group(0) return tables async def test_database(path: pathlib.Path): """ Opens the zigpy database with zigpy and attempts to load its contents. """ with tempfile.TemporaryDirectory() as dir_name: dir_path = pathlib.Path(dir_name) db_file = dir_path / "zigbee.db" db_file.write_bytes(path.read_bytes()) app = await ControllerApplication.new( {"database_path": str(db_file), "device": {"path": "/dev/null"}}, auto_form=False, start_radio=False, ) await app.shutdown() return app @db.command() @click.argument("input_path", type=click.Path(exists=True)) @click.argument("output_path", type=click.Path()) def recover(input_path, output_path): if pathlib.Path(output_path).exists(): LOGGER.error("Output database already exists: %s", output_path) return # Fetch the user version, it isn't dumped by `.recover` with sqlite3.connect(input_path) as conn: cur = conn.cursor() cur.execute("PRAGMA user_version") (pragma_user_version,) = cur.fetchone() # Get the table suffix versions as well table_versions = get_table_versions(cur) LOGGER.info("Pragma user version is %d", pragma_user_version) max_table_version = max( int(v[2:], 10) for v in table_versions.values() if v.startswith("_v") ) LOGGER.info("Maximum table version is %d", max_table_version) if max_table_version != pragma_user_version: LOGGER.warning( "Maximum table version is %d but the user_version is %d!", max_table_version, pragma_user_version, ) if zigpy.appdb.DB_VERSION != max_table_version: LOGGER.warning( "Zigpy's current DB version is %s but the maximum table version is %s!", zigpy.appdb.DB_VERSION, max_table_version, ) sql = sqlite3_recover(input_path) statements = sqlite3_split_statements(sql) # Perform the `INSERT` statements separately data_sql = [] schema_sql = [f"PRAGMA user_version={max_table_version};"] for statement in statements: if statement.startswith("INSERT"): data_sql.append(statement) else: schema_sql.append(statement) assert schema_sql[-2:] == ["PRAGMA writable_schema = off;", "COMMIT;"] # Finally, perform the recovery with sqlite3.connect(output_path) as conn: cur = conn.cursor() # First create the schema for statement in schema_sql[:-2]: LOGGER.debug("Schema: %s", statement) cur.execute(statement) # Then insert data, logging errors for statement in data_sql: LOGGER.debug("Data: %s", statement) # Ignore internal tables if statement.startswith( ( 'INSERT INTO "sqlite_sequence"(', "CREATE TABLE IF NOT EXISTS sqlite_sequence(", ) ): continue try: cur.execute(statement) except sqlite3.IntegrityError as e: LOGGER.warning("Skipping %s: %r", statement, e) # And finally commit for statement in ["PRAGMA writable_schema = off;", "COMMIT;"]: LOGGER.debug("Postamble: %s", statement) cur.execute(statement) LOGGER.info("Finished writing database") # Load the database with zigpy and test it app = asyncio.run(test_database(pathlib.Path(output_path))) uninitialized_devices = [d for d in app.devices.values() if not d.is_initialized] LOGGER.info( "Recovered %d devices (%d uninitialized)", len(app.devices), len(uninitialized_devices), ) for device in app.devices.values(): LOGGER.info("%s", device)
zigpy-cli
/zigpy_cli-1.0.4-py3-none-any.whl/zigpy_cli/database.py
database.py
import enum import zigpy.types as zigpy_t from zigpy.types import bitmap8, bitmap16 # noqa: F401 def deserialize(data, schema): result = [] for type_ in schema: value, data = type_.deserialize(data) result.append(value) return result, data def serialize(data, schema): return b"".join(t(v).serialize() for t, v in zip(schema, data)) class Bytes(bytes): def serialize(self): return self @classmethod def deserialize(cls, data): return cls(data), b"" class LVBytes(bytes): def serialize(self): return uint16_t(len(self)).serialize() + self @classmethod def deserialize(cls, data, byteorder="little"): length, data = uint16_t.deserialize(data) return cls(data[:length]), data[length:] class int_t(int): _signed = True _size = 0 def serialize(self, byteorder="little"): return self.to_bytes(self._size, byteorder, signed=self._signed) @classmethod def deserialize(cls, data, byteorder="little"): # Work around https://bugs.python.org/issue23640 r = cls(int.from_bytes(data[: cls._size], byteorder, signed=cls._signed)) data = data[cls._size :] return r, data class int8s(int_t): _size = 1 class int16s(int_t): _size = 2 class int24s(int_t): _size = 3 class int32s(int_t): _size = 4 class int40s(int_t): _size = 5 class int48s(int_t): _size = 6 class int56s(int_t): _size = 7 class int64s(int_t): _size = 8 class uint_t(int_t): _signed = False class uint8_t(uint_t): _size = 1 class uint16_t(uint_t): _size = 2 class uint24_t(uint_t): _size = 3 class uint32_t(uint_t): _size = 4 class uint40_t(uint_t): _size = 5 class uint48_t(uint_t): _size = 6 class uint56_t(uint_t): _size = 7 class uint64_t(uint_t): _size = 8 class AddressMode(uint8_t, enum.Enum): # Address modes used in deconz protocol GROUP = 0x01 NWK = 0x02 IEEE = 0x03 NWK_AND_IEEE = 0x04 class DeconzSendDataFlags(bitmap8): NONE = 0x00 NODE_ID = 0x01 RELAYS = 0x02 class DeconzTransmitOptions(bitmap8): NONE = 0x00 SECURITY_ENABLED = 0x01 USE_NWK_KEY_SECURITY = 0x02 USE_APS_ACKS = 0x04 ALLOW_FRAGMENTATION = 0x08 class Struct: _fields = [] def __init__(self, *args, **kwargs): """Initialize instance.""" if len(args) == 1 and isinstance(args[0], self.__class__): # copy constructor for field in self._fields: if hasattr(args[0], field[0]): setattr(self, field[0], getattr(args[0], field[0])) def serialize(self): r = b"" for field in self._fields: if hasattr(self, field[0]): r += getattr(self, field[0]).serialize() return r @classmethod def deserialize(cls, data): """Deserialize data.""" r = cls() for field_name, field_type in cls._fields: v, data = field_type.deserialize(data) setattr(r, field_name, v) return r, data def __eq__(self, other): """Check equality between structs.""" if not isinstance(other, type(self)): return NotImplemented return all(getattr(self, n) == getattr(other, n) for n, _ in self._fields) def __repr__(self): """Instance representation.""" r = f"<{self.__class__.__name__} " r += " ".join([f"{f[0]}={getattr(self, f[0], None)}" for f in self._fields]) r += ">" return r class List(list): _length = None _itemtype = None def serialize(self): assert self._length is None or len(self) == self._length return b"".join([self._itemtype(i).serialize() for i in self]) @classmethod def deserialize(cls, data): assert cls._itemtype is not None r = cls() while data: item, data = cls._itemtype.deserialize(data) r.append(item) return r, data class LVList(list): _length_type = None _itemtype = None def serialize(self): return self._length_type(len(self)).serialize() + b"".join( [self._itemtype(i).serialize() for i in self] ) @classmethod def deserialize(cls, data): length, data = cls._length_type.deserialize(data) r = cls() for _ in range(length): item, data = cls._itemtype.deserialize(data) r.append(item) return r, data class FixedList(List): _length = None _itemtype = None @classmethod def deserialize(cls, data): assert cls._itemtype is not None r = cls() for i in range(cls._length): item, data = cls._itemtype.deserialize(data) r.append(item) return r, data class EUI64(FixedList): _length = 8 _itemtype = uint8_t def __repr__(self): """Instance representation.""" return ":".join("%02x" % i for i in self[::-1]) def __hash__(self): """Hash magic method.""" return hash(repr(self)) class HexRepr: def __repr__(self): """Instance representation.""" return ("0x{:0" + str(self._size * 2) + "x}").format(self) def __str__(self): """Instance str method.""" return ("0x{:0" + str(self._size * 2) + "x}").format(self) class GroupId(HexRepr, uint16_t): pass class NWK(HexRepr, uint16_t): pass class PanId(HexRepr, uint16_t): pass class ExtendedPanId(EUI64): pass class NWKList(LVList): _length_type = uint8_t _itemtype = NWK ZIGPY_ADDR_MODE_MAPPING = { zigpy_t.AddrMode.NWK: AddressMode.NWK, zigpy_t.AddrMode.IEEE: AddressMode.IEEE, zigpy_t.AddrMode.Group: AddressMode.GROUP, zigpy_t.AddrMode.Broadcast: AddressMode.NWK, } ZIGPY_ADDR_TYPE_MAPPING = { zigpy_t.AddrMode.NWK: NWK, zigpy_t.AddrMode.IEEE: EUI64, zigpy_t.AddrMode.Group: GroupId, zigpy_t.AddrMode.Broadcast: NWK, } ZIGPY_ADDR_MODE_REVERSE_MAPPING = { AddressMode.NWK: zigpy_t.AddrMode.NWK, AddressMode.IEEE: zigpy_t.AddrMode.IEEE, AddressMode.GROUP: zigpy_t.AddrMode.Group, AddressMode.NWK_AND_IEEE: zigpy_t.AddrMode.IEEE, } ZIGPY_ADDR_TYPE_REVERSE_MAPPING = { AddressMode.NWK: zigpy_t.NWK, AddressMode.IEEE: zigpy_t.EUI64, AddressMode.GROUP: zigpy_t.Group, AddressMode.NWK_AND_IEEE: zigpy_t.NWK, } class DeconzAddress(Struct): _fields = [ # The address format (AddressMode) ("address_mode", AddressMode), ("address", EUI64), ] @classmethod def deserialize(cls, data): r = cls() mode, data = AddressMode.deserialize(data) r.address_mode = mode if mode in [AddressMode.GROUP, AddressMode.NWK, AddressMode.NWK_AND_IEEE]: r.address, data = NWK.deserialize(data) elif mode == AddressMode.IEEE: r.address, data = EUI64.deserialize(data) if mode == AddressMode.NWK_AND_IEEE: r.ieee, data = EUI64.deserialize(data) return r, data def serialize(self): r = super().serialize() if self.address_mode == AddressMode.NWK_AND_IEEE: r += self.ieee.serialize() return r def as_zigpy_type(self): addr_mode = ZIGPY_ADDR_MODE_REVERSE_MAPPING[self.address_mode] address = ZIGPY_ADDR_TYPE_REVERSE_MAPPING[self.address_mode](self.address) if self.address_mode == AddressMode.NWK and self.address > 0xFFF7: addr_mode = zigpy_t.AddrMode.Broadcast address = zigpy_t.BroadcastAddress(self.address) elif self.address_mode == AddressMode.NWK_AND_IEEE: address = zigpy_t.EUI64(self.ieee) return zigpy_t.AddrModeAddress( addr_mode=addr_mode, address=address, ) @classmethod def from_zigpy_type(cls, addr): instance = cls() instance.address_mode = ZIGPY_ADDR_MODE_MAPPING[addr.addr_mode] instance.address = ZIGPY_ADDR_TYPE_MAPPING[addr.addr_mode](addr.address) return instance class DeconzAddressEndpoint(Struct): _fields = [ # The address format (AddressMode) ("address_mode", AddressMode), ("address", EUI64), ("endpoint", uint8_t), ] @classmethod def deserialize(cls, data): r, data = DeconzAddress.deserialize.__func__(cls, data) if r.address_mode in ( AddressMode.NWK, AddressMode.IEEE, AddressMode.NWK_AND_IEEE, ): r.endpoint, data = uint8_t.deserialize(data) else: r.endpoint = None return r, data def serialize(self): r = uint8_t(self.address_mode).serialize() if self.address_mode in (AddressMode.NWK, AddressMode.NWK_AND_IEEE): r += NWK(self.address).serialize() elif self.address_mode == AddressMode.GROUP: r += GroupId(self.address).serialize() if self.address_mode in (AddressMode.IEEE, AddressMode.NWK_AND_IEEE): r += EUI64(self.address).serialize() if self.address_mode in ( AddressMode.NWK, AddressMode.IEEE, AddressMode.NWK_AND_IEEE, ): r += uint8_t(self.endpoint).serialize() return r @classmethod def from_zigpy_type(cls, addr, endpoint): temp_addr = DeconzAddress.from_zigpy_type(addr) instance = cls() instance.address_mode = temp_addr.address_mode instance.address = temp_addr.address instance.endpoint = endpoint return instance class Key(FixedList): _itemtype = uint8_t _length = 16 class DataIndicationFlags(bitmap8): Always_Use_NWK_Source_Addr = 0b00000001 Last_Hop_In_Reserved_Bytes = 0b00000010 Include_Both_NWK_And_IEEE = 0b00000100
zigpy-deconz
/zigpy_deconz-0.21.0-py3-none-any.whl/zigpy_deconz/types.py
types.py
import asyncio import binascii import logging from typing import Callable, Dict from zigpy.config import CONF_DEVICE_PATH import zigpy.serial LOGGER = logging.getLogger(__name__) DECONZ_BAUDRATE = 38400 class Gateway(asyncio.Protocol): END = b"\xC0" ESC = b"\xDB" ESC_END = b"\xDC" ESC_ESC = b"\xDD" def __init__(self, api, connected_future=None): """Initialize instance of the UART gateway.""" self._api = api self._buffer = b"" self._connected_future = connected_future self._transport = None def connection_lost(self, exc) -> None: """Port was closed expectedly or unexpectedly.""" if exc is not None: LOGGER.warning("Lost connection: %r", exc, exc_info=exc) self._api.connection_lost(exc) def connection_made(self, transport): """Call this when the uart connection is established.""" LOGGER.debug("Connection made") self._transport = transport if self._connected_future and not self._connected_future.done(): self._connected_future.set_result(True) def close(self): self._transport.close() def send(self, data): """Send data, taking care of escaping and framing.""" LOGGER.debug("Send: 0x%s", binascii.hexlify(data).decode()) checksum = bytes(self._checksum(data)) frame = self._escape(data + checksum) self._transport.write(self.END + frame + self.END) def data_received(self, data): """Handle data received from the uart.""" self._buffer += data while self._buffer: end = self._buffer.find(self.END) if end < 0: return None frame = self._buffer[:end] self._buffer = self._buffer[(end + 1) :] frame = self._unescape(frame) if len(frame) < 4: continue checksum = frame[-2:] frame = frame[:-2] if self._checksum(frame) != checksum: LOGGER.warning( "Invalid checksum: 0x%s, data: 0x%s", binascii.hexlify(checksum).decode(), binascii.hexlify(frame).decode(), ) continue LOGGER.debug("Frame received: 0x%s", binascii.hexlify(frame).decode()) try: self._api.data_received(frame) except Exception as exc: LOGGER.error("Unexpected error handling the frame", exc_info=exc) def _unescape(self, data): ret = [] idx = 0 while idx < len(data): b = data[idx] if b == self.ESC[0]: idx += 1 if idx >= len(data): return None elif data[idx] == self.ESC_END[0]: b = self.END[0] elif data[idx] == self.ESC_ESC[0]: b = self.ESC[0] ret.append(b) idx += 1 return bytes(ret) def _escape(self, data): ret = [] for b in data: if b == self.END[0]: ret.append(self.ESC[0]) ret.append(self.ESC_END[0]) elif b == self.ESC[0]: ret.append(self.ESC[0]) ret.append(self.ESC_ESC[0]) else: ret.append(b) return bytes(ret) def _checksum(self, data): ret = [] s = ~(sum(data)) + 1 ret.append(s % 0x100) ret.append((s >> 8) % 0x100) return bytes(ret) async def connect(config: Dict[str, str], api: Callable) -> Gateway: loop = asyncio.get_running_loop() connected_future = loop.create_future() protocol = Gateway(api, connected_future) LOGGER.debug("Connecting to %s", config[CONF_DEVICE_PATH]) _, protocol = await zigpy.serial.create_serial_connection( loop=loop, protocol_factory=lambda: protocol, url=config[CONF_DEVICE_PATH], baudrate=DECONZ_BAUDRATE, xonxoff=False, ) await connected_future LOGGER.debug("Connected to %s", config[CONF_DEVICE_PATH]) return protocol
zigpy-deconz
/zigpy_deconz-0.21.0-py3-none-any.whl/zigpy_deconz/uart.py
uart.py
from __future__ import annotations import asyncio import binascii import enum import functools import logging from typing import Any, Callable from zigpy.config import CONF_DEVICE_PATH import zigpy.exceptions from zigpy.types import APSStatus, Bool, Channels from zigpy.zdo.types import SimpleDescriptor from zigpy_deconz.exception import APIException, CommandError import zigpy_deconz.types as t import zigpy_deconz.uart LOGGER = logging.getLogger(__name__) COMMAND_TIMEOUT = 1.8 PROBE_TIMEOUT = 2 MIN_PROTO_VERSION = 0x010B REQUEST_RETRY_DELAYS = (0.5, 1.0, 1.5, None) class Status(t.uint8_t, enum.Enum): SUCCESS = 0 FAILURE = 1 BUSY = 2 TIMEOUT = 3 UNSUPPORTED = 4 ERROR = 5 NO_NETWORK = 6 INVALID_VALUE = 7 class DeviceState(enum.IntFlag): APSDE_DATA_CONFIRM = 0x04 APSDE_DATA_INDICATION = 0x08 CONF_CHANGED = 0x10 APSDE_DATA_REQUEST_SLOTS_AVAILABLE = 0x20 @classmethod def deserialize(cls, data) -> tuple[DeviceState, bytes]: """Deserialize DevceState.""" state, data = t.uint8_t.deserialize(data) return cls(state), data def serialize(self) -> bytes: """Serialize data.""" return t.uint8_t(self).serialize() @property def network_state(self) -> NetworkState: """Return network state.""" return NetworkState(self & 0x03) class NetworkState(t.uint8_t, enum.Enum): OFFLINE = 0 JOINING = 1 CONNECTED = 2 LEAVING = 3 class SecurityMode(t.uint8_t, enum.Enum): NO_SECURITY = 0x00 PRECONFIGURED_NETWORK_KEY = 0x01 NETWORK_KEY_FROM_TC = 0x02 ONLY_TCLK = 0x03 class ZDPResponseHandling(t.bitmap16): NONE = 0x0000 NodeDescRsp = 0x0001 class Command(t.uint8_t, enum.Enum): aps_data_confirm = 0x04 device_state = 0x07 change_network_state = 0x08 read_parameter = 0x0A write_parameter = 0x0B version = 0x0D device_state_changed = 0x0E aps_data_request = 0x12 aps_data_indication = 0x17 zigbee_green_power = 0x19 mac_poll = 0x1C add_neighbour = 0x1D simplified_beacon = 0x1F class TXStatus(t.uint8_t, enum.Enum): SUCCESS = 0x00 @classmethod def _missing_(cls, value): chained = APSStatus(value) status = t.uint8_t.__new__(cls, chained.value) status._name_ = chained.name status._value_ = value return status TX_COMMANDS = { Command.add_neighbour: (t.uint16_t, t.uint8_t, t.NWK, t.EUI64, t.uint8_t), Command.aps_data_confirm: (t.uint16_t,), Command.aps_data_indication: ( t.uint16_t, t.DataIndicationFlags, ), Command.aps_data_request: ( t.uint16_t, t.uint8_t, t.DeconzSendDataFlags, t.DeconzAddressEndpoint, t.uint16_t, t.uint16_t, t.uint8_t, t.LVBytes, t.uint8_t, t.uint8_t, t.NWKList, # optional ), Command.change_network_state: (t.uint8_t,), Command.device_state: (t.uint8_t, t.uint8_t, t.uint8_t), Command.read_parameter: (t.uint16_t, t.uint8_t, t.Bytes), Command.version: (t.uint32_t,), Command.write_parameter: (t.uint16_t, t.uint8_t, t.Bytes), } RX_COMMANDS = { Command.add_neighbour: ((t.uint16_t, t.uint8_t, t.NWK, t.EUI64, t.uint8_t), True), Command.aps_data_confirm: ( ( t.uint16_t, DeviceState, t.uint8_t, t.DeconzAddressEndpoint, t.uint8_t, TXStatus, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t, ), True, ), Command.aps_data_indication: ( ( t.uint16_t, DeviceState, t.DeconzAddress, t.uint8_t, t.DeconzAddress, t.uint8_t, t.uint16_t, t.uint16_t, t.LVBytes, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t, t.int8s, ), True, ), Command.aps_data_request: ((t.uint16_t, DeviceState, t.uint8_t), True), Command.change_network_state: ((t.uint8_t,), True), Command.device_state: ((DeviceState, t.uint8_t, t.uint8_t), True), Command.device_state_changed: ((DeviceState, t.uint8_t), False), Command.mac_poll: ((t.uint16_t, t.DeconzAddress, t.uint8_t, t.int8s), False), Command.read_parameter: ((t.uint16_t, t.uint8_t, t.Bytes), True), Command.simplified_beacon: ( (t.uint16_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.uint8_t), False, ), Command.version: ((t.uint32_t,), True), Command.write_parameter: ((t.uint16_t, t.uint8_t), True), Command.zigbee_green_power: ((t.LVBytes,), False), } class NetworkParameter(t.uint8_t, enum.Enum): mac_address = 0x01 nwk_panid = 0x05 nwk_address = 0x07 nwk_extended_panid = 0x08 aps_designed_coordinator = 0x09 channel_mask = 0x0A aps_extended_panid = 0x0B trust_center_address = 0x0E security_mode = 0x10 configure_endpoint = 0x13 use_predefined_nwk_panid = 0x15 network_key = 0x18 link_key = 0x19 current_channel = 0x1C permit_join = 0x21 protocol_version = 0x22 nwk_update_id = 0x24 watchdog_ttl = 0x26 nwk_frame_counter = 0x27 app_zdp_response_handling = 0x28 NETWORK_PARAMETER_SCHEMA = { NetworkParameter.mac_address: (t.EUI64,), NetworkParameter.nwk_panid: (t.PanId,), NetworkParameter.nwk_address: (t.NWK,), NetworkParameter.nwk_extended_panid: (t.ExtendedPanId,), NetworkParameter.aps_designed_coordinator: (t.uint8_t,), NetworkParameter.channel_mask: (Channels,), NetworkParameter.aps_extended_panid: (t.ExtendedPanId,), NetworkParameter.trust_center_address: (t.EUI64,), NetworkParameter.security_mode: (t.uint8_t,), NetworkParameter.use_predefined_nwk_panid: (Bool,), NetworkParameter.network_key: (t.uint8_t, t.Key), NetworkParameter.link_key: (t.EUI64, t.Key), NetworkParameter.current_channel: (t.uint8_t,), NetworkParameter.permit_join: (t.uint8_t,), NetworkParameter.configure_endpoint: (t.uint8_t, SimpleDescriptor), NetworkParameter.protocol_version: (t.uint16_t,), NetworkParameter.nwk_update_id: (t.uint8_t,), NetworkParameter.watchdog_ttl: (t.uint32_t,), NetworkParameter.nwk_frame_counter: (t.uint32_t,), NetworkParameter.app_zdp_response_handling: (ZDPResponseHandling,), } class Deconz: """deCONZ API class.""" def __init__(self, app: Callable, device_config: dict[str, Any]): """Init instance.""" self._app = app self._aps_data_ind_flags: t.DataIndicationFlags = ( t.DataIndicationFlags.Always_Use_NWK_Source_Addr ) self._awaiting = {} self._command_lock = asyncio.Lock() self._config = device_config self._data_indication: bool = False self._data_confirm: bool = False self._device_state = DeviceState(NetworkState.OFFLINE) self._seq = 1 self._proto_ver: int | None = None self._firmware_version: int | None = None self._uart: zigpy_deconz.uart.Gateway | None = None @property def firmware_version(self) -> int | None: """Return ConBee firmware version.""" return self._firmware_version @property def network_state(self) -> NetworkState: """Return current network state.""" return self._device_state.network_state @property def protocol_version(self) -> int | None: """Protocol Version.""" return self._proto_ver async def connect(self) -> None: assert self._uart is None self._uart = await zigpy_deconz.uart.connect(self._config, self) def connection_lost(self, exc: Exception) -> None: """Lost serial connection.""" LOGGER.debug( "Serial %r connection lost unexpectedly: %r", self._config[CONF_DEVICE_PATH], exc, ) if self._app is not None: self._app.connection_lost(exc) def close(self): self._app = None if self._uart is not None: self._uart.close() self._uart = None async def _command(self, cmd, *args): if self._uart is None: # connection was lost raise CommandError(Status.ERROR, "API is not running") async with self._command_lock: LOGGER.debug("Command %s %s", cmd, args) data, seq = self._api_frame(cmd, *args) self._uart.send(data) fut = asyncio.Future() self._awaiting[seq] = fut try: return await asyncio.wait_for(fut, timeout=COMMAND_TIMEOUT) except asyncio.TimeoutError: LOGGER.warning( "No response to '%s' command with seq id '0x%02x'", cmd, seq ) self._awaiting.pop(seq, None) raise def _api_frame(self, cmd, *args): schema = TX_COMMANDS[cmd] d = t.serialize(args, schema) data = t.uint8_t(cmd).serialize() self._seq = (self._seq % 255) + 1 data += t.uint8_t(self._seq).serialize() data += t.uint8_t(0).serialize() data += t.uint16_t(len(d) + 5).serialize() data += d return data, self._seq def data_received(self, data): try: command = Command(data[0]) schema, solicited = RX_COMMANDS[command] except ValueError: LOGGER.debug("Unknown command received: 0x%02x", data[0]) return seq = data[1] try: status = Status(data[2]) except ValueError: status = data[2] fut = None if solicited and seq in self._awaiting: fut = self._awaiting.pop(seq) if status != Status.SUCCESS: try: fut.set_exception( CommandError(status, f"{command}, status: {status}") ) except asyncio.InvalidStateError: LOGGER.warning( "Duplicate or delayed response for 0x:%02x sequence", seq ) return try: data, _ = t.deserialize(data[5:], schema) except Exception: LOGGER.warning("Failed to deserialize frame: %s", binascii.hexlify(data)) if fut is not None and not fut.done(): fut.set_exception( APIException( f"Failed to deserialize frame: {binascii.hexlify(data)}" ) ) return if fut is not None: try: fut.set_result(data) except asyncio.InvalidStateError: LOGGER.warning( "Duplicate or delayed response for 0x:%02x sequence", seq ) LOGGER.debug("Received command %s%r", command.name, data) getattr(self, f"_handle_{command.name}")(data) add_neighbour = functools.partialmethod(_command, Command.add_neighbour, 12) device_state = functools.partialmethod(_command, Command.device_state, 0, 0, 0) change_network_state = functools.partialmethod( _command, Command.change_network_state ) def _handle_device_state(self, data): LOGGER.debug("Device state response: %s", data) self._handle_device_state_value(data[0]) def _handle_change_network_state(self, data): LOGGER.debug("Change network state response: %s", NetworkState(data[0]).name) @classmethod async def probe(cls, device_config: dict[str, Any]) -> bool: """Probe port for the device presence.""" api = cls(None, device_config) try: await asyncio.wait_for(api._probe(), timeout=PROBE_TIMEOUT) return True except Exception as exc: LOGGER.debug( "Unsuccessful radio probe of '%s' port", device_config[CONF_DEVICE_PATH], exc_info=exc, ) finally: api.close() return False async def _probe(self) -> None: """Open port and try sending a command.""" await self.connect() await self.device_state() self.close() async def read_parameter(self, id_, *args): try: if isinstance(id_, str): param = NetworkParameter[id_] else: param = NetworkParameter(id_) except (KeyError, ValueError): raise KeyError(f"Unknown parameter id: {id_}") data = t.serialize(args, NETWORK_PARAMETER_SCHEMA[param]) r = await self._command(Command.read_parameter, 1 + len(data), param, data) data = t.deserialize(r[2], NETWORK_PARAMETER_SCHEMA[param])[0] LOGGER.debug("Read parameter %s response: %s", param.name, data) return data def reconnect(self): """Reconnect using saved parameters.""" LOGGER.debug("Reconnecting '%s' serial port", self._config[CONF_DEVICE_PATH]) return self.connect() def _handle_read_parameter(self, data): pass def write_parameter(self, id_, *args): try: if isinstance(id_, str): param = NetworkParameter[id_] else: param = NetworkParameter(id_) except (KeyError, ValueError): raise KeyError(f"Unknown parameter id: {id_} write request") v = t.serialize(args, NETWORK_PARAMETER_SCHEMA[param]) length = len(v) + 1 return self._command(Command.write_parameter, length, param, v) def _handle_write_parameter(self, data): try: param = NetworkParameter(data[1]) except ValueError: LOGGER.error("Received unknown network param id '%s' response", data[1]) return LOGGER.debug("Write parameter %s: SUCCESS", param.name) async def version(self): (self._proto_ver,) = await self.read_parameter( NetworkParameter.protocol_version ) (self._firmware_version,) = await self._command(Command.version, 0) if ( self.protocol_version >= MIN_PROTO_VERSION and (self.firmware_version & 0x0000FF00) == 0x00000500 ): self._aps_data_ind_flags = t.DataIndicationFlags.Include_Both_NWK_And_IEEE return self.firmware_version def _handle_version(self, data): LOGGER.debug("Version response: %x", data[0]) def _handle_device_state_changed(self, data): LOGGER.debug("Device state changed response: %s", data) self._handle_device_state_value(data[0]) async def _aps_data_indication(self): try: r = await self._command( Command.aps_data_indication, 1, self._aps_data_ind_flags ) LOGGER.debug( ( "'aps_data_indication' response from %s, ep: %s, " "profile: 0x%04x, cluster_id: 0x%04x, data: %s" ), r[4], r[5], r[6], r[7], binascii.hexlify(r[8]), ) return r except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException): pass finally: self._data_indication = False def _handle_aps_data_indication(self, data): LOGGER.debug("APS data indication response: %s", data) self._data_indication = False self._handle_device_state_value(data[1]) if not self._app: return self._app.handle_rx( src=data[4], src_ep=data[5], dst=data[2], dst_ep=data[3], profile_id=data[6], cluster_id=data[7], data=data[8], lqi=data[11], rssi=data[16], ) async def aps_data_request( self, req_id, dst_addr_ep, profile, cluster, src_ep, aps_payload, *, relays=None, tx_options=t.DeconzTransmitOptions.USE_NWK_KEY_SECURITY, radius=0, ): dst = dst_addr_ep.serialize() length = len(dst) + len(aps_payload) + 11 flags = t.DeconzSendDataFlags.NONE extras = [] # https://github.com/zigpy/zigpy-deconz/issues/180#issuecomment-1017932865 if relays: # There is a max of 9 relays assert len(relays) <= 9 flags |= t.DeconzSendDataFlags.RELAYS extras.append(t.NWKList(relays)) length += sum(len(e.serialize()) for e in extras) for delay in REQUEST_RETRY_DELAYS: try: return await self._command( Command.aps_data_request, length, req_id, flags, dst_addr_ep, profile, cluster, src_ep, aps_payload, tx_options, radius, *extras, ) except CommandError as ex: LOGGER.debug("'aps_data_request' failure: %s", ex) if delay is None or ex.status != Status.BUSY: raise LOGGER.debug("retrying 'aps_data_request' in %ss", delay) await asyncio.sleep(delay) def _handle_aps_data_request(self, data): LOGGER.debug("APS data request response: %s", data) self._handle_device_state_value(data[1]) async def _aps_data_confirm(self): try: r = await self._command(Command.aps_data_confirm, 0) LOGGER.debug( "Request id: 0x%02x 'aps_data_confirm' for %s, status: 0x%02x", r[2], r[3], r[5], ) return r except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException): pass finally: self._data_confirm = False def _handle_add_neighbour(self, data) -> None: """Handle add_neighbour response.""" LOGGER.debug("add neighbour response: %s", data) def _handle_aps_data_confirm(self, data): LOGGER.debug( "APS data confirm response for request with id %s: %02x", data[2], data[5] ) self._data_confirm = False self._handle_device_state_value(data[1]) self._app.handle_tx_confirm(data[2], data[5]) def _handle_mac_poll(self, data): pass def _handle_zigbee_green_power(self, data): pass def _handle_simplified_beacon(self, data): LOGGER.debug( ( "Received simplified beacon frame: source=0x%04x, " "pan_id=0x%04x, channel=%s, flags=0x%02x, " "update_id=0x%02x" ), data[1], data[2], data[3], data[4], data[5], ) def _handle_device_state_value(self, state: DeviceState) -> None: if state.network_state != self.network_state: LOGGER.debug( "Network state transition: %s -> %s", self.network_state.name, state.network_state.name, ) self._device_state = state if DeviceState.APSDE_DATA_REQUEST_SLOTS_AVAILABLE not in state: LOGGER.debug("Data request queue full.") if DeviceState.APSDE_DATA_INDICATION in state and not self._data_indication: self._data_indication = True asyncio.create_task(self._aps_data_indication()) if DeviceState.APSDE_DATA_CONFIRM in state and not self._data_confirm: self._data_confirm = True asyncio.create_task(self._aps_data_confirm()) def __getitem__(self, key): """Access parameters via getitem.""" return self.read_parameter(key)
zigpy-deconz
/zigpy_deconz-0.21.0-py3-none-any.whl/zigpy_deconz/api.py
api.py
from __future__ import annotations import asyncio import logging import re from typing import Any import zigpy.application import zigpy.config import zigpy.device import zigpy.endpoint import zigpy.exceptions from zigpy.exceptions import FormationFailure, NetworkNotFormed import zigpy.state import zigpy.types import zigpy.util import zigpy.zdo.types as zdo_t import zigpy_deconz from zigpy_deconz import types as t from zigpy_deconz.api import ( Deconz, NetworkParameter, NetworkState, SecurityMode, Status, TXStatus, ) from zigpy_deconz.config import CONF_WATCHDOG_TTL, CONFIG_SCHEMA, SCHEMA_DEVICE import zigpy_deconz.exception LOGGER = logging.getLogger(__name__) CHANGE_NETWORK_WAIT = 1 DELAY_NEIGHBOUR_SCAN_S = 1500 SEND_CONFIRM_TIMEOUT = 60 PROTO_VER_MANUAL_SOURCE_ROUTE = 0x010C PROTO_VER_WATCHDOG = 0x0108 PROTO_VER_NEIGBOURS = 0x0107 class ControllerApplication(zigpy.application.ControllerApplication): SCHEMA = CONFIG_SCHEMA SCHEMA_DEVICE = SCHEMA_DEVICE def __init__(self, config: dict[str, Any]): """Initialize instance.""" super().__init__(config=zigpy.config.ZIGPY_SCHEMA(config)) self._api = None self._pending = zigpy.util.Requests() self.version = 0 self._reset_watchdog_task = None self._reconnect_task = None self._written_endpoints = set() async def _reset_watchdog(self): while True: try: await self._api.write_parameter( NetworkParameter.watchdog_ttl, self._config[CONF_WATCHDOG_TTL] ) except Exception as e: LOGGER.warning("Failed to reset watchdog", exc_info=e) self.connection_lost(e) return await asyncio.sleep(self._config[CONF_WATCHDOG_TTL] * 0.75) async def connect(self): api = Deconz(self, self._config[zigpy.config.CONF_DEVICE]) try: await api.connect() self.version = await api.version() except Exception: api.close() raise self._api = api self._written_endpoints.clear() def close(self): if self._reset_watchdog_task is not None: self._reset_watchdog_task.cancel() self._reset_watchdog_task = None if self._reconnect_task is not None: self._reconnect_task.cancel() self._reconnect_task = None if self._api is not None: self._api.close() self._api = None async def disconnect(self): self.close() if self._api is not None: self._api.close() async def permit_with_key(self, node: t.EUI64, code: bytes, time_s=60): raise NotImplementedError() async def start_network(self): await self.register_endpoints() await self.load_network_info(load_devices=False) await self._change_network_state(NetworkState.CONNECTED) coordinator = await DeconzDevice.new( self, self.state.node_info.ieee, self.state.node_info.nwk, self.version, self._config[zigpy.config.CONF_DEVICE][zigpy.config.CONF_DEVICE_PATH], ) self.devices[self.state.node_info.ieee] = coordinator if self._api.protocol_version >= PROTO_VER_NEIGBOURS: await self.restore_neighbours() asyncio.create_task(self._delayed_neighbour_scan()) async def _change_network_state( self, target_state: NetworkState, *, timeout: int = 10 * CHANGE_NETWORK_WAIT ): async def change_loop(): while True: (state, _, _) = await self._api.device_state() if state.network_state == target_state: break await asyncio.sleep(CHANGE_NETWORK_WAIT) await self._api.change_network_state(target_state) try: await asyncio.wait_for(change_loop(), timeout=timeout) except asyncio.TimeoutError: if target_state != NetworkState.CONNECTED: raise raise FormationFailure( "Network formation refused: there is likely too much RF interference." " Make sure your coordinator is on a USB 2.0 extension cable and" " away from any sources of interference, like USB 3.0 ports, SSDs," " 2.4GHz routers, motherboards, etc." ) if self._api.protocol_version < PROTO_VER_WATCHDOG: return if self._reset_watchdog_task is not None: self._reset_watchdog_task.cancel() if target_state == NetworkState.CONNECTED: self._reset_watchdog_task = asyncio.create_task(self._reset_watchdog()) async def reset_network_info(self): # TODO: There does not appear to be a way to factory reset a Conbee await self.form_network() async def write_network_info(self, *, network_info, node_info): try: await self._api.write_parameter( NetworkParameter.nwk_frame_counter, network_info.network_key.tx_counter ) except zigpy_deconz.exception.CommandError as ex: assert ex.status == Status.UNSUPPORTED LOGGER.warning( "Writing the network frame counter is not supported with this firmware," " please update your Conbee" ) if node_info.logical_type == zdo_t.LogicalType.Coordinator: await self._api.write_parameter( NetworkParameter.aps_designed_coordinator, 1 ) else: await self._api.write_parameter( NetworkParameter.aps_designed_coordinator, 0 ) await self._api.write_parameter(NetworkParameter.nwk_address, node_info.nwk) if node_info.ieee != zigpy.types.EUI64.UNKNOWN: # TODO: is there a way to revert it back to the hardware default? Or is this # information lost when the parameter is overwritten? await self._api.write_parameter( NetworkParameter.mac_address, node_info.ieee ) node_ieee = node_info.ieee else: (ieee,) = await self._api[NetworkParameter.mac_address] node_ieee = zigpy.types.EUI64(ieee) # There is no way to specify both a mask and the logical channel if network_info.channel is not None: channel_mask = zigpy.types.Channels.from_channel_list( [network_info.channel] ) if network_info.channel_mask and channel_mask != network_info.channel_mask: LOGGER.warning( "Channel mask %s will be replaced with current logical channel %s", network_info.channel_mask, channel_mask, ) else: channel_mask = network_info.channel_mask await self._api.write_parameter(NetworkParameter.channel_mask, channel_mask) await self._api.write_parameter(NetworkParameter.use_predefined_nwk_panid, True) await self._api.write_parameter(NetworkParameter.nwk_panid, network_info.pan_id) await self._api.write_parameter( NetworkParameter.aps_extended_panid, network_info.extended_pan_id ) await self._api.write_parameter( NetworkParameter.nwk_update_id, network_info.nwk_update_id ) await self._api.write_parameter( NetworkParameter.network_key, 0, network_info.network_key.key ) if network_info.network_key.seq != 0: LOGGER.warning( "Non-zero network key sequence number is not supported: %s", network_info.network_key.seq, ) tc_link_key_partner_ieee = network_info.tc_link_key.partner_ieee if tc_link_key_partner_ieee == zigpy.types.EUI64.UNKNOWN: tc_link_key_partner_ieee = node_ieee await self._api.write_parameter( NetworkParameter.trust_center_address, tc_link_key_partner_ieee, ) await self._api.write_parameter( NetworkParameter.link_key, tc_link_key_partner_ieee, network_info.tc_link_key.key, ) if network_info.security_level == 0x00: await self._api.write_parameter( NetworkParameter.security_mode, SecurityMode.NO_SECURITY ) else: await self._api.write_parameter( NetworkParameter.security_mode, SecurityMode.ONLY_TCLK ) # Note: Changed network configuration parameters become only affective after # sending a Leave Network Request followed by a Create or Join Network Request await self._change_network_state(NetworkState.OFFLINE) await self._change_network_state(NetworkState.CONNECTED) async def load_network_info(self, *, load_devices=False): network_info = self.state.network_info node_info = self.state.node_info network_info.source = f"zigpy-deconz@{zigpy_deconz.__version__}" network_info.metadata = { "deconz": { "version": self.version, } } (ieee,) = await self._api[NetworkParameter.mac_address] node_info.ieee = zigpy.types.EUI64(ieee) (designed_coord,) = await self._api[NetworkParameter.aps_designed_coordinator] if designed_coord == 0x01: node_info.logical_type = zdo_t.LogicalType.Coordinator else: node_info.logical_type = zdo_t.LogicalType.Router (node_info.nwk,) = await self._api[NetworkParameter.nwk_address] (network_info.pan_id,) = await self._api[NetworkParameter.nwk_panid] (network_info.extended_pan_id,) = await self._api[ NetworkParameter.aps_extended_panid ] if network_info.extended_pan_id == zigpy.types.EUI64.convert( "00:00:00:00:00:00:00:00" ): (network_info.extended_pan_id,) = await self._api[ NetworkParameter.nwk_extended_panid ] (network_info.channel,) = await self._api[NetworkParameter.current_channel] (network_info.channel_mask,) = await self._api[NetworkParameter.channel_mask] (network_info.nwk_update_id,) = await self._api[NetworkParameter.nwk_update_id] if network_info.channel == 0: raise NetworkNotFormed("Network channel is zero") network_info.network_key = zigpy.state.Key() ( _, network_info.network_key.key, ) = await self._api.read_parameter(NetworkParameter.network_key, 0) try: (network_info.network_key.tx_counter,) = await self._api[ NetworkParameter.nwk_frame_counter ] except zigpy_deconz.exception.CommandError as ex: assert ex.status == Status.UNSUPPORTED network_info.tc_link_key = zigpy.state.Key() (network_info.tc_link_key.partner_ieee,) = await self._api[ NetworkParameter.trust_center_address ] (_, network_info.tc_link_key.key) = await self._api.read_parameter( NetworkParameter.link_key, network_info.tc_link_key.partner_ieee, ) (security_mode,) = await self._api[NetworkParameter.security_mode] if security_mode == SecurityMode.NO_SECURITY: network_info.security_level = 0x00 elif security_mode == SecurityMode.ONLY_TCLK: network_info.security_level = 0x05 else: LOGGER.warning("Unsupported security mode %r", security_mode) network_info.security_level = 0x05 async def force_remove(self, dev): """Forcibly remove device from NCP.""" async def energy_scan( self, channels: t.Channels.ALL_CHANNELS, duration_exp: int, count: int ) -> dict[int, float]: results = await super().energy_scan( channels=channels, duration_exp=duration_exp, count=count ) # The Conbee seems to max out at an LQI of 85, which is exactly 255/3 return {c: v * 3 for c, v in results.items()} async def _move_network_to_channel( self, new_channel: int, new_nwk_update_id: int ) -> None: """Move device to a new channel.""" channel_mask = zigpy.types.Channels.from_channel_list([new_channel]) await self._api.write_parameter(NetworkParameter.channel_mask, channel_mask) await self._api.write_parameter( NetworkParameter.nwk_update_id, new_nwk_update_id ) await self._change_network_state(NetworkState.OFFLINE) await self._change_network_state(NetworkState.CONNECTED) async def add_endpoint(self, descriptor: zdo_t.SimpleDescriptor) -> None: """Register an endpoint on the device, replacing any with conflicting IDs.""" endpoints = {} # Read and count the current endpoints. Some firmwares have three, others four. for index in range(255 + 1): try: _, current_descriptor = await self._api.read_parameter( NetworkParameter.configure_endpoint, index ) except zigpy_deconz.exception.CommandError as ex: assert ex.status == Status.UNSUPPORTED break else: endpoints[index] = current_descriptor LOGGER.debug("Got endpoint slots: %r", endpoints) # Don't write endpoints unnecessarily if descriptor in endpoints.values(): LOGGER.debug("Endpoint already registered, skipping") # Pretend we wrote it self._written_endpoints.add(list(endpoints.values()).index(descriptor)) return # Keep track of the best endpoint descriptor to replace target_index = None for index, current_descriptor in endpoints.items(): # Ignore ones we've already written if index in self._written_endpoints: continue target_index = index if current_descriptor.endpoint == descriptor.endpoint: # Prefer to replace the endpoint with the same ID break if target_index is None: raise ValueError(f"No available endpoint slots exist: {endpoints!r}") LOGGER.debug("Writing %s to slot %r", descriptor, target_index) await self._api.write_parameter( NetworkParameter.configure_endpoint, target_index, descriptor ) async def send_packet(self, packet): LOGGER.debug("Sending packet: %r", packet) tx_options = t.DeconzTransmitOptions.USE_NWK_KEY_SECURITY if ( zigpy.types.TransmitOptions.ACK in packet.tx_options and packet.dst.addr_mode in (zigpy.types.AddrMode.NWK, zigpy.types.AddrMode.IEEE) ): tx_options |= t.DeconzTransmitOptions.USE_APS_ACKS async with self._limit_concurrency(): req_id = self.get_sequence() with self._pending.new(req_id) as req: try: await self._api.aps_data_request( req_id=req_id, dst_addr_ep=t.DeconzAddressEndpoint.from_zigpy_type( packet.dst, packet.dst_ep or 0 ), profile=packet.profile_id, cluster=packet.cluster_id, src_ep=min(1, packet.src_ep), aps_payload=packet.data.serialize(), tx_options=tx_options, relays=packet.source_route, radius=packet.radius or 0, ) except zigpy_deconz.exception.CommandError as ex: raise zigpy.exceptions.DeliveryError( f"Failed to enqueue packet: {ex!r}", ex.status ) status = await asyncio.wait_for(req.result, SEND_CONFIRM_TIMEOUT) if status != TXStatus.SUCCESS: raise zigpy.exceptions.DeliveryError( f"Failed to deliver packet: {status!r}", status ) def handle_rx( self, src, src_ep, dst, dst_ep, profile_id, cluster_id, data, lqi, rssi ): self.packet_received( zigpy.types.ZigbeePacket( src=src.as_zigpy_type(), src_ep=src_ep, dst=dst.as_zigpy_type(), dst_ep=dst_ep, tsn=None, profile_id=profile_id, cluster_id=cluster_id, data=zigpy.types.SerializableBytes(data), lqi=lqi, rssi=rssi, ) ) async def permit_ncp(self, time_s=60): assert 0 <= time_s <= 254 await self._api.write_parameter(NetworkParameter.permit_join, time_s) def handle_tx_confirm(self, req_id, status): try: self._pending[req_id].result.set_result(status) return except KeyError: LOGGER.warning( "Unexpected transmit confirm for request id %s, Status: %s", req_id, status, ) except asyncio.InvalidStateError as exc: LOGGER.debug( "Invalid state on future - probably duplicate response: %s", exc ) async def restore_neighbours(self) -> None: """Restore children.""" coord = self.get_device(ieee=self.state.node_info.ieee) for neighbor in self.topology.neighbors[coord.ieee]: try: device = self.get_device(ieee=neighbor.ieee) except KeyError: continue descr = device.node_desc LOGGER.debug( "device: 0x%04x - %s %s, FFD=%s, Rx_on_when_idle=%s", device.nwk, device.manufacturer, device.model, descr.is_full_function_device if descr is not None else None, descr.is_receiver_on_when_idle if descr is not None else None, ) if ( descr is None or descr.is_full_function_device or descr.is_receiver_on_when_idle ): continue LOGGER.debug( "Restoring %s/0x%04x device as direct child", device.ieee, device.nwk, ) await self._api.add_neighbour( 0x01, device.nwk, device.ieee, descr.mac_capability_flags ) async def _delayed_neighbour_scan(self) -> None: """Scan coordinator's neighbours.""" await asyncio.sleep(DELAY_NEIGHBOUR_SCAN_S) coord = self.get_device(ieee=self.state.node_info.ieee) await self.topology.scan(devices=[coord]) def connection_lost(self, exc: Exception) -> None: """Lost connection.""" if exc is not None: LOGGER.warning("Lost connection: %r", exc) self.close() self._reconnect_task = asyncio.create_task(self._reconnect_loop()) async def _reconnect_loop(self) -> None: attempt = 1 while True: LOGGER.debug("Reconnecting, attempt %s", attempt) try: await asyncio.wait_for(self.connect(), timeout=10) await asyncio.wait_for(self.initialize(), timeout=10) break except Exception as exc: wait = 2 ** min(attempt, 5) attempt += 1 LOGGER.debug( "Couldn't re-open '%s' serial port, retrying in %ss: %s", self._config[zigpy.config.CONF_DEVICE][ zigpy.config.CONF_DEVICE_PATH ], wait, str(exc), exc_info=exc, ) await asyncio.sleep(wait) LOGGER.debug( "Reconnected '%s' serial port after %s attempts", self._config[zigpy.config.CONF_DEVICE][zigpy.config.CONF_DEVICE_PATH], attempt, ) class DeconzDevice(zigpy.device.Device): """Zigpy Device representing Coordinator.""" def __init__(self, version: int, device_path: str, *args): """Initialize instance.""" super().__init__(*args) is_gpio_device = re.match(r"/dev/tty(S|AMA|ACM)\d+", device_path) self._model = "RaspBee" if is_gpio_device else "ConBee" self._model += " II" if ((version & 0x0000FF00) == 0x00000700) else "" async def add_to_group(self, grp_id: int, name: str = None) -> None: group = self.application.groups.add_group(grp_id, name) for epid in self.endpoints: if not epid: continue # skip ZDO group.add_member(self.endpoints[epid]) return [0] async def remove_from_group(self, grp_id: int) -> None: for epid in self.endpoints: if not epid: continue # skip ZDO self.application.groups[grp_id].remove_member(self.endpoints[epid]) return [0] @property def manufacturer(self): return "dresden elektronik" @property def model(self): return self._model @classmethod async def new(cls, application, ieee, nwk, version: int, device_path: str): """Create or replace zigpy device.""" dev = cls(version, device_path, application, ieee, nwk) if ieee in application.devices: from_dev = application.get_device(ieee=ieee) dev.status = from_dev.status dev.node_desc = from_dev.node_desc for ep_id, from_ep in from_dev.endpoints.items(): if not ep_id: continue # Skip ZDO ep = dev.add_endpoint(ep_id) ep.profile_id = from_ep.profile_id ep.device_type = from_ep.device_type ep.status = from_ep.status ep.in_clusters = from_ep.in_clusters ep.out_clusters = from_ep.out_clusters else: application.devices[ieee] = dev await dev.initialize() return dev
zigpy-deconz
/zigpy_deconz-0.21.0-py3-none-any.whl/zigpy_deconz/zigbee/application.py
application.py
# zigpy [![Build Status](https://travis-ci.org/zigpy/zigpy.svg?branch=master)](https://travis-ci.org/zigpy/zigpy) [![Coverage](https://coveralls.io/repos/github/zigpy/zigpy/badge.svg?branch=master)](https://coveralls.io/github/zigpy/zigpy?branch=master) **[zigpy](https://github.com/zigpy/zigpy)** is **[Zigbee protocol stack](https://en.wikipedia.org/wiki/Zigbee)** integration project to implement the **[Zigbee Home Automation](https://www.zigbee.org/)** standard as a Python 3 library. Zigbee Home Automation integration with zigpy allows you to connect one of many off-the-shelf Zigbee adapters using one of the available Zigbee radio library modules compatible with zigpy to control Zigbee based devices. There is currently support for controlling Zigbee device types such as binary sensors (e.g., motion and door sensors), sensors (e.g., temperature sensors), lightbulbs, switches, and fans. A working implementation of zigbe exist in **[Home Assistant](https://www.home-assistant.io)** (Python based open source home automation software) as part of its **[ZHA component](https://www.home-assistant.io/components/zha/)** ## Compatible hardware zigpy works with separate radio libraries which can each interface with multiple USB and GPIO radio hardware adapters/modules over different native UART serial protocols. Such radio libraries includes **[bellows](https://github.com/zigpy/bellows)** (which communicates with EZSP/EmberZNet based radios), **[zigpy-xbee](https://github.com/zigpy/zigpy-xbee)** (which communicates with XBee based Zigbee radios), and as **[zigpy-deconz](https://github.com/zigpy/zigpy-deconz)** for deCONZ serial protocol (for communicating with ConBee and RaspBee USB and GPIO radios from Dresden-Elektronik). There are also experimental radio libraries called **[zigpy-zigate](https://github.com/doudz/zigpy-zigate)** for communicating with ZiGate based radios and **[zigpy-cc](https://github.com/sanyatuning/zigpy-cc)** for communicating with Texas Instruments based radios based radios that have custom Z-Stack coordinator firmware. ### Known working Zigbee radio modules - **EmberZNet based radios** using the EZSP protocol (via the [bellows](https://github.com/zigpy/bellows) library for zigpy) - [Nortek GoControl QuickStick Combo Model HUSBZB-1 (Z-Wave & Zigbee USB Adapter)](https://www.nortekcontrol.com/products/2gig/husbzb-1-gocontrol-quickstick-combo/) - [Elelabs Zigbee USB Adapter](https://elelabs.com/products/elelabs_usb_adapter.html) - [Elelabs Zigbee Raspberry Pi Shield](https://elelabs.com/products/elelabs_zigbee_shield.html) - Telegesis ETRX357USB (Note! First have to be flashed with other EmberZNet firmware) - Telegesis ETRX357USB-LRS (Note! First have to be flashed with other EmberZNet firmware) - Telegesis ETRX357USB-LRS+8M (Note! First have to be flashed with other EmberZNet firmware) - **XBee Zigbee based radios** (via the [zigpy-xbee](https://github.com/zigpy/zigpy-xbee) library for zigpy) - Digi XBee Series 2C (S2C) modules - Digi XBee Series 2 (S2) modules. Note: These will need to be manually flashed with the Zigbee Coordinator API firmware via XCTU. - Digi XBee Series 3 (xbee3-24) modules - **deCONZ based radios** (via the [zigpy-deconz](https://github.com/zigpy/zigpy-deconz) library for zigpy) - [ConBee II (a.k.a. ConBee 2) USB adapter from Dresden-Elektronik](https://shop.dresden-elektronik.de/conbee-2.html) - [ConBee](https://www.dresden-elektronik.de/conbee/) USB radio adapter from [Dresden-Elektronik](https://www.dresden-elektronik.de) - [RaspBee](https://www.dresden-elektronik.de/raspbee/) GPIO radio adapter from [Dresden-Elektronik](https://www.dresden-elektronik.de) ### Experimental support for additional Zigbee radio modules - **[ZiGate open source ZigBee adapter hardware](https://zigate.fr/)** (via the [zigpy-zigate](https://github.com/doudz/zigpy-zigate) library for zigpy) - [ZiGate USB-TTL](https://zigate.fr/produit/zigate-ttl/) (Note! Requires ZiGate firmware 3.1a or later) - [ZiGate USB-DIN](https://zigate.fr/produit/zigate-usb-din/) (Note! Requires ZiGate firmware 3.1a or later) - [PiZiGate (ZiGate module for Raspberry Pi GPIO)](https://zigate.fr/produit/pizigate-v1-0/) (Note! Requires ZiGate firmware 3.1a or later) - [ZiGate Pack WiFi](https://zigate.fr/produit/zigate-pack-wifi-v1-3/) (Note! Requires ZiGate firmware 3.1a or later) - **Texas Instruments CC253x, CC26x2R, and CC13x2 based radios** (via the [zigpy-cc](https://github.com/sanyatuning/zigpy-cc) library for zigpy) - [CC2531 USB stick hardware flashed with custom Z-Stack coordinator firmware from the Zigbee2mqtt project](https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html) - [CC2530 + CC2591 USB stick hardware flashed with custom Z-Stack coordinator firmware from the Zigbee2mqtt project](https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html) - [CC2530 + CC2592 dev board hardware flashed with custom Z-Stack coordinator firmware from the Zigbee2mqtt project](https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html) - [CC2652R dev board hardware flashed with custom Z-Stack coordinator firmware from the Zigbee2mqtt project](https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html) - [CC1352P-2 dev board hardware flashed with custom Z-Stack coordinator firmware from the Zigbee2mqtt project](https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html) - [CC2538 + CC2592 dev board hardware flashed with custom Z-Stack coordinator firmware from the Zigbee2mqtt project](https://www.zigbee2mqtt.io/getting_started/what_do_i_need.html) ## Release packages available via PyPI Packages of tagged versions are also released via PyPI - https://pypi.org/project/zigpy-homeassistant/ - https://pypi.org/project/bellows-homeassistant/ - https://pypi.org/project/zigpy-xbee-homeassistant/ - https://pypi.org/project/zigpy-deconz/ - https://pypi.org/project/zigpy-zigate/ - https://pypi.org/project/zigpy-cc/ ## How to contribute If you are looking to make a contribution to this project we suggest that you follow the steps in these guides: - https://github.com/firstcontributions/first-contributions/blob/master/README.md - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md Some developers might also be interested in receiving donations in the form of hardware such as Zigbee modules or devices, and even if such donations are most often donated with no strings attached it could in many cases help the developers motivation and indirect improve the development of this project. ## Developer references Silicon Labs video playlist of ZigBee Concepts: Architecture basics, MAC/PHY, node types, and application profiles - https://www.youtube.com/playlist?list=PL-awFRrdECXvAs1mN2t2xaI0_bQRh2AqD ## Related projects ### ZHA Device Handlers ZHA deviation handling in Home Assistant relies on on the third-party [ZHA Device Handlers](https://github.com/dmulcahey/zha-device-handlers) project. Zigbee devices that deviate from or do not fully conform to the standard specifications set by the [Zigbee Alliance](https://www.zigbee.org) may require the development of custom [ZHA Device Handlers](https://github.com/dmulcahey/zha-device-handlers) (ZHA custom quirks handler implementation) to for all their functions to work properly with the ZHA component in Home Assistant. These ZHA Device Handlers for Home Assistant can thus be used to parse custom messages to and from non-compliant Zigbee devices. The custom quirks implementations for zigpy implemented as ZHA Device Handlers for Home Assistant are a similar concept to that of [Hub-connected Device Handlers for the SmartThings Classics platform](https://docs.smartthings.com/en/latest/device-type-developers-guide/) as well as that of [Zigbee-Shepherd Converters as used by Zigbee2mqtt](https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html), meaning they are each virtual representations of a physical device that expose additional functionality that is not provided out-of-the-box by the existing integration between these platforms.
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/README.md
README.md
import abc import asyncio import functools import inspect import logging import traceback from typing import Any, Coroutine, Optional, Tuple, Type, Union from Crypto.Cipher import AES from crccheck.crc import CrcX25 from zigpy.exceptions import DeliveryError, ZigbeeException import zigpy.types as t LOGGER = logging.getLogger(__name__) class ListenableMixin: def _add_listener(self, listener, include_context): id_ = id(listener) while id_ in self._listeners: id_ += 1 self._listeners[id_] = (listener, include_context) return id_ def add_listener(self, listener): return self._add_listener(listener, include_context=False) def add_context_listener(self, listener): return self._add_listener(listener, include_context=True) def listener_event(self, method_name, *args): result = [] for listener, include_context in self._listeners.values(): method = getattr(listener, method_name, None) if not method: continue try: if include_context: result.append(method(self, *args)) else: result.append(method(*args)) except Exception as e: LOGGER.warning("Error calling listener.%s: %s", method_name, e) return result async def async_event(self, method_name, *args): tasks = [] for listener, include_context in self._listeners.values(): method = getattr(listener, method_name, None) if not method: continue if include_context: tasks.append(method(self, *args)) else: tasks.append(method(*args)) results = [] for result in await asyncio.gather(*tasks, return_exceptions=True): if isinstance(result, Exception): LOGGER.warning("Error calling listener: %s", result) else: results.append(result) return results class LocalLogMixin: @abc.abstractmethod def log(self, lvl: int, msg: str, *args, **kwargs): # pragma: no cover pass def exception(self, msg, *args, **kwargs): return self.log(logging.ERROR, msg, *args, **kwargs) def debug(self, msg, *args, **kwargs): return self.log(logging.DEBUG, msg, *args, **kwargs) def info(self, msg, *args, **kwargs): return self.log(logging.INFO, msg, *args, **kwargs) def warning(self, msg, *args, **kwargs): return self.log(logging.WARNING, msg, *args, **kwargs) def error(self, msg, *args, **kwargs): return self.log(logging.ERROR, msg, *args, **kwargs) async def retry(func, retry_exceptions, tries=3, delay=0.1): """Retry a function in case of exception Only exceptions in `retry_exceptions` will be retried. """ while True: print("Tries remaining: %s" % (tries,)) try: r = await func() return r except retry_exceptions: if tries <= 1: raise tries -= 1 await asyncio.sleep(delay) def retryable(retry_exceptions, tries=1, delay=0.1): """Return a decorator which makes a function able to be retried This adds "tries" and "delay" keyword arguments to the function. Only exceptions in `retry_exceptions` will be retried. """ def decorator(func): nonlocal tries, delay @functools.wraps(func) def wrapper(*args, tries=tries, delay=delay, **kwargs): if tries <= 1: return func(*args, **kwargs) return retry( functools.partial(func, *args, **kwargs), retry_exceptions, tries=tries, delay=delay, ) return wrapper return decorator retryable_request = retryable((DeliveryError, asyncio.TimeoutError)) def aes_mmo_hash_update(length, result, data): while len(data) >= AES.block_size: # Encrypt aes = AES.new(bytes(result), AES.MODE_ECB) result = bytearray(aes.encrypt(bytes(data[: AES.block_size]))) # XOR for i in range(AES.block_size): result[i] ^= bytes(data[: AES.block_size])[i] data = data[AES.block_size :] length += AES.block_size return (length, result) def aes_mmo_hash(data): result_len = 0 remaining_length = 0 length = len(data) result = bytearray([0] * AES.block_size) temp = bytearray([0] * AES.block_size) if data and length > 0: remaining_length = length & (AES.block_size - 1) if length >= AES.block_size: # Mask out the lower byte since hash update will hash # everything except the last piece, if the last piece # is less than 16 bytes. hashed_length = length & ~(AES.block_size - 1) (result_len, result) = aes_mmo_hash_update(result_len, result, data) data = data[hashed_length:] for i in range(remaining_length): temp[i] = data[i] # Per the spec, Concatenate a 1 bit followed by all zero bits # (previous memset() on temp[] set the rest of the bits to zero) temp[remaining_length] = 0x80 result_len += remaining_length # If appending the bit string will push us beyond the 16-byte boundary # we must hash that block and append another 16-byte block. if (AES.block_size - remaining_length) < 3: (result_len, result) = aes_mmo_hash_update(result_len, result, temp) # Since this extra data is due to the concatenation, # we remove that length. We want the length of data only # and not the padding. result_len -= AES.block_size temp = bytearray([0] * AES.block_size) bit_size = result_len * 8 temp[AES.block_size - 2] = (bit_size >> 8) & 0xFF temp[AES.block_size - 1] = (bit_size) & 0xFF (result_len, result) = aes_mmo_hash_update(result_len, result, temp) return t.KeyData([t.uint8_t(c) for c in result]) def convert_install_code(code): if len(code) not in (8, 10, 14, 18): return None real_crc = bytes(code[-2:]) crc = CrcX25() crc.process(code[:-2]) if real_crc != crc.finalbytes(byteorder="little"): return None return aes_mmo_hash(code) class Request: """Request context manager.""" def __init__(self, pending: dict, sequence: t.uint8_t) -> None: """Init context manager for requests.""" assert sequence not in pending self._pending = pending self._result = asyncio.Future() self._sequence = sequence @property def result(self) -> asyncio.Future: return self._result @property def sequence(self) -> t.uint8_t: """Send Future.""" return self._sequence def __enter__(self): """Return context manager.""" self._pending[self.sequence] = self return self def __exit__(self, exc_type, exc_value, exc_traceback): """Clean up pending on exit.""" if not self.result.done(): self.result.cancel() self._pending.pop(self.sequence) return not exc_type class Requests(dict): def new(self, sequence: t.uint8_t) -> Request: """Wrap new request into a context manager.""" return Request(self, sequence) class CatchingTaskMixin(LocalLogMixin): """Allow creating tasks suppressing exceptions.""" def create_catching_task( self, target: Coroutine, exceptions: Optional[Union[Type[Exception], Tuple]] = None, ) -> None: """Create a task.""" asyncio.ensure_future(self.catching_coro(target, exceptions)) async def catching_coro( self, target: Coroutine, exceptions: Optional[Union[Type[Exception], Tuple]] = None, ) -> Any: """Wrap a target coro and catch specified exceptions.""" if exceptions is None: exceptions = (asyncio.TimeoutError, ZigbeeException) try: return await target except exceptions: pass except Exception: # pylint: disable=broad-except # Do not print the wrapper in the traceback frames = len(inspect.trace()) - 1 exc_msg = traceback.format_exc(-frames) self.exception("%s", exc_msg) return None
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/util.py
util.py
import logging import sqlite3 import zigpy.device import zigpy.endpoint import zigpy.profiles import zigpy.quirks import zigpy.types as t from zigpy.zcl.clusters.general import Basic from zigpy.zdo import types as zdo_t LOGGER = logging.getLogger(__name__) DB_VERSION = 0x0003 def _sqlite_adapters(): def adapt_ieee(eui64): return str(eui64) sqlite3.register_adapter(t.EUI64, adapt_ieee) def convert_ieee(s): return t.EUI64.convert(s.decode()) sqlite3.register_converter("ieee", convert_ieee) class PersistingListener: def __init__(self, database_file, application): self._database_file = database_file _sqlite_adapters() self._db = sqlite3.connect(database_file, detect_types=sqlite3.PARSE_DECLTYPES) self._cursor = self._db.cursor() self._enable_foreign_keys() self._create_table_devices() self._create_table_endpoints() self._create_table_clusters() self._create_table_node_descriptors() self._create_table_output_clusters() self._create_table_attributes() self._create_table_groups() self._create_table_group_members() self._create_table_relays() self._application = application def execute(self, *args, **kwargs): return self._cursor.execute(*args, **kwargs) def device_joined(self, device): pass def raw_device_initialized(self, device): self._save_device(device) def device_initialized(self, device): pass def device_left(self, device): pass def device_removed(self, device): self._remove_device(device) def device_relays_updated(self, device, relays): """Device relay list is updated.""" if relays is None: self._save_device_relays_clear(device.ieee) return self._save_device_relays_update(device.ieee, t.Relays(relays).serialize()) def attribute_updated(self, cluster, attrid, value): if cluster.endpoint.device.status != zigpy.device.Status.ENDPOINTS_INIT: return self._save_attribute( cluster.endpoint.device.ieee, cluster.endpoint.endpoint_id, cluster.cluster_id, attrid, value, ) def node_descriptor_updated(self, device): self._save_node_descriptor(device) self._db.commit() def group_added(self, group): q = "INSERT OR REPLACE INTO groups VALUES (?, ?)" self.execute(q, (group.group_id, group.name)) self._db.commit() def group_member_added(self, group, ep): q = "INSERT OR REPLACE INTO group_members VALUES (?, ?, ?)" self.execute(q, (group.group_id, *ep.unique_id)) self._db.commit() def group_member_removed(self, group, ep): q = """DELETE FROM group_members WHERE group_id=? AND ieee=? AND endpoint_id=?""" self.execute(q, (group.group_id, *ep.unique_id)) self._db.commit() def group_removed(self, group): q = "DELETE FROM groups WHERE group_id=?" self.execute(q, (group.group_id,)) self._db.commit() def _create_table(self, table_name, spec): self.execute("CREATE TABLE IF NOT EXISTS %s %s" % (table_name, spec)) self.execute("PRAGMA user_version = %s" % (DB_VERSION,)) def _create_index(self, index_name, table, columns): self.execute( "CREATE UNIQUE INDEX IF NOT EXISTS %s ON %s(%s)" % (index_name, table, columns) ) def _create_table_devices(self): self._create_table("devices", "(ieee ieee, nwk, status)") self._create_index("ieee_idx", "devices", "ieee") def _create_table_endpoints(self): self._create_table( "endpoints", ( "(ieee ieee, endpoint_id, profile_id, device_type device_type, status, " "FOREIGN KEY(ieee) REFERENCES devices(ieee) ON DELETE CASCADE)" ), ) self._create_index("endpoint_idx", "endpoints", "ieee, endpoint_id") def _create_table_clusters(self): self._create_table( "clusters", ( "(ieee ieee, endpoint_id, cluster, " "FOREIGN KEY(ieee, endpoint_id) REFERENCES endpoints(ieee, endpoint_id)" " ON DELETE CASCADE)" ), ) self._create_index("cluster_idx", "clusters", "ieee, endpoint_id, cluster") def _create_table_node_descriptors(self): self._create_table( "node_descriptors", ( "(ieee ieee, value, " "FOREIGN KEY(ieee) REFERENCES devices(ieee) ON DELETE CASCADE)" ), ) self._create_index("node_descriptors_idx", "node_descriptors", "ieee") def _create_table_output_clusters(self): self._create_table( "output_clusters", ( "(ieee ieee, endpoint_id, cluster, " "FOREIGN KEY(ieee, endpoint_id) REFERENCES endpoints(ieee, endpoint_id)" " ON DELETE CASCADE)" ), ) self._create_index( "output_cluster_idx", "output_clusters", "ieee, endpoint_id, cluster" ) def _create_table_attributes(self): self._create_table( "attributes", ( "(ieee ieee, endpoint_id, cluster, attrid, value, " "FOREIGN KEY(ieee) " "REFERENCES devices(ieee) " "ON DELETE CASCADE)" ), ) self._create_index( "attribute_idx", "attributes", "ieee, endpoint_id, cluster, attrid" ) def _create_table_groups(self): self._create_table("groups", "(group_id, name)") self._create_index("group_idx", "groups", "group_id") def _create_table_group_members(self): self._create_table( "group_members", """(group_id, ieee ieee, endpoint_id, FOREIGN KEY(group_id) REFERENCES groups(group_id) ON DELETE CASCADE, FOREIGN KEY(ieee, endpoint_id) REFERENCES endpoints(ieee, endpoint_id) ON DELETE CASCADE)""", ) self._create_index( "group_members_idx", "group_members", "group_id, ieee, endpoint_id" ) def _create_table_relays(self): self._create_table( "relays", """(ieee ieee, relays, FOREIGN KEY(ieee) REFERENCES devices(ieee) ON DELETE CASCADE)""", ) self._create_index("relays_idx", "relays", "ieee") def _enable_foreign_keys(self): self.execute("PRAGMA foreign_keys = ON") def _remove_device(self, device): self.execute("DELETE FROM attributes WHERE ieee = ?", (device.ieee,)) self.execute("DELETE FROM node_descriptors WHERE ieee = ?", (device.ieee,)) self.execute("DELETE FROM clusters WHERE ieee = ?", (device.ieee,)) self.execute("DELETE FROM output_clusters WHERE ieee = ?", (device.ieee,)) self.execute("DELETE FROM group_members WHERE ieee = ?", (device.ieee,)) self.execute("DELETE FROM endpoints WHERE ieee = ?", (device.ieee,)) self.execute("DELETE FROM devices WHERE ieee = ?", (device.ieee,)) self._db.commit() def _save_device(self, device): if device.status != zigpy.device.Status.ENDPOINTS_INIT: LOGGER.warning( "Not saving uninitialized %s/%s device: %s", device.ieee, device.nwk, device.status, ) return q = "INSERT OR REPLACE INTO devices (ieee, nwk, status) VALUES (?, ?, ?)" self.execute(q, (device.ieee, device.nwk, device.status)) self._save_node_descriptor(device) if isinstance(device, zigpy.quirks.CustomDevice): self._db.commit() return self._save_endpoints(device) for epid, ep in device.endpoints.items(): if epid == 0: # ZDO continue self._save_input_clusters(ep) self._save_attribute_cache(ep) self._save_output_clusters(ep) self._db.commit() def _save_endpoints(self, device): q = "INSERT OR REPLACE INTO endpoints VALUES (?, ?, ?, ?, ?)" endpoints = [] for epid, ep in device.endpoints.items(): if epid == 0: continue # Skip zdo device_type = getattr(ep, "device_type", None) eprow = ( device.ieee, ep.endpoint_id, getattr(ep, "profile_id", None), device_type, ep.status, ) endpoints.append(eprow) self._cursor.executemany(q, endpoints) def _save_node_descriptor(self, device): if ( device.status != zigpy.device.Status.ENDPOINTS_INIT or not device.node_desc.is_valid ): return q = "INSERT OR REPLACE INTO node_descriptors VALUES (?, ?)" self.execute(q, (device.ieee, device.node_desc.serialize())) def _save_input_clusters(self, endpoint): q = "INSERT OR REPLACE INTO clusters VALUES (?, ?, ?)" clusters = [ (endpoint.device.ieee, endpoint.endpoint_id, cluster.cluster_id) for cluster in endpoint.in_clusters.values() ] self._cursor.executemany(q, clusters) def _save_attribute_cache(self, ep): q = "INSERT OR REPLACE INTO attributes VALUES (?, ?, ?, ?, ?)" clusters = [ (ep.device.ieee, ep.endpoint_id, cluster.cluster_id, attrid, value) for cluster in ep.in_clusters.values() for attrid, value in cluster._attr_cache.items() ] self._cursor.executemany(q, clusters) def _save_output_clusters(self, endpoint): q = "INSERT OR REPLACE INTO output_clusters VALUES (?, ?, ?)" clusters = [ (endpoint.device.ieee, endpoint.endpoint_id, cluster.cluster_id) for cluster in endpoint.out_clusters.values() ] self._cursor.executemany(q, clusters) def _save_attribute(self, ieee, endpoint_id, cluster_id, attrid, value): q = "INSERT OR REPLACE INTO attributes VALUES (?, ?, ?, ?, ?)" self.execute(q, (ieee, endpoint_id, cluster_id, attrid, value)) self._db.commit() def _save_device_relays_update(self, ieee, value): q = "INSERT OR REPLACE INTO relays VALUES (?, ?)" self.execute(q, (ieee, value)) self._db.commit() def _save_device_relays_clear(self, ieee): self.execute("DELETE FROM relays WHERE ieee = ?", (ieee,)) self._db.commit() def _scan(self, table, filter=None): if filter is None: return self.execute("SELECT * FROM %s" % (table,)) return self.execute("SELECT * FROM %s WHERE %s" % (table, filter)) def load(self): LOGGER.debug("Loading application state from %s", self._database_file) self._load_devices() self._load_node_descriptors() self._load_endpoints() self._load_clusters() def _load_attributes(filter=None): for (ieee, endpoint_id, cluster, attrid, value) in self._scan( "attributes", filter ): dev = self._application.get_device(ieee) if endpoint_id in dev.endpoints: ep = dev.endpoints[endpoint_id] if cluster in ep.in_clusters: clus = ep.in_clusters[cluster] clus._attr_cache[attrid] = value LOGGER.debug("Attribute id: %s value: %s", attrid, value) if cluster == Basic.cluster_id and attrid == 4: if isinstance(value, bytes): value = value.split(b"\x00")[0] dev.manufacturer = value.decode().strip() else: dev.manufacturer = value if cluster == Basic.cluster_id and attrid == 5: if isinstance(value, bytes): value = value.split(b"\x00")[0] dev.model = value.decode().strip() else: dev.model = value _load_attributes("attrid=4 OR attrid=5") for device in self._application.devices.values(): device = zigpy.quirks.get_device(device) self._application.devices[device.ieee] = device _load_attributes() self._load_groups() self._load_group_members() self._load_relays() def _load_devices(self): for (ieee, nwk, status) in self._scan("devices"): dev = self._application.add_device(ieee, nwk) dev.status = zigpy.device.Status(status) def _load_node_descriptors(self): for (ieee, value) in self._scan("node_descriptors"): dev = self._application.get_device(ieee) dev.node_desc = zdo_t.NodeDescriptor.deserialize(value)[0] def _load_endpoints(self): for (ieee, epid, profile_id, device_type, status) in self._scan("endpoints"): dev = self._application.get_device(ieee) ep = dev.add_endpoint(epid) ep.profile_id = profile_id ep.device_type = device_type if profile_id == 260: ep.device_type = zigpy.profiles.zha.DeviceType(device_type) elif profile_id == 49246: ep.device_type = zigpy.profiles.zll.DeviceType(device_type) ep.status = zigpy.endpoint.Status(status) def _load_clusters(self): for (ieee, endpoint_id, cluster) in self._scan("clusters"): dev = self._application.get_device(ieee) ep = dev.endpoints[endpoint_id] ep.add_input_cluster(cluster) for (ieee, endpoint_id, cluster) in self._scan("output_clusters"): dev = self._application.get_device(ieee) ep = dev.endpoints[endpoint_id] ep.add_output_cluster(cluster) def _load_groups(self): for (group_id, name) in self._scan("groups"): self._application.groups.add_group(group_id, name, suppress_event=True) def _load_group_members(self): for (group_id, ieee, ep_id) in self._scan("group_members"): group = self._application.groups[group_id] group.add_member( self._application.get_device(ieee).endpoints[ep_id], suppress_event=True ) def _load_relays(self): for (ieee, value) in self._scan("relays"): dev = self._application.get_device(ieee) dev.relays = t.Relays.deserialize(value)[0] for dev in self._application.devices.values(): dev.add_context_listener(self)
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/appdb.py
appdb.py
import asyncio import logging import os.path from typing import Dict, Optional import voluptuous as vol import zigpy.appdb import zigpy.device import zigpy.group import zigpy.ota import zigpy.quirks import zigpy.types as t import zigpy.util import zigpy.zcl import zigpy.zdo import zigpy.zdo.types as zdo_types CONFIG_SCHEMA = vol.Schema({}, extra=vol.ALLOW_EXTRA) DEFAULT_ENDPOINT_ID = 1 LOGGER = logging.getLogger(__name__) OTA_DIR = "zigpy_ota/" class ControllerApplication(zigpy.util.ListenableMixin): def __init__(self, database_file=None, config={}): self._send_sequence = 0 self.devices: Dict[t.EUI64, zigpy.device.Device] = {} self._groups = zigpy.group.Groups(self) self._listeners = {} self._config = CONFIG_SCHEMA(config) self._channel = None self._channels = None self._ext_pan_id = None self._ieee = None self._nwk = None self._nwk_update_id = None self._pan_id = None self._ota = zigpy.ota.OTA(self) if database_file is None: ota_dir = None else: ota_dir = os.path.dirname(database_file) ota_dir = os.path.join(ota_dir, OTA_DIR) self.ota.initialize(ota_dir) self._dblistener = None if database_file is not None: self._dblistener = zigpy.appdb.PersistingListener(database_file, self) self.add_listener(self._dblistener) self.groups.add_listener(self._dblistener) self._dblistener.load() async def shutdown(self): """Perform a complete application shutdown.""" pass async def startup(self, auto_form=False): """Perform a complete application startup""" raise NotImplementedError async def form_network(self, channel=15, pan_id=None, extended_pan_id=None): """Form a new network""" raise NotImplementedError def add_device(self, ieee, nwk): assert isinstance(ieee, t.EUI64) # TODO: Shut down existing device dev = zigpy.device.Device(self, ieee, nwk) self.devices[ieee] = dev return dev async def update_network( self, channel: Optional[t.uint8_t] = None, channels: Optional[t.uint32_t] = None, pan_id: Optional[t.PanId] = None, extended_pan_id: Optional[t.ExtendedPanId] = None, network_key: Optional[t.KeyData] = None, ): """Update network parameters. :param channel: Radio channel :param channels: Channels mask :param pan_id: Network pan id :param extended_pan_id: Extended pan id :param network_key: network key """ raise NotImplementedError def device_initialized(self, device): """Used by a device to signal that it is initialized""" self.listener_event("raw_device_initialized", device) device = zigpy.quirks.get_device(device) self.devices[device.ieee] = device if self._dblistener is not None: device.add_context_listener(self._dblistener) self.listener_event("device_initialized", device) async def remove(self, ieee): assert isinstance(ieee, t.EUI64) dev = self.devices.get(ieee) if not dev: LOGGER.debug("Device not found for removal: %s", ieee) return LOGGER.info("Removing device 0x%04x (%s)", dev.nwk, ieee) zdo_worked = False try: resp = await dev.zdo.leave() zdo_worked = resp[0] == 0 except (zigpy.exceptions.DeliveryError, asyncio.TimeoutError) as ex: LOGGER.debug("Sending 'zdo_leave_req' failed: %s", ex) if not zdo_worked: await self.force_remove(dev) self.devices.pop(ieee, None) self.listener_event("device_removed", dev) async def force_remove(self, dev): raise NotImplementedError def deserialize(self, sender, endpoint_id, cluster_id, data): return sender.deserialize(endpoint_id, cluster_id, data) def handle_message(self, sender, profile, cluster, src_ep, dst_ep, message): if sender.status == zigpy.device.Status.NEW and dst_ep != 0: # only allow ZDO responses while initializing device LOGGER.debug( "Received frame on uninitialized device %s (%s) for endpoint: %s", sender.ieee, sender.status, dst_ep, ) return elif ( sender.status == zigpy.device.Status.ZDO_INIT and dst_ep != 0 and cluster != 0 ): # only allow access to basic cluster while initializing endpoints LOGGER.debug( "Received frame on uninitialized device %s endpoint %s for cluster: %s", sender.ieee, dst_ep, cluster, ) return return sender.handle_message(profile, cluster, src_ep, dst_ep, message) def handle_join(self, nwk, ieee, parent_nwk): ieee = t.EUI64(ieee) LOGGER.info("Device 0x%04x (%s) joined the network", nwk, ieee) if ieee in self.devices: dev = self.get_device(ieee) if dev.nwk != nwk: LOGGER.debug( "Device %s changed id (0x%04x => 0x%04x)", ieee, dev.nwk, nwk ) dev.nwk = nwk dev.schedule_group_membership_scan() elif dev.initializing or dev.status == zigpy.device.Status.ENDPOINTS_INIT: LOGGER.debug("Skip initialization for existing device %s", ieee) dev.schedule_group_membership_scan() return else: dev = self.add_device(ieee, nwk) self.listener_event("device_joined", dev) dev.schedule_initialize() def handle_leave(self, nwk, ieee): LOGGER.info("Device 0x%04x (%s) left the network", nwk, ieee) dev = self.devices.get(ieee, None) if dev is not None: self.listener_event("device_left", dev) async def mrequest( self, group_id, profile, cluster, src_ep, sequence, data, *, hops=0, non_member_radius=3 ): """Submit and send data out as a multicast transmission. :param group_id: destination multicast address :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param sequence: transaction sequence number of the message :param data: Zigbee message payload :param hops: the message will be delivered to all nodes within this number of hops of the sender. A value of zero is converted to MAX_HOPS :param non_member_radius: the number of hops that the message will be forwarded by devices that are not members of the group. A value of 7 or greater is treated as infinite :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ raise NotImplementedError @zigpy.util.retryable_request async def request( self, device, profile, cluster, src_ep, dst_ep, sequence, data, expect_reply=True, use_ieee=False, ): """Submit and send data out as an unicast transmission. :param device: destination device :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param dst_ep: destination endpoint id :param sequence: transaction sequence number of the message :param data: Zigbee message payload :param expect_reply: True if this is essentially a request :param use_ieee: use EUI64 for destination addressing :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ raise NotImplementedError async def broadcast( self, profile, cluster, src_ep, dst_ep, grpid, radius, sequence, data, broadcast_address, ): """Submit and send data out as an unicast transmission. :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param dst_ep: destination endpoint id :param: grpid: group id to address the broadcast to :param radius: max radius of the broadcast :param sequence: transaction sequence number of the message :param data: zigbee message payload :param timeout: how long to wait for transmission ACK :param broadcast_address: broadcast address. :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ raise NotImplementedError async def permit_ncp(self, time_s=60): """Permit joining on NCP.""" raise NotImplementedError async def permit(self, time_s=60, node=None): """Permit joining on a specific node or all router nodes.""" assert 0 <= time_s <= 254 if node is not None: if not isinstance(node, t.EUI64): node = t.EUI64([t.uint8_t(p) for p in node]) if node != self._ieee: try: dev = self.get_device(ieee=node) r = await dev.zdo.permit(time_s) LOGGER.debug("Sent 'mgmt_permit_joining_req' to %s: %s", node, r) except KeyError: LOGGER.warning("Device '%s' not found", node) except zigpy.exceptions.DeliveryError as ex: LOGGER.warning("Couldn't open '%s' for joining: %s", node, ex) else: await self.permit_ncp(time_s) return await zigpy.zdo.broadcast( self, 0x0036, 0x0000, 0x00, time_s, 0, broadcast_address=t.BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR, ) return await self.permit_ncp(time_s) def permit_with_key(self, node, code, time_s=60): raise NotImplementedError def get_sequence(self): self._send_sequence = (self._send_sequence + 1) % 256 return self._send_sequence def get_device(self, ieee=None, nwk=None): if ieee is not None: return self.devices[ieee] for dev in self.devices.values(): # TODO: Make this not terrible if dev.nwk == nwk: return dev raise KeyError def get_endpoint_id(self, cluster_id: int, is_server_cluster: bool = False): """Returns coordinator endpoint id for specified cluster id.""" return DEFAULT_ENDPOINT_ID def get_dst_address(self, cluster): """Helper to get a dst address for bind/unbind operations. Allows radios to provide correct information especially for radios which listen on specific endpoints only. :param cluster: cluster instance to be bound to coordinator :returns: returns a "destination address" """ dstaddr = zdo_types.MultiAddress() dstaddr.addrmode = 3 dstaddr.ieee = self.ieee dstaddr.endpoint = self.get_endpoint_id(cluster.cluster_id, cluster.is_server) return dstaddr @property def channel(self): """Current radio channel.""" return self._channel @property def channels(self): """Channel mask.""" return self._channels @property def config(self) -> dict: """Return current configuration.""" return self._config @property def extended_pan_id(self): """Extended PAN Id.""" return self._ext_pan_id @property def groups(self): return self._groups @property def ieee(self): return self._ieee @property def nwk(self): return self._nwk @property def nwk_update_id(self): """NWK Update ID.""" return self._nwk_update_id @property def ota(self): return self._ota @property def pan_id(self): """Network PAN Id.""" return self._pan_id
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/application.py
application.py
import asyncio import enum import logging import zigpy.exceptions import zigpy.profiles import zigpy.util import zigpy.zcl from zigpy.zcl.clusters.general import Basic from zigpy.zcl.foundation import Status as ZCLStatus from zigpy.zdo.types import Status as zdo_status LOGGER = logging.getLogger(__name__) class Status(enum.IntEnum): """The status of an Endpoint""" # No initialization is done NEW = 0 # Endpoint information (device type, clusters, etc) init done ZDO_INIT = 1 # Endpoint Inactive ENDPOINT_INACTIVE = 3 class Endpoint(zigpy.util.LocalLogMixin, zigpy.util.ListenableMixin): """An endpoint on a device on the network""" def __init__(self, device, endpoint_id): self._device = device self._endpoint_id = endpoint_id self.device_type = None self.in_clusters = {} self.out_clusters = {} self._cluster_attr = {} self.status = Status.NEW self._listeners = {} self._manufacturer = None self._member_of = {} self._model = None self.profile_id = None async def initialize(self): if self.status == Status.ZDO_INIT: return self.info("Discovering endpoint information") try: sdr = await self._device.zdo.Simple_Desc_req( self._device.nwk, self._endpoint_id, tries=3, delay=2 ) if sdr[0] == zdo_status.NOT_ACTIVE: # These endpoints are essentially junk but this lets the device join self.status = Status.ENDPOINT_INACTIVE return elif sdr[0] != zdo_status.SUCCESS: raise Exception("Failed to retrieve service descriptor: %s", sdr) except Exception: self.warning( "Failed ZDO request during endpoint initialization", exc_info=True ) return self.info("Discovered endpoint information: %s", sdr[2]) sd = sdr[2] self.profile_id = sd.profile self.device_type = sd.device_type if self.profile_id == 260: self.device_type = zigpy.profiles.zha.DeviceType(self.device_type) elif self.profile_id == 49246: self.device_type = zigpy.profiles.zll.DeviceType(self.device_type) for cluster in sd.input_clusters: self.add_input_cluster(cluster) for cluster in sd.output_clusters: self.add_output_cluster(cluster) self.status = Status.ZDO_INIT def add_input_cluster(self, cluster_id, cluster=None): """Adds an endpoint's input cluster (a server cluster supported by the device) """ if cluster_id in self.in_clusters and cluster is None: return self.in_clusters[cluster_id] if cluster is None: cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=True) self.in_clusters[cluster_id] = cluster if hasattr(cluster, "ep_attribute"): self._cluster_attr[cluster.ep_attribute] = cluster if hasattr(self._device.application, "_dblistener"): listener = zigpy.zcl.ClusterPersistingListener( self._device.application._dblistener, cluster ) cluster.add_listener(listener) return cluster def add_output_cluster(self, cluster_id, cluster=None): """Adds an endpoint's output cluster (a client cluster supported by the device) """ if cluster_id in self.out_clusters and cluster is None: return self.out_clusters[cluster_id] if cluster is None: cluster = zigpy.zcl.Cluster.from_id(self, cluster_id, is_server=False) self.out_clusters[cluster_id] = cluster return cluster async def add_to_group(self, grp_id: int, name: str = None): try: res = await self.groups.add(grp_id, name) except AttributeError: self.debug("Cannot add 0x%04x group, no groups cluster", grp_id) return ZCLStatus.FAILURE if res[0] != ZCLStatus.SUCCESS: self.debug("Couldn't add to 0x%04x group: %s", grp_id, res[0]) return res[0] group = self.device.application.groups.add_group(grp_id, name) group.add_member(self) return res[0] async def remove_from_group(self, grp_id: int): try: res = await self.groups.remove(grp_id) except AttributeError: self.debug("Cannot remove 0x%04x group, no groups cluster", grp_id) return ZCLStatus.FAILURE if res[0] != ZCLStatus.SUCCESS: self.debug("Couldn't remove to 0x%04x group: %s", grp_id, res[0]) return res[0] if grp_id in self.device.application.groups: self.device.application.groups[grp_id].remove_member(self) return res[0] async def group_membership_scan(self) -> None: """Sync up group membership.""" try: res = await self.groups.get_membership([]) except AttributeError: return except (asyncio.TimeoutError, zigpy.exceptions.ZigbeeException): self.debug("Failed to sync-up group membership") return groups = {group for group in res[1]} self.device.application.groups.update_group_membership(self, groups) async def get_model_info(self): if Basic.cluster_id not in self.in_clusters: return None, None attributes = {"manufacturer": None, "model": None} async def read(attribute_names): """Read attributes and update extra_info convenience function.""" try: result, _ = await self.basic.read_attributes( attribute_names, allow_cache=True ) attributes.update(result) except (zigpy.exceptions.ZigbeeException, asyncio.TimeoutError): pass await read(["manufacturer", "model"]) if attributes["manufacturer"] is None or attributes["model"] is None: # Some devices fail at returning multiple results. Attempt separately. await read(["manufacturer"]) await read(["model"]) self.debug("Manufacturer: %s", attributes["manufacturer"]) self.debug("Model: %s", attributes["model"]) return attributes["model"], attributes["manufacturer"] def deserialize(self, cluster_id, data): """Deserialize data for ZCL""" if cluster_id not in self.in_clusters and cluster_id not in self.out_clusters: raise KeyError("No cluster ID 0x%04x on %s" % (cluster_id, self.unique_id)) cluster = self.in_clusters.get(cluster_id, self.out_clusters.get(cluster_id)) return cluster.deserialize(data) def handle_message(self, profile, cluster, hdr, args): if cluster in self.in_clusters: handler = self.in_clusters[cluster].handle_message elif cluster in self.out_clusters: handler = self.out_clusters[cluster].handle_message else: self.debug("Message on unknown cluster 0x%04x", cluster) self.listener_event("unknown_cluster_message", hdr.command_id, args) return handler(hdr, args) def request(self, cluster, sequence, data, expect_reply=True, command_id=0x00): if self.profile_id == zigpy.profiles.zll.PROFILE_ID and not ( cluster == zigpy.zcl.clusters.lightlink.LightLink.cluster_id and command_id < 0x40 ): profile_id = zigpy.profiles.zha.PROFILE_ID else: profile_id = self.profile_id return self.device.request( profile_id, cluster, self._endpoint_id, self._endpoint_id, sequence, data, expect_reply=expect_reply, ) def reply(self, cluster, sequence, data, command_id=0x00): if self.profile_id == zigpy.profiles.zll.PROFILE_ID and not ( cluster == zigpy.zcl.clusters.lightlink.LightLink.cluster_id and command_id < 0x40 ): profile_id = zigpy.profiles.zha.PROFILE_ID else: profile_id = self.profile_id return self.device.reply( profile_id, cluster, self._endpoint_id, self._endpoint_id, sequence, data ) def log(self, lvl, msg, *args, **kwargs): msg = "[0x%04x:%s] " + msg args = (self._device.nwk, self._endpoint_id) + args return LOGGER.log(lvl, msg, *args, **kwargs) @property def device(self): return self._device @property def endpoint_id(self): return self._endpoint_id @property def manufacturer(self): if self._manufacturer is not None: return self._manufacturer return self.device.manufacturer @manufacturer.setter def manufacturer(self, value): self.warning( ( "Overriding manufacturer from quirks is not supported and " "will be removed in the next zigpy version" ) ) self._manufacturer = value @property def member_of(self): return self._member_of @property def model(self): if self._model is not None: return self._model return self.device.model @model.setter def model(self, value): self.warning( ( "Overriding model from quirks is not supported and " "will be removed in the next version" ) ) self._model = value @property def unique_id(self): return self.device.ieee, self.endpoint_id def __getattr__(self, name): try: return self._cluster_attr[name] except KeyError: raise AttributeError
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/endpoint.py
endpoint.py
import logging from typing import Optional, Set from zigpy import types as t from zigpy.endpoint import Endpoint import zigpy.profiles.zha as zha_profile from zigpy.util import ListenableMixin, LocalLogMixin import zigpy.zcl LOGGER = logging.getLogger(__name__) class Group(ListenableMixin, dict): def __init__(self, group_id, name=None, groups=None, *args, **kwargs): self._groups = groups self._group_id = t.Group(group_id) self._listeners = {} self._name = name self._endpoint = GroupEndpoint(self) if groups is not None: self.add_listener(groups) super().__init__(*args, **kwargs) def add_member(self, ep: Endpoint, suppress_event=False): if not isinstance(ep, Endpoint): raise ValueError("%s is not %s class" % (ep, Endpoint.__class__.__name__)) if ep.unique_id in self: return self[ep.unique_id] self[ep.unique_id] = ep ep.member_of[self.group_id] = self if not suppress_event: self.listener_event("member_added", self, ep) return self def remove_member(self, ep: Endpoint, suppress_event=False): self.pop(ep.unique_id, None) ep.member_of.pop(self.group_id, None) if not suppress_event: self.listener_event("member_removed", self, ep) return self async def request(self, profile, cluster, sequence, data, *args, **kwargs): """Send multicast request.""" res = await self.application.mrequest( self.group_id, profile, cluster, self.application.get_endpoint_id(cluster, is_server_cluster=False), sequence, data, ) return [data[2], zigpy.zcl.foundation.Status(res[0])] def __repr__(self): return "<{} group_id={} name='{}' members={}>".format( self.__class__.__name__, self.group_id, self.name, super().__repr__() ) @property def application(self): """Expose application to FakeEndpoint/GroupCluster.""" return self.groups.application @property def groups(self): return self._groups @property def group_id(self): return self._group_id @property def members(self): return self @property def name(self): if self._name is None: return "No name group {}".format(self.group_id) return self._name @property def endpoint(self): return self._endpoint class Groups(ListenableMixin, dict): def __init__(self, app, *args, **kwargs): self._application = app self._listeners = {} super().__init__(*args, **kwargs) def add_group( self, group_id: int, name: str = None, suppress_event: bool = False ) -> Optional[Group]: if group_id in self: return self[group_id] LOGGER.debug("Adding group: %s, %s", group_id, name) group = Group(group_id, name, self) self[group_id] = group if not suppress_event: self.listener_event("group_added", group) return group def member_added(self, group: Group, ep: Endpoint): self.listener_event("group_member_added", group, ep) def member_removed(self, group: Group, ep: Endpoint): self.listener_event("group_member_removed", group, ep) def pop(self, item, *args) -> Optional[Group]: if isinstance(item, Group): group = super().pop(item.group_id, *args) if isinstance(group, Group): for member in (*group.values(),): group.remove_member(member) self.listener_event("group_removed", group) return group group = super().pop(item, *args) if isinstance(group, Group): for member in (*group.values(),): group.remove_member(member) self.listener_event("group_removed", group) return group remove_group = pop def update_group_membership(self, ep: Endpoint, groups: Set[int]) -> None: """Sync up device group membership.""" old_groups = { group.group_id for group in self.values() if ep.unique_id in group.members } for grp_id in old_groups - groups: self[grp_id].remove_member(ep) for grp_id in groups - old_groups: group = self.add_group(grp_id) group.add_member(ep) @property def application(self): """Return application controller.""" return self._application class GroupCluster(zigpy.zcl.Cluster): """Virtual cluster for group requests. """ @classmethod def from_id(cls, group_endpoint, cluster_id: int): """Instantiate from ZCL cluster by cluster id.""" if cluster_id in cls._registry: return cls._registry[cluster_id](group_endpoint, is_server=True) group_endpoint.debug( "0x%04x cluster id is not supported for group requests", cluster_id ) raise KeyError("Unsupported 0x{:04x} cluster id for groups".format(cluster_id)) @classmethod def from_attr(cls, group_endpoint, ep_name: str): """Instantiate by Cluster name.""" for cluster in cls._registry.values(): if hasattr(cluster, "ep_attribute") and cluster.ep_attribute == ep_name: return cluster(group_endpoint, is_server=True) raise AttributeError("Unsupported %s group cluster".format(ep_name)) class GroupEndpoint(LocalLogMixin): """Group request handlers. wrapper for virtual clusters. """ def __init__(self, group: Group): """Instantiate GroupRequest.""" self._group = group self._clusters = {} self._cluster_by_attr = {} @property def clusters(self): """Group clusters. most of the times, group requests are addressed from client -> server clusters. """ return self._clusters @property def device(self): """Group is our fake zigpy device""" return self._group def request(self, cluster, sequence, data, *args, **kwargs): """Send multicast request.""" return self.device.request(zha_profile.PROFILE_ID, cluster, sequence, data) def reply(self, cluster, sequence, data, *args, **kwargs): """Send multicast reply. do we really need this one :shrug: """ return self.request(cluster, sequence, data, *args, **kwargs) def log(self, lvl, msg, *args, **kwargs): msg = "[0x%04x] " + msg args = (self._group.group_id,) + args return LOGGER.log(lvl, msg, *args, **kwargs) def __getitem__(self, item: int): """Return or instantiate a group cluster.""" try: return self.clusters[item] except KeyError: self.debug("trying to create new group %s cluster id", item) cluster = GroupCluster.from_id(self, item) self.clusters[item] = cluster return cluster def __getattr__(self, name: str): """Return or instantiate a group cluster by cluster name.""" try: return self._cluster_by_attr[name] except KeyError: self.debug("trying to create a new group '%s' cluster", name) cluster = GroupCluster.from_attr(self, name) self._cluster_by_attr[name] = cluster return cluster
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/group.py
group.py
import asyncio import binascii import enum import logging import time from typing import Dict, Optional, Union import zigpy.endpoint import zigpy.exceptions from zigpy.types import NWK, BroadcastAddress, Relays import zigpy.util import zigpy.zcl.foundation as foundation import zigpy.zdo as zdo APS_REPLY_TIMEOUT = 5 APS_REPLY_TIMEOUT_EXTENDED = 28 LOGGER = logging.getLogger(__name__) class Status(enum.IntEnum): """The status of a Device""" # No initialization done NEW = 0 # ZDO endpoint discovery done ZDO_INIT = 1 # Endpoints initialized ENDPOINTS_INIT = 2 class Device(zigpy.util.LocalLogMixin, zigpy.util.ListenableMixin): """A device on the network""" def __init__(self, application, ieee, nwk): self._application = application self._ieee = ieee self._init_handle = None self.nwk = NWK(nwk) self.zdo = zdo.ZDO(self) self.endpoints: Dict[int, Union[zdo.ZDO, zigpy.endpoint.Endpoint]] = { 0: self.zdo } self.lqi = None self.rssi = None self.last_seen = None self.status = Status.NEW self.initializing = False self._group_scan_handle: Optional[asyncio.Task] = None self._listeners = {} self._manufacturer = None self._model = None self.node_desc = zdo.types.NodeDescriptor() self._node_handle = None self._pending = zigpy.util.Requests() self._relays = None self._skip_configuration = False def schedule_initialize(self): if self.initializing: LOGGER.debug("Canceling old initialize call") self._init_handle.cancel() else: self.initializing = True self._init_handle = asyncio.ensure_future(self._initialize()) def schedule_group_membership_scan(self) -> None: """Rescan device group's membership.""" if self._group_scan_handle and not self._group_scan_handle.done(): self.debug("Cancelling old group rescan") self._group_scan_handle.cancel() self._group_scan_handle = asyncio.ensure_future(self.group_membership_scan()) async def group_membership_scan(self) -> None: """Sync up group membership.""" for ep_id, ep in self.endpoints.items(): if ep_id: await ep.group_membership_scan() async def get_node_descriptor(self): self.info("Requesting 'Node Descriptor'") try: status, _, node_desc = await self.zdo.Node_Desc_req( self.nwk, tries=2, delay=1 ) if status == zdo.types.Status.SUCCESS: self.node_desc = node_desc self.info("Node Descriptor: %s", node_desc) return node_desc else: self.warning("Requesting Node Descriptor failed: %s", status) except Exception: self.warning("Requesting Node Descriptor failed", exc_info=True) async def refresh_node_descriptor(self): if await self.get_node_descriptor(): self._application.listener_event("node_descriptor_updated", self) async def _initialize(self): if self.status == Status.NEW: if self._node_handle is None or self._node_handle.done(): self._node_handle = asyncio.ensure_future(self.get_node_descriptor()) await self._node_handle self.info("Discovering endpoints") try: epr = await self.zdo.Active_EP_req(self.nwk, tries=3, delay=2) if epr[0] != 0: raise Exception("Endpoint request failed: %s", epr) except Exception: self.initializing = False LOGGER.exception( "Failed ZDO request during device initialization", exc_info=True ) return self.info("Discovered endpoints: %s", epr[2]) for endpoint_id in epr[2]: self.add_endpoint(endpoint_id) self.status = Status.ZDO_INIT for endpoint_id, ep in self.endpoints.items(): if endpoint_id == 0: # ZDO continue try: await ep.initialize() except Exception as exc: self.debug("Endpoint %s initialization failure: %s", endpoint_id, exc) break if self.manufacturer is None or self.model is None: self.model, self.manufacturer = await ep.get_model_info() ep_failed_init = [ ep.status == zigpy.endpoint.Status.NEW for epid, ep in self.endpoints.items() if epid ] if any(ep_failed_init): self.initializing = False self.application.listener_event("device_init_failure", self) await self.application.remove(self.ieee) return self.status = Status.ENDPOINTS_INIT self.initializing = False self._application.device_initialized(self) def add_endpoint(self, endpoint_id): ep = zigpy.endpoint.Endpoint(self, endpoint_id) self.endpoints[endpoint_id] = ep return ep async def add_to_group(self, grp_id: int, name: str = None): for ep_id, ep in self.endpoints.items(): if ep_id: await ep.add_to_group(grp_id, name) async def remove_from_group(self, grp_id: int): for ep_id, ep in self.endpoints.items(): if ep_id: await ep.remove_from_group(grp_id) async def request( self, profile, cluster, src_ep, dst_ep, sequence, data, expect_reply=True, timeout=APS_REPLY_TIMEOUT, use_ieee=False, ): if expect_reply and self.node_desc.is_end_device in (True, None): self.debug("Extending timeout for 0x%02x request", sequence) timeout = APS_REPLY_TIMEOUT_EXTENDED with self._pending.new(sequence) as req: result, msg = await self._application.request( self, profile, cluster, src_ep, dst_ep, sequence, data, expect_reply=expect_reply, use_ieee=use_ieee, ) if result != foundation.Status.SUCCESS: self.debug( ( "Delivery error for seq # 0x%02x, on endpoint id %s " "cluster 0x%04x: %s" ), sequence, dst_ep, cluster, msg, ) raise zigpy.exceptions.DeliveryError( "[0x{:04x}:{}:0x{:04x}]: Message send failure".format( self.nwk, dst_ep, cluster ) ) # If application.request raises an exception, we won't get here, so # won't update last_seen, as expected self.last_seen = time.time() if expect_reply: result = await asyncio.wait_for(req.result, timeout) return result def deserialize(self, endpoint_id, cluster_id, data): return self.endpoints[endpoint_id].deserialize(cluster_id, data) def handle_message(self, profile, cluster, src_ep, dst_ep, message): self.last_seen = time.time() if not self.node_desc.is_valid and ( self._node_handle is None or self._node_handle.done() ): self._node_handle = asyncio.ensure_future(self.refresh_node_descriptor()) try: hdr, args = self.deserialize(src_ep, cluster, message) except ValueError as e: LOGGER.error( "Failed to parse message (%s) on cluster %d, because %s", binascii.hexlify(message), cluster, e, ) return except KeyError as e: LOGGER.debug( ( "Ignoring message (%s) on cluster %d: " "unknown endpoint or cluster id: %s" ), binascii.hexlify(message), cluster, e, ) return if hdr.tsn in self._pending and hdr.is_reply: try: self._pending[hdr.tsn].result.set_result(args) return except asyncio.InvalidStateError: self.debug( ( "Invalid state on future for 0x%02x seq " "-- probably duplicate response" ), hdr.tsn, ) return endpoint = self.endpoints[src_ep] return endpoint.handle_message(profile, cluster, hdr, args) def reply(self, profile, cluster, src_ep, dst_ep, sequence, data, use_ieee=False): return self.request( profile, cluster, src_ep, dst_ep, sequence, data, expect_reply=False, use_ieee=use_ieee, ) def radio_details(self, lqi, rssi): self.lqi = lqi self.rssi = rssi def log(self, lvl, msg, *args, **kwargs): msg = "[0x%04x] " + msg args = (self.nwk,) + args return LOGGER.log(lvl, msg, *args, **kwargs) @property def application(self): return self._application @property def ieee(self): return self._ieee @property def manufacturer(self): return self._manufacturer @manufacturer.setter def manufacturer(self, value): if isinstance(value, str): self._manufacturer = value @property def model(self): return self._model @property def skip_configuration(self): return self._skip_configuration @skip_configuration.setter def skip_configuration(self, should_skip_configuration): if isinstance(should_skip_configuration, bool): self._skip_configuration = should_skip_configuration else: self._skip_configuration = False @model.setter def model(self, value): if isinstance(value, str): self._model = value @property def relays(self) -> Optional[Relays]: """Relay list.""" return self._relays @relays.setter def relays(self, relays: Optional[Relays]) -> None: self._relays = relays self.listener_event("device_relays_updated", relays) def __getitem__(self, key): return self.endpoints[key] def get_signature(self): signature = {} for endpoint_id, endpoint in self.endpoints.items(): if endpoint_id == 0: # ZDO continue in_clusters = [c for c in endpoint.in_clusters] out_clusters = [c for c in endpoint.out_clusters] signature[endpoint_id] = { "in_clusters": in_clusters, "out_clusters": out_clusters, } return signature async def broadcast( app, profile, cluster, src_ep, dst_ep, grpid, radius, sequence, data, broadcast_address=BroadcastAddress.RX_ON_WHEN_IDLE, ): result = await app.broadcast( profile, cluster, src_ep, dst_ep, grpid, radius, sequence, data, broadcast_address=broadcast_address, ) return result
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/device.py
device.py
import asyncio from collections import defaultdict import datetime import logging import os import os.path from typing import Optional import aiohttp import attr from zigpy.ota.image import ImageKey, OTAImage, OTAImageHeader import zigpy.util LOGGER = logging.getLogger(__name__) LOCK_REFRESH = "firmware_list" ENABLE_IKEA_OTA = "enable_ikea_ota" ENABLE_LEDVANCE_OTA = "enable_ledvance_ota" SKIP_OTA_FILES = (ENABLE_IKEA_OTA, ENABLE_LEDVANCE_OTA) class Basic(zigpy.util.LocalLogMixin): """Skeleton OTA Firmware provider.""" REFRESH = datetime.timedelta(hours=12) def __init__(self): self._cache = {} self._is_enabled = False self._locks = defaultdict(asyncio.Semaphore) self._last_refresh = None async def initialize_provider(self, ota_dir: str) -> None: pass async def refresh_firmware_list(self) -> None: """Loads list of firmware into memory.""" raise NotImplementedError async def filter_get_image(self, key: ImageKey) -> bool: """Filter unwanted get_image lookups.""" return False async def get_image(self, key: ImageKey) -> Optional[OTAImage]: if await self.filter_get_image(key): return None if not self.is_enabled or self._locks[key].locked(): return None if self.expired: await self.refresh_firmware_list() try: fw_file = self._cache[key] except KeyError: return None async with self._locks[key]: return await fw_file.fetch_image() def disable(self) -> None: self._is_enabled = False def enable(self) -> None: self._is_enabled = True def update_expiration(self): self._last_refresh = datetime.datetime.now() @property def is_enabled(self) -> bool: return self._is_enabled @property def expired(self) -> bool: """Return True if firmware list needs refreshing.""" if self._last_refresh is None: return True return datetime.datetime.now() - self._last_refresh > self.REFRESH def log(self, lvl, msg, *args, **kwargs): """Log a message""" msg = f"{self.__class__.__name__}: {msg}" return LOGGER.log(lvl, msg, *args, **kwargs) @attr.s class IKEAImage: manufacturer_id = attr.ib() image_type = attr.ib() version = attr.ib(default=None) image_size = attr.ib(default=None) url = attr.ib(default=None) @classmethod def new(cls, data): res = cls(data["fw_manufacturer_id"], data["fw_image_type"]) res.file_version = data["fw_file_version_MSB"] << 16 res.file_version |= data["fw_file_version_LSB"] res.image_size = data["fw_filesize"] res.url = data["fw_binary_url"] return res @property def key(self): return ImageKey(self.manufacturer_id, self.image_type) async def fetch_image(self) -> Optional[OTAImage]: async with aiohttp.ClientSession() as req: LOGGER.debug("Downloading %s for %s", self.url, self.key) async with req.get(self.url) as rsp: data = await rsp.read() assert len(data) > 24 offset = int.from_bytes(data[16:20], "little") size = int.from_bytes(data[20:24], "little") assert len(data) > offset + size ota_image, _ = OTAImage.deserialize(data[offset : offset + size]) assert ota_image.key == self.key LOGGER.debug( "Finished downloading %s bytes from %s for %s ver %s", self.image_size, self.url, self.key, self.version, ) return ota_image class Trådfri(Basic): """IKEA OTA Firmware provider.""" UPDATE_URL = "https://fw.ota.homesmart.ikea.net/feed/version_info.json" MANUFACTURER_ID = 4476 HEADERS = {"accept": "application/json;q=0.9,*/*;q=0.8"} async def initialize_provider(self, ota_dir: str) -> None: if ota_dir is None: return if os.path.isfile(os.path.join(ota_dir, ENABLE_IKEA_OTA)): self.info("OTA provider enabled") await self.refresh_firmware_list() self.enable() async def refresh_firmware_list(self) -> None: if self._locks[LOCK_REFRESH].locked(): return async with self._locks[LOCK_REFRESH]: async with aiohttp.ClientSession(headers=self.HEADERS) as req: async with req.get(self.UPDATE_URL) as rsp: # IKEA does not always respond with an appropriate Content-Type # but the response is always JSON fw_lst = await rsp.json(content_type=None) self.debug("Finished downloading firmware update list") self._cache.clear() for fw in fw_lst: if "fw_file_version_MSB" not in fw: continue img = IKEAImage.new(fw) self._cache[img.key] = img self.update_expiration() async def filter_get_image(self, key: ImageKey) -> bool: return key.manufacturer_id != self.MANUFACTURER_ID @attr.s class LedvanceImage: """Ledvance image handler.""" manufacturer_id = attr.ib() image_type = attr.ib() version = attr.ib(default=None) image_size = attr.ib(default=None) url = attr.ib(default=None) @classmethod def new(cls, data): ident = data["identity"] company, product, ver = (ident["company"], ident["product"], ident["version"]) major, minor, build = (ver["major"], ver["minor"], ver["build"]) res = cls(company, product) res.file_version = int(data["fullName"].split("/")[1], 16) res.image_size = data["length"] res.url = ( f"https://api.update.ledvance.com/v1/zigbee/firmwares/download" f"?Company={company}&Product={product}&Version={major}.{minor}.{build}" ) return res @property def key(self): return ImageKey(self.manufacturer_id, self.image_type) async def fetch_image(self) -> Optional[OTAImage]: async with aiohttp.ClientSession() as req: LOGGER.debug("Downloading %s for %s", self.url, self.key) async with req.get(self.url) as rsp: data = await rsp.read() img, _ = OTAImage.deserialize(data) assert img.key == self.key LOGGER.debug( "%s: version: %s, hw_ver: (%s, %s), OTA string: %s", img.key, img.header.file_version, img.header.minimum_hardware_version, img.header.maximum_hardware_version, img.header.header_string, ) LOGGER.debug( "Finished downloading %s bytes from %s for %s ver %s", self.image_size, self.url, self.key, self.version, ) return img class Ledvance(Basic): """ Ledvance firmware provider """ # documentation: https://portal.update.ledvance.com/docs/services/firmware-rest-api/ UPDATE_URL = "https://api.update.ledvance.com/v1/zigbee/firmwares" HEADERS = {"accept": "application/json"} async def initialize_provider(self, ota_dir: str) -> None: if ota_dir is None: return if os.path.isfile(os.path.join(ota_dir, ENABLE_LEDVANCE_OTA)): self.info("OTA provider enabled") await self.refresh_firmware_list() self.enable() async def refresh_firmware_list(self) -> None: if self._locks[LOCK_REFRESH].locked(): return async with self._locks[LOCK_REFRESH]: async with aiohttp.ClientSession(headers=self.HEADERS) as req: async with req.get(self.UPDATE_URL) as rsp: fw_lst = await rsp.json() self.debug("Finished downloading firmware update list") self._cache.clear() for fw in fw_lst["firmwares"]: img = LedvanceImage.new(fw) self._cache[img.key] = img self.update_expiration() @attr.s class FileImage(OTAImageHeader): REFRESH = datetime.timedelta(hours=24) file_name = attr.ib(default=None) @property def key(self) -> ImageKey: return ImageKey(self.manufacturer_id, self.image_type) @property def version(self) -> int: return self.file_version @classmethod def scan_image(cls, file_name: str): """Check the header of the image.""" try: with open(file_name, mode="rb") as file: data = file.read(512) offset = data.index(cls.OTA_HEADER) if offset >= 0: img = cls.deserialize(data[offset:])[0] img.file_name = file_name LOGGER.debug( "%s: %s, version: %s, hw_ver: (%s, %s), OTA string: %s", img.key, file_name, img.file_version, img.minimum_hardware_version, img.maximum_hardware_version, img.header_string, ) return img except (OSError, ValueError): LOGGER.debug( "File '%s' doesn't appear to be a OTA image", file_name, exc_info=True ) return None def fetch_image(self) -> Optional[OTAImage]: """Load image using executor.""" loop = asyncio.get_event_loop() return loop.run_in_executor(None, self._fetch_image) def _fetch_image(self) -> Optional[OTAImage]: """Loads full OTA Image from the file.""" try: with open(self.file_name, mode="rb") as file: data = file.read() offset = data.index(self.OTA_HEADER) if offset >= 0: img = OTAImage.deserialize(data[offset:])[0] return img except (OSError, ValueError): LOGGER.debug("Couldn't load '%s' OTA image", self.file_name, exc_info=True) return None class FileStore(Basic): def __init__(self, ota_dir=None): super().__init__() self._ota_dir = self.validate_ota_dir(ota_dir) @staticmethod def validate_ota_dir(ota_dir: str) -> str: """Return True if exists and is a dir.""" if ota_dir is None: return None if os.path.exists(ota_dir): if os.path.isdir(ota_dir): return ota_dir LOGGER.error("OTA image path '%s' is not a directory", ota_dir) else: LOGGER.debug("OTA image directory '%s' does not exist", ota_dir) return None async def initialize_provider(self, ota_dir: str) -> None: if self._ota_dir is None: self._ota_dir = self.validate_ota_dir(ota_dir) if self._ota_dir is not None: self.enable() await self.refresh_firmware_list() async def refresh_firmware_list(self) -> None: if self._ota_dir is None: return None self._cache.clear() loop = asyncio.get_event_loop() for root, dirs, files in os.walk(self._ota_dir): for file in files: if file in SKIP_OTA_FILES: continue file_name = os.path.join(root, file) img = await loop.run_in_executor(None, FileImage.scan_image, file_name) if img is None: continue if img.key in self._cache: if img.version > self._cache[img.key].version: self.debug( "%s: Preferring '%s' over '%s'", img.key, file_name, self._cache[img.key].file_name, ) self._cache[img.key] = img elif img.version == self._cache[img.key].version: self.debug( "%s: Ignoring '%s' already have %s version", img.key, file_name, img.version, ) else: self.debug( "%s: Preferring '%s' over '%s'", img.key, self._cache[img.key].file_name, file_name, ) else: self._cache[img.key] = img self.update_expiration()
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/ota/provider.py
provider.py
import attr import zigpy.types as t @attr.s(frozen=True) class ImageKey: manufacturer_id = attr.ib(default=None) image_type = attr.ib(default=None) class HWVersion(t.uint16_t): @property def version(self): return self >> 8 @property def revision(self): return self & 0x00FF def __repr__(self): return "<{} version={} revision={}>".format( self.__class__.__name__, self.version, self.revision ) class HeaderString(str): _size = 32 @classmethod def deserialize(cls, data): if len(data) < cls._size: raise ValueError("Data is too short. Should be at least %s", cls._size) raw = data[: cls._size].split(b"\x00")[0] return cls(raw.decode("utf8", errors="replace")), data[cls._size :] def serialize(self): return self.encode("utf8").ljust(self._size, b"\x00") class OTAImageHeader(t.Struct): MAGIC_VALUE = 0x0BEEF11E OTA_HEADER = MAGIC_VALUE.to_bytes(4, "little") _fields = [ ("upgrade_file_id", t.uint32_t), ("header_version", t.uint16_t), ("header_length", t.uint16_t), ("field_control", t.uint16_t), ("manufacturer_id", t.uint16_t), ("image_type", t.uint16_t), ("file_version", t.uint32_t), ("stack_version", t.uint16_t), ("header_string", HeaderString), ("image_size", t.uint32_t), ] @property def security_credential_version_present(self) -> bool: if self.field_control is None: return None return bool(self.field_control & 0x01) @property def device_specific_file(self) -> bool: if self.field_control is None: return None return bool(self.field_control & 0x02) @property def hardware_versions_present(self) -> bool: if self.field_control is None: return None return bool(self.field_control & 0x04) @classmethod def deserialize(cls, data) -> tuple: hdr, data = super().deserialize(data) if hdr.upgrade_file_id != cls.MAGIC_VALUE: raise ValueError( "Wrong magic number for OTA Image: %s" % (hdr.upgrade_file_id,) ) if hdr.security_credential_version_present: hdr.security_credential_version, data = t.uint8_t.deserialize(data) else: hdr.security_credential_version = None if hdr.device_specific_file: hdr.upgrade_file_destination, data = t.EUI64.deserialize(data) else: hdr.upgrade_file_destination = None if hdr.hardware_versions_present: hdr.minimum_hardware_version, data = HWVersion.deserialize(data) hdr.maximum_hardware_version, data = HWVersion.deserialize(data) else: hdr.minimum_hardware_version = None hdr.maximum_hardware_version = None return hdr, data def serialize(self) -> bytes: data = super().serialize() if self.security_credential_version_present: data += self.security_credential_version.serialize() if self.device_specific_file: data += self.upgrade_file_destination.serialize() if self.hardware_versions_present: data += self.minimum_hardware_version.serialize() data += self.maximum_hardware_version.serialize() return data class ElementTagId(t.enum16): UPGRADE_IMAGE = 0x0000 ECDSA_SIGNATURE = 0x0001 ECDSA_SIGNING_CERTIFICATE = 0x0002 IMAGE_INTEGRITY_CODE = 0x0003 class SubElement(bytes): @property def data(self): return self @property def length(self): return t.uint32_t(len(self)) @classmethod def deserialize(cls, data) -> tuple: if len(data) < 6: raise ValueError("Data is too short for {}".format(cls.__name__)) tag_id, rest = ElementTagId.deserialize(data) length, rest = t.uint32_t.deserialize(rest) if length > len(rest): raise ValueError("Data is too short for {}".format(cls.__name__)) r = cls(rest[:length]) r.tag_id = tag_id return r, rest[length:] def serialize(self): return self.tag_id.serialize() + self.length.serialize() + self @attr.s class OTAImage: MAXIMUM_DATA_SIZE = 40 header = attr.ib(factory=OTAImageHeader) subelements = attr.ib(factory=list) @classmethod def deserialize(cls, data): hdr, data = OTAImageHeader.deserialize(data) elements_len = hdr.image_size - hdr.header_length if elements_len > len(data): raise ValueError("Data is too short for {}".format(cls.__name__)) image = cls(hdr) element_data, data = data[:elements_len], data[elements_len:] while element_data: element, element_data = SubElement.deserialize(element_data) image.subelements.append(element) return image, data def serialize(self): res = self.header.serialize() for element in self.subelements: res += element.serialize() assert len(res) == self.header.image_size return res @property def key(self) -> ImageKey: return ImageKey(self.header.manufacturer_id, self.header.image_type) @property def version(self) -> int: return self.header.file_version def should_update(self, manufacturer_id, img_type, ver, hw_ver=None) -> bool: """Check if it should upgrade""" key = ImageKey(manufacturer_id, img_type) should_update = [key == self.key, ver < self.version] if hw_ver is not None and self.header.hardware_versions_present: min_ver = self.header.minimum_hardware_version max_ver = self.header.maximum_hardware_version should_update.append(min_ver <= hw_ver <= max_ver) return all(should_update) def get_image_block(self, offset: t.uint32_t, size: t.uint8_t) -> bytes: data = self.serialize() if offset > len(data): raise ValueError("Offset exceeds image size") return data[offset : offset + min(self.MAXIMUM_DATA_SIZE, size)]
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/ota/image.py
image.py
import asyncio import datetime import logging from typing import Optional import attr from zigpy.ota.image import ImageKey, OTAImage import zigpy.ota.provider import zigpy.util LOGGER = logging.getLogger(__name__) DELAY_EXPIRATION = datetime.timedelta(hours=2) TIMEDELTA_0 = datetime.timedelta() @attr.s class CachedImage(OTAImage): DEFAULT_EXPIRATION = datetime.timedelta(hours=18) expires_on = attr.ib(default=None) @classmethod def new(cls, img: OTAImage): expiration = datetime.datetime.now() + cls.DEFAULT_EXPIRATION return cls(img.header, img.subelements, expiration) @property def expired(self) -> bool: if self.expires_on is None: return False return self.expires_on - datetime.datetime.now() < TIMEDELTA_0 def get_image_block(self, *args, **kwargs) -> bytes: if ( self.expires_on is not None and self.expires_on - datetime.datetime.now() < DELAY_EXPIRATION ): self.expires_on += DELAY_EXPIRATION return super().get_image_block(*args, **kwargs) class OTA(zigpy.util.ListenableMixin): """OTA Manager.""" def __init__(self, app, *args, **kwargs): self._app = app self._image_cache = {} self._not_initialized = True self._listeners = {} self.add_listener(zigpy.ota.provider.Trådfri()) self.add_listener(zigpy.ota.provider.FileStore()) self.add_listener(zigpy.ota.provider.Ledvance()) async def _initialize(self, ota_dir: str) -> None: LOGGER.debug("Initialize OTA providers") await self.async_event("initialize_provider", ota_dir) def initialize(self, ota_dir: str) -> None: self._not_initialized = False asyncio.ensure_future(self._initialize(ota_dir)) async def get_ota_image(self, manufacturer_id, image_type) -> Optional[OTAImage]: key = ImageKey(manufacturer_id, image_type) if key in self._image_cache and not self._image_cache[key].expired: return self._image_cache[key] images = await self.async_event("get_image", key) images = [img for img in images if img] if not images: return None cached = CachedImage.new(max(images, key=lambda img: img.version)) self._image_cache[key] = cached return cached @property def not_initialized(self): return self._not_initialized
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/ota/__init__.py
__init__.py
import enum import struct from typing import Callable, TypeVar CALLABLE_T = TypeVar("CALLABLE_T", bound=Callable) # pylint: disable=invalid-name class int_t(int): # noqa: N801 _signed = True def serialize(self): return self.to_bytes(self._size, "little", signed=self._signed) @classmethod def deserialize(cls, data): if len(data) < cls._size: raise ValueError("Data is too short to contain %d bytes" % cls._size) r = cls.from_bytes(data[: cls._size], "little", signed=cls._signed) return r, data[cls._size :] class int8s(int_t): # noqa: N801 _size = 1 class int16s(int_t): # noqa: N801 _size = 2 class int24s(int_t): # noqa: N801 _size = 3 class int32s(int_t): # noqa: N801 _size = 4 class int40s(int_t): # noqa: N801 _size = 5 class int48s(int_t): # noqa: N801 _size = 6 class int56s(int_t): # noqa: N801 _size = 7 class int64s(int_t): # noqa: N801 _size = 8 class uint_t(int_t): # noqa: N801 _signed = False class uint8_t(uint_t): # noqa: N801 _size = 1 class uint16_t(uint_t): # noqa: N801 _size = 2 class uint24_t(uint_t): # noqa: N801 _size = 3 class uint32_t(uint_t): # noqa: N801 _size = 4 class uint40_t(uint_t): # noqa: N801 _size = 5 class uint48_t(uint_t): # noqa: N801 _size = 6 class uint56_t(uint_t): # noqa: N801 _size = 7 class uint64_t(uint_t): # noqa: N801 _size = 8 class _IntEnumMeta(enum.EnumMeta): def __call__(cls, value, names=None, *args, **kwargs): if isinstance(value, str) and value.startswith("0x"): value = int(value, base=16) else: value = int(value) return super().__call__(value, names, *args, **kwargs) def enum_factory(int_type: CALLABLE_T, undefined: str = "undefined") -> CALLABLE_T: """Enum factory.""" class _NewEnum(enum.IntEnum, metaclass=_IntEnumMeta): def serialize(self): """Serialize enum.""" return int_type(self.value).serialize() @classmethod def deserialize(cls, data: bytes) -> (bytes, bytes): """Deserialize data.""" val, data = int_type.deserialize(data) return cls(val), data @classmethod def _missing_(cls, value): new = int_type.__new__(cls, value) name = f"{undefined}_0x{{:0{int_type._size * 2}x}}" # pylint: disable=protected-access new._name_ = name.format(value) new._value_ = value return new return _NewEnum class enum8(enum_factory(uint8_t)): # noqa: N801 pass class enum16(enum_factory(uint16_t)): # noqa: N801 pass def bitmap_factory(int_type: CALLABLE_T) -> CALLABLE_T: """Bitmap factory.""" class _NewBitmap(enum.IntFlag): def serialize(self): """Serialize enum.""" return int_type(self.value).serialize() @classmethod def deserialize(cls, data: bytes) -> (bytes, bytes): """Deserialize data.""" val, data = int_type.deserialize(data) return cls(val), data return _NewBitmap class bitmap8(bitmap_factory(uint8_t)): # noqa: N801 pass class bitmap16(bitmap_factory(uint16_t)): # noqa: N801 pass class bitmap24(bitmap_factory(uint24_t)): # noqa: N801 pass class bitmap32(bitmap_factory(uint32_t)): # noqa: N801 pass class bitmap40(bitmap_factory(uint40_t)): # noqa: N801 pass class bitmap48(bitmap_factory(uint48_t)): # noqa: N801 pass class bitmap56(bitmap_factory(uint56_t)): # noqa: N801 pass class bitmap64(bitmap_factory(uint64_t)): # noqa: N801 pass class Single(float): _fmt = "<f" def serialize(self): return struct.pack(self._fmt, self) @classmethod def deserialize(cls, data): size = struct.calcsize(cls._fmt) if len(data) < size: raise ValueError("Data is too short to contain %s float" % cls.__name__) return struct.unpack(cls._fmt, data[0:size])[0], data[size:] class Double(Single): _fmt = "<d" class LVBytes(bytes): _prefix_length = 1 def serialize(self): if len(self) >= pow(256, self._prefix_length) - 1: raise ValueError("OctetString is too long") return len(self).to_bytes(self._prefix_length, "little", signed=False) + self @classmethod def deserialize(cls, data): if len(data) < cls._prefix_length: raise ValueError("Data is too short") num_bytes = int.from_bytes(data[: cls._prefix_length], "little") if len(data) < cls._prefix_length + num_bytes: raise ValueError("Data is too short") s = data[cls._prefix_length : cls._prefix_length + num_bytes] return cls(s), data[cls._prefix_length + num_bytes :] class LongOctetString(LVBytes): _prefix_length = 2 class _List(list): _length = None def serialize(self): assert self._length is None or len(self) == self._length return b"".join([self._itemtype(i).serialize() for i in self]) @classmethod def deserialize(cls, data): r = cls() while data: item, data = r._itemtype.deserialize(data) r.append(item) return r, data class _LVList(_List): _prefix_length = 1 def serialize(self): head = len(self).to_bytes(self._prefix_length, "little") data = super().serialize() return head + data @classmethod def deserialize(cls, data): r = cls() if len(data) < cls._prefix_length: raise ValueError("Data is too short") length = int.from_bytes(data[: cls._prefix_length], "little") data = data[cls._prefix_length :] for i in range(length): item, data = r._itemtype.deserialize(data) r.append(item) return r, data def List(itemtype): # noqa: N802 class List(_List): _itemtype = itemtype return List def LVList(itemtype, prefix_length=1): # noqa: N802 class LVList(_LVList): _itemtype = itemtype _prefix_length = prefix_length return LVList class _FixedList(_List): @classmethod def deserialize(cls, data): r = cls() for i in range(r._length): item, data = r._itemtype.deserialize(data) r.append(item) return r, data def fixed_list(length, itemtype): class FixedList(_FixedList): _length = length _itemtype = itemtype return FixedList class CharacterString(str): _prefix_length = 1 def serialize(self): if len(self) >= pow(256, self._prefix_length) - 1: raise ValueError("String is too long") return len(self).to_bytes( self._prefix_length, "little", signed=False ) + self.encode("utf8") @classmethod def deserialize(cls, data): if len(data) < cls._prefix_length: raise ValueError("Data is too short") length = int.from_bytes(data[: cls._prefix_length], "little") if len(data) < cls._prefix_length + length: raise ValueError("Data is too short") raw = data[cls._prefix_length : cls._prefix_length + length] r = cls(raw.split(b"\x00")[0].decode("utf8", errors="replace")) r.raw = raw return r, data[cls._prefix_length + length :] class LongCharacterString(CharacterString): _prefix_length = 2 def LimitedCharString(max_len): # noqa: N802 class LimitedCharString(CharacterString): _max_len = max_len def serialize(self): if len(self) > self._max_len: raise ValueError("String is too long") return super().serialize() return LimitedCharString def Optional(optional_item_type): class Optional(optional_item_type): optional = True @classmethod def deserialize(cls, data): try: return super().deserialize(data) except ValueError: return None, b"" return Optional class data8(_FixedList): """General data, Discrete, 8 bit.""" _itemtype = uint8_t _length = 1 class data16(data8): """General data, Discrete, 16 bit.""" _length = 2 class data24(data8): """General data, Discrete, 24 bit.""" _length = 3 class data32(data8): """General data, Discrete, 32 bit.""" _length = 4 class data40(data8): """General data, Discrete, 40 bit.""" _length = 5 class data48(data8): """General data, Discrete, 48 bit.""" _length = 6 class data56(data8): """General data, Discrete, 56 bit.""" _length = 7 class data64(data8): """General data, Discrete, 64 bit.""" _length = 8
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/types/basic.py
basic.py
import enum import typing from . import basic from .struct import Struct class BroadcastAddress(basic.enum16): ALL_DEVICES = 0xFFFF RESERVED_FFFE = 0xFFFE RX_ON_WHEN_IDLE = 0xFFFD ALL_ROUTERS_AND_COORDINATOR = 0xFFFC LOW_POWER_ROUTER = 0xFFFB RESERVED_FFFA = 0xFFFA RESERVED_FFF9 = 0xFFF9 RESERVED_FFF8 = 0xFFF8 class EUI64(basic.fixed_list(8, basic.uint8_t)): # EUI 64-bit ID (an IEEE address). def __repr__(self): return ":".join("%02x" % i for i in self[::-1]) def __hash__(self): return hash(repr(self)) @classmethod def convert(cls, ieee: str): if ieee is None: return None ieee = [basic.uint8_t(p, base=16) for p in ieee.split(":")[::-1]] assert len(ieee) == cls._length return cls(ieee) class KeyData(basic.fixed_list(16, basic.uint8_t)): pass class Bool(basic.uint8_t, enum.Enum): false = 0 true = 1 class HexRepr: def __repr__(self): return ("0x{:0" + str(self._size * 2) + "x}").format(self) def __str__(self): return ("0x{:0" + str(self._size * 2) + "x}").format(self) class AttributeId(HexRepr, basic.uint16_t): pass class BACNetOid(basic.uint32_t): pass class Channels(basic.bitmap32): """Zigbee Channels.""" NO_CHANNELS = 0x00000000 ALL_CHANNELS = 0x07FFF800 CHANNEL_11 = 0x00000800 CHANNEL_12 = 0x00001000 CHANNEL_13 = 0x00002000 CHANNEL_14 = 0x00004000 CHANNEL_15 = 0x00008000 CHANNEL_16 = 0x00010000 CHANNEL_17 = 0x00020000 CHANNEL_18 = 0x00040000 CHANNEL_19 = 0x00080000 CHANNEL_20 = 0x00100000 CHANNEL_21 = 0x00200000 CHANNEL_22 = 0x00400000 CHANNEL_23 = 0x00800000 CHANNEL_24 = 0x01000000 CHANNEL_25 = 0x02000000 CHANNEL_26 = 0x04000000 @classmethod def from_channel_list(cls, channels: typing.Iterable[int]) -> "Channels": mask = cls.NO_CHANNELS for channel in channels: if not 11 <= channel <= 26: raise ValueError( f"Invalid channel number {channel}. Must be between 11 and 26." ) mask |= cls[f"CHANNEL_{channel}"] return mask class ClusterId(basic.uint16_t): pass class Date(Struct): _fields = [ ("_year", basic.uint8_t), ("month", basic.uint8_t), ("day", basic.uint8_t), ("day_of_week", basic.uint8_t), ] @property def year(self): """Return year.""" if self._year is None: return self._year return 1900 + self._year @year.setter def year(self, value): assert 1900 <= value <= 2155 self._year = basic.uint8_t(value - 1900) class NWK(HexRepr, basic.uint16_t): pass class PanId(NWK): pass class ExtendedPanId(EUI64): pass class Group(HexRepr, basic.uint16_t): pass class NoData: @classmethod def deserialize(cls, data): return cls(), data def serialize(self): return b"" class TimeOfDay(Struct): _fields = [ ("hours", basic.uint8_t), ("minutes", basic.uint8_t), ("seconds", basic.uint8_t), ("hundredths", basic.uint8_t), ] class _Time(basic.uint32_t): pass class UTCTime(_Time): pass class StandardTime(_Time): """Adjusted for TimeZone but not for daylight saving.""" pass class LocalTime(_Time): """Standard time adjusted for daylight saving.""" pass class Relays(basic.LVList(NWK)): """Relay list for static routing.""" pass class APSStatus(basic.enum8): # A request has been executed successfully APS_SUCCESS = 0x00 # A transmit request failed since the ASDU is too large and fragmentation # is not supported APS_ASDU_TOO_LONG = 0xA0 # A received fragmented frame could not be defragmented at the current time APS_DEFRAG_DEFERRED = 0xA1 # A received fragmented frame could not be defragmented since the device # does not support fragmentation APS_DEFRAG_UNSUPPORTED = 0xA2 # A parameter value was out of range APS_ILLEGAL_REQUEST = 0xA3 # An APSME-UNBIND.request failed due to the requested binding link not # existing in the binding table APS_INVALID_BINDING = 0xA4 # An APSME-REMOVE-GROUP.request has been issued with a group identifier # that does not appear in the group table APS_INVALID_GROUP = 0xA5 # A parameter value was invalid or out of range APS_INVALID_PARAMETER = 0xA6 # An APSDE-DATA.request requesting acknowledged transmission failed due to # no acknowledgement being received APS_NO_ACK = 0xA7 # An APSDE-DATA.request with a destination addressing mode set to 0x00 # failed due to there being no devices bound to this device APS_NO_BOUND_DEVICE = 0xA8 # An APSDE-DATA.request with a destination addressing mode set to 0x03 # failed due to no corresponding short address found in the address map # table APS_NO_SHORT_ADDRESS = 0xA9 # An APSDE-DATA.request with a destination addressing mode set to 0x00 # failed due to a binding table not being supported on the device APS_NOT_SUPPORTED = 0xAA # An ASDU was received that was secured using a link key APS_SECURED_LINK_KEY = 0xAB # An ASDU was received that was secured using a network key APS_SECURED_NWK_KEY = 0xAC # An APSDE-DATA.request requesting security has resulted in an error # during the corresponding security processing APS_SECURITY_FAIL = 0xAD # An APSME-BIND.request or APSME.ADDGROUP.request issued when the binding # or group tables, respectively, were full APS_TABLE_FULL = 0xAE # An ASDU was received without any security APS_UNSECURED = 0xAF # An APSME-GET.request or APSMESET.request has been issued with an unknown # attribute identifier APS_UNSUPPORTED_ATTRIBUTE = 0xB0 @classmethod def _missing_(cls, value): chained = NWKStatus(value) status = basic.uint8_t.__new__(cls, chained.value) status._name_ = chained.name status._value_ = value return status class MACStatus(basic.enum8): # Operation was successful MAC_SUCCESS = 0x00 # Association Status field MAC_PAN_AT_CAPACITY = 0x01 MAC_PAN_ACCESS_DENIED = 0x02 # The frame counter purportedly applied by the originator of the received # frame is invalid MAC_COUNTER_ERROR = 0xDB # The key purportedly applied by the originator of the received frame is # not allowed to be used with that frame type according to the key usage # policy of the recipient MAC_IMPROPER_KEY_TYPE = 0xDC # The security level purportedly applied # by the originator of the # received frame does not meet the minimum security level # required/expected by the recipient for that frame type MAC_IMPROPER_SECURITY_LEVEL = 0xDD # The received frame was purportedly secured using security based on IEEE # Std 802.15.4-2003, and such security is not supported by this standard MAC_UNSUPPORTED_LEGACY = 0xDE # The security purportedly applied by the originator of the received frame # is not supported MAC_UNSUPPORTED_SECURITY = 0xDF # The beacon was lost following a synchronization request MAC_BEACON_LOSS = 0xE0 # A transmission could not take place due to activity on the channel, i.e. # the CSMA-CA mechanism has failed MACX_CHANNEL_ACCESS_FAILURE = 0xE1 # The GTS request has been denied by the PAN coordinator MAC_DENIED = 0xE2 # The attempt to disable the transceiver has failed MAC_DISABLE_TRX_FAILURE = 0xE3 # Cryptographic processing of the received secured frame failed MAC_SECURITY_ERROR = 0xE4 # Either a frame resulting from processing has a length that is greater # than aMaxPHYPacketSize or a requested transaction is too large to fit in # the CAP or GTS MAC_FRAME_TOO_LONG = 0xE5 # The requested GTS transmission failed because the specified GTS either # did not have a transmit GTS direction or was not defined MAC_INVALID_GTS = 0xE6 # A request to purge an MSDU from the transaction queue was made using an # MSDU handle that was not found in the transaction table MAC_INVALID_HANDLE = 0xE7 # A parameter in the primitive is either not supported or is out of the # valid range MAC_INVALID_PARAMETER = 0xE8 # No acknowledgment was received after macMaxFrameRetries MAC_NO_ACK = 0xE9 # A scan operation failed to find any network beacons MAC_NO_BEACON = 0xEA # No response data was available following a request MAC_NO_DATA = 0xEB # The operation failed because a 16-bit short address was not allocated MAC_NO_SHORT_ADDRESS = 0xEC # A receiver enable request was unsuccessful because it could not be # completed within the CAP. @note The enumeration description is not used # in this standard, and it is included only to meet the backwards # compatibility requirements for IEEE Std 802.15.4-2003 MAC_OUT_OF_CAP = 0xED # A PAN identifier conflict has been detected and communicated to the PAN # coordinator MAC_PAN_ID_CONFLICT = 0xEE # A coordinator realignment command has been received MAC_REALIGNMENT = 0xEF # The transaction has expired and its information was discarded MAC_TRANSACTION_EXPIRED = 0xF0 # There is no capacity to store the transaction MAC_TRANSACTION_OVERFLOW = 0xF1 # The transceiver was in the transmitter enabled state when the receiver # was requested to be enabled. @note The enumeration description is not # used in this standard, and it is included only to meet the backwards # compatibility requirements for IEEE Std 802.15.4-2003 MAC_TX_ACTIVE = 0xF2 # The key purportedly used by the originator of the received frame is not # available or, if available, the originating device is not known or is # blacklisted with that particular key MAC_UNAVAILABLE_KEY = 0xF3 # A SET/GET request was issued with the identifier of a PIB attribute that # is not supported MAC_UNSUPPORTED_ATTRIBUTE = 0xF4 # A request to send data was unsuccessful because neither the source # address parameters nor the destination address parameters were present MAC_INVALID_ADDRESS = 0xF5 # A receiver enable request was unsuccessful because it specified a number # of symbols that was longer than the beacon interval MAC_ON_TIME_TOO_LONG = 0xF6 # A receiver enable request was unsuccessful because it could not be # completed within the current superframe and was not permitted to be # deferred until the next superframe MAC_PAST_TIME = 0xF7 # The device was instructed to start sending beacons based on the timing # of the beacon transmissions of its coordinator, but the device is not # currently tracking the beacon of its coordinator MAC_TRACKING_OFF = 0xF8 # An attempt to write to a MAC PIB attribute that is in a table failed # because the specified table index was out of range MAC_INVALID_INDEX = 0xF9 # A scan operation terminated prematurely because the number of PAN # descriptors stored reached an implementation specified maximum MAC_LIMIT_REACHED = 0xFA # A SET/GET request was issued with the identifier of an attribute that is # read only MAC_READ_ONLY = 0xFB # A request to perform a scan operation failed because the MLME was in the # process of performing a previously initiated scan operation MAC_SCAN_IN_PROGRESS = 0xFC # The device was instructed to start sending beacons based on the timing # of the beacon transmissions of its coordinator, but the instructed start # time overlapped the transmission time of the beacon of its coordinator MAC_SUPERFRAME_OVERLAP = 0xFD class NWKStatus(basic.enum8): # A request has been executed successfully NWK_SUCCESS = 0x00 # An invalid or out-of-range parameter has been passed to a primitive from # the next higher layer NWK_INVALID_PARAMETER = 0xC1 # The next higher layer has issued a request that is invalid or cannot be # executed given the current state of the NWK layer NWK_INVALID_REQUEST = 0xC2 # An NLME-JOIN.request has been disallowed NWK_NOT_PERMITTED = 0xC3 # An NLME-NETWORK-FORMATION.request has failed to start a network NWK_STARTUP_FAILURE = 0xC4 # A device with the address supplied to the NLMEDIRECT-JOIN.request is # already present in the neighbor table of the device on which the # NLMEDIRECT-JOIN.request was issued NWK_ALREADY_PRESENT = 0xC5 # Used to indicate that an NLME-SYNC.request has failed at the MAC layer NWK_SYNC_FAILURE = 0xC6 # An NLME-JOIN-DIRECTLY.request has failed because there is no more room # in the neighbor table NWK_NEIGHBOR_TABLE_FULL = 0xC7 # An NLME-LEAVE.request has failed because the device addressed in the # parameter list is not in the neighbor table of the issuing device NWK_UNKNOWN_DEVICE = 0xC8 # An NLME-GET.request or NLME-SET.request has been issued with an unknown # attribute identifier NWK_UNSUPPORTED_ATTRIBUTE = 0xC9 # An NLME-JOIN.request has been issued in an environment where no networks # are detectable NWK_NO_NETWORKS = 0xCA NWK_RESERVED_0xCB = 0xCB # Security processing has been attempted on an outgoing frame, and has # failed because the frame counter has reached its maximum value NWK_NWK_MAX_FRM_COUNTER = 0xCC # Security processing has been attempted on an outgoing frame, and has # failed because no key was available with which to process it NWK_NO_KEY = 0xCD # Security processing has been attempted on an outgoing frame, and has # failed because the security engine produced erroneous output NWK_BAD_CCM_OUTPUT = 0xCE NWK_RESERVED_0xCF = 0xCF # An attempt to discover a route has failed due to a reason other than a # lack of routing capacity NWK_ROUTE_DISCOVERY_FAILED = 0xD0 # An NLDE-DATA.request has failed due to a routing failure on the sending # device or an NLMEROUTE-DISCOVERY.request has failed due to the cause # cited in the accompanying NetworkStatusCode NWK_ROUTE_ERROR = 0xD1 # An attempt to send a broadcast frame or member mode multicast has failed # due to the fact that there is no room in the BTT NWK_BT_TABLE_FULL = 0xD2 # An NLDE-DATA.request has failed due to insufficient buffering available. # A non-member mode multicast frame was discarded pending route discovery NWK_FRAME_NOT_BUFFERED = 0xD3 @classmethod def _missing_(cls, value): chained = MACStatus(value) status = basic.uint8_t.__new__(cls, chained.value) status._name_ = chained.name status._value_ = value return status
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/types/named.py
named.py
from typing import Optional, Tuple, Union import zigpy.types as t class Status(t.enum8): SUCCESS = 0x00 # Operation was successful. FAILURE = 0x01 # Operation was not successful NOT_AUTHORIZED = 0x7E # The sender of the command does not have RESERVED_FIELD_NOT_ZERO = 0x7F # A reserved field/subfield/bit contains a MALFORMED_COMMAND = 0x80 # The command appears to contain the wrong UNSUP_CLUSTER_COMMAND = 0x81 # The specified cluster command is not UNSUP_GENERAL_COMMAND = 0x82 # The specified general ZCL command is not UNSUP_MANUF_CLUSTER_COMMAND = 0x83 # A manufacturer specific unicast, UNSUP_MANUF_GENERAL_COMMAND = 0x84 # A manufacturer specific unicast, ZCL INVALID_FIELD = 0x85 # At least one field of the command contains an UNSUPPORTED_ATTRIBUTE = 0x86 # The specified attribute does not exist on INVALID_VALUE = 0x87 # Out of range error, or set to a reserved value. READ_ONLY = 0x88 # Attempt to write a read only attribute. INSUFFICIENT_SPACE = 0x89 # An operation (e.g. an attempt to create an DUPLICATE_EXISTS = 0x8A # An attempt to create an entry in a table failed NOT_FOUND = 0x8B # The requested information (e.g. table entry) UNREPORTABLE_ATTRIBUTE = 0x8C # Periodic reports cannot be issued for this INVALID_DATA_TYPE = 0x8D # The data type given for an attribute is INVALID_SELECTOR = 0x8E # The selector for an attribute is incorrect. WRITE_ONLY = 0x8F # A request has been made to read an attribute INCONSISTENT_STARTUP_STATE = 0x90 # Setting the requested values would put DEFINED_OUT_OF_BAND = 0x91 # An attempt has been made to write an INCONSISTENT = ( 0x92 # The supplied values (e.g., contents of table cells) are inconsistent ) ACTION_DENIED = 0x93 # The credentials presented by the device sending the TIMEOUT = 0x94 # The exchange was aborted due to excessive response time ABORT = 0x95 # Failed case when a client or a server decides to abort the upgrade process INVALID_IMAGE = 0x96 # Invalid OTA upgrade image (ex. failed signature WAIT_FOR_DATA = 0x97 # Server does not have data block available yet NO_IMAGE_AVAILABLE = 0x98 # No OTA upgrade image available for a particular client REQUIRE_MORE_IMAGE = 0x99 # The client still requires more OTA upgrade image NOTIFICATION_PENDING = 0x9A # The command has been received and is being processed HARDWARE_FAILURE = 0xC0 # An operation was unsuccessful due to a SOFTWARE_FAILURE = 0xC1 # An operation was unsuccessful due to a CALIBRATION_ERROR = 0xC2 # An error occurred during calibration UNSUPPORTED_CLUSTER = 0xC3 # The cluster is not supported @classmethod def _missing_(cls, value): chained = t.APSStatus(value) status = t.uint8_t.__new__(cls, chained.value) status._name_ = chained.name status._value_ = value return status class Analog: pass class Discrete: pass class Null: pass class Unknown(t.NoData): pass class TypeValue: def __init__(self, python_type=None, value=None): self.type = python_type self.value = value def serialize(self): return self.type.to_bytes(1, "little") + self.value.serialize() @classmethod def deserialize(cls, data): self = cls() self.type, data = t.uint8_t.deserialize(data) python_type = DATA_TYPES[self.type][1] self.value, data = python_type.deserialize(data) return self, data def __repr__(self): return "<%s type=%s, value=%s>" % ( self.__class__.__name__, self.value.__class__.__name__, self.value, ) class TypedCollection(TypeValue): @classmethod def deserialize(cls, data): self = cls() self.type, data = data[0], data[1:] python_item_type = DATA_TYPES[self.type][1] python_type = t.LVList(python_item_type) self.value, data = python_type.deserialize(data) return self, data class Array(TypedCollection): pass class Bag(TypedCollection): pass class Set(TypedCollection): pass # ToDo: Make this a real set? class DataTypes(dict): """DataTypes container.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._idx_by_class = { _type: type_id for type_id, (name, _type, ad) in self.items() } self._idx_by_cls_name = { cls.__name__: type_id for cls, type_id in self._idx_by_class.items() } def pytype_to_datatype_id(self, python_type) -> int: """Return Zigbee Datatype ID for a give python type.""" data_type_id = self._idx_by_class.get(python_type) if data_type_id is not None: return data_type_id # lookup by class name try: return self._idx_by_cls_name[python_type.__name__] except KeyError: pass for cls, type_id in self._idx_by_class.items(): if issubclass(python_type, cls): self._idx_by_cls_name[python_type.__name__] = type_id return type_id return 0xFF DATA_TYPES = DataTypes( { 0x00: ("No data", t.NoData, Null), 0x08: ("General", t.data8, Discrete), 0x09: ("General", t.data16, Discrete), 0x0A: ("General", t.data24, Discrete), 0x0B: ("General", t.data32, Discrete), 0x0C: ("General", t.data40, Discrete), 0x0D: ("General", t.data48, Discrete), 0x0E: ("General", t.data56, Discrete), 0x0F: ("General", t.data64, Discrete), 0x10: ("Boolean", t.Bool, Discrete), 0x18: ("Bitmap", t.bitmap8, Discrete), 0x19: ("Bitmap", t.bitmap16, Discrete), 0x1A: ("Bitmap", t.bitmap24, Discrete), 0x1B: ("Bitmap", t.bitmap32, Discrete), 0x1C: ("Bitmap", t.bitmap40, Discrete), 0x1D: ("Bitmap", t.bitmap48, Discrete), 0x1E: ("Bitmap", t.bitmap56, Discrete), 0x1F: ("Bitmap", t.bitmap64, Discrete), 0x20: ("Unsigned Integer", t.uint8_t, Analog), 0x21: ("Unsigned Integer", t.uint16_t, Analog), 0x22: ("Unsigned Integer", t.uint24_t, Analog), 0x23: ("Unsigned Integer", t.uint32_t, Analog), 0x24: ("Unsigned Integer", t.uint40_t, Analog), 0x25: ("Unsigned Integer", t.uint48_t, Analog), 0x26: ("Unsigned Integer", t.uint56_t, Analog), 0x27: ("Unsigned Integer", t.uint64_t, Analog), 0x28: ("Signed Integer", t.int8s, Analog), 0x29: ("Signed Integer", t.int16s, Analog), 0x2A: ("Signed Integer", t.int24s, Analog), 0x2B: ("Signed Integer", t.int32s, Analog), 0x2C: ("Signed Integer", t.int40s, Analog), 0x2D: ("Signed Integer", t.int48s, Analog), 0x2E: ("Signed Integer", t.int56s, Analog), 0x2F: ("Signed Integer", t.int64s, Analog), 0x30: ("Enumeration", t.enum8, Discrete), 0x31: ("Enumeration", t.enum16, Discrete), # 0x38: ('Floating point', t.Half, Analog), 0x39: ("Floating point", t.Single, Analog), 0x3A: ("Floating point", t.Double, Analog), 0x41: ("Octet string", t.LVBytes, Discrete), 0x42: ("Character string", t.CharacterString, Discrete), 0x43: ("Long octet string", t.LongOctetString, Discrete), 0x44: ("Long character string", t.LongCharacterString, Discrete), 0x48: ("Array", Array, Discrete), 0x4C: ("Structure", t.LVList(TypeValue, 2), Discrete), 0x50: ("Set", Set, Discrete), 0x51: ("Bag", Bag, Discrete), 0xE0: ("Time of day", t.TimeOfDay, Analog), 0xE1: ("Date", t.Date, Analog), 0xE2: ("UTCTime", t.UTCTime, Analog), 0xE8: ("Cluster ID", t.ClusterId, Discrete), 0xE9: ("Attribute ID", t.AttributeId, Discrete), 0xEA: ("BACNet OID", t.BACNetOid, Discrete), 0xF0: ("IEEE address", t.EUI64, Discrete), 0xF1: ("128-bit security key", t.KeyData, Discrete), 0xFF: ("Unknown", Unknown, None), } ) class ReadAttributeRecord(t.Struct): """Read Attribute Record.""" _fields = [("attrid", t.uint16_t), ("status", Status), ("value", TypeValue)] @classmethod def deserialize(cls, data): r = cls() r.attrid, data = t.uint16_t.deserialize(data) r.status, data = Status.deserialize(data) if r.status == Status.SUCCESS: r.value, data = TypeValue.deserialize(data) return r, data def serialize(self): r = t.uint16_t(self.attrid).serialize() r += t.uint8_t(self.status).serialize() if self.status == Status.SUCCESS: r += self.value.serialize() return r def __repr__(self): r = "<ReadAttributeRecord attrid=%s status=%s" % (self.attrid, self.status) if self.status == Status.SUCCESS: r += " value=%s" % (self.value.value,) r += ">" return r class Attribute(t.Struct): _fields = [("attrid", t.uint16_t), ("value", TypeValue)] class WriteAttributesStatusRecord(t.Struct): _fields = [("status", Status), ("attrid", t.uint16_t)] @classmethod def deserialize(cls, data): r = cls() r.status, data = Status.deserialize(data) if r.status != Status.SUCCESS: r.attrid, data = t.uint16_t.deserialize(data) return r, data def serialize(self): r = Status(self.status).serialize() if self.status != Status.SUCCESS: r += t.uint16_t(self.attrid).serialize() return r def __repr__(self): r = "<%s status=%s" % (self.__class__.__name__, self.status) if self.status != Status.SUCCESS: r += " attrid=%s" % (self.attrid,) r += ">" return r class WriteAttributesResponse(list): """Write Attributes response list. Response to Write Attributes request should contain only success status, in case when all attributes were successfully written or list of status + attr_id records for all failed writes. """ @classmethod def deserialize(cls, data: bytes) -> Tuple["WriteAttributesResponse", bytes]: record, data = WriteAttributesStatusRecord.deserialize(data) r = cls([record]) if record.status == Status.SUCCESS: return r, data while len(data) >= 3: record, data = WriteAttributesStatusRecord.deserialize(data) r.append(record) return r, data def serialize(self): failed = [record for record in self if record.status != Status.SUCCESS] if failed: return b"".join( [WriteAttributesStatusRecord(i).serialize() for i in failed] ) return Status.SUCCESS.serialize() class ReportingDirection(t.enum8): SendReports = 0x00 ReceiveReports = 0x01 class AttributeReportingConfig: def __init__(self, other=None): if isinstance(other, self.__class__): self.direction = other.direction self.attrid = other.attrid if self.direction == ReportingDirection.ReceiveReports: self.timeout = other.timeout return self.datatype = other.datatype self.min_interval = other.min_interval self.max_interval = other.max_interval self.reportable_change = other.reportable_change def serialize(self): r = ReportingDirection(self.direction).serialize() r += t.uint16_t(self.attrid).serialize() if self.direction == ReportingDirection.ReceiveReports: r += t.uint16_t(self.timeout).serialize() else: r += t.uint8_t(self.datatype).serialize() r += t.uint16_t(self.min_interval).serialize() r += t.uint16_t(self.max_interval).serialize() datatype = DATA_TYPES.get(self.datatype, None) if datatype and datatype[2] is Analog: datatype = datatype[1] r += datatype(self.reportable_change).serialize() return r @classmethod def deserialize(cls, data): self = cls() self.direction, data = ReportingDirection.deserialize(data) self.attrid, data = t.uint16_t.deserialize(data) if self.direction == ReportingDirection.ReceiveReports: # Requesting things to be received by me self.timeout, data = t.uint16_t.deserialize(data) else: # Notifying that I will report things to you self.datatype, data = t.uint8_t.deserialize(data) self.min_interval, data = t.uint16_t.deserialize(data) self.max_interval, data = t.uint16_t.deserialize(data) datatype = DATA_TYPES[self.datatype] if datatype[2] is Analog: self.reportable_change, data = datatype[1].deserialize(data) return self, data class ConfigureReportingResponseRecord(t.Struct): _fields = [ ("status", Status), ("direction", ReportingDirection), ("attrid", t.uint16_t), ] @classmethod def deserialize(cls, data): r = cls() r.status, data = Status.deserialize(data) if r.status == Status.SUCCESS: r.direction, data = t.Optional(t.uint8_t).deserialize(data) if r.direction is not None: r.direction = ReportingDirection(r.direction) r.attrid, data = t.Optional(t.uint16_t).deserialize(data) return r, data r.direction, data = ReportingDirection.deserialize(data) r.attrid, data = t.uint16_t.deserialize(data) return r, data def serialize(self): r = Status(self.status).serialize() if self.status != Status.SUCCESS: r += ReportingDirection(self.direction).serialize() r += t.uint16_t(self.attrid).serialize() return r def __repr__(self): r = "<%s status=%s" % (self.__class__.__name__, self.status) if self.status != Status.SUCCESS: r += " direction=%s attrid=%s" % (self.direction, self.attrid) r += ">" return r class ConfigureReportingResponse(t.List(ConfigureReportingResponseRecord)): def serialize(self): failed = [record for record in self if record.status != Status.SUCCESS] if failed: return b"".join( [ConfigureReportingResponseRecord(i).serialize() for i in failed] ) return Status.SUCCESS.serialize() class ReadReportingConfigRecord(t.Struct): _fields = [("direction", t.uint8_t), ("attrid", t.uint16_t)] class DiscoverAttributesResponseRecord(t.Struct): _fields = [("attrid", t.uint16_t), ("datatype", t.uint8_t)] class AttributeAccessControl(t.bitmap8): READ = 0x01 WRITE = 0x02 REPORT = 0x04 class DiscoverAttributesExtendedResponseRecord(t.Struct): _fields = [ ("attrid", t.uint16_t), ("datatype", t.uint8_t), ("acl", AttributeAccessControl), ] class Command(t.enum8): """ZCL Foundation Global Command IDs.""" Read_Attributes = 0x00 Read_Attributes_rsp = 0x01 Write_Attributes = 0x02 Write_Attributes_Undivided = 0x03 Write_Attributes_rsp = 0x04 Write_Attributes_No_Response = 0x05 Configure_Reporting = 0x06 Configure_Reporting_rsp = 0x07 Read_Reporting_Configuration = 0x08 Read_Reporting_Configuration_rsp = 0x09 Report_Attributes = 0x0A Default_Response = 0x0B Discover_Attributes = 0x0C Discover_Attributes_rsp = 0x0D # Read_Attributes_Structured = 0x0e # Write_Attributes_Structured = 0x0f # Write_Attributes_Structured_rsp = 0x10 Discover_Commands_Received = 0x11 Discover_Commands_Received_rsp = 0x12 Discover_Commands_Generated = 0x13 Discover_Commands_Generated_rsp = 0x14 Discover_Attribute_Extended = 0x15 Discover_Attribute_Extended_rsp = 0x16 COMMANDS = { # id: (params, is_response) Command.Configure_Reporting: ((t.List(AttributeReportingConfig),), False), Command.Configure_Reporting_rsp: ((ConfigureReportingResponse,), True), Command.Default_Response: ((t.uint8_t, Status), True), Command.Discover_Attributes: ((t.uint16_t, t.uint8_t), False), Command.Discover_Attributes_rsp: ( (t.Bool, t.List(DiscoverAttributesResponseRecord)), True, ), Command.Discover_Attribute_Extended: ((t.uint16_t, t.uint8_t), False), Command.Discover_Attribute_Extended_rsp: ( (t.Bool, t.List(DiscoverAttributesExtendedResponseRecord)), True, ), Command.Discover_Commands_Generated: ((t.uint8_t, t.uint8_t), False), Command.Discover_Commands_Generated_rsp: ((t.Bool, t.List(t.uint8_t)), True), Command.Discover_Commands_Received: ((t.uint8_t, t.uint8_t), False), Command.Discover_Commands_Received_rsp: ((t.Bool, t.List(t.uint8_t)), True), Command.Read_Attributes: ((t.List(t.uint16_t),), False), Command.Read_Attributes_rsp: ((t.List(ReadAttributeRecord),), True), # Command.Read_Attributes_Structured: ((, ), False), Command.Read_Reporting_Configuration: ((t.List(ReadReportingConfigRecord),), False), Command.Read_Reporting_Configuration_rsp: ( (t.List(AttributeReportingConfig),), True, ), Command.Report_Attributes: ((t.List(Attribute),), False), Command.Write_Attributes: ((t.List(Attribute),), False), Command.Write_Attributes_No_Response: ((t.List(Attribute),), False), Command.Write_Attributes_rsp: ((WriteAttributesResponse,), True), # Command.Write_Attributes_Structured: ((, ), False), # Command.Write_Attributes_Structured_rsp: ((, ), True), Command.Write_Attributes_Undivided: ((t.List(Attribute),), False), } class FrameType(t.enum8): """ZCL Frame Type.""" GLOBAL_COMMAND = 0b00 CLUSTER_COMMAND = 0b01 RESERVED_2 = 0b10 RESERVED_3 = 0b11 class FrameControl: """The frame control field contains information defining the command type and other control flags.""" def __init__(self, frame_control: int = 0x00) -> None: self.value = frame_control @property def disable_default_response(self) -> bool: """Return True if default response is disabled.""" return bool(self.value & 0b10000) @disable_default_response.setter def disable_default_response(self, value: bool) -> None: """Disable the default response.""" if value: self.value |= 0b10000 return self.value &= 0b11101111 @property def frame_type(self) -> FrameType: """Return frame type.""" return FrameType(self.value & 0b00000011) @frame_type.setter def frame_type(self, value: FrameType) -> None: """Sets frame type to Global general command.""" self.value &= 0b11111100 self.value |= value @property def is_cluster(self) -> bool: """Return True if command is a local cluster specific command.""" return bool(self.frame_type == FrameType.CLUSTER_COMMAND) @property def is_general(self) -> bool: """Return True if command is a global ZCL command.""" return bool(self.frame_type == FrameType.GLOBAL_COMMAND) @property def is_manufacturer_specific(self) -> bool: """Return True if manufacturer code is present.""" return bool(self.value & 0b100) @is_manufacturer_specific.setter def is_manufacturer_specific(self, value: bool) -> None: """Sets manufacturer specific code.""" if value: self.value |= 0b100 return self.value &= 0b11111011 @property def is_reply(self) -> bool: """Return True if is a reply (server cluster -> client cluster.""" return bool(self.value & 0b1000) # in ZCL specs the above is the "direction" field direction = is_reply @is_reply.setter def is_reply(self, value: bool) -> None: """Sets the direction.""" if value: self.value |= 0b1000 return self.value &= 0b11110111 def __repr__(self) -> str: """Representation.""" return ( "<{} frame_type={} manufacturer_specific={} is_reply={} " "disable_default_response={}>" ).format( self.__class__.__name__, self.frame_type.name, self.is_manufacturer_specific, self.is_reply, self.disable_default_response, ) def serialize(self) -> bytes: return t.uint8_t(self.value).serialize() @classmethod def cluster(cls, is_reply: bool = False): """New Local Cluster specific command frame control.""" r = cls(FrameType.CLUSTER_COMMAND) r.is_reply = is_reply if is_reply: r.disable_default_response = True return r @classmethod def deserialize(cls, data): frc, data = t.uint8_t.deserialize(data) return cls(frc), data @classmethod def general(cls, is_reply: bool = False): """New General ZCL command frame control.""" r = cls(FrameType.GLOBAL_COMMAND) r.is_reply = is_reply if is_reply: r.disable_default_response = True return r class ZCLHeader: """ZCL Header.""" def __init__( self, frame_control: FrameControl, tsn: Union[int, t.uint8_t] = 0, command_id: Union[Command, int, t.uint8_t] = 0, manufacturer: Optional[Union[int, t.uint16_t]] = None, ) -> None: """Initialize ZCL Frame instance.""" self._frc = frame_control if frame_control.is_general: self._cmd_id = Command(command_id) else: self._cmd_id = t.uint8_t(command_id) self._manufacturer = manufacturer if manufacturer is not None: self.frame_control.is_manufacturer_specific = True self._tsn = t.uint8_t(tsn) @property def frame_control(self) -> FrameControl: """Return frame control.""" return self._frc @property def command_id(self) -> Command: """Return command identifier.""" return self._cmd_id @command_id.setter def command_id(self, value: Command) -> None: """Setter for command identifier.""" if self.frame_control.is_general: self._cmd_id = Command(value) return self._cmd_id = t.uint8_t(value) @property def is_reply(self) -> bool: """Return direction of Frame Control.""" return self.frame_control.is_reply @property def manufacturer(self) -> Optional[t.uint16_t]: """Return manufacturer id.""" if self._manufacturer is None: return None return t.uint16_t(self._manufacturer) @manufacturer.setter def manufacturer(self, value: t.uint16_t) -> None: self.frame_control.is_manufacturer_specific = bool(value) self._manufacturer = value @property def tsn(self) -> t.uint8_t: """Return transaction seq number.""" return self._tsn @tsn.setter def tsn(self, value: t.uint8_t) -> None: """Setter for tsn.""" self._tsn = t.uint8_t(value) @classmethod def deserialize(cls, data): """Deserialize from bytes.""" frc, data = FrameControl.deserialize(data) r = cls(frc) if frc.is_manufacturer_specific: r.manufacturer, data = t.uint16_t.deserialize(data) r.tsn, data = t.uint8_t.deserialize(data) r.command_id, data = Command.deserialize(data) return r, data def serialize(self): """Serialize to bytes.""" d = self.frame_control.serialize() if self.frame_control.is_manufacturer_specific: d += self.manufacturer.serialize() d += self.tsn.serialize() d += self.command_id.serialize() return d @classmethod def general( cls, tsn: Union[int, t.uint8_t], command_id: Union[int, t.uint8_t], manufacturer: Optional[Union[int, t.uint16_t]] = None, is_reply: bool = False, ) -> "ZCLHeader": r = cls(FrameControl.general(is_reply), tsn, command_id, manufacturer) if manufacturer is not None: r.frame_control.is_manufacturer_specific = True return r @classmethod def cluster( cls, tsn: Union[int, t.uint8_t], command_id: Union[int, t.uint8_t], manufacturer: Optional[Union[int, t.uint16_t]] = None, is_reply: bool = False, ) -> "ZCLHeader": r = cls(FrameControl.cluster(is_reply), tsn, command_id, manufacturer) if manufacturer is not None: r.frame_control.is_manufacturer_specific = True return r def __repr__(self) -> str: """Representation.""" return "<{} frame_control={} manufacturer={} tsn={} command_id={}>".format( self.__class__.__name__, self.frame_control, self.manufacturer, self.tsn, str(self.command_id), )
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/foundation.py
foundation.py
import asyncio import enum import functools import logging from typing import Any, Coroutine, Dict, List, Optional, Tuple, Union from zigpy import util import zigpy.types as t from zigpy.zcl import foundation LOGGER = logging.getLogger(__name__) class Registry(type): def __init__(cls, name, bases, nmspc): # noqa: N805 super(Registry, cls).__init__(name, bases, nmspc) if hasattr(cls, "cluster_id"): cls.cluster_id = t.ClusterId(cls.cluster_id) if hasattr(cls, "attributes"): cls.attridx = {} for attrid, (attrname, datatype) in cls.attributes.items(): cls.attridx[attrname] = attrid if hasattr(cls, "server_commands"): cls._server_command_idx = {} for command_id, details in cls.server_commands.items(): command_name, schema, is_reply = details cls._server_command_idx[command_name] = command_id if hasattr(cls, "client_commands"): cls._client_command_idx = {} for command_id, details in cls.client_commands.items(): command_name, schema, is_reply = details cls._client_command_idx[command_name] = command_id if getattr(cls, "_skip_registry", False): return if hasattr(cls, "cluster_id"): cls._registry[cls.cluster_id] = cls if hasattr(cls, "cluster_id_range"): cls._registry_range[cls.cluster_id_range] = cls class ClusterType(enum.IntEnum): Server = 0 Client = 1 class Cluster(util.ListenableMixin, util.CatchingTaskMixin, metaclass=Registry): """A cluster on an endpoint""" _registry = {} _registry_range = {} _server_command_idx = {} _client_command_idx = {} def __init__(self, endpoint, is_server=True): self._endpoint = endpoint self._attr_cache = {} self._listeners = {} if is_server: self._type = ClusterType.Server else: self._type = ClusterType.Client @classmethod def from_id(cls, endpoint, cluster_id, is_server=True): if cluster_id in cls._registry: return cls._registry[cluster_id](endpoint, is_server) else: for cluster_id_range, cluster in cls._registry_range.items(): if cluster_id_range[0] <= cluster_id <= cluster_id_range[1]: c = cluster(endpoint, is_server) c.cluster_id = cluster_id return c LOGGER.warning("Unknown cluster %s", cluster_id) c = cls(endpoint, is_server) c.cluster_id = cluster_id return c def deserialize(self, data): hdr, data = foundation.ZCLHeader.deserialize(data) self.debug("ZCL deserialize: %s", hdr) if hdr.frame_control.frame_type == foundation.FrameType.CLUSTER_COMMAND: # Cluster command if hdr.is_reply: commands = self.client_commands else: commands = self.server_commands try: schema = commands[hdr.command_id][1] hdr.frame_control.is_reply = commands[hdr.command_id][2] except KeyError: self.warning("Unknown cluster-specific command %s", hdr.command_id) return hdr, data else: # General command try: schema = foundation.COMMANDS[hdr.command_id][0] hdr.frame_control.is_reply = foundation.COMMANDS[hdr.command_id][1] except KeyError: self.warning("Unknown foundation command %s", hdr.command_id) return hdr, data value, data = t.deserialize(data, schema) if data != b"": self.warning("Data remains after deserializing ZCL frame") return hdr, value @util.retryable_request def request( self, general: bool, command_id: Union[foundation.Command, int, t.uint8_t], schema: Tuple, *args, manufacturer: Optional[Union[int, t.uint16_t]] = None, expect_reply: bool = True, tsn: Optional[Union[int, t.uint8_t]] = None, ): optional = len([s for s in schema if hasattr(s, "optional") and s.optional]) if len(schema) < len(args) or len(args) < len(schema) - optional: self.error("Schema and args lengths do not match in request") error = asyncio.Future() error.set_exception( ValueError( "Wrong number of parameters for request, expected %d argument(s)" % len(schema) ) ) return error if tsn is None: tsn = self._endpoint.device.application.get_sequence() if general: hdr = foundation.ZCLHeader.general(tsn, command_id, manufacturer) else: hdr = foundation.ZCLHeader.cluster(tsn, command_id, manufacturer) hdr.manufacturer = manufacturer data = hdr.serialize() + t.serialize(args, schema) return self._endpoint.request( self.cluster_id, tsn, data, expect_reply=expect_reply, command_id=command_id ) def reply( self, general: bool, command_id: Union[foundation.Command, int, t.uint8_t], schema: Tuple, *args, manufacturer: Optional[Union[int, t.uint16_t]] = None, tsn: Optional[Union[int, t.uint8_t]] = None, ): if len(schema) != len(args) and foundation.Status not in schema: self.debug("Schema and args lengths do not match in reply") if tsn is None: tsn = self._endpoint.device.application.get_sequence() if general: hdr = foundation.ZCLHeader.general( tsn, command_id, manufacturer, is_reply=True ) else: hdr = foundation.ZCLHeader.cluster( tsn, command_id, manufacturer, is_reply=True ) hdr.manufacturer = manufacturer data = hdr.serialize() + t.serialize(args, schema) return self._endpoint.reply(self.cluster_id, tsn, data, command_id=command_id) def handle_message(self, hdr, args): self.debug("ZCL request 0x%04x: %s", hdr.command_id, args) if hdr.frame_control.is_cluster: self.handle_cluster_request(hdr.tsn, hdr.command_id, args) self.listener_event("cluster_command", hdr.tsn, hdr.command_id, args) return self.listener_event("general_command", hdr.tsn, hdr.command_id, args) self.handle_cluster_general_request(hdr.tsn, hdr.command_id, args) def handle_cluster_request(self, tsn, command_id, args): self.debug("No handler for cluster command %s", command_id) def handle_cluster_general_request(self, tsn, command_id, args): if command_id == foundation.Command.Report_Attributes: valuestr = ", ".join( [ "%s=%s" % (self.attributes.get(a.attrid, [a.attrid])[0], a.value.value) for a in args[0] ] ) self.debug("Attribute report received: %s", valuestr) for attr in args[0]: try: value = self.attributes[attr.attrid][1](attr.value.value) except KeyError: value = attr.value.value except ValueError: self.debug( "Couldn't normalize %a attribute with %s value", attr.attrid, attr.value.value, exc_info=True, ) value = attr.value.value self._update_attribute(attr.attrid, value) def read_attributes_raw(self, attributes, manufacturer=None): attributes = [t.uint16_t(a) for a in attributes] return self._read_attributes(attributes, manufacturer=manufacturer) async def read_attributes( self, attributes, allow_cache=False, only_cache=False, raw=False, manufacturer=None, ): if raw: assert len(attributes) == 1 success, failure = {}, {} attribute_ids = [] orig_attributes = {} for attribute in attributes: if isinstance(attribute, str): attrid = self.attridx[attribute] else: attrid = attribute attribute_ids.append(attrid) orig_attributes[attrid] = attribute to_read = [] if allow_cache or only_cache: for idx, attribute in enumerate(attribute_ids): if attribute in self._attr_cache: success[attributes[idx]] = self._attr_cache[attribute] else: to_read.append(attribute) else: to_read = attribute_ids if not to_read or only_cache: if raw: return success[attributes[0]] return success, failure result = await self.read_attributes_raw(to_read, manufacturer=manufacturer) if not isinstance(result[0], list): for attrid in to_read: orig_attribute = orig_attributes[attrid] failure[orig_attribute] = result[0] # Assume default response else: for record in result[0]: orig_attribute = orig_attributes[record.attrid] if record.status == foundation.Status.SUCCESS: try: value = self.attributes[record.attrid][1](record.value.value) except KeyError: value = record.value.value except ValueError: value = record.value.value self.debug( "Couldn't normalize %a attribute with %s value", record.attrid, value, exc_info=True, ) self._update_attribute(record.attrid, value) success[orig_attribute] = value else: failure[orig_attribute] = record.status if raw: # KeyError is an appropriate exception here, I think. return success[attributes[0]] return success, failure def read_attributes_rsp(self, attributes, manufacturer=None, *, tsn=None): args = [] for attrid, value in attributes.items(): if isinstance(attrid, str): attrid = self.attridx[attrid] a = foundation.ReadAttributeRecord( attrid, foundation.Status.UNSUPPORTED_ATTRIBUTE, foundation.TypeValue() ) args.append(a) if value is None: continue try: a.status = foundation.Status.SUCCESS python_type = self.attributes[attrid][1] a.value.type = foundation.DATA_TYPES.pytype_to_datatype_id(python_type) a.value.value = python_type(value) except ValueError as e: a.status = foundation.Status.UNSUPPORTED_ATTRIBUTE self.error(str(e)) return self._read_attributes_rsp(args, manufacturer=manufacturer, tsn=tsn) def _write_attr_records( self, attributes: Dict[Union[str, int], Any] ) -> List[foundation.Attribute]: args = [] for attrid, value in attributes.items(): if isinstance(attrid, str): attrid = self.attridx[attrid] if attrid not in self.attributes: self.error("%d is not a valid attribute id", attrid) continue a = foundation.Attribute(attrid, foundation.TypeValue()) try: python_type = self.attributes[attrid][1] a.value.type = foundation.DATA_TYPES.pytype_to_datatype_id(python_type) a.value.value = python_type(value) args.append(a) except ValueError as e: self.error(str(e)) return args async def write_attributes( self, attributes: Dict[Union[str, int], Any], manufacturer: Optional[int] = None ) -> List: args = self._write_attr_records(attributes) result = await self._write_attributes(args, manufacturer=manufacturer) if not isinstance(result[0], list): return result records = result[0] if len(records) == 1 and records[0].status == foundation.Status.SUCCESS: for attr_rec in args: self._attr_cache[attr_rec.attrid] = attr_rec.value.value else: failed = [rec.attrid for rec in records] for attr_rec in args: if attr_rec.attrid not in failed: self._attr_cache[attr_rec.attrid] = attr_rec.value.value return result def write_attributes_undivided( self, attributes: Dict[Union[str, int], Any], manufacturer: Optional[int] = None ) -> List: """Either all or none of the attributes are written by the device.""" args = self._write_attr_records(attributes) return self._write_attributes_undivided(args, manufacturer=manufacturer) def bind(self): return self._endpoint.device.zdo.bind(cluster=self) def unbind(self): return self._endpoint.device.zdo.unbind(cluster=self) def _attr_reporting_rec( self, attribute: Union[int, str], min_interval: int, max_interval: int, reportable_change: int = 1, direction: int = 0x00, ) -> foundation.ConfigureReportingResponseRecord: if isinstance(attribute, str): attrid = self.attridx.get(attribute) else: attrid = attribute if attrid is None or attrid not in self.attributes: raise ValueError(f"Unknown {attribute} name of {self.ep_attribute} cluster") cfg = foundation.AttributeReportingConfig() cfg.direction = direction cfg.attrid = attrid cfg.datatype = foundation.DATA_TYPES.pytype_to_datatype_id( self.attributes.get(attrid, (None, foundation.Unknown))[1] ) cfg.min_interval = min_interval cfg.max_interval = max_interval cfg.reportable_change = reportable_change return cfg def configure_reporting( self, attribute: Union[int, str], min_interval: int, max_interval: int, reportable_change: int, manufacturer: Optional[int] = None, ) -> Coroutine: cfg = self._attr_reporting_rec( attribute, min_interval, max_interval, reportable_change ) return self._configure_reporting([cfg], manufacturer=manufacturer) def configure_reporting_multiple( self, attributes: Dict[Union[int, str], Tuple[int, int, int]], manufacturer: Optional[int] = None, ) -> Coroutine: """Configure attribute reporting for multiple attributes in the same request. :param attributes: dict of attributes to configure attribute reporting. Key is either int or str for attribute id or attribute name. Value is a Tuple of: - minimum reporting interval - maximum reporting interval - reportable change :param manufacturer: optional manufacturer id to use with the command """ cfg = [ self._attr_reporting_rec(attr, rep[0], rep[1], rep[2]) for attr, rep in attributes.items() ] return self._configure_reporting(cfg, manufacturer=manufacturer) def command( self, command_id: Union[foundation.Command, int, t.uint8_t], *args, manufacturer: Optional[Union[int, t.uint16_t]] = None, expect_reply: bool = True, tsn: Optional[Union[int, t.uint8_t]] = None, ): schema = self.server_commands[command_id][1] return self.request( False, command_id, schema, *args, manufacturer=manufacturer, expect_reply=expect_reply, tsn=tsn, ) def client_command( self, command_id: Union[foundation.Command, int, t.uint8_t], *args, tsn: Optional[Union[int, t.uint8_t]] = None, ): schema = self.client_commands[command_id][1] return self.reply(False, command_id, schema, *args, tsn=tsn) @property def is_client(self) -> bool: """Return True if this is a client cluster.""" return self._type == ClusterType.Client @property def is_server(self) -> bool: """Return True if this is a server cluster.""" return self._type == ClusterType.Server @property def name(self): return self.__class__.__name__ @property def endpoint(self): return self._endpoint @property def commands(self): return list(self._server_command_idx.keys()) def _update_attribute(self, attrid, value): self._attr_cache[attrid] = value self.listener_event("attribute_updated", attrid, value) def log(self, lvl, msg, *args, **kwargs): msg = "[0x%04x:%s:0x%04x] " + msg args = ( self._endpoint.device.nwk, self._endpoint.endpoint_id, self.cluster_id, ) + args return LOGGER.log(lvl, msg, *args, **kwargs) def __getattr__(self, name): if name in self._client_command_idx: return functools.partial( self.client_command, self._client_command_idx[name] ) elif name in self._server_command_idx: return functools.partial(self.command, self._server_command_idx[name]) else: raise AttributeError("No such command name: %s" % (name,)) def __getitem__(self, key): return self.read_attributes([key], allow_cache=True, raw=True) def general_command( self, command_id: Union[foundation.Command, int, t.uint8_t], *args, manufacturer: Optional[Union[int, t.uint16_t]] = None, expect_reply: bool = True, tries: int = 1, tsn: Optional[Union[int, t.uint8_t]] = None, ): schema = foundation.COMMANDS[command_id][0] if foundation.COMMANDS[command_id][1]: # should reply be retryable? return self.reply( True, command_id, schema, *args, manufacturer=manufacturer, tsn=tsn ) return self.request( True, command_id, schema, *args, manufacturer=manufacturer, expect_reply=expect_reply, tries=tries, tsn=tsn, ) _configure_reporting = functools.partialmethod( general_command, foundation.Command.Configure_Reporting ) _read_attributes = functools.partialmethod( general_command, foundation.Command.Read_Attributes ) _read_attributes_rsp = functools.partialmethod( general_command, foundation.Command.Read_Attributes_rsp ) _write_attributes = functools.partialmethod( general_command, foundation.Command.Write_Attributes ) _write_attributes_undivided = functools.partialmethod( general_command, foundation.Command.Write_Attributes_Undivided ) discover_attributes = functools.partialmethod( general_command, foundation.Command.Discover_Attributes ) discover_attributes_extended = functools.partialmethod( general_command, foundation.Command.Discover_Attribute_Extended ) discover_commands_received = functools.partialmethod( general_command, foundation.Command.Discover_Commands_Received ) discover_commands_generated = functools.partialmethod( general_command, foundation.Command.Discover_Commands_Generated ) class ClusterPersistingListener: def __init__(self, applistener, cluster): self._applistener = applistener self._cluster = cluster def attribute_updated(self, attrid, value): self._applistener.attribute_updated(self._cluster, attrid, value) def cluster_command(self, *args, **kwargs): pass def general_command(self, *args, **kwargs): pass # Import to populate the registry from . import clusters # noqa: F401, F402, isort:skip
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/__init__.py
__init__.py
from typing import Tuple import zigpy.types as t from zigpy.zcl import Cluster class IasZone(Cluster): """The IAS Zone cluster defines an interface to the functionality of an IAS security zone device. IAS Zone supports up to two alarm types per zone, low battery reports and supervision of the IAS network.""" class ZoneState(t.enum8): Not_enrolled = 0x00 Enrolled = 0x01 class ZoneType(t.enum_factory(t.uint16_t, "manufacturer_specific")): """Zone type enum.""" Standard_CIE = 0x0000 Motion_Sensor = 0x000D Contact_Switch = 0x0015 Fire_Sensor = 0x0028 Water_Sensor = 0x002A Carbon_Monoxide_Sensor = 0x002B Personal_Emergency_Device = 0x002C Vibration_Movement_Sensor = 0x002D Remote_Control = 0x010F Key_Fob = 0x0115 Key_Pad = 0x021D Standard_Warning_Device = 0x0225 Glass_Break_Sensor = 0x0226 Security_Repeater = 0x0229 Invalid_Zone_Type = 0xFFFF class ZoneStatus(t.bitmap16): """ZoneStatus attribute.""" Alarm_1 = 0x0001 Alarm_2 = 0x0002 Tamper = 0x0004 Battery = 0x0008 Supervision_reports = 0x0010 Restore_reports = 0x0020 Trouble = 0x0040 AC_mains = 0x0080 Test = 0x0100 Battery_Defect = 0x0200 class EnrollResponse(t.enum8): """Enroll response code.""" Success = 0x00 Not_supported = 0x01 No_enroll_permit = 0x02 Too_many_zones = 0x03 cluster_id = 0x0500 name = "IAS Zone" ep_attribute = "ias_zone" attributes = { # Zone Information 0x0000: ("zone_state", ZoneState), 0x0001: ("zone_type", ZoneType), 0x0002: ("zone_status", ZoneStatus), # Zone Settings 0x0010: ("cie_addr", t.EUI64), 0x0011: ("zone_id", t.uint8_t), 0x0012: ("num_zone_sensitivity_levels_supported", t.uint8_t), 0x0013: ("current_zone_sensitivity_level", t.uint8_t), } server_commands = { 0x0000: ("enroll_response", (EnrollResponse, t.uint8_t), True), 0x0001: ("init_normal_op_mode", (), False), 0x0002: ("init_test_mode", (t.uint8_t, t.uint8_t), False), } client_commands = { 0x0000: ( "status_change_notification", (ZoneStatus, t.bitmap8, t.uint8_t, t.uint16_t), False, ), 0x0001: ("enroll", (ZoneType, t.uint16_t), False), } class IasAce(Cluster): class AlarmStatus(t.enum8): """IAS ACE alarm status enum.""" No_Alarm = 0x00 Burglar = 0x01 Fire = 0x02 Emergency = 0x03 Police_Panic = 0x04 Fire_Panic = 0x05 Emergency_Panic = 0x06 class ArmMode(t.enum8): """IAS ACE arm mode enum.""" Disarm = 0x00 Arm_Day_Home_Only = 0x01 Arm_Night_Sleep_Only = 0x02 Arm_All_Zones = 0x03 class ArmNotification(t.enum8): """IAS ACE arm notification enum.""" All_Zones_Disarmed = 0x00 Only_Day_Home_Zones_Armed = 0x01 Only_Night_Sleep_Zones_Armed = 0x02 All_Zones_Armed = 0x03 Invalid_Arm_Disarm_Code = 0x04 Not_Ready_To_Arm = 0x05 Already_Disarmed = 0x06 class AudibleNotification(t.enum_factory(t.uint8_t, "manufacturer_specific")): """IAS ACE audible notification enum.""" Mute = 0x00 Default_Sound = 0x01 class BypassResponse(t.enum8): """Bypass result.""" Zone_bypassed = 0x00 Zone_not_bypassed = 0x01 Not_allowed = 0x02 Invalid_Zone_ID = 0x03 Unknown_Zone_ID = 0x04 Invalid_Code = 0x05 class PanelStatus(t.enum8): """IAS ACE panel status enum.""" Panel_Disarmed = 0x00 Armed_Stay = 0x01 Armed_Night = 0x02 Armed_Away = 0x03 Exit_Delay = 0x04 Entry_Delay = 0x05 Not_Ready_To_Arm = 0x06 In_Alarm = 0x07 Arming_Stay = 0x08 Arming_Night = 0x09 Arming_Away = 0x0A ZoneType = IasZone.ZoneType ZoneStatus = IasZone.ZoneStatus class ZoneStatusRsp(t.Struct): """Zone status response.""" _fields = [("zone_id", t.uint8_t), ("zone_status", IasZone.ZoneStatus)] cluster_id = 0x0501 name = "IAS Ancillary Control Equipment" ep_attribute = "ias_ace" attributes = {} server_commands = { 0x0000: ("arm", (ArmMode, t.CharacterString, t.uint8_t), False), 0x0001: ("bypass", (t.LVList(t.uint8_t), t.CharacterString), False), 0x0002: ("emergency", (), False), 0x0003: ("fire", (), False), 0x0004: ("panic", (), False), 0x0005: ("get_zone_id_map", (), False), 0x0006: ("get_zone_info", (t.uint8_t,), False), 0x0007: ("get_panel_status", (), False), 0x0008: ("get_bypassed_zone_list", (), False), 0x0009: ("get_zone_status", (t.uint8_t, t.uint8_t, t.Bool, ZoneStatus), False), } client_commands = { 0x0000: ("arm_response", (ArmNotification,), True), 0x0001: ("get_zone_id_map_response", (t.List(t.bitmap16),), True), 0x0002: ( "get_zone_info_response", (t.uint8_t, ZoneType, t.EUI64, t.CharacterString), True, ), 0x0003: ( "zone_status_changed", (t.uint8_t, ZoneStatus, AudibleNotification, t.CharacterString), False, ), 0x0004: ( "panel_status_changed", (PanelStatus, t.uint8_t, AudibleNotification, AlarmStatus), False, ), 0x0005: ( "panel_status_response", (PanelStatus, t.uint8_t, AudibleNotification, AlarmStatus), True, ), 0x0006: ("set_bypassed_zone_list", (t.LVList(t.uint8_t),), False), 0x0007: ("bypass_response", (t.LVList(BypassResponse),), True), 0x0008: ("get_zone_status_response", (t.Bool, t.LVList(ZoneStatusRsp)), True), } class Strobe(t.enum8): No_strobe = 0x00 Strobe = 0x01 class _SquawkOrWarningCommand: def __init__(self, value: int = 0) -> None: self.value = t.uint8_t(value) @classmethod def deserialize(cls, data: bytes) -> Tuple["_SquawkOrWarningCommand", bytes]: val, data = t.uint8_t.deserialize(data) return cls(val), data def serialize(self) -> bytes: return t.uint8_t(self.value).serialize() def __repr__(self) -> str: return ( f"<{self.__class__.__name__}.mode={self.mode.name} " f"strobe={self.strobe.name} level={self.level.name}: " f"{self.value}>" ) def __eq__(self, other): """Compare to int.""" return self.value == other class IasWd(Cluster): """The IAS WD cluster provides an interface to the functionality of any Warning Device equipment of the IAS system. Using this cluster, a ZigBee enabled CIE device can access a ZigBee enabled IAS WD device and issue alarm warning indications (siren, strobe lighting, etc.) when a system alarm condition is detected """ class StrobeLevel(t.enum8): Low_level_strobe = 0x00 Medium_level_strobe = 0x01 High_level_strobe = 0x02 Very_high_level_strobe = 0x03 class Warning(_SquawkOrWarningCommand): Strobe = Strobe class SirenLevel(t.enum8): Low_level_sound = 0x00 Medium_level_sound = 0x01 High_level_sound = 0x02 Very_high_level_sound = 0x03 class WarningMode(t.enum8): Stop = 0x00 Burglar = 0x01 Fire = 0x02 Emergency = 0x03 Police_Panic = 0x04 Fire_Panic = 0x05 Emergency_Panic = 0x06 @property def mode(self) -> "WarningMode": return self.WarningMode((self.value >> 4) & 0x0F) @mode.setter def mode(self, mode: WarningMode) -> None: self.value = (self.value & 0xF) | (mode << 4) @property def strobe(self) -> "Strobe": return self.Strobe((self.value >> 2) & 0x01) @strobe.setter def strobe(self, strobe: "Strobe") -> None: self.value = (self.value & 0xF7) | ((strobe & 0x01) << 2) @property def level(self) -> "SirenLevel": return self.SirenLevel(self.value & 0x03) @level.setter def level(self, level: SirenLevel) -> None: self.value = (self.value & 0xFC) | (level & 0x03) class Squawk(_SquawkOrWarningCommand): Strobe = Strobe class SquawkLevel(t.enum8): Low_level_sound = 0x00 Medium_level_sound = 0x01 High_level_sound = 0x02 Very_high_level_sound = 0x03 class SquawkMode(t.enum8): Armed = 0x00 Disarmed = 0x01 @property def mode(self) -> "SquawkMode": return self.SquawkMode((self.value >> 4) & 0x0F) @mode.setter def mode(self, mode: SquawkMode) -> None: self.value = (self.value & 0xF) | ((mode & 0x0F) << 4) @property def strobe(self) -> "Strobe": return self.Strobe((self.value >> 3) & 0x01) @strobe.setter def strobe(self, strobe: Strobe) -> None: self.value = (self.value & 0xF7) | (strobe << 3) @property def level(self) -> "SquawkLevel": return self.SquawkLevel(self.value & 0x03) @level.setter def level(self, level: SquawkLevel) -> None: self.value = (self.value & 0xFC) | (level & 0x03) cluster_id = 0x0502 name = "IAS Warning Device" ep_attribute = "ias_wd" attributes = {0x0000: ("max_duration", t.uint16_t)} server_commands = { 0x0000: ("start_warning", (Warning, t.uint16_t, t.uint8_t, StrobeLevel), False), 0x0001: ("squawk", (Squawk,), False), } client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/security.py
security.py
import zigpy.types as t from zigpy.zcl import Cluster class Pump(Cluster): """An interface for configuring and controlling pumps.""" class AlarmMask(t.bitmap16): Supply_voltage_too_low = 0x0001 Supply_voltage_too_high = 0x0002 Power_missing_phase = 0x0004 System_pressure_too_low = 0x0008 System_pressure_too_high = 0x0010 Dry_running = 0x0020 Motor_temperature_too_high = 0x0040 Pump_motor_has_fatal_failure = 0x0080 Electronic_temperature_too_high = 0x0100 Pump_blocked = 0x0200 Sensor_failure = 0x0400 Electronic_non_fatal_failure = 0x0800 Electronic_fatal_failure = 0x1000 General_fault = 0x2000 class ControlMode(t.enum8): Constant_speed = 0x00 Constant_pressure = 0x01 Proportional_pressure = 0x02 Constant_flow = 0x03 Constant_temperature = 0x05 Automatic = 0x07 class OperationMode(t.enum8): Normal = 0x00 Minimum = 0x01 Maximum = 0x02 Local = 0x03 class PumpStatus(t.bitmap16): Device_fault = 0x0001 Supply_fault = 0x0002 Speed_low = 0x0004 Speed_high = 0x0008 Local_override = 0x0010 Running = 0x0020 Remote_Pressure = 0x0040 Remote_Flow = 0x0080 Remote_Temperature = 0x0100 cluster_id = 0x0200 name = "Pump Configuration and Control" ep_attribute = "pump" attributes = { # Pump Information 0x0000: ("max_pressure", t.int16s), 0x0001: ("max_speed", t.uint16_t), 0x0002: ("max_flow", t.uint16_t), 0x0003: ("min_const_pressure", t.int16s), 0x0004: ("max_const_pressure", t.int16s), 0x0005: ("min_comp_pressure", t.int16s), 0x0006: ("max_comp_pressure", t.int16s), 0x0007: ("min_const_speed", t.uint16_t), 0x0008: ("max_const_speed", t.uint16_t), 0x0009: ("min_const_flow", t.uint16_t), 0x000A: ("max_const_flow", t.uint16_t), 0x000B: ("min_const_temp", t.int16s), 0x000C: ("max_const_temp", t.int16s), # Pump Dynamic Information 0x0010: ("pump_status", PumpStatus), 0x0011: ("effective_operation_mode", OperationMode), 0x0012: ("effective_control_mode", ControlMode), 0x0013: ("capacity", t.int16s), 0x0014: ("speed", t.uint16_t), 0x0015: ("lifetime_running_hours", t.uint24_t), 0x0016: ("power", t.uint24_t), 0x0017: ("lifetime_energy_consumed", t.uint32_t), # Pump Settings 0x0020: ("operation_mode", OperationMode), 0x0021: ("control_mode", ControlMode), 0x0022: ("alarm_mask", AlarmMask), } server_commands = {} client_commands = {} class CoolingSystemStage(t.enum8): Cool_Stage_1 = 0x00 Cool_Stage_2 = 0x01 Cool_Stage_3 = 0x02 Reserved = 0x03 class HeatingSystemStage(t.enum8): Heat_Stage_1 = 0x00 Heat_Stage_2 = 0x01 Heat_Stage_3 = 0x02 Reserved = 0x03 class HeatingSystemType(t.enum8): Conventional = 0x00 Heat_Pump = 0x01 class HeatingFuelSource(t.enum8): Electric = 0x00 Gas = 0x01 class Thermostat(Cluster): """An interface for configuring and controlling the functionality of a thermostat.""" class ACCapacityFormat(t.enum8): BTUh = 0x00 class ACCompressorType(t.enum8): Reserved = 0x00 T1_max_working_43C = 0x01 T2_max_working_35C = 0x02 T3_max_working_52C = 0x03 class ACType(t.enum8): Reserved = 0x00 Cooling_fixed_speed = 0x01 Heat_Pump_fixed_speed = 0x02 Cooling_Inverter = 0x03 Heat_Pump_Inverter = 0x04 class ACRefrigerantType(t.enum8): Reserved = 0x00 R22 = 0x01 R410a = 0x02 R407c = 0x03 class ACErrorCode(t.bitmap32): No_Errors = 0x00000000 Commpressor_Failure = 0x00000001 Room_Temperature_Sensor_Failure = 0x00000002 Outdoor_Temperature_Sensor_Failure = 0x00000004 Indoor_Coil_Temperature_Sensor_Failure = 0x00000008 Fan_Failure = 0x00000010 class ACLouverPosition(t.enum8): Closed = 0x01 Open = 0x02 Qurter_Open = 0x03 Half_Open = 0x04 Three_Quarters_Open = 0x05 class AlarmMask(t.bitmap8): No_Alarms = 0x00 Initialization_failure = 0x01 Hardware_failure = 0x02 Self_calibration_failure = 0x04 class ControlSequenceOfOperation(t.enum8): Cooling_Only = 0x00 Cooling_With_Reheat = 0x01 Heating_Only = 0x02 Heating_With_Reheat = 0x03 Cooling_and_Heating = 0x04 Cooling_and_Heating_with_Reheat = 0x08 class SeqDayOfWeek(t.bitmap8): Sunday = 0x01 Monday = 0x02 Tuesday = 0x04 Wednesday = 0x08 Thursday = 0x10 Friday = 0x20 Saturday = 0x40 Away = 0x80 class SeqMode(t.bitmap8): Heat = 0x01 Cool = 0x02 class Occupancy(t.bitmap8): Unoccupied = 0x00 Occupied = 0x01 class ProgrammingOperationMode(t.bitmap8): Simple = 0x00 Schedule_programming_mode = 0x01 Auto_recovery_mode = 0x02 Economy_mode = 0x04 class RemoteSensing(t.bitmap8): all_local = 0x00 local_temperature_sensed_remotely = 0x01 outdoor_temperature_sensed_remotely = 0x02 occupancy_sensed_remotely = 0x04 class SetpointChangeSource(t.enum8): Manual = 0x00 Schedule = 0x01 External = 0x02 class SetpointMode(t.enum8): Heat = 0x00 Cool = 0x01 Both = 0x02 class StartOfWeek(t.enum8): Sunday = 0x00 Monday = 0x01 Tuesday = 0x02 Wednesday = 0x03 Thursday = 0x04 Friday = 0x05 Saturday = 0x06 class SystemMode(t.enum8): Off = 0x00 Auto = 0x01 Cool = 0x03 Heat = 0x04 Emergency_Heating = 0x05 Pre_cooling = 0x06 Fan_only = 0x07 Dry = 0x08 Sleep = 0x09 class SystemType(t.bitmap8): Heat_and_or_Cool_Stage_1 = 0x00 Cool_Stage_1 = 0x01 Cool_Stage_2 = 0x02 Heat_Stage_1 = 0x04 Heat_Stage_2 = 0x08 Heat_Pump = 0x10 Gas = 0x20 @property def cooling_system_stage(self) -> CoolingSystemStage: return CoolingSystemStage(self & 0x03) @property def heating_system_stage(self) -> HeatingSystemStage: return HeatingSystemStage((self >> 2) & 0x03) @property def heating_system_type(self) -> HeatingSystemType: return HeatingSystemType((self >> 4) & 0x01) @property def heating_fuel_source(self) -> HeatingFuelSource: return HeatingFuelSource((self >> 5) & 0x01) class TemperatureSetpointHold(t.enum8): Setpoint_Hold_Off = 0x00 Setpoint_Hold_On = 0x01 class RunningMode(t.enum8): Off = 0x00 Cool = 0x03 Heat = 0x04 class RunningState(t.bitmap16): Idle = 0x0000 Heat_State_On = 0x0001 Cool_State_On = 0x0002 Fan_State_On = 0x0004 Heat_2nd_Stage_On = 0x0008 Cool_2nd_Stage_On = 0x0010 Fan_2nd_Stage_On = 0x0020 Fan_3rd_Stage_On = 0x0040 cluster_id = 0x0201 ep_attribute = "thermostat" attributes = { # Thermostat Information 0x0000: ("local_temp", t.int16s), 0x0001: ("outdoor_temp", t.int16s), 0x0002: ("occupancy", Occupancy), 0x0003: ("abs_min_heat_setpoint_limit", t.int16s), 0x0004: ("abs_max_heat_setpoint_limit", t.int16s), 0x0005: ("abs_min_cool_setpoint_limit", t.int16s), 0x0006: ("abs_max_cool_setpoint_limit", t.int16s), 0x0007: ("pi_cooling_demand", t.uint8_t), 0x0008: ("pi_heating_demand", t.uint8_t), 0x0009: ("system_type_config", SystemType), # Thermostat Settings 0x0010: ("local_temperature_calibration", t.int8s), 0x0011: ("occupied_cooling_setpoint", t.int16s), 0x0012: ("occupied_heating_setpoint", t.int16s), 0x0013: ("unoccupied_cooling_setpoint", t.int16s), 0x0014: ("unoccupied_heating_setpoint", t.int16s), 0x0015: ("min_heat_setpoint_limit", t.int16s), 0x0016: ("max_heat_setpoint_limit", t.int16s), 0x0017: ("min_cool_setpoint_limit", t.int16s), 0x0018: ("max_cool_setpoint_limit", t.int16s), 0x0019: ("min_setpoint_dead_band", t.int8s), 0x001A: ("remote_sensing", RemoteSensing), 0x001B: ("ctrl_seqe_of_oper", ControlSequenceOfOperation), 0x001C: ("system_mode", SystemMode), 0x001D: ("alarm_mask", AlarmMask), 0x001E: ("running_mode", RunningMode), # ... 0x0020: ("start_of_week", StartOfWeek), 0x0021: ("number_of_weekly_trans", t.uint8_t), 0x0022: ("number_of_daily_trans", t.uint8_t), 0x0023: ("temp_setpoint_hold", TemperatureSetpointHold), 0x0024: ("temp_setpoint_hold_duration", t.uint16_t), 0x0025: ("programing_oper_mode", ProgrammingOperationMode), 0x0029: ("running_state", RunningState), 0x0030: ("setpoint_change_source", SetpointChangeSource), 0x0031: ("setpoint_change_amount", t.int16s), 0x0032: ("setpoint_change_source_time_stamp", t.uint32_t), 0x0040: ("ac_type", ACType), 0x0041: ("ac_capacity", t.uint16_t), 0x0042: ("ac_refrigerant_type", ACRefrigerantType), 0x0043: ("ac_compressor_type", ACCompressorType), 0x0044: ("ac_error_code", ACErrorCode), 0x0045: ("ac_louver_position", ACLouverPosition), 0x0046: ("ac_coll_temp", t.int16s), 0x0047: ("ac_capacity_format", ACCapacityFormat), } server_commands = { 0x0000: ("setpoint_raise_lower", (SetpointMode, t.int8s), False), 0x0001: ( "set_weekly_schedule", (t.enum8, SeqDayOfWeek, SeqMode, t.List(t.int16s)), False, ), 0x0002: ("get_weekly_schedule", (SeqDayOfWeek, SeqMode), False), 0x0003: ("clear_weekly_schedule", (), False), 0x0004: ("get_relay_status_log", (), False), } client_commands = { 0x0000: ( "get_weekly_schedule_response", (t.enum8, SeqDayOfWeek, SeqMode, t.List(t.int16s)), True, ), 0x0001: ( "get_relay_status_log_response", (t.uint16_t, t.bitmap8, t.int16s, t.uint8_t, t.int16s, t.uint16_t), True, ), } class Fan(Cluster): """ An interface for controlling a fan in a heating / cooling system.""" class FanMode(t.enum8): Off = 0x00 Low = 0x01 Medium = 0x02 High = 0x03 On = 0x04 Auto = 0x05 Smart = 0x06 class FanModeSequence(t.enum8): Low_Med_High = 0x00 Low_High = 0x01 Low_Med_High_Auto = 0x02 Low_High_Auto = 0x03 On_Auto = 0x04 cluster_id = 0x0202 name = "Fan Control" ep_attribute = "fan" attributes = { # Fan Control Status 0x0000: ("fan_mode", FanMode), 0x0001: ("fan_mode_sequence", FanModeSequence), } server_commands = {} client_commands = {} class Dehumidification(Cluster): """An interface for controlling dehumidification.""" class RelativeHumidityMode(t.enum8): RH_measured_locally = 0x00 RH_measured_remotely = 0x01 class DehumidificationLockout(t.enum8): Dehumidification_not_allowed = 0x00 Dehumidification_is_allowed = 0x01 class RelativeHumidityDisplay(t.enum8): RH_not_displayed = 0x00 RH_is_displayed = 0x01 cluster_id = 0x0203 ep_attribute = "dehumidification" attributes = { # Dehumidification Information 0x0000: ("relative_humidity", t.uint8_t), 0x0001: ("dehumid_cooling", t.uint8_t), # Dehumidification Settings 0x0010: ("rh_dehumid_setpoint", t.uint8_t), 0x0011: ("relative_humidity_mode", RelativeHumidityMode), 0x0012: ("dehumid_lockout", DehumidificationLockout), 0x0013: ("dehumid_hysteresis", t.uint8_t), 0x0014: ("dehumid_max_cool", t.uint8_t), 0x0015: ("relative_humid_display", RelativeHumidityDisplay), } server_commands = {} client_commands = {} class UserInterface(Cluster): """An interface for configuring the user interface of a thermostat (which may be remote from the thermostat).""" class TemperatureDisplayMode(t.enum8): Metric = 0x00 Imperial = 0x01 class KeypadLockout(t.enum8): No_lockout = 0x00 Level_1_lockout = 0x01 Level_2_lockout = 0x02 Level_3_lockout = 0x03 Level_4_lockout = 0x04 Level_5_lockout = 0x05 class ScheduleProgrammingVisibility(t.enum8): Enabled = 0x00 Disabled = 0x02 cluster_id = 0x0204 name = "Thermostat User Interface Configuration" ep_attribute = "thermostat_ui" attributes = { 0x0000: ("temp_display_mode", TemperatureDisplayMode), 0x0001: ("keypad_lockout", KeypadLockout), 0x0002: ("programming_visibility", ScheduleProgrammingVisibility), } server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/hvac.py
hvac.py
import zigpy.types as t from zigpy.zcl import Cluster, foundation class Shade(Cluster): """Attributes and commands for configuring a shade""" cluster_id = 0x0100 name = "Shade Configuration" ep_attribute = "shade" attributes = { # Shade Information 0x0000: ("physical_closed_limit", t.uint16_t), 0x0001: ("motor_step_size", t.uint8_t), 0x0002: ("status", t.bitmap8), # Shade Settings 0x0010: ("closed_limit", t.uint16_t), 0x0012: ("mode", t.enum8), } server_commands = {} client_commands = {} class DoorLock(Cluster): """The door lock cluster provides an interface to a generic way to secure a door.""" class LockState(t.enum8): Not_fully_locked = 0x00 Locked = 0x01 Unlocked = 0x02 Undefined = 0xFF class LockType(t.enum8): Dead_bolt = 0x00 Magnetic = 0x01 Other = 0x02 Mortise = 0x03 Rim = 0x04 Latch_bolt = 0x05 Cylindrical_lock = 0x06 Tubular_lock = 0x07 Interconnected_lock = 0x08 Dead_latch = 0x09 Door_furniture = 0x0A class DoorState(t.enum8): Open = 0x00 Closed = 0x01 Error_jammed = 0x02 Error_forced_open = 0x03 Error_unspecified = 0x04 Undefined = 0xFF class OperatingMode(t.enum8): Normal = 0x00 Vacation = 0x01 Privacy = 0x02 No_RF_Lock_Unlock = 0x03 Passage = 0x04 class SupportedOperatingModes(t.bitmap16): Normal = 0x0001 Vacation = 0x0002 Privacy = 0x0004 No_RF = 0x0008 Passage = 0x0010 class DefaultConfigurationRegister(t.bitmap16): Enable_Local_Programming = 0x0001 Keypad_Interface_default_access = 0x0002 RF_Interface_default_access = 0x0004 Sound_Volume_non_zero = 0x0020 Auto_Relock_time_non_zero = 0x0040 Led_settings_non_zero = 0x0080 class ZigbeeSecurityLevel(t.enum8): Network_Security = 0x00 APS_Security = 0x01 class AlarmMask(t.bitmap16): Deadbolt_Jammed = 0x0001 Lock_Reset_to_Factory_Defaults = 0x0002 Reserved = 0x0004 RF_Module_Power_Cycled = 0x0008 Tamper_Alarm_wrong_code_entry_limit = 0x0010 Tamper_Alarm_front_escutcheon_removed = 0x0020 Forced_Door_Open_under_Door_Lockec_Condition = 0x0040 class KeypadOperationEventMask(t.bitmap16): Manufacturer_specific = 0x0001 Lock_source_keypad = 0x0002 Unlock_source_keypad = 0x0004 Lock_source_keypad_error_invalid_code = 0x0008 Lock_source_keypad_error_invalid_schedule = 0x0010 Unlock_source_keypad_error_invalid_code = 0x0020 Unlock_source_keypad_error_invalid_schedule = 0x0040 Non_Access_User_Operation = 0x0080 class RFOperationEventMask(t.bitmap16): Manufacturer_specific = 0x0001 Lock_source_RF = 0x0002 Unlock_source_RF = 0x0004 Lock_source_RF_error_invalid_code = 0x0008 Lock_source_RF_error_invalid_schedule = 0x0010 Unlock_source_RF_error_invalid_code = 0x0020 Unlock_source_RF_error_invalid_schedule = 0x0040 class ManualOperatitonEventMask(t.bitmap16): Manufacturer_specific = 0x0001 Thumbturn_Lock = 0x0002 Thumbturn_Unlock = 0x0004 One_touch_lock = 0x0008 Key_Lock = 0x0010 Key_Unlock = 0x0020 Auto_lock = 0x0040 Schedule_Lock = 0x0080 Schedule_Unlock = 0x0100 Manual_Lock_key_or_thumbturn = 0x0200 Manual_Unlock_key_or_thumbturn = 0x0400 class RFIDOperationEventMask(t.bitmap16): Manufacturer_specific = 0x0001 Lock_source_RFID = 0x0002 Unlock_source_RFID = 0x0004 Lock_source_RFID_error_invalid_RFID_ID = 0x0008 Lock_source_RFID_error_invalid_schedule = 0x0010 Unlock_source_RFID_error_invalid_RFID_ID = 0x0020 Unlock_source_RFID_error_invalid_schedule = 0x0040 class KeypadProgrammingEventMask(t.bitmap16): Manufacturer_Specific = 0x0001 Master_code_changed = 0x0002 PIN_added = 0x0004 PIN_deleted = 0x0008 PIN_changed = 0x0010 class RFProgrammingEventMask(t.bitmap16): Manufacturer_Specific = 0x0001 PIN_added = 0x0004 PIN_deleted = 0x0008 PIN_changed = 0x0010 RFID_code_added = 0x0020 RFID_code_deleted = 0x0040 class RFIDProgrammingEventMask(t.bitmap16): Manufacturer_Specific = 0x0001 RFID_code_added = 0x0020 RFID_code_deleted = 0x0040 class OperationEventSource(t.enum8): Keypad = 0x00 RF = 0x01 Manual = 0x02 RFID = 0x03 Indeterminate = 0xFF class OperationEvent(t.enum8): UnknownOrMfgSpecific = 0x00 Lock = 0x01 Unlock = 0x02 LockFailureInvalidPINorID = 0x03 LockFailureInvalidSchedule = 0x04 UnlockFailureInvalidPINorID = 0x05 UnlockFailureInvalidSchedule = 0x06 OnTouchLock = 0x07 KeyLock = 0x08 KeyUnlock = 0x09 AutoLock = 0x0A ScheduleLock = 0x0B ScheduleUnlock = 0x0C Manual_Lock = 0x0D Manual_Unlock = 0x0E Non_Access_User_Operational_Event = 0x0F class ProgrammingEvent(t.enum8): UnknownOrMfgSpecific = 0x00 MasterCodeChanged = 0x01 PINCodeAdded = 0x02 PINCodeDeleted = 0x03 PINCodeChanges = 0x04 RFIDCodeAdded = 0x05 RFIDCodeDeleted = 0x06 class UserStatus(t.enum8): Available = 0x00 Enabled = 0x01 Disabled = 0x03 Not_Supported = 0xFF class UserType(t.enum8): Unrestricted = 0x00 Year_Day_Schedule_User = 0x01 Week_Day_Schedule_User = 0x02 Master_User = 0x03 Non_Access_User = 0x04 Not_Supported = 0xFF class DayMask(t.bitmap8): Sun = 0x01 Mon = 0x02 Tue = 0x04 Wed = 0x08 Thu = 0x10 Fri = 0x20 Sat = 0x40 class EventType(t.enum8): Operation = 0x00 Programming = 0x01 Alarm = 0x02 cluster_id = 0x0101 name = "Door Lock" ep_attribute = "door_lock" attributes = { 0x0000: ("lock_state", LockState), 0x0001: ("lock_type", LockType), 0x0002: ("actuator_enabled", t.Bool), 0x0003: ("door_state", DoorState), 0x0004: ("door_open_events", t.uint32_t), 0x0005: ("door_closed_events", t.uint32_t), 0x0006: ("open_period", t.uint16_t), 0x0010: ("num_of_lock_records_supported", t.uint16_t), 0x0011: ("num_of_total_users_supported", t.uint16_t), 0x0012: ("num_of_pin_users_supported", t.uint16_t), 0x0013: ("num_of_rfid_users_supported", t.uint16_t), 0x0014: ("num_of_week_day_schedules_supported_per_user", t.uint8_t), 0x0015: ("num_of_year_day_schedules_supported_per_user", t.uint8_t), 0x0016: ("num_of_holiday_scheduleds_supported", t.uint8_t), 0x0017: ("max_pin_len", t.uint8_t), 0x0018: ("min_pin_len", t.uint8_t), 0x0019: ("max_rfid_len", t.uint8_t), 0x001A: ("min_rfid_len", t.uint8_t), 0x0020: ("enable_logging", t.Bool), 0x0021: ("language", t.LimitedCharString(3)), 0x0022: ("led_settings", t.uint8_t), 0x0023: ("auto_relock_time", t.uint32_t), 0x0024: ("sound_volume", t.uint8_t), 0x0025: ("operating_mode", OperatingMode), 0x0026: ("supported_operating_modes", SupportedOperatingModes), 0x0027: ("default_configuration_register", DefaultConfigurationRegister), 0x0028: ("enable_local_programming", t.Bool), 0x0029: ("enable_one_touch_locking", t.Bool), 0x002A: ("enable_inside_status_led", t.Bool), 0x002B: ("enable_privacy_mode_button", t.Bool), 0x0030: ("wrong_code_entry_limit", t.uint8_t), 0x0031: ("user_code_temporary_disable_time", t.uint8_t), 0x0032: ("send_pin_ota", t.Bool), 0x0033: ("require_pin_for_rf_operation", t.Bool), 0x0034: ("zigbee_security_level", ZigbeeSecurityLevel), 0x0040: ("alarm_mask", AlarmMask), 0x0041: ("keypad_operation_event_mask", KeypadOperationEventMask), 0x0042: ("rf_operation_event_mask", RFOperationEventMask), 0x0043: ("manual_operation_event_mask", ManualOperatitonEventMask), 0x0044: ("rfid_operation_event_mask", RFIDOperationEventMask), 0x0045: ("keypad_programming_event_mask", KeypadProgrammingEventMask), 0x0046: ("rf_programming_event_mask", RFProgrammingEventMask), 0x0047: ("rfid_programming_event_mask", RFIDProgrammingEventMask), } server_commands = { 0x0000: ("lock_door", (t.Optional(t.CharacterString),), False), 0x0001: ("unlock_door", (t.Optional(t.CharacterString),), False), 0x0002: ("toggle_door", (t.Optional(t.CharacterString),), False), 0x0003: ( "unlock_with_timeout", (t.uint16_t, t.Optional(t.CharacterString)), False, ), 0x0004: ("get_log_record", (t.uint16_t,), False), 0x0005: ( "set_pin_code", (t.uint16_t, UserStatus, UserType, t.CharacterString), False, ), 0x0006: ("get_pin_code", (t.uint16_t,), False), 0x0007: ("clear_pin_code", (t.uint16_t,), False), 0x0008: ("clear_all_pin_codes", (), False), 0x0009: ("set_user_status", (t.uint16_t, UserStatus), False), 0x000A: ("get_user_status", (t.uint16_t,), False), 0x000B: ( "set_week_day_schedule", ( t.uint8_t, t.uint16_t, DayMask, t.uint8_t, t.uint8_t, t.uint8_t, t.uint8_t, ), False, ), 0x000C: ("get_week_day_schedule", (t.uint8_t, t.uint16_t), False), 0x000D: ("clear_week_day_schedule", (t.uint8_t, t.uint16_t), False), 0x000E: ( "set_year_day_schedule", (t.uint8_t, t.uint16_t, t.LocalTime, t.LocalTime), False, ), 0x000F: ("get_year_day_schedule", (t.uint8_t, t.uint16_t), False), 0x0010: ("clear_year_day_schedule", (t.uint8_t, t.uint16_t), False), 0x0011: ( "set_holiday_schedule", (t.uint8_t, t.LocalTime, t.LocalTime, OperatingMode), False, ), 0x0012: ("get_holiday_schedule", (t.uint8_t,), False), 0x0013: ("clear_holiday_schedule", (t.uint8_t,), False), 0x0014: ("set_user_type", (t.uint16_t, UserType), False), 0x0015: ("get_user_type", (t.uint16_t,), False), 0x0016: ( "set_rfid_code", (t.uint16_t, UserStatus, UserType, t.CharacterString), False, ), 0x0017: ("get_rfid_code", (t.uint16_t,), False), 0x0018: ("clear_rfid_code", (t.uint16_t,), False), 0x0019: ("clear_all_rfid_codes", (), False), } client_commands = { 0x0000: ("lock_door_response", (foundation.Status,), True), 0x0001: ("unlock_door_response", (foundation.Status,), True), 0x0002: ("toggle_door_response", (foundation.Status,), True), 0x0003: ("unlock_with_timeout_response", (foundation.Status,), True), 0x0004: ( "get_log_record_response", ( t.uint16_t, t.uint32_t, EventType, OperationEventSource, t.uint8_t, t.uint16_t, t.Optional(t.CharacterString), ), True, ), 0x0005: ("set_pin_code_response", (foundation.Status,), True), 0x0006: ( "get_pin_code_response", (t.uint16_t, UserStatus, UserType, t.CharacterString), True, ), 0x0007: ("clear_pin_code_response", (foundation.Status,), True), 0x0008: ("clear_all_pin_codes_response", (foundation.Status,), True), 0x0009: ("set_user_status_response", (foundation.Status,), True), 0x000A: ("get_user_status_response", (t.uint16_t, UserStatus), True), 0x000B: ("set_week_day_schedule_response", (foundation.Status,), True), 0x000C: ( "get_week_day_schedule_response", ( t.uint8_t, t.uint16_t, foundation.Status, t.Optional(t.uint8_t), t.Optional(t.uint8_t), t.Optional(t.uint8_t), t.Optional(t.uint8_t), ), True, ), 0x000D: ("clear_week_day_schedule_response", (foundation.Status,), True), 0x000E: ("set_year_day_schedule_response", (foundation.Status,), True), 0x000F: ( "get_year_day_schedule_response", ( t.uint8_t, t.uint16_t, foundation.Status, t.Optional(t.LocalTime), t.Optional(t.LocalTime), ), True, ), 0x0010: ("clear_year_day_schedule_response", (foundation.Status,), True), 0x0011: ("set_holiday_schedule_response", (foundation.Status,), True), 0x0012: ( "get_holiday_schedule_response", ( t.uint8_t, foundation.Status, t.Optional(t.LocalTime), t.Optional(t.LocalTime), t.Optional(t.uint8_t), ), True, ), 0x0013: ("clear_holiday_schedule_response", (foundation.Status,), True), 0x0014: ("set_user_type_response", (foundation.Status,), True), 0x0015: ("get_user_type_response", (t.uint16_t, UserType), True), 0x0016: ("set_rfid_code_response", (t.uint8_t,), True), 0x0017: ( "get_rfid_code_response", (t.uint16_t, UserStatus, UserType, t.CharacterString), True, ), 0x0018: ("clear_rfid_code_response", (foundation.Status,), True), 0x0019: ("clear_all_rfid_codes_response", (foundation.Status,), True), 0x0020: ( "operation_event_notification", ( OperationEventSource, OperationEvent, t.uint16_t, t.uint8_t, t.LocalTime, t.CharacterString, ), False, ), 0x0021: ( "programming_event_notification", ( OperationEventSource, ProgrammingEvent, t.uint16_t, t.uint8_t, UserType, UserStatus, t.LocalTime, t.CharacterString, ), False, ), } class WindowCovering(Cluster): cluster_id = 0x0102 name = "Window Covering" ep_attribute = "window_covering" attributes = { # Window Covering Information 0x0000: ("window_covering_type", t.enum8), 0x0001: ("physical_close_limit_lift_cm", t.uint16_t), 0x0002: ("physical_close_limit_tilt_ddegree", t.uint16_t), 0x0003: ("current_position_lift_cm", t.uint16_t), 0x0004: ("current_position_tilt_ddegree", t.uint16_t), 0x0005: ("num_of_actuation_lift", t.uint16_t), 0x0007: ("config_status", t.bitmap8), 0x0008: ("current_position_lift_percentage", t.uint8_t), 0x0009: ("current_position_tilt_percentage", t.uint8_t), # Window Covering Settings 0x0010: ("installed_open_limit_lift_cm", t.uint16_t), 0x0011: ("installed_closed_limit_lift_cm", t.uint16_t), 0x0012: ("installed_open_limit_tilt_ddegree", t.uint16_t), 0x0013: ("installed_closed_limit_tilt_ddegree", t.uint16_t), 0x0014: ("velocity_lift", t.uint16_t), 0x0015: ("acceleration_time_lift", t.uint16_t), 0x0016: ("num_of_actuation_tilt", t.uint16_t), 0x0017: ("window_covering_mode", t.uint8_t), 0x0018: ("intermediate_setpoints_lift", t.CharacterString), 0x0019: ("intermediate_setpoints_tilt", t.CharacterString), } server_commands = { 0x0000: ("up_open", (), False), 0x0001: ("down_close", (), False), 0x0002: ("stop", (), False), 0x0004: ("go_to_lift_value", (t.uint16_t,), False), 0x0005: ("go_to_lift_percentage", (t.uint8_t,), False), 0x0007: ("go_to_tilt_value", (t.uint16_t,), False), 0x0008: ("go_to_tilt_percentage", (t.uint8_t,), False), } client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/closures.py
closures.py
import asyncio import collections from datetime import datetime from typing import Tuple from zigpy.exceptions import DeliveryError import zigpy.types as t from zigpy.zcl import Cluster, foundation class Basic(Cluster): """ Attributes for determining basic information about a device, setting user device information such as location, and enabling a device. """ class PowerSource(t.enum8): """Power source enum.""" Unknown = 0x00 Mains_single_phase = 0x01 Mains_three_phase = 0x02 Battery = 0x03 DC_Source = 0x04 Emergency_Mains_Always_On = 0x05 Emergency_Mains_Transfer_Switch = 0x06 def __init__(self, *args, **kwargs): self.battery_backup = False @classmethod def deserialize(cls, data: bytes) -> Tuple[bytes, bytes]: val, data = t.uint8_t.deserialize(data) r = cls(val & 0x7F) r.battery_backup = bool(val & 0x80) return r, data class PhysicalEnvironment(t.enum8): Unspecified_environment = 0x00 Mirror = 0x01 Atrium = 0x01 Bar = 0x02 Courtyard = 0x03 Bathroom = 0x04 Bedroom = 0x05 Billiard_Room = 0x06 Utility_Room = 0x07 Cellar = 0x08 Storage_Closet = 0x09 Theater = 0x0A Office = 0x0B Deck = 0x0C Den = 0x0D Dining_Room = 0x0E Electrical_Room = 0x0F Elevator = 0x10 Entry = 0x11 Family_Room = 0x12 Main_Floor = 0x13 Upstairs = 0x14 Downstairs = 0x15 Basement = 0x16 Gallery = 0x17 Game_Room = 0x18 Garage = 0x19 Gym = 0x1A Hallway = 0x1B House = 0x1C Kitchen = 0x1D Laundry_Room = 0x1E Library = 0x1F Master_Bedroom = 0x20 Mud_Room_small_room_for_coats_and_boots = 0x21 Nursery = 0x22 Pantry = 0x23 Office_2 = 0x24 Outside = 0x25 Pool = 0x26 Porch = 0x27 Sewing_Room = 0x28 Sitting_Room = 0x29 Stairway = 0x2A Yard = 0x2B Attic = 0x2C Hot_Tub = 0x2D Living_Room = 0x2E Sauna = 0x2F Workshop = 0x30 Guest_Bedroom = 0x31 Guest_Bath = 0x32 Back_Yard = 0x34 Front_Yard = 0x35 Patio = 0x36 Driveway = 0x37 Sun_Room = 0x38 Grand_Room = 0x39 Spa = 0x3A Whirlpool = 0x3B Shed = 0x3C Equipment_Storage = 0x3D Craft_Room = 0x3E Fountain = 0x3F Pond = 0x40 Reception_Room = 0x41 Breakfast_Room = 0x42 Nook = 0x43 Garden = 0x44 Balcony = 0x45 Panic_Room = 0x46 Terrace = 0x47 Roof = 0x48 Toilet = 0x49 Toilet_Main = 0x4A Outside_Toilet = 0x4B Shower_room = 0x4C Study = 0x4D Front_Garden = 0x4E Back_Garden = 0x4F Kettle = 0x50 Television = 0x51 Stove = 0x52 Microwave = 0x53 Toaster = 0x54 Vacuum = 0x55 Appliance = 0x56 Front_Door = 0x57 Back_Door = 0x58 Fridge_Door = 0x59 Medication_Cabinet_Door = 0x60 Wardrobe_Door = 0x61 Front_Cupboard_Door = 0x62 Other_Door = 0x63 Waiting_Room = 0x64 Triage_Room = 0x65 Doctors_Office = 0x66 Patients_Private_Room = 0x67 Consultation_Room = 0x68 Nurse_Station = 0x69 Ward = 0x6A Corridor = 0x6B Operating_Theatre = 0x6C Dental_Surgery_Room = 0x6D Medical_Imaging_Room = 0x6E Decontamination_Room = 0x6F Unknown_environment = 0xFF class AlarmMask(t.bitmap8): General_hardware_fault = 0x01 General_software_fault = 0x02 class DisableLocalConfig(t.bitmap8): Reset = 0x01 Device_Configuration = 0x02 cluster_id = 0x0000 ep_attribute = "basic" attributes = { # Basic Device Information 0x0000: ("zcl_version", t.uint8_t), 0x0001: ("app_version", t.uint8_t), 0x0002: ("stack_version", t.uint8_t), 0x0003: ("hw_version", t.uint8_t), 0x0004: ("manufacturer", t.CharacterString), 0x0005: ("model", t.CharacterString), 0x0006: ("date_code", t.CharacterString), 0x0007: ("power_source", PowerSource), 0x0008: ("app_profile_version", t.enum8), # Basic Device Settings 0x0010: ("location_desc", t.LimitedCharString(16)), 0x0011: ("physical_env", PhysicalEnvironment), 0x0012: ("device_enabled", t.Bool), 0x0013: ("alarm_mask", AlarmMask), 0x0014: ("disable_local_config", DisableLocalConfig), 0x4000: ("sw_build_id", t.CharacterString), } server_commands = {0x0000: ("reset_fact_default", (), False)} client_commands = {} class PowerConfiguration(Cluster): """ Attributes for determining more detailed information about a device’s power source(s), and for configuring under/over voltage alarms.""" cluster_id = 0x0001 name = "Power Configuration" ep_attribute = "power" attributes = { # Mains Information 0x0000: ("mains_voltage", t.uint16_t), 0x0001: ("mains_frequency", t.uint8_t), # Mains Settings 0x0010: ("mains_alarm_mask", t.bitmap8), 0x0011: ("mains_volt_min_thres", t.uint16_t), 0x0012: ("mains_volt_max_thres", t.uint16_t), 0x0013: ("mains_voltage_dwell_trip_point", t.uint16_t), # Battery Information 0x0020: ("battery_voltage", t.uint8_t), 0x0021: ("battery_percentage_remaining", t.uint8_t), # Battery Settings 0x0030: ("battery_manufacturer", t.CharacterString), 0x0031: ("battery_size", t.enum8), 0x0032: ("battery_a_hr_rating", t.uint16_t), 0x0033: ("battery_quantity", t.uint8_t), 0x0034: ("battery_rated_voltage", t.uint8_t), 0x0035: ("battery_alarm_mask", t.bitmap8), 0x0036: ("battery_volt_min_thres", t.uint8_t), 0x0037: ("battery_volt_thres1", t.uint16_t), 0x0038: ("battery_volt_thres2", t.uint16_t), 0x0039: ("battery_volt_thres3", t.uint16_t), 0x003A: ("battery_percent_min_thres", t.uint8_t), 0x003B: ("battery_percent_thres1", t.uint8_t), 0x003C: ("battery_percent_thres2", t.uint8_t), 0x003D: ("battery_percent_thres3", t.uint8_t), 0x003E: ("battery_alarm_state", t.bitmap32), # Battery 2 Information 0x0040: ("battery_2_voltage", t.uint8_t), 0x0041: ("battery_2_percentage_remaining", t.uint8_t), # Battery 2 Settings 0x0050: ("battery_2_manufacturer", t.CharacterString), 0x0051: ("battery_2_size", t.enum8), 0x0052: ("battery_2_a_hr_rating", t.uint16_t), 0x0053: ("battery_2_quantity", t.uint8_t), 0x0054: ("battery_2_rated_voltage", t.uint8_t), 0x0055: ("battery_2_alarm_mask", t.bitmap8), 0x0056: ("battery_2_volt_min_thres", t.uint8_t), 0x0057: ("battery_2_volt_thres1", t.uint16_t), 0x0058: ("battery_2_volt_thres2", t.uint16_t), 0x0059: ("battery_2_volt_thres3", t.uint16_t), 0x005A: ("battery_2_percent_min_thres", t.uint8_t), 0x005B: ("battery_2_percent_thres1", t.uint8_t), 0x005C: ("battery_2_percent_thres2", t.uint8_t), 0x005D: ("battery_2_percent_thres3", t.uint8_t), 0x005E: ("battery_2_alarm_state", t.bitmap32), # Battery 3 Information 0x0060: ("battery_3_voltage", t.uint8_t), 0x0061: ("battery_3_percentage_remaining", t.uint8_t), # Battery 3 Settings 0x0070: ("battery_3_manufacturer", t.CharacterString), 0x0071: ("battery_3_size", t.enum8), 0x0072: ("battery_3_a_hr_rating", t.uint16_t), 0x0073: ("battery_3_quantity", t.uint8_t), 0x0074: ("battery_3_rated_voltage", t.uint8_t), 0x0075: ("battery_3_alarm_mask", t.bitmap8), 0x0076: ("battery_3_volt_min_thres", t.uint8_t), 0x0077: ("battery_3_volt_thres1", t.uint16_t), 0x0078: ("battery_3_volt_thres2", t.uint16_t), 0x0079: ("battery_3_volt_thres3", t.uint16_t), 0x007A: ("battery_3_percent_min_thres", t.uint8_t), 0x007B: ("battery_3_percent_thres1", t.uint8_t), 0x007C: ("battery_3_percent_thres2", t.uint8_t), 0x007D: ("battery_3_percent_thres3", t.uint8_t), 0x007E: ("battery_3_alarm_state", t.bitmap32), } server_commands = {} client_commands = {} class DeviceTemperature(Cluster): """Attributes for determining information about a device’s internal temperature, and for configuring under/over temperature alarms.""" cluster_id = 0x0002 name = "Device Temperature" ep_attribute = "device_temperature" attributes = { # Device Temperature Information 0x0000: ("current_temperature", t.int16s), 0x0001: ("min_temp_experienced", t.int16s), 0x0002: ("max_temp_experienced", t.int16s), 0x0003: ("over_temp_total_dwell", t.uint16_t), # Device Temperature Settings 0x0010: ("dev_temp_alarm_mask", t.bitmap8), 0x0011: ("low_temp_thres", t.int16s), 0x0012: ("high_temp_thres", t.int16s), 0x0013: ("low_temp_dwell_trip_point", t.uint24_t), 0x0014: ("high_temp_dwell_trip_point", t.uint24_t), } server_commands = {} client_commands = {} class Identify(Cluster): """Attributes and commands for putting a device into Identification mode (e.g. flashing a light)""" cluster_id = 0x0003 ep_attribute = "identify" attributes = { 0x0000: ("identify_time", t.uint16_t), 0x0001: ("identify_commission_state", t.bitmap8), } server_commands = { 0x0000: ("identify", (t.uint16_t,), False), 0x0001: ("identify_query", (), False), 0x0002: ("ezmode_invoke", (t.bitmap8,), False), 0x0003: ("update_commission_state", (t.bitmap8,), False), 0x0040: ("trigger_effect", (t.uint8_t, t.uint8_t), False), } client_commands = {0x0000: ("identify_query_response", (t.uint16_t,), True)} class Groups(Cluster): """Attributes and commands for group configuration and manipulation.""" cluster_id = 0x0004 ep_attribute = "groups" attributes = {0x0000: ("name_support", t.bitmap8)} server_commands = { 0x0000: ("add", (t.Group, t.CharacterString), False), 0x0001: ("view", (t.Group,), False), 0x0002: ("get_membership", (t.LVList(t.Group),), False), 0x0003: ("remove", (t.Group,), False), 0x0004: ("remove_all", (), False), 0x0005: ("add_if_identifying", (t.Group, t.CharacterString), False), } client_commands = { 0x0000: ("add_response", (foundation.Status, t.Group), True), 0x0001: ( "view_response", (foundation.Status, t.Group, t.CharacterString), True, ), 0x0002: ("get_membership_response", (t.uint8_t, t.LVList(t.Group)), True), 0x0003: ("remove_response", (foundation.Status, t.Group), True), } class Scenes(Cluster): """Attributes and commands for scene configuration and manipulation.""" cluster_id = 0x0005 ep_attribute = "scenes" attributes = { # Scene Management Information 0x0000: ("count", t.uint8_t), 0x0001: ("current_scene", t.uint8_t), 0x0002: ("current_group", t.uint16_t), 0x0003: ("scene_valid", t.Bool), 0x0004: ("name_support", t.bitmap8), 0x0005: ("last_configured_by", t.EUI64), } server_commands = { 0x0000: ( "add", (t.uint16_t, t.uint8_t, t.uint16_t, t.CharacterString), False, ), # + extension field sets 0x0001: ("view", (t.uint16_t, t.uint8_t), False), 0x0002: ("remove", (t.uint16_t, t.uint8_t), False), 0x0003: ("remove_all", (t.uint16_t,), False), 0x0004: ("store", (t.uint16_t, t.uint8_t), False), 0x0005: ("recall", (t.uint16_t, t.uint8_t), False), 0x0006: ("get_scene_membership", (t.uint16_t,), False), 0x0040: ("enhanced_add", (), False), 0x0041: ("enhanced_view", (), False), 0x0042: ("copy", (), False), } client_commands = { 0x0000: ("add_response", (t.uint8_t, t.uint16_t, t.uint8_t), True), 0x0001: ( "view_response", (t.uint8_t, t.uint16_t, t.uint8_t), True, ), # + 3 more optionals 0x0002: ("remove_response", (t.uint8_t, t.uint16_t, t.uint8_t), True), 0x0003: ("remove_all_response", (t.uint8_t, t.uint16_t), True), 0x0004: ("store_response", (t.uint8_t, t.uint16_t, t.uint8_t), True), 0x0006: ( "get_scene_membership_response", (t.uint8_t, t.uint8_t, t.uint16_t, t.Optional(t.LVList(t.uint8_t))), True, ), 0x0040: ("enhanced_add_response", (), True), 0x0041: ("enhanced_view_response", (), True), 0x0042: ("copy_response", (), True), } class OnOff(Cluster): """Attributes and commands for switching devices between ‘On’ and ‘Off’ states. """ cluster_id = 0x0006 name = "On/Off" ep_attribute = "on_off" attributes = { 0x0000: ("on_off", t.Bool), 0x4000: ("global_scene_control", t.Bool), 0x4001: ("on_time", t.uint16_t), 0x4002: ("off_wait_time", t.uint16_t), } server_commands = { 0x0000: ("off", (), False), 0x0001: ("on", (), False), 0x0002: ("toggle", (), False), 0x0040: ("off_with_effect", (t.uint8_t, t.uint8_t), False), 0x0041: ("on_with_recall_global_scene", (), False), 0x0042: ("on_with_timed_off", (t.uint8_t, t.uint16_t, t.uint16_t), False), } client_commands = {} class OnOffConfiguration(Cluster): """Attributes and commands for configuring On/Off switching devices""" cluster_id = 0x0007 name = "On/Off Switch Configuration" ep_attribute = "on_off_config" attributes = { # Switch Information 0x0000: ("switch_type", t.enum8), # Switch Settings 0x0010: ("switch_actions", t.enum8), } server_commands = {} client_commands = {} class LevelControl(Cluster): """Attributes and commands for controlling devices that can be set to a level between fully ‘On’ and fully ‘Off’.""" cluster_id = 0x0008 name = "Level control" ep_attribute = "level" attributes = { 0x0000: ("current_level", t.uint8_t), 0x0001: ("remaining_time", t.uint16_t), 0x0010: ("on_off_transition_time", t.uint16_t), 0x0011: ("on_level", t.uint8_t), 0x0012: ("on_transition_time", t.uint16_t), 0x0013: ("off_transition_time", t.uint16_t), 0x0014: ("default_move_rate", t.uint8_t), } server_commands = { 0x0000: ("move_to_level", (t.uint8_t, t.uint16_t), False), 0x0001: ("move", (t.uint8_t, t.uint8_t), False), 0x0002: ("step", (t.uint8_t, t.uint8_t, t.uint16_t), False), 0x0003: ("stop", (), False), 0x0004: ("move_to_level_with_on_off", (t.uint8_t, t.uint16_t), False), 0x0005: ("move_with_on_off", (t.uint8_t, t.uint8_t), False), 0x0006: ("step_with_on_off", (t.uint8_t, t.uint8_t, t.uint16_t), False), 0x0007: ("stop", (), False), } client_commands = {} class Alarms(Cluster): """ Attributes and commands for sending notifications and configuring alarm functionality.""" cluster_id = 0x0009 ep_attribute = "alarms" attributes = { # Alarm Information 0x0000: ("alarm_count", t.uint16_t) } server_commands = { 0x0000: ("reset", (t.uint8_t, t.uint16_t), False), 0x0001: ("reset_all", (), False), 0x0002: ("get_alarm", (), False), 0x0003: ("reset_log", (), False), 0x0004: ("publish_event_log", (), False), } client_commands = { 0x0000: ("alarm", (t.uint8_t, t.uint16_t), False), 0x0001: ( "get_alarm_response", ( t.uint8_t, t.Optional(t.uint8_t), t.Optional(t.uint16_t), t.Optional(t.uint32_t), ), True, ), 0x0002: ("get_event_log", (), False), } class Time(Cluster): """ Attributes and commands that provide a basic interface to a real-time clock.""" cluster_id = 0x000A ep_attribute = "time" attributes = { 0x0000: ("time", t.UTCTime), 0x0001: ("time_status", t.bitmap8), 0x0002: ("time_zone", t.int32s), 0x0003: ("dst_start", t.uint32_t), 0x0004: ("dst_end", t.uint32_t), 0x0005: ("dst_shift", t.int32s), 0x0006: ("standard_time", t.StandardTime), 0x0007: ("local_time", t.LocalTime), 0x0008: ("last_set_time", t.uint32_t), 0x0009: ("valid_until_time", t.uint32_t), } server_commands = {} client_commands = {} def handle_cluster_general_request(self, tsn, command_id, *args): if command_id == foundation.Command.Read_Attributes: # responses should be in the same order. Is it time to ditch py35? data = collections.OrderedDict() for attr in args[0][0]: if attr == 0: epoch = datetime(2000, 1, 1, 0, 0, 0, 0) diff = datetime.utcnow() - epoch data[attr] = diff.total_seconds() elif attr == 1: data[attr] = 7 elif attr == 2: diff = datetime.fromtimestamp(86400) - datetime.utcfromtimestamp( 86400 ) data[attr] = diff.total_seconds() elif attr == 7: epoch = datetime(2000, 1, 1, 0, 0, 0, 0) diff = datetime.now() - epoch data[attr] = diff.total_seconds() else: data[attr] = None self.create_catching_task(self.read_attributes_rsp(data, tsn=tsn)) class RSSILocation(Cluster): """Attributes and commands that provide a means for exchanging location information and channel parameters among devices.""" cluster_id = 0x000B ep_attribute = "rssi_location" attributes = { # Location Information 0x0000: ("type", t.uint8_t), 0x0001: ("method", t.enum8), 0x0002: ("age", t.uint16_t), 0x0003: ("quality_measure", t.uint8_t), 0x0004: ("num_of_devices", t.uint8_t), # Location Settings 0x0010: ("coordinate1", t.int16s), 0x0011: ("coordinate2", t.int16s), 0x0012: ("coordinate3", t.int16s), 0x0013: ("power", t.int16s), 0x0014: ("path_loss_exponent", t.uint16_t), 0x0015: ("reporting_period", t.uint16_t), 0x0016: ("calc_period", t.uint16_t), 0x0017: ("num_rssi_measurements", t.uint16_t), } server_commands = { 0x0000: ( "set_absolute_location", (t.int16s, t.int16s, t.int16s, t.int8s, t.uint16_t), False, ), 0x0001: ( "set_dev_config", (t.int16s, t.uint16_t, t.uint16_t, t.uint8_t, t.uint16_t), False, ), 0x0002: ("get_dev_config", (t.EUI64,), False), 0x0003: ("get_location_data", (t.bitmap8, t.uint8_t, t.EUI64), False), 0x0004: ( "rssi_response", (t.EUI64, t.int16s, t.int16s, t.int16s, t.int8s, t.uint8_t), True, ), 0x0005: ("send_pings", (t.EUI64, t.uint8_t, t.uint16_t), False), 0x0006: ( "anchor_node_announce", (t.EUI64, t.int16s, t.int16s, t.int16s), False, ), } class NeighborInfo(t.Struct): _fields = [ ("neighbor", t.EUI64), ("x", t.int16s), ("y", t.int16s), ("z", t.int16s), ("rssi", t.int8s), ("num_measurements", t.uint8_t), ] client_commands = { 0x0000: ( "dev_config_response", ( foundation.Status, t.Optional(t.int16s), t.Optional(t.uint16_t), t.Optional(t.uint16_t), t.Optional(t.uint8_t), t.Optional(t.uint16_t), ), True, ), 0x0001: ( "location_data_response", ( foundation.Status, t.Optional(t.uint8_t), t.Optional(t.int16s), t.Optional(t.int16s), t.Optional(t.int16s), t.Optional(t.uint16_t), t.Optional(t.uint8_t), t.Optional(t.uint8_t), t.Optional(t.uint16_t), ), True, ), 0x0002: ("location_data_notification", (), False), 0x0003: ("compact_location_data_notification", (), False), 0x0004: ("rssi_ping", (t.uint8_t,), False), # data8 0x0005: ("rssi_req", (), False), 0x0006: ("report_rssi_measurements", (t.EUI64, t.LVList(NeighborInfo)), False), 0x0007: ("request_own_location", (t.EUI64,), False), } class AnalogInput(Cluster): cluster_id = 0x000C ep_attribute = "analog_input" attributes = { 0x001C: ("description", t.CharacterString), 0x0041: ("max_present_value", t.Single), 0x0045: ("min_present_value", t.Single), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), 0x0067: ("reliability", t.enum8), 0x006A: ("resolution", t.Single), 0x006F: ("status_flags", t.bitmap8), 0x0075: ("engineering_units", t.enum16), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class AnalogOutput(Cluster): cluster_id = 0x000D ep_attribute = "analog_output" attributes = { 0x001C: ("description", t.CharacterString), 0x0041: ("max_present_value", t.Single), 0x0045: ("min_present_value", t.Single), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x0068: ("relinquish_default", t.Single), 0x006A: ("resolution", t.Single), 0x006F: ("status_flags", t.bitmap8), 0x0075: ("engineering_units", t.enum16), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class AnalogValue(Cluster): cluster_id = 0x000E ep_attribute = "analog_value" attributes = { 0x001C: ("description", t.CharacterString), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x0068: ("relinquish_default", t.Single), 0x006F: ("status_flags", t.bitmap8), 0x0075: ("engineering_units", t.enum16), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class BinaryInput(Cluster): cluster_id = 0x000F name = "Binary Input (Basic)" ep_attribute = "binary_input" attributes = { 0x0004: ("active_text", t.CharacterString), 0x001C: ("description", t.CharacterString), 0x002E: ("inactive_text", t.CharacterString), 0x0051: ("out_of_service", t.Bool), 0x0054: ("polarity", t.enum8), 0x0055: ("present_value", t.Bool), 0x0067: ("reliability", t.enum8), 0x006F: ("status_flags", t.bitmap8), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class BinaryOutput(Cluster): cluster_id = 0x0010 ep_attribute = "binary_output" attributes = { 0x0004: ("active_text", t.CharacterString), 0x001C: ("description", t.CharacterString), 0x002E: ("inactive_text", t.CharacterString), 0x0042: ("minimum_off_time", t.uint32_t), 0x0043: ("minimum_on_time", t.uint32_t), 0x0051: ("out_of_service", t.Bool), 0x0054: ("polarity", t.enum8), 0x0055: ("present_value", t.Bool), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x0068: ("relinquish_default", t.Bool), 0x006F: ("status_flags", t.bitmap8), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class BinaryValue(Cluster): cluster_id = 0x0011 ep_attribute = "binary_value" attributes = { 0x0004: ("active_text", t.CharacterString), 0x001C: ("description", t.CharacterString), 0x002E: ("inactive_text", t.CharacterString), 0x0042: ("minimum_off_time", t.uint32_t), 0x0043: ("minimum_on_time", t.uint32_t), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x0068: ("relinquish_default", t.Single), 0x006F: ("status_flags", t.bitmap8), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class MultistateInput(Cluster): cluster_id = 0x0012 ep_attribute = "multistate_input" attributes = { 0x000E: ("state_text", t.List(t.CharacterString)), 0x001C: ("description", t.CharacterString), 0x004A: ("number_of_states", t.uint16_t), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x006F: ("status_flags", t.bitmap8), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class MultistateOutput(Cluster): cluster_id = 0x0013 ep_attribute = "multistate_output" attributes = { 0x000E: ("state_text", t.List(t.CharacterString)), 0x001C: ("description", t.CharacterString), 0x004A: ("number_of_states", t.uint16_t), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x0068: ("relinquish_default", t.Single), 0x006F: ("status_flags", t.bitmap8), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class MultistateValue(Cluster): cluster_id = 0x0014 ep_attribute = "multistate_value" attributes = { 0x000E: ("state_text", t.List(t.CharacterString)), 0x001C: ("description", t.CharacterString), 0x004A: ("number_of_states", t.uint16_t), 0x0051: ("out_of_service", t.Bool), 0x0055: ("present_value", t.Single), # 0x0057: ('priority_array', TODO.array), # Array of 16 structures of (boolean, # single precision) 0x0067: ("reliability", t.enum8), 0x0068: ("relinquish_default", t.Single), 0x006F: ("status_flags", t.bitmap8), 0x0100: ("application_type", t.uint32_t), } server_commands = {} client_commands = {} class Commissioning(Cluster): """Attributes and commands for commissioning and managing a ZigBee device.""" cluster_id = 0x0015 ep_attribute = "commissioning" attributes = { # Startup Parameters 0x0000: ("short_address", t.uint16_t), 0x0001: ("extended_pan_id", t.EUI64), 0x0002: ("pan_id", t.uint16_t), 0x0003: ("channelmask", t.bitmap32), 0x0004: ("protocol_version", t.uint8_t), 0x0005: ("stack_profile", t.uint8_t), 0x0006: ("startup_control", t.enum8), 0x0010: ("trust_center_address", t.EUI64), 0x0011: ("trust_center_master_key", t.fixed_list(16, t.uint8_t)), 0x0012: ("network_key", t.fixed_list(16, t.uint8_t)), 0x0013: ("use_insecure_join", t.Bool), 0x0014: ("preconfigured_link_key", t.fixed_list(16, t.uint8_t)), 0x0015: ("network_key_seq_num", t.uint8_t), 0x0016: ("network_key_type", t.enum8), 0x0017: ("network_manager_address", t.uint16_t), # Join Parameters 0x0020: ("scan_attempts", t.uint8_t), 0x0021: ("time_between_scans", t.uint16_t), 0x0022: ("rejoin_interval", t.uint16_t), 0x0023: ("max_rejoin_interval", t.uint16_t), # End Device Parameters 0x0030: ("indirect_poll_rate", t.uint16_t), 0x0031: ("parent_retry_threshold", t.uint8_t), # Concentrator Parameters 0x0040: ("concentrator_flag", t.Bool), 0x0041: ("concentrator_radius", t.uint8_t), 0x0042: ("concentrator_discovery_time", t.uint8_t), } server_commands = { 0x0000: ("restart_device", (t.uint8_t, t.uint8_t, t.uint8_t), False), 0x0001: ("save_startup_parameters", (t.uint8_t, t.uint8_t), False), 0x0002: ("restore_startup_parameters", (t.uint8_t, t.uint8_t), False), 0x0003: ("reset_startup_parameters", (t.uint8_t, t.uint8_t), False), } client_commands = { 0x0000: ("restart_device_response", (t.uint8_t,), True), 0x0001: ("save_startup_params_response", (t.uint8_t,), True), 0x0002: ("restore_startup_params_response", (t.uint8_t,), True), 0x0003: ("reset_startup_params_response", (t.uint8_t,), True), } class Partition(Cluster): cluster_id = 0x0016 ep_attribute = "partition" attributes = {} server_commands = {} client_commands = {} class Ota(Cluster): cluster_id = 0x0019 ep_attribute = "ota" attributes = { 0x0000: ("upgrade_server_id", t.EUI64), 0x0001: ("file_offset", t.uint32_t), 0x0002: ("current_file_version", t.uint32_t), 0x0003: ("current_zigbee_stack_version", t.uint16_t), 0x0004: ("downloaded_file_version", t.uint32_t), 0x0005: ("downloaded_zigbee_stack_version", t.uint16_t), 0x0006: ("image_upgrade_status", t.enum8), 0x0007: ("manufacturer_id", t.uint16_t), 0x0008: ("image_type_id", t.uint16_t), 0x0009: ("minimum_block_req_delay", t.uint16_t), 0x000A: ("image_stamp", t.uint32_t), } server_commands = { 0x0001: ( "query_next_image", (t.uint8_t, t.uint16_t, t.uint16_t, t.uint32_t, t.Optional(t.uint16_t)), False, ), 0x0003: ( "image_block", ( t.uint8_t, t.uint16_t, t.uint16_t, t.uint32_t, t.uint32_t, t.uint8_t, t.Optional(t.EUI64), t.Optional(t.uint16_t), ), False, ), 0x0004: ( "image_page", ( t.uint8_t, t.uint16_t, t.uint16_t, t.uint32_t, t.uint32_t, t.uint8_t, t.uint16_t, t.uint16_t, t.Optional(t.EUI64), ), False, ), 0x0006: ( "upgrade_end", (foundation.Status, t.uint16_t, t.uint16_t, t.uint32_t), False, ), 0x0008: ( "query_specific_file", (t.EUI64, t.uint16_t, t.uint16_t, t.uint32_t, t.uint16_t), False, ), } client_commands = { 0x0000: ( "image_notify", ( t.uint8_t, t.uint8_t, t.Optional(t.uint16_t), t.Optional(t.uint16_t), t.Optional(t.uint32_t), ), False, ), 0x0002: ( "query_next_image_response", ( foundation.Status, t.Optional(t.uint16_t), t.Optional(t.uint16_t), t.Optional(t.uint32_t), t.Optional(t.uint32_t), ), True, ), 0x0005: ( "image_block_response", ( foundation.Status, t.uint16_t, t.uint16_t, t.uint32_t, t.uint32_t, t.LVBytes, ), True, ), 0x0007: ( "upgrade_end_response", (t.uint16_t, t.uint16_t, t.uint32_t, t.uint32_t, t.uint32_t), True, ), 0x0009: ( "query_specific_file_response", ( foundation.Status, t.Optional(t.uint16_t), t.Optional(t.uint16_t), t.Optional(t.uint32_t), t.Optional(t.uint32_t), ), True, ), } def handle_cluster_request(self, tsn, command_id, args): self.create_catching_task( self._handle_cluster_request(tsn, command_id, args), exceptions=(AssertionError, asyncio.TimeoutError, DeliveryError), ) async def _handle_cluster_request(self, tsn, command_id, args): """Parse OTA commands.""" cmd_name = self.server_commands.get(command_id, [command_id])[0] if cmd_name == "query_next_image": await self._handle_query_next_image(*args, tsn=tsn) elif cmd_name == "image_block": await self._handle_image_block(*args, tsn=tsn) elif cmd_name == "upgrade_end": await self._handle_upgrade_end(*args, tsn=tsn) else: self.debug( "no '%s' OTA command handler for '%s %s': %s", cmd_name, self.endpoint.manufacturer, self.endpoint.model, args, ) async def _handle_query_next_image( self, field_ctrl, manufacturer_id, image_type, current_file_version, hardware_version, *, tsn ): self.debug( ( "OTA query_next_image handler for '%s %s': " "field_control=%s, manufacture_id=%s, image_type=%s, " "current_file_version=%s, hardware_version=%s" ), self.endpoint.manufacturer, self.endpoint.model, field_ctrl, manufacturer_id, image_type, current_file_version, hardware_version, ) img = await self.endpoint.device.application.ota.get_ota_image( manufacturer_id, image_type ) if img is not None: should_update = img.should_update( manufacturer_id, image_type, current_file_version, hardware_version ) self.debug( "OTA image version: %s, size: %s. Update needed: %s", img.version, img.header.image_size, should_update, ) if should_update: self.info( "Updating: %s %s", self.endpoint.manufacturer, self.endpoint.model ) await self.query_next_image_response( foundation.Status.SUCCESS, img.key.manufacturer_id, img.key.image_type, img.version, img.header.image_size, tsn=tsn, ) return else: self.debug("No OTA image is available") await self.query_next_image_response( foundation.Status.NO_IMAGE_AVAILABLE, tsn=tsn ) async def _handle_image_block( self, field_ctr, manufacturer_id, image_type, file_version, file_offset, max_data_size, request_node_addr, block_request_delay, *, tsn=None ): self.debug( ( "OTA image_block handler for '%s %s': field_control=%s, " "manufacturer_id=%s, image_type=%s, file_version=%s, " "file_offset=%s, max_data_size=%s, request_node_addr=%s" "block_request_delay=%s" ), self.endpoint.manufacturer, self.endpoint.model, field_ctr, manufacturer_id, image_type, file_version, file_offset, max_data_size, request_node_addr, block_request_delay, ) img = await self.endpoint.device.application.ota.get_ota_image( manufacturer_id, image_type ) if img is None or img.version != file_version: self.debug("OTA image is not available") await self.image_block_response(foundation.Status.ABORT, tsn=tsn) return self.debug( "OTA upgrade progress: %0.1f", 100.0 * file_offset / img.header.image_size ) try: await self.image_block_response( foundation.Status.SUCCESS, img.key.manufacturer_id, img.key.image_type, img.version, file_offset, img.get_image_block(file_offset, max_data_size), tsn=tsn, ) except ValueError: await self.image_block_response( foundation.Status.MALFORMED_COMMAND, tsn=tsn ) async def _handle_upgrade_end( self, status, manufacturer_id, image_type, file_ver, *, tsn ): self.debug( ( "OTA upgrade_end handler for '%s %s': status=%s, " "manufacturer_id=%s, image_type=%s, file_version=%s" ), self.endpoint.manufacturer, self.endpoint.model, status, manufacturer_id, image_type, file_ver, ) await self.upgrade_end_response( manufacturer_id, image_type, file_ver, 0x00000000, 0x00000000, tsn=tsn ) class PowerProfile(Cluster): cluster_id = 0x001A ep_attribute = "power_profile" attributes = { 0x0000: ("total_profile_num", t.uint8_t), 0x0001: ("multiple_scheduling", t.uint8_t), 0x0002: ("energy_formatting", t.bitmap8), 0x0003: ("energy_remote", t.Bool), 0x0004: ("schedule_mode", t.bitmap8), } class ScheduleRecord(t.Struct): _fields = [("phase_id", t.uint8_t), ("scheduled_time", t.uint16_t)] class PowerProfilePhase(t.Struct): _fields = [ ("energy_phase_id", t.uint8_t), ("macro_phase_id", t.uint8_t), ("expected_duration", t.uint16_t), ("peak_power", t.uint16_t), ("energy", t.uint16_t), ] class PowerProfile(t.Struct): _fields = [ ("power_profile_id", t.uint8_t), ("energy_phase_id", t.uint8_t), ("power_profile_remote_control", t.Bool), ("power_profile_state", t.uint8_t), ] server_commands = { 0x0000: ("power_profile_request", (t.uint8_t,), False), 0x0001: ("power_profile_state_request", (), False), 0x0002: ( "get_power_profile_price_response", (t.uint8_t, t.uint16_t, t.uint32_t, t.uint8_t), True, ), 0x0003: ( "get_overall_schedule_price_response", (t.uint16_t, t.uint32_t, t.uint8_t), True, ), 0x0004: ( "energy_phases_schedule_notification", (t.uint8_t, t.LVList(ScheduleRecord)), False, ), 0x0005: ( "energy_phases_schedule_response", (t.uint8_t, t.LVList(ScheduleRecord)), True, ), 0x0006: ("power_profile_schedule_constraints_request", (t.uint8_t,), False), 0x0007: ("energy_phases_schedule_state_request", (t.uint8_t,), False), 0x0008: ( "get_power_profile_price_extended_response", (t.uint8_t, t.uint16_t, t.uint32_t, t.uint8_t), True, ), } client_commands = { 0x0000: ( "power_profile_notification", (t.uint8_t, t.uint8_t, t.LVList(PowerProfilePhase)), False, ), 0x0001: ( "power_profile_response", (t.uint8_t, t.uint8_t, t.LVList(PowerProfilePhase)), True, ), 0x0002: ("power_profile_state_response", (t.LVList(PowerProfile),), True), 0x0003: ("get_power_profile_price", (t.uint8_t,), False), 0x0004: ("power_profile_state_notification", (t.LVList(PowerProfile),), False), 0x0005: ("get_overall_schedule_price", (), False), 0x0006: ("energy_phases_schedule_request", (), False), 0x0007: ("energy_phases_schedule_state_response", (t.uint8_t, t.uint8_t), True), 0x0008: ( "energy_phases_schedule_state_notification", (t.uint8_t, t.uint8_t), False, ), 0x0009: ( "power_profile_schedule_constraints_notification", (t.uint8_t, t.uint16_t, t.uint16_t), False, ), 0x000A: ( "power_profile_schedule_constraints_response", (t.uint8_t, t.uint16_t, t.uint16_t), True, ), 0x000B: ( "get_power_profile_price_extended", (t.bitmap8, t.uint8_t, t.Optional(t.uint16_t)), False, ), } class ApplianceControl(Cluster): cluster_id = 0x001B ep_attribute = "appliance_control" attributes = {} server_commands = {} client_commands = {} class PollControl(Cluster): cluster_id = 0x0020 name = "Poll Control" ep_attribute = "poll_control" attributes = { 0x0000: ("checkin_interval", t.uint32_t), 0x0001: ("long_poll_interval", t.uint32_t), 0x0002: ("short_poll_interval", t.uint16_t), 0x0003: ("fast_poll_timeout", t.uint16_t), 0x0004: ("checkin_interval_min", t.uint32_t), 0x0005: ("long_poll_interval_min", t.uint32_t), 0x0006: ("fast_poll_timeout_max", t.uint16_t), } server_commands = { 0x0000: ("checkin_response", (t.uint8_t, t.uint16_t), True), 0x0001: ("fast_poll_stop", (), False), 0x0002: ("set_long_poll_interval", (t.uint32_t,), False), 0x0003: ("set_short_poll_interval", (t.uint16_t,), False), } client_commands = {0x0000: ("checkin", (), False)} class GreenPowerProxy(Cluster): cluster_id = 0x0021 ep_attribute = "green_power" attributes = {} server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/general.py
general.py
from zigpy import types as t from zigpy.zcl import Cluster, foundation NET_START = ( t.uint32_t, t.EUI64, t.uint8_t, t.KeyData, t.uint8_t, t.NWK, t.NWK, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.EUI64, t.NWK, ) NET_JOIN = ( t.uint32_t, t.EUI64, t.uint8_t, t.KeyData, t.uint8_t, t.uint8_t, t.NWK, t.NWK, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, ) class DeviceInfoRecord(t.Struct): _fields = [ ("ieee", t.EUI64), ("endpoint_id", t.uint8_t), ("profile_id", t.uint16_t), ("device_id", t.uint16_t), ("version", t.uint8_t), ("group_id_count", t.uint8_t), ("sort", t.uint8_t), ] class EndpointInfoRecord(t.Struct): _fields = [ ("nwk", t.NWK), ("endpoint_id", t.uint8_t), ("profile_id", t.uint16_t), ("device_id", t.uint16_t), ("version", t.uint8_t), ] class GroupInfoRecord(t.Struct): _fields = [("group_id", t.Group), ("group_type", t.uint8_t)] class LightLink(Cluster): cluster_id = 0x1000 ep_attribute = "lightlink" attributes = {} server_commands = { 0x0000: ("scan", (t.uint32_t, t.bitmap8, t.bitmap8), False), 0x0002: ("device_information", (t.uint32_t, t.uint8_t), False), 0x0006: ("identify", (t.uint32_t, t.uint16_t), False), 0x0007: ("reset_to_factory_new", (t.uint32_t,), False), 0x0010: ("network_start", NET_START, False), 0x0012: ("network_join_router", NET_JOIN, False), 0x0014: ("network_join_end_device", NET_JOIN, False), 0x0016: ( "network_update", (t.uint32_t, t.EUI64, t.uint8_t, t.uint8_t, t.NWK, t.NWK), False, ), 0x0041: ("get_group_identifiers", (t.uint8_t,), False), 0x0042: ("get_endpoint_list", (t.uint8_t,), False), } client_commands = { 0x0001: ( "scan_rsp", ( t.uint32_t, t.uint8_t, t.bitmap8, t.bitmap8, t.bitmap16, t.uint32_t, t.EUI64, t.uint8_t, t.uint8_t, t.NWK, t.NWK, t.uint8_t, t.uint8_t, t.Optional(t.uint8_t), t.Optional(t.uint16_t), t.Optional(t.uint16_t), t.Optional(t.uint8_t), t.Optional(t.uint8_t), ), True, ), 0x0003: ( "device_information_rsp", (t.uint32_t, t.uint8_t, t.uint8_t, t.LVList(DeviceInfoRecord)), True, ), 0x0011: ( "network_start_rsp", (t.uint32_t, foundation.Status, t.EUI64, t.uint8_t, t.uint8_t, t.uint16_t), True, ), 0x0013: ("network_join_router_rsp", (t.uint32_t, foundation.Status), True), 0x0015: ("network_join_end_device_rsp", (t.uint32_t, foundation.Status), True), 0x0040: ( "endpoint_information", (t.EUI64, t.NWK, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t), True, ), 0x0041: ( "get_group_identifiers_rsp", (t.uint8_t, t.uint8_t, t.LVList(GroupInfoRecord)), True, ), 0x0042: ( "get_endpoint_list_rsp", (t.uint8_t, t.uint8_t, t.LVList(EndpointInfoRecord)), True, ), }
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/lightlink.py
lightlink.py
import zigpy.types as t from zigpy.zcl import Cluster class Color(Cluster): """Attributes and commands for controlling the color properties of a color-capable light""" cluster_id = 0x0300 name = "Color Control" ep_attribute = "light_color" attributes = { # Color Information 0x0000: ("current_hue", t.uint8_t), 0x0001: ("current_saturation", t.uint8_t), 0x0002: ("remaining_time", t.uint16_t), 0x0003: ("current_x", t.uint16_t), 0x0004: ("current_y", t.uint16_t), 0x0005: ("drift_compensation", t.enum8), 0x0006: ("compensation_text", t.CharacterString), 0x0007: ("color_temperature", t.uint16_t), 0x0008: ("color_mode", t.enum8), # Defined Primaries Information 0x0010: ("num_primaries", t.uint8_t), 0x0011: ("primary1_x", t.uint16_t), 0x0012: ("primary1_y", t.uint16_t), 0x0013: ("primary1_intensity", t.uint8_t), 0x0015: ("primary2_x", t.uint16_t), 0x0016: ("primary2_y", t.uint16_t), 0x0017: ("primary2_intensity", t.uint8_t), 0x0019: ("primary3_x", t.uint16_t), 0x001A: ("primary3_y", t.uint16_t), 0x001B: ("primary3_intensity", t.uint8_t), # Additional Defined Primaries Information 0x0020: ("primary4_x", t.uint16_t), 0x0021: ("primary4_y", t.uint16_t), 0x0022: ("primary4_intensity", t.uint8_t), 0x0024: ("primary5_x", t.uint16_t), 0x0025: ("primary5_y", t.uint16_t), 0x0026: ("primary5_intensity", t.uint8_t), 0x0028: ("primary6_x", t.uint16_t), 0x0029: ("primary6_y", t.uint16_t), 0x002A: ("primary6_intensity", t.uint8_t), # Defined Color Point Settings 0x0030: ("white_point_x", t.uint16_t), 0x0031: ("white_point_y", t.uint16_t), 0x0032: ("color_point_r_x", t.uint16_t), 0x0033: ("color_point_r_y", t.uint16_t), 0x0034: ("color_point_r_intensity", t.uint8_t), 0x0036: ("color_point_g_x", t.uint16_t), 0x0037: ("color_point_g_y", t.uint16_t), 0x0038: ("color_point_g_intensity", t.uint8_t), 0x003A: ("color_point_b_x", t.uint16_t), 0x003B: ("color_point_b_y", t.uint16_t), 0x003C: ("color_point_b_intensity", t.uint8_t), # ... 0x4000: ("enhanced_current_hue", t.uint16_t), 0x4001: ("enhanced_color_mode", t.enum8), 0x4002: ("color_loop_active", t.uint8_t), 0x4003: ("color_loop_direction", t.uint8_t), 0x4004: ("color_loop_time", t.uint16_t), 0x4005: ("color_loop_start_enhanced_hue", t.uint16_t), 0x4006: ("color_loop_stored_enhanced_hue", t.uint16_t), 0x400A: ("color_capabilities", t.bitmap16), 0x400B: ("color_temp_physical_min", t.uint16_t), 0x400C: ("color_temp_physical_max", t.uint16_t), } server_commands = { 0x0000: ( "move_to_hue", (t.uint8_t, t.uint8_t, t.uint16_t), False, ), # hue, direction, duration 0x0001: ("move_hue", (t.uint8_t, t.uint8_t), False), # move mode, rate 0x0002: ( "step_hue", (t.uint8_t, t.uint8_t, t.uint8_t), False, ), # mode, size, duration 0x0003: ( "move_to_saturation", (t.uint8_t, t.uint16_t), False, ), # saturation, duration 0x0004: ("move_saturation", (t.uint8_t, t.uint8_t), False), # mode, rate 0x0005: ( "step_saturation", (t.uint8_t, t.uint8_t, t.uint8_t), False, ), # mode, size, duration 0x0006: ( "move_to_hue_and_saturation", (t.uint8_t, t.uint8_t, t.uint16_t), False, ), # hue, saturation, duration 0x0007: ( "move_to_color", (t.uint16_t, t.uint16_t, t.uint16_t), False, ), # x, y, duration 0x0008: ("move_color", (t.uint16_t, t.uint16_t), False), # ratex, ratey 0x0009: ( "step_color", (t.uint16_t, t.uint16_t, t.uint16_t), False, ), # stepx, stepy, duration 0x000A: ( "move_to_color_temp", (t.uint16_t, t.uint16_t), False, ), # temperature, duration 0x0040: ("enhanced_move_to_hue", (), False), 0x0041: ("enhanced_move_hue", (), False), 0x0042: ("enhanced_step_hue", (), False), 0x0043: ("enhanced_move_to_hue_and_saturation", (), False), 0x0044: ( "color_loop_set", (t.bitmap8, t.enum8, t.enum8, t.uint16_t, t.uint16_t), False, ), 0x0047: ("stop_move_step", (), False), 0x004B: ( "move_color_temp", (t.bitmap8, t.uint16_t, t.uint16_t, t.uint16_t), False, ), 0x004C: ( "step_color_temp", (t.bitmap8, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t), False, ), } client_commands = {} class Ballast(Cluster): """Attributes and commands for configuring a lighting ballast""" cluster_id = 0x0301 ep_attribute = "light_ballast" attributes = { # Ballast Information 0x0000: ("physical_min_level", t.uint8_t), 0x0001: ("physical_max_level", t.uint8_t), 0x0002: ("ballast_status", t.bitmap8), # Ballast Settings 0x0010: ("min_level", t.uint8_t), 0x0011: ("max_level", t.uint8_t), 0x0012: ("power_on_level", t.uint8_t), 0x0013: ("power_on_fade_time", t.uint16_t), 0x0014: ("intrinsic_ballast_factor", t.uint8_t), 0x0015: ("ballast_factor_adjustment", t.uint8_t), # Lamp Information 0x0020: ("lamp_quantity", t.uint8_t), # Lamp Settings 0x0030: ("lamp_type", t.LimitedCharString(16)), 0x0031: ("lamp_manufacturer", t.LimitedCharString(16)), 0x0032: ("lamp_rated_hours", t.uint24_t), 0x0033: ("lamp_burn_hours", t.uint24_t), 0x0034: ("lamp_alarm_mode", t.bitmap8), 0x0035: ("lamp_burn_hours_trip_point", t.uint24_t), } server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/lighting.py
lighting.py
import zigpy.types as t from zigpy.zcl import Cluster class DateTime(t.Struct): _fields = [("date", t.uint32_t), ("time", t.uint32_t)] class GenericTunnel(Cluster): cluster_id = 0x0600 ep_attribute = "generic_tunnel" attributes = { 0x0001: ("max_income_trans_size", t.uint16_t), 0x0002: ("max_outgo_trans_size", t.uint16_t), 0x0003: ("protocol_addr", t.LVBytes), } server_commands = {0x0000: ("match_protocol_addr", (), False)} client_commands = { 0x0000: ("match_protocol_addr_response", (), True), 0x0001: ("advertise_protocol_address", (), False), } class BacnetProtocolTunnel(Cluster): cluster_id = 0x0601 ep_attribute = "bacnet_tunnel" attributes = {} server_commands = {0x0000: ("transfer_npdu", (t.LVBytes,), False)} client_commands = {} class AnalogInputRegular(Cluster): cluster_id = 0x0602 ep_attribute = "bacnet_regular_analog_input" attributes = { 0x0016: ("cov_increment", t.Single), 0x001F: ("device_type", t.CharacterString), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x0076: ("update_interval", t.uint8_t), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class AnalogInputExtended(Cluster): cluster_id = 0x0603 ep_attribute = "bacnet_extended_analog_input" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0011: ("notification_class", t.uint16_t), 0x0019: ("deadband", t.Single), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x002D: ("high_limit", t.Single), 0x0034: ("limit_enable", t.bitmap8), 0x003B: ("low_limit", t.Single), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array) # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = { 0x0000: ("transfer_apdu", (), False), 0x0001: ("connect_req", (), False), 0x0002: ("disconnect_req", (), False), 0x0003: ("connect_status_noti", (), False), } client_commands = {} class AnalogOutputRegular(Cluster): cluster_id = 0x0604 ep_attribute = "bacnet_regular_analog_output" attributes = { 0x0016: ("cov_increment", t.Single), 0x001F: ("device_type", t.CharacterString), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x0076: ("update_interval", t.uint8_t), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class AnalogOutputExtended(Cluster): cluster_id = 0x0605 ep_attribute = "bacnet_extended_analog_output" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0011: ("notification_class", t.uint16_t), 0x0019: ("deadband", t.Single), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x002D: ("high_limit", t.Single), 0x0034: ("limit_enable", t.bitmap8), 0x003B: ("low_limit", t.Single), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array)# Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class AnalogValueRegular(Cluster): cluster_id = 0x0606 ep_attribute = "bacnet_regular_analog_value" attributes = { 0x0016: ("cov_increment", t.Single), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class AnalogValueExtended(Cluster): cluster_id = 0x0607 ep_attribute = "bacnet_extended_analog_value" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0011: ("notification_class", t.uint16_t), 0x0019: ("deadband", t.Single), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x002D: ("high_limit", t.Single), 0x0034: ("limit_enable", t.bitmap8), 0x003B: ("low_limit", t.Single), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class BinaryInputRegular(Cluster): cluster_id = 0x0608 ep_attribute = "bacnet_regular_binary_input" attributes = { 0x000F: ("change_of_state_count", t.uint32_t), 0x0010: ("change_of_state_time", DateTime), 0x001F: ("device_type", t.CharacterString), 0x0021: ("elapsed_active_time", t.uint32_t), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x0072: ("time_of_at_reset", DateTime), 0x0073: ("time_of_sc_reset", DateTime), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class BinaryInputExtended(Cluster): cluster_id = 0x0609 ep_attribute = "bacnet_extended_binary_input" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0006: ("alarm_value", t.Bool), 0x0011: ("notification_class", t.uint16_t), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class BinaryOutputRegular(Cluster): cluster_id = 0x060A ep_attribute = "bacnet_regular_binary_output" attributes = { 0x000F: ("change_of_state_count", t.uint32_t), 0x0010: ("change_of_state_time", DateTime), 0x001F: ("device_type", t.CharacterString), 0x0021: ("elapsed_active_time", t.uint32_t), 0x0028: ("feed_back_value", t.enum8), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x0072: ("time_of_at_reset", DateTime), 0x0073: ("time_of_sc_reset", DateTime), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class BinaryOutputExtended(Cluster): cluster_id = 0x060B ep_attribute = "bacnet_extended_binary_output" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0011: ("notification_class", t.uint16_t), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class BinaryValueRegular(Cluster): cluster_id = 0x060C ep_attribute = "bacnet_regular_binary_value" attributes = { 0x000F: ("change_of_state_count", t.uint32_t), 0x0010: ("change_of_state_time", DateTime), 0x0021: ("elapsed_active_time", t.uint32_t), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x0072: ("time_of_at_reset", DateTime), 0x0073: ("time_of_sc_reset", DateTime), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class BinaryValueExtended(Cluster): cluster_id = 0x060D ep_attribute = "bacnet_extended_binary_value" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0006: ("alarm_value", t.Bool), 0x0011: ("notification_class", t.uint16_t), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class MultistateInputRegular(Cluster): cluster_id = 0x060E ep_attribute = "bacnet_regular_multistate_input" attributes = { 0x001F: ("device_type", t.CharacterString), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class MultistateInputExtended(Cluster): cluster_id = 0x060F ep_attribute = "bacnet_extended_multistate_input" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0006: ("alarm_value", t.uint16_t), 0x0011: ("notification_class", t.uint16_t), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x0025: ("fault_values", t.uint16_t), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class MultistateOutputRegular(Cluster): cluster_id = 0x0610 ep_attribute = "bacnet_regular_multistate_output" attributes = { 0x001F: ("device_type", t.CharacterString), 0x0028: ("feed_back_value", t.enum8), 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class MultistateOutputExtended(Cluster): cluster_id = 0x0611 ep_attribute = "bacnet_extended_multistate_output" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0011: ("notification_class", t.uint16_t), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {} class MultistateValueRegular(Cluster): cluster_id = 0x0612 ep_attribute = "bacnet_regular_multistate_value" attributes = { 0x004B: ("object_id", t.fixed_list(4, t.uint8_t)), 0x004D: ("object_name", t.CharacterString), 0x004F: ("object_type", t.enum16), 0x00A8: ("profile_name", t.CharacterString), } server_commands = {} client_commands = {} class MultistateValueExtended(Cluster): cluster_id = 0x0613 ep_attribute = "bacnet_extended_multistate_value" attributes = { 0x0000: ("acked_transitions", t.bitmap8), 0x0006: ("alarm_value", t.uint16_t), 0x0011: ("notification_class", t.uint16_t), 0x0023: ("event_enable", t.bitmap8), 0x0024: ("event_state", t.enum8), 0x0025: ("fault_values", t.uint16_t), 0x0048: ("notify_type", t.enum8), 0x0071: ("time_delay", t.uint8_t), # 0x0082: ('event_time_stamps', TODO.array), # Array[3] of (16-bit unsigned # integer, time of day, or structure of (date, time of day)) } server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/protocol.py
protocol.py
import zigpy.types as t from zigpy.zcl import Cluster class IlluminanceMeasurement(Cluster): cluster_id = 0x0400 name = "Illuminance Measurement" ep_attribute = "illuminance" attributes = { # Illuminance Measurement Information 0x0000: ("measured_value", t.uint16_t), 0x0001: ("min_measured_value", t.uint16_t), 0x0002: ("max_measured_value", t.uint16_t), 0x0003: ("tolerance", t.uint16_t), 0x0004: ("light_sensor_type", t.enum8), } server_commands = {} client_commands = {} class IlluminanceLevelSensing(Cluster): cluster_id = 0x0401 name = "Illuminance Level Sensing" ep_attribute = "illuminance_level" attributes = { # Illuminance Level Sensing Information 0x0000: ("level_status", t.enum8), 0x0001: ("light_sensor_type", t.enum8), # Illuminance Level Sensing Settings 0x0010: ("illuminance_target_level", t.uint16_t), } server_commands = {} client_commands = {} class TemperatureMeasurement(Cluster): cluster_id = 0x0402 name = "Temperature Measurement" ep_attribute = "temperature" attributes = { # Temperature Measurement Information 0x0000: ("measured_value", t.int16s), 0x0001: ("min_measured_value", t.int16s), 0x0002: ("max_measured_value", t.int16s), 0x0003: ("tolerance", t.uint16_t), # 0x0010: ('min_percent_change', UNKNOWN), # 0x0011: ('min_absolute_change', UNKNOWN), } server_commands = {} client_commands = {} class PressureMeasurement(Cluster): cluster_id = 0x0403 name = "Pressure Measurement" ep_attribute = "pressure" attributes = { # Pressure Measurement Information 0x0000: ("measured_value", t.int16s), 0x0001: ("min_measured_value", t.int16s), 0x0002: ("max_measured_value", t.int16s), 0x0003: ("tolerance", t.uint16_t), } server_commands = {} client_commands = {} class FlowMeasurement(Cluster): cluster_id = 0x0404 name = "Flow Measurement" ep_attribute = "flow" attributes = { # Flow Measurement Information 0x0000: ("measured_value", t.uint16_t), 0x0001: ("min_measured_value", t.uint16_t), 0x0002: ("max_measured_value", t.uint16_t), 0x0003: ("tolerance", t.uint16_t), } server_commands = {} client_commands = {} class RelativeHumidity(Cluster): cluster_id = 0x0405 name = "Relative Humidity Measurement" ep_attribute = "humidity" attributes = { # Relative Humidity Measurement Information 0x0000: ("measured_value", t.uint16_t), 0x0001: ("min_measured_value", t.uint16_t), 0x0002: ("max_measured_value", t.uint16_t), 0x0003: ("tolerance", t.uint16_t), } server_commands = {} client_commands = {} class OccupancySensing(Cluster): cluster_id = 0x0406 name = "Occupancy Sensing" ep_attribute = "occupancy" attributes = { # Occupancy Sensor Information 0x0000: ("occupancy", t.bitmap8), 0x0001: ("occupancy_sensor_type", t.enum8), # PIR Configuration 0x0010: ("pir_o_to_u_delay", t.uint16_t), 0x0011: ("pir_u_to_o_delay", t.uint16_t), 0x0012: ("pir_u_to_o_threshold", t.uint8_t), # Ultrasonic Configuration 0x0020: ("ultrasonic_o_to_u_delay", t.uint16_t), 0x0021: ("ultrasonic_u_to_o_delay", t.uint16_t), 0x0022: ("ultrasonic_u_to_o_threshold", t.uint8_t), } server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/measurement.py
measurement.py
import zigpy.types as t from zigpy.zcl import Cluster class ApplianceIdentification(Cluster): cluster_id = 0x0B00 name = "Appliance Identification" ep_attribute = "appliance_id" attributes = { 0x0000: ("basic_identification", t.uint56_t), 0x0010: ("company_name", t.CharacterString), 0x0011: ("company_id", t.uint16_t), 0x0012: ("brand_name", t.CharacterString), 0x0013: ("brand_id", t.uint16_t), 0x0014: ("model", t.CharacterString), 0x0015: ("part_number", t.CharacterString), 0x0016: ("product_revision", t.CharacterString), 0x0017: ("software_revision", t.CharacterString), 0x0018: ("product_type_name", t.CharacterString), 0x0019: ("product_type_id", t.uint16_t), 0x001A: ("ceced_specification_version", t.uint8_t), } server_commands = {} client_commands = {} class MeterIdentification(Cluster): cluster_id = 0x0B01 name = "Meter Identification" ep_attribute = "meter_id" attributes = { 0x0000: ("company_name", t.LimitedCharString(16)), 0x0001: ("meter_type_id", t.uint16_t), 0x0004: ("data_quality_id", t.uint16_t), 0x0005: ("customer_name", t.LimitedCharString(16)), 0x0006: ("model", t.LimitedCharString(16)), 0x0007: ("part_number", t.LimitedCharString(16)), 0x0008: ("product_revision", t.LimitedCharString(6)), 0x000A: ("software_revision", t.LimitedCharString(6)), 0x000B: ("utility_name", t.LimitedCharString(16)), 0x000C: ("pod", t.LimitedCharString(16)), 0x000D: ("available_power", t.int24s), 0x000E: ("power_threshold", t.int24s), } server_commands = {} client_commands = {} class ApplianceEventAlerts(Cluster): cluster_id = 0x0B02 name = "Appliance Event Alerts" ep_attribute = "appliance_event" attributes = {} server_commands = {0x0000: ("get_alerts", (), False)} client_commands = { 0x0000: ("get_alarts_response", (), True), 0x0001: ("alerts_notification", (), False), 0x0002: ("event_notification", (), False), } class ApplianceStatistics(Cluster): cluster_id = 0x0B03 name = "Appliance Statistics" ep_attribute = "appliance_stats" attributes = { 0x0000: ("log_max_size", t.uint32_t), 0x0001: ("log_queue_max_size", t.uint8_t), } server_commands = {0x0000: ("log", (), False), 0x0001: ("log_queue", (), False)} client_commands = { 0x0000: ("log_notification", (), False), 0x0001: ("log_response", (), True), 0x0002: ("log_queue_response", (), True), 0x0003: ("statistics_available", (), False), } class ElectricalMeasurement(Cluster): cluster_id = 0x0B04 name = "Electrical Measurement" ep_attribute = "electrical_measurement" attributes = { # Basic Information 0x0000: ("measurement_type", t.bitmap32), # DC Measurement 0x0100: ("dc_voltage", t.int16s), 0x0101: ("dc_voltage_min", t.int16s), 0x0102: ("dcvoltagemax", t.int16s), 0x0103: ("dc_current", t.int16s), 0x0104: ("dc_current_min", t.int16s), 0x0105: ("dc_current_max", t.int16s), 0x0106: ("dc_power", t.int16s), 0x0107: ("dc_power_min", t.int16s), 0x0108: ("dc_power_max", t.int16s), # DC Formatting 0x0200: ("dc_voltage_multiplier", t.uint16_t), 0x0201: ("dc_voltage_divisor", t.uint16_t), 0x0202: ("dc_current_multiplier", t.uint16_t), 0x0203: ("dc_current_divisor", t.uint16_t), 0x0204: ("dc_power_multiplier", t.uint16_t), 0x0205: ("dc_power_divisor", t.uint16_t), # AC (Non-phase Specific) Measurements 0x0300: ("ac_frequency", t.uint16_t), 0x0301: ("ac_frequency_min", t.uint16_t), 0x0302: ("ac_frequency_max", t.uint16_t), 0x0303: ("neutral_current", t.uint16_t), 0x0304: ("total_active_power", t.int32s), 0x0305: ("total_reactive_power", t.int32s), 0x0306: ("total_apparent_power", t.uint32_t), 0x0307: ("meas1st_harmonic_current", t.int16s), 0x0308: ("meas3rd_harmonic_current", t.int16s), 0x0309: ("meas5th_harmonic_current", t.int16s), 0x030A: ("meas7th_harmonic_current", t.int16s), 0x030B: ("meas9th_harmonic_current", t.int16s), 0x030C: ("meas11th_harmonic_current", t.int16s), 0x030D: ("meas_phase1st_harmonic_current", t.int16s), 0x030E: ("meas_phase3rd_harmonic_current", t.int16s), 0x030F: ("meas_phase5th_harmonic_current", t.int16s), 0x0310: ("meas_phase7th_harmonic_current", t.int16s), 0x0311: ("meas_phase9th_harmonic_current", t.int16s), 0x0312: ("meas_phase11th_harmonic_current", t.int16s), # AC (Non-phase specific) Formatting 0x0400: ("ac_frequency_multiplier", t.uint16_t), 0x0401: ("ac_frequency_divisor", t.uint16_t), 0x0402: ("power_multiplier", t.uint32_t), 0x0403: ("power_divisor", t.uint32_t), 0x0404: ("harmonic_current_multiplier", t.int8s), 0x0405: ("phase_harmonic_current_multiplier", t.int8s), # AC (Single Phase or Phase A) Measurements 0x0500: ("instantaneous_voltage", t.int16s), 0x0501: ("instantaneous_line_current", t.uint16_t), 0x0502: ("instantaneous_active_current", t.int16s), 0x0503: ("instantaneous_reactive_current", t.int16s), 0x0504: ("instantaneous_power", t.int16s), 0x0505: ("rms_voltage", t.uint16_t), 0x0506: ("rms_voltage_min", t.uint16_t), 0x0507: ("rms_voltage_max", t.uint16_t), 0x0508: ("rms_current", t.uint16_t), 0x0509: ("rms_current_min", t.uint16_t), 0x050A: ("rms_current_max", t.uint16_t), 0x050B: ("active_power", t.int16s), 0x050C: ("active_power_min", t.int16s), 0x050D: ("active_power_max", t.int16s), 0x050E: ("reactive_power", t.int16s), 0x050F: ("apparent_power", t.uint16_t), 0x0510: ("power_factor", t.int8s), 0x0511: ("average_rms_voltage_meas_period", t.uint16_t), 0x0512: ("average_rms_over_voltage_counter", t.uint16_t), 0x0513: ("average_rms_under_voltage_counter", t.uint16_t), 0x0514: ("rms_extreme_over_voltage_period", t.uint16_t), 0x0515: ("rms_extreme_under_voltage_period", t.uint16_t), 0x0516: ("rms_voltage_sag_period", t.uint16_t), 0x0517: ("rms_voltage_swell_period", t.uint16_t), # AC Formatting 0x0600: ("ac_voltage_multiplier", t.uint16_t), 0x0601: ("ac_voltage_divisor", t.uint16_t), 0x0602: ("ac_current_multiplier", t.uint16_t), 0x0603: ("ac_current_divisor", t.uint16_t), 0x0604: ("ac_power_multiplier", t.uint16_t), 0x0605: ("ac_power_divisor", t.uint16_t), # DC Manufacturer Threshold Alarms 0x0700: ("dc_overload_alarms_mask", t.bitmap8), 0x0701: ("dc_voltage_overload", t.int16s), 0x0702: ("dc_current_overload", t.int16s), # AC Manufacturer Threshold Alarms 0x0800: ("ac_alarms_mask", t.bitmap16), 0x0801: ("ac_voltage_overload", t.int16s), 0x0802: ("ac_current_overload", t.int16s), 0x0803: ("ac_active_power_overload", t.int16s), 0x0804: ("ac_reactive_power_overload", t.int16s), 0x0805: ("average_rms_over_voltage", t.int16s), 0x0806: ("average_rms_under_voltage", t.int16s), 0x0807: ("rms_extreme_over_voltage", t.int16s), 0x0808: ("rms_extreme_under_voltage", t.int16s), 0x0809: ("rms_voltage_sag", t.int16s), 0x080A: ("rms_voltage_swell", t.int16s), # AC Phase B Measurements 0x0901: ("line_current_ph_b", t.uint16_t), 0x0902: ("active_current_ph_b", t.int16s), 0x0903: ("reactive_current_ph_b", t.int16s), 0x0905: ("rms_voltage_ph_b", t.uint16_t), 0x0906: ("rms_voltage_min_ph_b", t.uint16_t), 0x0907: ("rms_voltage_max_ph_b", t.uint16_t), 0x0908: ("rms_current_ph_b", t.uint16_t), 0x0909: ("rms_current_min_ph_b", t.uint16_t), 0x090A: ("rms_current_max_ph_b", t.uint16_t), 0x090B: ("active_power_ph_b", t.int16s), 0x090C: ("active_power_min_ph_b", t.int16s), 0x090D: ("active_power_max_ph_b", t.int16s), 0x090E: ("reactive_power_ph_b", t.int16s), 0x090F: ("apparent_power_ph_b", t.uint16_t), 0x0910: ("power_factor_ph_b", t.int8s), 0x0911: ("average_rms_voltage_measure_period_ph_b", t.uint16_t), 0x0912: ("average_rms_over_voltage_counter_ph_b", t.uint16_t), 0x0913: ("average_under_voltage_counter_ph_b", t.uint16_t), 0x0914: ("rms_extreme_over_voltage_period_ph_b", t.uint16_t), 0x0915: ("rms_extreme_under_voltage_period_ph_b", t.uint16_t), 0x0916: ("rms_voltage_sag_period_ph_b", t.uint16_t), 0x0917: ("rms_voltage_swell_period_ph_b", t.uint16_t), # AC Phase C Measurements 0x0A01: ("line_current_ph_c", t.uint16_t), 0x0A02: ("active_current_ph_c", t.int16s), 0x0A03: ("reactive_current_ph_c", t.int16s), 0x0A05: ("rms_voltage_ph_c", t.uint16_t), 0x0A06: ("rms_voltage_min_ph_c", t.uint16_t), 0x0A07: ("rms_voltage_max_ph_c", t.uint16_t), 0x0A08: ("rms_current_ph_c", t.uint16_t), 0x0A09: ("rms_current_min_ph_c", t.uint16_t), 0x0A0A: ("rms_current_max_ph_c", t.uint16_t), 0x0A0B: ("active_power_ph_c", t.int16s), 0x0A0C: ("active_power_min_ph_c", t.int16s), 0x0A0D: ("active_power_max_ph_c", t.int16s), 0x0A0E: ("reactive_power_ph_c", t.int16s), 0x0A0F: ("apparent_power_ph_c", t.uint16_t), 0x0A10: ("power_factor_ph_c", t.int8s), 0x0A11: ("average_rms_voltage_meas_period_ph_c", t.uint16_t), 0x0A12: ("average_rms_over_voltage_counter_ph_c", t.uint16_t), 0x0A13: ("average_under_voltage_counter_ph_c", t.uint16_t), 0x0A14: ("rms_extreme_over_voltage_period_ph_c", t.uint16_t), 0x0A15: ("rms_extreme_under_voltage_period_ph_c", t.uint16_t), 0x0A16: ("rms_voltage_sag_period_ph_c", t.uint16_t), 0x0A17: ("rms_voltage_swell_period_ph__c", t.uint16_t), } server_commands = { 0x0000: ("get_profile_info", (), False), 0x0001: ("get_measurement_profile", (), False), } client_commands = { 0x0000: ("get_profile_info_response", (), True), 0x0001: ("get_measurement_profile_response", (), True), } class Diagnostic(Cluster): cluster_id = 0x0B05 ep_attribute = "diagnostic" attributes = { # Hardware Information 0x0000: ("number_of_resets", t.uint16_t), 0x0001: ("persistent_memory_writes", t.uint16_t), # Stack/Network Information 0x0100: ("mac_rx_bcast", t.uint32_t), 0x0101: ("mac_tx_bcast", t.uint32_t), 0x0102: ("mac_rx_ucast", t.uint32_t), 0x0103: ("mac_tx_ucast", t.uint32_t), 0x0104: ("mac_tx_ucast_retry", t.uint16_t), 0x0105: ("mac_tx_ucast_fail", t.uint16_t), 0x0106: ("aps_rx_bcast", t.uint16_t), 0x0107: ("aps_tx_bcast", t.uint16_t), 0x0108: ("aps_rx_ucast", t.uint16_t), 0x0109: ("aps_tx_ucast_success", t.uint16_t), 0x010A: ("aps_tx_ucast_retry", t.uint16_t), 0x010B: ("aps_tx_ucast_fail", t.uint16_t), 0x010C: ("route_disc_initiated", t.uint16_t), 0x010D: ("neighbor_added", t.uint16_t), 0x010E: ("neighbor_removed", t.uint16_t), 0x010F: ("neighbor_stale", t.uint16_t), 0x0110: ("join_indication", t.uint16_t), 0x0111: ("child_moved", t.uint16_t), 0x0112: ("nwk_fc_failure", t.uint16_t), 0x0113: ("aps_fc_failure", t.uint16_t), 0x0114: ("aps_unauthorized_key", t.uint16_t), 0x0115: ("nwk_decrypt_failures", t.uint16_t), 0x0116: ("aps_decrypt_failures", t.uint16_t), 0x0117: ("packet_buffer_allocate_failures", t.uint16_t), 0x0118: ("relayed_ucast", t.uint16_t), 0x0119: ("phy_to_mac_queue_limit_reached", t.uint16_t), 0x011A: ("packet_validate_drop_count", t.uint16_t), 0x011B: ("average_mac_retry_per_aps_message_sent", t.uint16_t), 0x011C: ("last_message_lqi", t.uint8_t), 0x011D: ("last_message_rssi", t.int8s), } server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/homeautomation.py
homeautomation.py
import zigpy.types as t from zigpy.zcl import Cluster class Price(Cluster): cluster_id = 0x0700 ep_attribute = "smartenergy_price" attributes = {} server_commands = {} client_commands = {} class Drlc(Cluster): cluster_id = 0x0701 ep_attribute = "smartenergy_drlc" attributes = {} server_commands = {} client_commands = {} class Metering(Cluster): cluster_id = 0x0702 ep_attribute = "smartenergy_metering" attributes = { 0x0000: ("current_summ_delivered", t.uint48_t), 0x0001: ("current_summ_received", t.uint48_t), 0x0002: ("current_max_demand_delivered", t.uint48_t), 0x0003: ("current_max_demand_received", t.uint48_t), 0x0004: ("dft_summ", t.uint48_t), 0x0005: ("daily_freeze_time", t.uint16_t), 0x0006: ("power_factor", t.int8s), 0x0007: ("reading_snapshot_time", t.uint32_t), 0x0008: ("current_max_demand_deliverd_time", t.uint32_t), 0x0009: ("current_max_demand_received_time", t.uint32_t), 0x000A: ("default_update_period", t.uint8_t), 0x000B: ("fast_poll_update_period", t.uint8_t), 0x000C: ("current_block_period_consump_delivered", t.uint48_t), 0x000D: ("daily_consump_target", t.uint24_t), 0x000E: ("current_block", t.enum8), 0x000F: ("profile_interval_period", t.enum8), # 0x0010: ('interval_read_reporting_period', UNKNOWN), 0x0011: ("preset_reading_time", t.uint16_t), 0x0012: ("volume_per_report", t.uint16_t), 0x0013: ("flow_restriction", t.uint8_t), 0x0014: ("supply_status", t.enum8), 0x0015: ("current_in_energy_carrier_summ", t.uint48_t), 0x0016: ("current_out_energy_carrier_summ", t.uint48_t), 0x0017: ("inlet_tempreature", t.int24s), 0x0018: ("outlet_tempreature", t.int24s), 0x0019: ("control_tempreature", t.int24s), 0x001A: ("current_in_energy_carrier_demand", t.int24s), 0x001B: ("current_out_energy_carrier_demand", t.int24s), 0x001D: ("current_block_period_consump_received", t.uint48_t), 0x001E: ("current_block_received", t.uint48_t), # 0x0100: ('change_reporting_profile', UNKNOWN), 0x0100: ("current_tier1_summ_delivered", t.uint48_t), 0x0101: ("current_tier1_summ_received", t.uint48_t), 0x0102: ("current_tier2_summ_delivered", t.uint48_t), 0x0103: ("current_tier2_summ_received", t.uint48_t), 0x0104: ("current_tier3_summ_delivered", t.uint48_t), 0x0105: ("current_tier3_summ_received", t.uint48_t), 0x0106: ("current_tier4_summ_delivered", t.uint48_t), 0x0107: ("current_tier4_summ_received", t.uint48_t), 0x0108: ("current_tier5_summ_delivered", t.uint48_t), 0x0109: ("current_tier5_summ_received", t.uint48_t), 0x010A: ("current_tier6_summ_delivered", t.uint48_t), 0x010B: ("current_tier6_summ_received", t.uint48_t), 0x010C: ("current_tier7_summ_delivered", t.uint48_t), 0x010D: ("current_tier7_summ_received", t.uint48_t), 0x010E: ("current_tier8_summ_delivered", t.uint48_t), 0x010F: ("current_tier8_summ_received", t.uint48_t), 0x0110: ("current_tier9_summ_delivered", t.uint48_t), 0x0111: ("current_tier9_summ_received", t.uint48_t), 0x0112: ("current_tier10_summ_delivered", t.uint48_t), 0x0113: ("current_tier10_summ_received", t.uint48_t), 0x0114: ("current_tier11_summ_delivered", t.uint48_t), 0x0115: ("current_tier11_summ_received", t.uint48_t), 0x0116: ("current_tier12_summ_delivered", t.uint48_t), 0x0117: ("current_tier12_summ_received", t.uint48_t), 0x0118: ("current_tier13_summ_delivered", t.uint48_t), 0x0119: ("current_tier13_summ_received", t.uint48_t), 0x011A: ("current_tier14_summ_delivered", t.uint48_t), 0x011B: ("current_tier14_summ_received", t.uint48_t), 0x011C: ("current_tier15_summ_delivered", t.uint48_t), 0x011D: ("current_tier15_summ_received", t.uint48_t), 0x0200: ("status", t.bitmap8), 0x0201: ("remaining_batt_life", t.uint8_t), 0x0202: ("hours_in_operation", t.uint24_t), 0x0203: ("hours_in_fault", t.uint24_t), 0x0204: ("extended_status", t.bitmap64), 0x0300: ("unit_of_measure", t.enum8), 0x0301: ("multiplier", t.uint24_t), 0x0302: ("divisor", t.uint24_t), 0x0303: ("summa_formatting", t.bitmap8), 0x0304: ("demand_formatting", t.bitmap8), 0x0305: ("historical_consump_formatting", t.bitmap8), 0x0306: ("metering_device_type", t.bitmap8), 0x0307: ("site_id", t.LimitedCharString(32)), 0x0308: ("meter_serial_number", t.LimitedCharString(24)), 0x0309: ("energy_carrier_unit_of_meas", t.enum8), 0x030A: ("energy_carrier_summ_formatting", t.bitmap8), 0x030B: ("energy_carrier_demand_formatting", t.bitmap8), 0x030C: ("temperature_unit_of_meas", t.enum8), 0x030D: ("temperature_formatting", t.bitmap8), 0x030E: ("module_serial_number", t.LVBytes), 0x030F: ("operating_tariff_level", t.LVBytes), 0x0400: ("instantaneous_demand", t.int24s), 0x0401: ("currentday_consump_delivered", t.uint24_t), 0x0402: ("currentday_consump_received", t.uint24_t), 0x0403: ("previousday_consump_delivered", t.uint24_t), 0x0404: ("previousday_consump_received", t.uint24_t), 0x0405: ("cur_part_profile_int_start_time_delivered", t.uint32_t), 0x0406: ("cur_part_profile_int_start_time_received", t.uint32_t), 0x0407: ("cur_part_profile_int_value_delivered", t.uint24_t), 0x0408: ("cur_part_profile_int_value_received", t.uint24_t), 0x0409: ("current_day_max_pressure", t.uint48_t), 0x040A: ("current_day_min_pressure", t.uint48_t), 0x040B: ("previous_day_max_pressure", t.uint48_t), 0x040C: ("previous_day_min_pressure", t.uint48_t), 0x040D: ("current_day_max_demand", t.int24s), 0x040E: ("previous_day_max_demand", t.int24s), 0x040F: ("current_month_max_demand", t.int24s), 0x0410: ("current_year_max_demand", t.int24s), 0x0411: ("currentday_max_energy_carr_demand", t.int24s), 0x0412: ("previousday_max_energy_carr_demand", t.int24s), 0x0413: ("cur_month_max_energy_carr_demand", t.int24s), 0x0414: ("cur_month_min_energy_carr_demand", t.int24s), 0x0415: ("cur_year_max_energy_carr_demand", t.int24s), 0x0416: ("cur_year_min_energy_carr_demand", t.int24s), 0x0500: ("max_number_of_periods_delivered", t.uint8_t), 0x0600: ("current_demand_delivered", t.uint24_t), 0x0601: ("demand_limit", t.uint24_t), 0x0602: ("demand_integration_period", t.uint8_t), 0x0603: ("number_of_demand_subintervals", t.uint8_t), 0x0604: ("demand_limit_arm_duration", t.uint16_t), 0x0800: ("generic_alarm_mask", t.bitmap16), 0x0801: ("electricity_alarm_mask", t.bitmap32), 0x0802: ("gen_flow_pressure_alarm_mask", t.bitmap16), 0x0803: ("water_specific_alarm_mask", t.bitmap16), 0x0804: ("heat_cool_specific_alarm_mask", t.bitmap16), 0x0805: ("gas_specific_alarm_mask", t.bitmap16), 0x0806: ("extended_generic_alarm_mask", t.bitmap48), 0x0807: ("manufacture_alarm_mask", t.bitmap16), 0x0A00: ("bill_to_date", t.uint32_t), 0x0A01: ("bill_to_date_time_stamp", t.uint32_t), 0x0A02: ("projected_bill", t.uint32_t), 0x0A03: ("projected_bill_time_stamp", t.uint32_t), } server_commands = { 0x0000: ("get_profile", (), False), 0x0001: ("req_mirror", (), False), 0x0002: ("mirror_rem", (), False), 0x0003: ("req_fast_poll_mode", (), False), 0x0004: ("get_snapshot", (), False), 0x0005: ("take_snapshot", (), False), 0x0006: ("mirror_report_attr_response", (), True), } client_commands = { 0x0000: ("get_profile_response", (), True), 0x0001: ("req_mirror_response", (), True), 0x0002: ("mirror_rem_response", (), True), 0x0003: ("req_fast_poll_mode_response", (), True), 0x0004: ("get_snapshot_response", (), True), } class Messaging(Cluster): cluster_id = 0x0703 ep_attribute = "smartenergy_messaging" attributes = {} server_commands = {} client_commands = {} class Tunneling(Cluster): cluster_id = 0x0704 ep_attribute = "smartenergy_tunneling" attributes = {} server_commands = {} client_commands = {} class Prepayment(Cluster): cluster_id = 0x0705 ep_attribute = "smartenergy_prepayment" attributes = {} server_commands = {} client_commands = {} class EnergyManagement(Cluster): cluster_id = 0x0706 ep_attribute = "smartenergy_energy_management" attributes = {} server_commands = {} client_commands = {} class Calendar(Cluster): cluster_id = 0x0707 ep_attribute = "smartenergy_calendar" attributes = {} server_commands = {} client_commands = {} class DeviceManagement(Cluster): cluster_id = 0x0708 ep_attribute = "smartenergy_device_management" attributes = {} server_commands = {} client_commands = {} class Events(Cluster): cluster_id = 0x0709 ep_attribute = "smartenergy_events" attributes = {} server_commands = {} client_commands = {} class MduPairing(Cluster): cluster_id = 0x070A ep_attribute = "smartenergy_mdu_pairing" attributes = {} server_commands = {} client_commands = {} class KeyEstablishment(Cluster): cluster_id = 0x0800 ep_attribute = "smartenergy_key_establishment" attributes = {} server_commands = {} client_commands = {}
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zcl/clusters/smartenergy.py
smartenergy.py
import collections import itertools import logging import zigpy.quirks _LOGGER = logging.getLogger(__name__) SIG_MODELS_INFO = "models_info" class DeviceRegistry: def __init__(self, *args, **kwargs): dd = collections.defaultdict self._registry = dd(lambda: dd(list)) def add_to_registry(self, custom_device): """Add a device to the registry""" models_info = custom_device.signature.get(SIG_MODELS_INFO) if models_info: for manuf, model in models_info: self.registry[manuf][model].append(custom_device) else: manufacturer = self.get_manufacturer(custom_device) model = self.get_model(custom_device) self.registry[manufacturer][model].append(custom_device) def remove(self, custom_device): models_info = custom_device.signature.get(SIG_MODELS_INFO) if models_info: for manuf, model in models_info: self.registry[manuf][model].remove(custom_device) else: manufacturer = self.get_manufacturer(custom_device) model = self.get_model(custom_device) self.registry[manufacturer][model].remove(custom_device) def get_device(self, device): """Get a CustomDevice object, if one is available""" if isinstance(device, zigpy.quirks.CustomDevice): return device dev_ep = set(device.endpoints) - set([0]) _LOGGER.debug( "Checking quirks for %s %s (%s)", device.manufacturer, device.model, device.ieee, ) for candidate in itertools.chain( self.registry[device.manufacturer][device.model], self.registry[device.manufacturer][None], self.registry[None][None], ): _LOGGER.debug("Considering %s", candidate) sig = candidate.signature.get("endpoints", {}) if not sig: _LOGGER.warning( ( "%s signature update is required. Support for " "`signature = {1: { replacement }}`" " will be removed in the future releases. Use " "`signature = {'endpoints': {1: { replacement }}}" ), candidate, ) sig = { eid: ep for eid, ep in candidate.signature.items() if isinstance(eid, int) } if not device.model == candidate.signature.get("model", device.model): _LOGGER.debug("Fail, because device model mismatch: '%s'", device.model) continue if not ( device.manufacturer == candidate.signature.get("manufacturer", device.manufacturer) ): _LOGGER.debug( "Fail, because device manufacturer mismatch: '%s'", device.manufacturer, ) continue if not self._match(sig, dev_ep): _LOGGER.debug( "Fail because endpoint list mismatch: %s %s", set(sig.keys()), dev_ep, ) continue if not all( [ device[eid].profile_id == sig[eid].get("profile_id", device[eid].profile_id) for eid in sig ] ): _LOGGER.debug( "Fail because profile_id mismatch on at least one endpoint" ) continue if not all( [ device[eid].device_type == sig[eid].get("device_type", device[eid].device_type) for eid in sig ] ): _LOGGER.debug( "Fail because device_type mismatch on at least one endpoint" ) continue if not all( [ device[eid].model == sig[eid].get("model", device[eid].model) for eid in sig ] ): _LOGGER.debug("Fail because model mismatch on at least one endpoint") continue if not all( [ device[eid].manufacturer == sig[eid].get("manufacturer", device[eid].manufacturer) for eid in sig ] ): _LOGGER.debug( "Fail because manufacturer mismatch on at least one endpoint" ) continue if not all( [ self._match(device[eid].in_clusters, ep.get("input_clusters", [])) for eid, ep in sig.items() ] ): _LOGGER.debug( "Fail because input cluster mismatch on at least one endpoint" ) continue if not all( [ self._match(device[eid].out_clusters, ep.get("output_clusters", [])) for eid, ep in sig.items() ] ): _LOGGER.debug( "Fail because output cluster mismatch on at least one endpoint" ) continue _LOGGER.debug( "Found custom device replacement for %s: %s", device.ieee, candidate ) device = candidate(device._application, device.ieee, device.nwk, device) break return device @staticmethod def get_manufacturer(custom_dev): manuf = custom_dev.signature.get("manufacturer") if manuf is None: # Get manufacturer from legacy endpoint sig sig = { eid: ep for eid, ep in custom_dev.signature.items() if isinstance(eid, int) } manuf = next( (ep["manufacturer"] for ep in sig.values() if "manufacturer" in ep), None, ) return manuf @staticmethod def get_model(custom_dev): model = custom_dev.signature.get("model") if model is None: # Get model from legacy endpoint sig sig = { eid: ep for eid, ep in custom_dev.signature.items() if isinstance(eid, int) } model = next((ep["model"] for ep in sig.values() if "model" in ep), None) return model @staticmethod def _match(a, b): return set(a) == set(b) @property def registry(self): return self._registry def __contains__(self, device): manufacturer, model = device.signature.get( SIG_MODELS_INFO, [(self.get_manufacturer(device), self.get_model(device))] )[0] return device in itertools.chain( self.registry[manufacturer][model], self.registry[manufacturer][None], self.registry[None][None], )
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/quirks/registry.py
registry.py
import logging from typing import Any, Dict, Optional import zigpy.device import zigpy.endpoint from zigpy.quirks.registry import DeviceRegistry import zigpy.zcl import zigpy.zcl.foundation as foundation _LOGGER = logging.getLogger(__name__) _DEVICE_REGISTRY = DeviceRegistry() def get_device(device, registry=_DEVICE_REGISTRY): """Get a CustomDevice object, if one is available""" return registry.get_device(device) class Registry(type): def __init__(cls, name, bases, nmspc): # noqa: N805 super(Registry, cls).__init__(name, bases, nmspc) if hasattr(cls, "signature"): _DEVICE_REGISTRY.add_to_registry(cls) class CustomDevice(zigpy.device.Device, metaclass=Registry): replacement = {} def __init__(self, application, ieee, nwk, replaces): super().__init__(application, ieee, nwk) def set_device_attr(attr): if attr in self.replacement: setattr(self, attr, self.replacement[attr]) else: setattr(self, attr, getattr(replaces, attr)) for attr in ("lqi", "rssi", "last_seen", "relays"): setattr(self, attr, getattr(replaces, attr)) set_device_attr("status") set_device_attr("node_desc") set_device_attr("manufacturer") set_device_attr("model") set_device_attr("skip_configuration") for endpoint_id, endpoint in self.replacement.get("endpoints", {}).items(): self.add_endpoint(endpoint_id, replace_device=replaces) def add_endpoint(self, endpoint_id, replace_device=None): if endpoint_id not in self.replacement.get("endpoints", {}): return super().add_endpoint(endpoint_id) endpoints = self.replacement["endpoints"] if isinstance(endpoints[endpoint_id], tuple): custom_ep_type = endpoints[endpoint_id][0] replacement_data = endpoints[endpoint_id][1] else: custom_ep_type = CustomEndpoint replacement_data = endpoints[endpoint_id] ep = custom_ep_type(self, endpoint_id, replacement_data, replace_device) self.endpoints[endpoint_id] = ep return ep class CustomEndpoint(zigpy.endpoint.Endpoint): def __init__(self, device, endpoint_id, replacement_data, replace_device): super().__init__(device, endpoint_id) def set_device_attr(attr): if attr in replacement_data: setattr(self, attr, replacement_data[attr]) else: setattr(self, attr, getattr(replace_device[endpoint_id], attr)) set_device_attr("profile_id") set_device_attr("device_type") self.status = zigpy.endpoint.Status.ZDO_INIT for c in replacement_data.get("input_clusters", []): if isinstance(c, int): cluster = None cluster_id = c else: cluster = c(self, is_server=True) cluster_id = cluster.cluster_id self.add_input_cluster(cluster_id, cluster) for c in replacement_data.get("output_clusters", []): if isinstance(c, int): cluster = None cluster_id = c else: cluster = c(self, is_server=False) cluster_id = cluster.cluster_id self.add_output_cluster(cluster_id, cluster) class CustomCluster(zigpy.zcl.Cluster): _skip_registry = True _CONSTANT_ATTRIBUTES: Optional[Dict[int, Any]] = None async def read_attributes_raw(self, attributes, manufacturer=None): if not self._CONSTANT_ATTRIBUTES: return await super().read_attributes_raw( attributes, manufacturer=manufacturer ) succeeded = [ foundation.ReadAttributeRecord( attr, foundation.Status.SUCCESS, foundation.TypeValue() ) for attr in attributes if attr in self._CONSTANT_ATTRIBUTES ] for record in succeeded: record.value.value = self._CONSTANT_ATTRIBUTES[record.attrid] attrs_to_read = [ attr for attr in attributes if attr not in self._CONSTANT_ATTRIBUTES ] if not attrs_to_read: return [succeeded] results = await super().read_attributes_raw( attrs_to_read, manufacturer=manufacturer ) if not isinstance(results[0], list): for attrid in attrs_to_read: succeeded.append( foundation.ReadAttributeRecord( attrid, results[0], foundation.TypeValue() ) ) else: succeeded.extend(results[0]) return [succeeded]
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/quirks/__init__.py
__init__.py
import zigpy.types as t PROFILE_ID = 260 class DeviceType(t.enum16): # Generic ON_OFF_SWITCH = 0x0000 LEVEL_CONTROL_SWITCH = 0x0001 ON_OFF_OUTPUT = 0x0002 LEVEL_CONTROLLABLE_OUTPUT = 0x0003 SCENE_SELECTOR = 0x0004 CONFIGURATION_TOOL = 0x0005 REMOTE_CONTROL = 0x0006 COMBINED_INTERFACE = 0x0007 RANGE_EXTENDER = 0x0008 MAIN_POWER_OUTLET = 0x0009 DOOR_LOCK = 0x000A DOOR_LOCK_CONTROLLER = 0x000B SIMPLE_SENSOR = 0x000C CONSUMPTION_AWARENESS_DEVICE = 0x000D HOME_GATEWAY = 0x0050 SMART_PLUG = 0x0051 WHITE_GOODS = 0x0052 METER_INTERFACE = 0x0053 # Lighting ON_OFF_LIGHT = 0x0100 DIMMABLE_LIGHT = 0x0101 COLOR_DIMMABLE_LIGHT = 0x0102 ON_OFF_LIGHT_SWITCH = 0x0103 DIMMER_SWITCH = 0x0104 COLOR_DIMMER_SWITCH = 0x0105 LIGHT_SENSOR = 0x0106 OCCUPANCY_SENSOR = 0x0107 # ZLO device types ON_OFF_BALLAST = 0x0108 DIMMABLE_BALLAST = 0x0109 ON_OFF_PLUG_IN_UNIT = 0x010A DIMMABLE_PLUG_IN_UNIT = 0x010B COLOR_TEMPERATURE_LIGHT = 0x010C EXTENDED_COLOR_LIGHT = 0x010D LIGHT_LEVEL_SENSOR = 0x010E # Closure SHADE = 0x0200 SHADE_CONTROLLER = 0x0201 WINDOW_COVERING_DEVICE = 0x0202 WINDOW_COVERING_CONTROLLER = 0x0203 # HVAC HEATING_COOLING_UNIT = 0x0300 THERMOSTAT = 0x0301 TEMPERATURE_SENSOR = 0x0302 PUMP = 0x0303 PUMP_CONTROLLER = 0x0304 PRESSURE_SENSOR = 0x0305 FLOW_SENSOR = 0x0306 MINI_SPLIT_AC = 0x0307 # Intruder Alarm Systems IAS_CONTROL = 0x0400 # IAS Control and Indicating Equipment IAS_ANCILLARY_CONTROL = 0x0401 # IAS Ancillary Control Equipment IAS_ZONE = 0x0402 IAS_WARNING_DEVICE = 0x0403 # ZLO device types, continued COLOR_CONTROLLER = 0x0800 COLOR_SCENE_CONTROLLER = 0x0810 NON_COLOR_CONTROLLER = 0x0820 NON_COLOR_SCENE_CONTROLLER = 0x0830 CONTROL_BRIDGE = 0x0840 ON_OFF_SENSOR = 0x0850 CLUSTERS = { # Generic DeviceType.ON_OFF_SWITCH: ([0x0007], [0x0004, 0x0005, 0x0006]), DeviceType.LEVEL_CONTROL_SWITCH: ([0x0007], [0x0004, 0x0005, 0x0006, 0x0008]), DeviceType.ON_OFF_OUTPUT: ([0x0004, 0x0005, 0x0006], []), DeviceType.LEVEL_CONTROLLABLE_OUTPUT: ([0x0004, 0x0005, 0x0006, 0x0008], []), DeviceType.SCENE_SELECTOR: ([], [0x0004, 0x0005]), DeviceType.REMOTE_CONTROL: ([], [0x0004, 0x0005, 0x0006, 0x0008]), DeviceType.MAIN_POWER_OUTLET: ([0x0004, 0x0005, 0x0006], []), DeviceType.SMART_PLUG: ([0x0004, 0x0005, 0x0006], []), # Lighting DeviceType.ON_OFF_LIGHT: ([0x0004, 0x0005, 0x0006, 0x0008], []), DeviceType.DIMMABLE_LIGHT: ([0x0004, 0x0005, 0x0006, 0x0008], []), DeviceType.COLOR_DIMMABLE_LIGHT: ([0x0004, 0x0005, 0x0006, 0x0008, 0x0300], []), DeviceType.ON_OFF_LIGHT_SWITCH: ([0x0007], [0x0004, 0x0005, 0x0006]), DeviceType.DIMMER_SWITCH: ([0x0007], [0x0004, 0x0005, 0x0006, 0x0008]), DeviceType.COLOR_DIMMER_SWITCH: ( [0x0007], [0x0004, 0x0005, 0x0006, 0x0008, 0x0300], ), DeviceType.LIGHT_SENSOR: ([0x0400], []), DeviceType.OCCUPANCY_SENSOR: ([0x0406], []), DeviceType.COLOR_TEMPERATURE_LIGHT: ( [0x0003, 0x0004, 0x0005, 0x0006, 0x0008, 0x0300], [], ), DeviceType.EXTENDED_COLOR_LIGHT: ( [0x0003, 0x0004, 0x0005, 0x0006, 0x0008, 0x0300], [], ), # Closures DeviceType.WINDOW_COVERING_DEVICE: ([0x0004, 0x0005, 0x0102], []), # HVAC DeviceType.THERMOSTAT: ([0x0201, 0x0204], [0x0200, 0x0202, 0x0203]), }
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/profiles/zha.py
zha.py
import typing import zigpy.types as t class PowerDescriptor(t.Struct): _fields = [ ("byte_1", 1), # Current power mode 4, Available power sources 4 ("byte_2", 1), # Current power source 4, Current power source level 4 ] class SimpleDescriptor(t.Struct): _fields = [ ("endpoint", t.uint8_t), ("profile", t.uint16_t), ("device_type", t.uint16_t), ("device_version", t.uint8_t), ("input_clusters", t.LVList(t.uint16_t)), ("output_clusters", t.LVList(t.uint16_t)), ] class SizePrefixedSimpleDescriptor(SimpleDescriptor): def serialize(self): data = super().serialize() return len(data).to_bytes(1, "little") + data @classmethod def deserialize(cls, data): if not data or data[0] == 0: return None, data[1:] return SimpleDescriptor.deserialize(data[1:]) class LogicalType(t.enum8): Coordinator = 0b000 Router = 0b001 EndDevice = 0b010 Reserved3 = 0b011 Reserved4 = 0b100 Reserved5 = 0b101 Reserved6 = 0b110 Reserved7 = 0b111 class NodeDescriptor(t.Struct): _fields = [ ("byte1", t.uint8_t), ("byte2", t.uint8_t), ("mac_capability_flags", t.uint8_t), ("manufacturer_code", t.uint16_t), ("maximum_buffer_size", t.uint8_t), ("maximum_incoming_transfer_size", t.uint16_t), ("server_mask", t.uint16_t), ("maximum_outgoing_transfer_size", t.uint16_t), ("descriptor_capability_field", t.uint8_t), ] def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], self.__class__): # copy constructor for field in self._fields: setattr(self, field[0], getattr(args[0], field[0])) self._valid = True elif len(args) == len(self._fields): for field, val in zip(self._fields, args): setattr(self, field[0], field[1](val)) else: for field in self._fields: setattr(self, field[0], None) @property def is_valid(self): """Return True if all fields were initialized.""" non_empty_fields = [ getattr(self, field[0]) is not None for field in self._fields ] return all(non_empty_fields) @property def logical_type(self): """Return logical type of the device""" if self.byte1 is None: return None return LogicalType(self.byte1 & 0x07) @property def is_coordinator(self): """Return True whether this is a coordinator.""" if self.logical_type is None: return None return self.logical_type == LogicalType.Coordinator @property def is_end_device(self): """Return True whether this is an end device.""" if self.logical_type is None: return None return self.logical_type == LogicalType.EndDevice @property def is_router(self): """Return True whether this is a router.""" if self.logical_type is None: return None return self.logical_type == LogicalType.Router @property def complex_descriptor_available(self): if self.byte1 is None: return None return bool(self.byte1 & 0b00001000) @property def user_descriptor_available(self): if self.byte1 is None: return None return bool(self.byte1 & 0b00010000) @property def is_alternate_pan_coordinator(self): if self.mac_capability_flags is None: return None return bool(self.mac_capability_flags & 0b00000001) @property def is_full_function_device(self): if self.mac_capability_flags is None: return None return bool(self.mac_capability_flags & 0b00000010) @property def is_mains_powered(self): if self.mac_capability_flags is None: return None return bool(self.mac_capability_flags & 0b00000100) @property def is_receiver_on_when_idle(self): if self.mac_capability_flags is None: return None return bool(self.mac_capability_flags & 0b00001000) @property def is_security_capable(self): if self.mac_capability_flags is None: return None return bool(self.mac_capability_flags & 0b01000000) @property def allocate_address(self): if self.mac_capability_flags is None: return None return bool(self.mac_capability_flags & 0b10000000) class MultiAddress: """Used for binds, represents an IEEE+endpoint or NWK address""" def __init__(self, other=None): if isinstance(other, self.__class__): self.addrmode = other.addrmode self.nwk = getattr(other, "nwk", None) self.ieee = getattr(other, "ieee", None) self.endpoint = getattr(other, "endpoint", None) @classmethod def deserialize(cls, data): r = cls() r.addrmode, data = data[0], data[1:] if r.addrmode == 0x01: r.nwk, data = t.uint16_t.deserialize(data) elif r.addrmode == 0x03: r.ieee, data = t.EUI64.deserialize(data) r.endpoint, data = t.uint8_t.deserialize(data) else: raise ValueError("Invalid MultiAddress - unknown address mode") return r, data def serialize(self): if self.addrmode == 0x01: return self.addrmode.to_bytes(1, "little") + self.nwk.to_bytes(2, "little") elif self.addrmode == 0x03: return ( self.addrmode.to_bytes(1, "little") + self.ieee.serialize() + self.endpoint.to_bytes(1, "little") ) else: raise ValueError("Invalid value for addrmode") class Neighbor(t.Struct): """Neighbor Descriptor""" _fields = [ ("PanId", t.EUI64), ("IEEEAddr", t.EUI64), ("NWKAddr", t.NWK), ("NeighborType", t.uint8_t), ("PermitJoining", t.uint8_t), ("Depth", t.uint8_t), ("LQI", t.uint8_t), ] class Neighbors(t.Struct): """Mgmt_Lqi_rsp""" _fields = [ ("Entries", t.uint8_t), ("StartIndex", t.uint8_t), ("NeighborTableList", t.LVList(Neighbor)), ] class Route(t.Struct): """Route Descriptor""" _fields = [("DstNWK", t.NWK), ("RouteStatus", t.uint8_t), ("NextHop", t.NWK)] class Routes(t.Struct): _fields = [ ("Entries", t.uint8_t), ("StartIndex", t.uint8_t), ("RoutingTableList", t.LVList(Route)), ] class NwkUpdate(t.Struct): CHANNEL_CHANGE_REQ = 0xFE CHANNEL_MASK_MANAGER_ADDR_CHANGE_REQ = 0xFF _fields = [ ("ScanChannels", t.Channels), ("ScanDuration", t.uint8_t), ("ScanCount", t.uint8_t), ("nwkUpdateId", t.uint8_t), ("nwkManagerAddr", t.NWK), ] def serialize(self) -> bytes: """Serialize data.""" r = self.ScanChannels.serialize() + self.ScanDuration.serialize() if self.ScanDuration <= 0x05: r += self.ScanCount.serialize() if self.ScanDuration in ( self.CHANNEL_CHANGE_REQ, self.CHANNEL_MASK_MANAGER_ADDR_CHANGE_REQ, ): r += self.nwkUpdateId.serialize() if self.ScanDuration == self.CHANNEL_MASK_MANAGER_ADDR_CHANGE_REQ: r += self.nwkManagerAddr.serialize() return r @classmethod def deserialize(cls, data: bytes) -> typing.Tuple["NwkUpdate", bytes]: """Deserialize data.""" r = cls() r.ScanChannels, data = t.Channels.deserialize(data) r.ScanDuration, data = t.uint8_t.deserialize(data) if r.ScanDuration <= 0x05: r.ScanCount, data = t.uint8_t.deserialize(data) if r.ScanDuration in ( cls.CHANNEL_CHANGE_REQ, cls.CHANNEL_MASK_MANAGER_ADDR_CHANGE_REQ, ): r.nwkUpdateId, data = t.uint8_t.deserialize(data) if r.ScanDuration == cls.CHANNEL_MASK_MANAGER_ADDR_CHANGE_REQ: r.nwkManagerAddr, data = t.NWK.deserialize(data) return r, data class Status(t.enum8): # The requested operation or transmission was completed successfully. SUCCESS = 0x00 # The supplied request type was invalid. INV_REQUESTTYPE = 0x80 # The requested device did not exist on a device following a child # descriptor request to a parent. DEVICE_NOT_FOUND = 0x81 # The supplied endpoint was equal to = 0x00 or between 0xf1 and 0xff. INVALID_EP = 0x82 # The requested endpoint is not described by a simple descriptor. NOT_ACTIVE = 0x83 # The requested optional feature is not supported on the target device. NOT_SUPPORTED = 0x84 # A timeout has occurred with the requested operation. TIMEOUT = 0x85 # The end device bind request was unsuccessful due to a failure to match # any suitable clusters. NO_MATCH = 0x86 # The unbind request was unsuccessful due to the coordinator or source # device not having an entry in its binding table to unbind. NO_ENTRY = 0x88 # A child descriptor was not available following a discovery request to a # parent. NO_DESCRIPTOR = 0x89 # The device does not have storage space to support the requested # operation. INSUFFICIENT_SPACE = 0x8A # The device is not in the proper state to support the requested operation. NOT_PERMITTED = 0x8B # The device does not have table space to support the operation. TABLE_FULL = 0x8C # The permissions configuration table on the target indicates that the # request is not authorized from this device. NOT_AUTHORIZED = 0x8D @classmethod def _missing_(cls, value): chained = t.APSStatus(value) status = t.uint8_t.__new__(cls, chained.value) status._name_ = chained.name status._value_ = value return status NWK = ("NWKAddr", t.NWK) NWKI = ("NWKAddrOfInterest", t.NWK) IEEE = ("IEEEAddr", t.EUI64) STATUS = ("Status", Status) class _CommandID(t.HexRepr, t.uint16_t): _hex_len = 4 class ZDOCmd(t.enum_factory(_CommandID)): # Device and Service Discovery Server Requests NWK_addr_req = 0x0000 IEEE_addr_req = 0x0001 Node_Desc_req = 0x0002 Power_Desc_req = 0x0003 Simple_Desc_req = 0x0004 Active_EP_req = 0x0005 Match_Desc_req = 0x0006 Complex_Desc_req = 0x0010 User_Desc_req = 0x0011 Discovery_Cache_req = 0x0012 Device_annce = 0x0013 User_Desc_set = 0x0014 System_Server_Discovery_req = 0x0015 Discovery_store_req = 0x0016 Node_Desc_store_req = 0x0017 Active_EP_store_req = 0x0019 Simple_Desc_store_req = 0x001A Remove_node_cache_req = 0x001B Find_node_cache_req = 0x001C Extended_Simple_Desc_req = 0x001D Extended_Active_EP_req = 0x001E Parent_annce = 0x001F # Bind Management Server Services Responses End_Device_Bind_req = 0x0020 Bind_req = 0x0021 Unbind_req = 0x0022 # Network Management Server Services Requests # ... TODO optional stuff ... Mgmt_Lqi_req = 0x0031 Mgmt_Rtg_req = 0x0032 # ... TODO optional stuff ... Mgmt_Leave_req = 0x0034 Mgmt_Permit_Joining_req = 0x0036 Mgmt_NWK_Update_req = 0x0038 # ... TODO optional stuff ... # Responses # Device and Service Discovery Server Responses NWK_addr_rsp = 0x8000 IEEE_addr_rsp = 0x8001 Node_Desc_rsp = 0x8002 Power_Desc_rsp = 0x8003 Simple_Desc_rsp = 0x8004 Active_EP_rsp = 0x8005 Match_Desc_rsp = 0x8006 Complex_Desc_rsp = 0x8010 User_Desc_rsp = 0x8011 Discovery_Cache_rsp = 0x8012 User_Desc_conf = 0x8014 System_Server_Discovery_rsp = 0x8015 Discovery_Store_rsp = 0x8016 Node_Desc_store_rsp = 0x8017 Power_Desc_store_rsp = 0x8018 Active_EP_store_rsp = 0x8019 Simple_Desc_store_rsp = 0x801A Remove_node_cache_rsp = 0x801B Find_node_cache_rsp = 0x801C Extended_Simple_Desc_rsp = 0x801D Extended_Active_EP_rsp = 0x801E Parent_annce_rsp = 0x801F # Bind Management Server Services Responses End_Device_Bind_rsp = 0x8020 Bind_rsp = 0x8021 Unbind_rsp = 0x8022 # ... TODO optional stuff ... # Network Management Server Services Responses Mgmt_Lqi_rsp = 0x8031 Mgmt_Rtg_rsp = 0x8032 # ... TODO optional stuff ... Mgmt_Leave_rsp = 0x8034 Mgmt_Permit_Joining_rsp = 0x8036 # ... TODO optional stuff ... Mgmt_NWK_Update_rsp = 0x8038 CLUSTERS = { # Device and Service Discovery Server Requests ZDOCmd.NWK_addr_req: (IEEE, ("RequestType", t.uint8_t), ("StartIndex", t.uint8_t)), ZDOCmd.IEEE_addr_req: (NWKI, ("RequestType", t.uint8_t), ("StartIndex", t.uint8_t)), ZDOCmd.Node_Desc_req: (NWKI,), ZDOCmd.Power_Desc_req: (NWKI,), ZDOCmd.Simple_Desc_req: (NWKI, ("EndPoint", t.uint8_t)), ZDOCmd.Active_EP_req: (NWKI,), ZDOCmd.Match_Desc_req: ( NWKI, ("ProfileID", t.uint16_t), ("InClusterList", t.LVList(t.uint16_t)), ("OutClusterList", t.LVList(t.uint16_t)), ), # ZDO.Complex_Desc_req: (NWKI, ), ZDOCmd.User_Desc_req: (NWKI,), ZDOCmd.Discovery_Cache_req: (NWK, IEEE), ZDOCmd.Device_annce: (NWK, IEEE, ("Capability", t.uint8_t)), ZDOCmd.User_Desc_set: ( NWKI, ("UserDescriptor", t.fixed_list(16, t.uint8_t)), ), # Really a string ZDOCmd.System_Server_Discovery_req: (("ServerMask", t.uint16_t),), ZDOCmd.Discovery_store_req: ( NWK, IEEE, ("NodeDescSize", t.uint8_t), ("PowerDescSize", t.uint8_t), ("ActiveEPSize", t.uint8_t), ("SimpleDescSizeList", t.LVList(t.uint8_t)), ), ZDOCmd.Node_Desc_store_req: (NWK, IEEE, ("NodeDescriptor", NodeDescriptor)), ZDOCmd.Active_EP_store_req: (NWK, IEEE, ("ActiveEPList", t.LVList(t.uint8_t))), ZDOCmd.Simple_Desc_store_req: ( NWK, IEEE, ("SimpleDescriptor", SizePrefixedSimpleDescriptor), ), ZDOCmd.Remove_node_cache_req: (NWK, IEEE), ZDOCmd.Find_node_cache_req: (NWK, IEEE), ZDOCmd.Extended_Simple_Desc_req: ( NWKI, ("EndPoint", t.uint8_t), ("StartIndex", t.uint8_t), ), ZDOCmd.Extended_Active_EP_req: (NWKI, ("StartIndex", t.uint8_t)), ZDOCmd.Parent_annce: (("Children", t.LVList(t.EUI64)),), # Bind Management Server Services Responses ZDOCmd.End_Device_Bind_req: ( ("BindingTarget", t.uint16_t), ("SrcAddress", t.EUI64), ("SrcEndpoint", t.uint8_t), ("ProfileID", t.uint8_t), ("InClusterList", t.LVList(t.uint8_t)), ("OutClusterList", t.LVList(t.uint8_t)), ), ZDOCmd.Bind_req: ( ("SrcAddress", t.EUI64), ("SrcEndpoint", t.uint8_t), ("ClusterID", t.uint16_t), ("DstAddress", MultiAddress), ), ZDOCmd.Unbind_req: ( ("SrcAddress", t.EUI64), ("SrcEndpoint", t.uint8_t), ("ClusterID", t.uint16_t), ("DstAddress", MultiAddress), ), # Network Management Server Services Requests # ... TODO optional stuff ... ZDOCmd.Mgmt_Lqi_req: (("StartIndex", t.uint8_t),), ZDOCmd.Mgmt_Rtg_req: (("StartIndex", t.uint8_t),), # ... TODO optional stuff ... ZDOCmd.Mgmt_Leave_req: (("DeviceAddress", t.EUI64), ("Options", t.bitmap8)), ZDOCmd.Mgmt_Permit_Joining_req: ( ("PermitDuration", t.uint8_t), ("TC_Significant", t.Bool), ), ZDOCmd.Mgmt_NWK_Update_req: (("NwkUpdate", NwkUpdate),), # ... TODO optional stuff ... # Responses # Device and Service Discovery Server Responses ZDOCmd.NWK_addr_rsp: ( STATUS, IEEE, NWK, ("NumAssocDev", t.Optional(t.uint8_t)), ("StartIndex", t.Optional(t.uint8_t)), ("NWKAddressAssocDevList", t.Optional(t.List(t.NWK))), ), ZDOCmd.IEEE_addr_rsp: ( STATUS, IEEE, NWK, ("NumAssocDev", t.Optional(t.uint8_t)), ("StartIndex", t.Optional(t.uint8_t)), ("NWKAddrAssocDevList", t.Optional(t.List(t.NWK))), ), ZDOCmd.Node_Desc_rsp: ( STATUS, NWKI, ("NodeDescriptor", t.Optional(NodeDescriptor)), ), ZDOCmd.Power_Desc_rsp: ( STATUS, NWKI, ("PowerDescriptor", t.Optional(PowerDescriptor)), ), ZDOCmd.Simple_Desc_rsp: ( STATUS, NWKI, ("SimpleDescriptor", t.Optional(SizePrefixedSimpleDescriptor)), ), ZDOCmd.Active_EP_rsp: (STATUS, NWKI, ("ActiveEPList", t.LVList(t.uint8_t))), ZDOCmd.Match_Desc_rsp: (STATUS, NWKI, ("MatchList", t.LVList(t.uint8_t))), # ZDO.Complex_Desc_rsp: ( # STATUS, # NWKI, # ('Length', t.uint8_t), # ('ComplexDescriptor', t.Optional(ComplexDescriptor)), # ), ZDOCmd.User_Desc_rsp: ( STATUS, NWKI, ("Length", t.uint8_t), ("UserDescriptor", t.Optional(t.fixed_list(16, t.uint8_t))), ), ZDOCmd.Discovery_Cache_rsp: (STATUS,), ZDOCmd.User_Desc_conf: (STATUS, NWKI), ZDOCmd.System_Server_Discovery_rsp: (STATUS, ("ServerMask", t.uint16_t)), ZDOCmd.Discovery_Store_rsp: (STATUS,), ZDOCmd.Node_Desc_store_rsp: (STATUS,), ZDOCmd.Power_Desc_store_rsp: (STATUS, IEEE, ("PowerDescriptor", PowerDescriptor)), ZDOCmd.Active_EP_store_rsp: (STATUS,), ZDOCmd.Simple_Desc_store_rsp: (STATUS,), ZDOCmd.Remove_node_cache_rsp: (STATUS,), ZDOCmd.Find_node_cache_rsp: (("CacheNWKAddr", t.EUI64), NWK, IEEE), ZDOCmd.Extended_Simple_Desc_rsp: ( STATUS, NWK, ("Endpoint", t.uint8_t), ("AppInputClusterCount", t.uint8_t), ("AppOutputClusterCount", t.uint8_t), ("StartIndex", t.uint8_t), ("AppClusterList", t.Optional(t.List(t.uint16_t))), ), ZDOCmd.Extended_Active_EP_rsp: ( STATUS, NWKI, ("ActiveEPCount", t.uint8_t), ("StartIndex", t.uint8_t), ("ActiveEPList", t.List(t.uint8_t)), ), ZDOCmd.Parent_annce_rsp: (STATUS, ("Children", t.LVList(t.EUI64))), # Bind Management Server Services Responses ZDOCmd.End_Device_Bind_rsp: (STATUS,), ZDOCmd.Bind_rsp: (STATUS,), ZDOCmd.Unbind_rsp: (STATUS,), # ... TODO optional stuff ... # Network Management Server Services Responses ZDOCmd.Mgmt_Lqi_rsp: (STATUS, ("Neighbors", t.Optional(Neighbors))), ZDOCmd.Mgmt_Rtg_rsp: (STATUS, ("Routes", t.Optional(Routes))), # ... TODO optional stuff ... ZDOCmd.Mgmt_Leave_rsp: (STATUS,), ZDOCmd.Mgmt_Permit_Joining_rsp: (STATUS,), ZDOCmd.Mgmt_NWK_Update_rsp: ( STATUS, ("ScannedChannels", t.Channels), ("TotalTransmissions", t.uint16_t), ("TransmissionFailures", t.uint16_t), ("EnergyValues", t.LVList(t.uint8_t)), ) # ... TODO optional stuff ... } # Rewrite to (name, param_names, param_types) for command_id, schema in CLUSTERS.items(): param_names = [p[0] for p in schema] param_types = [p[1] for p in schema] CLUSTERS[command_id] = (param_names, param_types) class ZDOHeader: """Just a wrapper representing ZDO header, similar to ZCL header.""" def __init__(self, command_id: t.uint16_t = 0x0000, tsn: t.uint8_t = 0) -> None: self._command_id = ZDOCmd(command_id) self._tsn = t.uint8_t(tsn) @property def command_id(self) -> ZDOCmd: """Return ZDO command.""" return self._command_id @command_id.setter def command_id(self, value: t.uint16_t) -> None: """Command ID setter.""" self._command_id = ZDOCmd(value) @property def is_reply(self) -> bool: """Return True if this is a reply.""" return bool(self._command_id & 0x8000) @property def tsn(self) -> t.uint8_t: """Return transaction seq number.""" return self._tsn @tsn.setter def tsn(self, value: t.uint8_t) -> None: """Set TSN.""" self._tsn = t.uint8_t(value) @classmethod def deserialize( cls, command_id: t.uint16_t, data: bytes ) -> typing.Tuple["ZDOHeader", bytes]: """Deserialize data.""" tsn, data = t.uint8_t.deserialize(data) return cls(command_id, tsn), data def serialize(self) -> bytes: """Serialize header.""" return self.tsn.serialize()
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zdo/types.py
types.py
import functools import logging import zigpy.types as t import zigpy.util from . import types LOGGER = logging.getLogger(__name__) class ZDO(zigpy.util.CatchingTaskMixin, zigpy.util.ListenableMixin): """The ZDO endpoint of a device""" def __init__(self, device): self._device = device self._listeners = {} def _serialize(self, command, *args): schema = types.CLUSTERS[command][1] data = t.serialize(args, schema) return data def deserialize(self, cluster_id, data): hdr, data = types.ZDOHeader.deserialize(cluster_id, data) try: cluster_details = types.CLUSTERS[cluster_id] except KeyError: self.warning("Unknown ZDO cluster 0x%04x", cluster_id) return hdr, data args, data = t.deserialize(data, cluster_details[1]) if data != b"": # TODO: Seems sane to check, but what should we do? self.warning("Data remains after deserializing ZDO frame") return hdr, args @zigpy.util.retryable_request def request(self, command, *args, use_ieee=False): data = self._serialize(command, *args) tsn = self.device.application.get_sequence() data = t.uint8_t(tsn).serialize() + data return self._device.request(0, command, 0, 0, tsn, data, use_ieee=use_ieee) def reply(self, command, *args, tsn=None, use_ieee=False): data = self._serialize(command, *args) if tsn is None: tsn = self.device.application.get_sequence() data = t.uint8_t(tsn).serialize() + data return self._device.reply(0, command, 0, 0, tsn, data, use_ieee=use_ieee) def handle_message(self, profile, cluster, hdr, args): self.debug("ZDO request %s: %s", hdr.command_id, args) app = self._device.application if hdr.command_id == types.ZDOCmd.NWK_addr_req: if app.ieee == args[0]: self.create_catching_task( self.NWK_addr_rsp(0, app.ieee, app.nwk, 0, 0, [], tsn=hdr.tsn) ) elif hdr.command_id == types.ZDOCmd.IEEE_addr_req: broadcast = (0xFFFF, 0xFFFD, 0xFFFC) if args[0] in broadcast or app.nwk == args[0]: self.create_catching_task( self.IEEE_addr_rsp(0, app.ieee, app.nwk, 0, 0, [], tsn=hdr.tsn) ) elif hdr.command_id == types.ZDOCmd.Match_Desc_req: self.handle_match_desc(*args, tsn=hdr.tsn) elif hdr.command_id == types.ZDOCmd.Device_annce: self.listener_event("device_announce", self._device) elif hdr.command_id == types.ZDOCmd.Mgmt_Permit_Joining_req: self.listener_event("permit_duration", args[0]) else: self.debug("Unsupported ZDO request:%s", hdr.command_id) def handle_match_desc(self, addr, profile, in_clusters, out_clusters, *, tsn=None): local_addr = self._device.application.nwk if profile != 260: self.create_catching_task(self.Match_Desc_rsp(0, local_addr, [], tsn=tsn)) return self.create_catching_task( self.Match_Desc_rsp(0, local_addr, [t.uint8_t(1)], tsn=tsn) ) def bind(self, cluster): return self.Bind_req( self._device.ieee, cluster.endpoint.endpoint_id, cluster.cluster_id, self.device.application.get_dst_address(cluster), ) def unbind(self, cluster): return self.Unbind_req( self._device.ieee, cluster.endpoint.endpoint_id, cluster.cluster_id, self.device.application.get_dst_address(cluster), ) def leave(self): return self.Mgmt_Leave_req(self._device.ieee, 0x02) def permit(self, duration=60, tc_significance=0): return self.Mgmt_Permit_Joining_req(duration, tc_significance) def log(self, lvl, msg, *args, **kwargs): msg = "[0x%04x:zdo] " + msg args = (self._device.nwk,) + args return LOGGER.log(lvl, msg, *args, **kwargs) @property def device(self): return self._device def __getattr__(self, name): try: command = types.ZDOCmd[name] except KeyError: raise AttributeError("No such '%s' ZDO command" % (name,)) if command & 0x8000: return functools.partial(self.reply, command) return functools.partial(self.request, command) def broadcast( app, command, grpid, radius, *args, broadcast_address=t.BroadcastAddress.RX_ON_WHEN_IDLE ): sequence = app.get_sequence() data = sequence.to_bytes(1, "little") schema = types.CLUSTERS[command][1] data += t.serialize(args, schema) return zigpy.device.broadcast( app, 0, command, 0, 0, grpid, radius, sequence, data, broadcast_address=broadcast_address, )
zigpy-homeassistant
/zigpy-homeassistant-0.19.0.tar.gz/zigpy-homeassistant-0.19.0/zigpy/zdo/__init__.py
__init__.py
import enum import zigpy.types def deserialize(data, schema): result = [] for type_ in schema: value, data = type_.deserialize(data) result.append(value) return result, data def serialize(data, schema): return b"".join(t(v).serialize() for t, v in zip(schema, data)) class Bytes(bytes): def serialize(self): return self @classmethod def deserialize(cls, data): return cls(data), b"" class ATCommand(Bytes): @classmethod def deserialize(cls, data): return cls(data[:2]), data[2:] class int_t(int): _signed = True def serialize(self): return self.to_bytes(self._size, "big", signed=self._signed) @classmethod def deserialize(cls, data): # Work around https://bugs.python.org/issue23640 r = cls(int.from_bytes(data[: cls._size], "big", signed=cls._signed)) data = data[cls._size :] return r, data class int8s(int_t): _size = 1 class int16s(int_t): _size = 2 class int24s(int_t): _size = 3 class int32s(int_t): _size = 4 class int40s(int_t): _size = 5 class int48s(int_t): _size = 6 class int56s(int_t): _size = 7 class int64s(int_t): _size = 8 class uint_t(int_t): _signed = False class uint8_t(uint_t): _size = 1 class uint16_t(uint_t): _size = 2 class uint24_t(uint_t): _size = 3 class uint32_t(uint_t): _size = 4 class uint40_t(uint_t): _size = 5 class uint48_t(uint_t): _size = 6 class uint56_t(uint_t): _size = 7 class uint64_t(uint_t): _size = 8 class Bool(uint8_t, enum.Enum): # Boolean type with values true and false. false = 0x00 # An alias for zero, used for clarity. true = 0x01 # An alias for one, used for clarity. class EUI64(zigpy.types.EUI64): @classmethod def deserialize(cls, data): r, data = super().deserialize(data) return cls(r[::-1]), data def serialize(self): assert self._length == len(self) return super().serialize()[::-1] class UndefinedEnumMeta(enum.EnumMeta): def __call__(cls, value=None, *args, **kwargs): if value is None: # the 1st enum member is default return next(iter(cls)) try: return super().__call__(value, *args, **kwargs) except ValueError as exc: try: return super().__call__(cls._UNDEFINED) except AttributeError: raise exc class UndefinedEnum(enum.Enum, metaclass=UndefinedEnumMeta): pass class FrameId(uint8_t): pass class NWK(uint16_t): def __repr__(self): return "0x{:04x}".format(self) def __str__(self): return "0x{:04x}".format(self) UNKNOWN_IEEE = EUI64([uint8_t(0xFF) for i in range(0, 8)]) UNKNOWN_NWK = NWK(0xFFFE) class TXStatus(uint8_t, UndefinedEnum): """TX Status frame.""" SUCCESS = 0x00 # Standard # all retries are expired and no ACK is received. # Not returned for Broadcasts NO_ACK_RECEIVED = 0x01 CCA_FAILURE = 0x02 # Transmission was purged because a coordinator tried to send to an end # device, but it timed out waiting for a poll from the end device that # never occurred, this haapens when Coordinator times out of an indirect # transmission. Timeouse is defines ad 2.5 * 'SP' (Cyclic Sleep Period) # parameter value INDIRECT_TX_TIMEOUT = 0x03 # invalid destination endpoint INVALID_DESTINATION_ENDPOINT = 0x15 # not returned for Broadcasts NETWORK_ACK_FAILURE = 0x21 # TX failed because end device was not joined to the network INDIRECT_TX_FAILURE = 0x22 # Self addressed SELF_ADDRESSED = 0x23 # Address not found ADDRESS_NOT_FOUND = 0x24 # Route not found ROUTE_NOT_FOUND = 0x25 # Broadcast source failed to hear a neighbor relay the message BROADCAST_RELAY_FAILURE = 0x26 # Invalid binding table index INVALID_BINDING_IDX = 0x2B # Resource error lack of free buffers, timers, and so forth. NO_RESOURCES = 0x2C # Attempted broadcast with APS transmission BROADCAST_APS_TX_ATTEMPT = 0x2D # Attempted unicast with APS transmission, but EE=0 UNICAST_APS_TX_ATTEMPT = 0x2E INTERNAL_ERROR = 0x31 # Transmission failed due to resource depletion (for example, out of # buffers, especially for indirect messages from coordinator) NO_RESOURCES_2 = 0x32 # The payload in the frame was larger than allowed PAYLOAD_TOO_LARGE = 0x74 _UNDEFINED = 0x2C class DiscoveryStatus(uint8_t, UndefinedEnum): """Discovery status of TX Status frame.""" SUCCESS = 0x00 ADDRESS_DISCOVERY = 0x01 ROUTE_DISCOVERY = 0x02 ADDRESS_AND_ROUTE = 0x03 EXTENDED_TIMEOUT = 0x40 _UNDEFINED = 0x00
zigpy-xbee-homeassistant
/zigpy_xbee_homeassistant-0.11.0-py3-none-any.whl/zigpy_xbee/types.py
types.py
import asyncio import logging import serial import serial_asyncio LOGGER = logging.getLogger(__name__) class Gateway(asyncio.Protocol): START = b"\x7E" ESCAPE = b"\x7D" XON = b"\x11" XOFF = b"\x13" RESERVED = START + ESCAPE + XON + XOFF THIS_ONE = True def __init__(self, api, connected_future=None): self._buffer = b"" self._connected_future = connected_future self._api = api self._in_command_mode = False def send(self, data): """Send data, taking care of escaping and framing""" LOGGER.debug("Sending: %s", data) checksum = bytes([self._checksum(data)]) frame = self.START + self._escape( len(data).to_bytes(2, "big") + data + checksum ) self._transport.write(frame) @property def baudrate(self): """Baudrate.""" return self._transport.serial.baudrate @baudrate.setter def baudrate(self, baudrate): """Set baudrate.""" if baudrate in self._transport.serial.BAUDRATES: self._transport.serial.baudrate = baudrate else: raise ValueError( "baudrate must be one of {}".format(self._transport.serial.BAUDRATES) ) def connection_lost(self, exc) -> None: """Port was closed expectedly or unexpectedly.""" if self._connected_future and not self._connected_future.done(): if exc is None: self._connected_future.set_result(True) else: self._connected_future.set_exception(exc) if exc is None: LOGGER.debug("Closed serial connection") return LOGGER.error("Lost serial connection: %s", exc) self._api.connection_lost(exc) def connection_made(self, transport): """Callback when the uart is connected""" LOGGER.debug("Connection made") self._transport = transport if self._connected_future: self._connected_future.set_result(True) def command_mode_rsp(self, data): """Handles AT command mode response.""" data = data.decode("ascii", "ignore") LOGGER.debug("Handling AT command mode response: %s", data) self._api.handle_command_mode_rsp(data) def command_mode_send(self, data): """Send data in command mode.""" LOGGER.debug("Command mode sending %s to uart", data) self._in_command_mode = True self._transport.write(data) def data_received(self, data): """Callback when there is data received from the uart""" self._buffer += data while self._buffer: frame = self._extract_frame() if frame is None: break self.frame_received(frame) if self._in_command_mode and self._buffer[-1:] == b"\r": rsp, self._buffer = (self._buffer[:-1], b"") self.command_mode_rsp(rsp) def frame_received(self, frame): """Frame receive handler""" LOGGER.debug("Frame received: %s", frame) self._api.frame_received(frame) def close(self): self._transport.close() def reset_command_mode(self): """Reset command mode and ignore \r character as command mode response.""" self._in_command_mode = False def _extract_frame(self): first_start = self._buffer.find(self.START) if first_start < 0: return None data = self._buffer[first_start + 1 :] frame_len, data = self._get_unescaped(data, 2) if frame_len is None: return None frame_len = int.from_bytes(frame_len, "big") frame, data = self._get_unescaped(data, frame_len) if frame is None: return None checksum, data = self._get_unescaped(data, 1) if checksum is None: return None if self._checksum(frame) != checksum[0]: # TODO: Signal decode failure so that error frame can be sent self._buffer = data return None self._buffer = data return frame def _get_unescaped(self, data, n): ret = [] idx = 0 while len(ret) < n and idx < len(data): b = data[idx] if b == self.ESCAPE[0]: idx += 1 if idx >= len(data): return None, None b = data[idx] ^ 0x020 ret.append(b) idx += 1 if len(ret) >= n: return bytes(ret), data[idx:] return None, None def _escape(self, data): ret = [] for b in data: if b in self.RESERVED: ret.append(ord(self.ESCAPE)) ret.append(b ^ 0x20) else: ret.append(b) return bytes(ret) def _checksum(self, data): return 0xFF - (sum(data) % 0x100) async def connect(port, baudrate, api, loop=None): if loop is None: loop = asyncio.get_event_loop() connected_future = asyncio.Future() protocol = Gateway(api, connected_future) transport, protocol = await serial_asyncio.create_serial_connection( loop, lambda: protocol, url=port, baudrate=baudrate, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, ) await connected_future return protocol
zigpy-xbee-homeassistant
/zigpy_xbee_homeassistant-0.11.0-py3-none-any.whl/zigpy_xbee/uart.py
uart.py
import asyncio import binascii import enum import functools import logging import serial from zigpy.exceptions import APIException, DeliveryError from zigpy.types import LVList from . import types as t, uart LOGGER = logging.getLogger(__name__) AT_COMMAND_TIMEOUT = 2 REMOTE_AT_COMMAND_TIMEOUT = 30 PROBE_TIMEOUT = 45 class ModemStatus(t.uint8_t, t.UndefinedEnum): HARDWARE_RESET = 0x00 WATCHDOG_TIMER_RESET = 0x01 JOINED_NETWORK = 0x02 DISASSOCIATED = 0x03 COORDINATOR_STARTED = 0x06 NETWORK_SECURITY_KEY_UPDATED = 0x07 VOLTAGE_SUPPLY_LIMIT_EXCEEDED = 0x0D MODEM_CONFIGURATION_CHANGED_WHILE_JOIN_IN_PROGRESS = 0x11 UNKNOWN_MODEM_STATUS = 0xFF _UNDEFINED = 0xFF # https://www.digi.com/resources/documentation/digidocs/PDFs/90000976.pdf COMMAND_REQUESTS = { "at": (0x08, (t.FrameId, t.ATCommand, t.Bytes), 0x88), "queued_at": (0x09, (t.FrameId, t.ATCommand, t.Bytes), 0x88), "remote_at": ( 0x17, (t.FrameId, t.EUI64, t.NWK, t.uint8_t, t.ATCommand, t.Bytes), 0x97, ), "tx": (0x10, (), None), "tx_explicit": ( 0x11, ( t.FrameId, t.EUI64, t.NWK, t.uint8_t, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.Bytes, ), 0x8B, ), "create_source_route": ( 0x21, (t.FrameId, t.EUI64, t.NWK, t.uint8_t, LVList(t.NWK)), None, ), "register_joining_device": (0x24, (), None), } COMMAND_RESPONSES = { "at_response": (0x88, (t.FrameId, t.ATCommand, t.uint8_t, t.Bytes), None), "modem_status": (0x8A, (ModemStatus,), None), "tx_status": ( 0x8B, (t.FrameId, t.NWK, t.uint8_t, t.TXStatus, t.DiscoveryStatus), None, ), "route_information": (0x8D, (), None), "rx": (0x90, (), None), "explicit_rx_indicator": ( 0x91, ( t.EUI64, t.NWK, t.uint8_t, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t, t.Bytes, ), None, ), "rx_io_data_long_addr": (0x92, (), None), "remote_at_response": ( 0x97, (t.FrameId, t.EUI64, t.NWK, t.ATCommand, t.uint8_t, t.Bytes), None, ), "extended_status": (0x98, (), None), "route_record_indicator": (0xA1, (t.EUI64, t.NWK, t.uint8_t, LVList(t.NWK)), None), "many_to_one_rri": (0xA3, (t.EUI64, t.NWK, t.uint8_t), None), "node_id_indicator": (0x95, (), None), } # https://www.digi.com/resources/documentation/digidocs/pdfs/90001539.pdf pg 175 AT_COMMANDS = { # Addressing commands "DH": t.uint32_t, "DL": t.uint32_t, "MY": t.uint16_t, "MP": t.uint16_t, "NC": t.uint32_t, # 0 - MAX_CHILDREN. "SH": t.uint32_t, "SL": t.uint32_t, "NI": t, # 20 byte printable ascii string "SE": t.uint8_t, "DE": t.uint8_t, "CI": t.uint16_t, "TO": t.uint8_t, "NP": t.uint16_t, "DD": t.uint32_t, "CR": t.uint8_t, # 0 - 0x3F # Networking commands "CH": t.uint8_t, # 0x0B - 0x1A "DA": t, # no param "ID": t.uint64_t, "OP": t.uint64_t, "NH": t.uint8_t, "BH": t.uint8_t, # 0 - 0x1E "OI": t.uint16_t, "NT": t.uint8_t, # 0x20 - 0xFF "NO": t.uint8_t, # bitfield, 0 - 3 "SC": t.uint16_t, # 1 - 0xFFFF "SD": t.uint8_t, # 0 - 7 "ZS": t.uint8_t, # 0 - 2 "NJ": t.uint8_t, "JV": t.Bool, "NW": t.uint16_t, # 0 - 0x64FF "JN": t.Bool, "AR": t.uint8_t, "DJ": t.Bool, # WTF, docs "II": t.uint16_t, # Security commands "EE": t.Bool, "EO": t.uint8_t, "NK": t.Bytes, # 128-bit value "KY": t.Bytes, # 128-bit value # RF interfacing commands "PL": t.uint8_t, # 0 - 4 (basically an Enum) "PM": t.Bool, "DB": t.uint8_t, "PP": t.uint8_t, # RO "AP": t.uint8_t, # 1-2 (an Enum) "AO": t.uint8_t, # 0 - 3 (an Enum) "BD": t.uint8_t, # 0 - 7 (an Enum) "NB": t.uint8_t, # 0 - 3 (an Enum) "SB": t.uint8_t, # 0 - 1 (an Enum) "RO": t.uint8_t, "D6": t.uint8_t, # 0 - 5 (an Enum) "D7": t.uint8_t, # 0 - 7 (an Enum) "P3": t.uint8_t, # 0 - 5 (an Enum) "P4": t.uint8_t, # 0 - 5 (an Enum) # I/O commands "IR": t.uint16_t, "IC": t.uint16_t, "D0": t.uint8_t, # 0 - 5 (an Enum) "D1": t.uint8_t, # 0 - 5 (an Enum) "D2": t.uint8_t, # 0 - 5 (an Enum) "D3": t.uint8_t, # 0 - 5 (an Enum) "D4": t.uint8_t, # 0 - 5 (an Enum) "D5": t.uint8_t, # 0 - 5 (an Enum) "D8": t.uint8_t, # 0 - 5 (an Enum) "D9": t.uint8_t, # 0 - 5 (an Enum) "P0": t.uint8_t, # 0 - 5 (an Enum) "P1": t.uint8_t, # 0 - 5 (an Enum) "P2": t.uint8_t, # 0 - 5 (an Enum) "P5": t.uint8_t, # 0 - 5 (an Enum) "P6": t.uint8_t, # 0 - 5 (an Enum) "P7": t.uint8_t, # 0 - 5 (an Enum) "P8": t.uint8_t, # 0 - 5 (an Enum) "P9": t.uint8_t, # 0 - 5 (an Enum) "LT": t.uint8_t, "PR": t.uint16_t, "RP": t.uint8_t, "%V": t.uint16_t, # read only "V+": t.uint16_t, "TP": t.uint16_t, "M0": t.uint16_t, # 0 - 0x3FF "M1": t.uint16_t, # 0 - 0x3FF # Diagnostics commands "VR": t.uint16_t, "HV": t.uint16_t, "AI": t.uint8_t, # AT command options "CT": t.uint16_t, # 2 - 0x028F "CN": None, "GT": t.uint16_t, "CC": t.uint8_t, # Sleep commands "SM": t.uint8_t, "SN": t.uint16_t, "SP": t.uint16_t, "ST": t.uint16_t, "SO": t.uint8_t, "WH": t.uint16_t, "SI": None, "PO": t.uint16_t, # 0 - 0x3E8 # Execution commands "AC": None, "WR": None, "RE": None, "FR": None, "NR": t.Bool, "SI": None, "CB": t.uint8_t, "ND": t, # "optional 2-Byte NI value" "DN": t.Bytes, # "up to 20-Byte printable ASCII string" "IS": None, "1S": None, "AS": None, # Stuff I've guessed "CE": t.uint8_t, } BAUDRATE_TO_BD = { 1200: "ATBD0", 2400: "ATBD1", 4800: "ATBD2", 9600: "ATBD3", 19200: "ATBD4", 38400: "ATBD5", 57600: "ATBD6", 115200: "ATBD7", 230400: "ATBD8", } class ATCommandResult(enum.IntEnum): OK = 0 ERROR = 1 INVALID_COMMAND = 2 INVALID_PARAMETER = 3 TX_FAILURE = 4 class XBee: def __init__(self): self._uart = None self._uart_params = None self._seq = 1 self._commands_by_id = {v[0]: k for k, v in COMMAND_RESPONSES.items()} self._awaiting = {} self._app = None self._cmd_mode_future = None self._conn_lost_task = None self._reset = asyncio.Event() self._running = asyncio.Event() @property def reset_event(self): """Return reset event.""" return self._reset @property def coordinator_started_event(self): """Return coordinator started.""" return self._running @property def is_running(self): """Return true if coordinator is running.""" return self.coordinator_started_event.is_set() async def connect(self, device: str, baudrate: int = 115200) -> None: assert self._uart is None self._uart = await uart.connect(device, baudrate, self) self._uart_params = (device, baudrate) def reconnect(self): """Reconnect using saved parameters.""" LOGGER.debug( "Reconnecting '%s' serial port using %s", self._uart_params[0], self._uart_params[1], ) return self.connect(self._uart_params[0], self._uart_params[1]) def connection_lost(self, exc: Exception) -> None: """Lost serial connection.""" LOGGER.warning( "Serial '%s' connection lost unexpectedly: %s", self._uart_params[0], exc ) self._uart = None if self._conn_lost_task and not self._conn_lost_task.done(): self._conn_lost_task.cancel() self._conn_lost_task = asyncio.ensure_future(self._connection_lost()) async def _connection_lost(self) -> None: """Reconnect serial port.""" try: await self._reconnect_till_done() except asyncio.CancelledError: LOGGER.debug("Cancelling reconnection attempt") async def _reconnect_till_done(self) -> None: attempt = 1 while True: try: await asyncio.wait_for(self.reconnect(), timeout=10) break except (asyncio.TimeoutError, OSError) as exc: wait = 2 ** min(attempt, 5) attempt += 1 LOGGER.debug( "Couldn't re-open '%s' serial port, retrying in %ss: %s", self._uart_params[0], wait, str(exc), ) await asyncio.sleep(wait) LOGGER.debug( "Reconnected '%s' serial port after %s attempts", self._uart_params[0], attempt, ) def close(self): if self._uart: self._uart.close() self._uart = None def _command(self, name, *args, mask_frame_id=False): LOGGER.debug("Command %s %s", name, args) if self._uart is None: raise APIException("API is not running") frame_id = 0 if mask_frame_id else self._seq data, needs_response = self._api_frame(name, frame_id, *args) self._uart.send(data) future = None if needs_response and frame_id: future = asyncio.Future() self._awaiting[frame_id] = (future,) self._seq = (self._seq % 255) + 1 return future async def _remote_at_command(self, ieee, nwk, options, name, *args): LOGGER.debug("Remote AT command: %s %s", name, args) data = t.serialize(args, (AT_COMMANDS[name],)) try: return await asyncio.wait_for( self._command( "remote_at", ieee, nwk, options, name.encode("ascii"), data ), timeout=REMOTE_AT_COMMAND_TIMEOUT, ) except asyncio.TimeoutError: LOGGER.warning("No response to %s command", name) raise async def _at_partial(self, cmd_type, name, *args): LOGGER.debug("%s command: %s %s", cmd_type, name, args) data = t.serialize(args, (AT_COMMANDS[name],)) try: return await asyncio.wait_for( self._command(cmd_type, name.encode("ascii"), data), timeout=AT_COMMAND_TIMEOUT, ) except asyncio.TimeoutError: LOGGER.warning("%s: No response to %s command", cmd_type, name) raise _at_command = functools.partialmethod(_at_partial, "at") _queued_at = functools.partialmethod(_at_partial, "queued_at") def _api_frame(self, name, *args): c = COMMAND_REQUESTS[name] return (bytes([c[0]]) + t.serialize(args, c[1])), c[2] def frame_received(self, data): command = self._commands_by_id[data[0]] LOGGER.debug("Frame received: %s", command) data, rest = t.deserialize(data[1:], COMMAND_RESPONSES[command][1]) try: getattr(self, "_handle_%s" % (command,))(*data) except AttributeError: LOGGER.error("No '%s' handler. Data: %s", command, binascii.hexlify(data)) def _handle_at_response(self, frame_id, cmd, status, value): (fut,) = self._awaiting.pop(frame_id) try: status = ATCommandResult(status) except ValueError: status = ATCommandResult.ERROR if status: fut.set_exception( RuntimeError("AT Command response: {}".format(status.name)) ) return response_type = AT_COMMANDS[cmd.decode("ascii")] if response_type is None or len(value) == 0: fut.set_result(None) return response, remains = response_type.deserialize(value) fut.set_result(response) def _handle_remote_at_response(self, frame_id, ieee, nwk, cmd, status, value): """Remote AT command response.""" LOGGER.debug( "Remote AT command response from: %s", (frame_id, ieee, nwk, cmd, status, value), ) return self._handle_at_response(frame_id, cmd, status, value) def _handle_many_to_one_rri(self, ieee, nwk, reserved): LOGGER.debug("_handle_many_to_one_rri: %s", (ieee, nwk, reserved)) def _handle_modem_status(self, status): LOGGER.debug("Handle modem status frame: %s", status) status = status if status == ModemStatus.COORDINATOR_STARTED: self.coordinator_started_event.set() elif status in (ModemStatus.HARDWARE_RESET, ModemStatus.WATCHDOG_TIMER_RESET): self.reset_event.set() self.coordinator_started_event.clear() elif status == ModemStatus.DISASSOCIATED: self.coordinator_started_event.clear() if self._app: self._app.handle_modem_status(status) def _handle_explicit_rx_indicator( self, ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data ): LOGGER.debug( "_handle_explicit_rx: %s", (ieee, nwk, dst_ep, cluster, rx_opts, binascii.hexlify(data)), ) self._app.handle_rx(ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data) def _handle_route_record_indicator(self, ieee, src, rx_opts, hops): """Handle Route Record indicator from a device.""" LOGGER.debug("_handle_route_record_indicator: %s", (ieee, src, rx_opts, hops)) def _handle_tx_status(self, frame_id, nwk, tries, tx_status, dsc_status): LOGGER.debug( ( "tx_explicit to 0x%04x: %s after %i tries. Discovery Status: %s," " Frame #%i" ), nwk, tx_status, tries, dsc_status, frame_id, ) try: (fut,) = self._awaiting.pop(frame_id) except KeyError: LOGGER.debug("unexpected tx_status report received") return try: if tx_status in ( t.TXStatus.BROADCAST_APS_TX_ATTEMPT, t.TXStatus.SELF_ADDRESSED, t.TXStatus.SUCCESS, ): fut.set_result(tx_status) else: fut.set_exception(DeliveryError("%s" % (tx_status,))) except asyncio.InvalidStateError as ex: LOGGER.debug("duplicate tx_status for %s nwk? State: %s", nwk, ex) def set_application(self, app): self._app = app def handle_command_mode_rsp(self, data): """Handle AT command response in command mode.""" fut = self._cmd_mode_future if fut is None or fut.done(): return if "OK" in data: fut.set_result(True) elif "ERROR" in data: fut.set_result(False) else: fut.set_result(data) async def command_mode_at_cmd(self, command): """Sends AT command in command mode.""" self._cmd_mode_future = asyncio.Future() self._uart.command_mode_send(command.encode("ascii")) try: res = await asyncio.wait_for(self._cmd_mode_future, timeout=2) return res except asyncio.TimeoutError: LOGGER.debug("Command mode no response to AT '%s' command", command) return None async def enter_at_command_mode(self): """Enter command mode.""" await asyncio.sleep(1.2) # keep UART quiet for 1s before escaping return await self.command_mode_at_cmd("+++") async def api_mode_at_commands(self, baudrate): """Configure API and exit AT command mode.""" cmds = ["ATAP2", "ATWR", "ATCN"] bd = BAUDRATE_TO_BD.get(baudrate) if bd: cmds.insert(0, bd) for cmd in cmds: if not await self.command_mode_at_cmd(cmd + "\r"): LOGGER.debug("No response to %s cmd", cmd) return None LOGGER.debug("Successfuly sent %s cmd", cmd) self._uart.reset_command_mode() return True async def init_api_mode(self): """Configure API mode on XBee.""" current_baudrate = self._uart.baudrate if await self.enter_at_command_mode(): LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate) return await self.api_mode_at_commands(current_baudrate) for baudrate in sorted(BAUDRATE_TO_BD.keys()): LOGGER.debug( "Failed to enter AT command mode at %dbps, trying %d next", self._uart.baudrate, baudrate, ) self._uart.baudrate = baudrate if await self.enter_at_command_mode(): LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate) res = await self.api_mode_at_commands(current_baudrate) self._uart.baudrate = current_baudrate return res LOGGER.debug( ( "Couldn't enter AT command mode at any known baudrate." "Configure XBee manually for escaped API mode ATAP2" ) ) return False @classmethod async def probe(cls, device: str, baudrate: int) -> bool: """Probe port for the device presence.""" api = cls() try: await asyncio.wait_for(api._probe(device, baudrate), timeout=PROBE_TIMEOUT) return True except (asyncio.TimeoutError, serial.SerialException, APIException) as exc: LOGGER.debug("Unsuccessful radio probe of '%s' port", exc_info=exc) finally: api.close() return False async def _probe(self, device: str, baudrate: int) -> None: """Open port and try sending a command""" await self.connect(device, baudrate) try: # Ensure we have escaped commands await self._at_command("AP", 2) except asyncio.TimeoutError: if not await self.init_api_mode(): raise APIException("Failed to configure XBee for API mode") finally: self.close() def __getattr__(self, item): if item in COMMAND_REQUESTS: return functools.partial(self._command, item) raise AttributeError("Unknown command {}".format(item))
zigpy-xbee-homeassistant
/zigpy_xbee_homeassistant-0.11.0-py3-none-any.whl/zigpy_xbee/api.py
api.py
import asyncio import binascii import logging import time import zigpy.application import zigpy.device import zigpy.exceptions import zigpy.quirks import zigpy.types import zigpy.util from zigpy.zcl.clusters.general import Groups from zigpy.zdo.types import NodeDescriptor, ZDOCmd from zigpy_xbee.types import EUI64, UNKNOWN_IEEE, UNKNOWN_NWK, TXStatus # how long coordinator would hold message for an end device in 10ms units CONF_CYCLIC_SLEEP_PERIOD = 0x0300 # end device poll timeout = 3 * SN * SP * 10ms CONF_POLL_TIMEOUT = 0x029B TIMEOUT_TX_STATUS = 120 TIMEOUT_REPLY = 5 TIMEOUT_REPLY_EXTENDED = 28 LOGGER = logging.getLogger(__name__) XBEE_ENDPOINT_ID = 0xE6 class ControllerApplication(zigpy.application.ControllerApplication): def __init__(self, api, database_file=None): super().__init__(database_file=database_file) self._api = api api.set_application(self) self._nwk = 0 async def shutdown(self): """Shutdown application.""" self._api.close() async def startup(self, auto_form=False): """Perform a complete application startup""" try: # Ensure we have escaped commands await self._api._at_command("AP", 2) except asyncio.TimeoutError: LOGGER.debug("No response to API frame. Configure API mode") if not await self._api.init_api_mode(): LOGGER.error("Failed to configure XBee API mode.") return False await self._api._at_command("AO", 0x03) serial_high = await self._api._at_command("SH") serial_low = await self._api._at_command("SL") ieee = EUI64.deserialize( serial_high.to_bytes(4, "big") + serial_low.to_bytes(4, "big") )[0] self._ieee = zigpy.types.EUI64(ieee) LOGGER.debug("Read local IEEE address as %s", self._ieee) try: association_state = await asyncio.wait_for( self._get_association_state(), timeout=4 ) except asyncio.TimeoutError: association_state = 0xFF self._nwk = await self._api._at_command("MY") enc_enabled = await self._api._at_command("EE") enc_options = await self._api._at_command("EO") zb_profile = await self._api._at_command("ZS") should_form = ( enc_enabled != 1, enc_options != 2, zb_profile != 2, association_state != 0, self._nwk != 0, ) if auto_form and any(should_form): await self.form_network() await self._api._at_command("NJ", 0) await self._api._at_command("SP", CONF_CYCLIC_SLEEP_PERIOD) await self._api._at_command("SN", CONF_POLL_TIMEOUT) id = await self._api._at_command("ID") LOGGER.debug("Extended PAN ID: 0x%016x", id) id = await self._api._at_command("OP") LOGGER.debug("Operating Extended PAN ID: 0x%016x", id) id = await self._api._at_command("OI") LOGGER.debug("PAN ID: 0x%04x", id) try: ce = await self._api._at_command("CE") LOGGER.debug("Coordinator %s", "enabled" if ce else "disabled") except RuntimeError as exc: LOGGER.debug("sending CE command: %s", exc) dev = zigpy.device.Device(self, self.ieee, self.nwk) dev.status = zigpy.device.Status.ENDPOINTS_INIT dev.add_endpoint(XBEE_ENDPOINT_ID) self.listener_event("raw_device_initialized", dev) xbee_dev = XBeeCoordinator(self, self.ieee, self.nwk, dev) self.devices[dev.ieee] = xbee_dev async def force_remove(self, dev): """Forcibly remove device from NCP.""" pass async def form_network(self, channel=15, pan_id=None, extended_pan_id=None): LOGGER.info("Forming network on channel %s", channel) scan_bitmask = 1 << (channel - 11) await self._api._queued_at("ZS", 2) await self._api._queued_at("SC", scan_bitmask) await self._api._queued_at("EE", 1) await self._api._queued_at("EO", 2) await self._api._queued_at("NK", 0) await self._api._queued_at("KY", b"ZigBeeAlliance09") await self._api._queued_at("NJ", 0) await self._api._queued_at("SP", CONF_CYCLIC_SLEEP_PERIOD) await self._api._queued_at("SN", CONF_POLL_TIMEOUT) try: await self._api._queued_at("CE", 1) except RuntimeError: pass await self._api._at_command("WR") await asyncio.wait_for(self._api.coordinator_started_event.wait(), timeout=10) association_state = await asyncio.wait_for( self._get_association_state(), timeout=10 ) LOGGER.debug("Association state: %s", association_state) self._nwk = await self._api._at_command("MY") assert self._nwk == 0x0000 async def _get_association_state(self): """Wait for Zigbee to start.""" state = await self._api._at_command("AI") while state == 0xFF: LOGGER.debug("Waiting for radio startup...") await asyncio.sleep(0.2) state = await self._api._at_command("AI") return state async def mrequest( self, group_id, profile, cluster, src_ep, sequence, data, *, hops=0, non_member_radius=3 ): """Submit and send data out as a multicast transmission. :param group_id: destination multicast address :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param sequence: transaction sequence number of the message :param data: Zigbee message payload :param hops: the message will be delivered to all nodes within this number of hops of the sender. A value of zero is converted to MAX_HOPS :param non_member_radius: the number of hops that the message will be forwarded by devices that are not members of the group. A value of 7 or greater is treated as infinite :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ LOGGER.debug("Zigbee request tsn #%s: %s", sequence, binascii.hexlify(data)) send_req = self._api.tx_explicit( UNKNOWN_IEEE, group_id, src_ep, src_ep, cluster, profile, hops, 0x08, data ) try: v = await asyncio.wait_for(send_req, timeout=TIMEOUT_TX_STATUS) except asyncio.TimeoutError: return TXStatus.NETWORK_ACK_FAILURE, "Timeout waiting for ACK" if v != TXStatus.SUCCESS: return v, "Error sending tsn #%s: %s".format(sequence, v.name) return v, "Successfully sent tsn #%s: %s".format(sequence, v.name) async def request( self, device, profile, cluster, src_ep, dst_ep, sequence, data, expect_reply=True, use_ieee=False, ): """Submit and send data out as an unicast transmission. :param device: destination device :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param dst_ep: destination endpoint id :param sequence: transaction sequence number of the message :param data: Zigbee message payload :param expect_reply: True if this is essentially a request :param use_ieee: use EUI64 for destination addressing :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ LOGGER.debug("Zigbee request tsn #%s: %s", sequence, binascii.hexlify(data)) tx_opts = 0x00 if expect_reply and device.node_desc.is_end_device in (True, None): tx_opts |= 0x40 send_req = self._api.tx_explicit( device.ieee, UNKNOWN_NWK if use_ieee else device.nwk, src_ep, dst_ep, cluster, profile, 0, tx_opts, data, ) try: v = await asyncio.wait_for(send_req, timeout=TIMEOUT_TX_STATUS) except asyncio.TimeoutError: return TXStatus.NETWORK_ACK_FAILURE, "Timeout waiting for ACK" if v != TXStatus.SUCCESS: return v, "Error sending tsn #%s: %s".format(sequence, v.name) return v, "Succesfuly sent tsn #%s: %s".format(sequence, v.name) @zigpy.util.retryable_request def remote_at_command( self, nwk, cmd_name, *args, apply_changes=True, encryption=True ): LOGGER.debug("Remote AT%s command: %s", cmd_name, args) options = zigpy.types.uint8_t(0) if apply_changes: options |= 0x02 if encryption: options |= 0x20 dev = self.get_device(nwk=nwk) return self._api._remote_at_command(dev.ieee, nwk, options, cmd_name, *args) async def permit_ncp(self, time_s=60): assert 0 <= time_s <= 254 await self._api._at_command("NJ", time_s) await self._api._at_command("AC") await self._api._at_command("CB", 2) def handle_modem_status(self, status): LOGGER.info("Modem status update: %s (%s)", status.name, status.value) def handle_rx( self, src_ieee, src_nwk, src_ep, dst_ep, cluster_id, profile_id, rxopts, data ): if src_nwk == 0: LOGGER.info("handle_rx self addressed") ember_ieee = zigpy.types.EUI64(src_ieee) if dst_ep == 0 and cluster_id == ZDOCmd.Device_annce: # ZDO Device announce request nwk, rest = zigpy.types.NWK.deserialize(data[1:]) ieee, rest = zigpy.types.EUI64.deserialize(rest) LOGGER.info("New device joined: NWK 0x%04x, IEEE %s", nwk, ieee) if ember_ieee != ieee: LOGGER.warning( "Announced IEEE %s is different from originator %s", str(ieee), str(ember_ieee), ) if src_nwk != nwk: LOGGER.warning( "Announced 0x%04x NWK is different from originator 0x%04x", nwk, src_nwk, ) self.handle_join(nwk, ieee, 0) try: self.devices[self.ieee].last_seen = time.time() except KeyError: pass try: device = self.get_device(nwk=src_nwk) except KeyError: if ember_ieee != UNKNOWN_IEEE and ember_ieee in self.devices: self.handle_join(src_nwk, ember_ieee, 0) device = self.get_device(ieee=ember_ieee) else: LOGGER.debug( "Received frame from unknown device: 0x%04x/%s", src_nwk, str(ember_ieee), ) return self.handle_message(device, profile_id, cluster_id, src_ep, dst_ep, data) async def broadcast( self, profile, cluster, src_ep, dst_ep, grpid, radius, sequence, data, broadcast_address=zigpy.types.BroadcastAddress.RX_ON_WHEN_IDLE, ): """Submit and send data out as an broadcast transmission. :param profile: Zigbee Profile ID to use for outgoing message :param cluster: cluster id where the message is being sent :param src_ep: source endpoint id :param dst_ep: destination endpoint id :param grpid: group id to address the broadcast to :param radius: max radius of the broadcast :param sequence: transaction sequence number of the message :param data: zigbee message payload :param broadcast_address: broadcast address. :returns: return a tuple of a status and an error_message. Original requestor has more context to provide a more meaningful error message """ LOGGER.debug("Broadcast request seq %s", sequence) broadcast_as_bytes = [ zigpy.types.uint8_t(b) for b in broadcast_address.to_bytes(8, "little") ] request = self._api.tx_explicit( EUI64(broadcast_as_bytes), broadcast_address, src_ep, dst_ep, cluster, profile, radius, 0x00, data, ) try: v = await asyncio.wait_for(request, timeout=TIMEOUT_TX_STATUS) except asyncio.TimeoutError: return TXStatus.NETWORK_ACK_FAILURE, "Timeout waiting for ACK" if v != TXStatus.SUCCESS: return v, "Error sending broadcast tsn #%s: %s".format(sequence, v.name) return v, "Succesfuly sent broadcast tsn #%s: %s".format(sequence, v.name) class XBeeCoordinator(zigpy.quirks.CustomDevice): class XBeeGroup(zigpy.quirks.CustomCluster, Groups): cluster_id = 0x0006 class XBeeGroupResponse(zigpy.quirks.CustomCluster, Groups): import zigpy.zcl.foundation as f cluster_id = 0x8006 ep_attribute = "xbee_groups_response" client_commands = {**Groups.client_commands} client_commands[0x0004] = ("remove_all_response", (f.Status,), True) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.node_desc = NodeDescriptor( 0x01, 0x40, 0x8E, 0x101E, 0x52, 0x00FF, 0x2C00, 0x00FF, 0x00 ) replacement = { "manufacturer": "Digi", "model": "XBee", "endpoints": { XBEE_ENDPOINT_ID: { "device_type": 0x0050, "profile_id": 0xC105, "input_clusters": [XBeeGroup, XBeeGroupResponse], "output_clusters": [], } }, }
zigpy-xbee-homeassistant
/zigpy_xbee_homeassistant-0.11.0-py3-none-any.whl/zigpy_xbee/zigbee/application.py
application.py
import enum import zigpy.types def deserialize(data, schema): result = [] for type_ in schema: value, data = type_.deserialize(data) result.append(value) return result, data def serialize(data, schema): return b"".join(t(v).serialize() for t, v in zip(schema, data)) class Bytes(bytes): def serialize(self): return self @classmethod def deserialize(cls, data): return cls(data), b"" class ATCommand(Bytes): @classmethod def deserialize(cls, data): return cls(data[:2]), data[2:] class int_t(int): _signed = True def serialize(self): return self.to_bytes(self._size, "big", signed=self._signed) @classmethod def deserialize(cls, data): # Work around https://bugs.python.org/issue23640 r = cls(int.from_bytes(data[: cls._size], "big", signed=cls._signed)) data = data[cls._size :] return r, data class int8s(int_t): _size = 1 class int16s(int_t): _size = 2 class int24s(int_t): _size = 3 class int32s(int_t): _size = 4 class int40s(int_t): _size = 5 class int48s(int_t): _size = 6 class int56s(int_t): _size = 7 class int64s(int_t): _size = 8 class uint_t(int_t): _signed = False class uint8_t(uint_t): _size = 1 class uint16_t(uint_t): _size = 2 class uint24_t(uint_t): _size = 3 class uint32_t(uint_t): _size = 4 class uint40_t(uint_t): _size = 5 class uint48_t(uint_t): _size = 6 class uint56_t(uint_t): _size = 7 class uint64_t(uint_t): _size = 8 class Bool(uint8_t, enum.Enum): # Boolean type with values true and false. false = 0x00 # An alias for zero, used for clarity. true = 0x01 # An alias for one, used for clarity. class EUI64(zigpy.types.EUI64): @classmethod def deserialize(cls, data): r, data = super().deserialize(data) return cls(r[::-1]), data def serialize(self): assert self._length == len(self) return super().serialize()[::-1] class UndefinedEnumMeta(enum.EnumMeta): def __call__(cls, value=None, *args, **kwargs): if value is None: # the 1st enum member is default return next(iter(cls)) try: return super().__call__(value, *args, **kwargs) except ValueError as exc: try: return super().__call__(cls._UNDEFINED) except AttributeError: raise exc class UndefinedEnum(enum.Enum, metaclass=UndefinedEnumMeta): pass class FrameId(uint8_t): pass class NWK(uint16_t): def __repr__(self): return "0x{:04x}".format(self) def __str__(self): return "0x{:04x}".format(self) class Relays(zigpy.types.LVList, item_type=NWK, length_type=uint8_t): """List of Relays.""" UNKNOWN_IEEE = EUI64([uint8_t(0xFF) for i in range(0, 8)]) UNKNOWN_NWK = NWK(0xFFFE) class TXStatus(uint8_t, UndefinedEnum): """TX Status frame.""" SUCCESS = 0x00 # Standard # all retries are expired and no ACK is received. # Not returned for Broadcasts NO_ACK_RECEIVED = 0x01 CCA_FAILURE = 0x02 # Transmission was purged because a coordinator tried to send to an end # device, but it timed out waiting for a poll from the end device that # never occurred, this haapens when Coordinator times out of an indirect # transmission. Timeouse is defines ad 2.5 * 'SP' (Cyclic Sleep Period) # parameter value INDIRECT_TX_TIMEOUT = 0x03 # invalid destination endpoint INVALID_DESTINATION_ENDPOINT = 0x15 # not returned for Broadcasts NETWORK_ACK_FAILURE = 0x21 # TX failed because end device was not joined to the network INDIRECT_TX_FAILURE = 0x22 # Self addressed SELF_ADDRESSED = 0x23 # Address not found ADDRESS_NOT_FOUND = 0x24 # Route not found ROUTE_NOT_FOUND = 0x25 # Broadcast source failed to hear a neighbor relay the message BROADCAST_RELAY_FAILURE = 0x26 # Invalid binding table index INVALID_BINDING_IDX = 0x2B # Resource error lack of free buffers, timers, and so forth. NO_RESOURCES = 0x2C # Attempted broadcast with APS transmission BROADCAST_APS_TX_ATTEMPT = 0x2D # Attempted unicast with APS transmission, but EE=0 UNICAST_APS_TX_ATTEMPT = 0x2E INTERNAL_ERROR = 0x31 # Transmission failed due to resource depletion (for example, out of # buffers, especially for indirect messages from coordinator) NO_RESOURCES_2 = 0x32 # The payload in the frame was larger than allowed PAYLOAD_TOO_LARGE = 0x74 _UNDEFINED = 0x2C class DiscoveryStatus(uint8_t, UndefinedEnum): """Discovery status of TX Status frame.""" SUCCESS = 0x00 ADDRESS_DISCOVERY = 0x01 ROUTE_DISCOVERY = 0x02 ADDRESS_AND_ROUTE = 0x03 EXTENDED_TIMEOUT = 0x40 _UNDEFINED = 0x00 class TXOptions(zigpy.types.bitmap8): NONE = 0x00 Disable_Retries_and_Route_Repair = 0x01 Enable_APS_Encryption = 0x20 Use_Extended_TX_Timeout = 0x40
zigpy-xbee
/zigpy_xbee-0.18.1-py3-none-any.whl/zigpy_xbee/types.py
types.py
import asyncio import logging from typing import Any, Dict import zigpy.serial from zigpy_xbee.config import CONF_DEVICE_BAUDRATE, CONF_DEVICE_PATH LOGGER = logging.getLogger(__name__) class Gateway(asyncio.Protocol): START = b"\x7E" ESCAPE = b"\x7D" XON = b"\x11" XOFF = b"\x13" RESERVED = START + ESCAPE + XON + XOFF THIS_ONE = True def __init__(self, api, connected_future=None): self._buffer = b"" self._connected_future = connected_future self._api = api self._in_command_mode = False def send(self, data): """Send data, taking care of escaping and framing""" LOGGER.debug("Sending: %s", data) checksum = bytes([self._checksum(data)]) frame = self.START + self._escape( len(data).to_bytes(2, "big") + data + checksum ) self._transport.write(frame) @property def baudrate(self): """Baudrate.""" return self._transport.serial.baudrate @baudrate.setter def baudrate(self, baudrate): """Set baudrate.""" if baudrate in self._transport.serial.BAUDRATES: self._transport.serial.baudrate = baudrate else: raise ValueError( "baudrate must be one of {}".format(self._transport.serial.BAUDRATES) ) def connection_lost(self, exc) -> None: """Port was closed expectedly or unexpectedly.""" if self._connected_future and not self._connected_future.done(): if exc is None: self._connected_future.set_result(True) else: self._connected_future.set_exception(exc) if exc is None: LOGGER.debug("Closed serial connection") return LOGGER.error("Lost serial connection: %s", exc) self._api.connection_lost(exc) def connection_made(self, transport): """Callback when the uart is connected""" LOGGER.debug("Connection made") self._transport = transport if self._connected_future: self._connected_future.set_result(True) def command_mode_rsp(self, data): """Handles AT command mode response.""" data = data.decode("ascii", "ignore") LOGGER.debug("Handling AT command mode response: %s", data) self._api.handle_command_mode_rsp(data) def command_mode_send(self, data): """Send data in command mode.""" LOGGER.debug("Command mode sending %s to uart", data) self._in_command_mode = True self._transport.write(data) def data_received(self, data): """Callback when there is data received from the uart""" self._buffer += data while self._buffer: frame = self._extract_frame() if frame is None: break self.frame_received(frame) if self._in_command_mode and self._buffer[-1:] == b"\r": rsp, self._buffer = (self._buffer[:-1], b"") self.command_mode_rsp(rsp) def frame_received(self, frame): """Frame receive handler""" LOGGER.debug("Frame received: %s", frame) self._api.frame_received(frame) def close(self): self._transport.close() def reset_command_mode(self): """Reset command mode and ignore \r character as command mode response.""" self._in_command_mode = False def _extract_frame(self): first_start = self._buffer.find(self.START) if first_start < 0: return None data = self._buffer[first_start + 1 :] frame_len, data = self._get_unescaped(data, 2) if frame_len is None: return None frame_len = int.from_bytes(frame_len, "big") frame, data = self._get_unescaped(data, frame_len) if frame is None: return None checksum, data = self._get_unescaped(data, 1) if checksum is None: return None if self._checksum(frame) != checksum[0]: # TODO: Signal decode failure so that error frame can be sent self._buffer = data return None self._buffer = data return frame def _get_unescaped(self, data, n): ret = [] idx = 0 while len(ret) < n and idx < len(data): b = data[idx] if b == self.ESCAPE[0]: idx += 1 if idx >= len(data): return None, None b = data[idx] ^ 0x020 ret.append(b) idx += 1 if len(ret) >= n: return bytes(ret), data[idx:] return None, None def _escape(self, data): ret = [] for b in data: if b in self.RESERVED: ret.append(ord(self.ESCAPE)) ret.append(b ^ 0x20) else: ret.append(b) return bytes(ret) def _checksum(self, data): return 0xFF - (sum(data) % 0x100) async def connect(device_config: Dict[str, Any], api, loop=None) -> Gateway: if loop is None: loop = asyncio.get_event_loop() connected_future = asyncio.Future() protocol = Gateway(api, connected_future) transport, protocol = await zigpy.serial.create_serial_connection( loop, lambda: protocol, url=device_config[CONF_DEVICE_PATH], baudrate=device_config[CONF_DEVICE_BAUDRATE], xonxoff=False, ) await connected_future return protocol
zigpy-xbee
/zigpy_xbee-0.18.1-py3-none-any.whl/zigpy_xbee/uart.py
uart.py
import asyncio import binascii import enum import functools import logging from typing import Any, Dict, Optional import serial from zigpy.exceptions import APIException, DeliveryError import zigpy_xbee from zigpy_xbee.config import CONF_DEVICE_BAUDRATE, CONF_DEVICE_PATH, SCHEMA_DEVICE from . import types as t, uart LOGGER = logging.getLogger(__name__) AT_COMMAND_TIMEOUT = 1 REMOTE_AT_COMMAND_TIMEOUT = 30 PROBE_TIMEOUT = 45 class ModemStatus(t.uint8_t, t.UndefinedEnum): HARDWARE_RESET = 0x00 WATCHDOG_TIMER_RESET = 0x01 JOINED_NETWORK = 0x02 DISASSOCIATED = 0x03 COORDINATOR_STARTED = 0x06 NETWORK_SECURITY_KEY_UPDATED = 0x07 VOLTAGE_SUPPLY_LIMIT_EXCEEDED = 0x0D MODEM_CONFIGURATION_CHANGED_WHILE_JOIN_IN_PROGRESS = 0x11 PAN_ID_CONFLICT_DETECTED = 0x3E PAN_ID_UPDATED_DUE_TO_CONFLICT = 0x3F JOIN_WINDOW_OPENED = 0x43 JOIN_WINDOW_CLOSED = 0x44 NETWORK_SECURITY_KEY_ROTATION_INITIATED = 0x45 UNKNOWN_MODEM_STATUS = 0xFF _UNDEFINED = 0xFF # https://www.digi.com/resources/documentation/digidocs/PDFs/90000976.pdf COMMAND_REQUESTS = { "at": (0x08, (t.FrameId, t.ATCommand, t.Bytes), 0x88), "queued_at": (0x09, (t.FrameId, t.ATCommand, t.Bytes), 0x88), "remote_at": ( 0x17, (t.FrameId, t.EUI64, t.NWK, t.uint8_t, t.ATCommand, t.Bytes), 0x97, ), "tx": (0x10, (), None), "tx_explicit": ( 0x11, ( t.FrameId, t.EUI64, t.NWK, t.uint8_t, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.Bytes, ), 0x8B, ), "create_source_route": ( 0x21, (t.FrameId, t.EUI64, t.NWK, t.uint8_t, t.Relays), None, ), "register_joining_device": (0x24, (), None), } COMMAND_RESPONSES = { "at_response": (0x88, (t.FrameId, t.ATCommand, t.uint8_t, t.Bytes), None), "modem_status": (0x8A, (ModemStatus,), None), "tx_status": ( 0x8B, (t.FrameId, t.NWK, t.uint8_t, t.TXStatus, t.DiscoveryStatus), None, ), "route_information": (0x8D, (), None), "rx": (0x90, (), None), "explicit_rx_indicator": ( 0x91, ( t.EUI64, t.NWK, t.uint8_t, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t, t.Bytes, ), None, ), "rx_io_data_long_addr": (0x92, (), None), "remote_at_response": ( 0x97, (t.FrameId, t.EUI64, t.NWK, t.ATCommand, t.uint8_t, t.Bytes), None, ), "extended_status": (0x98, (), None), "route_record_indicator": (0xA1, (t.EUI64, t.NWK, t.uint8_t, t.Relays), None), "many_to_one_rri": (0xA3, (t.EUI64, t.NWK, t.uint8_t), None), "node_id_indicator": (0x95, (), None), } # https://www.digi.com/resources/documentation/digidocs/pdfs/90001539.pdf pg 175 AT_COMMANDS = { # Addressing commands "DH": t.uint32_t, "DL": t.uint32_t, "MY": t.uint16_t, "MP": t.uint16_t, "NC": t.uint32_t, # 0 - MAX_CHILDREN. "SH": t.uint32_t, "SL": t.uint32_t, "NI": t, # 20 byte printable ascii string "SE": t.uint8_t, "DE": t.uint8_t, "CI": t.uint16_t, "TO": t.uint8_t, "NP": t.uint16_t, "DD": t.uint32_t, "CR": t.uint8_t, # 0 - 0x3F # Networking commands "CH": t.uint8_t, # 0x0B - 0x1A "DA": t, # no param "ID": t.uint64_t, "OP": t.uint64_t, "NH": t.uint8_t, "BH": t.uint8_t, # 0 - 0x1E "OI": t.uint16_t, "NT": t.uint8_t, # 0x20 - 0xFF "NO": t.uint8_t, # bitfield, 0 - 3 "SC": t.uint16_t, # 1 - 0xFFFF "SD": t.uint8_t, # 0 - 7 "ZS": t.uint8_t, # 0 - 2 "NJ": t.uint8_t, "JV": t.Bool, "NW": t.uint16_t, # 0 - 0x64FF "JN": t.Bool, "AR": t.uint8_t, "DJ": t.Bool, # WTF, docs "II": t.uint16_t, # Security commands "EE": t.Bool, "EO": t.uint8_t, "NK": t.Bytes, # 128-bit value "KY": t.Bytes, # 128-bit value # RF interfacing commands "PL": t.uint8_t, # 0 - 4 (basically an Enum) "PM": t.Bool, "DB": t.uint8_t, "PP": t.uint8_t, # RO "AP": t.uint8_t, # 1-2 (an Enum) "AO": t.uint8_t, # 0 - 3 (an Enum) "BD": t.uint8_t, # 0 - 7 (an Enum) "NB": t.uint8_t, # 0 - 3 (an Enum) "SB": t.uint8_t, # 0 - 1 (an Enum) "RO": t.uint8_t, "D6": t.uint8_t, # 0 - 5 (an Enum) "D7": t.uint8_t, # 0 - 7 (an Enum) "P3": t.uint8_t, # 0 - 5 (an Enum) "P4": t.uint8_t, # 0 - 5 (an Enum) # I/O commands "IR": t.uint16_t, "IC": t.uint16_t, "D0": t.uint8_t, # 0 - 5 (an Enum) "D1": t.uint8_t, # 0 - 5 (an Enum) "D2": t.uint8_t, # 0 - 5 (an Enum) "D3": t.uint8_t, # 0 - 5 (an Enum) "D4": t.uint8_t, # 0 - 5 (an Enum) "D5": t.uint8_t, # 0 - 5 (an Enum) "D8": t.uint8_t, # 0 - 5 (an Enum) "D9": t.uint8_t, # 0 - 5 (an Enum) "P0": t.uint8_t, # 0 - 5 (an Enum) "P1": t.uint8_t, # 0 - 5 (an Enum) "P2": t.uint8_t, # 0 - 5 (an Enum) "P5": t.uint8_t, # 0 - 5 (an Enum) "P6": t.uint8_t, # 0 - 5 (an Enum) "P7": t.uint8_t, # 0 - 5 (an Enum) "P8": t.uint8_t, # 0 - 5 (an Enum) "P9": t.uint8_t, # 0 - 5 (an Enum) "LT": t.uint8_t, "PR": t.uint16_t, "RP": t.uint8_t, "%V": t.uint16_t, # read only "V+": t.uint16_t, "TP": t.uint16_t, "M0": t.uint16_t, # 0 - 0x3FF "M1": t.uint16_t, # 0 - 0x3FF # Diagnostics commands "VR": t.uint16_t, "HV": t.uint16_t, "AI": t.uint8_t, # AT command options "CT": t.uint16_t, # 2 - 0x028F "CN": None, "GT": t.uint16_t, "CC": t.uint8_t, # Sleep commands "SM": t.uint8_t, "SN": t.uint16_t, "SP": t.uint16_t, "ST": t.uint16_t, "SO": t.uint8_t, "WH": t.uint16_t, "SI": None, "PO": t.uint16_t, # 0 - 0x3E8 # Execution commands "AC": None, "WR": None, "RE": None, "FR": None, "NR": t.Bool, "SI": None, "CB": t.uint8_t, "ND": t, # "optional 2-Byte NI value" "DN": t.Bytes, # "up to 20-Byte printable ASCII string" "IS": None, "1S": None, "AS": None, # Stuff I've guessed "CE": t.uint8_t, } BAUDRATE_TO_BD = { 1200: "ATBD0", 2400: "ATBD1", 4800: "ATBD2", 9600: "ATBD3", 19200: "ATBD4", 38400: "ATBD5", 57600: "ATBD6", 115200: "ATBD7", 230400: "ATBD8", } class ATCommandResult(enum.IntEnum): OK = 0 ERROR = 1 INVALID_COMMAND = 2 INVALID_PARAMETER = 3 TX_FAILURE = 4 class XBee: def __init__(self, device_config: Dict[str, Any]) -> None: self._config = device_config self._uart: Optional[uart.Gateway] = None self._seq: int = 1 self._commands_by_id = {v[0]: k for k, v in COMMAND_RESPONSES.items()} self._awaiting = {} self._app = None self._cmd_mode_future: Optional[asyncio.Future] = None self._conn_lost_task: Optional[asyncio.Task] = None self._reset: asyncio.Event = asyncio.Event() self._running: asyncio.Event = asyncio.Event() @property def reset_event(self): """Return reset event.""" return self._reset @property def coordinator_started_event(self): """Return coordinator started.""" return self._running @property def is_running(self): """Return true if coordinator is running.""" return self.coordinator_started_event.is_set() @classmethod async def new( cls, application: "zigpy_xbee.zigbee.application.ControllerApplication", config: Dict[str, Any], ) -> "XBee": """Create new instance from""" xbee_api = cls(config) await xbee_api.connect() xbee_api.set_application(application) return xbee_api async def connect(self) -> None: assert self._uart is None self._uart = await uart.connect(self._config, self) def reconnect(self): """Reconnect using saved parameters.""" LOGGER.debug( "Reconnecting '%s' serial port using %s", self._config[CONF_DEVICE_PATH], self._config[CONF_DEVICE_BAUDRATE], ) return self.connect() def connection_lost(self, exc: Exception) -> None: """Lost serial connection.""" LOGGER.warning( "Serial '%s' connection lost unexpectedly: %s", self._config[CONF_DEVICE_PATH], exc, ) self._uart = None if self._conn_lost_task and not self._conn_lost_task.done(): self._conn_lost_task.cancel() self._conn_lost_task = asyncio.create_task(self._connection_lost()) async def _connection_lost(self) -> None: """Reconnect serial port.""" try: await self._reconnect_till_done() except asyncio.CancelledError: LOGGER.debug("Cancelling reconnection attempt") raise async def _reconnect_till_done(self) -> None: attempt = 1 while True: try: await asyncio.wait_for(self.reconnect(), timeout=10) break except (asyncio.TimeoutError, OSError) as exc: wait = 2 ** min(attempt, 5) attempt += 1 LOGGER.debug( "Couldn't re-open '%s' serial port, retrying in %ss: %s", self._config[CONF_DEVICE_PATH], wait, str(exc), ) await asyncio.sleep(wait) LOGGER.debug( "Reconnected '%s' serial port after %s attempts", self._config[CONF_DEVICE_PATH], attempt, ) def close(self): if self._uart: self._uart.close() self._uart = None def _command(self, name, *args, mask_frame_id=False): LOGGER.debug("Command %s %s", name, args) if self._uart is None: raise APIException("API is not running") frame_id = 0 if mask_frame_id else self._seq data, needs_response = self._api_frame(name, frame_id, *args) self._uart.send(data) future = None if needs_response and frame_id: future = asyncio.Future() self._awaiting[frame_id] = (future,) self._seq = (self._seq % 255) + 1 return future async def _remote_at_command(self, ieee, nwk, options, name, *args): LOGGER.debug("Remote AT command: %s %s", name, args) data = t.serialize(args, (AT_COMMANDS[name],)) try: return await asyncio.wait_for( self._command( "remote_at", ieee, nwk, options, name.encode("ascii"), data ), timeout=REMOTE_AT_COMMAND_TIMEOUT, ) except asyncio.TimeoutError: LOGGER.warning("No response to %s command", name) raise async def _at_partial(self, cmd_type, name, *args): LOGGER.debug("%s command: %s %s", cmd_type, name, args) data = t.serialize(args, (AT_COMMANDS[name],)) try: return await asyncio.wait_for( self._command(cmd_type, name.encode("ascii"), data), timeout=AT_COMMAND_TIMEOUT, ) except asyncio.TimeoutError: LOGGER.warning("%s: No response to %s command", cmd_type, name) raise _at_command = functools.partialmethod(_at_partial, "at") _queued_at = functools.partialmethod(_at_partial, "queued_at") def _api_frame(self, name, *args): c = COMMAND_REQUESTS[name] return (bytes([c[0]]) + t.serialize(args, c[1])), c[2] def frame_received(self, data): command = self._commands_by_id[data[0]] LOGGER.debug("Frame received: %s", command) data, rest = t.deserialize(data[1:], COMMAND_RESPONSES[command][1]) try: getattr(self, "_handle_%s" % (command,))(*data) except AttributeError: LOGGER.error("No '%s' handler. Data: %s", command, binascii.hexlify(data)) def _handle_at_response(self, frame_id, cmd, status, value): (fut,) = self._awaiting.pop(frame_id) try: status = ATCommandResult(status) except ValueError: status = ATCommandResult.ERROR if status: fut.set_exception( RuntimeError("AT Command response: {}".format(status.name)) ) return response_type = AT_COMMANDS[cmd.decode("ascii")] if response_type is None or len(value) == 0: fut.set_result(None) return response, remains = response_type.deserialize(value) fut.set_result(response) def _handle_remote_at_response(self, frame_id, ieee, nwk, cmd, status, value): """Remote AT command response.""" LOGGER.debug( "Remote AT command response from: %s", (frame_id, ieee, nwk, cmd, status, value), ) return self._handle_at_response(frame_id, cmd, status, value) def _handle_many_to_one_rri(self, ieee, nwk, reserved): LOGGER.debug("_handle_many_to_one_rri: %s", (ieee, nwk, reserved)) def _handle_modem_status(self, status): LOGGER.debug("Handle modem status frame: %s", status) status = status if status == ModemStatus.COORDINATOR_STARTED: self.coordinator_started_event.set() elif status in (ModemStatus.HARDWARE_RESET, ModemStatus.WATCHDOG_TIMER_RESET): self.reset_event.set() self.coordinator_started_event.clear() elif status == ModemStatus.DISASSOCIATED: self.coordinator_started_event.clear() if self._app: self._app.handle_modem_status(status) def _handle_explicit_rx_indicator( self, ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data ): LOGGER.debug( "_handle_explicit_rx: %s", (ieee, nwk, dst_ep, cluster, rx_opts, binascii.hexlify(data)), ) self._app.handle_rx(ieee, nwk, src_ep, dst_ep, cluster, profile, rx_opts, data) def _handle_route_record_indicator(self, ieee, src, rx_opts, hops): """Handle Route Record indicator from a device.""" LOGGER.debug("_handle_route_record_indicator: %s", (ieee, src, rx_opts, hops)) def _handle_tx_status(self, frame_id, nwk, tries, tx_status, dsc_status): LOGGER.debug( ( "tx_explicit to 0x%04x: %s after %i tries. Discovery Status: %s," " Frame #%i" ), nwk, tx_status, tries, dsc_status, frame_id, ) try: (fut,) = self._awaiting.pop(frame_id) except KeyError: LOGGER.debug("unexpected tx_status report received") return try: if tx_status in ( t.TXStatus.BROADCAST_APS_TX_ATTEMPT, t.TXStatus.SELF_ADDRESSED, t.TXStatus.SUCCESS, ): fut.set_result(tx_status) else: fut.set_exception(DeliveryError("%s" % (tx_status,))) except asyncio.InvalidStateError as ex: LOGGER.debug("duplicate tx_status for %s nwk? State: %s", nwk, ex) def set_application(self, app): self._app = app def handle_command_mode_rsp(self, data): """Handle AT command response in command mode.""" fut = self._cmd_mode_future if fut is None or fut.done(): return if "OK" in data: fut.set_result(True) elif "ERROR" in data: fut.set_result(False) else: fut.set_result(data) async def command_mode_at_cmd(self, command): """Sends AT command in command mode.""" self._cmd_mode_future = asyncio.Future() self._uart.command_mode_send(command.encode("ascii")) try: res = await asyncio.wait_for(self._cmd_mode_future, timeout=2) return res except asyncio.TimeoutError: LOGGER.debug("Command mode no response to AT '%s' command", command) return None async def enter_at_command_mode(self): """Enter command mode.""" await asyncio.sleep(1.2) # keep UART quiet for 1s before escaping return await self.command_mode_at_cmd("+++") async def api_mode_at_commands(self, baudrate): """Configure API and exit AT command mode.""" cmds = ["ATAP2", "ATWR", "ATCN"] bd = BAUDRATE_TO_BD.get(baudrate) if bd: cmds.insert(0, bd) for cmd in cmds: if not await self.command_mode_at_cmd(cmd + "\r"): LOGGER.debug("No response to %s cmd", cmd) return None LOGGER.debug("Successfuly sent %s cmd", cmd) self._uart.reset_command_mode() return True async def init_api_mode(self): """Configure API mode on XBee.""" current_baudrate = self._uart.baudrate if await self.enter_at_command_mode(): LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate) return await self.api_mode_at_commands(current_baudrate) for baudrate in sorted(BAUDRATE_TO_BD.keys()): LOGGER.debug( "Failed to enter AT command mode at %dbps, trying %d next", self._uart.baudrate, baudrate, ) self._uart.baudrate = baudrate if await self.enter_at_command_mode(): LOGGER.debug("Entered AT Command mode at %dbps.", self._uart.baudrate) res = await self.api_mode_at_commands(current_baudrate) self._uart.baudrate = current_baudrate return res LOGGER.debug( ( "Couldn't enter AT command mode at any known baudrate." "Configure XBee manually for escaped API mode ATAP2" ) ) return False @classmethod async def probe(cls, device_config: Dict[str, Any]) -> bool: """Probe port for the device presence.""" api = cls(SCHEMA_DEVICE(device_config)) try: await asyncio.wait_for(api._probe(), timeout=PROBE_TIMEOUT) return True except (asyncio.TimeoutError, serial.SerialException, APIException) as exc: LOGGER.debug( "Unsuccessful radio probe of '%s' port", device_config[CONF_DEVICE_PATH], exc_info=exc, ) finally: api.close() return False async def _probe(self) -> None: """Open port and try sending a command""" await self.connect() try: # Ensure we have escaped commands await self._at_command("AP", 2) except asyncio.TimeoutError: if not await self.init_api_mode(): raise APIException("Failed to configure XBee for API mode") finally: self.close() def __getattr__(self, item): if item in COMMAND_REQUESTS: return functools.partial(self._command, item) raise AttributeError("Unknown command {}".format(item))
zigpy-xbee
/zigpy_xbee-0.18.1-py3-none-any.whl/zigpy_xbee/api.py
api.py
from __future__ import annotations import asyncio import logging import time from typing import Any import zigpy.application import zigpy.config import zigpy.device import zigpy.exceptions import zigpy.quirks import zigpy.state import zigpy.types import zigpy.util from zigpy.zcl import foundation from zigpy.zcl.clusters.general import Groups import zigpy.zdo.types as zdo_t import zigpy_xbee import zigpy_xbee.api from zigpy_xbee.config import CONF_DEVICE, CONFIG_SCHEMA, SCHEMA_DEVICE from zigpy_xbee.types import EUI64, UNKNOWN_IEEE, UNKNOWN_NWK, TXOptions, TXStatus # how long coordinator would hold message for an end device in 10ms units CONF_CYCLIC_SLEEP_PERIOD = 0x0300 # end device poll timeout = 3 * SN * SP * 10ms CONF_POLL_TIMEOUT = 0x029B TIMEOUT_TX_STATUS = 120 TIMEOUT_REPLY = 5 TIMEOUT_REPLY_EXTENDED = 28 LOGGER = logging.getLogger(__name__) XBEE_ENDPOINT_ID = 0xE6 class ControllerApplication(zigpy.application.ControllerApplication): SCHEMA = CONFIG_SCHEMA SCHEMA_DEVICE = SCHEMA_DEVICE probe = zigpy_xbee.api.XBee.probe def __init__(self, config: dict[str, Any]): super().__init__(config=zigpy.config.ZIGPY_SCHEMA(config)) self._api: zigpy_xbee.api.XBee | None = None async def disconnect(self): """Shutdown application.""" if self._api: self._api.close() async def connect(self): self._api = await zigpy_xbee.api.XBee.new(self, self._config[CONF_DEVICE]) try: # Ensure we have escaped commands await self._api._at_command("AP", 2) except asyncio.TimeoutError: LOGGER.debug("No response to API frame. Configure API mode") if not await self._api.init_api_mode(): raise zigpy.exceptions.ControllerException( "Failed to configure XBee API mode." ) async def start_network(self): association_state = await asyncio.wait_for( self._get_association_state(), timeout=4 ) # Enable ZDO passthrough await self._api._at_command("AO", 0x03) if self.state.node_info == zigpy.state.NodeInfo(): await self.load_network_info() enc_enabled = await self._api._at_command("EE") enc_options = await self._api._at_command("EO") zb_profile = await self._api._at_command("ZS") if ( enc_enabled != 1 or enc_options & 0b0010 != 0b0010 or zb_profile != 2 or association_state != 0 or self.state.node_info.nwk != 0x0000 ): raise zigpy.exceptions.NetworkNotFormed("Network is not formed") # Disable joins await self._api._at_command("NJ", 0) await self._api._at_command("SP", CONF_CYCLIC_SLEEP_PERIOD) await self._api._at_command("SN", CONF_POLL_TIMEOUT) dev = zigpy.device.Device( self, self.state.node_info.ieee, self.state.node_info.nwk ) dev.status = zigpy.device.Status.ENDPOINTS_INIT dev.add_endpoint(XBEE_ENDPOINT_ID) xbee_dev = XBeeCoordinator( self, self.state.node_info.ieee, self.state.node_info.nwk, dev ) self.listener_event("raw_device_initialized", xbee_dev) self.devices[dev.ieee] = xbee_dev async def load_network_info(self, *, load_devices=False): # Load node info node_info = self.state.node_info node_info.nwk = zigpy.types.NWK(await self._api._at_command("MY")) serial_high = await self._api._at_command("SH") serial_low = await self._api._at_command("SL") node_info.ieee = zigpy.types.EUI64( (serial_high.to_bytes(4, "big") + serial_low.to_bytes(4, "big"))[::-1] ) try: if await self._api._at_command("CE") == 0x01: node_info.logical_type = zdo_t.LogicalType.Coordinator else: node_info.logical_type = zdo_t.LogicalType.EndDevice except RuntimeError: LOGGER.warning("CE command failed, assuming node is coordinator") node_info.logical_type = zdo_t.LogicalType.Coordinator # Load network info pan_id = await self._api._at_command("OI") extended_pan_id = await self._api._at_command("ID") network_info = self.state.network_info network_info.source = f"zigpy-xbee@{zigpy_xbee.__version__}" network_info.pan_id = zigpy.types.PanId(pan_id) network_info.extended_pan_id = zigpy.types.ExtendedPanId( zigpy.types.uint64_t(extended_pan_id).serialize() ) network_info.channel = await self._api._at_command("CH") async def reset_network_info(self) -> None: await self._api._at_command("NR", 0) async def write_network_info(self, *, network_info, node_info): epid, _ = zigpy.types.uint64_t.deserialize( network_info.extended_pan_id.serialize() ) await self._api._queued_at("ID", epid) await self._api._queued_at("ZS", 2) scan_bitmask = 1 << (network_info.channel - 11) await self._api._queued_at("SC", scan_bitmask) await self._api._queued_at("EE", 1) await self._api._queued_at("EO", 0b0010) await self._api._queued_at("NK", network_info.network_key.key.serialize()) await self._api._queued_at("KY", network_info.tc_link_key.key.serialize()) await self._api._queued_at("NJ", 0) await self._api._queued_at("SP", CONF_CYCLIC_SLEEP_PERIOD) await self._api._queued_at("SN", CONF_POLL_TIMEOUT) try: await self._api._queued_at("CE", 1) except RuntimeError: pass await self._api._at_command("WR") await asyncio.wait_for(self._api.coordinator_started_event.wait(), timeout=10) association_state = await asyncio.wait_for( self._get_association_state(), timeout=10 ) LOGGER.debug("Association state: %s", association_state) async def _move_network_to_channel( self, new_channel: int, new_nwk_update_id: int ) -> None: """Moves the coordinator to a new channel.""" scan_bitmask = 1 << (new_channel - 11) await self._api._queued_at("SC", scan_bitmask) async def energy_scan( self, channels: zigpy.types.Channels, duration_exp: int, count: int ) -> dict[int, float]: """Runs an energy detection scan and returns the per-channel scan results.""" LOGGER.warning("Coordinator does not support energy scanning") return {c: 0 for c in channels} async def force_remove(self, dev): """Forcibly remove device from NCP.""" pass async def add_endpoint(self, descriptor): """Register a new endpoint on the device.""" # This is not provided by the XBee API pass async def _get_association_state(self): """Wait for Zigbee to start.""" state = await self._api._at_command("AI") while state == 0xFF: LOGGER.debug("Waiting for radio startup...") await asyncio.sleep(0.2) state = await self._api._at_command("AI") return state async def send_packet(self, packet: zigpy.types.ZigbeePacket) -> None: LOGGER.debug("Sending packet %r", packet) try: device = self.get_device_with_address(packet.dst) except (KeyError, ValueError): device = None tx_opts = TXOptions.NONE if packet.extended_timeout: tx_opts |= TXOptions.Use_Extended_TX_Timeout if packet.dst.addr_mode == zigpy.types.AddrMode.Group: tx_opts |= 0x08 # where did this come from? long_addr = UNKNOWN_IEEE short_addr = UNKNOWN_NWK if packet.dst.addr_mode == zigpy.types.AddrMode.Broadcast: long_addr = EUI64( [ zigpy.types.uint8_t(b) for b in packet.dst.address.to_bytes(8, "little") ] ) short_addr = packet.dst.address elif packet.dst.addr_mode == zigpy.types.AddrMode.Group: short_addr = packet.dst.address elif packet.dst.addr_mode == zigpy.types.AddrMode.IEEE: long_addr = EUI64(packet.dst.address) elif device is not None: long_addr = EUI64(device.ieee) short_addr = device.nwk else: raise zigpy.exceptions.DeliveryError( "Cannot send a packet to a device without a known IEEE address" ) send_req = self._api.tx_explicit( long_addr, short_addr, packet.src_ep or 0, packet.dst_ep or 0, packet.cluster_id, packet.profile_id, packet.radius, tx_opts, packet.data.serialize(), ) try: v = await asyncio.wait_for(send_req, timeout=TIMEOUT_TX_STATUS) except asyncio.TimeoutError: raise zigpy.exceptions.DeliveryError( "Timeout waiting for ACK", status=TXStatus.NETWORK_ACK_FAILURE ) if v != TXStatus.SUCCESS: raise zigpy.exceptions.DeliveryError( f"Failed to deliver packet: {v!r}", status=v ) @zigpy.util.retryable_request() def remote_at_command( self, nwk, cmd_name, *args, apply_changes=True, encryption=True ): LOGGER.debug("Remote AT%s command: %s", cmd_name, args) options = zigpy.types.uint8_t(0) if apply_changes: options |= 0x02 if encryption: options |= 0x10 dev = self.get_device(nwk=nwk) return self._api._remote_at_command(dev.ieee, nwk, options, cmd_name, *args) async def permit_ncp(self, time_s=60): assert 0 <= time_s <= 254 await self._api._at_command("NJ", time_s) await self._api._at_command("AC") async def permit_with_key(self, node, code, time_s=60): raise NotImplementedError("XBee does not support install codes") def handle_modem_status(self, status): LOGGER.info("Modem status update: %s (%s)", status.name, status.value) def handle_rx( self, src_ieee, src_nwk, src_ep, dst_ep, cluster_id, profile_id, rxopts, data ): if src_nwk == 0: LOGGER.info("handle_rx self addressed") ember_ieee = zigpy.types.EUI64(src_ieee) if dst_ep == 0 and cluster_id == zdo_t.ZDOCmd.Device_annce: # ZDO Device announce request nwk, rest = zigpy.types.NWK.deserialize(data[1:]) ieee, rest = zigpy.types.EUI64.deserialize(rest) LOGGER.info("New device joined: NWK 0x%04x, IEEE %s", nwk, ieee) if ember_ieee != ieee: LOGGER.warning( "Announced IEEE %s is different from originator %s", str(ieee), str(ember_ieee), ) if src_nwk != nwk: LOGGER.warning( "Announced 0x%04x NWK is different from originator 0x%04x", nwk, src_nwk, ) self.handle_join(nwk, ieee, 0) try: self._device.last_seen = time.time() except KeyError: pass try: device = self.get_device(nwk=src_nwk) except KeyError: if ember_ieee != UNKNOWN_IEEE and ember_ieee in self.devices: self.handle_join(src_nwk, ember_ieee, 0) device = self.get_device(ieee=ember_ieee) else: LOGGER.debug( "Received frame from unknown device: 0x%04x/%s", src_nwk, str(ember_ieee), ) return self.handle_message(device, profile_id, cluster_id, src_ep, dst_ep, data) class XBeeCoordinator(zigpy.quirks.CustomDevice): class XBeeGroup(zigpy.quirks.CustomCluster, Groups): cluster_id = 0x0006 class XBeeGroupResponse(zigpy.quirks.CustomCluster, Groups): cluster_id = 0x8006 ep_attribute = "xbee_groups_response" client_commands = { **Groups.client_commands, 0x04: foundation.ZCLCommandDef( "remove_all_response", {"status": foundation.Status}, direction=foundation.Direction.Client_to_Server, ), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.node_desc = zdo_t.NodeDescriptor( logical_type=zdo_t.LogicalType.Coordinator, complex_descriptor_available=0, user_descriptor_available=0, reserved=0, aps_flags=0, frequency_band=zdo_t.NodeDescriptor.FrequencyBand.Freq2400MHz, mac_capability_flags=( zdo_t.NodeDescriptor.MACCapabilityFlags.AllocateAddress | zdo_t.NodeDescriptor.MACCapabilityFlags.RxOnWhenIdle | zdo_t.NodeDescriptor.MACCapabilityFlags.MainsPowered | zdo_t.NodeDescriptor.MACCapabilityFlags.FullFunctionDevice ), manufacturer_code=4126, maximum_buffer_size=82, maximum_incoming_transfer_size=255, server_mask=11264, maximum_outgoing_transfer_size=255, descriptor_capability_field=zdo_t.NodeDescriptor.DescriptorCapability.NONE, ) replacement = { "manufacturer": "Digi", "model": "XBee", "endpoints": { XBEE_ENDPOINT_ID: { "device_type": 0x0050, "profile_id": 0xC105, "input_clusters": [XBeeGroup, XBeeGroupResponse], "output_clusters": [], } }, }
zigpy-xbee
/zigpy_xbee-0.18.1-py3-none-any.whl/zigpy_xbee/zigbee/application.py
application.py
# zigpy-zboss **zigpy-zboss** is a Python library project that adds support for common Nordic Semiconductor nRF modules to **[zigpy (a open source Python Zigbee stack project)](https://github.com/zigpy/)** and other Network Co-Processor radios that uses firmware based on **[ZOI (ZBOSS Open Initiative) by DSR](https://dsr-zoi.com/)**. Together with the zigpy library and a home automation software application with compatible Zigbee gateway implementation, (such as for example the **[Home Assistant's ZHA integration component](https://www.home-assistant.io/integrations/zha/)**), you can directly control Zigbee devices from most product manufacturers, like; IKEA, Philips Hue, Inovelli, LEDVANCE/OSRAM, SmartThings/Samsung, SALUS/Computime, SONOFF/ITEAD, Xiaomi/Aqara, and many more. # Hardware requirements Nordic Semi USB adapters and development kits/boards based on nRF52840 SoC are used as reference hardware in the zigpy-zboss project: - **[nRF52840 dongle](https://www.nordicsemi.com/Products/Development-hardware/nrf52840-dongle)** - **[nRF52840 development kit](https://www.nordicsemi.com/Products/Development-hardware/nrf52840-dk)** # Firmware Development and testing in zigpy-zboss project is done with a firmware image built using the [ZBOSS NCP Host sample](https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/samples/zigbee/ncp/README.html) from Nordic Semi: - **[nrf-zboss-ncp](https://github.com/kardia-as/nrf-zboss-ncp)** - Compiled ZBOSS NCP Host firmware image required to be flash on the nRF52840 device. # Releases via PyPI Tagged versions will also be released via PyPI - https://pypi.org/project/zigpy-zboss/ - https://pypi.org/project/zigpy-zboss/#history - https://pypi.org/project/zigpy-zboss/#files # External links, documentation, and other development references - [ZBOSS NCP Serial Protocol (v1.5) prepared by DSR Corporation for ZOI](https://cloud.dsr-corporation.com/index.php/s/BAn4LtRWbJjFiAm) - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/index.html - Specifically see the ZBOSS NCP sample, Zigbee CLI examples, and the ZBOSS NCP Host user guide. - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/samples/zigbee/ncp/README.html - https://infocenter.nordicsemi.com/index.jsp?topic=%2Fsdk_tz_v4.1.0%2Fzigbee_only_examples.html - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/zboss/3.6.0.0/zboss_ncp_host_intro.html - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/protocols/zigbee/architectures.html#ug-zigbee-platform-design-ncp-details - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/samples/zigbee/ncp/README.html#zigbee-ncp-sample - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/protocols/zigbee/tools.html#ug-zigbee-tools-ncp-host - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/zboss/3.6.0.0/zboss_ncp_host.html - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/zboss/3.11.2.1/zboss_ncp_host_intro.html - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/protocols/zigbee/tools.html - https://developer.nordicsemi.com/nRF_Connect_SDK/doc/latest/nrf/protocols/zigbee/tools.html#ug-zigbee-tools-ncp-host - [ZBOSS NCP Host (v2.2.1) source code](https://developer.nordicsemi.com/Zigbee/ncp_sdk_for_host/ncp_host_v2.2.1.zip) - https://github.com/zigpy/zigpy/issues/394 - Previous development discussion about ZBOSS radio library for zigpy. - https://github.com/zigpy/zigpy/discussions/595 - Reference collections for Zigbee Stack and related dev docks - https://github.com/MeisterBob/zigpy_nrf52 - Other attemt at making a zigpy library for nFR52 - https://gist.github.com/tomchy/04ac4ff78d6e117d33ab92d9cc1de779 - Another attemt at making a zigpy controller for nFR ## Other radio libraries for zigpy to use as reference projects Note! The initial development of the zigpy-zboss radio library for zigpy stems from information learned from the work in the **[zigpy-znp](https://github.com/zigpy/zigpy-znp)** project. ### zigpy-znp The **[zigpy-znp](https://github.com/zigpy/zigpy-znp)** zigpy radio library for Texas Instruments Z-Stack ZNP interface and has been the primary reference to base the zigpy-zboss radio library on. zigpy-znp is very stable with TI Z-Stack 3.x.x, ([zigpy-znp also offers some stand-alone CLI tools](https://github.com/zigpy/zigpy-znp/blob/dev/TOOLS.md) that are unique for Texas Instruments hardware and Zigbee stack). ### zigpy-deconz The **[zigpy-deconz](https://github.com/zigpy/zigpy-deconz)** is another mature radio library for Dresden Elektronik's [deCONZ Serial Protocol interface](https://github.com/dresden-elektronik/deconz-serial-protocol) that is used by the deconz firmware for their ConBee and RaspBee seriies of Zigbee Coordinator adapters. Existing zigpy developers previous advice has been to also look at zigpy-deconz since it is somewhat similar to the ZBOSS serial protocol implementation. ##### zigpy deconz parser [zigpy-deconz-parser](https://github.com/zha-ng/zigpy-deconz-parser) allow developers to parse Home Assistant's ZHA component debug logs using the zigpy-deconz radio library if you are using a deCONZ based adapter like ConBee or RaspBee. ### bellows The **[bellows](https://github.com/zigpy/bellows)** is made Silicon Labs [EZSP (EmberZNet Serial Protocol)](https://www.silabs.com/documents/public/user-guides/ug100-ezsp-reference-guide.pdf) interface and is another mature zigpy radio library project worth taking a look at as a reference, (as both it and some other zigpy radio libraires have some unique features and functions that others do not). # How to contribute If you are looking to make a code or documentation contribution to this project suggest that you try to follow the steps in the contributions guide documentation from the zigpy project and its wiki: - https://github.com/zigpy/zigpy/blob/dev/Contributors.md - https://github.com/zigpy/zigpy/wiki Also see: - https://github.com/firstcontributions/first-contributions/blob/master/README.md - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md # Related projects ### zigpy **[zigpy](https://github.com/zigpy/zigpy)** is a **[Zigbee protocol stack](https://en.wikipedia.org/wiki/Zigbee)** integration project to implement the **[Zigbee Home Automation](https://www.zigbee.org/)** standard as a Python library. Zigbee Home Automation integration with zigpy allows you to connect one of many off-the-shelf Zigbee adapters using one of the available Zigbee radio library modules compatible with zigpy to control Zigbee devices. There is currently support for controlling Zigbee device types such as binary sensors (e.g. motion and door sensors), analog sensors (e.g. temperature sensors), lightbulbs, switches, and fans. Zigpy is tightly integrated with **[Home Assistant](https://www.home-assistant.io)**'s **[ZHA component](https://www.home-assistant.io/components/zha/)** and provides a user-friendly interface for working with a Zigbee network. ### zigpy-cli (zigpy command line interface) [zigpy-cli](https://github.com/zigpy/zigpy-cli) is a unified command line interface for zigpy radios. The goal of this project is to allow low-level network management from an intuitive command line interface and to group useful Zigbee tools into a single binary. ### ZHA Device Handlers ZHA deviation handling in Home Assistant relies on the third-party [ZHA Device Handlers](https://github.com/zigpy/zha-device-handlers) project (also known unders zha-quirks package name on PyPI). Zigbee devices that deviate from or do not fully conform to the standard specifications set by the [Zigbee Alliance](https://www.zigbee.org) may require the development of custom [ZHA Device Handlers](https://github.com/zigpy/zha-device-handlers) (ZHA custom quirks handler implementation) to for all their functions to work properly with the ZHA component in Home Assistant. These ZHA Device Handlers for Home Assistant can thus be used to parse custom messages to and from non-compliant Zigbee devices. The custom quirks implementations for zigpy implemented as ZHA Device Handlers for Home Assistant are a similar concept to that of [Hub-connected Device Handlers for the SmartThings platform](https://docs.smartthings.com/en/latest/device-type-developers-guide/) as well as that of [zigbee-herdsman converters as used by Zigbee2mqtt](https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html), meaning they are each virtual representations of a physical device that expose additional functionality that is not provided out-of-the-box by the existing integration between these platforms. ### ZHA integration component for Home Assistant [ZHA integration component for Home Assistant](https://www.home-assistant.io/integrations/zha/) is a reference implementation of the zigpy library as integrated into the core of **[Home Assistant](https://www.home-assistant.io)** (a Python based open source home automation software). There are also other GUI and non-GUI projects for Home Assistant's ZHA components which builds on or depends on its features and functions to enhance or improve its user-experience, some of those are listed and linked below. #### ZHA Toolkit [ZHA Toolkit](https://github.com/mdeweerd/zha-toolkit) is a custom service for "rare" Zigbee operations using the [ZHA integration component](https://www.home-assistant.io/integrations/zha) in [Home Assistant](https://www.home-assistant.io/). The purpose of ZHA Toolkit and its Home Assistant 'Services' feature, is to provide direct control over low level zigbee commands provided in ZHA or zigpy that are not otherwise available or too limited for some use cases. ZHA Toolkit can also; serve as a framework to do local low level coding (the modules are reloaded on each call), provide access to some higher level commands such as ZNP backup (and restore), make it easier to perform one-time operations where (some) Zigbee knowledge is sufficient and avoiding the need to understand the inner workings of ZHA or Zigpy (methods, quirks, etc). #### ZHA Device Exporter [zha-device-exporter](https://github.com/dmulcahey/zha-device-exporter) is a custom component for Home Assistant to allow the ZHA component to export lists of Zigbee devices. #### ZHA Network Visualization Card [zha-network-visualization-card](https://github.com/dmulcahey/zha-network-visualization-card) was a custom Lovelace element for Home Assistant which visualize the Zigbee network for the ZHA component. #### ZHA Network Card [zha-network-card](https://github.com/dmulcahey/zha-network-card) was a custom Lovelace card for Home Assistant that displays ZHA component Zigbee network and device information in Home Assistant
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/README.md
README.md
import serial import asyncio import logging import async_timeout import serial_asyncio import logging.handlers from zigpy_zboss import types as t DEBUG_LOG_FILE_NAME = "ncp_debug.log" DEBUG_LOGGER = logging.getLogger(__name__) LOG_FORMAT = ("%(asctime)s [%(levelname)s]: %(message)s") LOG_LEVEL = logging.DEBUG default_log_file_path = "/tmp/" + DEBUG_LOG_FILE_NAME RECONNECT_TIMEOUT = 10 DEBUG_LOGGER.setLevel(LOG_LEVEL) debug_logger_file_handler = logging.handlers.RotatingFileHandler( default_log_file_path, maxBytes=1024 * 1024, backupCount=5 ) debug_logger_file_handler.setLevel(LOG_LEVEL) debug_logger_file_handler.setFormatter(logging.Formatter(LOG_FORMAT)) DEBUG_LOGGER.propagate = False DEBUG_LOGGER.addHandler(debug_logger_file_handler) class NcpDebugLogger(asyncio.Protocol): """Class responsible for a serial debug connection.""" def __init__(self, api, dev_path): """Class initializer.""" self._api = api self._transport = None self._dev_path = dev_path self._buffer = bytearray() self._connected_event = asyncio.Event() def connection_made( self, transport: serial_asyncio.SerialTransport) -> None: """Notify when serial port opened.""" self._transport = transport message = f"Opened {transport.serial.name} serial port" DEBUG_LOGGER.debug(message) self._connected_event.set() def connection_lost(self, exc) -> None: """Lost connection.""" self.close() asyncio.create_task(self._reconnect()) async def _reconnect(self, timeout=RECONNECT_TIMEOUT): """Try to reconnect the disconnected serial port.""" loop = asyncio.get_running_loop() async with async_timeout.timeout(timeout): while True: try: _, proto = await serial_asyncio.create_serial_connection( loop=loop, protocol_factory=lambda: self, url=self._dev_path, baudrate=115_200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, rtscts=False, ) self._api._ncp_debug = proto break except serial.serialutil.SerialException: await asyncio.sleep(0.1) def close(self) -> None: """Close connection.""" self._buffer.clear() if self._transport: DEBUG_LOGGER.debug("Closing serial port") self._transport.close() self._transport = None def data_received(self, data: bytes) -> None: """Notify when there is data received from serial connection.""" self._buffer += data buff = self._buffer.split(b'\xde\xad') if len(buff) > 1: for line in buff[:-1]: try: DEBUG_LOGGER.debug(t.Bytes.__repr__(b'\xde\xad' + line)) except Exception: DEBUG_LOGGER.error("--- | Could not decode line | ---") self._buffer = buff[-1] async def connect_ncp_debug(api, dev_path) -> NcpDebugLogger: """Connect to serial device.""" loop = asyncio.get_running_loop() DEBUG_LOGGER.info(f"Connecting to {dev_path} for NCP debugging") _, protocol = await serial_asyncio.create_serial_connection( loop=loop, protocol_factory=lambda: NcpDebugLogger(api, dev_path), url=dev_path, baudrate=115200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, xonxoff=False, rtscts=False, ) await protocol._connected_event.wait() return protocol
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/debug.py
debug.py
from __future__ import annotations import dataclasses import zigpy_zboss.types as t from zigpy_zboss.exceptions import InvalidFrame from zigpy_zboss.checksum import CRC8 from zigpy_zboss.checksum import CRC16 class LLHeader(t.uint56_t): """Low Level Header class.""" def __new__( cls, value: int = 0x00000000000000, *, sign=None, size=None, frame_type=None, flags=None, crc8=None) -> "LLHeader": """Create a new low level header object.""" instance = super().__new__(cls, value) if sign is not None: instance = instance.with_signature(sign) if size is not None: instance = instance.with_size(size) if frame_type is not None: instance = instance.with_type(frame_type) if flags is not None: instance = instance.with_flags(flags) if crc8 is not None: instance = instance.with_crc8(crc8) return instance @property def signature(self) -> t.uint16_t: """Return the frame signature.""" return t.uint16_t(self & 0xFFFF) @property def size(self) -> t.uint16_t: """Return the frame size.""" return t.uint16_t((self >> 16) & 0xFFFF) @property def frame_type(self) -> t.uint8_t: """Return the type of api.""" return t.uint8_t((self >> 32) & 0xFF) @property def flags(self) -> t.LLFlags: """Return 8 bit flag enum.""" return t.LLFlags((self >> 40) & 0xFF) @property def crc8(self) -> t.uint8_t: """Return the calculated CRC8 starting from size.""" return t.uint8_t(self >> 48) def with_signature(self, value) -> "LLHeader": """Set the frame signature.""" return type(self)(self & 0xFFFFFFFFFF0000 | (value & 0xFFFF)) def with_size(self, value) -> "LLHeader": """Set the frame size.""" return type(self)(self & 0xFFFFFF0000FFFF | (value & 0xFFFF) << 16) def with_type(self, value) -> "LLHeader": """Set the frame type.""" return type(self)(self & 0xFFFF00FFFFFFFF | (value & 0xFF) << 32) def with_flags(self, value) -> "LLHeader": """Set the frame flags.""" return type(self)(self & 0xFF00FFFFFFFFFF | (value & 0xFF) << 40) def with_crc8(self, value) -> "LLHeader": """Set the header crc8.""" return type(self)(self & 0x00FFFFFFFFFFFF | (value & 0xFF) << 48) def __str__(self) -> str: """Return a string representation.""" return ( f"{type(self).__name__}(" f"signature=0x{self.signature:04X}, " f"size=0x{self.size:04X}, " f"frame_type=0x{self.frame_type:02X}, " f"flags=0x{self.flags:02X}, " f"crc8=0x{self.crc8:02X}" ")" ) __repr__ = __str__ @dataclasses.dataclass(frozen=True) class HLPacket: """High level part of the frame.""" header: t.HLCommonHeader data: t.Bytes def __post_init__(self) -> None: """Magic method.""" # We're frozen so `self.header = ...` is disallowed if not isinstance(self.header, t.HLCommonHeader): object.__setattr__( self, "header", t.HLCommonHeader(self.header)) if not isinstance(self.data, t.Bytes): object.__setattr__(self, "data", t.Bytes(self.data)) @property def length(self) -> t.uint8_t: """Length of the frame (including HL checksum).""" return t.uint8_t(len(self.serialize())) @classmethod def deserialize(cls, data): """Deserialize frame and sanity checks.""" check, data = t.uint16_t.deserialize(data) if not check == CRC16(data).digest(): raise InvalidFrame("Crc calculation error.") header, payload = t.HLCommonHeader.deserialize(data) return cls(header, payload) def serialize(self) -> bytes: """Serialize frame and calculate CRC.""" hl_checksum = CRC16( self.header.serialize() + self.data.serialize()).digest() return hl_checksum.serialize() + self.header.serialize() + \ self.data.serialize() @dataclasses.dataclass class Frame: """Frame containing low level header and high level packet.""" ll_header: LLHeader hl_packet: HLPacket signature: t.uint16_t = dataclasses.field( default=t.uint16_t(0xADDE), repr=False) @classmethod def deserialize(cls, data: bytes) -> tuple[Frame, bytes]: """Deserialize frame and sanity check.""" ll_header, data = LLHeader.deserialize(data) if ll_header.signature != cls.signature: raise InvalidFrame( "Expected frame to start with Signature " f"0x{cls.signature:04X}, got 0x{ll_header.signature:04X}" ) ll_checksum = CRC8(ll_header.serialize()[2:6]).digest() if ll_checksum != ll_header.crc8: raise InvalidFrame( f"Invalid frame checksum for data {ll_header}: " f"expected 0x{ll_header.crc8:02X}, got 0x{ll_checksum:02X}" ) if ll_header.flags & t.LLFlags.isACK: return cls(ll_header, None), data length = ll_header.size - 5 payload, data = data[:length], data[length:] hl_packet = HLPacket.deserialize(payload) return cls(ll_header, hl_packet), data @classmethod def ack(cls, ack_seq, retransmit=False): """Return an ACK frame.""" flag = t.LLFlags(ack_seq << 4) flag |= t.LLFlags.isACK if retransmit: flag |= t.LLFlags.Retransmit ll_header = ( LLHeader() .with_signature(cls.signature) .with_size(5) .with_type(t.TYPE_ZBOSS_NCP_API_HL) .with_flags(flag) ) crc = CRC8(ll_header.serialize()[2:6]).digest() ll_header = ll_header.with_crc8(crc) return cls(ll_header, None) def serialize(self) -> bytes: """Serialize the frame.""" if self.hl_packet is None: return self.ll_header.serialize() return self.ll_header.serialize() + self.hl_packet.serialize() @property def is_ack(self) -> bool: """Return True if the frame is an acknowelgement frame.""" return True if ( self.ll_header.flags & t.LLFlags.isACK) else False
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/frames.py
frames.py
import zigpy_zboss.types as t class CRC8: """Crc8 checksum calculation. Description: width=8 poly=0x4d init=0xff refin=true refout=true xorout=0xff check=0xd8 name="CRC-8/KOOP" """ digest_size = 1 block_size = 1 _table = [ 0xea, 0xd4, 0x96, 0xa8, 0x12, 0x2c, 0x6e, 0x50, 0x7f, 0x41, 0x03, 0x3d, 0x87, 0xb9, 0xfb, 0xc5, 0xa5, 0x9b, 0xd9, 0xe7, 0x5d, 0x63, 0x21, 0x1f, 0x30, 0x0e, 0x4c, 0x72, 0xc8, 0xf6, 0xb4, 0x8a, 0x74, 0x4a, 0x08, 0x36, 0x8c, 0xb2, 0xf0, 0xce, 0xe1, 0xdf, 0x9d, 0xa3, 0x19, 0x27, 0x65, 0x5b, 0x3b, 0x05, 0x47, 0x79, 0xc3, 0xfd, 0xbf, 0x81, 0xae, 0x90, 0xd2, 0xec, 0x56, 0x68, 0x2a, 0x14, 0xb3, 0x8d, 0xcf, 0xf1, 0x4b, 0x75, 0x37, 0x09, 0x26, 0x18, 0x5a, 0x64, 0xde, 0xe0, 0xa2, 0x9c, 0xfc, 0xc2, 0x80, 0xbe, 0x04, 0x3a, 0x78, 0x46, 0x69, 0x57, 0x15, 0x2b, 0x91, 0xaf, 0xed, 0xd3, 0x2d, 0x13, 0x51, 0x6f, 0xd5, 0xeb, 0xa9, 0x97, 0xb8, 0x86, 0xc4, 0xfa, 0x40, 0x7e, 0x3c, 0x02, 0x62, 0x5c, 0x1e, 0x20, 0x9a, 0xa4, 0xe6, 0xd8, 0xf7, 0xc9, 0x8b, 0xb5, 0x0f, 0x31, 0x73, 0x4d, 0x58, 0x66, 0x24, 0x1a, 0xa0, 0x9e, 0xdc, 0xe2, 0xcd, 0xf3, 0xb1, 0x8f, 0x35, 0x0b, 0x49, 0x77, 0x17, 0x29, 0x6b, 0x55, 0xef, 0xd1, 0x93, 0xad, 0x82, 0xbc, 0xfe, 0xc0, 0x7a, 0x44, 0x06, 0x38, 0xc6, 0xf8, 0xba, 0x84, 0x3e, 0x00, 0x42, 0x7c, 0x53, 0x6d, 0x2f, 0x11, 0xab, 0x95, 0xd7, 0xe9, 0x89, 0xb7, 0xf5, 0xcb, 0x71, 0x4f, 0x0d, 0x33, 0x1c, 0x22, 0x60, 0x5e, 0xe4, 0xda, 0x98, 0xa6, 0x01, 0x3f, 0x7d, 0x43, 0xf9, 0xc7, 0x85, 0xbb, 0x94, 0xaa, 0xe8, 0xd6, 0x6c, 0x52, 0x10, 0x2e, 0x4e, 0x70, 0x32, 0x0c, 0xb6, 0x88, 0xca, 0xf4, 0xdb, 0xe5, 0xa7, 0x99, 0x23, 0x1d, 0x5f, 0x61, 0x9f, 0xa1, 0xe3, 0xdd, 0x67, 0x59, 0x1b, 0x25, 0x0a, 0x34, 0x76, 0x48, 0xf2, 0xcc, 0x8e, 0xb0, 0xd0, 0xee, 0xac, 0x92, 0x28, 0x16, 0x54, 0x6a, 0x45, 0x7b, 0x39, 0x07, 0xbd, 0x83, 0xc1, 0xff] def __init__(self, initial_string=b'', initial_start=0x00): """Create a new crc8 hash instance.""" self._sum = initial_start self._update(initial_string) def update(self, bytes_): """Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b). """ self._update(bytes_) def digest(self): """Return the digest of the bytes passed to the update() method so far. This is a string of digest_size bytes which may contain non-ASCII characters, including null bytes. """ return t.uint8_t(self._sum) def hexdigest(self): """Return digest() as hexadecimal string. Like digest() except the digest is returned as a string of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments. """ return hex(self._sum)[2:].zfill(2) def _update(self, bytes_): if isinstance(bytes_, str): raise TypeError("Unicode-objects must be encoded before" " hashing") elif not isinstance(bytes_, (bytes, bytearray)): raise TypeError("object supporting the buffer API required") table = self._table _sum = self._sum for byte in bytes_: _sum = table[_sum ^ byte] self._sum = _sum def copy(self): """Return a clone of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. """ crc = CRC8() crc._sum = self._sum return crc class CRC16: """Crc16 checksum calculation. Description: width=16 poly=0x1021 init=0xff refin=false refout=false xorout=0x0000 check=0x29b1 name="CRC-16/CITT" """ digest_size = 1 block_size = 1 _table = [ 0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf, 0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7, 0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e, 0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876, 0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd, 0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5, 0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c, 0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974, 0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb, 0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3, 0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a, 0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72, 0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9, 0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1, 0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738, 0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70, 0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7, 0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff, 0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036, 0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e, 0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5, 0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd, 0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134, 0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c, 0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3, 0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb, 0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232, 0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a, 0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1, 0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9, 0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330, 0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78 ] def __init__(self, initial_string=b'', initial_start=0x0000): """Create a new crc16 hash instance.""" self._sum = initial_start self._update(initial_string) def update(self, bytes_): """Update the hash object with the string arg. Repeated calls are equivalent to a single call with the concatenation of all the arguments: m.update(a); m.update(b) is equivalent to m.update(a+b). """ self._update(bytes_) def digest(self): """Return the digest of the bytes passed to the update() method so far. This is a string of digest_size bytes which may contain non-ASCII characters, including null bytes. """ return t.uint16_t(self._sum) def hexdigest(self): """Return digest() as hexadecimal string. Like digest() except the digest is returned as a string of double length, containing only hexadecimal digits. This may be used to exchange the value safely in email or other non-binary environments. """ return hex(self._sum)[2:].zfill(4) def _update(self, bytes_): if isinstance(bytes_, str): raise TypeError("Unicode-objects must be encoded before" " hashing") elif not isinstance(bytes_, (bytes, bytearray)): raise TypeError("object supporting the buffer API required") table = self._table _sum = self._sum for byte in bytes_: _sum = (_sum >> 8) ^ table[(_sum ^ byte) & 0x00FF] self._sum = _sum def copy(self): """Return a clone of the hash object. This can be used to efficiently compute the digests of strings that share a common initial substring. """ crc = CRC16() crc._sum = self._sum return crc
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/checksum.py
checksum.py
import typing import asyncio import logging import zigpy.serial import async_timeout import serial # type: ignore import zigpy_zboss.config as conf from zigpy_zboss import types as t from zigpy_zboss.frames import Frame from zigpy_zboss.checksum import CRC8 from zigpy_zboss.logger import SERIAL_LOGGER from zigpy_zboss.exceptions import InvalidFrame LOGGER = logging.getLogger(__name__) ACK_TIMEOUT = 1 SEND_RETRIES = 2 STARTUP_TIMEOUT = 5 RECONNECT_TIMEOUT = 10 class BufferTooShort(Exception): """Exception when the buffer is too short.""" class ZbossNcpProtocol(asyncio.Protocol): """Zboss Ncp Protocol class.""" def __init__(self, config, api) -> None: """Initialize the ZbossNcpProtocol object.""" self._api = api self._ack_seq = 0 self._pack_seq = 0 self._config = config self._transport = None self._reset_flag = False self._buffer = bytearray() self._reconnect_task = None self._tx_lock = asyncio.Lock() self._ack_received_event = None self._connected_event = asyncio.Event() self._port = config[conf.CONF_DEVICE_PATH] self._baudrate = config[conf.CONF_DEVICE_BAUDRATE] self._flow_control = config[conf.CONF_DEVICE_FLOW_CONTROL] @property def api(self): """Return the owner of that object.""" return self._api @property def name(self) -> str: """Return serial name.""" return self._transport.serial.name @property def baudrate(self) -> int: """Return the baudrate.""" return self._transport.serial.baudrate @property def reset_flag(self) -> bool: """Return True if a reset is in process.""" return self._reset_flag @reset_flag.setter def reset_flag(self, value) -> None: if isinstance(value, bool): self._reset_flag = value def connection_made( self, transport: asyncio.BaseTransport) -> None: """Notify serial port opened.""" self._transport = transport message = f"Opened {transport.serial.name} serial port" if self._reset_flag: self._reset_flag = False return SERIAL_LOGGER.info(message) self._connected_event.set() def connection_lost(self, exc: typing.Optional[Exception]) -> None: """Lost connection.""" if self._api is not None: self._api.connection_lost(exc) self.close() # Do not try to reconnect if no exception occured. if exc is None: return if not self._reset_flag: SERIAL_LOGGER.warning( f"Unexpected connection lost... {exc}") self._reconnect_task = asyncio.create_task(self._reconnect()) async def _reconnect(self, timeout=RECONNECT_TIMEOUT): """Try to reconnect the disconnected serial port.""" SERIAL_LOGGER.info("Trying to reconnect to the NCP module!") assert self._api is not None loop = asyncio.get_running_loop() async with async_timeout.timeout(timeout): while True: try: _, proto = await zigpy.serial.create_serial_connection( loop=loop, protocol_factory=lambda: self, url=self._port, baudrate=self._baudrate, xonxoff=(self._flow_control == "software"), rtscts=(self._flow_control == "hardware"), ) self._api._uart = proto break except serial.serialutil.SerialException: await asyncio.sleep(0.1) def close(self) -> None: """Close serial connection.""" self._buffer.clear() self._ack_seq = 0 self._pack_seq = 0 if self._reconnect_task is not None: self._reconnect_task.cancel() self._reconnect_task = None # Reset transport if self._transport: message = "Closing serial port" LOGGER.debug(message) SERIAL_LOGGER.info(message) self._transport.close() self._transport = None def write(self, data: bytes) -> None: """Write raw bytes to the transport. This method should be used instead of directly writing to the transport with `transport.write`. """ if self._transport is not None: SERIAL_LOGGER.debug("TX: %s", t.Bytes.__repr__(data)) self._transport.write(data) async def send(self, frame: Frame) -> None: """Send data, and wait for acknowledgement.""" async with self._tx_lock: if isinstance(frame, Frame) and self._transport: self._ack_received_event = asyncio.Event() try: async with async_timeout.timeout(ACK_TIMEOUT): frame = self._set_frame_flag(frame) frame = self._ll_checksum(frame) self.write(frame.serialize()) await self._ack_received_event.wait() except asyncio.TimeoutError: SERIAL_LOGGER.debug( f'No ACK after {ACK_TIMEOUT}s for ' f'{t.Bytes.__repr__(frame.serialize())}' ) def _set_frame_flag(self, frame): """Return frame with required flags set.""" flag = t.LLFlags(self._pack_seq << 2) flag |= t.LLFlags.FirstFrag flag |= t.LLFlags.LastFrag frame.ll_header = frame.ll_header.with_flags(flag) return frame def _ll_checksum(self, frame): """Return frame with new crc8 checksum calculation.""" crc = CRC8(frame.ll_header.serialize()[2:6]).digest() frame.ll_header = frame.ll_header.with_crc8(crc) return frame def data_received(self, data: bytes) -> None: """Notify when there is data received from serial connection.""" self._buffer += data for frame in self._extract_frames(): SERIAL_LOGGER.debug(f"RX: {t.Bytes.__repr__(frame.serialize())}") ll_header = frame.ll_header # Check if the frame is an ACK if ll_header.flags & t.LLFlags.isACK: ack_seq = (ll_header.flags & t.LLFlags.ACKSeq) >> 4 if ack_seq == self._pack_seq: # Calculate next sequence number self._pack_seq = self._pack_seq % 3 + 1 self._ack_received_event.set() return # Acknowledge the received frame self._ack_seq = (frame.ll_header.flags & t.LLFlags.PacketSeq) >> 2 self.write(self._ack_frame().serialize()) if frame.hl_packet is not None: try: self._api.frame_received(frame) except Exception as e: LOGGER.error( "Received an exception while passing frame to API: %s", frame, exc_info=e, ) def _extract_frames(self) -> typing.Iterator[Frame]: """Extract frames from the buffer until it is exhausted.""" while True: try: yield self._extract_frame() except BufferTooShort: # If the buffer is too short, there is nothing more we can do break except InvalidFrame: # If the buffer contains invalid data, # drop it until we find the signature signature_idx = self._buffer.find( Frame.signature.serialize(), 1) if signature_idx < 0: # If we don't have a signature in the buffer, # drop everything self._buffer.clear() else: del self._buffer[:signature_idx] def _extract_frame(self) -> Frame: """Extract a single frame from the buffer.""" # The shortest possible frame is 7 bytes long if len(self._buffer) < 7: raise BufferTooShort() # The buffer must start with a SoF if self._buffer[0:2] != Frame.signature.serialize(): raise InvalidFrame() length, _ = t.uint16_t.deserialize(self._buffer[2:4]) # Don't bother deserializing anything if the packet is too short if len(self._buffer) < length + 2: raise BufferTooShort() # Check that the packet type is ZBOSS NCP API HL. if self._buffer[4] != t.TYPE_ZBOSS_NCP_API_HL: raise InvalidFrame() # At this point we should have a complete frame # If not, deserialization will fail and the error will propapate up frame, rest = Frame.deserialize(self._buffer) # If we get this far then we have a valid frame. Update the buffer. del self._buffer[: len(self._buffer) - len(rest)] return frame def _ack_frame(self): """Return acknowledgement frame.""" ack_frame = Frame.ack(self._ack_seq) return ack_frame def __repr__(self) -> str: """Return a string representing the class.""" return ( f"<" f"{type(self).__name__} connected to {self.name!r}" f" at {self.baudrate} baud" f" (api: {self._api})" f">" ) async def connect(config: conf.ConfigType, api) -> ZbossNcpProtocol: """Instantiate Uart object and connect to it.""" loop = asyncio.get_running_loop() port = config[conf.CONF_DEVICE_PATH] baudrate = config[conf.CONF_DEVICE_BAUDRATE] flow_control = config[conf.CONF_DEVICE_FLOW_CONTROL] LOGGER.info("Connecting to %s at %s baud", port, baudrate) _, protocol = await zigpy.serial.create_serial_connection( loop=loop, protocol_factory=lambda: ZbossNcpProtocol(config, api), url=port, baudrate=baudrate, xonxoff=(flow_control == "software"), rtscts=(flow_control == "hardware"), ) try: async with async_timeout.timeout(STARTUP_TIMEOUT): await protocol._connected_event.wait() except asyncio.TimeoutError: protocol.close() raise RuntimeError("Could not communicate with NCP!") return protocol
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/uart.py
uart.py
import typing import numbers import voluptuous as vol from zigpy.config import ( # noqa: F401 CONF_NWK, CONF_DEVICE, CONF_NWK_KEY, CONFIG_SCHEMA, SCHEMA_DEVICE, CONF_NWK_PAN_ID, CONF_NWK_CHANNEL, CONF_DEVICE_PATH, CONF_NWK_KEY_SEQ, CONF_NWK_CHANNELS, CONF_NWK_UPDATE_ID, CONF_NWK_TC_ADDRESS, CONF_NWK_TC_LINK_KEY, CONF_NWK_EXTENDED_PAN_ID, cv_boolean, ) LOG_FILE_NAME = "zigpy-zboss.log" SERIAL_LOG_FILE_NAME = "serial-zigpy-zboss.log" ConfigType = typing.Dict[str, typing.Any] VolPositiveNumber = vol.All(numbers.Real, vol.Range(min=0)) CONF_DEVICE_BAUDRATE = "baudrate" CONF_DEVICE_FLOW_CONTROL = "flow_control" CONF_DEVICE_BAUDRATE_DEFAULT = 115_200 CONF_DEVICE_FLOW_CONTROL_DEFAULT = None SCHEMA_DEVICE = SCHEMA_DEVICE.extend( { vol.Optional( CONF_DEVICE_BAUDRATE, default=CONF_DEVICE_BAUDRATE_DEFAULT): int, vol.Optional( CONF_DEVICE_FLOW_CONTROL, default=CONF_DEVICE_FLOW_CONTROL_DEFAULT): vol.In( ("hardware", "software", None) ), } ) def keys_have_same_length(*keys): """Raise an error if values don't have the same length.""" def validator(config): lengths = [len(config[k]) for k in keys] if len(set(lengths)) != 1: raise vol.Invalid( f"Values for {keys} must all have the same length: {lengths}" ) return config return validator CONF_NRF_CONFIG = "nrf_config" CONF_TX_POWER = "tx_power" CONF_LED_MODE = "led_mode" CONF_SKIP_BOOTLOADER = "skip_bootloader" CONF_REQ_TIMEOUT = "request_timeout" CONF_AUTO_RECONNECT_RETRY_DELAY = "auto_reconnect_retry_delay" CONF_MAX_CONCURRENT_REQUESTS = "max_concurrent_requests" CONF_CONNECT_RTS_STATES = "connect_rts_pin_states" CONF_CONNECT_DTR_STATES = "connect_dtr_pin_states" CONFIG_SCHEMA = CONFIG_SCHEMA.extend( { vol.Required(CONF_DEVICE): SCHEMA_DEVICE, vol.Optional(CONF_NRF_CONFIG, default={}): vol.Schema( vol.All( { vol.Optional(CONF_TX_POWER, default=None): vol.Any( None, vol.All(int, vol.Range(min=-22, max=22)) ), vol.Optional( CONF_REQ_TIMEOUT, default=15): VolPositiveNumber, vol.Optional( CONF_AUTO_RECONNECT_RETRY_DELAY, default=5 ): VolPositiveNumber, vol.Optional( CONF_SKIP_BOOTLOADER, default=True): cv_boolean, vol.Optional(CONF_LED_MODE, default=None): vol.Any(None), vol.Optional( CONF_MAX_CONCURRENT_REQUESTS, default="auto"): vol.Any( "auto", VolPositiveNumber ), vol.Optional( CONF_CONNECT_RTS_STATES, default=[False, True, False] ): vol.Schema([cv_boolean]), vol.Optional( CONF_CONNECT_DTR_STATES, default=[False, False, False] ): vol.Schema([cv_boolean]), }, keys_have_same_length( CONF_CONNECT_RTS_STATES, CONF_CONNECT_DTR_STATES), ) ), } )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/config.py
config.py
from __future__ import annotations import typing import asyncio import logging import dataclasses import zigpy_zboss.types as t LOGGER = logging.getLogger(__name__) def deduplicate_commands( commands: typing.Iterable[t.CommandBase], ) -> tuple[t.CommandBase]: """Deduplicates an iterable of commands. Deduplicates an iterable of commands by folding more-specific commands into less-specific commands. Used to avoid triggering callbacks multiple times per packet. """ # We essentially need to find the "maximal" commands, if you treat the # relationship between two commands as a partial order. maximal_commands = [] # Command matching as a relation forms a partially ordered set. for command in commands: for index, other_command in enumerate(maximal_commands): if other_command.matches(command): # If the other command matches us, we are redundant break elif command.matches(other_command): # If we match another command, we replace it maximal_commands[index] = command break else: # Otherwise, we keep looking continue # pragma: no cover else: # If we matched nothing and nothing matched us, we extend the list maximal_commands.append(command) # The start of each chain is the maximal element return tuple(maximal_commands) @dataclasses.dataclass(frozen=True) class BaseResponseListener: """Class representing the base of a response listener.""" matching_commands: tuple[t.CommandBase] def __post_init__(self): """Set matching_commands parameter when used as parent.""" commands = deduplicate_commands(self.matching_commands) if not commands: raise ValueError( "Cannot create a listener without any matching commands") # We're frozen so __setattr__ is disallowed object.__setattr__(self, "matching_commands", commands) def matching_headers(self) -> set[t.HLCommonHeader]: """Return the set of command headers for all the matching commands.""" return {response.header for response in self.matching_commands} def resolve(self, response: t.CommandBase) -> bool: """Try to resolve listener. Attempts to resolve the listener with a given response. Can be called with any command as an argument, including ones we don't match. """ if not any(c.matches(response) for c in self.matching_commands): return False return self._resolve(response) def _resolve(self, response: t.CommandBase) -> bool: """Implement by subclasses to handle matched commands. Return value indicates whether or not the listener has actually resolved, which can sometimes be unavoidable. """ raise NotImplementedError() # pragma: no cover def cancel(self): """Implement by subclasses to cancel the listener. Return value indicates whether or not the listener is cancelable. """ raise NotImplementedError() # pragma: no cover @dataclasses.dataclass(frozen=True) class OneShotResponseListener(BaseResponseListener): """One shot response listener. A response listener that resolves a single future exactly once. """ future: asyncio.Future = dataclasses.field( default_factory=lambda: asyncio.get_running_loop().create_future() ) def _resolve(self, response: t.CommandBase) -> bool: if self.future.done(): # This happens if the UART receives multiple packets during the # same event loop step and all of them match this listener. # Our Future's add_done_callback will not fire synchronously and # thus the listener is never properly removed. # This isn't going to break anything. LOGGER.debug("Future already has a result set: %s", self.future) return False self.future.set_result(response) return True def cancel(self): """Cancel a one shot callback.""" if not self.future.done(): self.future.cancel() return True @dataclasses.dataclass(frozen=True) class IndicationListener(BaseResponseListener): """Indication listener. A response listener with a sync or async callback that is never resolved. """ callback: typing.Callable[[t.CommandBase], typing.Any] def _resolve(self, response: t.CommandBase) -> bool: try: result = self.callback(response) # Run coroutines in the background if asyncio.iscoroutine(result): asyncio.create_task(result) except Exception: LOGGER.warning( "Caught an exception while executing callback", exc_info=True ) # Callbacks are always resolved return True def cancel(self): """Return false when trying to cancel an indication callback.""" # You can't cancel a callback return False class CatchAllResponse: """Response-like object that matches every request.""" header = object() # sentinel def matches(self, other) -> bool: """Return true if object are matching.""" return True
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/utils.py
utils.py
from __future__ import annotations import asyncio import logging import itertools import zigpy.state import async_timeout import zigpy_zboss.types as t import zigpy_zboss.config as conf from zigpy_zboss import uart from zigpy_zboss.frames import Frame from zigpy_zboss import commands as c from zigpy_zboss.nvram import NVRAMHelper from collections import Counter, defaultdict from zigpy_zboss.utils import IndicationListener from zigpy_zboss.utils import BaseResponseListener from zigpy_zboss.utils import OneShotResponseListener LOGGER = logging.getLogger(__name__) # All of these are in seconds AFTER_BOOTLOADER_SKIP_BYTE_DELAY = 2.5 NETWORK_COMMISSIONING_TIMEOUT = 30 BOOTLOADER_PIN_TOGGLE_DELAY = 0.15 CONNECT_PING_TIMEOUT = 0.50 CONNECT_PROBE_TIMEOUT = 10 DEFAULT_TIMEOUT = 5 class NRF: """Class linking zigpy with the nRF SoC.""" def __init__(self, config: conf.ConfigType): """Initialize NRF class.""" self._uart = None self._app = None self._config = config self._listeners = defaultdict(list) self._blocking_request_lock = asyncio.Lock() self.capabilities = None self.nvram = NVRAMHelper(self) self.network_info: zigpy.state.NetworkInformation = None self.node_info: zigpy.state.NodeInfo = None self._ncp_debug = None def set_application(self, app): """Set the application using the NRF class.""" assert self._app is None self._app = app @property def _port_path(self) -> str: return self._config[conf.CONF_DEVICE][conf.CONF_DEVICE_PATH] @property def _nrf_config(self) -> conf.ConfigType: return self._config[conf.CONF_NRF_CONFIG] async def connect(self) -> None: """Connect to serial device. Connects to the device specified by the "device" section of the config dict. """ # So we cannot connect twice assert self._uart is None try: self._uart = await uart.connect( self._config[conf.CONF_DEVICE], self) except (Exception, asyncio.CancelledError): LOGGER.debug( "Connection to %s failed, cleaning up", self._port_path) self.close() raise LOGGER.debug( "Connected to %s at %s baud", self._uart.name, self._uart.baudrate) def connection_made(self) -> None: """Notify that connection has been made. Called by the UART object when a connection has been made. """ pass def connection_lost(self, exc) -> None: """Port has been closed. Called by the UART object to indicate that the port was closed. Propagates up to the `ControllerApplication` that owns this NRF instance. """ LOGGER.debug("We were disconnected from %s: %s", self._port_path, exc) def close(self) -> None: """Clean up resources, namely the listener queues. Calling this will reset NRF to the same internal state as a fresh NRF instance. """ self._app = None self.version = None if self._uart is not None: self._uart.close() self._uart = None def frame_received(self, frame: Frame) -> bool: """Frame has been received. Called when a frame has been received. Returns whether or not the frame was handled by any listener. XXX: Can be called multiple times in a single event loop step! """ if frame.hl_packet.header not in c.COMMANDS_BY_ID: LOGGER.debug("Received an unknown frame: %s", frame) return command_cls = c.COMMANDS_BY_ID[frame.hl_packet.header] try: command, _ = command_cls.from_frame(frame) except ValueError: raise LOGGER.debug("Received command: %s", command) matched = False one_shot_matched = False for listener in self._listeners[command.header]: if one_shot_matched and isinstance( listener, OneShotResponseListener): continue if not listener.resolve(command): LOGGER.debug(f"{command} does not match {listener}") continue matched = True LOGGER.debug(f"{command} matches {listener}") if isinstance(listener, OneShotResponseListener): one_shot_matched = True if not matched: self._unhandled_command(command) return matched def _unhandled_command(self, command: t.CommandBase): """Command not handled by any listener.""" LOGGER.debug(f"Command was not handled: {command}") async def request( self, request: t.CommandBase, timeout=DEFAULT_TIMEOUT, **response_params) -> t.CommandBase: """Send a REQ request and returns its RSP. Failing if any of the RSP's parameters don't match `response_params`. """ if type(request) is not request.Req: raise ValueError( f"Cannot send a command that isn't a request: {request!r}") frame = request.to_frame() response_future = self.wait_for_response(request.Rsp(partial=True)) if request.blocking: async with self._blocking_request_lock: return await self._send_to_uart( frame, response_future, timeout=timeout) return await self._send_to_uart( frame, response_future, timeout=timeout) async def _send_to_uart( self, frame, response_future, timeout=DEFAULT_TIMEOUT): """Send the frame and waits for the response.""" if self._uart is None: return try: await self._uart.send(frame) async with async_timeout.timeout(timeout): return await response_future except asyncio.TimeoutError: LOGGER.debug(f"Timeout after {timeout}s: {frame}") raise def wait_for_responses( self, responses, *, context=False) -> asyncio.Future: """Create a one-shot listener. Matches any *one* of the given responses. """ listener = OneShotResponseListener(responses) LOGGER.debug("Creating one-shot listener %s", listener) for header in listener.matching_headers(): self._listeners[header].append(listener) # Remove the listener when the future is done, # not only when it gets a result listener.future.add_done_callback( lambda _: self.remove_listener(listener)) if context: return listener.future, listener else: return listener.future def wait_for_response(self, response: t.CommandBase) -> asyncio.Future: """Create a one-shot listener for a single response.""" return self.wait_for_responses([response]) def remove_listener(self, listener: BaseResponseListener) -> None: """ Unbinds a listener from NRF. Used by `wait_for_responses` to remove listeners for completed futures, regardless of their completion reason. """ if not self._listeners: return LOGGER.debug("Removing listener %s", listener) for header in listener.matching_headers(): try: self._listeners[header].remove(listener) except ValueError: pass if not self._listeners[header]: LOGGER.debug( "Cleaning up empty listener list for header %s", header ) del self._listeners[header] counts = Counter() for listener in itertools.chain.from_iterable( self._listeners.values()): counts[type(listener)] += 1 LOGGER.debug( f"There are {counts[IndicationListener]} callbacks and" f" {counts[OneShotResponseListener]} one-shot listeners remaining" ) def register_indication_listeners( self, responses, callback) -> IndicationListener: """Create an indication listener. Matches any of the provided responses. """ listener = IndicationListener(responses, callback=callback) LOGGER.debug(f"Creating callback {listener}") for header in listener.matching_headers(): self._listeners[header].append(listener) return listener def register_indication_listener( self, response: t.CommandBase, callback ) -> IndicationListener: """Create a callback listener for a single response.""" return self.register_indication_listeners([response], callback) async def version(self): """Get NCP module version.""" if self._app is not None: tsn = self._app.get_sequence() else: tsn = 0 req = c.NcpConfig.GetModuleVersion.Req(TSN=tsn) res = await self.request(req) if res.StatusCode: return version = ['', '', ''] for idx, ver in enumerate( [res.FWVersion, res.StackVersion, res.ProtocolVersion]): major = str((ver & 0xFF000000) >> 24) minor = str((ver & 0x00FF0000) >> 16) revision = str((ver & 0x0000FF00) >> 8) commit = str((ver & 0x000000FF)) version[idx] = ".".join([major, minor, revision, commit]) return tuple(version) async def reset(self, option=t.ResetOptions(0)): """Reset the NCP module (see ResetOptions).""" if self._app is not None: tsn = self._app.get_sequence() else: tsn = 0 req = c.NcpConfig.NCPModuleReset.Req(TSN=tsn, Option=option) self._uart.reset_flag = True res = await self._send_to_uart( req.to_frame(), self.wait_for_response( c.NcpConfig.NCPModuleReset.Rsp(partial=True) ), timeout=10 ) if not res.TSN == 0xFF: raise ValueError("Should get TSN 0xFF")
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/api.py
api.py
import asyncio import logging import zigpy.util import zigpy.state import zigpy.appdb import zigpy.config import zigpy.device import async_timeout import zigpy.endpoint import zigpy.exceptions import zigpy.types as t import zigpy.application import zigpy_zboss.types as t_zboss import zigpy.zdo.types as zdo_t import zigpy_zboss.config as conf from typing import Any, Dict from zigpy_zboss.api import NRF from zigpy_zboss import commands as c from zigpy.exceptions import DeliveryError from .device import NrfCoordinator, NrfDevice from zigpy_zboss.exceptions import NrfResponseError from zigpy_zboss.config import CONFIG_SCHEMA, SCHEMA_DEVICE LOGGER = logging.getLogger(__name__) PROBE_TIMEOUT = 5 FORMAT = "%H:%M:%S" DEVICE_JOIN_MAX_DELAY = 2 REQUEST_MAX_RETRIES = 2 class ControllerApplication(zigpy.application.ControllerApplication): """Controller class.""" SCHEMA = CONFIG_SCHEMA SCHEMA_DEVICE = SCHEMA_DEVICE def __init__(self, config: Dict[str, Any]): """Initialize instance.""" super().__init__(config=zigpy.config.ZIGPY_SCHEMA(config)) self._api: NRF | None = None self._reset_task = None self.version = None async def connect(self): """Connect to the zigbee module.""" assert self._api is None is_responsive = await self.probe(self.config) if not is_responsive: raise NrfResponseError nrf = NRF(self.config) await nrf.connect() self._api = nrf self._api.set_application(self) self._bind_callbacks() async def disconnect(self): """Disconnect from the zigbee module.""" if self._reset_task and not self._reset_task.done(): self._reset_task.cancel() if self._api is not None: await self._api.reset() self._api.close() self._api = None async def start_network(self): """Start the network.""" if self.state.node_info == zigpy.state.NodeInfo(): await self.load_network_info() await self.start_without_formation() self.version = await self._api.version() self.devices[self.state.node_info.ieee] = NrfCoordinator( self, self.state.node_info.ieee, self.state.node_info.nwk ) await self._device.schedule_initialize() async def force_remove(self, dev: zigpy.device.Device) -> None: """Send a lower-level leave command to the device.""" # ZBOSS NCP does not have any way to do this async def add_endpoint(self, descriptor: zdo_t.SimpleDescriptor) -> None: """Register a new endpoint on the device.""" simple_desc = t_zboss.SimpleDescriptor( endpoint=descriptor.endpoint, profile=descriptor.profile, device_type=descriptor.device_type, device_version=descriptor.device_version, input_clusters=descriptor.input_clusters, output_clusters=descriptor.output_clusters, ) simple_desc.input_clusters_count = len(simple_desc.input_clusters) simple_desc.output_clusters_count = len(simple_desc.output_clusters) await self._api.request(c.AF.SetSimpleDesc.Req( TSN=self.get_sequence(), SimpleDesc=descriptor)) def get_sequence(self): """Sequence getter overwrite.""" # Do not use tsn 255 as specified in NCP protocol. self._send_sequence = (self._send_sequence + 1) % 255 return self._send_sequence def get_default_stack_specific_formation_settings(self): """Populate stack specific config dictionary with default values.""" return { "rx_on_when_idle": t.Bool.true, "end_device_timeout": t_zboss.TimeoutIndex.Minutes_256, "max_children": t.uint8_t(100), "joined": t.Bool.false, "authenticated": t.Bool.false, "parent_nwk": None, "coordinator_version": None, "tc_policy": { "unique_tclk_required": t.Bool.false, "ic_required": t.Bool.false, "tc_rejoin_enabled": t.Bool.true, "unsecured_tc_rejoin_enabled": t.Bool.false, "tc_rejoin_ignored": t.Bool.false, "aps_insecure_join_enabled": t.Bool.false, "mgmt_channel_update_disabled": t.Bool.false, }, } async def write_network_info(self, *, network_info, node_info): """Write the provided network and node info to the radio hardware.""" network_info.stack_specific = \ self.get_default_stack_specific_formation_settings() node_info.ieee = network_info.extended_pan_id # Write self.state.node_info. await self._api.request( c.NcpConfig.SetLocalIEEE.Req( TSN=self.get_sequence(), MacInterfaceNum=0, IEEE=node_info.ieee ) ) await self._api.request( request=c.NcpConfig.SetZigbeeRole.Req( TSN=self.get_sequence(), DeviceRole=t_zboss.DeviceRole.ZC ) ) await self._api.request( request=c.NcpConfig.SetExtendedPANID.Req( TSN=self.get_sequence(), ExtendedPANID=network_info.extended_pan_id ) ) await self._api.request( request=c.NcpConfig.SetShortPANID.Req( TSN=self.get_sequence(), PANID=network_info.pan_id ) ) await self._api.request( request=c.NcpConfig.SetChannelMask.Req( TSN=self.get_sequence(), Page=t.uint8_t(0x00), Mask=network_info.channel_mask ) ) await self._api.request( request=c.NcpConfig.SetNwkKey.Req( TSN=self.get_sequence(), NwkKey=network_info.network_key.key, KeyNumber=network_info.network_key.seq ) ) # Write stack-specific parameters. await self._api.request( request=c.NcpConfig.SetRxOnWhenIdle.Req( TSN=self.get_sequence(), RxOnWhenIdle=network_info.stack_specific["rx_on_when_idle"] ) ) await self._api.request( request=c.NcpConfig.SetEDTimeout.Req( TSN=self.get_sequence(), Timeout=network_info.stack_specific["end_device_timeout"] ) ) await self._api.request( request=c.NcpConfig.SetMaxChildren.Req( TSN=self.get_sequence(), ChildrenNbr=network_info.stack_specific[ "max_children"] ) ) await self._api.request( request=c.NcpConfig.SetTCPolicy.Req( TSN=self.get_sequence(), PolicyType=t_zboss.PolicyType.TC_Link_Keys_Required, PolicyValue=network_info.stack_specific[ "tc_policy"]["unique_tclk_required"] ) ) await self._api.request( request=c.NcpConfig.SetTCPolicy.Req( TSN=self.get_sequence(), PolicyType=t_zboss.PolicyType.IC_Required, PolicyValue=network_info.stack_specific[ "tc_policy"]["ic_required"] ) ) await self._api.request( request=c.NcpConfig.SetTCPolicy.Req( TSN=self.get_sequence(), PolicyType=t_zboss.PolicyType.TC_Rejoin_Enabled, PolicyValue=network_info.stack_specific[ "tc_policy"]["tc_rejoin_enabled"] ) ) await self._api.request( request=c.NcpConfig.SetTCPolicy.Req( TSN=self.get_sequence(), PolicyType=t_zboss.PolicyType.Ignore_TC_Rejoin, PolicyValue=network_info.stack_specific[ "tc_policy"]["tc_rejoin_ignored"] ) ) await self._api.request( request=c.NcpConfig.SetTCPolicy.Req( TSN=self.get_sequence(), PolicyType=t_zboss.PolicyType.APS_Insecure_Join, PolicyValue=network_info.stack_specific[ "tc_policy"]["aps_insecure_join_enabled"] ) ) await self._api.request( request=c.NcpConfig.SetTCPolicy.Req( TSN=self.get_sequence(), PolicyType=t_zboss.PolicyType.Disable_NWK_MGMT_Channel_Update, PolicyValue=network_info.stack_specific[ "tc_policy"]["mgmt_channel_update_disabled"] ) ) await self._form_network(network_info) async def _form_network(self, network_info): """Clear the current config and forms a new network.""" await self._api.request( request=c.NWK.Formation.Req( TSN=self.get_sequence(), ChannelList=t_zboss.ChannelEntryList([ t_zboss.ChannelEntry( page=0, channel_mask=network_info.channel_mask) ]), ScanDuration=0x05, DistributedNetFlag=0x00, DistributedNetAddr=t.NWK(0x0000), IEEEAddr=network_info.extended_pan_id ) ) async def _move_network_to_channel( self, new_channel: int, new_nwk_update_id: int) -> None: """Move device to a new channel.""" await self._api.request( request=c.ZDO.MgmtNwkUpdate.Req( TSN=self.get_sequence(), ScanChannelMask=t.Channels.from_channel_list([new_channel]), ScanDuration=zdo_t.NwkUpdate.CHANNEL_CHANGE_REQ, ScanCount=0, MgrAddr=0x0000, DstNWK=0x0000, ), ) async def load_network_info(self, *, load_devices=False): """Populate state.node_info and state.network_info.""" res = await self._api.request( c.NcpConfig.GetJoinStatus.Req(TSN=self.get_sequence())) if not res.Joined & 0x01: raise zigpy.exceptions.NetworkNotFormed res = await self._api.request(c.NcpConfig.GetShortAddr.Req( TSN=self.get_sequence() )) self.state.node_info.nwk = res.NWKAddr res = await self._api.request( c.NcpConfig.GetLocalIEEE.Req( TSN=self.get_sequence(), MacInterfaceNum=0)) self.state.node_info.ieee = res.IEEE res = await self._api.request( c.NcpConfig.GetZigbeeRole.Req(TSN=self.get_sequence())) self.state.node_info.logical_type = res.DeviceRole res = await self._api.request( c.NcpConfig.GetExtendedPANID.Req(TSN=self.get_sequence())) # FIX! Swaping bytes because of module sending IEEE the wrong way. self.state.network_info.extended_pan_id = t.EUI64( res.ExtendedPANID.serialize()[::-1]) res = await self._api.request( c.NcpConfig.GetShortPANID.Req(TSN=self.get_sequence())) self.state.network_info.pan_id = res.PANID self.state.network_info.nwk_update_id = self.config[ conf.CONF_NWK][conf.CONF_NWK_UPDATE_ID] res = await self._api.request( c.NcpConfig.GetCurrentChannel.Req(TSN=self.get_sequence())) self.state.network_info.channel = res.Channel res = await self._api.request( c.NcpConfig.GetChannelMask.Req(TSN=self.get_sequence())) self.state.network_info.channel_mask = res.ChannelList[0].channel_mask self.state.network_info.security_level = 0x05 res = await self._api.request( c.NcpConfig.GetNwkKeys.Req(TSN=self.get_sequence())) self.state.network_info.network_key = zigpy.state.Key( key=res.NwkKey1, tx_counter=0, rx_counter=0, seq=res.KeyNumber1, partner_ieee=self.state.node_info.ieee, ) if self.state.node_info.logical_type == \ zdo_t.LogicalType.Coordinator: self.state.network_info.tc_link_key = zigpy.state.Key( key=self.config[conf.CONF_NWK][conf.CONF_NWK_TC_LINK_KEY], tx_counter=0, rx_counter=0, seq=0, partner_ieee=self.state.node_info.ieee, ) else: res = await self._api.request( c.NcpConfig.GetTrustCenterAddr.Req(TSN=self.get_sequence())) self.state.network_info.tc_link_key = ( zigpy.state.Key( key=None, tx_counter=0, rx_counter=0, seq=0, partner_ieee=res.TCIEEE, ), ) res = await self._api.request( c.NcpConfig.GetRxOnWhenIdle.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "rx_on_when_idle" ] = res.RxOnWhenIdle res = await self._api.request( c.NcpConfig.GetEDTimeout.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "end_device_timeout" ] = res.Timeout res = await self._api.request( c.NcpConfig.GetMaxChildren.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "max_children" ] = res.ChildrenNbr res = await self._api.request( c.NcpConfig.GetJoinStatus.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "joined" ] = res.Joined res = await self._api.request( c.NcpConfig.GetAuthenticationStatus.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "authenticated" ] = res.Authenticated res = await self._api.request( c.NcpConfig.GetParentAddr.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "parent_nwk" ] = res.NWKParentAddr res = await self._api.request( c.NcpConfig.GetCoordinatorVersion.Req(TSN=self.get_sequence())) self.state.network_info.stack_specific[ "coordinator_version" ] = res.CoordinatorVersion if not load_devices: return map = await self._api.nvram.read( t_zboss.DatasetId.ZB_NVRAM_ADDR_MAP, t_zboss.NwkAddrMap ) for rec in map: if rec.nwk_addr == 0x0000: continue self.state.network_info.children.append(rec.ieee_addr) self.state.network_info.nwk_addresses[rec.ieee_addr] = rec.nwk_addr keys = await self._api.nvram.read( t_zboss.DatasetId.ZB_NVRAM_APS_SECURE_DATA, t_zboss.ApsSecureKeys ) for key_entry in keys: zigpy_key = zigpy.state.Key() zigpy_key.key = t.KeyData(key_entry.key) zigpy_key.partner_ieee = key_entry.ieee_addr self.state.network_info.key_table.append(zigpy_key) async def reset_network_info(self) -> None: """Reset node network information and leaves the current network.""" pass async def start_without_formation(self): """Start the network with settings currently stored on the module.""" res = await self._api.request( c.NWK.StartWithoutFormation.Req(TSN=self.get_sequence())) if res.StatusCode != 0: raise zigpy.exceptions.NetworkNotFormed async def permit_ncp(self, time_s=60): """Permits joins on the coordinator.""" await self._api.request( c.ZDO.PermitJoin.Req( TSN=self.get_sequence(), DestNWK=t.NWK(0x0000), PermitDuration=t.uint8_t(time_s), TCSignificance=t.uint8_t(0x01), ) ) def permit_with_key(self, node, code, time_s=60): """Permit with key.""" raise NotImplementedError @property def nrf_config(self) -> conf.ConfigType: """Shortcut property to access the NRF radio config.""" return self.config[conf.CONF_NRF_CONFIG] @classmethod async def probe(cls, device_config: dict) -> bool: """Probe the NCP. Checks whether the NCP device is responding to request. """ nrf = NRF(device_config) try: await nrf.connect() async with async_timeout.timeout(PROBE_TIMEOUT): await nrf.request( c.NcpConfig.GetZigbeeRole.Req(TSN=1), timeout=1) return True except asyncio.TimeoutError: return False finally: nrf.close() # Overwrites zigpy because of custom ZDO layer required for ZBOSS. def add_device(self, ieee: t.EUI64, nwk: t.NWK): """Create zigpy `Device` object with the provided IEEE and NWK addr.""" assert isinstance(ieee, t.EUI64) # TODO: Shut down existing device dev = NrfDevice(self, ieee, nwk) self.devices[ieee] = dev return dev ##################################################### # Callbacks attached during startup # ##################################################### def _bind_callbacks(self) -> None: """Bind indication callbacks to their associated methods.""" self._api.register_indication_listener( c.NWK.NwkLeaveInd.Ind(partial=True), self.on_nwk_leave ) self._api.register_indication_listener( c.ZDO.DevUpdateInd.Ind(partial=True), self.on_dev_update ) self._api.register_indication_listener( c.APS.DataIndication.Ind(partial=True), self.on_apsde_indication ) self._api.register_indication_listener( c.ZDO.DevAnnceInd.Ind(partial=True), self.on_zdo_device_announcement ) self._api.register_indication_listener( c.NcpConfig.DeviceResetIndication.Ind(partial=True), self.on_ncp_reset ) def on_nwk_leave(self, msg: c.NWK.NwkLeaveInd.Ind): """Device left indication.""" dev = self.devices.get(msg.IEEE) if dev: self.handle_leave(nwk=dev.nwk, ieee=msg.IEEE) def on_zdo_device_announcement(self, msg: c.ZDO.DevAnnceInd.Ind): """ZDO Device announcement command received.""" self.handle_join(nwk=msg.NWK, ieee=msg.IEEE, parent_nwk=None) def on_dev_update(self, msg: c.ZDO.DevUpdateInd.Ind): """Device update indication.""" if msg.Status == t_zboss.DeviceUpdateStatus.secured_rejoin: # 0x000 as parent device, currently unused pass # self.handle_join(msg.Nwk, msg.IEEE, 0x0000) elif msg.Status == t_zboss.DeviceUpdateStatus.unsecured_join: # 0x000 as parent device, currently unused pass # self.handle_join(msg.Nwk, msg.IEEE, 0x0000) elif msg.Status == t_zboss.DeviceUpdateStatus.device_left: pass # self.handle_leave(msg.Nwk, msg.IEEE) elif msg.Status == t_zboss.DeviceUpdateStatus.tc_rejoin: pass # self.handle_join(msg.Nwk, msg.IEEE, 0x0000) def on_apsde_indication(self, msg): """APSDE-DATA.indication handler.""" is_broadcast = bool(msg.FrameFC & t_zboss.APSFrameFC.Broadcast) is_group = bool(msg.FrameFC & t_zboss.APSFrameFC.Group) is_secure = bool(msg.FrameFC & t_zboss.APSFrameFC.Secure) if is_broadcast: dst = t.AddrModeAddress( addr_mode=t.AddrMode.Broadcast, address=t.BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR, ) elif is_group: dst = t.AddrModeAddress( addr_mode=t.AddrMode.Group, address=msg.GrpAddr ) else: dst = t.AddrModeAddress( addr_mode=t.AddrMode.NWK, address=self.state.node_info.nwk, ) packet = t.ZigbeePacket( src=t.AddrModeAddress( addr_mode=t.AddrMode.NWK, address=msg.SrcAddr, ), src_ep=msg.SrcEndpoint, dst=dst, dst_ep=msg.DstEndpoint, tsn=msg.Payload[1], profile_id=msg.ProfileId, cluster_id=msg.ClusterId, data=t.SerializableBytes( t.List[t.uint8_t](msg.Payload[0:msg.PayloadLength]).serialize() ), tx_options=( t.TransmitOptions.APS_Encryption if is_secure else t.TransmitOptions.NONE ), ) self.packet_received(packet) def on_ncp_reset(self, msg): """NCP_RESET.indication handler.""" if msg.ResetSrc == t_zboss.ResetSource.RESET_SRC_POWER_ON: return LOGGER.debug( f"Resetting ControllerApplication. Source: {msg.ResetSrc}") if self._reset_task: LOGGER.debug("Preempting ControllerApplication reset") self._reset_task.cancel() self._reset_task = asyncio.create_task(self._reset_controller()) async def _reset_controller(self): """Restart the application controller.""" self.disconnect() await self.startup() async def send_packet(self, packet: t.ZigbeePacket) -> None: """Send packets.""" if self._api is None: raise DeliveryError( "Coordinator is disconnected, cannot send request") LOGGER.debug("Sending packet %r", packet) options = c.aps.TransmitOptions.NONE if t.TransmitOptions.ACK in packet.tx_options: options |= c.aps.TransmitOptions.ACK_ENABLED if t.TransmitOptions.APS_Encryption in packet.tx_options: options |= c.aps.TransmitOptions.SECURITY_ENABLED # Prepare ZBOSS types from zigpy types. dst_addr = packet.dst.address dst_addr_mode = packet.dst.addr_mode if packet.dst.addr_mode != t.AddrMode.IEEE: dst_addr = t.EUI64( [ packet.dst.address % 0x100, packet.dst.address >> 8, 0, 0, 0, 0, 0, 0, ] ) if packet.dst.addr_mode == t.AddrMode.Broadcast: dst_addr_mode = t.AddrMode.Group # Don't release the concurrency-limiting semaphore until we are done # trying. There is no point in allowing requests to take turns getting # buffer errors. async with self._limit_concurrency(): await self._api.request( c.APS.DataReq.Req( TSN=packet.tsn, ParamLength=t.uint8_t(21), # Fixed value 21 DataLength=t.uint16_t(len(packet.data.serialize())), DstAddr=dst_addr, ProfileID=packet.profile_id, ClusterId=packet.cluster_id, DstEndpoint=packet.dst_ep, SrcEndpoint=packet.src_ep, Radius=packet.radius or 0, DstAddrMode=dst_addr_mode, TxOptions=options, UseAlias=t.Bool.false, AliasSrcAddr=t.NWK(0x0000), AliasSeqNbr=t.uint8_t(0x00), Payload=t_zboss.Payload(packet.data.serialize()), ) )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/zigbee/application.py
application.py
import logging import zigpy.util import zigpy.device import zigpy.endpoint import zigpy.types as t import zigpy_zboss.types as t_nrf from zigpy_zboss import commands as c from zigpy.zdo import types as zdo_t from zigpy.zdo import ZDO as ZigpyZDO class NrfZDO(ZigpyZDO): """The ZDO endpoint of a device.""" def handle_mgmt_permit_joining_req( self, permit_duration: int, tc_significance: int, ): """Handle ZDO permit joining request.""" hdr = zdo_t.ZDOHeader(zdo_t.ZDOCmd.Mgmt_Permit_Joining_req, 0) dst_addressing = t.Addressing.IEEE self.listener_event("permit_duration", permit_duration) self.listener_event( "zdo_mgmt_permit_joining_req", self._device, dst_addressing, hdr, (permit_duration, tc_significance), ) @zigpy.util.retryable_request async def Bind_req(self, eui64, ep, cluster, dst_address): """Binding request.""" if dst_address.addrmode == t.AddrMode.IEEE: addr_mode = t_nrf.BindAddrMode.IEEE dst_eui64 = dst_address.ieee # ZBOSS does not support the NWK mode for binding elif dst_address.addrmode == t.AddrMode.NWK: self.log( logging.WARNING, "Nwk address mode is not supported for the Bind request." ) elif dst_address.addrmode == t.AddrMode.Group: addr_mode = t_nrf.BindAddrMode.Group dst_eui64 = [ dst_address.nwk % 0x100, dst_address.nwk >> 8, 0, 0, 0, 0, 0, 0, ] res = await self._device._application._api.request( c.ZDO.BindReq.Req( TSN=self._device._application.get_sequence(), TargetNwkAddr=self._device.nwk, SrcIEEE=eui64, SrcEndpoint=ep, ClusterId=cluster, DstAddrMode=addr_mode, DstAddr=dst_eui64, DstEndpoint=dst_address.endpoint, ) ) if res.StatusCode != 0: return (res.StatusCode % 0xFF, dst_address, cluster) return (zdo_t.Status.SUCCESS, dst_address, cluster) @zigpy.util.retryable_request async def Unbind_req(self, eui64, ep, cluster, dst_address): """Unbinding request.""" if dst_address.addrmode == t.AddrMode.IEEE: addr_mode = t_nrf.BindAddrMode.IEEE dst_eui64 = t.Addressing.IEEE # ZBOSS does not support the NWK mode for binding elif dst_address.addrmode == t.AddrMode.NWK: self.log( logging.WARNING, "Nwk address mode is not supported for the Unbind request." ) elif dst_address.addrmode == t.AddrMode.Group: addr_mode = t_nrf.BindAddrMode.Group dst_eui64 = [ dst_address.nwk % 0x100, dst_address.nwk >> 8, 0, 0, 0, 0, 0, 0, ] res = await self._device._application._api.request( c.ZDO.UnbindReq.Req( TSN=self._device._application.get_sequence(), TargetNwkAddr=self._device.nwk, SrcIEEE=eui64, SrcEndpoint=ep, ClusterId=cluster, DstAddrMode=addr_mode, DstAddr=dst_eui64, DstEndpoint=dst_address.endpoint, ) ) if res.StatusCode != 0: return (res.StatusCode % 0xFF, dst_address, cluster) return (zdo_t.Status.SUCCESS, dst_address, cluster) @zigpy.util.retryable_request def request(self, command, *args, use_ieee=False): """Request overwrite for Bind/Unbind requests.""" if command == zdo_t.ZDOCmd.Bind_req: return self.Bind_req(*args) if command == zdo_t.ZDOCmd.Unbind_req: return self.Unbind_req(*args) return super().request(command, *args, use_ieee=use_ieee) @zigpy.util.retryable_request async def Node_Desc_req(self, nwk): """Node descriptor request.""" res = await self._device._application._api.request( c.ZDO.NodeDescReq.Req( TSN=self._device._application.get_sequence(), NwkAddr=nwk ) ) if res.StatusCode != 0: return (res.StatusCode, None, None) return (zdo_t.Status.SUCCESS, None, res.NodeDesc) @zigpy.util.retryable_request async def Simple_Desc_req(self, nwk, ep): """Request simple descriptor.""" res = await self._device._application._api.request( c.ZDO.SimpleDescriptorReq.Req( TSN=self._device._application.get_sequence(), NwkAddr=nwk, Endpoint=ep ) ) if res.StatusCode != 0: return (res.StatusCode, None, None) desc = zdo_t.SimpleDescriptor( endpoint=res.SimpleDesc.endpoint, profile=res.SimpleDesc.profile, device_type=res.SimpleDesc.device_type, device_version=res.SimpleDesc.device_version, input_clusters=res.SimpleDesc.input_clusters, output_clusters=res.SimpleDesc.output_clusters, ) return (zdo_t.Status.SUCCESS, None, desc) @zigpy.util.retryable_request async def Active_EP_req(self, nwk): """Request active end points.""" res = await self._device._application._api.request( c.ZDO.ActiveEpReq.Req( TSN=self._device._application.get_sequence(), NwkAddr=nwk ) ) if res.StatusCode != 0: return (res.StatusCode, None, None) return (zdo_t.Status.SUCCESS, None, res.ActiveEpList) @zigpy.util.retryable_request async def Mgmt_Lqi_req(self, idx): """Request Link Quality Index.""" res = await self._device._application._api.request( c.ZDO.MgmtLqi.Req( TSN=self._device._application.get_sequence(), DestNWK=self._device.nwk, Index=idx, ) ) if res.StatusCode != 0: return (res.StatusCode, None) return (res.StatusCode, res.Neighbors) async def Mgmt_Leave_req(self, ieee, flags): """Request device leaving the network.""" res = await self._device._application._api.request( c.ZDO.MgtLeave.Req( TSN=self._device._application.get_sequence(), DestNWK=t.NWK(self._device._application.devices[ieee].nwk), IEEE=t.EUI64(ieee), Flags=t.uint8_t(flags), ) ) return res.StatusCode async def Mgmt_Permit_Joining_req(self, duration, tc_significance): """Request join permition.""" res = await self._device._application._api.request( c.ZDO.PermitJoin.Req( TSN=self._device._application.get_sequence(), DestNWK=t.NWK(t.BroadcastAddress.RX_ON_WHEN_IDLE), PermitDuration=t.uint8_t(duration), TCSignificance=t.uint8_t(tc_significance), ) ) return res.StatusCode async def Mgmt_NWK_Update_req(self, nwkUpdate): """Request join permition.""" res = await self._device._application._api.request( c.ZDO.MgmtNwkUpdate.Req( TSN=self._device._application.get_sequence(), ScanChannelMask=nwkUpdate.ScanChannels, ScanDuration=nwkUpdate.ScanDuration, ScanCount=nwkUpdate.ScanCount or 0, MgrAddr=self._device.nwk, DstNWK=t.NWK(0x0000), ) ) if res.StatusCode != 0: return (None, None, None, None, None) return (None, res.ScannedChannels, None, None, res.EnergyValues) class NrfDevice(zigpy.device.Device): """Class representing an nRF device.""" def __init__(self, *args, **kwargs): """Initialize instance.""" super().__init__(*args, **kwargs) assert hasattr(self, "zdo") self.zdo = NrfZDO(self) self.endpoints[0] = self.zdo class NrfCoordinator(NrfDevice): """Zigpy Device representing the controller.""" def __init__(self, *args, **kwargs): """Initialize instance.""" super().__init__(*args, **kwargs) @property def manufacturer(self): """Return manufacturer.""" return "Nordic Semiconductor" @property def model(self): """Return model.""" return "nRF52840"
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/zigbee/device.py
device.py
from __future__ import annotations import enum import logging import dataclasses import zigpy.zdo.types import zigpy_zboss.types as t LOGGER = logging.getLogger(__name__) TYPE_ZBOSS_NCP_API_HL = t.uint8_t(0x06) class ControlType(t.enum_uint8): """Control Type.""" REQ = 0x00 RSP = 0x01 IND = 0x02 class StatusCategory(t.enum_uint8): """Status Category.""" GENERIC = 0 MAC = 2 NWK = 3 APS = 4 ZDO = 5 CBKE = 6 class StatusCodeGeneric(t.enum_uint8): """Status Code for the Generic category.""" OK = 0 ERROR = 1 BLOCKED = 2 EXIT = 3 BUSY = 4 EOF = 5 OUT_OF_RANGE = 6 EMPTY = 7 CANCELLED = 8 INVALID_PARAMETER_1 = 10 INVALID_PARAMETER_2 = 11 INVALID_PARAMETER_3 = 12 INVALID_PARAMETER_4 = 13 INVALID_PARAMETER_5 = 14 INVALID_PARAMETER_6 = 15 INVALID_PARAMETER_7 = 16 INVALID_PARAMETER_8 = 17 INVALID_PARAMETER_9 = 18 INVALID_PARAMETER_10 = 19 INVALID_PARAMETER_11_OR_MORE = 20 PENDING = 21 NO_MEMORY = 22 INVALID_PARAMETER = 23 OPERATION_FAILED = 24 BUFFER_TOO_SMALL = 25 END_OF_LIST = 26 ALREADY_EXISTS = 27 NOT_FOUND = 28 OVERFLOW = 29 TIMEOUT = 30 NOT_IMPLEMENTED = 31 NO_RESOURCES = 32 UNINITIALIZED = 33 NO_SERVER = 34 INVALID_STATE = 35 CONNECTION_FAILED = 37 CONNECTION_LOST = 38 UNAUTHORIZED = 40 CONFLICT = 41 INVALID_FORMAT = 42 NO_MATCH = 43 PROTOCOL_ERROR = 44 VERSION = 45 MALFORMED_ADDRESS = 46 COULD_NOT_READ_FILE = 47 FILE_NOT_FOUND = 48 DIRECTORY_NOT_FOUND = 49 CONVERSION_ERROR = 50 INCOMPATIBLE_TYPES = 51 FILE_CORRUPTED = 56 PAGE_NOT_FOUND = 57 ILLEGAL_REQUEST = 62 INVALID_GROUP = 64 TABLE_FULL = 65 IGNORE = 69 AGAIN = 70 DEVICE_NOT_FOUND = 71 OBSOLETE = 72 class StatusCodeAPS(t.enum_uint8): """Status Code for the APS category.""" # A request has been executed successfully. SUCCESS = 0x00 # A transmit request failed since the ASDU is too large and fragmentation # is not supported. ASDU_TOO_LONG = 0xa0 # A received fragmented frame could not be defragmented at the current # time. DEFRAG_DEFERRED = 0xa1 # A received fragmented frame could not be defragmented since the device # does not support fragmentation. DEFRAG_UNSUPPORTED = 0xa2 # A parameter value was out of range. ILLEGAL_REQUEST = 0xa3 # An APSME-UNBIND.request failed due to the requested binding link not # existing in the binding table. INVALID_BINDING = 0xa4 # An APSME-REMOVE-GROUP.request has been issued with a group identifier # that does not appear in the group table. INVALID_GROUP = 0xa5 # A parameter value was invalid or out of range. INVALID_PARAMETER = 0xa6 # An APSDE-DATA.request requesting acknowledged trans- mission failed due # to no acknowledgement being received. NO_ACK = 0xa7 # An APSDE-DATA.request with a destination addressing mode set to 0x00 # failed due to there being no devices bound to this device. NO_BOUND_DEVICE = 0xa8 # An APSDE-DATA.request with a destination addressing mode set to 0x03 # failed due to no corresponding short address found in the address map # table. NO_SHORT_ADDRESS = 0xa9 # An APSDE-DATA.request with a destination addressing mode set to 0x00 # failed due to a binding table not being supported on the device. NOT_SUPPORTED = 0xaa # An ASDU was received that was secured using a link key. SECURED_LINK_KEY = 0xab # An ASDU was received that was secured using a network key. SECURED_NWK_KEY = 0xac # An APSDE-DATA.request requesting security has resulted in an error # during the corresponding security processing. SECURITY_FAIL = 0xad # An APSME-BIND.request or APSME.ADD-GROUP.request issued when the # binding or group tables, respectively, were full. TABLE_FULL = 0xae # An ASDU was received without any security. UNSECURED = 0xaf # An APSME-GET.request or APSME-SET.request has been issued with an # unknown attribute identifier. UNSUPPORTED_ATTRIBUTE = 0xb0 class StatusCodeCBKE(t.enum_uint8): """Status Code for the CBKE category.""" # The Issuer field within the key establishment partner's certificate is # unknown to the sending device UNKNOWN_ISSUER = 1 # The device could not confirm that it shares the same key with the # corresponding device BAD_KEY_CONFIRM = 2 # The device received a bad message from the corresponding device BAD_MESSAGE = 3 # The device does not currently have the internal resources necessary to # perform key establishment NO_RESOURCES = 4 # The device does not support the specified key establishment suite in the # partner's Initiate Key Establishment message UNSUPPORTED_SUITE = 5 # The received certificate specifies a type, curve, hash, or other # parameter that is either unsupported by the device or invalid INVALID_CERTIFICATE = 6 # Non-standard ZBOSS extension: SE KE endpoint not found NO_KE_EP = 7 class LLFlags(t.enum_flag_uint8): """Flags in low level header.""" isACK = 0x01 Retransmit = 0x02 PacketSeq = 0x0C ACKSeq = 0x30 FirstFrag = 0x40 LastFrag = 0x80 class HLCommonHeader(t.uint32_t): """High Level Common Header class.""" def __new__( cls, value: int = 0x00000000, *, version=None, type=None, id=None ) -> "HLCommonHeader": """Create high level common header.""" instance = super().__new__(cls, value) if version is not None: instance = instance.with_version(version) if type is not None: instance = instance.with_type(type) if id is not None: instance = instance.with_id(id) return instance @property def version(self) -> t.uint8_t: """Return protocol version.""" return t.uint8_t(self & 0x000000FF) @property def control_type(self) -> ControlType: """Return control type.""" return ControlType((self & 0x0000FF00) >> 8) @property def id(self) -> t.uint16_t: """Return high level command id.""" return t.uint16_t((self & 0xFFFF0000) >> 16) def with_id(self, value: int) -> "HLCommonHeader": """Set the command ID.""" return type(self)(self & 0xFFFF | (value & 0xFFFF) << 16) def with_type(self, value: ControlType) -> "HLCommonHeader": """Set the control type.""" return type(self)(self & 0xFFFF00FF | (value & 0xFF) << 8) def with_version(self, value: t.uint8_t) -> "HLCommonHeader": """Set the protocol version in use.""" return type(self)(self & 0xFFFFFF00 | (value & 0xFF)) def __str__(self) -> str: """Set the string representation of the high level common header.""" return ( f"{type(self).__name__}(" f"version=0x{self.version:02X}, " f"type={self.control_type!s}, " f"command_id=0x{self.id:04X}" ")" ) __repr__ = __str__ @dataclasses.dataclass(frozen=True) class CommandDef: """Class used to define a command.""" control_type: ControlType command_id: t.uint16_t blocking: bool = False req_schema: tuple | None = None rsp_schema: tuple | None = None class CommandsMeta(type): """Metaclass for commands. Metaclass that creates `Command` subclasses out of the `CommandDef` definitions. """ def __new__(cls, name: str, bases, classdict): """Create new class instance.""" # Ignore CommandsBase if not bases: return type.__new__(cls, name, bases, classdict) classdict["_commands"] = [] for command, definition in classdict.items(): if not isinstance(definition, CommandDef): continue # We manually create the qualname to match the final obj structure qualname = classdict["__qualname__"] + "." + command # The commands class is dynamically created from the definition helper_class_dict = { "definition": definition, "type": definition.control_type, "__qualname__": qualname, "Req": None, "Rsp": None, "Ind": None, } header = ( HLCommonHeader() .with_id(definition.command_id) .with_type(definition.control_type) ) if definition.req_schema is not None: req_header = header rsp_header = req_header.with_type(ControlType.RSP) class Req( CommandBase, header=req_header, schema=definition.req_schema, blocking=definition.blocking ): pass class Rsp( CommandBase, header=rsp_header, schema=definition.rsp_schema ): pass Req.__qualname__ = qualname + ".Req" Req.Req = Req Req.Rsp = Rsp Req.Ind = None helper_class_dict["Req"] = Req Rsp.__qualname__ = qualname + ".Rsp" Rsp.Rsp = Rsp Rsp.Req = Req Rsp.Ind = None helper_class_dict["Rsp"] = Rsp else: assert definition.rsp_schema is not None, definition if definition.control_type == ControlType.IND: # If there is no request schema, this is an indication class Ind( CommandBase, header=header, schema=definition.rsp_schema ): pass Ind.__qualname__ = qualname + ".Ind" Ind.Req = None Ind.Rsp = None Ind.Ind = Ind helper_class_dict["Ind"] = Ind else: raise RuntimeError( f"Invalid command definition {command} = {definition}" ) # pragma: no cover classdict[command] = type(command, (), helper_class_dict) classdict["_commands"].append(classdict[command]) return type.__new__(cls, name, bases, classdict) def __iter__(self): """Overwrite iteration.""" return iter(self._commands) class CommandsBase(metaclass=CommandsMeta): """Parent class for commands type (APS, AF, NWK, ...).""" class CommandBase: """Class containing required objects for a command.""" Req = None Rsp = None Ind = None def __init_subclass__(cls, *, header, schema, blocking=False): """Set class parameters when the class is used as parent.""" super().__init_subclass__() cls.header = header cls.schema = schema cls.blocking = blocking def __init__(self, *, partial=False, **params): """Initialize object.""" super().__setattr__("_partial", partial) super().__setattr__("_bound_params", {}) all_params = [p.name for p in self.schema] optional_params = [p.name for p in self.schema if p.optional] given_params = set(params.keys()) given_optional = [p for p in params.keys() if p in optional_params] unknown_params = given_params - set(all_params) missing_params = ( set(all_params) - set(optional_params)) - given_params if unknown_params: raise KeyError( f"Unexpected parameters: {unknown_params}. " f"Expected one of {missing_params}" ) if not partial: # Optional params must be passed without any skips if optional_params[: len(given_optional)] != given_optional: raise KeyError( f"Optional parameters cannot be skipped: " f"expected order {optional_params}, got {given_optional}." ) if missing_params: raise KeyError( f"Missing parameters: {set(all_params) - given_params}") bound_params = {} for param in self.schema: if params.get(param.name) is None and (partial or param.optional): bound_params[param.name] = (param, None) continue value = params[param.name] if not isinstance(value, param.type): # fmt: off is_coercible_type = [ isinstance(value, int) and # noqa: W504 issubclass(param.type, int) and # noqa: W504 not issubclass(param.type, enum.Enum), isinstance(value, bytes) and # noqa: W504 issubclass(param.type, (t.ShortBytes, t.LongBytes)), isinstance(value, list) and issubclass(param.type, list), isinstance(value, bool) and issubclass(param.type, t.Bool), ] # fmt: on if any(is_coercible_type): value = param.type(value) elif type(value) is zigpy.zdo.types.SimpleDescriptor and \ param.type is \ zigpy.zdo.types.SizePrefixedSimpleDescriptor: data = value.serialize() value, _ = param.type.deserialize( bytes([len(data)]) + data) else: raise ValueError( f"In {type(self)}, param {param.name} is " f"type {param.type}, got {type(value)}" ) try: value.serialize() except Exception as e: raise ValueError( f"Invalid parameter value: {param.name}={value!r}" ) from e bound_params[param.name] = (param, value) super().__setattr__("_bound_params", bound_params) def to_frame(self, *, align=False): """Return a Frame object.""" if self._partial: raise ValueError(f"Cannot serialize a partial frame: {self}") from zigpy_zboss.frames import HLPacket from zigpy_zboss.frames import LLHeader from zigpy_zboss.frames import Frame chunks = [] for param, value in self._bound_params.values(): if value is None: continue if issubclass(param.type, t.CStruct): chunks.append(value.serialize(align=align)) else: chunks.append(value.serialize()) hl_packet = HLPacket(self.header, b"".join(chunks)) # Flags and CRC8 are set later. Before sending to NCP. ll_header = ( LLHeader() .with_signature(Frame.signature) .with_size(hl_packet.length + 5) .with_type(TYPE_ZBOSS_NCP_API_HL) ) return Frame(ll_header, hl_packet) @classmethod def from_frame(cls, frame, *, align=False) -> "CommandBase": """Return a CommandBase object.""" if frame.hl_packet.header != cls.header: raise ValueError( f"Wrong frame header in {cls}: {cls.header} != " f"{frame.hl_packet.header}" ) data = frame.hl_packet.data params = {} for param in cls.schema: try: if issubclass(param.type, t.CStruct): params[param.name], data = param.type.deserialize( data, align=align) else: params[param.name], data = param.type.deserialize(data) except ValueError: if not data and param.optional: # If we're out of data and the parameter is optional, # we're done break elif not data and not param.optional: # If we're out of data but the parameter is required, # this is bad raise ValueError( f"Frame data is truncated (parsed {params})," f" required parameter remains: {param}" ) else: # Otherwise, let the exception happen raise # if data: # raise ValueError( # f"Frame {frame} contains trailing data after parsing: {data}" # ) return cls(**params), data def matches(self, other: "CommandBase") -> bool: """Match parameters and values with other CommandBase.""" if type(self) is not type(other): return False assert self.header == other.header param_pairs = zip( self._bound_params.values(), other._bound_params.values()) for ( (expected_param, expected_value), (actual_param, actual_value), ) in param_pairs: assert expected_param == actual_param # Only non-None bound params are considered if expected_value is not None and expected_value != actual_value: return False return True def __eq__(self, other): """Return True if bound parameters are equal.""" return type(self) is type(other) and \ self._bound_params == other._bound_params def __hash__(self): """Return a hash from tuple made of command parameters.""" params = tuple(self._bound_params.items()) return hash((type(self), self.header, self.schema, params)) def __getattribute__(self, key): """Try to return the attribute of the command.""" try: return object.__getattribute__(self, key) except AttributeError: pass try: param, value = object.__getattribute__(self, "_bound_params")[key] return value except KeyError: pass raise AttributeError(f"{self} has no attribute {key!r}") def __setattr__(self, key, value): """Prevent attributes to be changed.""" raise RuntimeError("Command instances are immutable") def __delattr__(self, key): """Prevent attributes to be deleted.""" raise RuntimeError("Command instances are immutable") def __repr__(self): """Return a command representation.""" params = [f"{p.name}={v!r}" for p, v in self._bound_params.values()] return f'{self.__class__.__qualname__}({", ".join(params)})' __str__ = __repr__ class PolicyType(t.enum_uint16): """Class representing the policy type of the trust center.""" TC_Link_Keys_Required = 0x0000 IC_Required = 0x0001 TC_Rejoin_Enabled = 0x0002 Ignore_TC_Rejoin = 0x0003 APS_Insecure_Join = 0x0004 Disable_NWK_MGMT_Channel_Update = 0x0005 class ResetOptions(t.enum_uint8): """Enum class for the reset options.""" NoOptions = 0 EraseNVRAM = 1 FactoryReset = 2 LockReadingKeys = 3 class ResetSource(t.enum_uint8): """Enum class for the reset source.""" RESET_SRC_POWER_ON = 0 RESET_SRC_SW_RESET = 1 RESET_SRC_RESET_PIN = 2 RESET_SRC_BROWN_OUT = 3 RESET_SRC_CLOCK_LOSS = 4 RESET_SRC_OTHER = 5 class DeviceRole(t.enum_uint8): """Enum class for the device role.""" ZC = 0 ZR = 1 ZED = 2 NONE = 3 class TimeoutIndex(t.enum_uint8): """Enum for the timeout index.""" Seconds_10 = 0x00 Minutes_2 = 0x01 Minutes_4 = 0x02 Minutes_8 = 0x03 Minutes_16 = 0x04 Minutes_32 = 0x05 Minutes_64 = 0x06 Minutes_128 = 0x07 Minutes_256 = 0x08 Minutes_512 = 0x09 Minutes_1024 = 0x0A Minutes_2048 = 0x0B Minutes_4096 = 0x0C Minutes_8192 = 0x0D Minutes_16384 = 0x0E class PowerMode(t.enum_uint8): """Enum class for power mode.""" # Receiver synchronized with the receiver on when idle subfield of the # node descriptor Sync = 0x00 # Receiver comes on periodically as defined by the node power descriptor Perio = 0x01 # Receiver comes on when stimulated, for example, by a user pressing a # button Stim = 0x02 class PowerSourceLevel(t.enum_uint8): """Enum class for the power source level.""" Critical = 0 Percent_33 = 4 Percent_66 = 8 Percent_100 = 12 class APSFrameFC(t.enum_flag_uint8): """Enum class for APS frame flags.""" Unicast = 1 << 0 Broadcast = 1 << 2 Group = 1 << 3 Secure = 1 << 5 Retransmit = 1 << 6 class MACCapability(t.enum_flag_uint8): """Enum class for MAC capabilities.""" AlternatePANCoordinator = 1 << 0 DeviceType = 1 << 1 PowerSource = 1 << 2 ReceiveOnWhenIdle = 1 << 3 SecurityCapability = 1 << 6 AllocateAddress = 1 << 7 class PowerSource(t.enum_flag_uint8): """Enum class for power source.""" Mains = 1 << 0 RechargeableBattery = 1 << 1 DisposableBattery = 1 << 2 Reserved = 1 << 3 STATUS_SCHEMA = ( t.Param("TSN", t.uint8_t, "Transmit Sequence Number"), t.Param("StatusCat", StatusCategory, "Status category code"), t.Param("StatusCode", t.uint8_t, "Status code inside category"), )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/types/commands.py
commands.py
from __future__ import annotations import enum from zigpy_zboss.types.cstruct import CStruct class Bytes(bytes): """Class for Bytes representation.""" def serialize(self) -> Bytes: """Serialize object.""" return self @classmethod def deserialize(cls, data: bytes) -> tuple[Bytes, bytes]: """Deserialize object.""" return cls(data), b"" def __repr__(self) -> str: """Redefine Bytes representation.""" # Reading byte sequences like \x200\x21 is extremely annoying # compared to \x20\x30\x21 escaped = "".join(f":{b:02X}" for b in self)[1:] return f"b'{escaped}'" __str__ = __repr__ class FixedIntType(int): """Class for fized int type.""" _signed = None _size = None def __new__(cls, *args, **kwargs): """Instantiate object.""" if cls._signed is None or cls._size is None: raise TypeError(f"{cls} is abstract and cannot be created") instance = super().__new__(cls, *args, **kwargs) instance.serialize() return instance def __init_subclass__(cls, signed=None, size=None, hex_repr=None) -> None: """Define parameters when the class is used as parent.""" super().__init_subclass__() if signed is not None: cls._signed = signed if size is not None: cls._size = size if hex_repr: fmt = f"0x{{:0{cls._size * 2}X}}" cls.__str__ = cls.__repr__ = lambda self: fmt.format(self) elif hex_repr is not None and not hex_repr: cls.__str__ = super().__str__ cls.__repr__ = super().__repr__ # XXX: The enum module uses the first class with __new__ in its # __dict__ as the member type. # We have to ensure this is true for every subclass. if "__new__" not in cls.__dict__: cls.__new__ = cls.__new__ def serialize(self) -> bytes: """Serialize object.""" try: return self.to_bytes(self._size, "little", signed=self._signed) except OverflowError as e: # OverflowError is not a subclass of ValueError, # making it annoying to catch raise ValueError(str(e)) from e @classmethod def deserialize(cls, data: bytes) -> tuple[FixedIntType, bytes]: """Deserialize object.""" if len(data) < cls._size: raise ValueError(f"Data is too short to contain {cls._size} bytes") r = cls.from_bytes(data[: cls._size], "little", signed=cls._signed) data = data[cls._size:] return r, data class uint_t(FixedIntType, signed=False): """Class representing the uint_t type.""" class int_t(FixedIntType, signed=True): """Class representing int_t type.""" class int8s(int_t, size=1): """Class representing the int8s type.""" class int16s(int_t, size=2): """Class representing the int16s type.""" class int24s(int_t, size=3): """Class representing the int24s type.""" class int32s(int_t, size=4): """Class representing the int32s type.""" class int40s(int_t, size=5): """Class representing the int40s type.""" class int48s(int_t, size=6): """Class representing the int48s type.""" class int56s(int_t, size=7): """Class representing the int56s type.""" class int64s(int_t, size=8): """Class representing the int64s type.""" class uint8_t(uint_t, size=1): """Class representing the uint8_t type.""" class uint16_t(uint_t, size=2): """Class representing the uint16_t type.""" class uint24_t(uint_t, size=3): """Class representing the uint24_t type.""" class uint32_t(uint_t, size=4): """Class representing the uint32_t type.""" class uint40_t(uint_t, size=5): """Class representing the uint40_t type.""" class uint48_t(uint_t, size=6): """Class representing the uint48_t type.""" class uint56_t(uint_t, size=7): """Class representing the uint56_t type.""" class uint64_t(uint_t, size=8): """Class representing the uint64_t type.""" class ShortBytes(Bytes): """Class representing Bytes with 1 byte header.""" _header = uint8_t def serialize(self) -> Bytes: """Serialize object.""" return self._header(len(self)).serialize() + self @classmethod def deserialize(cls, data: bytes) -> tuple[Bytes, bytes]: """Deserialize object.""" length, data = cls._header.deserialize(data) if length > len(data): raise ValueError( f"Data is too short to contain {length} bytes of data") return cls(data[:length]), data[length:] class LongBytes(ShortBytes): """Class representing Bytes with 2 bytes header.""" _header = uint16_t class BaseListType(list): """Class defining the list type base.""" _item_type = None @classmethod def _serialize_item(cls, item, *, align): if not isinstance(item, cls._item_type): item = cls._item_type(item) if issubclass(cls._item_type, CStruct): return item.serialize(align=align) else: return item.serialize() @classmethod def _deserialize_item(cls, data, *, align): if issubclass(cls._item_type, CStruct): return cls._item_type.deserialize(data, align=align) else: return cls._item_type.deserialize(data) class LVList(BaseListType): """Class representing a list of type with a length header.""" _header = None def __init_subclass__(cls, *, item_type, length_type) -> None: """Set class parameter when the class is used as parent.""" super().__init_subclass__() cls._item_type = item_type cls._header = length_type def serialize(self, *, align=False) -> bytes: """Serialize object.""" assert self._item_type is not None return self._header(len(self)).serialize() + b"".join( [self._serialize_item(i, align=align) for i in self] ) @classmethod def deserialize(cls, data: bytes, *, align=False) -> tuple[LVList, bytes]: """Deserialize object.""" length, data = cls._header.deserialize(data) r = cls() for i in range(length): item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data class FixedList(BaseListType): """Class representing a fixed list.""" _length = None def __init_subclass__(cls, *, item_type, length) -> None: """Set the length when the class is used as parent.""" super().__init_subclass__() cls._item_type = item_type cls._length = length def serialize(self, *, align=False) -> bytes: """Serialize object.""" assert self._length is not None if len(self) != self._length: raise ValueError( f"Invalid length for {self!r}: expected " f"{self._length}, got {len(self)}" ) return b"".join([self._serialize_item(i, align=align) for i in self]) @classmethod def deserialize( cls, data: bytes, *, align=False) -> tuple[FixedList, bytes]: """Deserialize object.""" r = cls() for i in range(cls._length): item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data class CompleteList(BaseListType): """Class representing a complete list.""" def __init_subclass__(cls, *, item_type) -> None: """Set class parameter when the class is used as parent.""" super().__init_subclass__() cls._item_type = item_type def serialize(self, *, align=False) -> bytes: """Serialize object.""" return b"".join([self._serialize_item(i, align=align) for i in self]) @classmethod def deserialize( cls, data: bytes, *, align=False) -> tuple[CompleteList, bytes]: """Deserialize object.""" r = cls() while data: item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data def enum_flag_factory(int_type: FixedIntType) -> enum.Flag: """Enum flag factory. Mixins are broken by Python 3.8.6 so we must dynamically create the enum with the appropriate methods but with only one non-Enum parent class. """ class _NewEnum(int_type, enum.Flag): # Rebind classmethods to our own class _missing_ = classmethod(enum.IntFlag._missing_.__func__) _create_pseudo_member_ = classmethod( enum.IntFlag._create_pseudo_member_.__func__ ) __or__ = enum.IntFlag.__or__ __and__ = enum.IntFlag.__and__ __xor__ = enum.IntFlag.__xor__ __ror__ = enum.IntFlag.__ror__ __rand__ = enum.IntFlag.__rand__ __rxor__ = enum.IntFlag.__rxor__ __invert__ = enum.IntFlag.__invert__ return _NewEnum class enum_uint8(uint8_t, enum.Enum): """Class representing the enum_uint8 type.""" class enum_uint16(uint16_t, enum.Enum): """Class representing the enum_uint16 type.""" class enum_uint24(uint24_t, enum.Enum): """Class representing the enum_uint24 type.""" class enum_uint32(uint32_t, enum.Enum): """Class representing the enum_uint32 type.""" class enum_uint40(uint40_t, enum.Enum): """Class representing the enum_uint40 type.""" class enum_uint48(uint48_t, enum.Enum): """Class representing the enum_uint48 type.""" class enum_uint56(uint56_t, enum.Enum): """Class representing the enum_uint56 type.""" class enum_uint64(uint64_t, enum.Enum): """Class representing the enum_uint64 type.""" class enum_flag_uint8(enum_flag_factory(uint8_t)): """Class representing the enum_flag_uint8 type.""" class enum_flag_uint16(enum_flag_factory(uint16_t)): """Class representing the enum_flag_uint16 type.""" class enum_flag_uint24(enum_flag_factory(uint24_t)): """Class representing the enum_flag_uint24 type.""" class enum_flag_uint32(enum_flag_factory(uint32_t)): """Class representing the enum_flag_uint32 type.""" class enum_flag_uint40(enum_flag_factory(uint40_t)): """Class representing the enum_flag_uint40 type.""" class enum_flag_uint48(enum_flag_factory(uint48_t)): """Class representing the enum_flag_uint48 type.""" class enum_flag_uint56(enum_flag_factory(uint56_t)): """Class representing the enum_flag_uint56 type.""" class enum_flag_uint64(enum_flag_factory(uint64_t)): """Class representing the enum_flag_uint64 type."""
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/types/basic.py
basic.py
from __future__ import annotations import zigpy.types as t import zigpy_zboss.types as zboss_t from . import basic class DatasetId(zboss_t.enum_uint16): """NVRAM dataset types.""" ZB_NVRAM_RESERVED = 0 ZB_NVRAM_COMMON_DATA = 1 ZB_NVRAM_HA_DATA = 2 ZB_NVRAM_ZCL_REPORTING_DATA = 3 ZB_NVRAM_APS_SECURE_DATA_GAP = 4 ZB_NVRAM_APS_BINDING_DATA_GAP = 5 ZB_NVRAM_HA_POLL_CONTROL_DATA = 6 ZB_IB_COUNTERS = 7, ZB_NVRAM_DATASET_GRPW_DATA = 8 ZB_NVRAM_APP_DATA1 = 9 ZB_NVRAM_APP_DATA2 = 10 ZB_NVRAM_ADDR_MAP = 11 ZB_NVRAM_NEIGHBOUR_TBL = 12 ZB_NVRAM_INSTALLCODES = 13 ZB_NVRAM_APS_SECURE_DATA = 14 ZB_NVRAM_APS_BINDING_DATA = 15 ZB_NVRAM_DATASET_GP_PRPOXYT = 16 ZB_NVRAM_DATASET_GP_SINKT = 17 ZB_NVRAM_DATASET_GP_CLUSTER = 18 ZB_NVRAM_APS_GROUPS_DATA = 19 ZB_NVRAM_DATASET_SE_CERTDB = 20 ZB_NVRAM_ZCL_WWAH_DATA = 21 ZB_NVRAM_APP_DATA3 = 27 ZB_NVRAM_APP_DATA4 = 28 class NVRAMDataset( basic.LVList, item_type=basic.uint8_t, length_type=basic.uint16_t): """Class representing a NVRAM dataset.""" class NwkAddrMapHeader(t.Struct): """Class representing a NVRAM network address map header.""" length: t.uint8_t version: t.uint8_t _align: t.uint16_t class NwkAddrMapRecord(t.Struct): """Class representing a NVRAM network address map record v2.""" ieee_addr: t.EUI64 nwk_addr: t.NWK index: t.uint8_t redirect_type: t.uint8_t redirect_ref: t.uint8_t _align: t.uint24_t class NwkAddrMap( basic.LVList, item_type=NwkAddrMapRecord, length_type=NwkAddrMapHeader): """Class representing a NVRAM network address map.""" @classmethod def deserialize( cls, data: bytes, *, align=False) -> tuple[basic.LVList, bytes]: """Deserialize object.""" data = data[2:] # Dropping dataset length attribute header, data = cls._header.deserialize(data) r = cls() for _ in range(header.length): item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data class ApsSecureEntry(t.Struct): """Class representing a NVRAM APS Secure key entry.""" ieee_addr: t.EUI64 key: t.KeyData _unknown_1: basic.uint32_t # Helper attribute to extract list size. _entry_byte_size = 28 class ApsSecureKeys( basic.LVList, item_type=ApsSecureEntry, length_type=basic.uint16_t): """Class representing a list of APS secure keys.""" @classmethod def deserialize( cls, data: bytes, *, align=False) -> tuple[basic.LVList, bytes]: """Deserialize object.""" length, data = cls._header.deserialize(data) r = cls() data = data[4:] # Dropping the 4 first bytes from the list entry_cnt = (length - 4) / ApsSecureEntry._entry_byte_size for _ in range(int(entry_cnt)): item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/types/nvids.py
nvids.py
from __future__ import annotations import typing import inspect import dataclasses import zigpy.types as zigpy_t import zigpy_zboss.types as t class ListSubclass(list): """A list subclass.""" # So we can call `setattr()` on it @dataclasses.dataclass(frozen=True) class CStructField: """Class for Cstruct field.""" name: str type: type def __post_init__(self) -> None: """Set parameters about the cstruct.""" # Throw an error early self.get_size_and_alignment() def get_size_and_alignment(self, align=False) -> tuple[int, int]: """Return size and alignment of a cstruct.""" if issubclass(self.type, (zigpy_t.FixedIntType, t.FixedIntType)): return self.type._size, self.type._size if align else 1 elif issubclass(self.type, zigpy_t.EUI64): return 8, 1 elif issubclass(self.type, zigpy_t.KeyData): return 16, 1 elif issubclass(self.type, CStruct): return self.type.get_size(align=align), \ self.type.get_alignment(align=align) elif issubclass(self.type, t.AddrModeAddress): return 1 + 8, 1 else: raise TypeError(f"Cannot get size of unknown type: {self.type!r}") class CStruct: """Class represeting cstruct.""" _padding_byte = b"\xFF" def __init_subclass__(cls): """Set cstruct fields when used as parent class.""" super().__init_subclass__() fields = ListSubclass() for name, annotation in typing.get_type_hints(cls).items(): try: field = CStructField(name=name, type=annotation) except Exception as e: raise TypeError(f"Invalid field {name}={annotation!r}") from e fields.append(field) setattr(fields, field.name, field) cls.fields = fields def __new__(cls, *args, **kwargs) -> CStruct: """Create a Cstruct instance.""" # Like a copy constructor if len(args) == 1 and isinstance(args[0], cls): if kwargs: raise ValueError( f"Cannot use copy constructor with kwargs: {kwargs!r}") kwargs = args[0].as_dict() args = () # Pretend our signature is `__new__(cls, p1: t1, p2: t2, ...)` signature = inspect.Signature( parameters=[ inspect.Parameter( name=f.name, kind=inspect.Parameter.POSITIONAL_OR_KEYWORD, default=None, annotation=f.type, ) for f in cls.fields ] ) bound = signature.bind(*args, **kwargs) bound.apply_defaults() instance = super().__new__(cls) # Set and convert the attributes to their respective types for name, value in bound.arguments.items(): field = getattr(cls.fields, name) if value is not None: try: value = field.type(value) except Exception as e: raise ValueError( f"Failed to convert {name}={value!r} from type" f" {type(value)} to {field.type}" ) from e setattr(instance, name, value) return instance def as_dict(self) -> dict[str, typing.Any]: """Return a dict representation of a Cstruct.""" return {f.name: getattr(self, f.name) for f in self.fields} @classmethod def get_padded_fields( cls, *, align=False ) -> typing.Iterable[tuple[int, int, CStructField]]: """Get padded fields.""" offset = 0 for field in cls.fields: size, alignment = field.get_size_and_alignment(align=align) padding = (-offset) % alignment offset += padding + size yield padding, size, field @classmethod def get_alignment(cls, *, align=False) -> int: """Return the max alignments.""" alignments = [] for field in cls.fields: size, alignment = field.get_size_and_alignment(align=align) alignments.append(alignment) return max(alignments) @classmethod def get_size(cls, *, align=False) -> int: """Return the total size.""" total_size = 0 for padding, size, field in cls.get_padded_fields(align=align): total_size += padding + size final_padding = (-total_size) % cls.get_alignment(align=align) return total_size + final_padding def serialize(self, *, align=False) -> bytes: """Serialize the object.""" result = b"" for padding, _, field in self.get_padded_fields(align=align): value = getattr(self, field.name) if value is None: raise ValueError(f"Field {field} cannot be empty") try: value = field.type(value) except Exception as e: raise ValueError( f"Failed to convert {field.name}={value!r} from type" f" {type(value)} to {field.type}" ) from e result += self._padding_byte * padding if isinstance(value, CStruct): result += value.serialize(align=align) else: result += value.serialize() # Pad the result to our final length return result.ljust(self.get_size(align=align), self._padding_byte) @classmethod def deserialize(cls, data: bytes, *, align=False) -> tuple[CStruct, bytes]: """Deserialize the object.""" instance = cls() orig_length = len(data) expected_size = cls.get_size(align=align) if orig_length < expected_size: raise ValueError( f"Data is too short, must be at least {expected_size} " f"bytes: {data!r}" ) for padding, _, field in cls.get_padded_fields(align=align): data = data[padding:] if issubclass(field.type, CStruct): value, data = field.type.deserialize(data, align=align) else: value, data = field.type.deserialize(data) setattr(instance, field.name, value) # Strip off the final padding data = data[expected_size - (orig_length - len(data)):] return instance, data def replace(self, **kwargs) -> CStruct: """Return a Cstruct copy.""" d = self.as_dict().copy() d.update(kwargs) return type(self)(**d) def __eq__(self, other: CStruct) -> bool: """Return True if the dict representation of two Cstruct are equal.""" if not isinstance(self, type(other)) and \ not isinstance(other, type(self)): return NotImplemented return self.as_dict() == other.as_dict() def __repr__(self) -> str: """Return a Cstruct representation.""" kwargs = ", ".join([f"{k}={v!r}" for k, v in self.as_dict().items()]) return f"{type(self).__name__}({kwargs})"
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/types/cstruct.py
cstruct.py
from __future__ import annotations import sys import typing import logging import dataclasses from zigpy.types import ( # noqa: F401 NWK, List, Bool, PanId, EUI64, Struct, bitmap8, KeyData, Channels, ClusterId, ExtendedPanId, CharacterString, ) from . import basic LOGGER = logging.getLogger(__name__) JSONType = typing.Union[typing.Dict[str, typing.Any], typing.List[typing.Any]] class BindAddrMode(basic.enum_uint8): """Address mode for bind related requests.""" Reserved_1 = 0x00 Group = 0x01 Reserved_2 = 0x02 IEEE = 0x03 class ChannelEntry: """Class representing a channel entry.""" def __new__(cls, page=None, channel_mask=None): """Create a channel entry instance.""" instance = super().__new__(cls) instance.page = basic.uint8_t(page) instance.channel_mask = channel_mask return instance @classmethod def deserialize(cls, data: bytes) -> "ChannelEntry": """Deserialize the object.""" page, data = basic.uint8_t.deserialize(data) channel_mask, data = Channels.deserialize(data) return cls(page=page, channel_mask=channel_mask), data def serialize(self) -> bytes: """Serialize the object.""" return self.page.serialize() + self.channel_mask.serialize() def __eq__(self, other): """Return True if channel_masks and pages are equal.""" if not isinstance(other, type(self)): return NotImplemented return self.page == other.page and \ self.channel_mask == other.channel_mask def __repr__(self) -> str: """Return a representation of a channel entry.""" return f"{type(self).__name__}(page={self.page!r}," \ f" channels={self.channel_mask!r})" class GroupId(basic.uint16_t, hex_repr=True): """Group ID class.""" @dataclasses.dataclass(frozen=True) class Param: """Schema parameter.""" name: str type: type = None description: str = "" optional: bool = False class MissingEnumMixin: """Mixin class for enum.""" @classmethod def _missing_(cls, value): if not isinstance(value, int): raise ValueError(f"{value} is not a valid {cls.__name__}") new_member = cls._member_type_.__new__(cls, value) new_member._name_ = f"unknown_0x{value:02X}" new_member._value_ = cls._member_type_(value) if sys.version_info >= (3, 8): # Show the warning in the calling code, not in this function LOGGER.warning( "Unhandled %s value: %s", cls.__name__, new_member, stacklevel=2 ) else: LOGGER.warning("Unhandled %s value: %s", cls.__name__, new_member) return new_member class ChannelEntryList( basic.LVList, item_type=ChannelEntry, length_type=basic.uint8_t): """Class representing a list of channel entries.""" class NWKList(basic.LVList, item_type=NWK, length_type=basic.uint8_t): """Class representing a list of NWK addresses.""" class GrpList( basic.LVList, item_type=basic.uint16_t, length_type=basic.uint8_t): """Class representing a list of group addresses.""" class Payload(List, item_type=basic.uint8_t): """Class representing a payload.""" class DeviceUpdateStatus(basic.enum_uint8): """Enum class for device update status.""" secured_rejoin = 0x00 unsecured_join = 0x01 device_left = 0x02 tc_rejoin = 0x03 class ApsAttributes(bitmap8): """Bitmap class for aps attributes.""" key_source = 0b00000001 key_attributes_0 = 0b00000010 key_attributes_2 = 0b00000100 key_from_trust_center = 0b00001000 extended_frame_control_0 = 0b00010000 extended_frame_control_1 = 0b00100000 reserved_0 = 0b01000000 reserved_1 = 0b10000000
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/types/named.py
named.py
import zigpy_zboss.types as t class SecurityCommandCode(t.enum_uint16): """Enum class for Security command_ids.""" SECUR_SET_LOCAL_IC = 0x0501 SECUR_ADD_IC = 0x0502 SECUR_DEL_IC = 0x0503 SECUR_GET_LOCAL_IC = 0x050d SECUR_TCLK_IND = 0x050e SECUR_TCLK_EXCHANGE_FAILED_IND = 0x050f SECUR_NWK_INITIATE_KEY_SWITCH_PROCEDURE = 0x0517 SECUR_GET_IC_LIST = 0x0518 SECUR_GET_IC_BY_IDX = 0x0519 SECUR_REMOVE_ALL_IC = 0x051a class SEC(t.CommandsBase): """SEC commands.""" # SetLocalDeviceInstallcode = t.CommandDef( # t.ControlType.REQ, # SecurityCommandCode.SECUR_SET_LOCAL_IC, # req_schema=( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # t.Param( # "InstallCode", # ???, # "Installcode, including trailing 2 bytes of CRC", # ), # ), # rsp_schema=t.STATUS_SCHEMA, # ) # AddInstallcode = t.CommandDef( # t.ControlType.REQ, # SecurityCommandCode.SECUR_ADD_IC, # req_schema=( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # t.Param("IEEE", t.EUI64, "IEEE address of the remote device"), # t.Param( # "InstallCode", # ???, # "Installcode, including trailing 2 bytes of CRC", # ), # ), # rsp_schema=t.STATUS_SCHEMA, # ) DeleteInstallcode = t.CommandDef( t.ControlType.REQ, SecurityCommandCode.SECUR_DEL_IC, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("IEEE", t.EUI64, "IEEE address of the remote device"), ), rsp_schema=t.STATUS_SCHEMA, ) # GetLocalInstallcode = t.CommandDef( # t.ControlType.REQ, # SecurityCommandCode.SECUR_GET_LOCAL_IC, # req_schema=( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # ), # rsp_schema=t.STATUS_SCHEMA + ( # t.Param( # "InstallCode", # ???, # "Installcode, including trailing 2 bytes of CRC", # ), # ), # ) TCLKIndication = t.CommandDef( t.ControlType.IND, SecurityCommandCode.SECUR_TCLK_IND, req_schema=None, rsp_schema=( t.Param("TCAddr", t.EUI64, "Trust Center Address"), t.Param("KeyType", t.uint8_t, "Key type"), ), ) TCLKExchangeFailedIndication = t.CommandDef( t.ControlType.IND, SecurityCommandCode.SECUR_TCLK_EXCHANGE_FAILED_IND, req_schema=None, rsp_schema=( t.Param("StatusCat", t.uint8_t, "Status category"), t.Param("StatusCode", t.uint8_t, "Status code"), ), ) InitKeySwitchProcedure = t.CommandDef( t.ControlType.REQ, SecurityCommandCode.SECUR_NWK_INITIATE_KEY_SWITCH_PROCEDURE, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA, ) # GetICList = t.CommandDef( # t.ControlType.REQ, # SecurityCommandCode.SECUR_GET_IC_LIST, # req_schema=( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # t.Param( # "StartIdx", # t.uint8_t, # "SoC will return IC Table entries starting with this index" # ), # ), # rsp_schema=t.STATUS_SCHEMA + ( # t.Param( # "ICTableSize", # t.uint8_t, # "The total number of entries in the IC table" # ), # t.Param("StartIdx", t.uint8_t, "Start index"), # t.Param( # "EntryCount", # t.uint8_t, # "The number of entries in this response" # ), # t.Param( # "Entries", # ???, # "Array containing IC entries" # ), # ), # ) # GetICbyIdx = t.CommandDef( # t.ControlType.REQ, # SecurityCommandCode.SECUR_GET_IC_BY_IDX, # req_schema=( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # t.Param( # "ICEntryIdx", # t.uint8_t, # "the index of the entry to get" # ), # ), # rsp_schema=t.STATUS_SCHEMA + ( # t.Param( # "Entry", # ???, # "Array containing IC entries" # ), # ), # ) RemoveAllIC = t.CommandDef( t.ControlType.REQ, SecurityCommandCode.SECUR_REMOVE_ALL_IC, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA, )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/commands/security.py
security.py
import zigpy_zboss.types as t class NcpConfigCommandCode(t.enum_uint16): """Enum class for NCP config command_ids.""" GET_MODULE_VERSION = 0x0001 NCP_RESET = 0x0002 GET_ZIGBEE_ROLE = 0x0004 SET_ZIGBEE_ROLE = 0x0005 GET_ZIGBEE_CHANNEL_MASK = 0x0006 SET_ZIGBEE_CHANNEL_MASK = 0x0007 GET_ZIGBEE_CHANNEL = 0x0008 GET_PAN_ID = 0x0009 SET_PAN_ID = 0x000a GET_LOCAL_IEEE_ADDR = 0x000b SET_LOCAL_IEEE_ADDR = 0x000c GET_TX_POWER = 0x0010 SET_TX_POWER = 0x0011 GET_RX_ON_WHEN_IDLE = 0x0012 SET_RX_ON_WHEN_IDLE = 0x0013 GET_JOINED = 0x0014 GET_AUTHENTICATED = 0x0015 GET_ED_TIMEOUT = 0x0016 SET_ED_TIMEOUT = 0x0017 SET_NWK_KEY = 0x001b GET_NWK_KEYS = 0x001e GET_APS_KEY_BY_IEEE = 0x001f GET_PARENT_ADDRESS = 0x0022 GET_EXTENDED_PAN_ID = 0x0023 GET_COORDINATOR_VERSION = 0x0024 GET_SHORT_ADDRESS = 0x0025 GET_TRUST_CENTER_ADDRESS = 0x0026 NCP_RESET_IND = 0x002b NVRAM_WRITE = 0x002e NVRAM_READ = 0x002f NVRAM_ERASE = 0x0030 NVRAM_CLEAR = 0x0031 SET_TC_POLICY = 0x0032 SET_EXTENDED_PAN_ID = 0x0033 SET_MAX_CHILDREN = 0x0034 GET_MAX_CHILDREN = 0x0035 class NcpConfig(t.CommandsBase): """Ncp Config commands. This category of the API provides general configuration facilities of the NCP. """ GetModuleVersion = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_MODULE_VERSION, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("FWVersion", t.uint32_t, "NCP module firmware version"), t.Param("StackVersion", t.uint32_t, "NCP module stack version"), t.Param( "ProtocolVersion", t.uint32_t, "NCP module protocol version"), ), ) NCPModuleReset = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.NCP_RESET, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("Option", t.ResetOptions, "Reset options"), ), rsp_schema=t.STATUS_SCHEMA, ) GetZigbeeRole = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_ZIGBEE_ROLE, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("DeviceRole", t.DeviceRole, "Zigbee device role"), ), ) SetZigbeeRole = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_ZIGBEE_ROLE, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("DeviceRole", t.DeviceRole, "Zigbee device role"), ), rsp_schema=t.STATUS_SCHEMA, ) GetChannelMask = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_ZIGBEE_CHANNEL_MASK, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "ChannelList", t.ChannelEntryList, "Array of ChannelListEntry structures" ), ), ) SetChannelMask = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_ZIGBEE_CHANNEL_MASK, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("Page", t.uint8_t, "Channel page number"), t.Param("Mask", t.Channels, "Channel mask"), ), rsp_schema=t.STATUS_SCHEMA, ) GetCurrentChannel = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_ZIGBEE_CHANNEL, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("Page", t.uint8_t, "Channel page number"), t.Param("Channel", t.uint8_t, "Channel number"), ), ) GetShortPANID = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_PAN_ID, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("PANID", t.PanId, "Short PAN ID"), ), ) SetShortPANID = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_PAN_ID, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("PANID", t.PanId, "Short PAN ID"), ), rsp_schema=t.STATUS_SCHEMA, ) GetLocalIEEE = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_LOCAL_IEEE_ADDR, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("MacInterfaceNum", t.uint8_t, "Mac interface number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("MacInterfaceNum", t.uint8_t, "Mac interface number"), t.Param("IEEE", t.EUI64, "IEEE address"), ), ) SetLocalIEEE = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_LOCAL_IEEE_ADDR, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("MacInterfaceNum", t.uint8_t, "Mac interface number"), t.Param("IEEE", t.EUI64, "IEEE address"), ), rsp_schema=t.STATUS_SCHEMA, ) GetTransmitPower = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_TX_POWER, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "CurrentTxPower", t.int8s, "Current transmit power in dBm"), ), ) SetTransmitPower = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_TX_POWER, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "RequiredTxPower", t.int8s, "Required transmitter power. In the range of -20..+20 dBm" ), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "ResultantTxPower", t.int8s, "If the required TX power is valid, " "returns the same value or the lowest possible"), ), ) GetRxOnWhenIdle = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_RX_ON_WHEN_IDLE, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "RxOnWhenIdle", t.uint8_t, "Rx On When Idle PIB attribute value: 0 - False, 1 - True" ), ), ) SetRxOnWhenIdle = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_RX_ON_WHEN_IDLE, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "RxOnWhenIdle", t.uint8_t, "Rx On When Idle PIB attribute value: 0 - False, 1 - True" ), ), rsp_schema=t.STATUS_SCHEMA, ) GetJoinStatus = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_JOINED, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "Joined", t.uint8_t, "Bit 0: Device is joined 0 - False, 1 - True" "Bit 1: Parent is lost 0 - False, 1 - True" ), ), ) GetAuthenticationStatus = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_AUTHENTICATED, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "Authenticated", t.uint8_t, "0 Device is not authenticated" "1 device is authenticated" ), ), ) GetEDTimeout = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_ED_TIMEOUT, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "Timeout", t.TimeoutIndex, "0x00 - 10s otherwise 2^N minutes"), ), ) SetEDTimeout = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_ED_TIMEOUT, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "Timeout", t.TimeoutIndex, "0x00 - 10s otherwise 2^N minutes"), ), rsp_schema=t.STATUS_SCHEMA, ) SetNwkKey = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_NWK_KEY, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("NwkKey", t.KeyData, "NWK Key"), t.Param("KeyNumber", t.uint8_t, "Number of NWK Key"), ), rsp_schema=t.STATUS_SCHEMA, ) GetNwkKeys = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_NWK_KEYS, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("NwkKey1", t.KeyData, "NWK Key"), t.Param("KeyNumber1", t.uint8_t, "Number of NWK Key"), t.Param("NwkKey2", t.KeyData, "NWK Key"), t.Param("KeyNumber2", t.uint8_t, "Number of NWK Key"), t.Param("NwkKey3", t.KeyData, "NWK Key"), t.Param("KeyNumber3", t.uint8_t, "Number of NWK Key"), ), ) GetAPSKeyByIEEE = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_APS_KEY_BY_IEEE, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("IEEE", t.EUI64, "IEEE address of remote device"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("APSKey", t.KeyData, "APS Key"), ), ) GetParentAddr = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_PARENT_ADDRESS, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("NWKParentAddr", t.NWK, "NWK PArent address"), ), ) GetExtendedPANID = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_EXTENDED_PAN_ID, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("ExtendedPANID", t.EUI64, "Extended PAN ID"), ), ) GetCoordinatorVersion = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_COORDINATOR_VERSION, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("CoordinatorVersion", t.uint8_t, "Coordinator version"), ), ) GetShortAddr = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_SHORT_ADDRESS, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("NWKAddr", t.NWK, "NWK address of the device"), ), ) GetTrustCenterAddr = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_TRUST_CENTER_ADDRESS, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("TCIEEE", t.EUI64, "TC IEEE address"), ), ) DeviceResetIndication = t.CommandDef( t.ControlType.IND, NcpConfigCommandCode.NCP_RESET_IND, req_schema=None, rsp_schema=( t.Param( "ResetSrc", t.ResetSource, "Reset source which triggered reset" ), ), ) # WriteNVRAM = t.CommandDef( # t.ControlType.REQ, # NcpConfigCommandCode.NVRAM_WRITE, # blocking=True, # req_schema=( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # t.Param( # "DatasetNbr", # t.uint8_t, # "A number of datasets contained in this request" # ), # t.Param("Data", ???, "Data bytes array"), # ), # rsp_schema=t.STATUS_SCHEMA, # ) ReadNVRAM = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.NVRAM_READ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("DatasetId", t.uint16_t, "A dataset type to read"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("NVRAMVersion", t.uint16_t, "Current NVRAM version"), t.Param("DatasetId", t.DatasetId, "Requested dataset type"), t.Param("DatasetVersion", t.uint16_t, "Current dataset version"), t.Param("Dataset", t.NVRAMDataset, "Data bytes array"), ), ) EraseNVRAM = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.NVRAM_ERASE, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA, ) ClearNVRAM = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.NVRAM_CLEAR, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA, ) SetTCPolicy = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_TC_POLICY, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("PolicyType", t.PolicyType, "A policy type to set"), t.Param("PolicyValue", t.uint8_t, "A policy value to set"), ), rsp_schema=t.STATUS_SCHEMA, ) SetExtendedPANID = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_EXTENDED_PAN_ID, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("ExtendedPANID", t.EUI64, "Extended PAN ID to set"), ), rsp_schema=t.STATUS_SCHEMA, ) SetMaxChildren = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.SET_MAX_CHILDREN, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "ChildrenNbr", t.uint8_t, "Number of children to set as a maximum allowed" ), ), rsp_schema=t.STATUS_SCHEMA, ) GetMaxChildren = t.CommandDef( t.ControlType.REQ, NcpConfigCommandCode.GET_MAX_CHILDREN, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "ChildrenNbr", t.uint8_t, "The maximum number of children currently allowed" ), ), )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/commands/ncp_config.py
ncp_config.py
import zigpy_zboss.types as t class NWKCommandCode(t.enum_uint16): """Enum class for NWK command_ids.""" NWK_FORMATION = 0x0401 NWK_DISCOVERY = 0x0402 NWK_NLME_JOIN = 0x0403 NWK_PERMIT_JOINING = 0x0404 NWK_GET_IEEE_BY_SHORT = 0x0405 NWK_GET_SHORT_BY_IEEE = 0x0406 NWK_GET_NEIGHBOR_BY_IEEE = 0x0407 NWK_REJOINED_IND = 0x0409 NWK_REJOIN_FAILED_IND = 0x040a NWK_LEAVE_IND = 0x040b PIM_SET_FAST_POLL_INTERVAL = 0x040e PIM_SET_LONG_POLL_INTERVAL = 0x040f PIM_START_FAST_POLL = 0x0410 PIM_START_LONG_POLL = 0x0411 PIM_START_POLL = 0x0412 PIM_STOP_FAST_POLL = 0x0414 PIM_STOP_POLL = 0x0415 PIM_ENABLE_TURBO_POLL = 0x0416 PIM_DISABLE_TURBO_POLL = 0x0417 NWK_PAN_ID_CONFLICT_RESOLVE = 0x041a NWK_PAN_ID_CONFLICT_IND = 0x041b NWK_ADDRESS_UPDATE_IND = 0x041c NWK_START_WITHOUT_FORMATION = 0x041d NWK_NLME_ROUTER_START = 0x041e PARENT_LOST_IND = 0x0420 PIM_START_TURBO_POLL_PACKETS = 0x0424 PIM_START_TURBO_POLL_CONTINUOUS = 0x0425 PIM_TURBO_POLL_CONTINUOUS_LEAVE = 0x0426 PIM_TURBO_POLL_PACKETS_LEAVE = 0x0427 PIM_PERMIT_TURBO_POLL = 0x0428 PIM_SET_FAST_POLL_TIMEOUT = 0x0429 PIM_GET_LONG_POLL_INTERVAL = 0x042a PIM_GET_IN_FAST_POLL_FLAG = 0x042b SET_KEEPALIVE_MOVE = 0x042c START_CONCENTRATOR_MODE = 0x042d STOP_CONCENTRATOR_MODE = 0x042e NWK_ENABLE_PAN_ID_CONFLICT_RESOLUTION = 0x042f NWK_ENABLE_AUTO_PAN_ID_CONFLICT_RESOLUTION = 0x0430 PIM_TURBO_POLL_CANCEL_PACKET = 0x0431 class NWK(t.CommandsBase): """Commands for network management. This category of the API enables to manage Network Layer at the NCP. """ Formation = t.CommandDef( t.ControlType.REQ, NWKCommandCode.NWK_FORMATION, blocking=True, req_schema=( ( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "ChannelList", t.ChannelEntryList, "Array of ChannelListEntry structures." ), t.Param( "ScanDuration", t.uint8_t, "The time spent scanning each channel is " "(aBaseSuperframeDuration * (2^n + 1)) symbols, " "n = ScanDuration parameter." ), t.Param( "DistributedNetFlag", t.uint8_t, "If 0, create a Centralized network, device is ZC." " If 1, create a Distributed network, device is ZR" ), t.Param( "DistributedNetAddr", t.NWK, "The address the device will use when forming a " "distributed network" ), t.Param( "IEEEAddr", t.EUI64, "The ieee address of the device" ), ) ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("NWKAddr", t.NWK, "NWK address"), ), ) # Discovery = t.CommandDef( # t.ControlType.REQ, # NWKCommandCode.NWK_DISCOVERY, # blocking=True, # req_schema=( # ( # t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), # t.Param( # "ChannelListLen", # t.uint8_t, # "Number of entries in the following Channel List array." # " Must be 1 for 2.4GHz-only build." # ), # t.Param( # "ChannelList", # ???, # "Array of ChannelListEntry structures." # ), # t.Param( # "ScanDuration", # t.uint8_t, # "The time spent scanning each channel is " # "(aBaseSuperframeDuration * (2^n + 1)) symbols, " # "n = ScanDuration parameter." # ), # ) # ), # rsp_schema=t.STATUS_SCHEMA + ( # t.Param( # "NetworkCount", # t.uint8_t, # "Length of Network descriptors array followed" # ), # t.Param("NetworkDesc", ???, "Array of Network descriptors"), # ), # ) PermitJoin = t.CommandDef( t.ControlType.REQ, NWKCommandCode.NWK_PERMIT_JOINING, blocking=True, req_schema=( ( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "PermitDuration", t.uint8_t, "Permit join duration, in seconds. 0 == 'disable'," " 0xff == 0xfe" ), ) ), rsp_schema=t.STATUS_SCHEMA, ) NwkLeaveInd = t.CommandDef( t.ControlType.IND, NWKCommandCode.NWK_LEAVE_IND, rsp_schema=( t.Param("IEEE", t.EUI64, "IEEE address"), t.Param( "Rejoin", t.uint8_t, "0 - No rejoin, 1 - Rejoin requested"), ), ) StartWithoutFormation = t.CommandDef( t.ControlType.REQ, NWKCommandCode.NWK_START_WITHOUT_FORMATION, req_schema=( ( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ) ), rsp_schema=t.STATUS_SCHEMA, )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/commands/nwk_mgmt.py
nwk_mgmt.py
from __future__ import annotations from zigpy.zdo import types as zdo_t import zigpy.types import zigpy.zdo.types import zigpy_zboss.types as t class ZdoCommandCode(t.enum_uint16): """Enum class for ZDO command_ids.""" ZDO_NWK_ADDR_REQ = 0x0201 ZDO_IEEE_ADDR_REQ = 0x0202 ZDO_POWER_DESC_REQ = 0x0203 ZDO_NODE_DESC_REQ = 0x0204 ZDO_SIMPLE_DESC_REQ = 0x0205 ZDO_ACTIVE_EP_REQ = 0x0206 ZDO_MATCH_DESC_REQ = 0x0207 ZDO_BIND_REQ = 0x0208 ZDO_UNBIND_REQ = 0x0209 ZDO_MGMT_LEAVE_REQ = 0x020a ZDO_PERMIT_JOINING_REQ = 0x020b ZDO_DEV_ANNCE_IND = 0x020c ZDO_REJOIN = 0x020d ZDO_SYSTEM_SRV_DISCOVERY_REQ = 0x020e ZDO_MGMT_BIND_REQ = 0x020f ZDO_MGMT_LQI_REQ = 0x0210 ZDO_MGMT_NWK_UPDATE_REQ = 0x0211 ZDO_GET_STATS = 0x0213 ZDO_DEV_AUTHORIZED_IND = 0x0214 ZDO_DEV_UPDATE_IND = 0x0215 ZDO_SET_NODE_DESC_MANUF_CODE = 0x0216 class EnergyValues(t.LVList, item_type=t.uint8_t, length_type=t.uint8_t): """List of enery values.""" class NWKArray(t.CompleteList, item_type=t.NWK): """List of nwk addresses.""" class AddrRequestType(t.enum_uint8): """Enum class for address request type.""" SINGLE = 0x00 EXTENDED = 0x01 class ZDO(t.CommandsBase): """Commands accessing ZDO. This category of the API provides an access to the Zigbee Device Object resided at the NCP. """ NwkAddrReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_NWK_ADDR_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "DstNWK", t.NWK, "NWK address of the remote device to send request to", ), t.Param( "IEEE", t.EUI64, "IEEE address to be matched by the remote device", ), t.Param( "RequestType", AddrRequestType, "0x00 -- single device request, 0x01 -- Extended", ), t.Param( "StartIndex", t.int8s, "Starting index of the returned associated device list." "Valid only if the Request type is Extended response" ), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "RemoteDevIEEE", t.EUI64, "IEEE address of the matched remote device" ), t.Param( "RemoteDevNWK", t.NWK, "NWK address of the matched remote device" ), t.Param( "NumAssocDev", t.uint8_t, "Number of associated devices in the following address list." " Present only if Request type parameter of the request is " "Extended response" ), t.Param( "StartIndex", t.uint8_t, "Starting index of the returned associated device the list. " "Present only if the Request type is Extended response and " "Num Assoc Dev is not 0" ), t.Param( "AssocDevNWKList", NWKArray, "Variable-size array of NWK addresses of devices associated " "with the remote device. Present only if the Request type is " "Extended response and Num Assoc Dev is not 0" ), ), ) IeeeAddrReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_IEEE_ADDR_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "DstNWK", t.NWK, "NWK address of the remote device to send request to", ), t.Param( "NWKtoMatch", t.NWK, "NWK address to be matched by the remote device", ), t.Param( "RequestType", t.uint8_t, "0x00 -- single device request, 0x01 -- Extended", ), t.Param( "StartIndex", t.int8s, "Starting index of the returned associated device list." "Valid only if the Request type is Extended response" ), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "RemoteDevIEEE", t.EUI64, "IEEE address of the matched remote device" ), t.Param( "RemoteDevNWK", t.NWK, "NWK address of the matched remote device" ), t.Param( "NumAssocDev", t.uint8_t, "Number of associated devices in the following address list." " Present only if Request type parameter of the request is " "Extended response", optional=True, ), t.Param( "StartIndex", t.uint8_t, "Starting index of the returned associated device the list. " "Present only if the Request type is Extended response and " "Num Assoc Dev is not 0", optional=True, ), t.Param( "AssocDevNWKList", NWKArray, "Variable-size array of NWK addresses of devices associated " "with the remote device. Present only if the Request type is " "Extended response and Num Assoc Dev is not 0", optional=True, ), ), ) PowerDesc = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_POWER_DESC_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "NWK", t.NWK, "NWK address to be matched by the remote device", ), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "PowerDesc", zigpy.zdo.types.PowerDescriptor, "Power Descriptor Bit Fields" ), t.Param("SrcNWK", t.NWK, "NWK address of source device"), ), ) MgtLeave = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_MGMT_LEAVE_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "DestNWK", t.NWK, "NWK address of the remote device to send the request to", ), t.Param( "IEEE", t.EUI64, "IEEE address of the device to be removed from the network.", ), t.Param("Flags", t.uint8_t, "Leave flags bitfield",), ), rsp_schema=t.STATUS_SCHEMA, ) PermitJoin = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_PERMIT_JOINING_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "DestNWK", t.NWK, "NWK address of the remote device to send the request to", ), t.Param( "PermitDuration", t.uint8_t, "The length of time in seconds during which the ZigBee " "coordinator or router will allow associations. The value" " 0x00 and 0xff indicate that permission is disabled or " "enabled, respectively, without a specified time limit", ), t.Param( "TCSignificance", t.uint8_t, "Trust center significance", ), ), rsp_schema=t.STATUS_SCHEMA, ) DevAnnceInd = t.CommandDef( t.ControlType.IND, ZdoCommandCode.ZDO_DEV_ANNCE_IND, rsp_schema=( t.Param("NWK", t.NWK, "Short address of the joined device"), t.Param("IEEE", t.EUI64, "IEEE address of the joined device."), t.Param( "MacCap", t.uint8_t, "MAC Capabilities of the joined device"), ), ) SetNodeDescManCode = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_SET_NODE_DESC_MANUF_CODE, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("ManCode", t.uint16_t, "Manufacturer code to set"), ), rsp_schema=t.STATUS_SCHEMA, ) NodeDescReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_NODE_DESC_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("NwkAddr", t.NWK, "Network address of interest"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("NodeDesc", zdo_t.NodeDescriptor, "Node descriptor"), t.Param("NwkAddr", t.NWK, "Network address of source device"), ), ) ActiveEpReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_ACTIVE_EP_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("NwkAddr", t.NWK, "Network address of interest"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "ActiveEpList", zigpy.types.LVBytes, "Active enpoints list" ), t.Param("NwkAddr", t.NWK, "Network address of source device"), ), ) MatchDescReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_MATCH_DESC_REQ, blocking=False, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("NwkAddr", t.NWK, "Network address of interest"), t.Param("ProfileId", t.uint16_t, "ID of the profile of interest"), t.Param( "InClusterCnt", t.uint8_t, "Count of Input cluster IDs in the following list" ), t.Param( "OutClusterCnt", t.uint8_t, "Count of Output cluster IDs in the following list" ), t.Param( "InClusterList", t.List[t.uint16_t], "Network address of interest" ), t.Param( "OutClusterList", t.List[t.uint16_t], "Network address of interest" ), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "ActiveEpList", zigpy.types.LVBytes, "Active enpoints list" ), t.Param("NwkAddr", t.NWK, "Network address of source device"), ), ) SimpleDescriptorReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_SIMPLE_DESC_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("NwkAddr", t.NWK, "Network address of interest"), t.Param("Endpoint", t.uint8_t, "Endpoint of interest"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("SimpleDesc", t.SimpleDescriptor, "Simple descriptor"), t.Param("NwkAddr", t.NWK, "Network address of source device"), ), ) BindReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_BIND_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "TargetNwkAddr", t.NWK, "NWK address of the remote device to send the request to"), t.Param("SrcIEEE", t.EUI64, "IEEE address of the source device."), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint"), t.Param("ClusterId", t.uint16_t, "Cluster ID to bind"), t.Param("DstAddrMode", t.BindAddrMode, "Destination addr mode"), t.Param( "DstAddr", t.EUI64, "Destination addr depending on dst addr mode. Always 8 bytes." " 2-bytes short address must be put into first 2 bytes" ), t.Param( "DstEndpoint", t.uint8_t, "Destination endpoint number. Shall be set to 0, " "if Destination Address Mode isn't 0x03."), ), rsp_schema=t.STATUS_SCHEMA ) UnbindReq = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_UNBIND_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "TargetNwkAddr", t.NWK, "NWK address of the remote device to send the request to"), t.Param("SrcIEEE", t.EUI64, "IEEE address of the source device."), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint"), t.Param("ClusterId", t.uint16_t, "Cluster ID to unbind"), t.Param("DstAddrMode", t.BindAddrMode, "Destination addr mode"), t.Param( "DstAddr", t.EUI64, "Destination addr depending on dst addr mode. Always 8 bytes." " 2-bytes short address must be put into first 2 bytes" ), t.Param( "DstEndpoint", t.uint8_t, "Destination endpoint number. Shall be set to 0, " "if Destination Address Mode isn't 0x03."), ), rsp_schema=t.STATUS_SCHEMA ) MgmtLqi = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_MGMT_LQI_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "DestNWK", t.NWK, "The address of the device to send a request to" ), t.Param("Index", t.uint8_t, "Start entry index"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("Neighbors", zdo_t.Neighbors, "Neighbors"), ), ) MgmtNwkUpdate = t.CommandDef( t.ControlType.REQ, ZdoCommandCode.ZDO_MGMT_NWK_UPDATE_REQ, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("ScanChannelMask", t.Channels, "Scan channel mask"), t.Param("ScanDuration", t.uint8_t, "Scan duration"), t.Param( "ScanCount", t.uint8_t, "the number of energy scans to be conducted and reported" ), t.Param( "MgrAddr", t.NWK, "the NWK address of the network manager"), t.Param( "DstNWK", t.NWK, "the address of the device to send a request to" ), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("ScannedChannels", t.Channels, ""), t.Param("TotalTransmissions", t.uint16_t, ""), t.Param("TransmissionFailures", t.uint16_t, ""), t.Param("EnergyValues", EnergyValues, ""), ), ) DevUpdateInd = t.CommandDef( t.ControlType.IND, ZdoCommandCode.ZDO_DEV_UPDATE_IND, rsp_schema=( t.Param("IEEE", t.EUI64, "the IEEE address of the joined device"), t.Param("Nwk", t.NWK, "the NWK address of the joined device"), t.Param( "Status", t.DeviceUpdateStatus, "Device Update Status Code"), ), )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/commands/zdo.py
zdo.py
import zigpy_zboss.types as t class AFCommandCode(t.enum_uint16): """Enum class for AF command_ids.""" AF_SET_SIMPLE_DESC = 0x0101 AF_DEL_SIMPLE_DESC = 0x0102 AF_SET_NODE_DESC = 0x0103 AF_SET_POWER_DESC = 0x0104 class AF(t.CommandsBase): """AF commands. This category of the API provides an access to the Application Framework part resided at the NCP. """ SetSimpleDesc = t.CommandDef( t.ControlType.REQ, AFCommandCode.AF_SET_SIMPLE_DESC, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("SimpleDesc", t.SimpleDescriptor, "Simple descriptor"), ), rsp_schema=t.STATUS_SCHEMA, ) DelSimpleDesc = t.CommandDef( t.ControlType.REQ, AFCommandCode.AF_DEL_SIMPLE_DESC, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "Endpoint", t.uint8_t, "Endpoint number to delete simple descriptor for" ), ), rsp_schema=t.STATUS_SCHEMA, ) SetNodeDesc = t.CommandDef( t.ControlType.REQ, AFCommandCode.AF_SET_NODE_DESC, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param( "DeviceType", t.DeviceRole, "Device type: 0 - ZC, 1 - ZR, 2 - ZED" ), t.Param("MACCap", t.MACCapability, "MAC Capabilities bitfield"), t.Param("ManufacturerCode", t.uint16_t, "Manufacturer code"), ), rsp_schema=t.STATUS_SCHEMA, ) SetPowerDesc = t.CommandDef( t.ControlType.REQ, AFCommandCode.AF_SET_POWER_DESC, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("CurrentMode", t.PowerMode, "Current power mode value"), t.Param( "AvailablePowerSrc", t.PowerSource, "Available power sources bits" ), t.Param( "CurrentPowerSrc", t.PowerSource, "Current power source bit"), t.Param( "CurrentPowerSrcLevel", t.PowerSourceLevel, "Current power source level value" ), ), rsp_schema=t.STATUS_SCHEMA, )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/commands/af.py
af.py
import zigpy.types import zigpy_zboss.types as t class APSCommandCode(t.enum_uint16): """Enum class for APS command_ids.""" APSDE_DATA_REQ = 0x0301 APSME_BIND = 0x0302 APSME_UNBIND = 0x0303 APSME_ADD_GROUP = 0x0304 APSME_RM_GROUP = 0x0305 APSDE_DATA_IND = 0x0306 APSME_RM_ALL_GROUPS = 0x0307 APS_CHECK_BINDING = 0x0308 APS_GET_GROUP_TABLE = 0x0309 APSME_UNBIND_ALL = 0x030a class KeySrcAndAttr(t.enum_flag_uint8): """Enum class for key source.""" KeySrc = 1 << 0 KeyUsed = 3 << 1 class TransmitOptions(t.enum_flag_uint8): """Enum class for transmit options.""" NONE = 0x00 # Security enabled transmission SECURITY_ENABLED = 0x01 # Obsolete OBSOLETE = 0x02 # Acknowledged transmission ACK_ENABLED = 0x04 # Fragmentation permitted FRAGMENTATION_PERMITED = 0x08 # Include extended nonce in APS security frame. EXTENDED_NONCE_ENABLED = 0x10 # Force mesh route discovery for this request. FORCE_ROUTE_DISCOVERY = 0x20 # Send route record for this request. SEND_ROUTE_RECORD = 0x40 class APS(t.CommandsBase): """APS layer commands. This category of the API provides an access to the Application Support Sub-layer at the NCP """ DataReq = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSDE_DATA_REQ, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number",), t.Param( "ParamLength", t.uint8_t, "Length of parameters section (fixed as 21 bytes)" ), t.Param("DataLength", t.uint16_t, "Data section length"), t.Param( "DstAddr", t.EUI64, "Destination addr depending on dst addr mode. Always 8 bytes." " 2-bytes short address must be put into first 2 bytes" ), t.Param("ProfileID", t.uint16_t, "Profile ID"), t.Param("ClusterId", t.uint16_t, "Cluster ID"), t.Param("DstEndpoint", t.uint8_t, "Destination endpoint"), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint"), t.Param("Radius", t.uint8_t, "Radius in hops"), t.Param( "DstAddrMode", zigpy.types.AddrMode, "Destination addr mode"), t.Param("TxOptions", TransmitOptions, "Tx Options bitmap"), t.Param( "UseAlias", t.uint8_t, "0 or 1. If 1, use alias src address, else local short address" ), t.Param( "AliasSrcAddr", t.uint16_t, "Alias source address. Ignored if use alias 0" ), t.Param( "AliasSeqNbr", t.uint8_t, "Alias sequence number. Ignored if use alias 0" ), t.Param("Payload", t.Payload, "data bytes array"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "DstAddr", t.EUI64, "Destination addr depending on dst addr mode. Always 8 bytes." " 2-bytes short address must be put into first 2 bytes" ), t.Param("DstEndpoint", t.uint8_t, "Destination endpoint"), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint"), t.Param("TxTime", t.uint32_t, "Transmit timestamp, ms"), t.Param( "DstAddrMode", zigpy.types.AddrMode, "Destination addr mode"), ), ) Bind = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSME_BIND, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number",), t.Param("SrcIEEE", t.EUI64, "IEEE address of the source device."), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint number"), t.Param("ClusterId", t.uint16_t, "Cluster ID to bind"), t.Param("DstAddrMode", t.BindAddrMode, "Destination Addr Mode"), t.Param( "DstAddr", t.EUI64, "IEEE or NWK address of the destination device depending " "on address mode specified" ), t.Param("DstEndpoint", t.uint8_t, "Destination endpoint number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("Idx", t.uint8_t, "Index of bind table entry"), ), ) UnBind = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSME_UNBIND, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number",), t.Param("SrcIEEE", t.EUI64, "IEEE address of the source device."), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint number"), t.Param("ClusterId", t.uint16_t, "Cluster ID to bind"), t.Param("DstAddrMode", t.BindAddrMode, "Destination Addr Mode"), t.Param( "DstAddr", t.EUI64, "IEEE or NWK address of the destination device depending " "on address mode specified" ), t.Param("DstEndpoint", t.uint8_t, "Destination endpoint number"), ), rsp_schema=t.STATUS_SCHEMA ) AddGroup = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSME_ADD_GROUP, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number",), t.Param("GroupNWKAddr", t.NWK, "NWK address of the group"), t.Param("Endpoint", t.uint8_t, "Endpoint number"), ), rsp_schema=t.STATUS_SCHEMA, ) RemoveGroup = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSME_RM_GROUP, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number",), t.Param("GroupNWKAddr", t.NWK, "NWK address of the group"), t.Param("Endpoint", t.uint8_t, "Endpoint number"), ), rsp_schema=t.STATUS_SCHEMA, ) DataIndication = t.CommandDef( t.ControlType.IND, APSCommandCode.APSDE_DATA_IND, rsp_schema=( t.Param( "ParamLength", t.uint8_t, "Length of parameters section (fixed as 21 bytes)" ), t.Param("PayloadLength", t.uint16_t, "Length of data"), t.Param("FrameFC", t.APSFrameFC, "Received APS frame FC field"), t.Param("SrcAddr", t.NWK, "Received frame source NWK address"), t.Param( "DstAddr", t.NWK, "Received frame destination NWK address"), t.Param( "GrpAddr", t.NWK, "Received frame APS group address " "(if frame is marked as Group addressed in FC)" ), t.Param("DstEndpoint", t.uint8_t, "Destination endpoint"), t.Param("SrcEndpoint", t.uint8_t, "Source endpoint"), t.Param("ClusterId", t.uint16_t, "Cluster ID"), t.Param("ProfileId", t.uint16_t, "Profile ID"), t.Param("PacketCounter", t.uint8_t, "APS packet counter"), t.Param( "SrcMACAddr", t.NWK, "Received frame last hop source MAC address" ), t.Param( "DstMACAddr", t.NWK, "Received frame last hop destination MAC address" ), t.Param("LQI", t.uint8_t, "Received frame LQI"), t.Param("RSSI", t.uint8_t, "Received frame RSSI"), t.Param( "KeySrcAndAttr", t.ApsAttributes, "Aps Key source and APS key used bitmap" ), t.Param("Payload", t.Payload, "data bytes array"), ), ) RmAllGroups = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSME_RM_ALL_GROUPS, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("Endpoint", t.uint8_t, "Endpoint Number"), ), rsp_schema=t.STATUS_SCHEMA, ) CheckBinding = t.CommandDef( t.ControlType.REQ, APSCommandCode.APS_CHECK_BINDING, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), t.Param("Endpoint", t.uint8_t, "Endpoint Number"), t.Param("ClusterId", t.uint16_t, "Cluster ID"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param( "Exists", t.uint8_t, "flag indicating whether a binding exists" ), ), ) GetGroupTable = t.CommandDef( t.ControlType.REQ, APSCommandCode.APS_GET_GROUP_TABLE, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA + ( t.Param("GrpList", t.GrpList, "group list"), ), ) UnbindAll = t.CommandDef( t.ControlType.REQ, APSCommandCode.APSME_UNBIND_ALL, blocking=True, req_schema=( t.Param("TSN", t.uint8_t, "Transmission Sequence Number"), ), rsp_schema=t.STATUS_SCHEMA )
zigpy-zboss
/zigpy-zboss-1.1.0.tar.gz/zigpy-zboss-1.1.0/zigpy_zboss/commands/aps.py
aps.py
# zigpy-zigate ![Build & Tests](https://github.com/zigpy/zigpy-zigate/workflows/Build%20&%20Tests/badge.svg?branch=master) [![Coverage](https://coveralls.io/repos/github/zigpy/zigpy-zigate/badge.svg?branch=master)](https://coveralls.io/github/zigpy/zigpy-zigate?branch=master) [zigpy-zigate](https://github.com/zigpy/zigpy-zigate) is a Python 3 implementation for the [Zigpy](https://github.com/zigpy/) project to implement [ZiGate](https://www.zigate.fr/) based [Zigbee](https://www.zigbee.org) radio devices. - https://github.com/zigpy/zigpy-zigate ZiGate is a open source ZigBee adapter hardware that was initially launched on Kickstarter by @fairecasoimeme - https://www.zigate.fr - https://www.kickstarter.com/projects/1361563794/zigate-universal-zigbee-gateway-for-smarthome ## Hardware and firmware compatibility The ZiGate USB adapter communicates via a PL-2303HX USB to Serial Bridge Controller module by Prolific. There's also a Wi-Fi adapter to communicate with ZiGate over network. Note! ZiGate open source ZigBee USB and GPIO adapter hardware requires ZiGate 3.1a firmware or later to work with this zigpy-zigate module, however ZiGate 3.1d firmware or later is recommended as it contains a specific bug-fix related to zigpy. See all available official ZiGate firmware releases [here (link)](https://github.com/fairecasoimeme/ZiGate/releases). ### Known working ZiGate compatible Zigbee radio modules - [ZiGate + USB / ZiGate USB-TTL](https://zigate.fr/produit/zigate-USB/) - [ZiGate + USB-DIN / ZiGate USB-DIN](https://zigate.fr/produit/zigatev2-usb-din/) - [PiZiGate + / PiZiGate (ZiGate HAT/Shield module for Raspberry Pi compatible GPIO header)](https://zigate.fr/produit/pizigatev2/) - Tip! PiZiGate are not limited to Raspberry Pi series as works with all computers with a Raspberry Pi compatible GPIO header. - [ZiGate Ethernet (ZiGate Ethernet serial-to-IP server)](https://zigate.fr/produit/zigate-ethernet/) (Note! Requires the [PiZiGate + radio module](https://zigate.fr/produit/pizigatev2/)) - Tip! [ZiGate Ethernet](https://zigate.fr/produit/zigate-ethernet/) can as alternativly also be used via [ESPHome serial bridge firmware for ESP32](https://github.com/thegroove/esphome-zbbridge/) as an option. - [ZiGate + WiFi Pack / ZiGate WiFi Pack (ZiGate WiFi serial-to-IP server)](https://zigate.fr/produit/zigatev2-pack-wifi/) - Tip! [ZiGate compatible WiFi module](https://zigate.fr/produit/module-wifi-v1-3-compatible-zigate/) can also be used to convert radio board from [ZiGate USB-TTL](https://zigate.fr/produit/zigate-ttl/) into this "ZiGate WiFi Pack". ### Experimental ZiGate compatible Zigbee radio modules - [Open Lumi Gateway](https://github.com/openlumi) - [DIY ZiGate WiFi bridge hacked from an Xiaomi Lumi Gateway with modded OpenWRT firmware](https://github.com/zigpy/zigpy-zigate/issues/59) ## Port configuration - To configure __usb__ ZiGate (USB TTL or DIN) port, just specify the port, example : `/dev/ttyUSB0` - Alternatively you could manually set port to `auto` to enable automatic usb port discovery - To configure __pizigate__ port, specify the port, example : `/dev/serial0` or `/dev/ttyAMA0` - To configure __wifi__ ZiGate, manually specify IP address and port, example : `socket://192.168.1.10:9999` __pizigate__ does require some additional adjustements on Raspberry Pi 3/Zero, and 4: - [Raspberry Pi 3 and Raspberry Pi Zero configuration adjustements](https://zigate.fr/documentation/compatibilite-raspberry-pi-3-et-zero-w/) - [Raspberry Pi 4 configuration adjustements](https://zigate.fr/documentation/compatibilite-raspberry-pi-4-b/) ## Flasher (ZiGate Firmware Tool) zigpy-zigate has an integrated Python "flasher" tool to flash firmware updates on your ZiGate (NXP Jennic JN5168). Thanks to Sander Hoentjen (tjikkun) zigpy-zigate now has an integrated firmware flasher tool! - [tjikkun original zigate-flasher repo](https://github.com/tjikkun/zigate-flasher) See all available official ZiGate firmware releases [here (link)](https://github.com/fairecasoimeme/ZiGate/releases). ### Flasher Usage ```bash usage: python3 -m zigpy_zigate.tools.flasher [-h] -p {/dev/ttyUSB0} [-w WRITE] [-s SAVE] [-u] [-d] [--gpio] [--din] optional arguments: -h, --help show this help message and exit -p {/dev/ttyUSB0}, --serialport {/dev/ttyUSB0} Serial port, e.g. /dev/ttyUSB0 -w WRITE, --write WRITE Firmware bin to flash onto the chip -s SAVE, --save SAVE File to save the currently loaded firmware to -u, --upgrade Download and flash the lastest available firmware -d, --debug Set log level to DEBUG --gpio Configure GPIO for PiZiGate flash --din Configure USB for ZiGate DIN flash ``` ## Testing new releases Testing a new release of the zigpy-zigate library before it is released in Home Assistant. If you are using Supervised Home Assistant (formerly known as the Hassio/Hass.io distro): - Add https://github.com/home-assistant/hassio-addons-development as "add-on" repository - Install "Custom deps deployment" addon - Update config like: ``` pypi: - zigpy-zigate==0.5.1 apk: [] ``` where 0.5.1 is the new version - Start the addon If you are instead using some custom python installation of Home Assistant then do this: - Activate your python virtual env - Update package with ``pip`` ``` pip install zigpy-zigate==0.5.1 ## Releases via PyPI Tagged versions are also released via PyPI - https://pypi.org/project/zigpy-zigate/ - https://pypi.org/project/zigpy-zigate/#history - https://pypi.org/project/zigpy-zigate/#files ## Developer references Documents that layout the serial protocol used for ZiGate serial interface communication can be found here: - https://github.com/fairecasoimeme/ZiGate/tree/master/Protocol - https://github.com/doudz/zigate - https://github.com/Neonox31/zigate - https://github.com/nouknouk/node-zigate ## How to contribute If you are looking to make a contribution to this project we suggest that you follow the steps in these guides: - https://github.com/firstcontributions/first-contributions/blob/master/README.md - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md Some developers might also be interested in receiving donations in the form of hardware such as Zigbee modules or devices, and even if such donations are most often donated with no strings attached it could in many cases help the developers motivation and indirect improve the development of this project. ## Related projects #### Zigpy [Zigpy](https://github.com/zigpy/zigpy) is [Zigbee protocol stack](https://en.wikipedia.org/wiki/Zigbee) integration project to implement the [Zigbee Home Automation](https://www.zigbee.org/) standard as a Python 3 library. Zigbee Home Automation integration with zigpy allows you to connect one of many off-the-shelf Zigbee adapters using one of the available Zigbee radio library modules compatible with zigpy to control Zigbee based devices. There is currently support for controlling Zigbee device types such as binary sensors (e.g., motion and door sensors), sensors (e.g., temperature sensors), lightbulbs, switches, and fans. A working implementation of zigbe exist in [Home Assistant](https://www.home-assistant.io) (Python based open source home automation software) as part of its [ZHA component](https://www.home-assistant.io/components/zha/) #### ZHA Device Handlers ZHA deviation handling in Home Assistant relies on the third-party [ZHA Device Handlers](https://github.com/zigpy/zha-device-handlers) project. Zigbee devices that deviate from or do not fully conform to the standard specifications set by the [Zigbee Alliance](https://www.zigbee.org) may require the development of custom [ZHA Device Handlers](https://github.com/zigpy/zha-device-handlers) (ZHA custom quirks handler implementation) to for all their functions to work properly with the ZHA component in Home Assistant. These ZHA Device Handlers for Home Assistant can thus be used to parse custom messages to and from non-compliant Zigbee devices. The custom quirks implementations for zigpy implemented as ZHA Device Handlers for Home Assistant are a similar concept to that of [Hub-connected Device Handlers for the SmartThings platform](https://docs.smartthings.com/en/latest/device-type-developers-guide/) as well as that of [zigbee-herdsman converters as used by Zigbee2mqtt](https://www.zigbee2mqtt.io/how_tos/how_to_support_new_devices.html), meaning they are each virtual representations of a physical device that expose additional functionality that is not provided out-of-the-box by the existing integration between these platforms. #### ZHA integration component for Home Assistant [ZHA integration component for Home Assistant](https://www.home-assistant.io/integrations/zha/) is a reference implementation of the zigpy library as integrated into the core of [Home Assistant](https://www.home-assistant.io) (a Python based open source home automation software). There are also other GUI and non-GUI projects for Home Assistant's ZHA components which builds on or depends on its features and functions to enhance or improve its user-experience, some of those are listed and linked below. #### ZHA Custom Radios [zha-custom-radios](https://github.com/zha-ng/zha-custom-radios) adds support for custom radio modules for zigpy to [[Home Assistant's ZHA (Zigbee Home Automation) integration component]](https://www.home-assistant.io/integrations/zha/). This custom component for Home Assistant allows users to test out new modules for zigpy in Home Assistant's ZHA integration component before they are integrated into zigpy ZHA and also helps developers new zigpy radio modules without having to modify the Home Assistant's source code. #### ZHA Custom [zha_custom](https://github.com/Adminiuga/zha_custom) is a custom component package for Home Assistant (with its ZHA component for zigpy integration) that acts as zigpy commands service wrapper, when installed it allows you to enter custom commands via to zigy to example change advanced configuration and settings that are not available in the UI. #### ZHA Map [zha-map](https://github.com/zha-ng/zha-map) for Home Assistant's ZHA component can build a Zigbee network topology map. #### ZHA Network Visualization Card [zha-network-visualization-card](https://github.com/dmulcahey/zha-network-visualization-card) is a custom Lovelace element for Home Assistant which visualize the Zigbee network for the ZHA component. #### ZHA Network Card [zha-network-card](https://github.com/dmulcahey/zha-network-card) is a custom Lovelace card for Home Assistant that displays ZHA component Zigbee network and device information in Home Assistant #### Zigzag [Zigzag](https://github.com/Samantha-uk/zigzag) is an custom card/panel for [Home Assistant](https://www.home-assistant.io/) that displays a graphical layout of Zigbee devices and the connections between them. Zigzag can be installed as a panel or a custom card and relies on the data provided by the [zha-map](https://github.com/zha-ng/zha-map) integration commponent. #### ZHA Device Exporter [zha-device-exporter](https://github.com/dmulcahey/zha-device-exporter) is a custom component for Home Assistant to allow the ZHA component to export lists of Zigbee devices.
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/README.md
README.md
import re import time import os.path import serial.tools.list_ports import serial import logging import asyncio from gpiozero import OutputDevice LOGGER = logging.getLogger(__name__) GPIO_PIN0 = 17 GPIO_PIN2 = 27 class UnclosableOutputDevice(OutputDevice): """ `OutputDevice` that never closes its pins. Allows for the last-written pin state to be retained even after the `OutputDevice` is garbage collected. """ def __init__( self, pin=None, *, active_high=True, initial_value=False, pin_factory=None ): super().__init__( pin, active_high=active_high, initial_value=initial_value, pin_factory=pin_factory, ) self._pin.close = lambda *args, **kwargs: None self.pin_factory.close = lambda *args, **kwargs: None def discover_port(): """ discover zigate port """ devices = list(serial.tools.list_ports.grep('ZiGate')) if devices: port = devices[0].device LOGGER.info('ZiGate found at %s', port) else: devices = list(serial.tools.list_ports.grep('067b:2303|CP2102')) if devices: port = devices[0].device LOGGER.info('ZiGate probably found at %s', port) else: LOGGER.error('Unable to find ZiGate using auto mode') raise serial.SerialException("Unable to find Zigate using auto mode") return port def is_pizigate(port): """ detect pizigate """ # Suppose pizigate on /dev/ttyAMAx or /dev/serialx if port.startswith('pizigate:'): return True port = os.path.realpath(port) return re.match(r"/dev/(tty(S|AMA)|serial)\d+", port) is not None def is_zigate_din(port): """ detect zigate din """ port = os.path.realpath(port) if re.match(r"/dev/ttyUSB\d+", port): try: device = next(serial.tools.list_ports.grep(port)) # Suppose zigate din /dev/ttyUSBx return device.description == 'ZiGate' and device.manufacturer == 'FTDI' except StopIteration: pass return False def is_zigate_wifi(port): """ detect zigate din """ return port.startswith('socket://') def set_pizigate_running_mode(): LOGGER.info('Put PiZiGate in running mode') gpio0 = UnclosableOutputDevice(pin=GPIO_PIN0, initial_value=None) gpio2 = UnclosableOutputDevice(pin=GPIO_PIN2, initial_value=None) gpio2.on() time.sleep(0.5) gpio0.off() time.sleep(0.5) gpio0.on() time.sleep(0.5) def set_pizigate_flashing_mode(): LOGGER.info('Put PiZiGate in flashing mode') gpio0 = UnclosableOutputDevice(pin=GPIO_PIN0, initial_value=None) gpio2 = UnclosableOutputDevice(pin=GPIO_PIN2, initial_value=None) gpio2.off() time.sleep(0.5) gpio0.off() time.sleep(0.5) gpio0.on() time.sleep(0.5) def ftdi_set_bitmode(dev, bitmask): ''' Set mode for ZiGate DIN module ''' import usb BITMODE_CBUS = 0x20 SIO_SET_BITMODE_REQUEST = 0x0b bmRequestType = usb.util.build_request_type(usb.util.CTRL_OUT, usb.util.CTRL_TYPE_VENDOR, usb.util.CTRL_RECIPIENT_DEVICE) wValue = bitmask | (BITMODE_CBUS << BITMODE_CBUS) dev.ctrl_transfer(bmRequestType, SIO_SET_BITMODE_REQUEST, wValue) def set_zigatedin_running_mode(): import usb dev = usb.core.find(idVendor=0x0403, idProduct=0x6001) if not dev: raise RuntimeError('ZiGate DIN not found.') LOGGER.info('Put ZiGate DIN in running mode') ftdi_set_bitmode(dev, 0xC8) time.sleep(0.5) ftdi_set_bitmode(dev, 0xCC) time.sleep(0.5) def set_zigatedin_flashing_mode(): import usb dev = usb.core.find(idVendor=0x0403, idProduct=0x6001) if not dev: raise RuntimeError('ZiGate DIN not found.') LOGGER.info('Put ZiGate DIN in flashing mode') ftdi_set_bitmode(dev, 0x00) time.sleep(0.5) ftdi_set_bitmode(dev, 0xCC) time.sleep(0.5) ftdi_set_bitmode(dev, 0xC0) time.sleep(0.5) ftdi_set_bitmode(dev, 0xC4) time.sleep(0.5) ftdi_set_bitmode(dev, 0xCC) time.sleep(0.5) def async_run_in_executor(function): """Decorator to make a sync function async.""" async def replacement(*args): return asyncio.get_running_loop().run_in_executor(None, function, *args) replacement._sync_func = function return replacement # Create async version of all of the above functions async_set_pizigate_running_mode = async_run_in_executor(set_pizigate_running_mode) async_set_pizigate_flashing_mode = async_run_in_executor(set_pizigate_flashing_mode) async_set_zigatedin_running_mode = async_run_in_executor(set_zigatedin_running_mode) async_set_zigatedin_flashing_mode = async_run_in_executor(set_zigatedin_flashing_mode)
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/common.py
common.py
import enum import zigpy.types def deserialize(data, schema): result = [] for type_ in schema: # value, data = type_.deserialize(data) if data: value, data = type_.deserialize(data) else: value = None result.append(value) return result, data def serialize(data, schema): return b''.join(t(v).serialize() for t, v in zip(schema, data)) class Bytes(bytes): def serialize(self): return self @classmethod def deserialize(cls, data): return cls(data), b'' class LBytes(bytes): def serialize(self): return uint8_t(len(self)).serialize() + self @classmethod def deserialize(cls, data, byteorder='big'): _bytes = int.from_bytes(data[:1], byteorder) s = data[1:_bytes + 1] return s, data[_bytes + 1:] class int_t(int): _signed = True _size = 0 def serialize(self, byteorder='big'): return self.to_bytes(self._size, byteorder, signed=self._signed) @classmethod def deserialize(cls, data, byteorder='big'): # Work around https://bugs.python.org/issue23640 r = cls(int.from_bytes(data[:cls._size], byteorder, signed=cls._signed)) data = data[cls._size:] return r, data class int8s(int_t): _size = 1 class int16s(int_t): _size = 2 class int24s(int_t): _size = 3 class int32s(int_t): _size = 4 class int40s(int_t): _size = 5 class int48s(int_t): _size = 6 class int56s(int_t): _size = 7 class int64s(int_t): _size = 8 class uint_t(int_t): _signed = False class uint8_t(uint_t): _size = 1 class uint16_t(uint_t): _size = 2 class uint24_t(uint_t): _size = 3 class uint32_t(uint_t): _size = 4 class uint40_t(uint_t): _size = 5 class uint48_t(uint_t): _size = 6 class uint56_t(uint_t): _size = 7 class uint64_t(uint_t): _size = 8 class EUI64(zigpy.types.EUI64): @classmethod def deserialize(cls, data): r, data = super().deserialize(data) return cls(r[::-1]), data def serialize(self): assert self._length == len(self) return super().serialize()[::-1] class NWK(uint16_t): def __repr__(self): return "0x{:04x}".format(self) def __str__(self): return "0x{:04x}".format(self) class AddressMode(uint8_t, enum.Enum): # Address modes used in zigate protocol BOUND = 0x00 GROUP = 0x01 NWK = 0x02 IEEE = 0x03 BROADCAST = 0x04 NO_TRANSMIT = 0x05 BOUND_NO_ACK = 0x06 NWK_NO_ACK = 0x07 IEEE_NO_ACK = 0x08 BOUND_NON_BLOCKING = 0x09 BOUND_NON_BLOCKING_NO_ACK = 0x0A class Status(uint8_t, enum.Enum): Success = 0x00 IncorrectParams = 0x01 UnhandledCommand = 0x02 CommandFailed = 0x03 Busy = 0x04 StackAlreadyStarted = 0x05 # Errors below are due to resource shortage, retrying may succeed OR There are no # free Network PDUs. The number of NPDUs is set in the “Number of NPDUs” property # of the “PDU Manager” section of the config editor ResourceShortage = 0x80 # There are no free Application PDUs. The number of APDUs is set in the “Instances” # property of the appropriate “APDU” child of the “PDU Manager” section of the # config editor NoFreeAppPDUs = 0x81 # There are no free simultaneous data request handles. The number of handles is set # in the “Maximum Number of Simultaneous Data Requests” field of the “APS layer # configuration” section of the config editor NoFreeDataReqHandles = 0x82 # There are no free APS acknowledgement handles. The number of handles is set in # the “Maximum Number of Simultaneous Data Requests with Acks” field of the “APS # layer configuration” section of the config editor NoFreeAPSAckHandles = 0x83 # There are no free fragment record handles. The number of handles is set in # the “Maximum Number of Transmitted Simultaneous Fragmented Messages” field of # the “APS layer configuration” section of the config editor NoFreeFragRecHandles = 0x84 # There are no free MCPS request descriptors. There are 8 MCPS request descriptors. # These are only ever likely to be exhausted under very heavy network load or when # trying to transmit too many frames too close together. NoFreeMCPSReqDesc = 0x85 # The loop back send is currently busy. There can be only one loopback request at a # time. LoopbackSendBusy = 0x86 # There are no free entries in the extended address table. The extended address # table is configured in the config editor NoFreeExtAddrTableEntries = 0x87 # The simple descriptor does not exist for this endpoint / cluster. SimpleDescDoesNotExist = 0x88 # A bad parameter has been found while processing an APSDE request or response BadAPSDEParam = 0x89 # No free Routing table entries left NoFreeRoutingTableEntries = 0x8A # No free BTR entries left. NoFreeBTREntries = 0x8B # A transmit request failed since the ASDU is too large and fragmentation is not # supported. AsduTooLong = 0xA0 # A received fragmented frame could not be defragmented at the current time. DefragDeferred = 0xA1 # A received fragmented frame could not be defragmented since the device does not # support fragmentation. DefragUnsupported = 0xA2 # A parameter value was out of range. IllegalRequest = 0xA3 # An APSME-UNBIND.request failed due to the requested binding link not existing in # the binding table. InvalidBinding = 0xA4 # An APSME-REMOVE-GROUP.request has been issued with a group identifier that does # not appear in the group table. InvalidGroup = 0xA5 # A parameter value was invalid or out of range. InvalidParameter = 0xA6 # An APSDE-DATA.request requesting acknowledged transmission failed due to no # acknowledgement being received. NoAck = 0xA7 # An APSDE-DATA.request with a destination addressing mode set to 0x00 failed due to # there being no devices bound to this device. NoBoundDevice = 0xA8 # An APSDE-DATA.request with a destination addressing mode set to 0x03 failed due to # no corresponding short address found in the address map table. NoShortAddress = 0xA9 # An APSDE-DATA.request with a destination addressing mode set to 0x00 failed due to # a binding table not being supported on the device. NotSupported = 0xAA # An ASDU was received that was secured using a link key. SecuredLinkKey = 0xAB # An ASDU was received that was secured using a network key. SecuredNwkKey = 0xAC # An APSDE-DATA.request requesting security has resulted in an error during the # corresponding security processing. SecurityFail = 0xAD # An APSME-BIND.request or APSME.ADDGROUP.request issued when the binding or group # tables, respectively, were full. TableFull = 0xAE # An ASDU was received without any security. Unsecured = 0xAF # An APSME-GET.request or APSMESET. request has been issued with an unknown # attribute identifier. UnsupportedAttribute = 0xB0 @classmethod def _missing_(cls, value): if not isinstance(value, int): raise ValueError(f"{value} is not a valid {cls.__name__}") new_member = cls._member_type_.__new__(cls, value) new_member._name_ = f"unknown_0x{value:02X}" new_member._value_ = cls._member_type_(value) return new_member class LogLevel(uint8_t, enum.Enum): Emergency = 0 Alert = 1 Critical = 2 Error = 3 Warning = 4 Notice = 5 Information = 6 Debug = 7 class Struct: _fields = [] def __init__(self, *args, **kwargs): if len(args) == 1 and isinstance(args[0], self.__class__): # copy constructor for field in self._fields: if hasattr(args[0], field[0]): setattr(self, field[0], getattr(args[0], field[0])) elif len(args) == len(self._fields): for arg, field in zip(args, self._fields): setattr(self, field[0], field[1](arg)) elif kwargs: for k, v in kwargs.items(): setattr(self, k, v) def serialize(self): r = b'' for field in self._fields: if hasattr(self, field[0]): r += getattr(self, field[0]).serialize() return r @classmethod def deserialize(cls, data): r = cls() for field_name, field_type in cls._fields: v, data = field_type.deserialize(data) setattr(r, field_name, v) return r, data def __repr__(self): r = '<%s ' % (self.__class__.__name__, ) r += ' '.join( ['%s=%s' % (f[0], getattr(self, f[0], None)) for f in self._fields] ) r += '>' return r ZIGPY_TO_ZIGATE_ADDR_MODE = { # With ACKs (zigpy.types.AddrMode.NWK, True): AddressMode.NWK, (zigpy.types.AddrMode.IEEE, True): AddressMode.IEEE, (zigpy.types.AddrMode.Broadcast, True): AddressMode.BROADCAST, (zigpy.types.AddrMode.Group, True): AddressMode.GROUP, # Without ACKs (zigpy.types.AddrMode.NWK, False): AddressMode.NWK_NO_ACK, (zigpy.types.AddrMode.IEEE, False): AddressMode.IEEE_NO_ACK, (zigpy.types.AddrMode.Broadcast, False): AddressMode.BROADCAST, (zigpy.types.AddrMode.Group, False): AddressMode.GROUP, } ZIGATE_TO_ZIGPY_ADDR_MODE = { zigate_addr: (zigpy_addr, ack) for (zigpy_addr, ack), zigate_addr in ZIGPY_TO_ZIGATE_ADDR_MODE.items() } class Address(Struct): _fields = [ ('address_mode', AddressMode), ('address', EUI64), ] def __eq__(self, other): return other.address_mode == self.address_mode and other.address == self.address @classmethod def deserialize(cls, data): r = cls() r.address_mode, data = AddressMode.deserialize(data) if r.address_mode in (AddressMode.IEEE, AddressMode.IEEE_NO_ACK): r.address, data = EUI64.deserialize(data) else: r.address, data = NWK.deserialize(data) return r, data def to_zigpy_type(self): zigpy_addr_mode, ack = ZIGATE_TO_ZIGPY_ADDR_MODE[self.address_mode] return ( zigpy.types.AddrModeAddress(addr_mode=zigpy_addr_mode, address=self.address), ack, ) class DeviceEntry(Struct): _fields = [ ("id", uint8_t), ("short_addr", NWK), ("ieee_addr", EUI64), ("power_source", uint8_t), ("link_quality", uint8_t), ] class DeviceEntryArray(tuple): @classmethod def deserialize(cls, data): if len(data) % 13 != 0: raise ValueError("Data is not an array of DeviceEntry") entries = [] while data: entry, data = DeviceEntry.deserialize(data) entries.append(entry) return cls(entries), data def serialize(self): return b"".join([e.serialize() for e in self])
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/types.py
types.py
import asyncio import binascii import logging import struct from typing import Any, Dict import zigpy.serial from .config import CONF_DEVICE_PATH from . import common as c LOGGER = logging.getLogger(__name__) ZIGATE_BAUDRATE = 115200 class Gateway(asyncio.Protocol): START = b'\x01' END = b'\x03' def __init__(self, api, connected_future=None): self._buffer = b'' self._connected_future = connected_future self._api = api def connection_lost(self, exc) -> None: """Port was closed expecteddly or unexpectedly.""" if self._connected_future and not self._connected_future.done(): if exc is None: self._connected_future.set_result(True) else: self._connected_future.set_exception(exc) if exc is None: LOGGER.debug("Closed serial connection") return LOGGER.error("Lost serial connection: %s", exc) self._api.connection_lost(exc) def connection_made(self, transport): """Callback when the uart is connected""" LOGGER.debug("Connection made") self._transport = transport if self._connected_future: self._connected_future.set_result(True) def close(self): if self._transport: self._transport.close() def send(self, cmd, data=b''): """Send data, taking care of escaping and framing""" LOGGER.debug("Send: 0x%04x %s", cmd, binascii.hexlify(data)) length = len(data) byte_head = struct.pack('!HH', cmd, length) checksum = self._checksum(byte_head, data) frame = struct.pack('!HHB%ds' % length, cmd, length, checksum, data) LOGGER.debug('Frame to send: %s', frame) frame = self._escape(frame) LOGGER.debug('Frame escaped: %s', frame) self._transport.write(self.START + frame + self.END) def data_received(self, data): """Callback when there is data received from the uart""" self._buffer += data # LOGGER.debug('data_received %s', self._buffer) endpos = self._buffer.find(self.END) while endpos != -1: startpos = self._buffer.rfind(self.START, 0, endpos) if startpos != -1 and startpos < endpos: frame = self._buffer[startpos:endpos + 1] frame = self._unescape(frame[1:-1]) cmd, length, checksum, f_data, lqi = struct.unpack('!HHB%dsB' % (len(frame) - 6), frame) if self._length(frame) != length: LOGGER.warning("Invalid length: %s, data: %s", length, len(frame) - 6) self._buffer = self._buffer[endpos + 1:] endpos = self._buffer.find(self.END) continue if self._checksum(frame[:4], lqi, f_data) != checksum: LOGGER.warning("Invalid checksum: %s, data: 0x%s", checksum, binascii.hexlify(frame).decode()) self._buffer = self._buffer[endpos + 1:] endpos = self._buffer.find(self.END) continue LOGGER.debug("Frame received: %s", binascii.hexlify(frame).decode()) self._api.data_received(cmd, f_data, lqi) else: LOGGER.warning('Malformed packet received, ignore it') self._buffer = self._buffer[endpos + 1:] endpos = self._buffer.find(self.END) def _unescape(self, data): flip = False ret = [] for b in data: if flip: flip = False ret.append(b ^ 0x10) elif b == 0x02: flip = True else: ret.append(b) return bytes(ret) def _escape(self, data): ret = [] for b in data: if b < 0x10: ret.extend([0x02, 0x10 ^ b]) else: ret.append(b) return bytes(ret) def _checksum(self, *args): chcksum = 0 for arg in args: if isinstance(arg, int): chcksum ^= arg continue for x in arg: chcksum ^= x return chcksum def _length(self, frame): length = len(frame) - 5 return length async def connect(device_config: Dict[str, Any], api, loop=None): if loop is None: loop = asyncio.get_event_loop() connected_future = asyncio.Future() protocol = Gateway(api, connected_future) port = device_config[CONF_DEVICE_PATH] if port == 'auto': port = c.discover_port() if c.is_pizigate(port): LOGGER.debug('PiZiGate detected') await c.async_set_pizigate_running_mode() # in case of pizigate:/dev/ttyAMA0 syntax if port.startswith('pizigate:'): port = port.replace('pizigate:', '', 1) elif c.is_zigate_din(port): LOGGER.debug('ZiGate USB DIN detected') await c.async_set_zigatedin_running_mode() elif c.is_zigate_wifi(port): LOGGER.debug('ZiGate WiFi detected') _, protocol = await zigpy.serial.create_serial_connection( loop, lambda: protocol, url=port, baudrate=ZIGATE_BAUDRATE, xonxoff=False, ) await connected_future return protocol
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/uart.py
uart.py
import asyncio import binascii import functools import logging import enum import datetime from typing import Any, Dict import serial import zigpy.exceptions import zigpy_zigate.config import zigpy_zigate.uart from . import types as t LOGGER = logging.getLogger(__name__) COMMAND_TIMEOUT = 1.5 PROBE_TIMEOUT = 3.0 class CommandId(enum.IntEnum): SET_RAWMODE = 0x0002 NETWORK_STATE_REQ = 0x0009 GET_VERSION = 0x0010 RESET = 0x0011 ERASE_PERSISTENT_DATA = 0x0012 GET_DEVICES_LIST = 0x0015 SET_TIMESERVER = 0x0016 GET_TIMESERVER = 0x0017 SET_LED = 0x0018 SET_CE_FCC = 0x0019 SET_EXT_PANID = 0x0020 SET_CHANNELMASK = 0x0021 START_NETWORK = 0x0024 NETWORK_REMOVE_DEVICE = 0x0026 PERMIT_JOINING_REQUEST = 0x0049 MANAGEMENT_NETWORK_UPDATE_REQUEST = 0x004A SEND_RAW_APS_DATA_PACKET = 0x0530 AHI_SET_TX_POWER = 0x0806 class ResponseId(enum.IntEnum): DEVICE_ANNOUNCE = 0x004D STATUS = 0x8000 LOG = 0x8001 DATA_INDICATION = 0x8002 PDM_LOADED = 0x0302 NODE_NON_FACTORY_NEW_RESTART = 0x8006 NODE_FACTORY_NEW_RESTART = 0x8007 HEART_BEAT = 0x8008 NETWORK_STATE_RSP = 0x8009 VERSION_LIST = 0x8010 ACK_DATA = 0x8011 APS_DATA_CONFIRM = 0x8012 PERMIT_JOIN_RSP = 0x8014 GET_DEVICES_LIST_RSP = 0x8015 GET_TIMESERVER_LIST = 0x8017 NETWORK_JOINED_FORMED = 0x8024 PDM_EVENT = 0x8035 NODE_DESCRIPTOR_RSP = 0x8042 LEAVE_INDICATION = 0x8048 ROUTE_DISCOVERY_CONFIRM = 0x8701 APS_DATA_CONFIRM_FAILED = 0x8702 AHI_SET_TX_POWER_RSP = 0x8806 EXTENDED_ERROR = 0x9999 class SendSecurity(t.uint8_t, enum.Enum): NETWORK = 0x00 APPLINK = 0x01 TEMP_APPLINK = 0x02 class NonFactoryNewRestartStatus(t.uint8_t, enum.Enum): Startup = 0 Running = 1 Start = 2 class FactoryNewRestartStatus(t.uint8_t, enum.Enum): Startup = 0 Start = 2 Running = 6 RESPONSES = { ResponseId.DEVICE_ANNOUNCE: (t.NWK, t.EUI64, t.uint8_t, t.uint8_t), ResponseId.STATUS: (t.Status, t.uint8_t, t.uint16_t, t.Bytes), ResponseId.LOG: (t.LogLevel, t.Bytes), ResponseId.DATA_INDICATION: ( t.Status, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.Address, t.Address, t.Bytes, ), ResponseId.PDM_LOADED: (t.uint8_t,), ResponseId.NODE_NON_FACTORY_NEW_RESTART: (NonFactoryNewRestartStatus,), ResponseId.NODE_FACTORY_NEW_RESTART: (FactoryNewRestartStatus,), ResponseId.HEART_BEAT: (t.uint32_t,), ResponseId.NETWORK_STATE_RSP: (t.NWK, t.EUI64, t.uint16_t, t.uint64_t, t.uint8_t), ResponseId.VERSION_LIST: (t.uint16_t, t.uint16_t), ResponseId.ACK_DATA: (t.Status, t.NWK, t.uint8_t, t.uint16_t, t.uint8_t), ResponseId.APS_DATA_CONFIRM: ( t.Status, t.uint8_t, t.uint8_t, t.Address, t.uint8_t, ), ResponseId.PERMIT_JOIN_RSP: (t.uint8_t,), ResponseId.GET_DEVICES_LIST_RSP: (t.DeviceEntryArray,), ResponseId.GET_TIMESERVER_LIST: (t.uint32_t,), ResponseId.NETWORK_JOINED_FORMED: (t.uint8_t, t.NWK, t.EUI64, t.uint8_t), ResponseId.PDM_EVENT: (t.Status, t.uint32_t), ResponseId.NODE_DESCRIPTOR_RSP: ( t.uint8_t, t.Status, t.NWK, t.uint16_t, t.uint16_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint16_t, ), ResponseId.LEAVE_INDICATION: (t.EUI64, t.uint8_t), ResponseId.ROUTE_DISCOVERY_CONFIRM: (t.uint8_t, t.uint8_t), ResponseId.APS_DATA_CONFIRM_FAILED: ( t.Status, t.uint8_t, t.uint8_t, t.Address, t.uint8_t, ), ResponseId.AHI_SET_TX_POWER_RSP: (t.uint8_t,), ResponseId.EXTENDED_ERROR: (t.Status,), } COMMANDS = { CommandId.SET_RAWMODE: (t.uint8_t,), CommandId.SET_TIMESERVER: (t.uint32_t,), CommandId.SET_LED: (t.uint8_t,), CommandId.SET_CE_FCC: (t.uint8_t,), CommandId.SET_EXT_PANID: (t.uint64_t,), CommandId.SET_CHANNELMASK: (t.uint32_t,), CommandId.NETWORK_REMOVE_DEVICE: (t.EUI64, t.EUI64), CommandId.PERMIT_JOINING_REQUEST: (t.NWK, t.uint8_t, t.uint8_t), CommandId.MANAGEMENT_NETWORK_UPDATE_REQUEST: ( t.NWK, t.uint32_t, t.uint8_t, t.uint8_t, t.uint8_t, t.uint16_t, ), CommandId.SEND_RAW_APS_DATA_PACKET: ( t.uint8_t, t.NWK, t.uint8_t, t.uint8_t, t.uint16_t, t.uint16_t, t.uint8_t, t.uint8_t, t.LBytes, ), CommandId.AHI_SET_TX_POWER: (t.uint8_t,), } class AutoEnum(enum.IntEnum): def _generate_next_value_(name, start, count, last_values): return count class PDM_EVENT(enum.IntEnum): E_PDM_SYSTEM_EVENT_WEAR_COUNT_TRIGGER_VALUE_REACHED = 0 E_PDM_SYSTEM_EVENT_DESCRIPTOR_SAVE_FAILED = 1 E_PDM_SYSTEM_EVENT_PDM_NOT_ENOUGH_SPACE = 2 E_PDM_SYSTEM_EVENT_LARGEST_RECORD_FULL_SAVE_NO_LONGER_POSSIBLE = 3 E_PDM_SYSTEM_EVENT_SEGMENT_DATA_CHECKSUM_FAIL = 4 E_PDM_SYSTEM_EVENT_SEGMENT_SAVE_OK = 5 E_PDM_SYSTEM_EVENT_EEPROM_SEGMENT_HEADER_REPAIRED = 6 E_PDM_SYSTEM_EVENT_SYSTEM_INTERNAL_BUFFER_WEAR_COUNT_SWAP = 7 E_PDM_SYSTEM_EVENT_SYSTEM_DUPLICATE_FILE_SEGMENT_DETECTED = 8 E_PDM_SYSTEM_EVENT_SYSTEM_ERROR = 9 E_PDM_SYSTEM_EVENT_SEGMENT_PREWRITE = 10 E_PDM_SYSTEM_EVENT_SEGMENT_POSTWRITE = 11 E_PDM_SYSTEM_EVENT_SEQUENCE_DUPLICATE_DETECTED = 12 E_PDM_SYSTEM_EVENT_SEQUENCE_VERIFY_FAIL = 13 E_PDM_SYSTEM_EVENT_PDM_SMART_SAVE = 14 E_PDM_SYSTEM_EVENT_PDM_FULL_SAVE = 15 class NoResponseError(zigpy.exceptions.APIException): pass class NoStatusError(NoResponseError): pass class CommandError(zigpy.exceptions.APIException): pass class ZiGate: def __init__(self, device_config: Dict[str, Any]): self._app = None self._config = device_config self._uart = None self._awaiting = {} self._status_awaiting = {} self._lock = asyncio.Lock() self._conn_lost_task = None self.network_state = None @classmethod async def new(cls, config: Dict[str, Any], application=None) -> "ZiGate": api = cls(config) await api.connect() api.set_application(application) return api async def connect(self): assert self._uart is None self._uart = await zigpy_zigate.uart.connect(self._config, self) def connection_lost(self, exc: Exception) -> None: """Lost serial connection.""" LOGGER.warning( "Serial '%s' connection lost unexpectedly: %s", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], exc, ) self._uart = None if self._conn_lost_task and not self._conn_lost_task.done(): self._conn_lost_task.cancel() self._conn_lost_task = asyncio.ensure_future(self._connection_lost()) async def _connection_lost(self) -> None: """Reconnect serial port.""" try: await self._reconnect_till_done() except asyncio.CancelledError: LOGGER.debug("Cancelling reconnection attempt") async def _reconnect_till_done(self) -> None: attempt = 1 while True: try: await asyncio.wait_for(self.reconnect(), timeout=10) break except (asyncio.TimeoutError, OSError) as exc: wait = 2 ** min(attempt, 5) attempt += 1 LOGGER.debug( "Couldn't re-open '%s' serial port, retrying in %ss: %s", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], wait, str(exc), ) await asyncio.sleep(wait) LOGGER.debug( "Reconnected '%s' serial port after %s attempts", self._config[zigpy_zigate.config.CONF_DEVICE_PATH], attempt, ) def close(self): if self._uart: self._uart.close() self._uart = None def reconnect(self): """Reconnect using saved parameters.""" LOGGER.debug("Reconnecting '%s' serial port", self._config[zigpy_zigate.config.CONF_DEVICE_PATH]) return self.connect() def set_application(self, app): self._app = app def data_received(self, cmd, data, lqi): if cmd not in RESPONSES: LOGGER.warning('Received unhandled response 0x%04x: %r', cmd, binascii.hexlify(data)) return cmd = ResponseId(cmd) data, rest = t.deserialize(data, RESPONSES[cmd]) LOGGER.debug("Response received: %s %s %s (LQI:%s)", cmd, data, rest, lqi) if cmd == ResponseId.STATUS: if data[2] in self._status_awaiting: fut = self._status_awaiting.pop(data[2]) fut.set_result((data, lqi)) if cmd in self._awaiting: fut = self._awaiting.pop(cmd) fut.set_result((data, lqi)) self.handle_callback(cmd, data, lqi) async def wait_for_status(self, cmd): LOGGER.debug('Wait for status to command %s', cmd) if cmd in self._status_awaiting: self._status_awaiting[cmd].cancel() status_fut = asyncio.Future() self._status_awaiting[cmd] = status_fut try: return await status_fut finally: if cmd in self._status_awaiting: self._status_awaiting[cmd].cancel() del self._status_awaiting[cmd] async def wait_for_response(self, wait_response): LOGGER.debug('Wait for response %s', wait_response) if wait_response in self._awaiting: self._awaiting[wait_response].cancel() response_fut = asyncio.Future() self._awaiting[wait_response] = response_fut try: return await response_fut finally: if wait_response in self._awaiting: self._awaiting[wait_response].cancel() del self._awaiting[wait_response] async def command(self, cmd, data=b'', wait_response=None, wait_status=True, timeout=COMMAND_TIMEOUT): async with self._lock: tries = 3 tasks = [] status_task = None response_task = None LOGGER.debug( "Sending %s (%s), waiting for status: %s, waiting for response: %s", cmd, data, wait_status, wait_response, ) if wait_status: status_task = asyncio.create_task(self.wait_for_status(cmd)) tasks.append(status_task) if wait_response is not None: response_task = asyncio.create_task(self.wait_for_response(wait_response)) tasks.append(response_task) try: while tries > 0: if self._uart is None: # connection was lost raise CommandError("API is not running") tries -= 1 self._uart.send(cmd, data) done, pending = await asyncio.wait(tasks, timeout=timeout) if wait_status and tries == 0 and status_task in pending: raise NoStatusError() elif wait_response and tries == 0 and response_task in pending: raise NoResponseError() if wait_response and response_task in done: if wait_status and status_task in pending: continue elif wait_status: await status_task return await response_task elif wait_status and status_task in done: return await status_task elif not wait_response and not wait_status: return finally: for t in tasks: if not t.done(): t.cancel() await asyncio.gather(*tasks, return_exceptions=True) async def version(self): return await self.command(CommandId.GET_VERSION, wait_response=ResponseId.VERSION_LIST) async def version_str(self): version, lqi = await self.version() version = '{:x}'.format(version[1]) version = '{}.{}'.format(version[0], version[1:]) return version async def get_network_state(self): return await self.command(CommandId.NETWORK_STATE_REQ, wait_response=ResponseId.NETWORK_STATE_RSP) async def set_raw_mode(self, enable=True): data = t.serialize([enable], COMMANDS[CommandId.SET_RAWMODE]) await self.command(CommandId.SET_RAWMODE, data) async def reset(self, *, wait=True): wait_response = ResponseId.NODE_NON_FACTORY_NEW_RESTART if wait else None await self.command(CommandId.RESET, wait_response=wait_response) async def erase_persistent_data(self): await self.command(CommandId.ERASE_PERSISTENT_DATA, wait_status=False, wait_response=ResponseId.PDM_LOADED, timeout=10) await asyncio.sleep(1) await self.command(CommandId.RESET, wait_response=ResponseId.NODE_FACTORY_NEW_RESTART) async def set_time(self, dt=None): """ set internal time if timestamp is None, now is used """ dt = dt or datetime.datetime.now() timestamp = int((dt - datetime.datetime(2000, 1, 1)).total_seconds()) data = t.serialize([timestamp], COMMANDS[CommandId.SET_TIMESERVER]) await self.command(CommandId.SET_TIMESERVER, data) async def get_time_server(self): timestamp, lqi = await self.command(CommandId.GET_TIMESERVER, wait_response=ResponseId.GET_TIMESERVER_LIST) dt = datetime.datetime(2000, 1, 1) + datetime.timedelta(seconds=timestamp[0]) return dt async def set_led(self, enable=True): data = t.serialize([enable], COMMANDS[CommandId.SET_LED]) await self.command(CommandId.SET_LED, data) async def set_certification(self, typ='CE'): cert = {'CE': 1, 'FCC': 2}[typ] data = t.serialize([cert], COMMANDS[CommandId.SET_CE_FCC]) await self.command(CommandId.SET_CE_FCC, data) async def management_network_request(self): data = t.serialize([0x0000, 0x07fff800, 0xff, 5, 0xff, 0x0000], COMMANDS[CommandId.MANAGEMENT_NETWORK_UPDATE_REQUEST]) return await self.command(CommandId.MANAGEMENT_NETWORK_UPDATE_REQUEST)#, wait_response=0x804a, timeout=10) async def set_tx_power(self, power=63): if power > 63: power = 63 if power < 0: power = 0 data = t.serialize([power], COMMANDS[CommandId.AHI_SET_TX_POWER]) power, lqi = await self.command(CommandId.AHI_SET_TX_POWER, data, wait_response=CommandId.AHI_SET_TX_POWER_RSP) return power[0] async def set_channel(self, channels=None): channels = channels or [11, 14, 15, 19, 20, 24, 25, 26] if not isinstance(channels, list): channels = [channels] mask = functools.reduce(lambda acc, x: acc ^ 2 ** x, channels, 0) data = t.serialize([mask], COMMANDS[CommandId.SET_CHANNELMASK]) await self.command(CommandId.SET_CHANNELMASK, data) async def set_extended_panid(self, extended_pan_id): data = t.serialize([extended_pan_id], COMMANDS[CommandId.SET_EXT_PANID]) await self.command(CommandId.SET_EXT_PANID, data) async def get_devices_list(self): (entries,), lqi = await self.command(CommandId.GET_DEVICES_LIST, wait_response=ResponseId.GET_DEVICES_LIST_RSP) return list(entries or []) async def permit_join(self, duration=60): data = t.serialize([0x0000, duration, 1], COMMANDS[CommandId.PERMIT_JOINING_REQUEST]) return await self.command(CommandId.PERMIT_JOINING_REQUEST, data) async def start_network(self): return await self.command(CommandId.START_NETWORK, wait_response=ResponseId.NETWORK_JOINED_FORMED) async def remove_device(self, zigate_ieee, ieee): data = t.serialize([zigate_ieee, ieee], COMMANDS[CommandId.NETWORK_REMOVE_DEVICE]) return await self.command(CommandId.NETWORK_REMOVE_DEVICE, data) async def raw_aps_data_request(self, addr, src_ep, dst_ep, profile, cluster, payload, addr_mode=t.AddressMode.NWK, security=SendSecurity.NETWORK, radius=0): ''' Send raw APS Data request ''' data = t.serialize([addr_mode, addr, src_ep, dst_ep, cluster, profile, security, radius, payload], COMMANDS[CommandId.SEND_RAW_APS_DATA_PACKET]) return await self.command(CommandId.SEND_RAW_APS_DATA_PACKET, data) def handle_callback(self, *args): """run application callback handler""" if self._app: try: self._app.zigate_callback_handler(*args) except Exception as e: LOGGER.exception("Exception running handler", exc_info=e) @classmethod async def probe(cls, device_config: Dict[str, Any]) -> bool: """Probe port for the device presence.""" api = cls(zigpy_zigate.config.SCHEMA_DEVICE(device_config)) try: await asyncio.wait_for(api._probe(), timeout=PROBE_TIMEOUT) return True except ( asyncio.TimeoutError, serial.SerialException, zigpy.exceptions.ZigbeeException, ) as exc: LOGGER.debug( "Unsuccessful radio probe of '%s' port", device_config[zigpy_zigate.config.CONF_DEVICE_PATH], exc_info=exc, ) finally: api.close() return False async def _probe(self) -> None: """Open port and try sending a command""" try: device = next(serial.tools.list_ports.grep(self._config[zigpy_zigate.config.CONF_DEVICE_PATH])) if device.description == 'ZiGate': return except StopIteration: pass await self.connect() await self.set_raw_mode()
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/api.py
api.py
from __future__ import annotations import asyncio import logging from typing import Any, Dict, Optional import zigpy.application import zigpy.config import zigpy.device import zigpy.types import zigpy.util import zigpy.zdo import zigpy.exceptions import zigpy_zigate from zigpy_zigate import types as t from zigpy_zigate import common as c from zigpy_zigate.api import NoResponseError, ZiGate, CommandId, ResponseId, PDM_EVENT from zigpy_zigate.config import CONF_DEVICE, CONF_DEVICE_PATH, CONFIG_SCHEMA, SCHEMA_DEVICE LOGGER = logging.getLogger(__name__) class ControllerApplication(zigpy.application.ControllerApplication): SCHEMA = CONFIG_SCHEMA SCHEMA_DEVICE = SCHEMA_DEVICE probe = ZiGate.probe def __init__(self, config: Dict[str, Any]): super().__init__(zigpy.config.ZIGPY_SCHEMA(config)) self._api: Optional[ZiGate] = None self._pending = {} self._pending_join = [] self.version: str = "" async def connect(self): api = await ZiGate.new(self._config[CONF_DEVICE], self) await api.set_raw_mode() await api.set_time() (_, version), lqi = await api.version() major, minor = version.to_bytes(2, "big") self.version = f"{major:x}.{minor:x}" self._api = api if self.version < '3.21': LOGGER.error('Old ZiGate firmware detected, you should upgrade to 3.21 or newer') async def disconnect(self): # TODO: how do you stop the network? Is it possible? if self._api is not None: try: await self._api.reset(wait=False) except Exception as e: LOGGER.warning("Failed to reset before disconnect: %s", e) finally: self._api.close() self._api = None async def start_network(self): # TODO: how do you start the network? Is it always automatically started? dev = ZiGateDevice(self, self.state.node_info.ieee, self.state.node_info.nwk) self.devices[dev.ieee] = dev await dev.schedule_initialize() async def load_network_info(self, *, load_devices: bool = False): network_state, lqi = await self._api.get_network_state() if not network_state or network_state[3] == 0 or network_state[0] == 0xffff: raise zigpy.exceptions.NetworkNotFormed() self.state.node_info = zigpy.state.NodeInfo( nwk=zigpy.types.NWK(network_state[0]), ieee=zigpy.types.EUI64(network_state[1]), logical_type=zigpy.zdo.types.LogicalType.Coordinator, ) epid, _ = zigpy.types.ExtendedPanId.deserialize(zigpy.types.uint64_t(network_state[3]).serialize()) self.state.network_info = zigpy.state.NetworkInfo( source=f"zigpy-zigate@{zigpy_zigate.__version__}", extended_pan_id=epid, pan_id=zigpy.types.PanId(network_state[2]), nwk_update_id=0, nwk_manager_id=zigpy.types.NWK(0x0000), channel=network_state[4], channel_mask=zigpy.types.Channels.from_channel_list([network_state[4]]), security_level=5, # TODO: is it possible to read keys? # network_key=zigpy.state.Key(), # tc_link_key=zigpy.state.Key(), children=[], key_table=[], nwk_addresses={}, stack_specific={}, metadata={ "zigate": { "version": self.version, } } ) self.state.network_info.tc_link_key.partner_ieee = self.state.node_info.ieee if not load_devices: return for device in await self._api.get_devices_list(): if device.power_source != 0: # only battery-powered devices continue ieee = zigpy.types.EUI64(device.ieee_addr) self.state.network_info.children.append(ieee) self.state.network_info.nwk_addresses[ieee] = zigpy.types.NWK(device.short_addr) async def reset_network_info(self): await self._api.erase_persistent_data() async def write_network_info(self, *, network_info, node_info): LOGGER.warning('Setting the pan_id is not supported by ZiGate') await self.reset_network_info() await self._api.set_channel(network_info.channel) epid, _ = zigpy.types.uint64_t.deserialize(network_info.extended_pan_id.serialize()) await self._api.set_extended_panid(epid) network_formed, lqi = await self._api.start_network() if network_formed[0] not in ( t.Status.Success, t.Status.IncorrectParams, t.Status.Busy, ): raise zigpy.exceptions.FormationFailure( f"Unexpected error starting network: {network_formed!r}" ) LOGGER.warning('Starting network got status %s, wait...', network_formed[0]) for attempt in range(3): await asyncio.sleep(1) try: await self.load_network_info() except zigpy.exceptions.NetworkNotFormed as e: if attempt == 2: raise zigpy.exceptions.FormationFailure() from e async def permit_with_key(self, node, code, time_s = 60): LOGGER.warning("ZiGate does not support joins with install codes") async def _move_network_to_channel( self, new_channel: int, *, new_nwk_update_id: int ) -> None: """Moves the network to a new channel.""" await self._api.set_channel(new_channel) async def energy_scan( self, channels: zigpy.types.Channels, duration_exp: int, count: int ) -> dict[int, float]: """Runs an energy detection scan and returns the per-channel scan results.""" LOGGER.warning("Coordinator does not support energy scanning") return {c: 0 for c in channels} async def force_remove(self, dev): await self._api.remove_device(self.state.node_info.ieee, dev.ieee) async def add_endpoint(self, descriptor): # ZiGate does not support adding new endpoints pass def zigate_callback_handler(self, msg, response, lqi): LOGGER.debug('zigate_callback_handler %s %s', msg, response) if msg == ResponseId.LEAVE_INDICATION: nwk = 0 ieee = zigpy.types.EUI64(response[0]) self.handle_leave(nwk, ieee) elif msg == ResponseId.DEVICE_ANNOUNCE: nwk = response[0] ieee = zigpy.types.EUI64(response[1]) parent_nwk = 0 self.handle_join(nwk, ieee, parent_nwk) # Temporary disable two stages pairing due to firmware bug # rejoin = response[3] # if nwk in self._pending_join or rejoin: # LOGGER.debug('Finish pairing {} (2nd device announce)'.format(nwk)) # if nwk in self._pending_join: # self._pending_join.remove(nwk) # self.handle_join(nwk, ieee, parent_nwk) # else: # LOGGER.debug('Start pairing {} (1st device announce)'.format(nwk)) # self._pending_join.append(nwk) elif msg == ResponseId.DATA_INDICATION: ( status, profile_id, cluster_id, src_ep, dst_ep, src, dst, payload, ) = response packet = zigpy.types.ZigbeePacket( src=src.to_zigpy_type()[0], src_ep=src_ep, dst=dst.to_zigpy_type()[0], dst_ep=dst_ep, profile_id=profile_id, cluster_id=cluster_id, data=zigpy.types.SerializableBytes(payload), lqi=lqi, rssi=None, ) self.packet_received(packet) elif msg == ResponseId.ACK_DATA: LOGGER.debug('ACK Data received %s %s', response[4], response[0]) # disabled because of https://github.com/fairecasoimeme/ZiGate/issues/324 # self._handle_frame_failure(response[4], response[0]) elif msg == ResponseId.APS_DATA_CONFIRM: LOGGER.debug('ZPS Event APS data confirm, message routed to %s %s', response[3], response[0]) elif msg == ResponseId.PDM_EVENT: try: event = PDM_EVENT(response[0]).name except ValueError: event = 'Unknown event' LOGGER.debug('PDM Event %s %s, record %s', response[0], event, response[1]) elif msg == ResponseId.APS_DATA_CONFIRM_FAILED: LOGGER.debug('APS Data confirm Fail %s %s', response[4], response[0]) self._handle_frame_failure(response[4], response[0]) elif msg == ResponseId.EXTENDED_ERROR: LOGGER.warning('Extended error code %s', response[0]) def _handle_frame_failure(self, message_tag, status): try: send_fut = self._pending.pop(message_tag) send_fut.set_result(status) except KeyError: LOGGER.warning("Unexpected message send failure") except asyncio.futures.InvalidStateError as exc: LOGGER.debug("Invalid state on future - probably duplicate response: %s", exc) async def send_packet(self, packet): LOGGER.debug("Sending packet %r", packet) # Firmwares 3.1d and below allow a couple of _NO_ACK packets to send but all # subsequent ones will fail. ACKs must be enabled. ack = ( zigpy.types.TransmitOptions.ACK in packet.tx_options or self.version <= "3.1d" ) try: (status, tsn, packet_type, _), _ = await self._api.raw_aps_data_request( addr=packet.dst.address, src_ep=(1 if packet.dst_ep is None or packet.dst_ep > 0 else 0), # ZiGate only support endpoint 1 dst_ep=packet.dst_ep or 0, profile=packet.profile_id, cluster=packet.cluster_id, payload=packet.data.serialize(), addr_mode=t.ZIGPY_TO_ZIGATE_ADDR_MODE[packet.dst.addr_mode, ack], radius=packet.radius, ) except NoResponseError: raise zigpy.exceptions.DeliveryError("ZiGate did not respond to command") self._pending[tsn] = asyncio.get_running_loop().create_future() if status != t.Status.Success: self._pending.pop(tsn) # Firmwares 3.1d and below fail to send packets on every request if status == t.Status.InvalidParameter and self.version <= "3.1d": pass else: raise zigpy.exceptions.DeliveryError(f"Failed to send packet: {status!r}", status=status) # disabled because of https://github.com/fairecasoimeme/ZiGate/issues/324 # try: # v = await asyncio.wait_for(send_fut, 120) # except asyncio.TimeoutError: # return 1, "timeout waiting for message %s send ACK" % (sequence, ) # finally: # self._pending.pop(tsn) # return v, "Message sent" async def permit_ncp(self, time_s=60): assert 0 <= time_s <= 254 status, lqi = await self._api.permit_join(time_s) if status[0] != t.Status.Success: await self._api.reset() class ZiGateDevice(zigpy.device.Device): def __init__(self, application, ieee, nwk): """Initialize instance.""" super().__init__(application, ieee, nwk) port = application._config[CONF_DEVICE][CONF_DEVICE_PATH] model = 'ZiGate USB-TTL' if c.is_zigate_wifi(port): model = 'ZiGate WiFi' elif c.is_pizigate(port): model = 'PiZiGate' elif c.is_zigate_din(port): model = 'ZiGate USB-DIN' self._model = f'{model} {application.version}' @property def manufacturer(self): return "ZiGate" @property def model(self): return self._model
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/zigbee/application.py
application.py
import argparse import functools import itertools import logging import struct from operator import xor import datetime from .firmware import download_latest from zigpy_zigate import common as c import time import serial from serial.tools.list_ports import comports import usb LOGGER = logging.getLogger(__name__) _responses = {} ZIGATE_CHIP_ID = 0x10408686 ZIGATE_BINARY_VERSION = bytes.fromhex('07030008') ZIGATE_FLASH_START = 0x00000000 ZIGATE_FLASH_END = 0x00040000 class Command: def __init__(self, type_, fmt=None, raw=False): assert not (raw and fmt), 'Raw commands cannot use built-in struct formatting' LOGGER.debug('Command {} {} {}'.format(type_, fmt, raw)) self.type = type_ self.raw = raw if fmt: self.struct = struct.Struct(fmt) else: self.struct = None def __call__(self, func): @functools.wraps(func) def wrapper(*args, **kwargs): rv = func(*args, **kwargs) if self.struct: try: data = self.struct.pack(*rv) except TypeError: data = self.struct.pack(rv) elif self.raw: data = rv else: data = bytearray() return prepare(self.type, data) return wrapper class Response: def __init__(self, type_, data, chksum): LOGGER.debug('Response {} {} {}'.format(type_, data, chksum)) self.type = type_ self.data = data[1:] self.chksum = chksum self.status = data[0] @property def ok(self): return self.status == 0 def __str__(self): return 'Response(type=0x%02x, data=0x%s, checksum=0x%02x)' % (self.type, self.data.hex(), self.chksum) def register(type_): assert type_ not in _responses, 'Duplicate response type 0x%02x' % type_ def decorator(func): _responses[type_] = func return func return decorator def prepare(type_, data): length = len(data) + 2 checksum = functools.reduce(xor, itertools.chain(type_.to_bytes(2, 'big'), length.to_bytes(2, 'big'), data), 0) message = struct.pack('!BB%dsB' % len(data), length, type_, data, checksum) # print('Prepared command 0x%s' % message.hex()) return message def read_response(ser): length = ser.read() length = int.from_bytes(length, 'big') LOGGER.debug('read_response length {}'.format(length)) answer = ser.read(length) LOGGER.debug('read_response answer {}'.format(answer)) return _unpack_raw_message(length, answer) # type_, data, chksum = struct.unpack('!B%dsB' % (length - 2), answer) # return {'type': type_, 'data': data, 'chksum': chksum} def _unpack_raw_message(length, decoded): LOGGER.debug('unpack raw message {} {}'.format(length, decoded)) if len(decoded) != length or length < 2: LOGGER.exception("Unpack failed, length: %d, msg %s" % (length, decoded.hex())) return type_, data, chksum = \ struct.unpack('!B%dsB' % (length - 2), decoded) return _responses.get(type_, Response)(type_, data, chksum) @Command(0x07) def req_flash_erase(): pass @Command(0x09, raw=True) def req_flash_write(addr, data): msg = struct.pack('<L%ds' % len(data), addr, data) return msg @Command(0x0b, '<LH') def req_flash_read(addr, length): return (addr, length) @Command(0x1f, '<LH') def req_ram_read(addr, length): return (addr, length) @Command(0x25) def req_flash_id(): pass @Command(0x27, '!B') def req_change_baudrate(rate): # print(serial.Serial.BAUDRATES) clockspeed = 1000000 divisor = round(clockspeed / rate) # print(divisor) return divisor @Command(0x2c, '<BL') def req_select_flash_type(type_, custom_jump=0): return (type_, custom_jump) @Command(0x32) def req_chip_id(): pass @Command(0x36, 'B') def req_eeprom_erase(pdm_only=False): return not pdm_only @register(0x26) class ReadFlashIDResponse(Response): def __init__(self, *args): super().__init__(*args) self.manufacturer_id, self.device_id = struct.unpack('!BB', self.data) def __str__(self): return 'ReadFlashIDResponse %d (ok=%s, manufacturer_id=0x%02x, device_id=0x%02x)' % (self.status, self.ok, self.manufacturer_id, self.device_id) @register(0x28) class ChangeBaudrateResponse(Response): def __init__(self, *args): super().__init__(*args) def __str__(self): return 'ChangeBaudrateResponse %d (ok=%s)' % (self.status, self.ok) @register(0x33) class GetChipIDResponse(Response): def __init__(self, *args): super().__init__(*args) (self.chip_id,) = struct.unpack('!L', self.data) def __str__(self): return 'GetChipIDResponse (ok=%s, chip_id=0x%04x)' % (self.ok, self.chip_id) @register(0x37) class EraseEEPROMResponse(Response): def __init__(self, *args): super().__init__(*args) def __str__(self): return 'EraseEEPROMResponse %d (ok=%s)' % (self.status, self.ok) def change_baudrate(ser, baudrate): ser.write(req_change_baudrate(baudrate)) res = read_response(ser) if not res or not res.ok: LOGGER.exception('Change baudrate failed') raise SystemExit(1) ser.baudrate = baudrate def check_chip_id(ser): ser.write(req_chip_id()) res = read_response(ser) if not res or not res.ok: LOGGER.exception('Getting Chip ID failed') raise SystemExit(1) if res.chip_id != ZIGATE_CHIP_ID: LOGGER.exception('This is not a supported chip, patches welcome') raise SystemExit(1) def get_flash_type(ser): ser.write(req_flash_id()) res = read_response(ser) if not res or not res.ok: print('Getting Flash ID failed') raise SystemExit(1) if res.manufacturer_id != 0xcc or res.device_id != 0xee: print('Unsupported Flash ID, patches welcome') raise SystemExit(1) else: return 8 def get_mac(ser): ser.write(req_ram_read(0x01001570, 8)) res = read_response(ser) if res.data == bytes.fromhex('ffffffffffffffff'): ser.write(req_ram_read(0x01001580, 8)) res = read_response(ser) return ':'.join(''.join(x) for x in zip(*[iter(res.data.hex())] * 2)) def select_flash(ser, flash_type): ser.write(req_select_flash_type(flash_type)) res = read_response(ser) if not res or not res.ok: print('Selecting flash type failed') raise SystemExit(1) def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd="\r"): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) printEnd - Optional : end character (e.g. "\r", "\r\n") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print('\r{0} |{1}| {2}% {3}'.format(prefix, bar, percent, suffix), end=printEnd) # Print New Line on Complete if iteration == total: print() def write_flash_to_file(ser, filename): # flash_start = cur = ZIGATE_FLASH_START cur = ZIGATE_FLASH_START flash_end = ZIGATE_FLASH_END LOGGER.info('Backup firmware to %s', filename) with open(filename, 'wb') as fd: fd.write(ZIGATE_BINARY_VERSION) read_bytes = 128 while cur < flash_end: if cur + read_bytes > flash_end: read_bytes = flash_end - cur ser.write(req_flash_read(cur, read_bytes)) res = read_response(ser) if not res or not res.ok: print('Reading flash failed') raise SystemExit(1) if cur == 0: (flash_end,) = struct.unpack('>L', res.data[0x20:0x24]) fd.write(res.data) printProgressBar(cur, flash_end, 'Reading') cur += read_bytes printProgressBar(flash_end, flash_end, 'Reading') LOGGER.info('Backup firmware done') def write_file_to_flash(ser, filename): LOGGER.info('Writing new firmware from %s', filename) with open(filename, 'rb') as fd: ser.write(req_flash_erase()) res = read_response(ser) if not res or not res.ok: print('Erasing flash failed') raise SystemExit(1) # flash_start = cur = ZIGATE_FLASH_START cur = ZIGATE_FLASH_START flash_end = ZIGATE_FLASH_END bin_ver = fd.read(4) if bin_ver != ZIGATE_BINARY_VERSION: print('Not a valid image for Zigate') raise SystemExit(1) read_bytes = 128 while cur < flash_end: data = fd.read(read_bytes) if not data: break ser.write(req_flash_write(cur, data)) res = read_response(ser) if not res.ok: print('writing failed at 0x%08x, status: 0x%x, data: %s' % (cur, res.status, data.hex())) raise SystemExit(1) printProgressBar(cur, flash_end, 'Writing') cur += read_bytes printProgressBar(flash_end, flash_end, 'Writing') LOGGER.info('Writing new firmware done') def erase_EEPROM(ser, pdm_only=False): ser.timeout = 10 # increase timeout because official NXP programmer do it ser.write(req_eeprom_erase(pdm_only)) res = read_response(ser) if not res or not res.ok: print('Erasing EEPROM failed') raise SystemExit(1) def flash(serialport='auto', write=None, save=None, erase=False, pdm_only=False): """ Read or write firmware """ if serialport == 'auto': serialport = c.discover_port() try: ser = serial.Serial(serialport, 38400, timeout=5) except serial.SerialException: LOGGER.exception("Could not open serial device %s", serialport) return change_baudrate(ser, 115200) check_chip_id(ser) flash_type = get_flash_type(ser) mac_address = get_mac(ser) LOGGER.info('Found MAC-address: %s', mac_address) if write or save or erase: select_flash(ser, flash_type) if save: write_flash_to_file(ser, save) if write: write_file_to_flash(ser, write) if erase: erase_EEPROM(ser, pdm_only) change_baudrate(ser, 38400) ser.close() def upgrade_firmware(port): backup_filename = 'zigate_backup_{:%Y%m%d%H%M%S}.bin'.format(datetime.datetime.now()) flash(port, save=backup_filename) print('ZiGate backup created {}'.format(backup_filename)) firmware_path = download_latest() print('Firmware downloaded', firmware_path) flash(port, write=firmware_path) print('ZiGate flashed with {}'.format(firmware_path)) def main(): ports_available = [port for (port, _, _) in sorted(comports())] parser = argparse.ArgumentParser() parser.add_argument('-p', '--serialport', choices=ports_available, help='Serial port, e.g. /dev/ttyUSB0', required=True) parser.add_argument('-w', '--write', help='Firmware bin to flash onto the chip') parser.add_argument('-s', '--save', help='File to save the currently loaded firmware to') parser.add_argument('-u', '--upgrade', help='Download and flash the lastest available firmware', action='store_true', default=False) # parser.add_argument('-e', '--erase', help='Erase EEPROM', action='store_true') # parser.add_argument('--pdm-only', help='Erase PDM only, use it with --erase', action='store_true') parser.add_argument('-d', '--debug', help='Set log level to DEBUG', action='store_true') parser.add_argument('--gpio', help='Configure GPIO for PiZiGate flash', action='store_true', default=False) parser.add_argument('--din', help='Configure USB for ZiGate DIN flash', action='store_true', default=False) args = parser.parse_args() LOGGER.setLevel(logging.INFO) if args.debug: LOGGER.setLevel(logging.DEBUG) if args.gpio: c.set_pizigate_flashing_mode() elif args.din: c.set_zigatedin_flashing_mode() if args.upgrade: upgrade_firmware(args.serialport) else: try: ser = serial.Serial(args.serialport, 38400, timeout=5) except serial.SerialException: LOGGER.exception("Could not open serial device %s", args.serialport) raise SystemExit(1) change_baudrate(ser, 115200) check_chip_id(ser) flash_type = get_flash_type(ser) mac_address = get_mac(ser) LOGGER.info('Found MAC-address: %s', mac_address) if args.write or args.save: # or args.erase: select_flash(ser, flash_type) if args.save: write_flash_to_file(ser, args.save) if args.write: write_file_to_flash(ser, args.write) # if args.erase: # erase_EEPROM(ser, args.pdm_only) if args.gpio: c.set_pizigate_running_mode() elif args.din: c.set_zigatedin_running_mode() if __name__ == "__main__": logging.basicConfig() main()
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/tools/flasher.py
flasher.py
import urllib.request import logging import os import argparse import json from collections import OrderedDict URL = 'https://api.github.com/repos/fairecasoimeme/ZiGate/releases' LOGGER = logging.getLogger("ZiGate Firmware") def get_releases(): LOGGER.info('Searching for ZiGate firmware') releases = OrderedDict() r = urllib.request.urlopen(URL) if r.status == 200: for release in json.loads(r.read()): if release.get('draft'): continue if release.get('prerelease'): continue for asset in release['assets']: if 'pdm' in asset['name'].lower(): continue if asset['name'].endswith('.bin'): LOGGER.info('Found %s', asset['name']) releases[asset['name']] = asset['browser_download_url'] return releases def download(url, dest='/tmp'): filename = url.rsplit('/', 1)[1] LOGGER.info('Downloading %s to %s', url, dest) r = urllib.request.urlopen(url) if r.status == 200: filename = os.path.join(dest, filename) with open(filename, 'wb') as fp: fp.write(r.read()) LOGGER.info('Done') return filename else: LOGGER.error('Error downloading %s %s', r.status, r.reason) def download_latest(dest='/tmp'): LOGGER.info('Download latest firmware') releases = get_releases() if releases: latest = list(releases.keys())[0] LOGGER.info('Latest is %s', latest) return download(releases[latest], dest) if __name__ == '__main__': logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument("command", help="Command to start", choices=["list", "download", "download-latest"]) parser.add_argument('--url', help="Download URL") parser.add_argument('--dest', help="Download folder, default to /tmp", default='/tmp') args = parser.parse_args() if args.command == 'list': for k, v in get_releases().items(): print(k, v) elif args.command == 'download': if not args.url: LOGGER.error('You have to give a URL to download using --url') else: download(args.url, args.dest) elif args.command == 'download-latest': download_latest(args.dest)
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/tools/firmware.py
firmware.py
import argparse import asyncio import logging from os import wait from zigpy_zigate.api import LOGGER, ZiGate, NoResponseError, CommandError import zigpy_zigate.config async def main(): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument("command", help="Command to start", choices=["version", "reset", "erase_persistent", "set_time", "get_time", "set_led", "set_certification", "set_tx_power", "management_network_request", "loop"]) parser.add_argument("-p", "--port", help="Port", default='auto') parser.add_argument("-d", "--debug", help="Debug log", action='store_true') parser.add_argument("-v", "--value", help="Set command's value") args = parser.parse_args() print('Port set to', args.port) if args.debug: logging.root.setLevel(logging.DEBUG) device_config = {zigpy_zigate.config.CONF_DEVICE_PATH: args.port} api = ZiGate(device_config) await api.connect() if args.command == 'version': print('Firmware version', await api.version_str()) elif args.command == 'reset': await api.reset() print('ZiGate reseted') elif args.command == 'erase_persistent': await api.erase_persistent_data() print('ZiGate pesistent date erased') elif args.command == 'set_time': await api.set_time() print('ZiGate internal time server set to current time') elif args.command == 'get_time': print('ZiGate internal time server is', await api.get_time_server()) elif args.command == 'set_led': enable = int(args.value or 1) print('Set ZiGate led to', enable) await api.set_led(enable) elif args.command == 'set_certification': _type = args.value or 'CE' print('Set ZiGate Certification to', _type) await api.set_certification(_type) elif args.command == 'set_tx_power': power = int(args.value or 63) print('Set ZiGate TX Power to', power) print('Tx power set to', await api.set_tx_power(power)) elif args.command == 'management_network_request': await api.reset() # await api.set_raw_mode(False) await api.management_network_request() print('ok') await asyncio.sleep(10) elif args.command == 'loop': # for testing purpose enable = True while True: try: LOGGER.info('Set led %s', enable) await api.set_led(enable) enable = not enable await asyncio.sleep(1) except KeyboardInterrupt: break except (NoResponseError, CommandError): LOGGER.exception('NoResponseError') await asyncio.sleep(1) continue api.close() if __name__ == '__main__': asyncio.run(main())
zigpy-zigate
/zigpy-zigate-0.11.0.tar.gz/zigpy-zigate-0.11.0/zigpy_zigate/tools/cli.py
cli.py
# zigpy-znp [![Build Status](https://github.com/zigpy/zigpy-znp/workflows/CI/badge.svg)](https://github.com/zigpy/zigpy-znp/actions) [![Coverage Status](https://codecov.io/gh/zigpy/zigpy-znp/branch/dev/graph/badge.svg?token=Y1994N9D74)](https://codecov.io/gh/zigpy/zigpy-znp) **[zigpy-znp](https://github.com/zigpy/zigpy-znp/)** is a Python library that adds support for common [Texas Instruments ZNP (Zigbee Network Processors)](http://dev.ti.com/tirex/content/simplelink_zigbee_sdk_plugin_2_20_00_06/docs/zigbee_user_guide/html/zigbee/introduction.html) [Zigbee](https://www.zigbee.org) radio modules to [zigpy](https://github.com/zigpy/), a Python Zigbee stack project. Together with zigpy and compatible home automation software (namely Home Assistant's [ZHA (Zigbee Home Automation) integration component](https://www.home-assistant.io/integrations/zha/)), you can directly control Zigbee devices such as Philips Hue, GE, OSRAM LIGHTIFY, Xiaomi/Aqara, IKEA Tradfri, Samsung SmartThings, and many more. # Installation ## Python module Install the Python module within your virtual environment: ```console $ virtualenv -p python3.8 venv # if you don't already have one $ source venv/bin/activate (venv) $ pip install git+https://github.com/zigpy/zigpy-znp/ # latest commit from Git (venv) $ pip install zigpy-znp # or, latest stable from PyPI ``` ## Home Assistant Stable releases of zigpy-znp are automatically installed when you install the ZHA component. ### Testing `dev` with Home Assistant Core Upgrade the package within your virtual environment (requires `git`): ```console (venv) $ pip install git+https://github.com/zigpy/zigpy-znp/ ``` Launch Home Assistant with the `--skip-pip` command line option to prevent zigpy-znp from being downgraded. Running with this option may prevent newly added integrations from installing required packages. ### Testing `dev` with Home Assistant OS - Add https://github.com/home-assistant/hassio-addons-development as an addon repository. - Install the "Custom deps deployment" addon. - Add the following to your `configuration.yaml` file: ```yaml apk: [] pypi: - git+https://github.com/zigpy/zigpy-znp/ ``` # Configuration Below are the defaults with the top-level Home Assistant `zha:` key. **You do not need to copy this configuration, it is provided only for reference**: ```yaml zha: zigpy_config: znp_config: # Only if your stick has a built-in power amplifier (i.e. CC1352P and CC2592) # If set, must be between: # * CC1352/2652: -22 and 19 # * CC253x: -22 and 22 tx_power: # Only if your stick has a controllable LED (the CC2531) # If set, must be one of: off, on, blink, flash, toggle led_mode: off ### Internal configuration, there's no reason to touch these values # Skips the 60s bootloader delay on CC2531 sticks skip_bootloader: True # Timeout for synchronous requests' responses sreq_timeout: 15 # Timeout for asynchronous requests' callback responses arsp_timeout: 30 # Delay between auto-reconnect attempts in case the device gets disconnected auto_reconnect_retry_delay: 5 # Pin states for skipping the bootloader connect_rts_pin_states: [off, on, off] connect_dtr_pin_states: [off, off, off] ``` # Tools Various command line Zigbee utilities are a part of the zigpy-znp package and can be run with `python -m zigpy_znp.tools.name_of_tool`. More detailed documentation can be found in **[`TOOLS.md`](./TOOLS.md)** but a brief description of each tool is included below: - **`energy_scan`**: Performs a continuous energy scan to check for non-Zigbee interference. - **`flash_read`**: For CC2531s, reads firmware from flash. - **`flash_write`**: For CC2531s, writes a firmware `.bin` to flash. - **`form_network`**: Forms a network with randomized settings on channel 15. - **`network_backup`**: Backs up the network data and device information into a human-readable JSON document. - **`network_restore`**: Restores a JSON network backup to the adapter. - **`network_scan`**: Actively sends beacon requests for network stumbling. - **`nvram_read`**: Reads all possible NVRAM entries into a JSON document. - **`nvram_reset`**: Deletes all possible NVRAM entries - **`nvram_write`**: Writes all NVRAM entries from a JSON document. # Hardware requirements USB-adapters, GPIO-modules, and development-boards flashed with TI's Z-Stack are compatible with zigpy-znp: - CC2652P/CC2652R/CC2652RB USB stick and dev board hardware - CC1352P/CC1352R USB stick and dev board hardware - CC2538 + CC2592 USB stick and dev board hardware (**not recommended, old hardware and end-of-life firmware**) - CC2531 USB stick hardware (**not recommended for Zigbee networks with more than 20 devices**) - CC2530 + CC2591/CC2592 USB stick hardware (**not recommended for Zigbee networks with more than 20 devices**) Tip! Adapters listed as "[Texas Instruments sticks compatible with Zigbee2MQTT](https://www.zigbee2mqtt.io/information/supported_adapters)" also works with zigpy-znp. ## Reference hardware for this project These specific adapters are used as reference hardware for development and testing by zigpy-znp developers: - [TI LAUNCHXL-CC26X2R1](https://www.ti.com/tool/LAUNCHXL-CC26X2R1) running [Z-Stack 3 firmware (based on version 4.40.00.44)](https://github.com/Koenkk/Z-Stack-firmware/tree/master/coordinator/Z-Stack_3.x.0/bin). You can flash `CC2652R_20210120.hex` using [TI's UNIFLASH](https://www.ti.com/tool/download/UNIFLASH). - [Electrolama zzh CC2652R](https://electrolama.com/projects/zig-a-zig-ah/) and [Slaesh CC2652R](https://slae.sh/projects/cc2652/) sticks running [Z-Stack 3 firmware (based on version 4.40.00.44)](https://github.com/Koenkk/Z-Stack-firmware/tree/master/coordinator/Z-Stack_3.x.0/bin). You can flash `CC2652R_20210120.hex` or `CC2652RB_20210120.hex` respectively using [cc2538-bsl](https://github.com/JelmerT/cc2538-bsl). - CC2531 running [Z-Stack Home 1.2](https://github.com/Koenkk/Z-Stack-firmware/blob/master/coordinator/Z-Stack_Home_1.2/bin/default/CC2531_DEFAULT_20190608.zip). You can flash `CC2531ZNP-Prod.bin` to your stick directly with `zigpy_znp`: `python -m zigpy_znp.tools.flash_write -i /path/to/CC2531ZNP-Prod.bin /dev/serial/by-id/YOUR-CC2531` if your stick already has a serial bootloader. ## Texas Instruments Chip Part Numbers Texas Instruments (TI) has quite a few different wireless MCU chips and they are all used/mentioned in open-source Zigbee world which can be daunting if you are just starting out. Here is a quick summary of part numbers and key features. ### Supported newer generation TI chips #### 2.4GHz frequency only chips - CC2652R: 2.4GHz only wireless MCU for IEEE 802.15.4 multi-protocol (Zigbee, Bluetooth, Thread, IEEE 802.15.4g IPv6-enabled smart objects like 6LoWPAN, and proprietary systems). Cortex-M0 core for radio stack and Cortex-M4F core for application use, plenty of RAM. Free compiler option from TI. - CC2652RB: Pin compatible "Crystal-less" CC2652R (so you could use it if you were to build your own zzh and omit the crystal) but not firmware compatible. - CC2652P: CC2652R with a built-in RF PA. Not pin or firmware compatible with CC2652R/CC2652RB. #### Multi frequency chips - CC1352R: Sub 1 GHz & 2.4 GHz wireless MCU. Essentially CC2652R with an extra sub-1GHz radio. - CC1352P: CC1352R with a built in RF PA. ### Supported older generation TI chips - CC2538: 2.4GHz Zigbee, 6LoWPAN, and IEEE 802.15.4 wireless MCU. ARM Cortex-M3 core with with 512kB Flash and 32kB RAM. - CC2531: CC2530 with a built-in UART/TTL to USB Bridge. Used in the cheap "Zigbee sticks" sold everywhere. Intel 8051 core, 256 Flash, only has 8kB RAM. - CC2530: 2.4GHz Zigbee and IEEE 802.15.4 wireless MCU. Intel 8051 core, 256 Flash, only has 8kB RAM. ### Auxiliary TI chips - CC2591 and CC2592: 2.4 GHz range extenders. These are not wireless MCUs, just auxiliary PA (Power Amplifier) and LNA (Low Noise Amplifier) in the same package to improve RF (Radio Frequency) range of any 2.4 GHz radio chip. # Releases via PyPI Tagged versions will also be released via PyPI - https://pypi.org/project/zigpy-znp/ - https://pypi.org/project/zigpy-znp/#history - https://pypi.org/project/zigpy-znp/#files # External documentation and reference - http://www.ti.com/tool/LAUNCHXL-CC26X2R1 - http://www.ti.com/tool/LAUNCHXL-CC1352P # How to contribute If you are looking to make a code or documentation contribution to this project we suggest that you follow the steps in these guides: - https://github.com/firstcontributions/first-contributions/blob/master/README.md - https://github.com/firstcontributions/first-contributions/blob/master/github-desktop-tutorial.md # Related projects ### Zigpy **[zigpy](https://github.com/zigpy/zigpy)** is [Zigbee protocol stack](https://en.wikipedia.org/wiki/Zigbee) integration project to implement the **[Zigbee Home Automation](https://www.zigbee.org/)** standard as a Python library. Zigbee Home Automation integration with zigpy allows you to connect one of many off-the-shelf Zigbee adapters using one of the available Zigbee radio library modules compatible with zigpy to control Zigbee devices. There is currently support for controlling Zigbee device types such as binary sensors (e.g. motion and door sensors), analog sensors (e.g. temperature sensors), lightbulbs, switches, and fans. Zigpy is tightly integrated with [Home Assistant](https://www.home-assistant.io)'s [ZHA component](https://www.home-assistant.io/components/zha/) and provides a user-friendly interface for working with a Zigbee network.
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/README.md
README.md
from __future__ import annotations import functools import dataclasses import zigpy_znp.types as t from zigpy_znp.exceptions import InvalidFrame @dataclasses.dataclass(frozen=True) class GeneralFrame: header: t.CommandHeader data: t.Bytes def __post_init__(self) -> None: # We're frozen so `self.header = ...` is disallowed if not isinstance(self.header, t.CommandHeader): object.__setattr__(self, "header", t.CommandHeader(self.header)) if not isinstance(self.data, t.Bytes): object.__setattr__(self, "data", t.Bytes(self.data)) if self.length > 250: raise InvalidFrame( f"Frame length cannot exceed 250 bytes. Got: {self.length}" ) @property def length(self) -> t.uint8_t: """Length of the frame.""" return t.uint8_t(len(self.data)) @classmethod def deserialize(cls, data): """Deserialize frame and sanity checks.""" length, data = t.uint8_t.deserialize(data) if length > 250: raise InvalidFrame(f"Frame length cannot exceed 250 bytes. Got: {length}") if len(data) < length + 2: raise InvalidFrame(f"Data is too short for {cls.__name__}") header, data = t.CommandHeader.deserialize(data) payload, data = data[:length], data[length:] return cls(header, payload), data def serialize(self) -> bytes: return self.length.serialize() + self.header.serialize() + self.data.serialize() @dataclasses.dataclass class TransportFrame: """Transport frame.""" SOF = t.uint8_t(0xFE) # Start of frame marker payload: GeneralFrame @classmethod def deserialize(cls, data: bytes) -> tuple[TransportFrame, bytes]: sof, data = t.uint8_t.deserialize(data) if sof != cls.SOF: raise InvalidFrame( f"Expected frame to start with SOF 0x{cls.SOF:02X}, got 0x{sof:02X}" ) gen_frame, data = GeneralFrame.deserialize(data) checksum, data = t.uint8_t.deserialize(data) frame = cls(gen_frame) if frame.checksum() != checksum: raise InvalidFrame( f"Invalid frame checksum for data {gen_frame}: " f"expected 0x{frame.checksum():02X}, got 0x{checksum:02X}" ) return frame, data def checksum(self) -> t.uint8_t: """ Calculates the FCS of the payload. """ checksum = functools.reduce(lambda a, b: a ^ b, self.payload.serialize()) return t.uint8_t(checksum) def serialize(self) -> bytes: return ( self.SOF.serialize() + self.payload.serialize() + self.checksum().serialize() )
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/frames.py
frames.py
import logging import itertools import zigpy_znp.types as t import zigpy_znp.commands as c from zigpy_znp.types import nvids from zigpy_znp.exceptions import SecurityError, InvalidCommandResponse LOGGER = logging.getLogger(__name__) # Some NVIDs don't really exist and Z-Stack doesn't behave consistently when operations # are performed on them. PROXIED_NVIDS = {nvids.OsalNvIds.POLL_RATE_OLD16} class NVRAMHelper: def __init__(self, znp): self.znp = znp self.align_structs = None async def determine_alignment(self) -> None: """ Automatically determine struct memory alignment. Must be called before any structs are read/written. """ # This is the only known MT command to respond with a struct's in-memory # representation over serial. LOGGER.debug("Detecting struct alignment") rsp = await self.znp.request(c.UTIL.AssocFindDevice.Req(Index=0)) if len(rsp.Device) == 28: self.align_structs = False elif len(rsp.Device) == 36: # `AssociatedDevice` has an extra member at the end in Z-Stack 3.30 but # the struct does not change in size due to padding. self.align_structs = True else: raise ValueError(f"Cannot determine alignment from struct: {rsp!r}") LOGGER.debug("Detected struct alignment: %s", self.align_structs) def serialize(self, value) -> bytes: """ Serialize an object, automatically computing struct padding based on the target platform. """ if hasattr(value, "serialize"): if isinstance(value, (t.CStruct, t.BaseListType)): assert self.align_structs is not None value = value.serialize(align=self.align_structs) else: value = value.serialize() elif not isinstance(value, (bytes, bytearray)): raise TypeError( f"Only bytes or serializable types can be written to NVRAM." f" Got {value!r} (type {type(value)})" ) if not value: raise ValueError("NVRAM value cannot be empty") return value def deserialize(self, data: bytes, item_type, *, allow_trailing=False): """ Serialize raw bytes, automatically computing struct padding based on the target platform. """ if issubclass(item_type, (t.CStruct, t.BaseListType)): assert self.align_structs is not None value, remaining = item_type.deserialize(data, align=self.align_structs) else: value, remaining = item_type.deserialize(data) if remaining and not allow_trailing: raise ValueError(f"Data left after deserialization: {remaining!r}") return value async def osal_delete(self, nv_id: t.uint16_t) -> bool: """ Deletes an item from NVRAM. Returns whether or not the item existed. """ length = (await self.znp.request(c.SYS.OSALNVLength.Req(Id=nv_id))).ItemLen if length == 0: return False delete_rsp = await self.znp.request( c.SYS.OSALNVDelete.Req(Id=nv_id, ItemLen=length) ) return delete_rsp.Status == t.Status.SUCCESS async def osal_write(self, nv_id: t.uint16_t, value, *, create: bool = False): """ Writes a complete value to NVRAM, optionally resizing and creating the item if necessary. Serializes all serializable values and passes bytes directly. """ value = self.serialize(value) length = (await self.znp.request(c.SYS.OSALNVLength.Req(Id=nv_id))).ItemLen # Recreate the item if the length is not correct if length != len(value) and nv_id not in PROXIED_NVIDS: if not create: if length == 0: raise KeyError(f"NV item does not exist: {nv_id!r}") else: raise ValueError( f"Stored length and actual length differ:" f" {length} != {len(value)}" ) if length != 0: await self.znp.request( c.SYS.OSALNVDelete.Req(Id=nv_id, ItemLen=length), RspStatus=t.Status.SUCCESS, ) await self.znp.request( c.SYS.OSALNVItemInit.Req( Id=nv_id, ItemLen=len(value), Value=t.ShortBytes(value[:244]), ), RspStatus=t.Status.NV_ITEM_UNINIT, ) # 244 bytes is the most you can fit in a single `SYS.OSALNVWriteExt` command for offset in range(0, len(value), 244): await self.znp.request( c.SYS.OSALNVWriteExt.Req( Id=nv_id, Offset=offset, Value=t.ShortBytes(value[offset : offset + 244]), ), RspStatus=t.Status.SUCCESS, ) async def osal_read(self, nv_id: t.uint16_t, *, item_type): """ Reads a complete value from NVRAM. Raises an `KeyError` error if the NVID doesn't exist. """ # XXX: Some NVIDs don't really exist and Z-Stack behaves strangely with them if nv_id in PROXIED_NVIDS: read_rsp = await self.znp.request( c.SYS.OSALNVRead.Req(Id=nv_id, Offset=0), RspStatus=t.Status.SUCCESS, ) value = self.deserialize(read_rsp.Value, item_type) LOGGER.debug('Read NVRAM["LEGACY"][0x%04x] = %r', nv_id, value) return value # Every item has a length, even missing ones length = (await self.znp.request(c.SYS.OSALNVLength.Req(Id=nv_id))).ItemLen if length == 0: raise KeyError(f"NV item does not exist: {nv_id!r}") data = b"" try: while len(data) < length: read_rsp = await self.znp.request( c.SYS.OSALNVReadExt.Req(Id=nv_id, Offset=len(data)), RspStatus=t.Status.SUCCESS, ) data += read_rsp.Value except InvalidCommandResponse as e: # Only expected status code is INVALID_PARAMETER assert e.response.Status == t.Status.INVALID_PARAMETER # Not all items can be read out due to security policies, though this can # easily be bypassed for some. The SAPI "ConfigId" is only 8 bits which # means some nvids are not able to read this way. if not self.znp.capabilities & t.MTCapabilities.SAPI or nv_id > 0xFF: raise SecurityError( f"NV item cannot be read due to security constraints: {nv_id!r}" ) read_rsp = await self.znp.request( c.SAPI.ZBReadConfiguration.Req(ConfigId=nv_id), RspStatus=t.Status.SUCCESS, RspConfigId=nv_id, ) data = read_rsp.Value assert len(data) == length value = self.deserialize(data, item_type) LOGGER.debug('Read NVRAM["LEGACY"][0x%04x] = %r', nv_id, value) return value async def delete( self, *, sys_id: t.uint8_t = nvids.NvSysIds.ZSTACK, item_id: t.uint16_t, sub_id: t.uint16_t, ) -> bool: """ Deletes a subitem from NVRAM. Returns whether or not the item existed. """ delete_rsp = await self.znp.request( c.SYS.NVDelete.Req(SysId=sys_id, ItemId=item_id, SubId=sub_id) ) return delete_rsp.Status == t.Status.SUCCESS async def write( self, *, sys_id: t.uint8_t = nvids.NvSysIds.ZSTACK, item_id: t.uint16_t, sub_id: t.uint16_t, value, create: bool = True, ) -> None: """ Writes a value to NVRAM for the specified subsystem, item, and subitem. Calls to OSALNVWrite(sub_id=1) in newer Z-Stack releases are really calls to NVWrite(sys_id=ZSTACK, item_id=LEGACY, sub_id=1) in the background. """ value = self.serialize(value) length = ( await self.znp.request( c.SYS.NVLength.Req(SysId=sys_id, ItemId=item_id, SubId=sub_id) ) ).Length if length != len(value) and not ( sys_id == nvids.NvSysIds.ZSTACK and item_id in PROXIED_NVIDS and sub_id == 0x0000 ): if not create: if length == 0: raise KeyError( f"NV item does not exist:" f" sys_id={sys_id!r} item_id={item_id!r} sub_id={sub_id!r}" ) else: raise ValueError( f"Stored length and actual length differ:" f" {length} != {len(value)}" ) if length != 0: await self.znp.request( c.SYS.NVDelete.Req(SysId=sys_id, ItemId=item_id, SubId=sub_id), RspStatus=t.Status.SUCCESS, ) create_rsp = await self.znp.request( c.SYS.NVCreate.Req( SysId=sys_id, ItemId=item_id, SubId=sub_id, Length=len(value), ) ) if create_rsp.Status not in (t.Status.SUCCESS, t.Status.NV_ITEM_UNINIT): raise InvalidCommandResponse("Bad create status", create_rsp) # 244 bytes is the most you can fit in a single `SYS.NVWrite` command for offset in range(0, len(value), 244): await self.znp.request( c.SYS.NVWrite.Req( SysId=sys_id, ItemId=item_id, SubId=sub_id, Value=t.ShortBytes(value[offset : offset + 244]), Offset=0, ), RspStatus=t.Status.SUCCESS, ) async def read( self, *, sys_id: t.uint8_t = nvids.NvSysIds.ZSTACK, item_id: t.uint16_t, sub_id: t.uint16_t, item_type, ) -> bytes: """ Reads a value from NVRAM for the specified subsystem, item, and subitem. Calls to OSALNVRead(sub_id=1) in newer Z-Stack releases are really calls to NVRead(sys_id=ZSTACK, item_id=LEGACY, sub_id=1) in the background. Raises an `KeyError` error if the NVID doesn't exist. """ length_rsp = await self.znp.request( c.SYS.NVLength.Req(SysId=sys_id, ItemId=item_id, SubId=sub_id) ) length = length_rsp.Length if length == 0: raise KeyError( f"NV item does not exist:" f" sys_id={sys_id!r} item_id={item_id!r} sub_id={sub_id!r}" ) data = b"" while len(data) < length: read_rsp = await self.znp.request( c.SYS.NVRead.Req( SysId=sys_id, ItemId=item_id, SubId=sub_id, Offset=len(data), Length=length, ), RspStatus=t.Status.SUCCESS, ) data += read_rsp.Value assert len(data) == length value = self.deserialize(data, item_type) LOGGER.debug("Read NVRAM[%s][%s][0x%04x] = %r", sys_id, item_id, sub_id, value) return value async def write_table( self, *, sys_id: t.uint8_t = nvids.NvSysIds.ZSTACK, item_id: t.uint16_t, values, fill_value, ) -> None: for sub_id, value in itertools.zip_longest( range(0x0000, 0xFFFF + 1), values, fillvalue=fill_value ): value = self.serialize(value) try: await self.write( sys_id=sys_id, item_id=item_id, sub_id=sub_id, value=value, create=False, ) except KeyError: break async def osal_write_table( self, start_nvid: t.uint16_t, end_nvid: t.uint16_t, values, *, fill_value ) -> None: values = list(values) for nvid, value in itertools.zip_longest( range(start_nvid, end_nvid + 1), values, fillvalue=fill_value ): value = self.serialize(value) try: await self.osal_write( nv_id=nvid, value=value, create=False, ) except KeyError: break async def read_table( self, *, sys_id: t.uint8_t = nvids.NvSysIds.ZSTACK, item_id: t.uint16_t, item_type=t.Bytes, ): for sub_id in range(0x0000, 0xFFFF + 1): try: yield await self.read( sys_id=sys_id, item_id=item_id, sub_id=sub_id, item_type=item_type, ) except KeyError: break async def osal_read_table( self, start_nvid: t.uint16_t, end_nvid: t.uint16_t, item_type=t.Bytes, ): for nvid in range(start_nvid, end_nvid + 1): try: yield await self.osal_read(nvid, item_type=item_type) except KeyError: break
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/nvram.py
nvram.py
from __future__ import annotations import typing import asyncio import logging import zigpy.serial import zigpy_znp.config as conf import zigpy_znp.frames as frames import zigpy_znp.logger as log from zigpy_znp.types import Bytes from zigpy_znp.exceptions import InvalidFrame LOGGER = logging.getLogger(__name__) class BufferTooShort(Exception): pass class ZnpMtProtocol(asyncio.Protocol): def __init__(self, api, *, url: str | None = None) -> None: self._buffer = bytearray() self._api = api self._transport = None self._connected_event = asyncio.Event() self.url = url def close(self) -> None: """Closes the port.""" self._api = None self._buffer.clear() if self._transport is not None: LOGGER.debug("Closing serial port") self._transport.close() self._transport = None def connection_lost(self, exc: Exception | None) -> None: """Connection lost.""" if exc is not None: LOGGER.warning("Lost connection", exc_info=exc) if self._api is not None: self._api.connection_lost(exc) def connection_made(self, transport: asyncio.BaseTransport) -> None: """Opened serial port.""" self._transport = transport LOGGER.debug("Opened %s serial port", self.url) self._connected_event.set() if self._api is not None: self._api.connection_made() def data_received(self, data: bytes) -> None: """Callback when data is received.""" self._buffer += data LOGGER.log(log.TRACE, "Received data: %s", Bytes.__repr__(data)) for frame in self._extract_frames(): LOGGER.log(log.TRACE, "Parsed frame: %s", frame) try: self._api.frame_received(frame.payload) except Exception as e: LOGGER.error( "Received an exception while passing frame to API: %s", frame, exc_info=e, ) def send(self, payload: frames.GeneralFrame) -> None: """Sends data taking care of framing.""" self.write(frames.TransportFrame(payload).serialize()) def write(self, data: bytes) -> None: """ Writes raw bytes to the transport. This method should be used instead of directly writing to the transport with `transport.write`. """ LOGGER.log(log.TRACE, "Sending data: %s", Bytes.__repr__(data)) self._transport.write(data) def set_dtr_rts(self, *, dtr: bool, rts: bool) -> None: # TCP transport does not have DTR or RTS pins if not hasattr(self._transport, "serial"): return LOGGER.debug("Setting serial pin states: DTR=%s, RTS=%s", dtr, rts) self._transport.serial.dtr = dtr self._transport.serial.rts = rts def _extract_frames(self) -> typing.Iterator[frames.TransportFrame]: """Extracts frames from the buffer until it is exhausted.""" while True: try: yield self._extract_frame() except BufferTooShort: # If the buffer is too short, there is nothing more we can do break except InvalidFrame: # If the buffer contains invalid data, drop it until we find the SoF sof_index = self._buffer.find(frames.TransportFrame.SOF, 1) if sof_index < 0: # If we don't have a SoF in the buffer, drop everything self._buffer.clear() else: del self._buffer[:sof_index] def _extract_frame(self) -> frames.TransportFrame: """Extracts a single frame from the buffer.""" # The shortest possible frame is 5 bytes long if len(self._buffer) < 5: raise BufferTooShort() # The buffer must start with a SoF if self._buffer[0] != frames.TransportFrame.SOF: raise InvalidFrame() length = self._buffer[1] # If the packet length field exceeds 250, our packet is not valid if length > 250: raise InvalidFrame() # Don't bother deserializing anything if the packet is too short # [SoF:1] [Length:1] [Command:2] [Data:(Length)] [FCS:1] if len(self._buffer) < length + 5: raise BufferTooShort() # At this point we should have a complete frame # If not, deserialization will fail and the error will propapate up frame, rest = frames.TransportFrame.deserialize(self._buffer) # If we get this far then we have a valid frame. Update the buffer. del self._buffer[: len(self._buffer) - len(rest)] return frame def __repr__(self) -> str: return ( f"<" f"{type(self).__name__} connected to {self.url!r}" f" (api: {self._api})" f">" ) async def connect(config: conf.ConfigType, api) -> ZnpMtProtocol: loop = asyncio.get_running_loop() port = config[conf.CONF_DEVICE_PATH] baudrate = config[conf.CONF_DEVICE_BAUDRATE] flow_control = config[conf.CONF_DEVICE_FLOW_CONTROL] LOGGER.debug("Connecting to %s at %s baud", port, baudrate) _, protocol = await zigpy.serial.create_serial_connection( loop=loop, protocol_factory=lambda: ZnpMtProtocol(api, url=port), url=port, baudrate=baudrate, xonxoff=(flow_control == "software"), rtscts=(flow_control == "hardware"), ) await protocol._connected_event.wait() LOGGER.debug("Connected to %s at %s baud", port, baudrate) return protocol
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/uart.py
uart.py
import typing import numbers import voluptuous as vol from zigpy.config import ( # noqa: F401 CONF_NWK, CONF_DEVICE, CONF_NWK_KEY, CONFIG_SCHEMA, SCHEMA_DEVICE, CONF_NWK_PAN_ID, CONF_DEVICE_PATH, CONF_NWK_CHANNEL, CONF_NWK_CHANNELS, CONF_NWK_UPDATE_ID, CONF_NWK_TC_ADDRESS, CONF_NWK_TC_LINK_KEY, CONF_NWK_EXTENDED_PAN_ID, CONF_MAX_CONCURRENT_REQUESTS, cv_boolean, ) from zigpy_znp.commands.util import LEDMode ConfigType = typing.Dict[str, typing.Any] VolPositiveNumber = vol.All(numbers.Real, vol.Range(min=0)) CONF_DEVICE_BAUDRATE = "baudrate" CONF_DEVICE_FLOW_CONTROL = "flow_control" SCHEMA_DEVICE = SCHEMA_DEVICE.extend( { vol.Optional(CONF_DEVICE_BAUDRATE, default=115_200): int, vol.Optional(CONF_DEVICE_FLOW_CONTROL, default=None): vol.In( ("hardware", "software", None) ), } ) def EnumValue(enum, transformer=str): def validator(v): if isinstance(v, enum): return v return enum[transformer(v)] return validator def keys_have_same_length(*keys): def validator(config): lengths = [len(config[k]) for k in keys] if len(set(lengths)) != 1: raise vol.Invalid( f"Values for {keys} must all have the same length: {lengths}" ) return config return validator def bool_to_upper_str(value: typing.Any) -> str: """ Converts the value into an uppercase string, including unquoted YAML booleans. """ if value is True: return "ON" elif value is False: return "OFF" else: return str(value).upper() def cv_deprecated(message: str) -> typing.Callable[[typing.Any], None]: """ Raises a deprecation exception when a value is passed in. """ def validator(value: typing.Any) -> None: if value is not None: raise vol.Invalid(message) return validator CONF_ZNP_CONFIG = "znp_config" CONF_TX_POWER = "tx_power" CONF_LED_MODE = "led_mode" CONF_SKIP_BOOTLOADER = "skip_bootloader" CONF_SREQ_TIMEOUT = "sync_request_timeout" CONF_ARSP_TIMEOUT = "async_response_timeout" CONF_PREFER_ENDPOINT_1 = "prefer_endpoint_1" CONF_AUTO_RECONNECT_RETRY_DELAY = "auto_reconnect_retry_delay" CONF_CONNECT_RTS_STATES = "connect_rts_pin_states" CONF_CONNECT_DTR_STATES = "connect_dtr_pin_states" CONFIG_SCHEMA = CONFIG_SCHEMA.extend( { vol.Required(CONF_DEVICE): SCHEMA_DEVICE, vol.Optional(CONF_ZNP_CONFIG, default={}): vol.Schema( vol.All( { vol.Optional(CONF_TX_POWER, default=None): vol.Any( None, vol.All(int, vol.Range(min=-22, max=22)) ), vol.Optional(CONF_SREQ_TIMEOUT, default=15): VolPositiveNumber, vol.Optional(CONF_ARSP_TIMEOUT, default=30): VolPositiveNumber, vol.Optional( CONF_AUTO_RECONNECT_RETRY_DELAY, default=5 ): VolPositiveNumber, vol.Optional(CONF_SKIP_BOOTLOADER, default=True): cv_boolean, vol.Optional(CONF_PREFER_ENDPOINT_1, default=True): cv_boolean, vol.Optional(CONF_LED_MODE, default=LEDMode.OFF): vol.Any( None, EnumValue(LEDMode, transformer=bool_to_upper_str) ), vol.Optional(CONF_MAX_CONCURRENT_REQUESTS, default=None): ( cv_deprecated( "`zigpy_config: znp_config: max_concurrent_requests` has" " been renamed to `zigpy_config: max_concurrent_requests`." ) ), vol.Optional( CONF_CONNECT_RTS_STATES, default=[False, True, False] ): vol.Schema([cv_boolean]), vol.Optional( CONF_CONNECT_DTR_STATES, default=[False, False, False] ): vol.Schema([cv_boolean]), }, keys_have_same_length(CONF_CONNECT_RTS_STATES, CONF_CONNECT_DTR_STATES), ) ), } )
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/config.py
config.py
from __future__ import annotations import typing import asyncio import inspect import logging import functools import dataclasses import zigpy_znp.types as t LOGGER = logging.getLogger(__name__) def deduplicate_commands( commands: typing.Iterable[t.CommandBase], ) -> tuple[t.CommandBase, ...]: """ Deduplicates an iterable of commands by folding more-specific commands into less- specific commands. Used to avoid triggering callbacks multiple times per packet. """ # We essentially need to find the "maximal" commands, if you treat the relationship # between two commands as a partial order. maximal_commands = [] # Command matching as a relation forms a partially ordered set. for command in commands: for index, other_command in enumerate(maximal_commands): if other_command.matches(command): # If the other command matches us, we are redundant break elif command.matches(other_command): # If we match another command, we replace it maximal_commands[index] = command break else: # Otherwise, we keep looking continue # pragma: no cover else: # If we matched nothing and nothing matched us, we extend the list maximal_commands.append(command) # The start of each chain is the maximal element return tuple(maximal_commands) @dataclasses.dataclass(frozen=True) class BaseResponseListener: matching_commands: tuple[t.CommandBase] def __post_init__(self): commands = deduplicate_commands(self.matching_commands) if not commands: raise ValueError("Cannot create a listener without any matching commands") # We're frozen so __setattr__ is disallowed object.__setattr__(self, "matching_commands", commands) def matching_headers(self) -> set[t.CommandHeader]: """ Returns the set of Z-Stack MT command headers for all the matching commands. """ return {response.header for response in self.matching_commands} def resolve(self, response: t.CommandBase) -> bool: """ Attempts to resolve the listener with a given response. Can be called with any command as an argument, including ones we don't match. """ if not any(c.matches(response) for c in self.matching_commands): return False return self._resolve(response) def _resolve(self, response: t.CommandBase) -> bool: """ Implemented by subclasses to handle matched commands. Return value indicates whether or not the listener has actually resolved, which can sometimes be unavoidable. """ raise NotImplementedError() # pragma: no cover def cancel(self): """ Implement by subclasses to cancel the listener. Return value indicates whether or not the listener is cancelable. """ raise NotImplementedError() # pragma: no cover @dataclasses.dataclass(frozen=True) class OneShotResponseListener(BaseResponseListener): """ A response listener that resolves a single future exactly once. """ future: asyncio.Future = dataclasses.field( default_factory=lambda: asyncio.get_running_loop().create_future() ) def _resolve(self, response: t.CommandBase) -> bool: if self.future.done(): # This happens if the UART receives multiple packets during the same # event loop step and all of them match this listener. Our Future's # add_done_callback will not fire synchronously and thus the listener # is never properly removed. This isn't going to break anything. LOGGER.debug("Future already has a result set: %s", self.future) return False self.future.set_result(response) return True def cancel(self): if not self.future.done(): self.future.cancel() return True @dataclasses.dataclass(frozen=True) class CallbackResponseListener(BaseResponseListener): """ A response listener with a sync or async callback that is never resolved. """ callback: typing.Callable[[t.CommandBase], typing.Any] def _resolve(self, response: t.CommandBase) -> bool: try: # https://github.com/python/mypy/issues/5485 result = self.callback(response) # type:ignore[misc] # Run coroutines in the background if asyncio.iscoroutine(result): asyncio.create_task(result) except Exception: LOGGER.warning( "Caught an exception while executing callback", exc_info=True ) # Callbacks are always resolved return True def cancel(self): # You can't cancel a callback return False class CatchAllResponse: """ Response-like object that matches every request. """ header = object() # sentinel def matches(self, other) -> bool: return True def combine_concurrent_calls( function: typing.CoroutineFunction, ) -> typing.CoroutineFunction: """ Decorator that allows concurrent calls to expensive coroutines to share a result. """ tasks = {} signature = inspect.signature(function) @functools.wraps(function) async def replacement(*args, **kwargs): bound = signature.bind(*args, **kwargs) bound.apply_defaults() # XXX: all args and kwargs are assumed to be hashable key = tuple(bound.arguments.items()) if key in tasks: return await tasks[key] tasks[key] = asyncio.create_task(function(*args, **kwargs)) try: return await tasks[key] finally: assert tasks[key].done() del tasks[key] return replacement
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/utils.py
utils.py
from __future__ import annotations import os import time import typing import asyncio import logging import itertools import contextlib import dataclasses import importlib.metadata from collections import Counter, defaultdict import zigpy.state import async_timeout import zigpy.zdo.types as zdo_t import zigpy.exceptions from zigpy.exceptions import NetworkNotFormed import zigpy_znp.const as const import zigpy_znp.types as t import zigpy_znp.config as conf import zigpy_znp.logger as log import zigpy_znp.commands as c from zigpy_znp import uart from zigpy_znp.nvram import NVRAMHelper from zigpy_znp.utils import ( CatchAllResponse, BaseResponseListener, OneShotResponseListener, CallbackResponseListener, ) from zigpy_znp.frames import GeneralFrame from zigpy_znp.exceptions import CommandNotRecognized, InvalidCommandResponse from zigpy_znp.types.nvids import ExNvIds, OsalNvIds if typing.TYPE_CHECKING: import typing_extensions LOGGER = logging.getLogger(__name__) # All of these are in seconds STARTUP_TIMEOUT = 15 AFTER_BOOTLOADER_SKIP_BYTE_DELAY = 2.5 NETWORK_COMMISSIONING_TIMEOUT = 60 BOOTLOADER_PIN_TOGGLE_DELAY = 0.15 CONNECT_PING_TIMEOUT = 0.50 CONNECT_PROBE_TIMEOUT = 10 NVRAM_MIGRATION_ID = 1 class ZNP: def __init__(self, config: conf.ConfigType): self._uart = None self._app = None self._config = config self._listeners = defaultdict(list) self._sync_request_lock = asyncio.Lock() self.capabilities = None # type: int self.version = None # type: float self.nvram = NVRAMHelper(self) self.network_info: zigpy.state.NetworkInfo = None self.node_info: zigpy.state.NodeInfo = None def set_application(self, app): assert self._app is None self._app = app async def detect_zstack_version(self) -> float: """ Feature detects the major version of Z-Stack running on the device. """ # Z-Stack 1.2 does not have the AppConfig subsystem if not self.capabilities & t.MTCapabilities.APP_CNF: return 1.2 try: # Only Z-Stack 3.30+ has the new NVRAM system await self.nvram.read( item_id=ExNvIds.TCLK_TABLE, sub_id=0x0000, item_type=t.Bytes, ) return 3.30 except KeyError: return 3.30 except CommandNotRecognized: return 3.0 async def _load_network_info(self, *, load_devices=False): """ Loads low-level network information from NVRAM. Loading key data greatly increases the runtime so it not enabled by default. """ from zigpy_znp.znp import security nib = await self.nvram.osal_read(OsalNvIds.NIB, item_type=t.NIB) if nib.nwkLogicalChannel == 0 or not nib.nwkKeyLoaded: raise NetworkNotFormed() # This NVRAM item is the very first thing initialized in `zgInit` if ( self.version >= 3.0 and await self.nvram.osal_read( OsalNvIds.BDBNODEISONANETWORK, item_type=t.uint8_t ) != 1 ): raise NetworkNotFormed() ieee = await self.nvram.osal_read(OsalNvIds.EXTADDR, item_type=t.EUI64) logical_type = await self.nvram.osal_read( OsalNvIds.LOGICAL_TYPE, item_type=t.DeviceLogicalType ) node_info = zigpy.state.NodeInfo( ieee=ieee, nwk=nib.nwkDevAddress, logical_type=zdo_t.LogicalType(logical_type), ) key_desc = await self.nvram.osal_read( OsalNvIds.NWK_ACTIVE_KEY_INFO, item_type=t.NwkKeyDesc ) nwk_frame_counter = await security.read_nwk_frame_counter( self, ext_pan_id=nib.extendedPANID ) version = await self.request(c.SYS.Version.Req()) network_info = zigpy.state.NetworkInfo( source=f"zigpy-znp@{importlib.metadata.version('zigpy-znp')}", extended_pan_id=nib.extendedPANID, pan_id=nib.nwkPanId, nwk_update_id=nib.nwkUpdateId, channel=nib.nwkLogicalChannel, channel_mask=nib.channelList, security_level=nib.SecurityLevel, network_key=zigpy.state.Key( key=key_desc.Key, seq=key_desc.KeySeqNum, tx_counter=nwk_frame_counter, rx_counter=0, partner_ieee=node_info.ieee, ), tc_link_key=zigpy.state.Key( key=const.DEFAULT_TC_LINK_KEY, seq=0, tx_counter=0, rx_counter=0, partner_ieee=node_info.ieee, ), children=[], nwk_addresses={}, key_table=[], stack_specific={}, metadata={"zstack": version.as_dict()}, ) tclk_seed = None if self.version > 1.2: try: tclk_seed = await self.nvram.osal_read( OsalNvIds.TCLK_SEED, item_type=t.KeyData ) except ValueError: if self.version != 3.0: raise # CC2531s that have been cross-flashed from 1.2 -> 3.0 can have NVRAM # entries from both. Ignore deserialization length errors for the # trailing data to allow them to be backed up. tclk_seed_value = await self.nvram.osal_read( OsalNvIds.TCLK_SEED, item_type=t.Bytes ) tclk_seed = self.nvram.deserialize( tclk_seed_value, t.KeyData, allow_trailing=True ) LOGGER.error( "Your adapter's NVRAM is inconsistent! Perform a network backup," " re-flash its firmware, and restore the backup." ) network_info.stack_specific = { "zstack": { "tclk_seed": tclk_seed.serialize().hex(), } } # This takes a few seconds if load_devices: for dev in await security.read_devices(self, tclk_seed=tclk_seed): if dev.node_info.nwk == 0xFFFE: dev = dev.replace( node_info=dataclasses.replace(dev.node_info, nwk=None) ) if dev.is_child: network_info.children.append(dev.node_info.ieee) if dev.node_info.nwk is not None: network_info.nwk_addresses[dev.node_info.ieee] = dev.node_info.nwk if dev.key is not None: network_info.key_table.append(dev.key) self.network_info = network_info self.node_info = node_info async def load_network_info(self, *, load_devices=False): """ Loads low-level network information from NVRAM. Loading key data greatly increases the runtime so it not enabled by default. """ try: await self._load_network_info(load_devices=load_devices) except KeyError as e: raise NetworkNotFormed() from e async def start_network(self): # Both startup sequences end with the same callback started_as_coordinator = self.wait_for_response( c.ZDO.StateChangeInd.Callback(State=t.DeviceState.StartedAsCoordinator) ) # Handle the startup progress messages async with self.capture_responses( [ c.ZDO.StateChangeInd.Callback( State=t.DeviceState.StartingAsCoordinator ), c.AppConfig.BDBCommissioningNotification.Callback( partial=True, Status=c.app_config.BDBCommissioningStatus.InProgress, ), ] ): try: if self.version > 1.2: # Z-Stack 3 uses the BDB subsystem commissioning_rsp = await self.request_callback_rsp( request=c.AppConfig.BDBStartCommissioning.Req( Mode=c.app_config.BDBCommissioningMode.NwkFormation ), RspStatus=t.Status.SUCCESS, callback=c.AppConfig.BDBCommissioningNotification.Callback( partial=True, RemainingModes=c.app_config.BDBCommissioningMode.NONE, ), timeout=NETWORK_COMMISSIONING_TIMEOUT, ) # This is the correct startup sequence according to the forums, # including the formation failure error. Success is only returned # when the network is first formed. if commissioning_rsp.Status not in ( c.app_config.BDBCommissioningStatus.FormationFailure, c.app_config.BDBCommissioningStatus.Success, ): raise zigpy.exceptions.FormationFailure( f"Network formation failed: {commissioning_rsp}" ) else: # In Z-Stack 1.2.2, StartupFromApp actually does what it says rsp = await self.request(c.ZDO.StartupFromApp.Req(StartDelay=100)) if rsp.State not in ( c.zdo.StartupState.NewNetworkState, c.zdo.StartupState.RestoredNetworkState, ): raise InvalidCommandResponse( f"Invalid startup response state: {rsp.State}", rsp ) # Both versions still end with this callback async with async_timeout.timeout(STARTUP_TIMEOUT): await started_as_coordinator except asyncio.TimeoutError as e: raise zigpy.exceptions.FormationFailure( "Network formation refused: there is too much RF interference." " Make sure your coordinator is on a USB 2.0 extension cable and" " away from any sources of interference, like USB 3.0 ports, SSDs," " 2.4GHz routers, motherboards, etc." ) from e LOGGER.debug("Waiting for NIB to stabilize") # Even though the device says it is "ready" at this point, it takes a few more # seconds for `_NIB.nwkState` to switch from `NwkState.NWK_INIT`. There does # not appear to be any user-facing MT command to read this information. while True: try: nib = await self.nvram.osal_read(OsalNvIds.NIB, item_type=t.NIB) except KeyError: pass else: LOGGER.debug("Current NIB is %s", nib) # Usually this works after the first attempt if nib.nwkLogicalChannel != 0 and nib.nwkPanId != 0xFFFE: break await asyncio.sleep(1) async def reset_network_info(self): """ Resets node network information and leaves the current network. """ # Delete any existing NV items that store formation state await self.nvram.osal_delete(OsalNvIds.HAS_CONFIGURED_ZSTACK1) await self.nvram.osal_delete(OsalNvIds.HAS_CONFIGURED_ZSTACK3) await self.nvram.osal_delete(OsalNvIds.ZIGPY_ZNP_MIGRATION_ID) await self.nvram.osal_delete(OsalNvIds.BDBNODEISONANETWORK) # Instruct Z-Stack to reset everything on the next boot await self.nvram.osal_write( OsalNvIds.STARTUP_OPTION, t.StartupOptions.ClearState | t.StartupOptions.ClearConfig, ) await self.reset() async def write_network_info( self, *, network_info: zigpy.state.NetworkInfo, node_info: zigpy.state.NodeInfo, ) -> None: """ Writes network and node state to NVRAM. """ from zigpy_znp.znp import security try: if not network_info.stack_specific.get("form_quickly", False): await self.reset_network_info() except InvalidCommandResponse as rsp: if rsp.response.Status != t.Status.NV_OPER_FAILED: raise # Sonoff Zigbee 3.0 USB Dongle Plus coordinators randomly fail with NVRAM # corruption. This seemingly can only be fixed by re-flashing the firmware. raise zigpy.exceptions.FormationFailure( "Network formation failed: NVRAM is corrupted, re-flash your adapter's" " firmware." ) # Form a network with completely random settings to get NVRAM to a known state for item, value in { OsalNvIds.PANID: t.uint16_t(0xFFFF), OsalNvIds.APS_USE_EXT_PANID: t.EUI64(os.urandom(8)), OsalNvIds.PRECFGKEY: os.urandom(16), # XXX: Z2M requires this item to be False OsalNvIds.PRECFGKEYS_ENABLE: t.Bool(False), # Z-Stack will scan all of thse channels during formation OsalNvIds.CHANLIST: const.STARTUP_CHANNELS, }.items(): await self.nvram.osal_write(item, value, create=True) # Z-Stack 3+ ignores `CHANLIST` if self.version > 1.2: await self.request( c.AppConfig.BDBSetChannel.Req( IsPrimary=True, Channel=const.STARTUP_CHANNELS ), RspStatus=t.Status.SUCCESS, ) await self.request( c.AppConfig.BDBSetChannel.Req( IsPrimary=False, Channel=t.Channels.NO_CHANNELS ), RspStatus=t.Status.SUCCESS, ) LOGGER.debug("Forming temporary network") await self.start_network() await self.reset() if network_info.stack_specific.get("form_quickly", False): await self.nvram.osal_write( OsalNvIds.ZIGPY_ZNP_MIGRATION_ID, t.uint8_t(NVRAM_MIGRATION_ID), create=True, ) return LOGGER.debug("Writing actual network settings") # Now that we have a formed network, update its state nib = await self.nvram.osal_read(OsalNvIds.NIB, item_type=t.NIB) nib = nib.replace( nwkDevAddress=node_info.nwk, nwkPanId=network_info.pan_id, extendedPANID=network_info.extended_pan_id, nwkUpdateId=network_info.nwk_update_id, nwkLogicalChannel=network_info.channel, channelList=network_info.channel_mask, SecurityLevel=network_info.security_level, nwkManagerAddr=network_info.nwk_manager_id, nwkCoordAddress=0x0000, ) key_info = t.NwkActiveKeyItems( Active=t.NwkKeyDesc( KeySeqNum=network_info.network_key.seq, Key=network_info.network_key.key, ), FrameCounter=network_info.network_key.tx_counter, ) nvram = { OsalNvIds.NIB: nib, OsalNvIds.APS_USE_EXT_PANID: network_info.extended_pan_id, OsalNvIds.EXTENDED_PAN_ID: network_info.extended_pan_id, OsalNvIds.PRECFGKEY: key_info.Active.Key, OsalNvIds.CHANLIST: network_info.channel_mask, # If the EXTADDR entry is deleted, Z-Stack resets it to the hardware address OsalNvIds.EXTADDR: ( None if node_info.ieee == t.EUI64.UNKNOWN else node_info.ieee ), OsalNvIds.LOGICAL_TYPE: t.DeviceLogicalType(node_info.logical_type), OsalNvIds.NWK_ACTIVE_KEY_INFO: key_info.Active, OsalNvIds.NWK_ALTERN_KEY_INFO: key_info.Active, } tclk_seed = None if self.version == 1.2: # TCLK_SEED is TCLK_TABLE_START in Z-Stack 1 nvram[OsalNvIds.TCLK_SEED] = t.TCLinkKey( ExtAddr=t.EUI64.convert("FF:FF:FF:FF:FF:FF:FF:FF"), # global Key=network_info.tc_link_key.key, TxFrameCounter=0, RxFrameCounter=0, ) else: if network_info.tc_link_key.key != const.DEFAULT_TC_LINK_KEY: LOGGER.warning( "TC link key is configured at build time in Z-Stack 3 and cannot be" " changed at runtime: %s", network_info.tc_link_key.key, ) if ( network_info.stack_specific is not None and network_info.stack_specific.get("zstack", {}).get("tclk_seed") ): tclk_seed = t.KeyData( bytes.fromhex(network_info.stack_specific["zstack"]["tclk_seed"]) ) else: tclk_seed = t.KeyData(os.urandom(16)) nvram[OsalNvIds.TCLK_SEED] = tclk_seed for key, value in nvram.items(): if value is None: await self.nvram.osal_delete(key) else: await self.nvram.osal_write(key, value, create=True) await security.write_nwk_frame_counter( self, network_info.network_key.tx_counter, ext_pan_id=network_info.extended_pan_id, ) devices = {} for ieee in network_info.children or []: devices[ieee] = security.StoredDevice( node_info=zigpy.state.NodeInfo( nwk=network_info.nwk_addresses.get(ieee, 0xFFFE), ieee=ieee, logical_type=zdo_t.LogicalType.EndDevice, ), key=None, is_child=True, ) for key in network_info.key_table or []: device = devices.get(key.partner_ieee) if device is None: device = security.StoredDevice( node_info=zigpy.state.NodeInfo( nwk=network_info.nwk_addresses.get(key.partner_ieee, 0xFFFE), ieee=key.partner_ieee, logical_type=None, ), key=None, is_child=False, ) devices[key.partner_ieee] = device.replace(key=key) LOGGER.debug("Writing children and keys") # Recompute the TCLK if necessary if self.version > 1.2: optimal_tclk_seed = security.find_optimal_tclk_seed( devices.values(), tclk_seed ) if tclk_seed != optimal_tclk_seed: LOGGER.warning( "Provided TCLK seed %s is not optimal, using %s instead.", tclk_seed, optimal_tclk_seed, ) await self.nvram.osal_write(OsalNvIds.TCLK_SEED, optimal_tclk_seed) tclk_seed = optimal_tclk_seed await security.write_devices( znp=self, devices=list(devices.values()), tclk_seed=tclk_seed, counter_increment=0, ) # Prevent an unnecessary NVRAM migration from running await self.nvram.osal_write( OsalNvIds.ZIGPY_ZNP_MIGRATION_ID, t.uint8_t(NVRAM_MIGRATION_ID), create=True ) if self.version == 1.2: await self.nvram.osal_write( OsalNvIds.HAS_CONFIGURED_ZSTACK1, const.ZSTACK_CONFIGURE_SUCCESS, create=True, ) else: await self.nvram.osal_write( OsalNvIds.HAS_CONFIGURED_ZSTACK3, const.ZSTACK_CONFIGURE_SUCCESS, create=True, ) # Reset after writing network settings to allow Z-Stack to recreate NVRAM items # that were intentionally deleted. await self.reset() LOGGER.debug("Done!") async def migrate_nvram(self) -> bool: """ Migrates NVRAM entries using the `ZIGPY_ZNP_MIGRATION_ID` NVRAM item. Returns `True` if a migration was performed, `False` otherwise. """ from zigpy_znp.znp import security try: migration_id = await self.nvram.osal_read( OsalNvIds.ZIGPY_ZNP_MIGRATION_ID, item_type=t.uint8_t ) except KeyError: migration_id = 0 initial_migration_id = migration_id # Migration 1: empty `ADDRMGR` entries are version-dependent and were improperly # written for CC253x devices. # # This migration is stateless and can safely be run more than once: # the only downside is that startup times increase by 10s on newer # coordinators, which is why the migration ID is persisted. if migration_id < 1: try: entries = await security.read_addr_manager_entries(self) except KeyError: pass else: fixed_entries = [] for entry in entries: if entry.extAddr != t.EUI64.convert("FF:FF:FF:FF:FF:FF:FF:FF"): fixed_entries.append(entry) elif self.version == 3.30: fixed_entries.append(const.EMPTY_ADDR_MGR_ENTRY_ZSTACK3) else: fixed_entries.append(const.EMPTY_ADDR_MGR_ENTRY_ZSTACK1) if entries != fixed_entries: LOGGER.warning( "Repairing %d invalid empty address manager entries (total %d)", sum(i != j for i, j in zip(entries, fixed_entries)), len(entries), ) await security.write_addr_manager_entries(self, fixed_entries) migration_id = 1 if initial_migration_id == migration_id: return False await self.nvram.osal_write( OsalNvIds.ZIGPY_ZNP_MIGRATION_ID, t.uint8_t(migration_id), create=True ) await self.reset() return True async def reset(self, *, wait_for_reset: bool = True) -> None: """ Performs a soft reset within Z-Stack. A hard reset resets the serial port, causing the device to disconnect. """ if wait_for_reset: await self.request_callback_rsp( request=c.SYS.ResetReq.Req(Type=t.ResetType.Soft), callback=c.SYS.ResetInd.Callback(partial=True), ) else: await self.request(c.SYS.ResetReq.Req(Type=t.ResetType.Soft)) @property def _port_path(self) -> str: return self._config[conf.CONF_DEVICE][conf.CONF_DEVICE_PATH] @property def _znp_config(self) -> conf.ConfigType: return self._config[conf.CONF_ZNP_CONFIG] async def _skip_bootloader(self) -> c.SYS.Ping.Rsp: """ Attempt to skip the bootloader and return the ping response. """ async def ping_task(): LOGGER.debug("Toggling RTS/DTR pins to skip bootloader or reset chip") # The default sequence is DTR=false and RTS toggling false/true/false for dtr, rts in zip( self._znp_config[conf.CONF_CONNECT_DTR_STATES], self._znp_config[conf.CONF_CONNECT_RTS_STATES], ): self._uart.set_dtr_rts(dtr=dtr, rts=rts) await asyncio.sleep(BOOTLOADER_PIN_TOGGLE_DELAY) # First, just try pinging try: async with async_timeout.timeout(CONNECT_PING_TIMEOUT): return await self.request(c.SYS.Ping.Req()) except asyncio.TimeoutError: pass # If that doesn't work, send the bootloader skip bytes and try again. # Sending a bunch at a time fixes UART issues when the radio was previously # probed with another library at a different baudrate. LOGGER.debug("Sending CC253x bootloader skip bytes") self._uart.write(256 * bytes([c.ubl.BootloaderRunMode.FORCE_RUN])) await asyncio.sleep(AFTER_BOOTLOADER_SKIP_BYTE_DELAY) # At this point we have nothing left to try while True: try: async with async_timeout.timeout(2 * CONNECT_PING_TIMEOUT): return await self.request(c.SYS.Ping.Req()) except asyncio.TimeoutError: pass async with self.capture_responses([CatchAllResponse()]) as responses: ping_task = asyncio.create_task(ping_task()) try: async with async_timeout.timeout(CONNECT_PROBE_TIMEOUT): result = await responses.get() except Exception: ping_task.cancel() raise else: LOGGER.debug("Radio is alive: %s", result) # Give the ping task a little bit extra time to finish. Radios often queue # requests so when the reset indication is received, they will all be # immediately answered if not ping_task.done(): LOGGER.debug("Giving ping task %0.2fs to finish", CONNECT_PING_TIMEOUT) try: async with async_timeout.timeout(CONNECT_PING_TIMEOUT): result = await ping_task # type:ignore[misc] except asyncio.TimeoutError: ping_task.cancel() if isinstance(result, c.SYS.Ping.Rsp): return result return await self.request(c.SYS.Ping.Req()) async def connect(self, *, test_port=True) -> None: """ Connects to the device specified by the "device" section of the config dict. The `test_port` kwarg allows port testing to be disabled, mainly to get into the bootloader. """ # So we cannot connect twice assert self._uart is None try: self._uart = await uart.connect(self._config[conf.CONF_DEVICE], self) # To allow the ZNP interface to be used for bootloader commands, we have to # prevent any data from being sent if test_port: # The reset indication callback is sent when some sticks start up self.capabilities = (await self._skip_bootloader()).Capabilities # We need to know how structs are packed to deserialize frames correctly await self.nvram.determine_alignment() self.version = await self.detect_zstack_version() LOGGER.debug("Detected Z-Stack %s", self.version) except (Exception, asyncio.CancelledError): LOGGER.debug("Connection to %s failed, cleaning up", self._port_path) self.close() raise LOGGER.debug("Connected to %s", self._uart.url) def connection_made(self) -> None: """ Called by the UART object when a connection has been made. """ def connection_lost(self, exc) -> None: """ Called by the UART object to indicate that the port was closed. Propagates up to the `ControllerApplication` that owns this ZNP instance. """ LOGGER.debug("We were disconnected from %s: %s", self._port_path, exc) if self._app is not None: self._app.connection_lost(exc) def close(self) -> None: """ Cleans up resources, namely the listener queues. Calling this will reset ZNP to the same internal state as a fresh ZNP instance. """ self._app = None for _header, listeners in self._listeners.items(): for listener in listeners: listener.cancel() self._listeners.clear() self.version = None self.capabilities = None if self._uart is not None: self._uart.close() self._uart = None def remove_listener(self, listener: BaseResponseListener) -> None: """ Unbinds a listener from ZNP. Used by `wait_for_responses` to remove listeners for completed futures, regardless of their completion reason. """ # If ZNP is closed while it's still running, `self._listeners` will be empty. if not self._listeners: return LOGGER.log(log.TRACE, "Removing listener %s", listener) for header in listener.matching_headers(): try: self._listeners[header].remove(listener) except ValueError: pass if not self._listeners[header]: LOGGER.log( log.TRACE, "Cleaning up empty listener list for header %s", header ) del self._listeners[header] counts = Counter() for listener in itertools.chain.from_iterable(self._listeners.values()): counts[type(listener)] += 1 LOGGER.log( log.TRACE, "There are %d callbacks and %d one-shot listeners remaining", counts[CallbackResponseListener], counts[OneShotResponseListener], ) def frame_received(self, frame: GeneralFrame) -> bool | None: """ Called when a frame has been received. Returns whether or not the frame was handled by any listener. XXX: Can be called multiple times in a single event loop step! """ if frame.header not in c.COMMANDS_BY_ID: LOGGER.error("Received an unknown frame: %s", frame) return False command_cls = c.COMMANDS_BY_ID[frame.header] try: command = command_cls.from_frame(frame, align=self.nvram.align_structs) except ValueError: # Some commands can be received corrupted. They are not useful: # https://github.com/home-assistant/core/issues/50005 if command_cls == c.ZDO.ParentAnnceRsp.Callback: LOGGER.warning("Failed to parse broken %s as %s", frame, command_cls) return False raise LOGGER.debug("Received command: %s", command) matched = False one_shot_matched = False for listener in ( self._listeners[command.header] + self._listeners[CatchAllResponse.header] ): # XXX: A single response should *not* resolve multiple one-shot listeners! # `future.add_done_callback` doesn't remove our listeners synchronously # so doesn't prevent this from happening. if one_shot_matched and isinstance(listener, OneShotResponseListener): continue if not listener.resolve(command): LOGGER.log(log.TRACE, "%s does not match %s", command, listener) continue matched = True LOGGER.log(log.TRACE, "%s matches %s", command, listener) if isinstance(listener, OneShotResponseListener): one_shot_matched = True if not matched: self._unhandled_command(command) return matched def _unhandled_command(self, command: t.CommandBase): """ Called when a command that is not handled by any listener is received. """ LOGGER.debug("Command was not handled") @contextlib.asynccontextmanager async def capture_responses(self, responses): """ Captures all matched responses in a queue within the context manager. """ queue = asyncio.Queue() listener = self.callback_for_responses(responses, callback=queue.put_nowait) try: yield queue finally: self.remove_listener(listener) def callback_for_responses(self, responses, callback) -> CallbackResponseListener: """ Creates a callback listener that matches any of the provided responses. Only exists for consistency with `wait_for_responses`, since callbacks can be executed more than once. """ listener = CallbackResponseListener(responses, callback=callback) LOGGER.log(log.TRACE, "Creating callback %s", listener) for header in listener.matching_headers(): self._listeners[header].append(listener) return listener def callback_for_response( self, response: t.CommandBase, callback ) -> CallbackResponseListener: """ Creates a callback listener for a single response. """ return self.callback_for_responses([response], callback) @typing.overload def wait_for_responses( self, responses, *, context: typing_extensions.Literal[False] = ... ) -> asyncio.Future: ... @typing.overload def wait_for_responses( self, responses, *, context: typing_extensions.Literal[True] ) -> tuple[asyncio.Future, OneShotResponseListener]: ... def wait_for_responses( self, responses, *, context: bool = False ) -> asyncio.Future | tuple[asyncio.Future, OneShotResponseListener]: """ Creates a one-shot listener that matches any *one* of the given responses. """ listener = OneShotResponseListener(responses) LOGGER.log(log.TRACE, "Creating one-shot listener %s", listener) for header in listener.matching_headers(): self._listeners[header].append(listener) # Remove the listener when the future is done, not only when it gets a result listener.future.add_done_callback(lambda _: self.remove_listener(listener)) if context: return listener.future, listener else: return listener.future def wait_for_response(self, response: t.CommandBase) -> asyncio.Future: """ Creates a one-shot listener for a single response. """ return self.wait_for_responses([response]) async def request( self, request: t.CommandBase, timeout: int | None = None, **response_params ) -> t.CommandBase | None: """ Sends a SREQ/AREQ request and returns its SRSP (only for SREQ), failing if any of the SRSP's parameters don't match `response_params`. """ # Common mistake is to do `znp.request(c.SYS.Ping())` if type(request) is not request.Req: raise ValueError(f"Cannot send a command that isn't a request: {request!r}") # Construct a partial response out of the `Rsp*` kwargs if one is provided if request.Rsp: renamed_response_params = {} for param, value in response_params.items(): if not param.startswith("Rsp"): raise KeyError( f"All response params must start with 'Rsp': {param!r}" ) renamed_response_params[param.replace("Rsp", "", 1)] = value # Construct our response before we send the request so that we fail early partial_response = request.Rsp(partial=True, **renamed_response_params) elif response_params: raise ValueError( f"Command has no response so response_params={response_params} " f"will have no effect" ) frame = request.to_frame(align=self.nvram.align_structs) if self._uart is None: raise RuntimeError("Coordinator is disconnected, cannot send request") # Immediately send reset requests ctx = ( contextlib.AsyncExitStack() if isinstance(request, c.SYS.ResetReq.Req) else self._sync_request_lock ) # We should only be sending one SREQ at a time, according to the spec async with ctx: LOGGER.debug("Sending request: %s", request) # If our request has no response, we cannot wait for one if not request.Rsp: LOGGER.debug("Request has no response, not waiting for one.") self._uart.send(frame) return None # We need to create the response listener before we send the request response_future = self.wait_for_responses( [ request.Rsp(partial=True), c.RPCError.CommandNotRecognized.Rsp( partial=True, RequestHeader=request.header ), ] ) self._uart.send(frame) # We should get a SRSP in a reasonable amount of time async with async_timeout.timeout( timeout or self._znp_config[conf.CONF_SREQ_TIMEOUT] ): # We lock until either a sync response is seen or an error occurs response = await response_future if isinstance(response, c.RPCError.CommandNotRecognized.Rsp): raise CommandNotRecognized( f"Fatal request error {response} in response to {request}" ) # If the sync response we got is not what we wanted, this is an error if not partial_response.matches(response): raise InvalidCommandResponse( f"Expected SRSP response {partial_response}, got {response}", response ) return response async def request_callback_rsp( self, *, request, callback, timeout=None, background=False, **response_params ): """ Sends an SREQ, gets its SRSP confirmation, and waits for its real AREQ response. A bug-free version of: req_rsp = await req callback_rsp = await req_callback This is necessary because the SRSP and the AREQ may arrive in the same "chunk" from the UART and be handled in the same event loop step by ZNP. """ # Every request should have a timeout to prevent deadlocks if timeout is None: timeout = self._znp_config[conf.CONF_ARSP_TIMEOUT] callback_rsp, listener = self.wait_for_responses([callback], context=True) # Typical request/response/callbacks are not backgrounded if not background: try: async with async_timeout.timeout(timeout): await self.request(request, timeout=timeout, **response_params) return await callback_rsp finally: self.remove_listener(listener) # Backgrounded callback handlers need to respect the provided timeout start_time = time.monotonic() try: async with async_timeout.timeout(timeout): request_rsp = await self.request(request, **response_params) except Exception: # If the SREQ/SRSP pair fails, we must cancel the AREQ listener self.remove_listener(listener) raise # If it succeeds, create a background task to receive the AREQ but take into # account the time it took to start the SREQ to ensure we do not grossly exceed # the timeout async def callback_catcher(timeout): try: async with async_timeout.timeout(timeout): await callback_rsp finally: self.remove_listener(listener) callback_timeout = max(0, timeout - (time.monotonic() - start_time)) asyncio.create_task(callback_catcher(callback_timeout)) return request_rsp
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/api.py
api.py
from __future__ import annotations import os import asyncio import logging import itertools import zigpy.zcl import zigpy.zdo import zigpy.util import zigpy.state import zigpy.types import zigpy.config import zigpy.device import async_timeout import zigpy.profiles import zigpy.zdo.types as zdo_t import zigpy.application import zigpy.config.defaults from zigpy.exceptions import DeliveryError import zigpy_znp.const as const import zigpy_znp.types as t import zigpy_znp.config as conf import zigpy_znp.commands as c from zigpy_znp.api import ZNP from zigpy_znp.utils import combine_concurrent_calls from zigpy_znp.exceptions import CommandNotRecognized, InvalidCommandResponse from zigpy_znp.types.nvids import OsalNvIds from zigpy_znp.zigbee.device import ZNPCoordinator ZDO_ENDPOINT = 0 ZHA_ENDPOINT = 1 ZDO_PROFILE = 0x0000 # All of these are in seconds PROBE_TIMEOUT = 5 STARTUP_TIMEOUT = 5 DATA_CONFIRM_TIMEOUT = 8 EXTENDED_DATA_CONFIRM_TIMEOUT = 30 DEVICE_JOIN_MAX_DELAY = 5 WATCHDOG_PERIOD = 30 REQUEST_MAX_RETRIES = 5 REQUEST_ERROR_RETRY_DELAY = 0.5 # Errors that go away on their own after waiting for a bit REQUEST_TRANSIENT_ERRORS = { t.Status.BUFFER_FULL, t.Status.MAC_CHANNEL_ACCESS_FAILURE, t.Status.MAC_TRANSACTION_OVERFLOW, t.Status.MAC_NO_RESOURCES, t.Status.MEM_ERROR, t.Status.NWK_TABLE_FULL, } REQUEST_ROUTING_ERRORS = { t.Status.APS_NO_ACK, t.Status.APS_NOT_AUTHENTICATED, t.Status.NWK_NO_ROUTE, t.Status.NWK_INVALID_REQUEST, t.Status.MAC_NO_ACK, t.Status.MAC_TRANSACTION_EXPIRED, } REQUEST_RETRYABLE_ERRORS = REQUEST_TRANSIENT_ERRORS | REQUEST_ROUTING_ERRORS LOGGER = logging.getLogger(__name__) class RetryMethod(t.enum_flag_uint8): NONE = 0 AssocRemove = 2 << 0 RouteDiscovery = 2 << 1 LastGoodRoute = 2 << 2 IEEEAddress = 2 << 3 class ControllerApplication(zigpy.application.ControllerApplication): SCHEMA = conf.CONFIG_SCHEMA SCHEMA_DEVICE = conf.SCHEMA_DEVICE def __init__(self, config: conf.ConfigType): super().__init__(config=conf.CONFIG_SCHEMA(config)) self._znp: ZNP | None = None # It's simpler to work with Task objects if they're never actually None self._reconnect_task: asyncio.Future = asyncio.Future() self._reconnect_task.cancel() self._watchdog_task: asyncio.Future = asyncio.Future() self._watchdog_task.cancel() self._version_rsp = None self._join_announce_tasks: dict[t.EUI64, asyncio.TimerHandle] = {} ################################################################## # Implementation of the core zigpy ControllerApplication methods # ################################################################## @classmethod async def probe(cls, device_config): try: async with async_timeout.timeout(PROBE_TIMEOUT): return await super().probe(device_config) except asyncio.TimeoutError: return False async def connect(self): assert self._znp is None znp = ZNP(self.config) await znp.connect() # We only assign `self._znp` after it has successfully connected self._znp = znp self._znp.set_application(self) self._bind_callbacks() async def disconnect(self): self._reconnect_task.cancel() self._watchdog_task.cancel() if self._znp is not None: try: await self._znp.reset(wait_for_reset=False) except Exception as e: LOGGER.warning("Failed to reset before disconnect: %s", e) finally: self._znp.close() self._znp = None def close(self): self._reconnect_task.cancel() self._watchdog_task.cancel() # This will close the UART, which will then close the transport if self._znp is not None: self._znp.close() self._znp = None async def add_endpoint(self, descriptor: zdo_t.SimpleDescriptor) -> None: """ Registers a new endpoint on the device. """ await self._znp.request( c.AF.Register.Req( Endpoint=descriptor.endpoint, ProfileId=descriptor.profile, DeviceId=descriptor.device_type, DeviceVersion=descriptor.device_version, LatencyReq=c.af.LatencyReq.NoLatencyReqs, InputClusters=descriptor.input_clusters, OutputClusters=descriptor.output_clusters, ), RspStatus=t.Status.SUCCESS, ) async def load_network_info(self, *, load_devices=False) -> None: """ Loads network information from NVRAM. """ await self._znp.load_network_info(load_devices=load_devices) self.state.node_info = self._znp.node_info self.state.network_info = self._znp.network_info async def reset_network_info(self) -> None: """ Resets node network information and leaves the current network. """ await self._znp.reset_network_info() async def write_network_info( self, *, network_info: zigpy.state.NetworkInfo, node_info: zigpy.state.NodeInfo, ) -> None: """ Writes network and node state to NVRAM. """ network_info.stack_specific.setdefault("zstack", {}) if "tclk_seed" not in network_info.stack_specific["zstack"]: network_info.stack_specific["zstack"]["tclk_seed"] = os.urandom(16).hex() await self._znp.write_network_info( network_info=network_info, node_info=node_info ) async def start_network(self, *, read_only=False): if self.state.node_info == zigpy.state.NodeInfo(): await self.load_network_info() if not read_only: await self._znp.migrate_nvram() await self._write_stack_settings() await self._znp.reset() if self.znp_config[conf.CONF_TX_POWER] is not None: await self.set_tx_power(dbm=self.znp_config[conf.CONF_TX_POWER]) await self._znp.start_network() self._version_rsp = await self._znp.request(c.SYS.Version.Req()) # The CC2531 running Z-Stack Home 1.2 overrides the LED setting if it is changed # before the coordinator has started. if self.znp_config[conf.CONF_LED_MODE] is not None: await self._set_led_mode(led=0xFF, mode=self.znp_config[conf.CONF_LED_MODE]) await self.register_endpoints() # Receive a callback for every known ZDO command await self._znp.request(c.ZDO.MsgCallbackRegister.Req(ClusterId=0xFFFF)) # Setup the coordinator as a zigpy device and initialize it to request node info self.devices[self.state.node_info.ieee] = ZNPCoordinator( self, self.state.node_info.ieee, self.state.node_info.nwk ) await self._device.schedule_initialize() # Deprecate ZNP-specific config if self.znp_config[conf.CONF_MAX_CONCURRENT_REQUESTS] is not None: raise RuntimeError( "`zigpy_config:znp_config:max_concurrent_requests` is deprecated," " move this key up to `zigpy_config:max_concurrent_requests` instead." ) # Now that we know what device we are, set the max concurrent requests if self._config[conf.CONF_MAX_CONCURRENT_REQUESTS] in ( None, zigpy.config.defaults.CONF_MAX_CONCURRENT_REQUESTS_DEFAULT, ): max_concurrent_requests = 16 if self._znp.nvram.align_structs else 2 else: max_concurrent_requests = self._config[conf.CONF_MAX_CONCURRENT_REQUESTS] # Update the max value of the concurrent request semaphore at runtime self._concurrent_requests_semaphore.max_value = max_concurrent_requests if self.state.network_info.network_key.key == const.Z2M_NETWORK_KEY: LOGGER.warning( "Your network is using the insecure Zigbee2MQTT network key!" ) self._watchdog_task = asyncio.create_task(self._watchdog_loop()) async def set_tx_power(self, dbm: int) -> None: """ Sets the radio TX power. """ rsp = await self._znp.request(c.SYS.SetTxPower.Req(TXPower=dbm)) if self._znp.version >= 3.30 and rsp.StatusOrPower != t.Status.SUCCESS: # Z-Stack 3's response indicates success or failure raise InvalidCommandResponse( f"Failed to set TX power: {t.Status(rsp.StatusOrPower & 0xFF)!r}", rsp ) elif self._znp.version < 3.30 and rsp.StatusOrPower != dbm: # Old Z-Stack releases used the response status field to indicate the power # setting that was actually applied LOGGER.warning( "Requested TX power %d was adjusted to %d", dbm, rsp.StatusOrPower ) def get_dst_address(self, cluster: zigpy.zcl.Cluster) -> zdo_t.MultiAddress: """ Helper to get a dst address for bind/unbind operations. Allows radios to provide correct information, especially for radios which listen on specific endpoints only. """ dst_addr = zdo_t.MultiAddress() dst_addr.addrmode = 0x03 dst_addr.ieee = self.state.node_info.ieee dst_addr.endpoint = self._find_endpoint( dst_ep=cluster.endpoint.endpoint_id, profile=cluster.endpoint.profile_id, cluster=cluster.cluster_id, ) return dst_addr async def permit(self, time_s: int = 60, node: t.EUI64 = None): """ Permit joining the network via a specific node or via all router nodes. """ LOGGER.info("Permitting joins for %d seconds", time_s) # If joins were permitted through a specific router, older Z-Stack builds # did not allow the key to be distributed unless the coordinator itself was # also permitting joins. This also needs to happen if we're permitting joins # through the coordinator itself. # # Fixed in https://github.com/Koenkk/Z-Stack-firmware/commit/efac5ee46b9b437 if ( time_s == 0 or self._zstack_build_id < 20210708 or node == self.state.node_info.ieee ): response = await self._znp.request_callback_rsp( request=c.ZDO.MgmtPermitJoinReq.Req( AddrMode=t.AddrMode.NWK, Dst=self.state.node_info.nwk, Duration=time_s, TCSignificance=1, ), RspStatus=t.Status.SUCCESS, callback=c.ZDO.MgmtPermitJoinRsp.Callback( Src=self.state.node_info.nwk, partial=True ), ) if response.Status != t.Status.SUCCESS: raise RuntimeError(f"Failed to permit joins on coordinator: {response}") await super().permit(time_s=time_s, node=node) async def permit_ncp(self, time_s: int) -> None: """ Permits joins only on the coordinator. """ # Z-Stack does not need any special code to do this async def force_remove(self, dev: zigpy.device.Device) -> None: """ Send a lower-level leave command to the device """ # Z-Stack does not have any way to do this async def permit_with_key(self, node: t.EUI64, code: bytes, time_s=60): """ Permits a new device to join with the given IEEE and Install Code. """ key = zigpy.util.convert_install_code(code) install_code_format = c.app_config.InstallCodeFormat.KeyDerivedFromInstallCode if key is None: raise ValueError(f"Invalid install code: {code!r}") await self._znp.request( c.AppConfig.BDBAddInstallCode.Req( InstallCodeFormat=install_code_format, IEEE=node, InstallCode=t.Bytes(key), ), RspStatus=t.Status.SUCCESS, ) # Temporarily only allow joins that use an install code await self._znp.request( c.AppConfig.BDBSetJoinUsesInstallCodeKey.Req( BdbJoinUsesInstallCodeKey=True ), RspStatus=t.Status.SUCCESS, ) try: await self.permit(time_s) await asyncio.sleep(time_s) finally: # Revert back to normal. The BDB config is not persistent so if this request # fails, we will be back to normal the next time Z-Stack resets. await self._znp.request( c.AppConfig.BDBSetJoinUsesInstallCodeKey.Req( BdbJoinUsesInstallCodeKey=False ), RspStatus=t.Status.SUCCESS, ) async def _move_network_to_channel( self, new_channel: int, new_nwk_update_id: int ) -> None: """Moves device to a new channel.""" await self._znp.request( request=c.ZDO.MgmtNWKUpdateReq.Req( Dst=0x0000, DstAddrMode=t.AddrMode.NWK, Channels=t.Channels.from_channel_list([new_channel]), ScanDuration=zdo_t.NwkUpdate.CHANNEL_CHANGE_REQ, ScanCount=0, NwkManagerAddr=0x0000, # `new_nwk_update_id` is ignored ), RspStatus=t.Status.SUCCESS, ) def connection_lost(self, exc): """ Propagated up from UART through ZNP when the connection is lost. Spawns the auto-reconnect task. """ LOGGER.debug("Connection lost: %s", exc) self.close() LOGGER.debug("Restarting background reconnection task") self._reconnect_task = asyncio.create_task(self._reconnect()) ##################################################### # Z-Stack message callbacks attached during startup # ##################################################### def _bind_callbacks(self) -> None: """ Binds all of the necessary message callbacks to their associated methods. Z-Stack intercepts most (but not all!) ZDO requests/responses and replaces them ZNP requests/responses. """ self._znp.callback_for_response( c.AF.IncomingMsg.Callback(partial=True), self.on_af_message ) self._znp.callback_for_response( c.ZDO.TCDevInd.Callback.Callback(partial=True), self.on_zdo_tc_device_join, ) self._znp.callback_for_response( c.ZDO.LeaveInd.Callback(partial=True), self.on_zdo_device_leave ) self._znp.callback_for_response( c.ZDO.SrcRtgInd.Callback(partial=True), self.on_zdo_relays_message ) self._znp.callback_for_response( c.ZDO.PermitJoinInd.Callback(partial=True), self.on_zdo_permit_join_message ) self._znp.callback_for_response( c.ZDO.MsgCbIncoming.Callback(partial=True), self.on_zdo_message ) # These are responses to a broadcast but we ignore all but the first self._znp.callback_for_response( c.ZDO.IEEEAddrRsp.Callback(partial=True), self.on_intentionally_unhandled_message, ) def on_intentionally_unhandled_message(self, msg: t.CommandBase) -> None: """ Some commands are unhandled but frequently sent by devices on the network. To reduce unnecessary logging messages, they are given an explicit callback. """ async def on_zdo_message(self, msg: c.ZDO.MsgCbIncoming.Callback) -> None: """ Global callback for all ZDO messages. """ try: zdo_t.ZDOCmd(msg.ClusterId) except ValueError: pass else: # Ignore loopback ZDO requests, only receive announcements and responses if zdo_t.ZDOCmd(msg.ClusterId).name.endswith(("_req", "_set")): LOGGER.debug("Ignoring loopback ZDO request") return if msg.IsBroadcast: dst = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.Broadcast, address=zigpy.types.BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR, ) else: dst = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=self.state.node_info.nwk, ) packet = zigpy.types.ZigbeePacket( src=zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=msg.Src, ), src_ep=ZDO_ENDPOINT, dst=dst, dst_ep=ZDO_ENDPOINT, tsn=msg.TSN, profile_id=ZDO_PROFILE, cluster_id=msg.ClusterId, data=t.SerializableBytes(t.uint8_t(msg.TSN).serialize() + msg.Data), tx_options=( zigpy.types.TransmitOptions.APS_Encryption if msg.SecurityUse else zigpy.types.TransmitOptions.NONE ), ) # Peek into the ZDO packet so that we can cancel our existing TC join timer when # a device actually sends an announcemement try: zdo_hdr, zdo_args = self._device.zdo.deserialize( cluster_id=packet.cluster_id, data=packet.data.serialize() ) except Exception: LOGGER.warning("Failed to deserialize ZDO packet", exc_info=True) else: if zdo_hdr.command_id == zdo_t.ZDOCmd.Device_annce: _, ieee, _ = zdo_args # Cancel any existing TC join timers so we don't double announce if ieee in self._join_announce_tasks: self._join_announce_tasks.pop(ieee).cancel() self.packet_received(packet) def on_zdo_permit_join_message(self, msg: c.ZDO.PermitJoinInd.Callback) -> None: """ Coordinator join status change message. Only sent with Z-Stack 1.2 and 3.0. """ if msg.Duration == 0: LOGGER.info("Coordinator is not permitting joins anymore") else: LOGGER.info("Coordinator is permitting joins for %d seconds", msg.Duration) async def on_zdo_relays_message(self, msg: c.ZDO.SrcRtgInd.Callback) -> None: """ ZDO source routing message callback """ self.handle_relays(nwk=msg.DstAddr, relays=msg.Relays) def on_zdo_tc_device_join(self, msg: c.ZDO.TCDevInd.Callback) -> None: """ ZDO trust center device join callback. """ LOGGER.info("TC device join: %s", msg) # Perform route discovery (just in case) when a device joins the network so that # we can begin initialization as soon as possible. asyncio.create_task(self._discover_route(msg.SrcNwk)) if msg.SrcIEEE in self._join_announce_tasks: self._join_announce_tasks.pop(msg.SrcIEEE).cancel() # If the device already exists, immediately trigger a join to update its NWK. try: self.get_device(ieee=msg.SrcIEEE) except KeyError: pass else: self.handle_join( nwk=msg.SrcNwk, ieee=msg.SrcIEEE, parent_nwk=msg.ParentNwk, ) return # Some devices really don't like zigpy beginning its initialization process # before the device has announced itself. Wait a second or two before calling # `handle_join`, just in case the device announces itself first. self._join_announce_tasks[msg.SrcIEEE] = asyncio.get_running_loop().call_later( DEVICE_JOIN_MAX_DELAY, lambda: self.handle_join( nwk=msg.SrcNwk, ieee=msg.SrcIEEE, parent_nwk=msg.ParentNwk, ), ) def on_zdo_device_leave(self, msg: c.ZDO.LeaveInd.Callback) -> None: LOGGER.info("ZDO device left: %s", msg) self.handle_leave(nwk=msg.NWK, ieee=msg.IEEE) async def on_af_message(self, msg: c.AF.IncomingMsg.Callback) -> None: """ Handler for all non-ZDO messages. """ # XXX: Is it possible to receive messages on non-assigned endpoints? if msg.DstEndpoint != 0 and msg.DstEndpoint in self._device.endpoints: profile = self._device.endpoints[msg.DstEndpoint].profile_id else: LOGGER.warning("Received a message on an unregistered endpoint: %s", msg) profile = zigpy.profiles.zha.PROFILE_ID if msg.WasBroadcast: dst = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.Broadcast, address=zigpy.types.BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR, ) elif msg.GroupId != 0x0000: dst = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.Group, address=msg.GroupId, ) else: dst = zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=self.state.node_info.nwk, ) self.packet_received( zigpy.types.ZigbeePacket( src=zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=msg.SrcAddr ), src_ep=msg.SrcEndpoint, dst=dst, dst_ep=msg.DstEndpoint, tsn=msg.TSN, profile_id=profile, cluster_id=msg.ClusterId, data=t.SerializableBytes(bytes(msg.Data)), tx_options=( zigpy.types.TransmitOptions.APS_Encryption if msg.SecurityUse else zigpy.types.TransmitOptions.NONE ), radius=msg.MsgResultRadius, lqi=msg.LQI, rssi=None, ) ) #################### # Internal methods # #################### @property def _zstack_build_id(self) -> t.uint32_t: """ Z-Stack build ID, more recently the build date. """ # Old versions of Z-Stack do not include `CodeRevision` in the version response if self._version_rsp.CodeRevision is None: return t.uint32_t(0x00000000) return self._version_rsp.CodeRevision @property def znp_config(self) -> conf.ConfigType: """ Shortcut property to access the ZNP radio config. """ return self.config[conf.CONF_ZNP_CONFIG] async def _watchdog_loop(self): """ Watchdog loop to periodically test if Z-Stack is still running. """ LOGGER.debug("Starting watchdog loop") while True: await asyncio.sleep(WATCHDOG_PERIOD) # No point in trying to test the port if it's already disconnected if self._znp is None: break try: await self._znp.request(c.SYS.Ping.Req()) except Exception as e: LOGGER.error( "Watchdog check failed", exc_info=e, ) # Treat the watchdog failure as a disconnect self.connection_lost(e) return async def _set_led_mode(self, *, led: t.uint8_t, mode: c.util.LEDMode) -> None: """ Attempts to set the provided LED's mode. A Z-Stack bug causes the underlying command to never receive a response if the board has no LEDs, requiring this wrapper function to prevent the command from taking many seconds to time out. """ # XXX: If Z-Stack is not compiled with HAL_LED, it will just not respond at all try: async with async_timeout.timeout(0.5): await self._znp.request( c.UTIL.LEDControl.Req(LED=led, Mode=mode), RspStatus=t.Status.SUCCESS, ) except (asyncio.TimeoutError, CommandNotRecognized): LOGGER.info("This build of Z-Stack does not appear to support LED control") async def _write_stack_settings(self) -> bool: """ Writes network-independent Z-Stack settings to NVRAM. If no settings actually change, no reset will be performed. """ # It's better to be explicit than rely on the NVRAM defaults settings = { OsalNvIds.LOGICAL_TYPE: t.uint8_t(self.state.node_info.logical_type), # Source routing OsalNvIds.CONCENTRATOR_ENABLE: t.Bool(True), OsalNvIds.CONCENTRATOR_DISCOVERY: t.uint8_t(120), OsalNvIds.CONCENTRATOR_RC: t.Bool(True), OsalNvIds.SRC_RTG_EXPIRY_TIME: t.uint8_t(255), OsalNvIds.NWK_CHILD_AGE_ENABLE: t.Bool(False), # Default is 20 in Z-Stack 3.0.1, 30 in Z-Stack 3/4 OsalNvIds.BCAST_DELIVERY_TIME: t.uint8_t(30), # We want to receive all ZDO callbacks to proxy them back to zigpy OsalNvIds.ZDO_DIRECT_CB: t.Bool(True), } any_changed = False for nvid, value in settings.items(): try: current_value = await self._znp.nvram.osal_read( nvid, item_type=type(value) ) except InvalidCommandResponse: current_value = None # There is no point in issuing a write if the value will not change if current_value != value: await self._znp.nvram.osal_write(nvid, value) any_changed = True return any_changed async def _reconnect(self) -> None: """ Endlessly tries to reconnect to the currently configured radio. Relies on the fact that `self.startup()` only modifies `self` upon a successful connection to be essentially stateless. """ for attempt in itertools.count(start=1): LOGGER.debug( "Trying to reconnect to %s, attempt %d", self._config[conf.CONF_DEVICE][conf.CONF_DEVICE_PATH], attempt, ) try: await self.connect() await self.initialize() return except asyncio.CancelledError: raise except Exception as e: LOGGER.error("Failed to reconnect", exc_info=e) if self._znp is not None: self._znp.close() self._znp = None await asyncio.sleep( self._config[conf.CONF_ZNP_CONFIG][ conf.CONF_AUTO_RECONNECT_RETRY_DELAY ] ) def _find_endpoint(self, dst_ep: int, profile: int, cluster: int) -> int: """ Zigpy defaults to sending messages with src_ep == dst_ep. This does not work with all versions of Z-Stack, which requires endpoints to be registered explicitly on startup. """ if dst_ep == ZDO_ENDPOINT: return ZDO_ENDPOINT # Newer Z-Stack releases ignore profiles and will work properly with endpoint 1 if ( self._zstack_build_id >= 20210708 and self.znp_config[conf.CONF_PREFER_ENDPOINT_1] ): return ZHA_ENDPOINT # Always fall back to endpoint 1 candidates = [ZHA_ENDPOINT] for ep_id, endpoint in self._device.endpoints.items(): if ep_id == ZDO_ENDPOINT: continue if endpoint.profile_id != profile: continue # An exact match, no need to continue further # TODO: pass in `is_server_cluster` or something similar if cluster in endpoint.out_clusters or cluster in endpoint.in_clusters: return endpoint.endpoint_id # Otherwise, keep track of the candidate cluster # if we don't find anything better candidates.append(endpoint.endpoint_id) return candidates[-1] async def _send_request_raw( self, dst_addr: t.AddrModeAddress, dst_ep: int, src_ep: int, profile: int, cluster: int, sequence: int, options: c.af.TransmitOptions, radius: int, data: bytes, *, relays: list[int] | None = None, extended_timeout: bool = False, ) -> None: """ Used by `request`/`mrequest`/`broadcast` to send a request. Picks the correct request sending mechanism and fixes endpoint information. """ # Zigpy just sets src == dst, which doesn't work for devices with many endpoints # We pick ours based on the registered endpoints when using an older firmware src_ep = self._find_endpoint(dst_ep=dst_ep, profile=profile, cluster=cluster) if relays is None: request = c.AF.DataRequestExt.Req( DstAddrModeAddress=dst_addr, DstEndpoint=dst_ep or 0, DstPanId=0x0000, SrcEndpoint=src_ep, ClusterId=cluster, TSN=sequence, Options=options, Radius=radius, Data=data, ) else: request = c.AF.DataRequestSrcRtg.Req( DstAddr=dst_addr.address, DstEndpoint=dst_ep or 0, SrcEndpoint=src_ep, ClusterId=cluster, TSN=sequence, Options=options, Radius=radius, SourceRoute=relays, # force the packet to go through specific parents Data=data, ) if self._znp is None: raise DeliveryError("Coordinator is disconnected, cannot send request") # Z-Stack requires special treatment when sending ZDO requests if dst_ep == ZDO_ENDPOINT: # XXX: Joins *must* be sent via a ZDO command, even if they are directly # addressing another device. The router will receive the ZDO request and a # device will try to join, but Z-Stack will never send the network key. if cluster == zdo_t.ZDOCmd.Mgmt_Permit_Joining_req: if dst_addr.mode == t.AddrMode.Broadcast: # The coordinator responds to broadcasts permit_addr = self.state.node_info.nwk else: # Otherwise, the destination device responds permit_addr = dst_addr.address await self._znp.request_callback_rsp( request=c.ZDO.MgmtPermitJoinReq.Req( AddrMode=dst_addr.mode, Dst=dst_addr.address, Duration=data[1], TCSignificance=data[2], ), RspStatus=t.Status.SUCCESS, callback=c.ZDO.MgmtPermitJoinRsp.Callback( Src=permit_addr, partial=True ), ) # Internally forward ZDO requests destined for the coordinator back to zigpy # so we can send internal Z-Stack requests when necessary elif ( # Broadcast that will reach the device dst_addr.mode == t.AddrMode.Broadcast and dst_addr.address in ( zigpy.types.BroadcastAddress.ALL_DEVICES, zigpy.types.BroadcastAddress.RX_ON_WHEN_IDLE, zigpy.types.BroadcastAddress.ALL_ROUTERS_AND_COORDINATOR, ) ) or ( # Or a direct unicast request dst_addr.mode == t.AddrMode.NWK and dst_addr.address == self._device.nwk ): self.packet_received( zigpy.types.ZigbeePacket( src=zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=self._device.nwk, ), src_ep=src_ep, dst=zigpy.types.AddrModeAddress( addr_mode=zigpy.types.AddrMode.NWK, address=self._device.nwk, ), dst_ep=dst_ep, tsn=sequence, profile_id=profile, cluster_id=cluster, data=t.SerializableBytes(data), radius=radius, ) ) if dst_ep == ZDO_ENDPOINT or dst_addr.mode == t.AddrMode.Broadcast: # Broadcasts and ZDO requests will not receive a confirmation await self._znp.request(request=request, RspStatus=t.Status.SUCCESS) else: async with async_timeout.timeout( EXTENDED_DATA_CONFIRM_TIMEOUT if extended_timeout else DATA_CONFIRM_TIMEOUT ): # Shield from cancellation to prevent requests that time out in higher # layers from missing expected responses response = await asyncio.shield( self._znp.request_callback_rsp( request=request, RspStatus=t.Status.SUCCESS, callback=c.AF.DataConfirm.Callback( partial=True, TSN=sequence, # XXX: can this ever not match? # Endpoint=src_ep, ), # Multicasts eventually receive a confirmation but waiting for # it is unnecessary background=(dst_addr.mode == t.AddrMode.Group), ) ) # Both the callback and the response can have an error status if response.Status != t.Status.SUCCESS: raise InvalidCommandResponse( f"Unsuccessful request status code: {response.Status!r}", response, ) @combine_concurrent_calls async def _discover_route(self, nwk: t.NWK) -> None: """ Instructs the coordinator to re-discover routes to the provided NWK. Runs concurrently and at most once per NWK, even if called multiple times. """ # Route discovery with Z-Stack 1.2 and Z-Stack 3.0.2 on the CC2531 doesn't # appear to work very well (Z2M#2901) if self._znp.version < 3.30: return await self._znp.request( c.ZDO.ExtRouteDisc.Req( Dst=nwk, Options=c.zdo.RouteDiscoveryOptions.UNICAST, Radius=30, ), ) await asyncio.sleep(0.1 * 13) async def send_packet(self, packet: zigpy.types.ZigbeePacket) -> None: """ Fault-tolerant wrapper around `_send_request_raw` that transparently attempts to repair routes and contact the device through other methods when Z-Stack errors are encountered. """ LOGGER.debug("Sending packet %r", packet) options = c.af.TransmitOptions.SUPPRESS_ROUTE_DISC_NETWORK if zigpy.types.TransmitOptions.ACK in packet.tx_options: options |= c.af.TransmitOptions.ACK_REQUEST if zigpy.types.TransmitOptions.APS_Encryption in packet.tx_options: options |= c.af.TransmitOptions.ENABLE_SECURITY try: device = self.get_device_with_address(packet.dst) except (KeyError, ValueError): # Sometimes a request is sent to a device not in the database. This should # work, the device object is only for recovery. device = None dst_addr = t.AddrModeAddress.from_zigpy_type(packet.dst) succeeded = False association = None force_relays = None if packet.source_route is not None: force_relays = packet.source_route retry_methods = RetryMethod.NONE last_retry_method = RetryMethod.NONE # Don't release the concurrency-limiting semaphore until we are done trying. # There is no point in allowing requests to take turns getting buffer errors. try: async with self._limit_concurrency(): for attempt in range(REQUEST_MAX_RETRIES): try: # ZDO requests do not generate `AF.DataConfirm` messages # indicating that a route is missing so we need to explicitly # check for one. if ( packet.dst_ep == ZDO_ENDPOINT and dst_addr.mode == t.AddrMode.NWK and dst_addr.address != self.state.node_info.nwk ): route_status = await self._znp.request( c.ZDO.ExtRouteChk.Req( Dst=dst_addr.address, RtStatus=c.zdo.RouteStatus.ACTIVE, Options=( c.zdo.RouteOptions.MTO_ROUTE | c.zdo.RouteOptions.NO_ROUTE_CACHE ), ) ) if route_status.Status != c.zdo.RoutingStatus.SUCCESS: await self._discover_route(dst_addr.address) await self._send_request_raw( dst_addr=dst_addr, dst_ep=packet.dst_ep, src_ep=packet.src_ep, profile=packet.profile_id, cluster=packet.cluster_id, sequence=packet.tsn, options=options, radius=packet.radius or 0, data=packet.data.serialize(), relays=force_relays, extended_timeout=packet.extended_timeout, ) succeeded = True break except InvalidCommandResponse as e: status = e.response.Status if status not in REQUEST_RETRYABLE_ERRORS: raise # Just retry if: # - this is our first failure # - the error is transient and is not a routing issue # - or we are not sending a unicast request if ( attempt == 0 or status in REQUEST_TRANSIENT_ERRORS or dst_addr.mode not in (t.AddrMode.NWK, t.AddrMode.IEEE) ): LOGGER.debug( "Request failed (%s), retry attempt %s of %s (%s)", e, attempt + 1, REQUEST_MAX_RETRIES, retry_methods.name, ) await asyncio.sleep(3 * REQUEST_ERROR_RETRY_DELAY) continue # If we can't contact the device by forcing a specific route, # there is no point in trying this more than once. if ( retry_methods & RetryMethod.LastGoodRoute and force_relays is not None ): force_relays = None # If we fail to contact the device with its IEEE address, don't # try again. if ( retry_methods & RetryMethod.IEEEAddress and dst_addr.mode == t.AddrMode.IEEE and device is not None ): dst_addr = t.AddrModeAddress( mode=t.AddrMode.NWK, address=device.nwk, ) # Child aging is disabled so if a child switches parents from # the coordinator to another router, we will not be able to # re-discover a route to it. We have to manually drop the child # to do this. if ( status == t.Status.MAC_TRANSACTION_EXPIRED and device is not None and association is None and not retry_methods & RetryMethod.AssocRemove and self._znp.version >= 3.30 ): association = await self._znp.request( c.UTIL.AssocGetWithAddress.Req( IEEE=device.ieee, NWK=0x0000, # IEEE takes priority ) ) if ( association.Device.nodeRelation != c.util.NodeRelation.NOTUSED ): try: await self._znp.request( c.UTIL.AssocRemove.Req(IEEE=device.ieee) ) retry_methods |= RetryMethod.AssocRemove last_retry_method = RetryMethod.AssocRemove # Route discovery must be performed right after await self._discover_route(device.nwk) except CommandNotRecognized: LOGGER.debug( "The UTIL.AssocRemove command is available only" " in Z-Stack 3 releases built after 20201017" ) elif ( not retry_methods & RetryMethod.LastGoodRoute and device is not None ): # `ZDO.SrcRtgInd` callbacks tell us the last path taken by # messages from the device back to the coordinator. Sending # packets backwards via this same route may work. force_relays = (device.relays or [])[::-1] retry_methods |= RetryMethod.LastGoodRoute last_retry_method = RetryMethod.LastGoodRoute elif ( not retry_methods & RetryMethod.RouteDiscovery and dst_addr.mode == t.AddrMode.NWK ): # If that doesn't work, try re-discovering the route. # While we can in theory poll and wait until it is fixed, # letting the retry mechanism deal with it simpler. await self._discover_route(dst_addr.address) retry_methods |= RetryMethod.RouteDiscovery last_retry_method = RetryMethod.RouteDiscovery elif ( not retry_methods & RetryMethod.IEEEAddress and device is not None and dst_addr.mode == t.AddrMode.NWK ): # Try using the device's IEEE address instead of its NWK. # If it works, the NWK will be updated when relays arrive. retry_methods |= RetryMethod.IEEEAddress last_retry_method = RetryMethod.IEEEAddress dst_addr = t.AddrModeAddress( mode=t.AddrMode.IEEE, address=device.ieee, ) LOGGER.debug( "Request failed (%s), retry attempt %s of %s (%s)", e, attempt + 1, REQUEST_MAX_RETRIES, retry_methods.name, ) # We've tried everything already so at this point just wait await asyncio.sleep(REQUEST_ERROR_RETRY_DELAY) else: raise DeliveryError( f"Request failed after {REQUEST_MAX_RETRIES} attempts:" f" {status!r}", status=status, ) self.state.counters[f"Retry_{last_retry_method.name}"][ attempt ].increment() finally: # We *must* re-add the device association if we previously removed it but # the request still failed. Otherwise, it may be a direct child and we will # not be able to find it again. if not succeeded and retry_methods & RetryMethod.AssocRemove: await self._znp.request( c.UTIL.AssocAdd.Req( NWK=association.Device.shortAddr, IEEE=device.ieee, NodeRelation=association.Device.nodeRelation, ) )
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/zigbee/application.py
application.py
from __future__ import annotations import enum import typing import logging import dataclasses import zigpy.zdo.types import zigpy_znp.types as t LOGGER = logging.getLogger(__name__) class CommandType(t.enum_uint8): """Command Type.""" POLL = 0 SREQ = 1 # A synchronous request that requires an immediate response AREQ = 2 # An asynchronous request SRSP = 3 # A synchronous response. This type of command is only sent in response to # a SREQ command RESERVED_4 = 4 RESERVED_5 = 5 RESERVED_6 = 6 RESERVED_7 = 7 class ErrorCode(t.MissingEnumMixin, t.enum_uint8): """Error code.""" INVALID_SUBSYSTEM = 0x01 INVALID_COMMAND_ID = 0x02 INVALID_PARAMETER = 0x03 INVALID_LENGTH = 0x04 class Subsystem(t.enum_uint8): """Command subsystem.""" RPCError = 0x00 SYS = 0x01 MAC = 0x02 NWK = 0x03 AF = 0x04 ZDO = 0x05 SAPI = 0x06 UTIL = 0x07 DEBUG = 0x08 APP = 0x09 OTA = 0x0A ZNP = 0x0B RESERVED_12 = 0x0C UBL_FUNC = 0x0D RESERVED_14 = 0x0E APPConfig = 0x0F RESERVED_16 = 0x10 PROTOBUF = 0x11 RESERVED_18 = 0x12 RESERVED_19 = 0x13 RESERVED_20 = 0x14 ZGP = 0x15 RESERVED_22 = 0x16 RESERVED_23 = 0x17 RESERVED_24 = 0x18 RESERVED_25 = 0x19 RESERVED_26 = 0x1A RESERVED_27 = 0x1B RESERVED_28 = 0x1C RESERVED_29 = 0x1D RESERVED_30 = 0x1E RESERVED_31 = 0x1F class CallbackSubsystem(t.enum_uint16): """Subscribe/unsubscribe subsystem callbacks.""" MT_SYS = Subsystem.SYS << 8 MC_MAC = Subsystem.MAC << 8 MT_NWK = Subsystem.NWK << 8 MT_AF = Subsystem.AF << 8 MT_ZDO = Subsystem.ZDO << 8 MT_SAPI = Subsystem.SAPI << 8 MT_UTIL = Subsystem.UTIL << 8 MT_DEBUG = Subsystem.DEBUG << 8 MT_APP = Subsystem.APP << 8 MT_APPConfig = Subsystem.APPConfig << 8 MT_ZGP = Subsystem.ZGP << 8 ALL = 0xFFFF class CommandHeader(t.uint16_t): """CommandHeader class.""" def __new__( cls, value: int = 0x0000, *, id=None, subsystem=None, type=None ) -> CommandHeader: instance = super().__new__(cls, value) if id is not None: instance = instance.with_id(id) if subsystem is not None: instance = instance.with_subsystem(subsystem) if type is not None: instance = instance.with_type(type) return instance @property def cmd0(self) -> t.uint8_t: return t.uint8_t(self & 0x00FF) @property def id(self) -> t.uint8_t: """Return CommandHeader id.""" return t.uint8_t(self >> 8) def with_id(self, value: int) -> CommandHeader: """command ID setter.""" return type(self)(self & 0x00FF | (value & 0xFF) << 8) @property def subsystem(self) -> Subsystem: """Return subsystem of the command.""" return Subsystem(self.cmd0 & 0x1F) def with_subsystem(self, value: Subsystem) -> CommandHeader: return type(self)(self & 0xFFE0 | value & 0x1F) @property def type(self) -> CommandType: """Return command type.""" return CommandType(self.cmd0 >> 5) def with_type(self, value) -> CommandHeader: return type(self)(self & 0xFF1F | (value & 0x07) << 5) def __str__(self) -> str: return ( f"{type(self).__name__}(" f"id=0x{self.id:02X}, " f"subsystem={self.subsystem!s}, " f"type={self.type!s}" ")" ) __repr__ = __str__ @dataclasses.dataclass(frozen=True) class CommandDef: command_type: CommandType command_id: t.uint8_t req_schema: tuple | None = None rsp_schema: tuple | None = None class CommandsMeta(type): """ Metaclass that creates `Command` subclasses out of the `CommandDef` definitions """ def __new__(cls, name: str, bases, classdict, *, subsystem): # Ignore CommandsBase if not bases: return type.__new__(cls, name, bases, classdict) classdict["_commands"] = [] for command, definition in classdict.items(): if not isinstance(definition, CommandDef): continue # We manually create the qualname to match the final object structure qualname = classdict["__qualname__"] + "." + command # The commands class is dynamically created from the definition helper_class_dict = { "definition": definition, "type": definition.command_type, "subsystem": subsystem, "__qualname__": qualname, "Req": None, "Rsp": None, "Callback": None, } header = ( CommandHeader() .with_id(definition.command_id) .with_type(definition.command_type) .with_subsystem(subsystem) ) rsp_header = header # TODO: explore __set_name__ if definition.req_schema is not None: # AREQ doesn't necessarily mean it's a callback # Some requests don't have any response at all if definition.command_type == CommandType.AREQ: class Req(CommandBase, header=header, schema=definition.req_schema): pass Req.__qualname__ = qualname + ".Req" Req.Req = Req Req.Rsp = None Req.Callback = None helper_class_dict["Req"] = Req else: req_header = header rsp_header = CommandHeader(0x0040 + req_header) class Req( # type:ignore[no-redef] CommandBase, header=req_header, schema=definition.req_schema ): pass class Rsp( CommandBase, header=rsp_header, schema=definition.rsp_schema ): pass Req.__qualname__ = qualname + ".Req" Req.Req = Req Req.Rsp = Rsp Req.Callback = None helper_class_dict["Req"] = Req Rsp.__qualname__ = qualname + ".Rsp" Rsp.Req = Rsp Rsp.Req = Req Rsp.Callback = None helper_class_dict["Rsp"] = Rsp else: assert definition.rsp_schema is not None, definition if definition.command_type == CommandType.AREQ: # If there is no request schema, this is a callback class Callback( CommandBase, header=header, schema=definition.rsp_schema ): pass Callback.__qualname__ = qualname + ".Callback" Callback.Req = None Callback.Rsp = None Callback.Callback = Callback helper_class_dict["Callback"] = Callback elif definition.command_type == CommandType.SRSP: # XXX: This is the only command like this # everything else should be an error! if header != CommandHeader( subsystem=Subsystem.RPCError, id=0x00, type=CommandType.SRSP ): raise RuntimeError( f"Invalid command definition {command} = {definition}" ) # pragma: no cover # If there is no request, this is a just a response class Rsp( # type:ignore[no-redef] CommandBase, header=header, schema=definition.rsp_schema ): pass Rsp.__qualname__ = qualname + ".Rsp" Rsp.Req = None Rsp.Rsp = Rsp Rsp.Callback = None helper_class_dict["Rsp"] = Rsp else: raise RuntimeError( f"Invalid command definition {command} = {definition}" ) # pragma: no cover classdict[command] = type(command, (), helper_class_dict) classdict["_commands"].append(classdict[command]) return type.__new__(cls, name, bases, classdict) def __iter__(self): return iter(self._commands) class CommandsBase(metaclass=CommandsMeta, subsystem=None): pass class CommandBase: Req = None Rsp = None Callback = None def __init_subclass__(cls, *, header, schema): super().__init_subclass__() cls.header = header cls.schema = schema def __init__(self, *, partial=False, **params): super().__setattr__("_partial", partial) super().__setattr__("_bound_params", {}) all_params = [p.name for p in self.schema] optional_params = [p.name for p in self.schema if p.optional] given_params = set(params.keys()) given_optional = [p for p in params.keys() if p in optional_params] unknown_params = given_params - set(all_params) missing_params = (set(all_params) - set(optional_params)) - given_params if unknown_params: raise KeyError( f"Unexpected parameters: {unknown_params}. " f"Expected one of {missing_params}" ) if not partial: # Optional params must be passed without any skips if optional_params[: len(given_optional)] != given_optional: raise KeyError( f"Optional parameters cannot be skipped: " f"expected order {optional_params}, got {given_optional}." ) if missing_params: raise KeyError(f"Missing parameters: {set(all_params) - given_params}") bound_params = {} for param in self.schema: if params.get(param.name) is None and (partial or param.optional): bound_params[param.name] = (param, None) continue value = params[param.name] if not isinstance(value, param.type): # fmt: off is_coercible_type = [ isinstance(value, int) and issubclass(param.type, int) and not issubclass(param.type, enum.Enum), isinstance(value, bytes) and issubclass(param.type, (t.ShortBytes, t.LongBytes, t.Bytes)), isinstance(value, list) and issubclass(param.type, list), isinstance(value, bool) and issubclass(param.type, t.Bool), ] # fmt: on if any(is_coercible_type): value = param.type(value) elif ( type(value) is zigpy.zdo.types.SimpleDescriptor and param.type is zigpy.zdo.types.SizePrefixedSimpleDescriptor ): data = value.serialize() value, _ = param.type.deserialize(bytes([len(data)]) + data) else: raise ValueError( f"In {type(self)}, param {param.name} is " f"type {param.type}, got {type(value)}" ) try: # XXX: Break early if a type cannot be serialized value.serialize() except Exception as e: raise ValueError( f"Invalid parameter value: {param.name}={value!r}" ) from e bound_params[param.name] = (param, value) super().__setattr__("_bound_params", bound_params) def to_frame(self, *, align=False): if self._partial: raise ValueError(f"Cannot serialize a partial frame: {self}") from zigpy_znp.frames import GeneralFrame chunks = [] for param, value in self._bound_params.values(): # At this point the optional params are assumed to be in a valid order if value is None: continue if issubclass(param.type, t.CStruct): chunks.append(value.serialize(align=align)) else: chunks.append(value.serialize()) return GeneralFrame(self.header, b"".join(chunks)) @classmethod def from_frame(cls, frame, *, align=False) -> CommandBase: if frame.header != cls.header: raise ValueError( f"Wrong frame header in {cls}: {cls.header} != {frame.header}" ) data = frame.data params = {} for param in cls.schema: try: if issubclass(param.type, t.CStruct): params[param.name], data = param.type.deserialize(data, align=align) else: params[param.name], data = param.type.deserialize(data) except ValueError: if not data and param.optional: # If we're out of data and the parameter is optional, we're done break elif not data and not param.optional: # If we're out of data but the parameter is required, this is bad raise ValueError( f"Frame data is truncated (parsed {params})," f" required parameter remains: {param}" ) else: # Otherwise, let the exception happen raise if data: raise ValueError( f"Frame {frame} contains trailing data after parsing: {data}" ) return cls(**params) def matches(self, other: CommandBase) -> bool: if type(self) is not type(other): return False assert self.header == other.header param_pairs = zip(self._bound_params.values(), other._bound_params.values()) for ( (expected_param, expected_value), (actual_param, actual_value), ) in param_pairs: assert expected_param == actual_param # Only non-None bound params are considered if expected_value is not None and expected_value != actual_value: return False return True def replace(self, **kwargs) -> CommandBase: """ Returns a copy of the current command with replaced parameters. """ params = {key: value for key, (param, value) in self._bound_params.items()} params.update(kwargs) return type(self)(partial=self._partial, **params) def as_dict(self) -> dict[str, typing.Any]: """ Converts the command into a dictionary. """ return {p.name: v for p, v in self._bound_params.values()} def __eq__(self, other): return type(self) is type(other) and self._bound_params == other._bound_params def __hash__(self): params = tuple(self._bound_params.items()) return hash((type(self), self.header, self.schema, params)) def __getattribute__(self, key): try: return object.__getattribute__(self, key) except AttributeError: pass try: param, value = object.__getattribute__(self, "_bound_params")[key] return value except KeyError: pass raise AttributeError(f"{self} has no attribute {key!r}") def __setattr__(self, key, value): raise RuntimeError("Command instances are immutable") def __delattr__(self, key): raise RuntimeError("Command instances are immutable") def __repr__(self): params = [f"{p.name}={v!r}" for p, v in self._bound_params.values()] return f'{self.__class__.__qualname__}({", ".join(params)})' __str__ = __repr__ class DeviceState(t.enum_uint8): """Indicated device state.""" # Initialized - not started automatically InitializedNotStarted = 0x00 # Initialized - not connected to anything InitializedNotConnected = 0x01 # Discovering PAN's to join DiscoveringPANs = 0x02 # Joining a PAN Joining = 0x03 # ReJoining a PAN in secure mode scanning in current channel, only for end devices ReJoiningSecureScanningCurrentChannel = 0x04 # Joined but not yet authenticated by trust center JoinedNotAuthenticated = 0x05 # Started as device after authentication JoinedAsEndDevice = 0x06 # Device joined, authenticated and is a router JoinedAsRouter = 0x07 # Started as Zigbee Coordinator StartingAsCoordinator = 0x08 # Started as Zigbee Coordinator StartedAsCoordinator = 0x09 # Device has lost information about its parent LostParent = 0x0A # Device is sending KeepAlive message to its parent SendingKeepAliveToParent = 0x0B # Device is waiting before trying to rejoin BackoffBeforeRejoin = 0x0C # ReJoining a PAN in secure mode scanning in all channels, only for end devices RejoinSecureScanningAllChannels = 0x0D # ReJoining a PAN in unsecure mode scanning in current channel, only for end devices RejoinInsecureScanningCurrentChannel = 0x0E # ReJoining a PAN in unsecure mode scanning in all channels, only for end devices RejoinInsecureScanningAllChannels = 0x0F class InterPanCommand(t.enum_uint8): # Switch channel back to the NIB channel Clr = 0x00 # Set channel for inter-pan communication Set = 0x01 # Register an endpoint as inter-pan Reg = 0x02 # Check if an endpoint is registered as inter-pan Chk = 0x03 class MTCapabilities(t.enum_flag_uint16): SYS = 1 << 0 MAC = 1 << 1 NWK = 1 << 2 AF = 1 << 3 ZDO = 1 << 4 SAPI = 1 << 5 UTIL = 1 << 6 DEBUG = 1 << 7 APP = 1 << 8 GP = 1 << 9 APP_CNF = 1 << 10 UNK12 = 1 << 11 ZOAD = 1 << 12 UNK14 = 1 << 13 UNK15 = 1 << 14 UNK16 = 1 << 15 class Network(t.CStruct): PanId: t.PanId Channel: t.uint8_t StackProfileVersion: t.uint8_t BeaconOrderSuperframe: t.uint8_t PermitJoining: t.uint8_t STATUS_SCHEMA = ( t.Param("Status", t.Status, "Status is either Success (0) or Failure (1)"), )
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/types/commands.py
commands.py
from . import basic, named, cstruct, zigpy_types class NwkKeyDesc(cstruct.CStruct): KeySeqNum: basic.uint8_t Key: zigpy_types.KeyData class NwkState(basic.enum_uint8): NWK_INIT = 0 NWK_JOINING_ORPHAN = 1 NWK_DISC = 2 NWK_JOINING = 3 NWK_ENDDEVICE = 4 PAN_CHNL_SELECTION = 5 PAN_CHNL_VERIFY = 6 PAN_STARTING = 7 NWK_ROUTER = 8 NWK_REJOINING = 9 class NIB(cstruct.CStruct): # NwkState is 16 bits on newer platforms but we cheat a little and make it 8, since # its max value is 8. However, we can't allow values like 0xFF08 to be serialized. _padding_byte = b"\x00" SequenceNum: basic.uint8_t PassiveAckTimeout: basic.uint8_t MaxBroadcastRetries: basic.uint8_t MaxChildren: basic.uint8_t MaxDepth: basic.uint8_t MaxRouters: basic.uint8_t dummyNeighborTable: basic.uint8_t BroadcastDeliveryTime: basic.uint8_t ReportConstantCost: basic.uint8_t RouteDiscRetries: basic.uint8_t dummyRoutingTable: basic.uint8_t SecureAllFrames: basic.uint8_t SecurityLevel: basic.uint8_t SymLink: basic.uint8_t CapabilityFlags: basic.uint8_t TransactionPersistenceTime: basic.uint16_t nwkProtocolVersion: basic.uint8_t RouteDiscoveryTime: basic.uint8_t RouteExpiryTime: basic.uint8_t nwkDevAddress: zigpy_types.NWK nwkLogicalChannel: basic.uint8_t nwkCoordAddress: zigpy_types.NWK nwkCoordExtAddress: zigpy_types.EUI64 nwkPanId: basic.uint16_t # XXX: this is really a uint16_t but we pad with zeroes so it works out in the end nwkState: NwkState channelList: zigpy_types.Channels beaconOrder: basic.uint8_t superFrameOrder: basic.uint8_t scanDuration: basic.uint8_t battLifeExt: basic.uint8_t allocatedRouterAddresses: basic.uint32_t allocatedEndDeviceAddresses: basic.uint32_t nodeDepth: basic.uint8_t extendedPANID: zigpy_types.EUI64 nwkKeyLoaded: zigpy_types.Bool spare1: NwkKeyDesc spare2: NwkKeyDesc spare3: basic.uint8_t spare4: basic.uint8_t nwkLinkStatusPeriod: basic.uint8_t nwkRouterAgeLimit: basic.uint8_t nwkUseMultiCast: zigpy_types.Bool nwkIsConcentrator: zigpy_types.Bool nwkConcentratorDiscoveryTime: basic.uint8_t nwkConcentratorRadius: basic.uint8_t nwkAllFresh: basic.uint8_t nwkManagerAddr: zigpy_types.NWK nwkTotalTransmissions: basic.uint16_t nwkUpdateId: basic.uint8_t class Beacon(cstruct.CStruct): """Beacon message.""" Src: zigpy_types.NWK PanId: zigpy_types.PanId Channel: basic.uint8_t PermitJoining: basic.uint8_t RouterCapacity: basic.uint8_t DeviceCapacity: basic.uint8_t ProtocolVersion: basic.uint8_t StackProfile: basic.uint8_t LQI: basic.uint8_t Depth: basic.uint8_t UpdateId: basic.uint8_t ExtendedPanId: zigpy_types.ExtendedPanId class TCLinkKey(cstruct.CStruct): ExtAddr: zigpy_types.EUI64 Key: zigpy_types.KeyData TxFrameCounter: basic.uint32_t RxFrameCounter: basic.uint32_t class NwkActiveKeyItems(cstruct.CStruct): Active: NwkKeyDesc FrameCounter: basic.uint32_t class KeyType(named.MissingEnumMixin, basic.enum_uint8): NONE = 0 # Standard Network Key NWK = 1 # Application Master Key APP_MASTER = 2 # Application Link Key APP_LINK = 3 # Trust Center Link Key TC_LINK = 4 # XXX: just "6" in the Z-Stack source UNKNOWN_6 = 6 class KeyAttributes(basic.enum_uint8): # Used for IC derived keys PROVISIONAL_KEY = 0x00 # Unique key that is not verified UNVERIFIED_KEY = 0x01 # Unique key that got verified by ZC VERIFIED_KEY = 0x02 # Internal definitions # Use default key to join DISTRIBUTED_DEFAULT_KEY = 0xFC # Joined a network which is not R21 nwk, so TCLK process finished. NON_R21_NWK_JOINED = 0xFD # Unique key that got verified by Joining device. # This means that key is stored as plain text (not seed hashed) VERIFIED_KEY_JOINING_DEV = 0xFE # Entry using default key DEFAULT_KEY = 0xFF class TCLKDevEntry(cstruct.CStruct): _padding_byte = b"\x00" txFrmCntr: basic.uint32_t rxFrmCntr: basic.uint32_t extAddr: zigpy_types.EUI64 keyAttributes: KeyAttributes keyType: KeyType # For Unique key this is the number of shifts # for IC this is the offset on the NvId index SeedShift_IcIndex: basic.uint8_t class NwkSecMaterialDesc(cstruct.CStruct): FrameCounter: basic.uint32_t ExtendedPanID: zigpy_types.EUI64 class AddrMgrUserType(basic.enum_flag_uint8): Default = 0x00 Assoc = 0x01 Security = 0x02 Binding = 0x04 Private1 = 0x08 class AddrMgrEntry(cstruct.CStruct): type: AddrMgrUserType nwkAddr: zigpy_types.NWK extAddr: zigpy_types.EUI64 class AddressManagerTable(basic.CompleteList, item_type=AddrMgrEntry): pass class AuthenticationOption(basic.enum_uint8): NotAuthenticated = 0x00 AuthenticatedCBCK = 0x01 AuthenticatedEA = 0x02 class APSKeyDataTableEntry(cstruct.CStruct): Key: zigpy_types.KeyData TxFrameCounter: basic.uint32_t RxFrameCounter: basic.uint32_t class APSLinkKeyTableEntry(cstruct.CStruct): AddressManagerIndex: basic.uint16_t LinkKeyNvId: basic.uint16_t AuthenticationState: AuthenticationOption class APSLinkKeyTable( basic.LVList, length_type=basic.uint16_t, item_type=APSLinkKeyTableEntry ): pass class LinkInfo(cstruct.CStruct): # Counter of transmission success/failures txCounter: basic.uint8_t # Average of sending rssi values if link staus is enabled # i.e. NWK_LINK_STATUS_PERIOD is defined as non zero txCost: basic.uint8_t # average of received rssi values. # needs to be converted to link cost (1-7) before use rxLqi: basic.uint8_t # security key sequence number inKeySeqNum: basic.uint8_t # security frame counter.. inFrmCntr: basic.uint32_t # higher values indicate more failures txFailure: basic.uint16_t class AgingEndDevice(cstruct.CStruct): endDevCfg: basic.uint8_t deviceTimeout: basic.uint32_t class BaseAssociatedDevice(cstruct.CStruct): shortAddr: basic.uint16_t addrIdx: basic.uint16_t nodeRelation: basic.uint8_t devStatus: basic.uint8_t assocCnt: basic.uint8_t age: basic.uint8_t linkInfo: LinkInfo endDev: AgingEndDevice timeoutCounter: basic.uint32_t keepaliveRcv: zigpy_types.Bool class AssociatedDeviceZStack1(BaseAssociatedDevice): pass class AssociatedDeviceZStack3(BaseAssociatedDevice): ctrl: basic.uint8_t # This member was added
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/types/structs.py
structs.py
from __future__ import annotations import sys import enum import typing import zigpy.types as zigpy_t from zigpy_znp.types.cstruct import CStruct class Bytes(bytes): def serialize(self) -> Bytes: return self @classmethod def deserialize(cls, data: bytes) -> tuple[Bytes, bytes]: return cls(data), b"" def __repr__(self) -> str: # Reading byte sequences like \x200\x21 is extremely annoying # compared to \x20\x30\x21 escaped = "".join(f"\\x{b:02X}" for b in self) return f"b'{escaped}'" __str__ = __repr__ class TrailingBytes(Bytes): """ Bytes must occur at the very end of a parameter list for easy parsing. """ def serialize_list(objects) -> Bytes: return Bytes(b"".join([o.serialize() for o in objects])) class FixedIntType(int): _signed: bool _size: int def __new__(cls, *args, **kwargs): if getattr(cls, "_signed", None) is None or getattr(cls, "_size", None) is None: raise TypeError(f"{cls} is abstract and cannot be created") instance = super().__new__(cls, *args, **kwargs) instance.serialize() return instance def __init_subclass__(cls, signed=None, size=None, hex_repr=None) -> None: super().__init_subclass__() if signed is not None: cls._signed = signed if size is not None: cls._size = size if hex_repr: fmt = f"0x{{:0{cls._size * 2}X}}" # type:ignore[operator] cls.__str__ = cls.__repr__ = lambda self: fmt.format(self) elif hex_repr is not None and not hex_repr: cls.__str__ = super().__str__ cls.__repr__ = super().__repr__ if sys.version_info < (3, 10): # XXX: The enum module uses the first class with __new__ in its __dict__ # as the member type. We have to ensure this is true for # every subclass. # Fixed with https://github.com/python/cpython/pull/26658 if "__new__" not in cls.__dict__: cls.__new__ = cls.__new__ def serialize(self) -> bytes: try: return self.to_bytes(self._size, "little", signed=self._signed) except OverflowError as e: # OverflowError is not a subclass of ValueError, making it annoying to catch raise ValueError(str(e)) from e @classmethod def deserialize(cls, data: bytes) -> tuple[FixedIntType, bytes]: if len(data) < cls._size: raise ValueError(f"Data is too short to contain {cls._size} bytes") r = cls.from_bytes(data[: cls._size], "little", signed=cls._signed) data = data[cls._size :] return typing.cast(FixedIntType, r), data class uint_t(FixedIntType, signed=False): pass class int_t(FixedIntType, signed=True): pass class int8s(int_t, size=1): pass class int16s(int_t, size=2): pass class int24s(int_t, size=3): pass class int32s(int_t, size=4): pass class int40s(int_t, size=5): pass class int48s(int_t, size=6): pass class int56s(int_t, size=7): pass class int64s(int_t, size=8): pass class uint8_t(uint_t, size=1): pass class uint16_t(uint_t, size=2): pass class uint24_t(uint_t, size=3): pass class uint32_t(uint_t, size=4): pass class uint40_t(uint_t, size=5): pass class uint48_t(uint_t, size=6): pass class uint56_t(uint_t, size=7): pass class uint64_t(uint_t, size=8): pass class ShortBytes(Bytes): _header = uint8_t def serialize(self) -> Bytes: return self._header(len(self)).serialize() + self # type:ignore[return-value] @classmethod def deserialize(cls, data: bytes) -> tuple[Bytes, bytes]: length, data = cls._header.deserialize(data) if length > len(data): raise ValueError(f"Data is too short to contain {length} bytes of data") return cls(data[:length]), data[length:] class LongBytes(ShortBytes): _header = uint16_t class BaseListType(list): _item_type = None @classmethod def _serialize_item(cls, item, *, align): if not isinstance(item, cls._item_type): item = cls._item_type(item) # type:ignore[misc] if issubclass(cls._item_type, CStruct): return item.serialize(align=align) else: return item.serialize() @classmethod def _deserialize_item(cls, data, *, align): if issubclass(cls._item_type, CStruct): return cls._item_type.deserialize(data, align=align) else: return cls._item_type.deserialize(data) class LVList(BaseListType): _header = None def __init_subclass__(cls, *, item_type, length_type) -> None: super().__init_subclass__() cls._item_type = item_type cls._header = length_type def serialize(self, *, align=False) -> bytes: assert self._item_type is not None return self._header(len(self)).serialize() + b"".join( [self._serialize_item(i, align=align) for i in self] ) @classmethod def deserialize(cls, data: bytes, *, align=False) -> tuple[LVList, bytes]: length, data = cls._header.deserialize(data) r = cls() for _i in range(length): item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data class FixedList(BaseListType): _length = None def __init_subclass__(cls, *, item_type, length) -> None: super().__init_subclass__() cls._item_type = item_type cls._length = length def serialize(self, *, align=False) -> bytes: assert self._length is not None if len(self) != self._length: raise ValueError( f"Invalid length for {self!r}: expected {self._length}, got {len(self)}" ) return b"".join([self._serialize_item(i, align=align) for i in self]) @classmethod def deserialize(cls, data: bytes, *, align=False) -> tuple[FixedList, bytes]: r = cls() for _i in range(cls._length): item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data class CompleteList(BaseListType): def __init_subclass__(cls, *, item_type) -> None: super().__init_subclass__() cls._item_type = item_type def serialize(self, *, align=False) -> bytes: return b"".join([self._serialize_item(i, align=align) for i in self]) @classmethod def deserialize(cls, data: bytes, *, align=False) -> tuple[CompleteList, bytes]: r = cls() while data: item, data = cls._deserialize_item(data, align=align) r.append(item) return r, data class enum_uint8(uint8_t, enum.Enum): pass class enum_uint16(uint16_t, enum.Enum): pass class enum_uint24(uint24_t, enum.Enum): pass class enum_uint32(uint32_t, enum.Enum): pass class enum_uint40(uint40_t, enum.Enum): pass class enum_uint48(uint48_t, enum.Enum): pass class enum_uint56(uint56_t, enum.Enum): pass class enum_uint64(uint64_t, enum.Enum): pass class enum_flag_uint8(zigpy_t.bitmap_factory(uint8_t)): # type:ignore[misc] pass class enum_flag_uint16(zigpy_t.bitmap_factory(uint16_t)): # type:ignore[misc] pass class enum_flag_uint24(zigpy_t.bitmap_factory(uint24_t)): # type:ignore[misc] pass class enum_flag_uint32(zigpy_t.bitmap_factory(uint32_t)): # type:ignore[misc] pass class enum_flag_uint40(zigpy_t.bitmap_factory(uint40_t)): # type:ignore[misc] pass class enum_flag_uint48(zigpy_t.bitmap_factory(uint48_t)): # type:ignore[misc] pass class enum_flag_uint56(zigpy_t.bitmap_factory(uint56_t)): # type:ignore[misc] pass class enum_flag_uint64(zigpy_t.bitmap_factory(uint64_t)): # type:ignore[misc] pass
zigpy-znp
/zigpy-znp-0.11.4.tar.gz/zigpy-znp-0.11.4/zigpy_znp/types/basic.py
basic.py