id
int64 0
843k
| repository_name
stringlengths 7
55
| file_path
stringlengths 9
332
| class_name
stringlengths 3
290
| human_written_code
stringlengths 12
4.36M
| class_skeleton
stringlengths 19
2.2M
| total_program_units
int64 1
9.57k
| total_doc_str
int64 0
4.2k
| AvgCountLine
float64 0
7.89k
| AvgCountLineBlank
float64 0
300
| AvgCountLineCode
float64 0
7.89k
| AvgCountLineComment
float64 0
7.89k
| AvgCyclomatic
float64 0
130
| CommentToCodeRatio
float64 0
176
| CountClassBase
float64 0
48
| CountClassCoupled
float64 0
589
| CountClassCoupledModified
float64 0
581
| CountClassDerived
float64 0
5.37k
| CountDeclInstanceMethod
float64 0
4.2k
| CountDeclInstanceVariable
float64 0
299
| CountDeclMethod
float64 0
4.2k
| CountDeclMethodAll
float64 0
4.2k
| CountLine
float64 1
115k
| CountLineBlank
float64 0
9.01k
| CountLineCode
float64 0
94.4k
| CountLineCodeDecl
float64 0
46.1k
| CountLineCodeExe
float64 0
91.3k
| CountLineComment
float64 0
27k
| CountStmt
float64 1
93.2k
| CountStmtDecl
float64 0
46.1k
| CountStmtExe
float64 0
90.2k
| MaxCyclomatic
float64 0
759
| MaxInheritanceTree
float64 0
16
| MaxNesting
float64 0
34
| SumCyclomatic
float64 0
6k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
141,748 |
Kane610/deconz
|
pydeconz/models/sensor/water.py
|
pydeconz.models.sensor.water.TypedWaterState
|
class TypedWaterState(TypedDict):
"""Water state type definition."""
water: bool
|
class TypedWaterState(TypedDict):
'''Water state type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
141,749 |
Kane610/deconz
|
pydeconz/models/sensor/water.py
|
pydeconz.models.sensor.water.Water
|
class Water(SensorBase):
"""Water sensor."""
raw: TypedWater
@property
def water(self) -> bool:
"""Water detected."""
return self.raw["state"]["water"]
|
class Water(SensorBase):
'''Water sensor.'''
@property
def water(self) -> bool:
'''Water detected.'''
pass
| 3 | 2 | 3 | 0 | 2 | 1 | 1 | 0.4 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 21 | 9 | 2 | 5 | 3 | 2 | 2 | 4 | 2 | 2 | 1 | 3 | 0 | 1 |
141,750 |
Kane610/deconz
|
pydeconz/utils.py
|
pydeconz.utils.DiscoveredBridge
|
class DiscoveredBridge(TypedDict):
"""Discovered bridge type."""
id: str
host: str
mac: str
name: str
port: int
|
class DiscoveredBridge(TypedDict):
'''Discovered bridge type.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.17 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 1 | 6 | 1 | 5 | 1 | 6 | 1 | 5 | 0 | 1 | 0 | 0 |
141,751 |
Kane610/deconz
|
pydeconz/websocket.py
|
pydeconz.websocket.Signal
|
class Signal(enum.StrEnum):
"""What is the content of the callback."""
CONNECTION_STATE = "state"
DATA = "data"
|
class Signal(enum.StrEnum):
'''What is the content of the callback.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 5 | 1 | 3 | 3 | 2 | 1 | 3 | 3 | 2 | 0 | 3 | 0 | 0 |
141,752 |
Kane610/deconz
|
pydeconz/websocket.py
|
pydeconz.websocket.State
|
class State(enum.StrEnum):
"""State of the connection."""
NONE = ""
RETRYING = "retrying"
RUNNING = "running"
STOPPED = "stopped"
|
class State(enum.StrEnum):
'''State of the connection.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 7 | 1 | 5 | 5 | 4 | 1 | 5 | 5 | 4 | 0 | 3 | 0 | 0 |
141,753 |
Kane610/deconz
|
pydeconz/websocket.py
|
pydeconz.websocket.WSClient
|
class WSClient:
"""Websocket transport, session handling, message generation."""
def __init__(
self,
session: aiohttp.ClientSession,
host: str,
port: int,
callback: Callable[[Signal], Coroutine[Any, Any, None]],
) -> None:
"""Create resources for websocket communication."""
self.session = session
self.host = host
self.port = port
self.session_handler_callback = callback
self.loop = get_running_loop()
self._background_tasks: set[Task[Any]] = set()
self._data: deque[dict[str, Any]] = deque()
self._state = self._previous_state = State.NONE
def create_background_task(self, target: Coroutine[Any, Any, Any]) -> None:
"""Save a reference to the result of target.
To avoid a task disappearing mid-execution.
The event loop only keeps weak references to tasks.
A task that isn’t referenced elsewhere may get
garbage collected at any time, even before it’s done.
"""
task = create_task(target)
self._background_tasks.add(task)
task.add_done_callback(self._background_tasks.discard)
@property
def data(self) -> dict[str, Any]:
"""Return data from data queue."""
try:
return self._data.popleft()
except IndexError:
return {}
@property
def state(self) -> State:
"""State of websocket."""
return self._state
def set_state(self, value: State) -> None:
"""Set state of websocket and store previous state."""
self._previous_state = self._state
self._state = value
def state_changed(self) -> None:
"""Signal state change."""
self.create_background_task(
self.session_handler_callback(Signal.CONNECTION_STATE)
)
def start(self) -> None:
"""Start websocket and update its state."""
self.create_background_task(self.running())
async def running(self) -> None:
"""Start websocket connection."""
if self._state == State.RUNNING:
return
url = f"http://{self.host}:{self.port}"
try:
async with self.session.ws_connect(url, heartbeat=60) as ws:
LOGGER.info("Connected to deCONZ (%s)", self.host)
self.set_state(State.RUNNING)
self.state_changed()
async for msg in ws:
if self._state == State.STOPPED:
await ws.close()
break
if msg.type == aiohttp.WSMsgType.TEXT:
self._data.append(orjson.loads(msg.data))
self.create_background_task(
self.session_handler_callback(Signal.DATA)
)
LOGGER.debug(msg.data)
continue
if msg.type == aiohttp.WSMsgType.CLOSED:
LOGGER.warning("Connection closed (%s)", self.host)
break
if msg.type == aiohttp.WSMsgType.ERROR:
LOGGER.error("Websocket error (%s)", self.host)
break
except aiohttp.ClientConnectorError:
if self._state != State.RETRYING:
LOGGER.error("Websocket is not accessible (%s)", self.host)
except Exception as err:
if self._state != State.RETRYING:
LOGGER.error("Unexpected error (%s) %s", self.host, err)
if self._state != State.STOPPED:
self.retry()
def stop(self) -> None:
"""Close websocket connection."""
self.set_state(State.STOPPED)
LOGGER.info("Shutting down connection to deCONZ (%s)", self.host)
def retry(self) -> None:
"""Retry to connect to deCONZ.
Do an immediate retry without timer and without signalling state change.
Signal state change only after first retry fails.
"""
if self._state == State.RETRYING and self._previous_state == State.RUNNING:
LOGGER.info(
"Reconnecting to deCONZ (%s) failed, retrying in %i seconds",
self.host,
RETRY_TIMER,
)
self.state_changed()
self.set_state(State.RETRYING)
if self._previous_state == State.RUNNING:
LOGGER.info("Reconnecting to deCONZ (%s)", self.host)
self.start()
return
self.loop.call_later(RETRY_TIMER, self.start)
|
class WSClient:
'''Websocket transport, session handling, message generation.'''
def __init__(
self,
session: aiohttp.ClientSession,
host: str,
port: int,
callback: Callable[[Signal], Coroutine[Any, Any, None]],
) -> None:
'''Create resources for websocket communication.'''
pass
def create_background_task(self, target: Coroutine[Any, Any, Any]) -> None:
'''Save a reference to the result of target.
To avoid a task disappearing mid-execution.
The event loop only keeps weak references to tasks.
A task that isn’t referenced elsewhere may get
garbage collected at any time, even before it’s done.
'''
pass
@property
def data(self) -> dict[str, Any]:
'''Return data from data queue.'''
pass
@property
def state(self) -> State:
'''State of websocket.'''
pass
def set_state(self, value: State) -> None:
'''Set state of websocket and store previous state.'''
pass
def state_changed(self) -> None:
'''Signal state change.'''
pass
def start(self) -> None:
'''Start websocket and update its state.'''
pass
async def running(self) -> None:
'''Start websocket connection.'''
pass
def stop(self) -> None:
'''Close websocket connection.'''
pass
def retry(self) -> None:
'''Retry to connect to deCONZ.
Do an immediate retry without timer and without signalling state change.
Signal state change only after first retry fails.
'''
pass
| 13 | 11 | 12 | 2 | 9 | 2 | 2 | 0.21 | 0 | 14 | 2 | 0 | 10 | 9 | 10 | 10 | 134 | 26 | 89 | 32 | 70 | 19 | 73 | 22 | 62 | 12 | 0 | 4 | 24 |
141,754 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.LightResourceManager
|
class LightResourceManager(GroupedAPIHandler[LightResources]):
"""Represent deCONZ lights."""
resource_group = ResourceGroup.LIGHT
def __init__(self, gateway: DeconzSession) -> None:
"""Initialize light manager."""
self.configuration_tool = ConfigurationToolHandler(gateway, grouped=True)
self.covers = CoverHandler(gateway, grouped=True)
self.lights = LightHandler(gateway, grouped=True)
self.locks = LockHandler(gateway, grouped=True)
self.range_extender = RangeExtenderHandler(gateway, grouped=True)
self.sirens = SirenHandler(gateway, grouped=True)
handlers: list[APIHandler[Any]] = [
self.configuration_tool,
self.covers,
self.lights,
self.locks,
self.range_extender,
self.sirens,
]
super().__init__(gateway, handlers)
|
class LightResourceManager(GroupedAPIHandler[LightResources]):
'''Represent deCONZ lights.'''
def __init__(self, gateway: DeconzSession) -> None:
'''Initialize light manager.'''
pass
| 2 | 2 | 19 | 2 | 16 | 1 | 1 | 0.11 | 1 | 10 | 7 | 0 | 1 | 6 | 1 | 15 | 24 | 4 | 18 | 10 | 16 | 2 | 11 | 10 | 9 | 1 | 2 | 0 | 1 |
141,755 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.LightHandler
|
class LightHandler(APIHandler[Light]):
"""Handler for lights."""
resource_group = ResourceGroup.LIGHT
resource_types = {
ResourceType.COLOR_DIMMABLE_LIGHT,
ResourceType.COLOR_LIGHT,
ResourceType.COLOR_TEMPERATURE_LIGHT,
ResourceType.EXTENDED_COLOR_LIGHT,
ResourceType.DIMMABLE_LIGHT,
ResourceType.DIMMABLE_PLUGIN_UNIT,
ResourceType.DIMMER_SWITCH,
ResourceType.FAN,
ResourceType.ON_OFF_LIGHT,
ResourceType.ON_OFF_OUTPUT,
ResourceType.ON_OFF_PLUGIN_UNIT,
ResourceType.SMART_PLUG,
ResourceType.UNKNOWN, # Legacy support
}
item_cls = Light
async def set_state(
self,
id: str,
alert: LightAlert | None = None,
brightness: int | None = None,
color_loop_speed: int | None = None,
color_temperature: int | None = None,
effect: LightEffect | None = None,
fan_speed: LightFanSpeed | None = None,
hue: int | None = None,
on: bool | None = None,
on_time: int | None = None,
saturation: int | None = None,
transition_time: int | None = None,
xy: tuple[float, float] | None = None,
) -> dict[str, Any]:
"""Change state of a light.
Supported values:
- alert [str]
- "none" light is not performing an alert
- "select" light is blinking a short time
- "lselect" light is blinking a longer time
- brightness [int] 0-255
- color_loop_speed [int] 1-255
- 1 = very fast
- 15 is default
- 255 very slow
- color_temperature [int] between ctmin-ctmax
- effect [str]
- "none" no effect
- "colorloop" the light will cycle continuously through all
colors with the speed specified by colorloopspeed
- fan_speed [FanSpeed] Off, 25%, 50%, 75%, 100%, Auto, ComfortBreeze
- hue [int] 0-65535
- on [bool] True/False
- on_time [int] 0-65535 1/10 seconds resolution
- saturation [int] 0-255
- transition_time [int] 0-65535 1/10 seconds resolution
- xy [tuple] (0-1, 0-1)
"""
data: dict[str, Any] = {
key: value
for key, value in {
"bri": brightness,
"colorloopspeed": color_loop_speed,
"ct": color_temperature,
"hue": hue,
"on": on,
"ontime": on_time,
"sat": saturation,
"transitiontime": transition_time,
"xy": xy,
}.items()
if value is not None
}
if alert is not None:
data["alert"] = alert
if effect is not None:
data["effect"] = effect
if fan_speed is not None:
data["speed"] = fan_speed
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/state",
json=data,
)
|
class LightHandler(APIHandler[Light]):
'''Handler for lights.'''
async def set_state(
self,
id: str,
alert: LightAlert | None = None,
brightness: int | None = None,
color_loop_speed: int | None = None,
color_temperature: int | None = None,
effect: LightEffect | None = None,
fan_speed: LightFanSpeed | None = None,
hue: int | None = None,
on: bool | None = None,
on_time: int | None = None,
saturation: int | None = None,
transition_time: int | None = None,
xy: tuple[float, float] | None = None,
) -> dict[str, Any]:
'''Change state of a light.
Supported values:
- alert [str]
- "none" light is not performing an alert
- "select" light is blinking a short time
- "lselect" light is blinking a longer time
- brightness [int] 0-255
- color_loop_speed [int] 1-255
- 1 = very fast
- 15 is default
- 255 very slow
- color_temperature [int] between ctmin-ctmax
- effect [str]
- "none" no effect
- "colorloop" the light will cycle continuously through all
colors with the speed specified by colorloopspeed
- fan_speed [FanSpeed] Off, 25%, 50%, 75%, 100%, Auto, ComfortBreeze
- hue [int] 0-65535
- on [bool] True/False
- on_time [int] 0-65535 1/10 seconds resolution
- saturation [int] 0-255
- transition_time [int] 0-65535 1/10 seconds resolution
- xy [tuple] (0-1, 0-1)
'''
pass
| 2 | 2 | 67 | 1 | 42 | 24 | 4 | 0.43 | 1 | 10 | 3 | 0 | 1 | 0 | 1 | 16 | 88 | 3 | 60 | 21 | 43 | 26 | 13 | 6 | 11 | 4 | 2 | 1 | 4 |
141,756 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.CoverHandler
|
class CoverHandler(APIHandler[Cover]):
"""Handler for covers."""
resource_group = ResourceGroup.LIGHT
resource_types = {
ResourceType.LEVEL_CONTROLLABLE_OUTPUT,
ResourceType.WINDOW_COVERING_CONTROLLER,
ResourceType.WINDOW_COVERING_DEVICE,
}
item_cls = Cover
async def set_state(
self,
id: str,
action: CoverAction | None = None,
lift: int | None = None,
tilt: int | None = None,
legacy_mode: bool = False,
) -> dict[str, Any]:
"""Set state of cover.
Supported values:
- action [CoverAction] Open, Close, Stop
- lift [int] between 0-100
- tilt [int] between 0-100
"""
data: dict[str, bool | int] = {}
if action is not None and not legacy_mode:
if action is CoverAction.OPEN:
data["open"] = True
elif action is CoverAction.CLOSE:
data["open"] = False
elif action is CoverAction.STOP:
data["stop"] = True
elif action is not None and legacy_mode:
if action is CoverAction.OPEN:
data["on"] = False
elif action is CoverAction.CLOSE:
data["on"] = True
elif action is CoverAction.STOP:
data["bri_inc"] = 0
elif not legacy_mode:
if lift is not None:
data["lift"] = lift
if tilt is not None:
data["tilt"] = tilt
else:
if lift is not None:
data["bri"] = int(lift * 2.54)
if tilt is not None:
data["sat"] = int(tilt * 2.54)
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/state",
json=data,
)
|
class CoverHandler(APIHandler[Cover]):
'''Handler for covers.'''
async def set_state(
self,
id: str,
action: CoverAction | None = None,
lift: int | None = None,
tilt: int | None = None,
legacy_mode: bool = False,
) -> dict[str, Any]:
'''Set state of cover.
Supported values:
- action [CoverAction] Open, Close, Stop
- lift [int] between 0-100
- tilt [int] between 0-100
'''
pass
| 2 | 2 | 47 | 3 | 38 | 6 | 14 | 0.15 | 1 | 6 | 1 | 0 | 1 | 0 | 1 | 16 | 58 | 5 | 46 | 13 | 37 | 7 | 24 | 6 | 22 | 14 | 2 | 2 | 14 |
141,757 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.ConfigurationToolHandler
|
class ConfigurationToolHandler(APIHandler[ConfigurationTool]):
"""Handler for configuration tool."""
resource_group = ResourceGroup.LIGHT
resource_type = ResourceType.CONFIGURATION_TOOL
item_cls = ConfigurationTool
|
class ConfigurationToolHandler(APIHandler[ConfigurationTool]):
'''Handler for configuration tool.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,758 |
Kane610/deconz
|
pydeconz/interfaces/groups.py
|
pydeconz.interfaces.groups.GroupHandler
|
class GroupHandler(APIHandler[Group]):
"""Represent deCONZ groups."""
resource_group = ResourceGroup.GROUP
resource_type = ResourceType.GROUP
item_cls = Group
async def set_attributes(
self,
id: str,
hidden: bool | None = None,
light_sequence: list[str] | None = None,
lights: list[str] | None = None,
multi_device_ids: list[str] | None = None,
name: str | None = None,
) -> dict[str, Any]:
"""Change attributes of a group.
Supported values:
- hidden [bool] Indicates the hidden status of the group
- light_sequence [list of light IDs] Specify a sorted list of light IDs for apps
- lights [list of light IDs]IDs of the lights which are members of the group
- multi_device_ids [int] Subsequential light IDs of multidevices
- name [str] The name of the group
"""
data = {
key: value
for key, value in {
"hidden": hidden,
"lightsequence": light_sequence,
"lights": lights,
"multideviceids": multi_device_ids,
"name": name,
}.items()
if value is not None
}
return await self.gateway.request(
"put",
path=f"{self.path}/{id}",
json=data,
)
async def set_state(
self,
id: str,
alert: LightAlert | None = None,
brightness: int | None = None,
color_loop_speed: int | None = None,
color_temperature: int | None = None,
effect: LightEffect | None = None,
hue: int | None = None,
on: bool | None = None,
on_time: int | None = None,
saturation: int | None = None,
toggle: bool | None = None,
transition_time: int | None = None,
xy: tuple[float, float] | None = None,
) -> dict[str, Any]:
"""Change state of a group.
Supported values:
- alert [str]
- "none" light is not performing an alert
- "select" light is blinking a short time
- "lselect" light is blinking a longer time
- brightness [int] 0-255
- color_loop_speed [int] 1-255
- 1 = very fast
- 15 is default
- 255 very slow
- color_temperature [int] between ctmin-ctmax
- effect [str]
- "none" no effect
- "colorloop" the light will cycle continuously through all
colors with the speed specified by colorloopspeed
- hue [int] 0-65535
- on [bool] True/False
- on_time [int] 0-65535 1/10 seconds resolution
- saturation [int] 0-255
- toggle [bool] True toggles the lights of that group from on to off
or vice versa, false has no effect
- transition_time [int] 0-65535 1/10 seconds resolution
- xy [tuple] (0-1, 0-1)
"""
data: dict[str, Any] = {
key: value
for key, value in {
"bri": brightness,
"colorloopspeed": color_loop_speed,
"ct": color_temperature,
"hue": hue,
"on": on,
"ontime": on_time,
"sat": saturation,
"toggle": toggle,
"transitiontime": transition_time,
"xy": xy,
}.items()
if value is not None
}
if alert is not None:
data["alert"] = alert
if effect is not None:
data["effect"] = effect
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/action",
json=data,
)
|
class GroupHandler(APIHandler[Group]):
'''Represent deCONZ groups.'''
async def set_attributes(
self,
id: str,
hidden: bool | None = None,
light_sequence: list[str] | None = None,
lights: list[str] | None = None,
multi_device_ids: list[str] | None = None,
name: str | None = None,
) -> dict[str, Any]:
'''Change attributes of a group.
Supported values:
- hidden [bool] Indicates the hidden status of the group
- light_sequence [list of light IDs] Specify a sorted list of light IDs for apps
- lights [list of light IDs]IDs of the lights which are members of the group
- multi_device_ids [int] Subsequential light IDs of multidevices
- name [str] The name of the group
'''
pass
async def set_state(
self,
id: str,
alert: LightAlert | None = None,
brightness: int | None = None,
color_loop_speed: int | None = None,
color_temperature: int | None = None,
effect: LightEffect | None = None,
hue: int | None = None,
on: bool | None = None,
on_time: int | None = None,
saturation: int | None = None,
toggle: bool | None = None,
transition_time: int | None = None,
xy: tuple[float, float] | None = None,
) -> dict[str, Any]:
'''Change state of a group.
Supported values:
- alert [str]
- "none" light is not performing an alert
- "select" light is blinking a short time
- "lselect" light is blinking a longer time
- brightness [int] 0-255
- color_loop_speed [int] 1-255
- 1 = very fast
- 15 is default
- 255 very slow
- color_temperature [int] between ctmin-ctmax
- effect [str]
- "none" no effect
- "colorloop" the light will cycle continuously through all
colors with the speed specified by colorloopspeed
- hue [int] 0-65535
- on [bool] True/False
- on_time [int] 0-65535 1/10 seconds resolution
- saturation [int] 0-255
- toggle [bool] True toggles the lights of that group from on to off
or vice versa, false has no effect
- transition_time [int] 0-65535 1/10 seconds resolution
- xy [tuple] (0-1, 0-1)
'''
pass
| 3 | 3 | 51 | 1 | 33 | 17 | 2 | 0.49 | 1 | 10 | 2 | 0 | 2 | 0 | 2 | 17 | 109 | 5 | 70 | 31 | 44 | 34 | 14 | 8 | 11 | 3 | 2 | 1 | 4 |
141,759 |
Kane610/deconz
|
pydeconz/interfaces/events.py
|
pydeconz.interfaces.events.EventHandler
|
class EventHandler:
"""Event handler class."""
def __init__(self, gateway: DeconzSession) -> None:
"""Initialize API items."""
self.gateway = gateway
self._subscribers: list[SubscriptionType] = []
def subscribe(
self,
callback: Callable[[Event], None],
event_filter: tuple[EventType, ...] | EventType | None = None,
resource_filter: tuple[ResourceGroup, ...] | ResourceGroup | None = None,
) -> UnsubscribeType:
"""Subscribe to events.
"callback" - callback function to call when on event.
Return function to unsubscribe.
"""
if isinstance(event_filter, EventType):
event_filter = (event_filter,)
if isinstance(resource_filter, ResourceGroup):
resource_filter = (resource_filter,)
subscription = (callback, event_filter, resource_filter)
self._subscribers.append(subscription)
def unsubscribe() -> None:
self._subscribers.remove(subscription)
return unsubscribe
def handler(self, raw: dict[str, Any]) -> None:
"""Receive event from websocket and pass it along to subscribers."""
event = Event.from_dict(raw)
for callback, event_filter, resource_filter in self._subscribers:
if event_filter is not None and event.type not in event_filter:
continue
if resource_filter is not None and event.resource not in resource_filter:
continue
callback(event)
|
class EventHandler:
'''Event handler class.'''
def __init__(self, gateway: DeconzSession) -> None:
'''Initialize API items.'''
pass
def subscribe(
self,
callback: Callable[[Event], None],
event_filter: tuple[EventType, ...] | EventType | None = None,
resource_filter: tuple[ResourceGroup, ...] | ResourceGroup | None = None,
) -> UnsubscribeType:
'''Subscribe to events.
"callback" - callback function to call when on event.
Return function to unsubscribe.
'''
pass
def unsubscribe() -> None:
pass
def handler(self, raw: dict[str, Any]) -> None:
'''Receive event from websocket and pass it along to subscribers.'''
pass
| 5 | 4 | 10 | 2 | 7 | 2 | 2 | 0.26 | 0 | 9 | 3 | 0 | 3 | 2 | 3 | 3 | 44 | 10 | 27 | 15 | 17 | 7 | 22 | 10 | 17 | 4 | 0 | 2 | 9 |
141,760 |
Kane610/deconz
|
pydeconz/interfaces/api_handlers.py
|
pydeconz.interfaces.api_handlers.GroupedAPIHandler
|
class GroupedAPIHandler(Generic[DataResource]):
"""Represent a group of deCONZ API items."""
resource_group: ResourceGroup
def __init__(
self, gateway: DeconzSession, handlers: list[APIHandler[DataResource]]
) -> None:
"""Initialize grouped API handler."""
self.gateway = gateway
self._handlers = handlers
self._resource_type_to_handler: dict[ResourceType, APIHandler[DataResource]] = {
resource_type: handler
for handler in handlers
if handler.resource_types is not None
for resource_type in handler.resource_types
}
self._event_subscribe()
def _event_subscribe(self) -> None:
"""Post initialization method."""
self.gateway.events.subscribe(
self.process_event,
event_filter=(EventType.ADDED, EventType.CHANGED),
resource_filter=self.resource_group,
)
def process_raw(self, raw: dict[str, dict[str, Any]]) -> None:
"""Process full data."""
for id, raw_item in raw.items():
self.process_item(id, raw_item)
def process_event(self, event: Event) -> None:
"""Process event."""
if event.type == EventType.CHANGED and event.id in self:
self.process_item(event.id, event.changed_data)
elif event.type == EventType.ADDED and event.id not in self:
self.process_item(event.id, event.added_data)
def process_item(self, id: str, raw: dict[str, Any]) -> None:
"""Process item data."""
for handler in self._handlers:
if id in handler:
handler.process_item(id, raw)
return
if (
resource_type := ResourceType(raw.get("type") or "")
) not in self._resource_type_to_handler:
return
handler = self._resource_type_to_handler[resource_type]
handler.process_item(id, raw)
def subscribe(
self,
callback: CallbackType,
event_filter: tuple[EventType, ...] | EventType | None = None,
id_filter: tuple[str] | str | None = None,
) -> UnsubscribeType:
"""Subscribe to state changes for all grouped handler resources."""
subscribers = [
h.subscribe(callback, event_filter=event_filter, id_filter=id_filter)
for h in self._handlers
]
def unsubscribe() -> None:
for subscriber in subscribers:
subscriber()
return unsubscribe
def items(self) -> Iterable[tuple[str, DataResource]]:
"""Return dictionary of IDs and API items."""
return itertools.chain.from_iterable(h.items() for h in self._handlers)
def keys(self) -> list[str]:
"""Return item IDs."""
return [id for h in self._handlers for id in h]
def values(self) -> list[DataResource]:
"""Return API items."""
return [item for h in self._handlers for item in h.values()]
def get(self, id: str, default: Any = None) -> DataResource | None:
"""Get API item based on key, if no match return default."""
return next((h[id] for h in self._handlers if id in h), default)
def __getitem__(self, id: str) -> DataResource:
"""Get API item based on ID."""
if item := self.get(id):
return item
raise KeyError
def __iter__(self) -> Iterator[str]:
"""Allow iterate over item IDs."""
return iter(self.keys())
|
class GroupedAPIHandler(Generic[DataResource]):
'''Represent a group of deCONZ API items.'''
def __init__(
self, gateway: DeconzSession, handlers: list[APIHandler[DataResource]]
) -> None:
'''Initialize grouped API handler.'''
pass
def _event_subscribe(self) -> None:
'''Post initialization method.'''
pass
def process_raw(self, raw: dict[str, dict[str, Any]]) -> None:
'''Process full data.'''
pass
def process_event(self, event: Event) -> None:
'''Process event.'''
pass
def process_item(self, id: str, raw: dict[str, Any]) -> None:
'''Process item data.'''
pass
def subscribe(
self,
callback: CallbackType,
event_filter: tuple[EventType, ...] | EventType | None = None,
id_filter: tuple[str] | str | None = None,
) -> UnsubscribeType:
'''Subscribe to state changes for all grouped handler resources.'''
pass
def unsubscribe() -> None:
pass
def items(self) -> Iterable[tuple[str, DataResource]]:
'''Return dictionary of IDs and API items.'''
pass
def keys(self) -> list[str]:
'''Return item IDs.'''
pass
def values(self) -> list[DataResource]:
'''Return API items.'''
pass
def get(self, id: str, default: Any = None) -> DataResource | None:
'''Get API item based on key, if no match return default.'''
pass
def __getitem__(self, id: str) -> DataResource:
'''Get API item based on ID.'''
pass
def __iter__(self) -> Iterator[str]:
'''Allow iterate over item IDs.'''
pass
| 14 | 13 | 7 | 1 | 5 | 1 | 2 | 0.19 | 1 | 13 | 4 | 2 | 12 | 3 | 12 | 14 | 100 | 20 | 67 | 32 | 46 | 13 | 45 | 21 | 31 | 4 | 1 | 2 | 21 |
141,761 |
Kane610/deconz
|
pydeconz/interfaces/api_handlers.py
|
pydeconz.interfaces.api_handlers.APIHandler
|
class APIHandler(Generic[DataResource]):
"""Base class for a map of API Items."""
resource_group: ResourceGroup
resource_type = ResourceType.UNKNOWN
resource_types: set[ResourceType] | None = None
item_cls: Any
def __init__(self, gateway: DeconzSession, grouped: bool = False) -> None:
"""Initialize API handler."""
self.gateway = gateway
self._items: dict[str, DataResource] = {}
self._subscribers: dict[str, list[SubscriptionType]] = {ID_FILTER_ALL: []}
self.path = f"/{self.resource_group}"
if self.resource_types is None:
self.resource_types = {self.resource_type}
if not grouped:
self._event_subscribe()
def _event_subscribe(self) -> None:
"""Post initialization method."""
self.gateway.events.subscribe(
self.process_event,
event_filter=(EventType.ADDED, EventType.CHANGED),
resource_filter=self.resource_group,
)
async def update(self) -> None:
"""Refresh data."""
raw = await self.gateway.request("get", f"/{self.resource_group}")
self.process_raw(raw)
def process_raw(self, raw: dict[str, dict[str, Any]]) -> None:
"""Process full data."""
for id, raw_item in raw.items():
self.process_item(id, raw_item)
def process_event(self, event: Event) -> None:
"""Process event."""
if event.type == EventType.CHANGED and event.id in self:
self.process_item(event.id, event.changed_data)
return
if event.type == EventType.ADDED and event.id not in self:
self.process_item(event.id, event.added_data)
def process_item(self, id: str, raw: dict[str, Any]) -> None:
"""Process data."""
if id in self._items:
obj = self._items[id]
obj.update(raw)
event = EventType.CHANGED
else:
self._items[id] = self.item_cls(id, raw)
event = EventType.ADDED
subscribers: list[SubscriptionType] = (
self._subscribers.get(id, []) + self._subscribers[ID_FILTER_ALL]
)
for callback, event_filter in subscribers:
if event_filter is not None and event not in event_filter:
continue
callback(event, id)
def subscribe(
self,
callback: CallbackType,
event_filter: tuple[EventType, ...] | EventType | None = None,
id_filter: tuple[str] | str | None = None,
) -> UnsubscribeType:
"""Subscribe to events.
"callback" - callback function to call when on event.
Return function to unsubscribe.
"""
if isinstance(event_filter, EventType):
event_filter = (event_filter,)
_id_filter: tuple[str]
if id_filter is None:
_id_filter = (ID_FILTER_ALL,)
elif isinstance(id_filter, str):
_id_filter = (id_filter,)
subscription = (callback, event_filter)
for id in _id_filter:
if id not in self._subscribers:
self._subscribers[id] = []
self._subscribers[id].append(subscription)
def unsubscribe() -> None:
for id in _id_filter:
if id not in self._subscribers:
continue
self._subscribers[id].remove(subscription)
return unsubscribe
def items(self) -> ItemsView[str, DataResource]:
"""Return dictionary of IDs and API items."""
return self._items.items()
def keys(self) -> KeysView[str]:
"""Return item IDs."""
return self._items.keys()
def values(self) -> ValuesView[DataResource]:
"""Return API items."""
return self._items.values()
def get(self, id: str, default: Any = None) -> DataResource | Any | None:
"""Get API item based on key, if no match return default."""
return self._items.get(id, default)
def __getitem__(self, obj_id: str) -> DataResource:
"""Get API item based on ID."""
return self._items[obj_id]
def __iter__(self) -> Iterator[str]:
"""Allow iterate over item IDs."""
return iter(self._items)
|
class APIHandler(Generic[DataResource]):
'''Base class for a map of API Items.'''
def __init__(self, gateway: DeconzSession, grouped: bool = False) -> None:
'''Initialize API handler.'''
pass
def _event_subscribe(self) -> None:
'''Post initialization method.'''
pass
async def update(self) -> None:
'''Refresh data.'''
pass
def process_raw(self, raw: dict[str, dict[str, Any]]) -> None:
'''Process full data.'''
pass
def process_event(self, event: Event) -> None:
'''Process event.'''
pass
def process_item(self, id: str, raw: dict[str, Any]) -> None:
'''Process data.'''
pass
def subscribe(
self,
callback: CallbackType,
event_filter: tuple[EventType, ...] | EventType | None = None,
id_filter: tuple[str] | str | None = None,
) -> UnsubscribeType:
'''Subscribe to events.
"callback" - callback function to call when on event.
Return function to unsubscribe.
'''
pass
def unsubscribe() -> None:
pass
def items(self) -> ItemsView[str, DataResource]:
'''Return dictionary of IDs and API items.'''
pass
def keys(self) -> KeysView[str]:
'''Return item IDs.'''
pass
def values(self) -> ValuesView[DataResource]:
'''Return API items.'''
pass
def get(self, id: str, default: Any = None) -> DataResource | Any | None:
'''Get API item based on key, if no match return default.'''
pass
def __getitem__(self, obj_id: str) -> DataResource:
'''Get API item based on ID.'''
pass
def __iter__(self) -> Iterator[str]:
'''Allow iterate over item IDs.'''
pass
| 15 | 14 | 8 | 1 | 6 | 1 | 2 | 0.2 | 1 | 12 | 2 | 38 | 13 | 4 | 13 | 15 | 125 | 25 | 83 | 35 | 63 | 17 | 70 | 30 | 55 | 6 | 1 | 2 | 29 |
141,762 |
Kane610/deconz
|
pydeconz/interfaces/alarm_systems.py
|
pydeconz.interfaces.alarm_systems.AlarmSystems
|
class AlarmSystems(APIHandler[AlarmSystem]):
"""Manager of deCONZ alarm systems."""
item_cls = AlarmSystem
resource_group = ResourceGroup.ALARM
async def create_alarm_system(self, name: str) -> dict[str, Any]:
"""Create a new alarm system.
After creation the arm mode is set to disarmed.
"""
return await self.gateway.request(
"post",
path=self.path,
json={"name": name},
)
async def set_alarm_system_configuration(
self,
id: str,
code0: str | None = None,
armed_away_entry_delay: int | None = None,
armed_away_exit_delay: int | None = None,
armed_away_trigger_duration: int | None = None,
armed_night_entry_delay: int | None = None,
armed_night_exit_delay: int | None = None,
armed_night_trigger_duration: int | None = None,
armed_stay_entry_delay: int | None = None,
armed_stay_exit_delay: int | None = None,
armed_stay_trigger_duration: int | None = None,
disarmed_entry_delay: int | None = None,
disarmed_exit_delay: int | None = None,
) -> dict[str, Any]:
"""Set config of alarm system."""
data = {
key: value
for key, value in {
"code0": code0,
"armed_away_entry_delay": armed_away_entry_delay,
"armed_away_exit_delay": armed_away_exit_delay,
"armed_away_trigger_duration": armed_away_trigger_duration,
"armed_night_entry_delay": armed_night_entry_delay,
"armed_night_exit_delay": armed_night_exit_delay,
"armed_night_trigger_duration": armed_night_trigger_duration,
"armed_stay_entry_delay": armed_stay_entry_delay,
"armed_stay_exit_delay": armed_stay_exit_delay,
"armed_stay_trigger_duration": armed_stay_trigger_duration,
"disarmed_entry_delay": disarmed_entry_delay,
"disarmed_exit_delay": disarmed_exit_delay,
}.items()
if value is not None
}
return await self.gateway.request(
"put",
path=f"{self.path}/{id}/config",
json=data,
)
async def arm(
self,
id: str,
action: AlarmSystemArmAction,
pin_code: str,
) -> dict[str, Any]:
"""Set the alarm to away."""
return await self.gateway.request(
"put",
path=f"{self.path}/{id}/{action}",
json={"code0": pin_code},
)
async def add_device(
self,
id: str,
unique_id: str,
armed_away: bool = False,
armed_night: bool = False,
armed_stay: bool = False,
trigger: AlarmSystemDeviceTrigger | None = None,
is_keypad: bool = False,
) -> dict[str, Any]:
"""Link device with alarm system.
A device can be linked to exactly one alarm system.
If it is added to another alarm system, it is automatically removed
from the prior one.
This request is used for adding and also for updating a device entry.
The uniqueid refers to sensors, lights or keypads.
Adding a light can be useful, e.g. when an alarm should be triggered,
after a light is powered or switched on in the basement.
For keypads and keyfobs the request body can be an empty object.
"""
data = {"armmask": ""}
data["armmask"] += "A" if armed_away else ""
data["armmask"] += "N" if armed_night else ""
data["armmask"] += "S" if armed_stay else ""
if trigger:
data["trigger"] = trigger
if is_keypad:
data = {}
return await self.gateway.request(
"put",
path=f"{self.path}/{id}/device/{unique_id}",
json=data,
)
async def remove_device(self, id: str, unique_id: str) -> dict[str, Any]:
"""Unlink device with alarm system."""
return await self.gateway.request(
"delete",
path=f"{self.path}/{id}/device/{unique_id}",
)
|
class AlarmSystems(APIHandler[AlarmSystem]):
'''Manager of deCONZ alarm systems.'''
async def create_alarm_system(self, name: str) -> dict[str, Any]:
'''Create a new alarm system.
After creation the arm mode is set to disarmed.
'''
pass
async def set_alarm_system_configuration(
self,
id: str,
code0: str | None = None,
armed_away_entry_delay: int | None = None,
armed_away_exit_delay: int | None = None,
armed_away_trigger_duration: int | None = None,
armed_night_entry_delay: int | None = None,
armed_night_exit_delay: int | None = None,
armed_night_trigger_duration: int | None = None,
armed_stay_entry_delay: int | None = None,
armed_stay_exit_delay: int | None = None,
armed_stay_trigger_duration: int | None = None,
disarmed_entry_delay: int | None = None,
disarmed_exit_delay: int | None = None,
) -> dict[str, Any]:
'''Set config of alarm system.'''
pass
async def arm(
self,
id: str,
action: AlarmSystemArmAction,
pin_code: str,
) -> dict[str, Any]:
'''Set the alarm to away.'''
pass
async def add_device(
self,
id: str,
unique_id: str,
armed_away: bool = False,
armed_night: bool = False,
armed_stay: bool = False,
trigger: AlarmSystemDeviceTrigger | None = None,
is_keypad: bool = False,
) -> dict[str, Any]:
'''Link device with alarm system.
A device can be linked to exactly one alarm system.
If it is added to another alarm system, it is automatically removed
from the prior one.
This request is used for adding and also for updating a device entry.
The uniqueid refers to sensors, lights or keypads.
Adding a light can be useful, e.g. when an alarm should be triggered,
after a light is powered or switched on in the basement.
For keypads and keyfobs the request body can be an empty object.
'''
pass
async def remove_device(self, id: str, unique_id: str) -> dict[str, Any]:
'''Unlink device with alarm system.'''
pass
| 6 | 6 | 21 | 1 | 17 | 3 | 2 | 0.2 | 1 | 7 | 2 | 0 | 5 | 1 | 5 | 20 | 115 | 11 | 87 | 40 | 52 | 17 | 22 | 10 | 16 | 6 | 2 | 1 | 10 |
141,763 |
Kane610/deconz
|
pydeconz/models/sensor/switch.py
|
pydeconz.models.sensor.switch.TypedSwitchConfig
|
class TypedSwitchConfig(TypedDict):
"""Switch config type definition."""
devicemode: NotRequired[
Literal["dualpushbutton", "dualrocker", "singlepushbutton", "singlerocker"]
]
mode: NotRequired[Literal["momentary", "rocker"]]
windowcoveringtype: NotRequired[Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
|
class TypedSwitchConfig(TypedDict):
'''Switch config type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.17 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 1 | 6 | 1 | 5 | 1 | 4 | 1 | 3 | 0 | 1 | 0 | 0 |
141,764 |
Kane610/deconz
|
pydeconz/gateway.py
|
pydeconz.gateway.DeconzSession
|
class DeconzSession:
"""deCONZ representation that handles lights, groups, scenes and sensors."""
def __init__(
self,
session: aiohttp.ClientSession,
host: str,
port: int,
api_key: str | None = None,
connection_status: Callable[[bool], None] | None = None,
) -> None:
"""Session setup."""
self.session = session
self.host = host
self.port = port
self.api_key = api_key
self._sleep_tasks: dict[str, Task[None]] = {}
self.connection_status_callback = connection_status
self.config = Config({}, self.request)
self.events = EventHandler(self)
self.websocket: WSClient | None = None
self.alarm_systems = AlarmSystems(self)
self.groups = GroupHandler(self)
self.lights = LightResourceManager(self)
self.scenes = Scenes(self)
self.sensors = SensorResourceManager(self)
async def get_api_key(
self,
api_key: str | None = None,
client_name: str = "pydeconz",
) -> str:
"""Request a new API key.
Supported values:
- api_key [str] 10-40 characters, key to use for authentication
- client_name [str] 0-40 characters, name of the client application
"""
data = {
key: value
for key, value in {
"username": api_key,
"devicetype": client_name,
}.items()
if value is not None
}
response: list[dict[str, dict[str, str]]] = await self._request(
"post",
url=f"http://{self.host}:{self.port}/api",
json=data,
)
return response[0]["success"]["username"]
def start(self, websocketport: int | None = None) -> None:
"""Connect websocket to deCONZ."""
if self.config.websocket_port is not None:
websocketport = self.config.websocket_port
if not websocketport:
LOGGER.error("No websocket port specified")
return
self.websocket = WSClient(
self.session, self.host, websocketport, self.session_handler
)
self.websocket.start()
def close(self) -> None:
"""Close websession and websocket to deCONZ."""
if self.websocket:
self.websocket.stop()
async def refresh_state(self) -> None:
"""Read deCONZ parameters."""
data = await self.request("get", "")
self.config.raw.update(data[ResourceGroup.CONFIG])
self.alarm_systems.process_raw(data.get(ResourceGroup.ALARM, {}))
self.groups.process_raw(data[ResourceGroup.GROUP])
self.lights.process_raw(data[ResourceGroup.LIGHT])
self.sensors.process_raw(data[ResourceGroup.SENSOR])
def subscribe(self, callback: CallbackType) -> UnsubscribeType:
"""Subscribe to status changes for all resources."""
subscribers = [
self.alarm_systems.subscribe(callback),
self.groups.subscribe(callback),
self.lights.subscribe(callback),
self.sensors.subscribe(callback),
]
def unsubscribe() -> None:
for subscriber in subscribers:
subscriber()
return unsubscribe
async def request_with_retry(
self,
method: str,
path: str,
json: dict[str, Any] | None = None,
tries: int = 0,
) -> dict[str, Any]:
"""Make a request to the API, retry on BridgeBusy error."""
if sleep_task := self._sleep_tasks.pop(path, None):
sleep_task.cancel()
try:
return await self.request(method, path, json)
except BridgeBusy:
LOGGER.debug("Bridge is busy, schedule retry %s %s", path, str(json))
if (tries := tries + 1) < 3:
self._sleep_tasks[path] = sleep_task = create_task(sleep(2 ** (tries)))
try:
await sleep_task
except CancelledError:
return {}
return await self.request_with_retry(method, path, json, tries)
self._sleep_tasks.pop(path, None)
raise BridgeBusy
async def request(
self,
method: str,
path: str,
json: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Make a request to the API."""
response: dict[str, Any] = await self._request(
method,
url=f"http://{self.host}:{self.port}/api/{self.api_key}{path}",
json=json,
)
return response
async def _request(
self,
method: str,
url: str,
json: dict[str, Any] | None = None,
) -> Any:
"""Make a request."""
LOGGER.debug('Sending "%s" "%s" to "%s"', method, json, url)
try:
async with self.session.request(method, url, json=json) as res:
if res.content_type != "application/json":
raise ResponseError(
f"Invalid content type: {res.content_type} ({res})"
)
response = await res.json()
LOGGER.debug("HTTP request response: %s", pformat(response))
_raise_on_error(response)
return response
except aiohttp.client_exceptions.ClientError as err:
raise RequestError(
f"Error requesting data from {self.host}: {err}"
) from None
async def session_handler(self, signal: Signal) -> None:
"""Signalling from websocket.
data - new data available for processing.
state - network state has changed.
"""
if not self.websocket:
return
if signal == Signal.DATA:
self.events.handler(self.websocket.data)
elif signal == Signal.CONNECTION_STATE and self.connection_status_callback:
self.connection_status_callback(self.websocket.state == State.RUNNING)
|
class DeconzSession:
'''deCONZ representation that handles lights, groups, scenes and sensors.'''
def __init__(
self,
session: aiohttp.ClientSession,
host: str,
port: int,
api_key: str | None = None,
connection_status: Callable[[bool], None] | None = None,
) -> None:
'''Session setup.'''
pass
async def get_api_key(
self,
api_key: str | None = None,
client_name: str = "pydeconz",
) -> str:
'''Request a new API key.
Supported values:
- api_key [str] 10-40 characters, key to use for authentication
- client_name [str] 0-40 characters, name of the client application
'''
pass
def start(self, websocketport: int | None = None) -> None:
'''Connect websocket to deCONZ.'''
pass
def close(self) -> None:
'''Close websession and websocket to deCONZ.'''
pass
async def refresh_state(self) -> None:
'''Read deCONZ parameters.'''
pass
def subscribe(self, callback: CallbackType) -> UnsubscribeType:
'''Subscribe to status changes for all resources.'''
pass
def unsubscribe() -> None:
pass
async def request_with_retry(
self,
method: str,
path: str,
json: dict[str, Any] | None = None,
tries: int = 0,
) -> dict[str, Any]:
'''Make a request to the API, retry on BridgeBusy error.'''
pass
async def request_with_retry(
self,
method: str,
path: str,
json: dict[str, Any] | None = None,
tries: int = 0,
) -> dict[str, Any]:
'''Make a request to the API.'''
pass
async def _request(
self,
method: str,
url: str,
json: dict[str, Any] | None = None,
) -> Any:
'''Make a request.'''
pass
async def session_handler(self, signal: Signal) -> None:
'''Signalling from websocket.
data - new data available for processing.
state - network state has changed.
'''
pass
| 12 | 11 | 16 | 2 | 12 | 2 | 2 | 0.13 | 0 | 24 | 14 | 0 | 10 | 14 | 10 | 10 | 189 | 36 | 135 | 63 | 96 | 18 | 81 | 33 | 69 | 5 | 0 | 3 | 24 |
141,765 |
Kane610/deconz
|
pydeconz/models/sensor/switch.py
|
pydeconz.models.sensor.switch.TypedSwitchState
|
class TypedSwitchState(TypedDict):
"""Switch state type definition."""
angle: int
buttonevent: int
eventduration: int
gesture: int
xy: tuple[float, float]
|
class TypedSwitchState(TypedDict):
'''Switch state type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.17 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | 1 | 6 | 1 | 5 | 1 | 6 | 1 | 5 | 0 | 1 | 0 | 0 |
141,766 |
Kane610/deconz
|
pydeconz/models/sensor/vibration.py
|
pydeconz.models.sensor.vibration.TypedVibrationState
|
class TypedVibrationState(TypedDict):
"""Vibration state type definition."""
orientation: list[str]
tiltangle: int
vibration: bool
vibrationstrength: int
|
class TypedVibrationState(TypedDict):
'''Vibration state type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 7 | 1 | 5 | 1 | 4 | 1 | 5 | 1 | 4 | 0 | 1 | 0 | 0 |
141,767 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.PresenceHandler
|
class PresenceHandler(APIHandler[Presence]):
"""Handler for presence sensor."""
resource_group = ResourceGroup.SENSOR
resource_types = {
ResourceType.ZHA_PRESENCE,
ResourceType.CLIP_PRESENCE,
}
item_cls = Presence
async def set_config(
self,
id: str,
delay: int | None = None,
device_mode: PresenceConfigDeviceMode | None = None,
duration: int | None = None,
reset_presence: bool | None = None,
sensitivity: int | None = None,
trigger_distance: PresenceConfigTriggerDistance | None = None,
) -> dict[str, Any]:
"""Change config of presence sensor.
Supported values:
- delay [int] 0-65535 (in seconds)
- device_mode [str]
- leftright
- undirected
- duration [int] 0-65535 (in seconds)
- reset_presence [bool] True/False
- sensitivity [int] 0-[sensitivitymax]
- trigger_distance [str]
- far
- medium
- near
"""
data: dict[str, int | str] = {
key: value
for key, value in {
"delay": delay,
"duration": duration,
"resetpresence": reset_presence,
"sensitivity": sensitivity,
}.items()
if value is not None
}
if device_mode is not None:
data["devicemode"] = device_mode
if trigger_distance is not None:
data["triggerdistance"] = trigger_distance
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json=data,
)
|
class PresenceHandler(APIHandler[Presence]):
'''Handler for presence sensor.'''
async def set_config(
self,
id: str,
delay: int | None = None,
device_mode: PresenceConfigDeviceMode | None = None,
duration: int | None = None,
reset_presence: bool | None = None,
sensitivity: int | None = None,
trigger_distance: PresenceConfigTriggerDistance | None = None,
) -> dict[str, Any]:
'''Change config of presence sensor.
Supported values:
- delay [int] 0-65535 (in seconds)
- device_mode [str]
- leftright
- undirected
- duration [int] 0-65535 (in seconds)
- reset_presence [bool] True/False
- sensitivity [int] 0-[sensitivitymax]
- trigger_distance [str]
- far
- medium
- near
'''
pass
| 2 | 2 | 44 | 1 | 29 | 14 | 3 | 0.42 | 1 | 7 | 2 | 0 | 1 | 0 | 1 | 16 | 54 | 3 | 36 | 15 | 25 | 15 | 11 | 6 | 9 | 3 | 2 | 1 | 3 |
141,768 |
Kane610/deconz
|
pydeconz/models/sensor/vibration.py
|
pydeconz.models.sensor.vibration.TypedVibration
|
class TypedVibration(TypedDict):
"""Vibration type definition."""
config: TypedVibrationConfig
state: TypedVibrationState
|
class TypedVibration(TypedDict):
'''Vibration type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 3 | 1 | 2 | 1 | 3 | 1 | 2 | 0 | 1 | 0 | 0 |
141,769 |
Kane610/deconz
|
pydeconz/models/sensor/time.py
|
pydeconz.models.sensor.time.TypedTimeState
|
class TypedTimeState(TypedDict):
"""Time state type definition."""
lastset: str
|
class TypedTimeState(TypedDict):
'''Time state type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
141,770 |
Kane610/deconz
|
pydeconz/models/sensor/time.py
|
pydeconz.models.sensor.time.TypedTime
|
class TypedTime(TypedDict):
"""Time type definition."""
state: TypedTimeState
|
class TypedTime(TypedDict):
'''Time type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
141,771 |
Kane610/deconz
|
pydeconz/models/sensor/time.py
|
pydeconz.models.sensor.time.Time
|
class Time(SensorBase):
"""Time sensor."""
raw: TypedTime
@property
def last_set(self) -> str:
"""Last time time was set."""
return self.raw["state"]["lastset"]
|
class Time(SensorBase):
'''Time sensor.'''
@property
def last_set(self) -> str:
'''Last time time was set.'''
pass
| 3 | 2 | 3 | 0 | 2 | 1 | 1 | 0.4 | 1 | 1 | 0 | 0 | 1 | 0 | 1 | 21 | 9 | 2 | 5 | 3 | 2 | 2 | 4 | 2 | 2 | 1 | 3 | 0 | 1 |
141,772 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.TypedThermostatState
|
class TypedThermostatState(TypedDict):
"""Thermostat state type definition."""
errorcode: bool
floortemperature: int
heating: bool
mountingmodeactive: bool
on: bool
temperature: int
valve: int
|
class TypedThermostatState(TypedDict):
'''Thermostat state type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.13 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 1 | 8 | 1 | 7 | 1 | 8 | 1 | 7 | 0 | 1 | 0 | 0 |
141,773 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.TypedThermostatConfig
|
class TypedThermostatConfig(TypedDict):
"""Thermostat config type definition."""
coolsetpoint: int
displayflipped: bool
externalsensortemp: int
externalwindowopen: bool
fanmode: NotRequired[Literal["off", "low", "medium", "high", "on", "auto", "smart"]]
heatsetpoint: int
locked: bool
mode: NotRequired[
Literal[
"off",
"auto",
"cool",
"heat",
"emergency heating",
"precooling",
"fan only",
"dry",
"sleep",
]
]
mountingmode: bool
offset: int
preset: NotRequired[
Literal[
"auto", "boost", "comfort", "complex", "eco", "holiday", "manual", "program"
]
]
schedule_on: bool
swingmode: NotRequired[
Literal[
"fully closed",
"fully open",
"quarter open",
"half open",
"three quarters open",
]
]
temperaturemeasurement: NotRequired[
Literal["air sensor", "floor sensor", "floor protection"]
]
windowopen_set: bool
|
class TypedThermostatConfig(TypedDict):
'''Thermostat config type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.02 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 44 | 1 | 42 | 1 | 41 | 1 | 16 | 1 | 15 | 0 | 1 | 0 | 0 |
141,774 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.TypedThermostat
|
class TypedThermostat(TypedDict):
"""Thermostat type definition."""
config: TypedThermostatConfig
state: TypedThermostatState
|
class TypedThermostat(TypedDict):
'''Thermostat type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 3 | 1 | 2 | 1 | 3 | 1 | 2 | 0 | 1 | 0 | 0 |
141,775 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.ThermostatTemperatureMeasurement
|
class ThermostatTemperatureMeasurement(enum.StrEnum):
"""Set the mode of operation for Elko Super TR thermostat.
Supported values:
- "air sensor"
- "floor sensor"
- "floor protection"
"""
AIR_SENSOR = "air sensor"
FLOOR_SENSOR = "floor sensor"
FLOOR_PROTECTION = "floor protection"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value: object) -> ThermostatTemperatureMeasurement:
"""Set default enum member if an unknown value is provided."""
LOGGER.warning("Unexpected thermostat temperature measurement %s", value)
return cls.UNKNOWN
|
class ThermostatTemperatureMeasurement(enum.StrEnum):
'''Set the mode of operation for Elko Super TR thermostat.
Supported values:
- "air sensor"
- "floor sensor"
- "floor protection"
'''
@classmethod
def _missing_(cls, value: object) -> ThermostatTemperatureMeasurement:
'''Set default enum member if an unknown value is provided.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.78 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 69 | 20 | 4 | 9 | 7 | 6 | 7 | 8 | 6 | 6 | 1 | 3 | 0 | 1 |
141,776 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.ThermostatSwingMode
|
class ThermostatSwingMode(enum.StrEnum):
"""Set the AC louvers position.
Supported values:
- "fully closed"
- "fully open"
- "quarter open"
- "half open"
- "three quarters open"
"""
FULLY_CLOSED = "fully closed"
FULLY_OPEN = "fully open"
QUARTER_OPEN = "quarter open"
HALF_OPEN = "half open"
THREE_QUARTERS_OPEN = "three quarters open"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value: object) -> ThermostatSwingMode:
"""Set default enum member if an unknown value is provided."""
LOGGER.warning("Unexpected thermostat swing mode %s", value)
return cls.UNKNOWN
|
class ThermostatSwingMode(enum.StrEnum):
'''Set the AC louvers position.
Supported values:
- "fully closed"
- "fully open"
- "quarter open"
- "half open"
- "three quarters open"
'''
@classmethod
def _missing_(cls, value: object) -> ThermostatSwingMode:
'''Set default enum member if an unknown value is provided.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.82 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 69 | 24 | 4 | 11 | 9 | 8 | 9 | 10 | 8 | 8 | 1 | 3 | 0 | 1 |
141,777 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.ThermostatPreset
|
class ThermostatPreset(enum.StrEnum):
"""Set the current operating mode for Tuya thermostats.
Supported values:
- "auto"
- "boost"
- "comfort"
- "complex"
- "eco"
- "holiday"
- "manual"
- "program"
"""
AUTO = "auto"
BOOST = "boost"
COMFORT = "comfort"
COMPLEX = "complex"
ECO = "eco"
HOLIDAY = "holiday"
MANUAL = "manual"
PROGRAM = "program"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value: object) -> ThermostatPreset:
"""Set default enum member if an unknown value is provided."""
LOGGER.warning("Unexpected thermostat preset %s", value)
return cls.UNKNOWN
|
class ThermostatPreset(enum.StrEnum):
'''Set the current operating mode for Tuya thermostats.
Supported values:
- "auto"
- "boost"
- "comfort"
- "complex"
- "eco"
- "holiday"
- "manual"
- "program"
'''
@classmethod
def _missing_(cls, value: object) -> ThermostatPreset:
'''Set default enum member if an unknown value is provided.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.86 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 69 | 30 | 4 | 14 | 12 | 11 | 12 | 13 | 11 | 11 | 1 | 3 | 0 | 1 |
141,778 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.ThermostatMode
|
class ThermostatMode(enum.StrEnum):
"""Set the current operating mode of a thermostat.
Supported values:
- "off"
- "auto"
- "cool"
- "heat"
- "emergency heating"
- "precooling"
- "fan only"
- "dry"
- "sleep"
"""
OFF = "off"
AUTO = "auto"
COOL = "cool"
HEAT = "heat"
EMERGENCY_HEATING = "emergency heating"
PRE_COOLING = "precooling"
FAN_ONLY = "fan only"
DRY = "dry"
SLEEP = "sleep"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value: object) -> ThermostatMode:
"""Set default enum member if an unknown value is provided."""
LOGGER.warning("Unexpected thermostat mode %s", value)
return cls.UNKNOWN
|
class ThermostatMode(enum.StrEnum):
'''Set the current operating mode of a thermostat.
Supported values:
- "off"
- "auto"
- "cool"
- "heat"
- "emergency heating"
- "precooling"
- "fan only"
- "dry"
- "sleep"
'''
@classmethod
def _missing_(cls, value: object) -> ThermostatMode:
'''Set default enum member if an unknown value is provided.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.87 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 69 | 32 | 4 | 15 | 13 | 12 | 13 | 14 | 12 | 12 | 1 | 3 | 0 | 1 |
141,779 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.ThermostatFanMode
|
class ThermostatFanMode(enum.StrEnum):
"""Fan mode.
Supported values:
- "off"
- "low"
- "medium"
- "high"
- "on"
- "auto"
- "smart"
"""
OFF = "off"
LOW = "low"
MEDIUM = "medium"
HIGH = "high"
ON = "on"
AUTO = "auto"
SMART = "smart"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value: object) -> ThermostatFanMode:
"""Set default enum member if an unknown value is provided."""
LOGGER.warning("Unexpected thermostat fan mode %s", value)
return cls.UNKNOWN
|
class ThermostatFanMode(enum.StrEnum):
'''Fan mode.
Supported values:
- "off"
- "low"
- "medium"
- "high"
- "on"
- "auto"
- "smart"
'''
@classmethod
def _missing_(cls, value: object) -> ThermostatFanMode:
'''Set default enum member if an unknown value is provided.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.85 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 69 | 28 | 4 | 13 | 11 | 10 | 11 | 12 | 10 | 10 | 1 | 3 | 0 | 1 |
141,780 |
Kane610/deconz
|
pydeconz/models/sensor/thermostat.py
|
pydeconz.models.sensor.thermostat.Thermostat
|
class Thermostat(SensorBase):
"""Thermostat "sensor"."""
raw: TypedThermostat
@property
def cooling_setpoint(self) -> int | None:
"""Cooling setpoint.
700-3500.
"""
return self.raw["config"].get("coolsetpoint")
@property
def scaled_cooling_setpoint(self) -> float | None:
"""Cooling setpoint.
7-35.
"""
if temperature := self.cooling_setpoint:
return round(temperature / 100, 1)
return None
@property
def display_flipped(self) -> bool | None:
"""Tells if display for TRVs is flipped."""
return self.raw["config"].get("displayflipped")
@property
def error_code(self) -> bool | None:
"""Error code."""
return self.raw["state"].get("errorcode")
@property
def external_sensor_temperature(self) -> int | None:
"""Track temperature value provided by an external sensor.
-32768–32767.
Device dependent and only exposed for devices supporting it.
"""
return self.raw["config"].get("externalsensortemp")
@property
def scaled_external_sensor_temperature(self) -> float | None:
"""Track temperature value provided by an external sensor.
-327–327.
"""
if temperature := self.external_sensor_temperature:
return round(temperature / 100, 1)
return None
@property
def external_window_open(self) -> bool | None:
"""Track open/close state of an external sensor.
Device dependent and only exposed for devices supporting it.
"""
return self.raw["config"].get("externalwindowopen")
@property
def fan_mode(self) -> ThermostatFanMode | None:
"""Fan mode."""
if "fanmode" in self.raw["config"]:
return ThermostatFanMode(self.raw["config"]["fanmode"])
return None
@property
def floor_temperature(self) -> int | None:
"""Floor temperature."""
return self.raw["state"].get("floortemperature")
@property
def scaled_floor_temperature(self) -> float | None:
"""Floor temperature."""
if temperature := self.floor_temperature:
return round(temperature / 100, 1)
return None
@property
def heating(self) -> bool | None:
"""Heating setpoint."""
return self.raw["state"].get("heating")
@property
def heating_setpoint(self) -> int | None:
"""Heating setpoint.
500-3200.
"""
return self.raw["config"].get("heatsetpoint")
@property
def scaled_heating_setpoint(self) -> float | None:
"""Heating setpoint.
5-32.
"""
if temperature := self.heating_setpoint:
return round(temperature / 100, 1)
return None
@property
def locked(self) -> bool | None:
"""Child lock active/inactive for thermostats/TRVs supporting it."""
return self.raw["config"].get("locked")
@property
def mode(self) -> ThermostatMode | None:
"""Set the current operating mode of a thermostat."""
if "mode" in self.raw["config"]:
return ThermostatMode(self.raw["config"]["mode"])
return None
@property
def mounting_mode(self) -> bool | None:
"""Set a TRV into mounting mode if supported (valve fully open position)."""
return self.raw["config"].get("mountingmode")
@property
def mounting_mode_active(self) -> bool | None:
"""If thermostat mounting mode is active."""
return self.raw["state"].get("mountingmodeactive")
@property
def offset(self) -> int | None:
"""Add a signed offset value to measured temperature and humidity state values.
Values send by the REST-API are already amended by the offset.
"""
return self.raw["config"].get("offset")
@property
def preset(self) -> ThermostatPreset | None:
"""Set the current operating mode for Tuya thermostats."""
if "preset" in self.raw["config"]:
return ThermostatPreset(self.raw["config"]["preset"])
return None
@property
def schedule_enabled(self) -> bool | None:
"""Tell when thermostat schedule is enabled."""
return self.raw["config"].get("schedule_on")
@property
def state_on(self) -> bool | None:
"""Declare if the sensor is on or off."""
return self.raw["state"].get("on")
@property
def swing_mode(self) -> ThermostatSwingMode | None:
"""Set the AC louvers position."""
if "swingmode" in self.raw["config"]:
return ThermostatSwingMode(self.raw["config"]["swingmode"])
return None
@property
def temperature(self) -> int:
"""Temperature."""
return self.raw["state"]["temperature"]
@property
def scaled_temperature(self) -> float:
"""Scaled temperature."""
return round(self.temperature / 100, 1)
@property
def temperature_measurement(self) -> ThermostatTemperatureMeasurement | None:
"""Set the mode of operation for Elko Super TR thermostat."""
if "temperaturemeasurement" in self.raw["config"]:
return ThermostatTemperatureMeasurement(
self.raw["config"]["temperaturemeasurement"]
)
return None
@property
def valve(self) -> int | None:
"""How open the valve is."""
return self.raw["state"].get("valve")
@property
def window_open_detection(self) -> bool | None:
"""Set window open detection should be active or inactive for Tuya thermostats.
Device dependent and only exposed for devices supporting it.
"""
return self.raw["config"].get("windowopen_set")
|
class Thermostat(SensorBase):
'''Thermostat "sensor".'''
@property
def cooling_setpoint(self) -> int | None:
'''Cooling setpoint.
700-3500.
'''
pass
@property
def scaled_cooling_setpoint(self) -> float | None:
'''Cooling setpoint.
7-35.
'''
pass
@property
def display_flipped(self) -> bool | None:
'''Tells if display for TRVs is flipped.'''
pass
@property
def error_code(self) -> bool | None:
'''Error code.'''
pass
@property
def external_sensor_temperature(self) -> int | None:
'''Track temperature value provided by an external sensor.
-32768–32767.
Device dependent and only exposed for devices supporting it.
'''
pass
@property
def scaled_external_sensor_temperature(self) -> float | None:
'''Track temperature value provided by an external sensor.
-327–327.
'''
pass
@property
def external_window_open(self) -> bool | None:
'''Track open/close state of an external sensor.
Device dependent and only exposed for devices supporting it.
'''
pass
@property
def fan_mode(self) -> ThermostatFanMode | None:
'''Fan mode.'''
pass
@property
def floor_temperature(self) -> int | None:
'''Floor temperature.'''
pass
@property
def scaled_floor_temperature(self) -> float | None:
'''Floor temperature.'''
pass
@property
def heating(self) -> bool | None:
'''Heating setpoint.'''
pass
@property
def heating_setpoint(self) -> int | None:
'''Heating setpoint.
500-3200.
'''
pass
@property
def scaled_heating_setpoint(self) -> float | None:
'''Heating setpoint.
5-32.
'''
pass
@property
def locked(self) -> bool | None:
'''Child lock active/inactive for thermostats/TRVs supporting it.'''
pass
@property
def mode(self) -> ThermostatMode | None:
'''Set the current operating mode of a thermostat.'''
pass
@property
def mounting_mode(self) -> bool | None:
'''Set a TRV into mounting mode if supported (valve fully open position).'''
pass
@property
def mounting_mode_active(self) -> bool | None:
'''If thermostat mounting mode is active.'''
pass
@property
def offset(self) -> int | None:
'''Add a signed offset value to measured temperature and humidity state values.
Values send by the REST-API are already amended by the offset.
'''
pass
@property
def preset(self) -> ThermostatPreset | None:
'''Set the current operating mode for Tuya thermostats.'''
pass
@property
def schedule_enabled(self) -> bool | None:
'''Tell when thermostat schedule is enabled.'''
pass
@property
def state_on(self) -> bool | None:
'''Declare if the sensor is on or off.'''
pass
@property
def swing_mode(self) -> ThermostatSwingMode | None:
'''Set the AC louvers position.'''
pass
@property
def temperature(self) -> int:
'''Temperature.'''
pass
@property
def scaled_temperature(self) -> float:
'''Scaled temperature.'''
pass
@property
def temperature_measurement(self) -> ThermostatTemperatureMeasurement | None:
'''Set the mode of operation for Elko Super TR thermostat.'''
pass
@property
def valve(self) -> int | None:
'''How open the valve is.'''
pass
@property
def window_open_detection(self) -> bool | None:
'''Set window open detection should be active or inactive for Tuya thermostats.
Device dependent and only exposed for devices supporting it.
'''
pass
| 55 | 28 | 5 | 0 | 3 | 2 | 1 | 0.46 | 1 | 8 | 5 | 0 | 27 | 0 | 27 | 47 | 187 | 37 | 103 | 59 | 48 | 47 | 74 | 28 | 46 | 2 | 3 | 1 | 36 |
141,781 |
Kane610/deconz
|
pydeconz/models/sensor/temperature.py
|
pydeconz.models.sensor.temperature.TypedTemperatureState
|
class TypedTemperatureState(TypedDict):
"""Temperature state type definition."""
temperature: int
|
class TypedTemperatureState(TypedDict):
'''Temperature state type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
141,782 |
Kane610/deconz
|
pydeconz/models/sensor/temperature.py
|
pydeconz.models.sensor.temperature.TypedTemperature
|
class TypedTemperature(TypedDict):
"""Temperature type definition."""
state: TypedTemperatureState
|
class TypedTemperature(TypedDict):
'''Temperature type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.5 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 4 | 1 | 2 | 1 | 1 | 1 | 2 | 1 | 1 | 0 | 1 | 0 | 0 |
141,783 |
Kane610/deconz
|
pydeconz/models/sensor/vibration.py
|
pydeconz.models.sensor.vibration.TypedVibrationConfig
|
class TypedVibrationConfig(TypedDict):
"""Vibration config type definition."""
sensitivity: int
sensitivitymax: int
|
class TypedVibrationConfig(TypedDict):
'''Vibration config type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 3 | 1 | 2 | 1 | 3 | 1 | 2 | 0 | 1 | 0 | 0 |
141,784 |
Kane610/deconz
|
pydeconz/models/sensor/temperature.py
|
pydeconz.models.sensor.temperature.Temperature
|
class Temperature(SensorBase):
"""Temperature sensor."""
raw: TypedTemperature
@property
def temperature(self) -> int:
"""Temperature."""
return self.raw["state"]["temperature"]
@property
def scaled_temperature(self) -> float:
"""Scaled temperature."""
return self.temperature / 100
|
class Temperature(SensorBase):
'''Temperature sensor.'''
@property
def temperature(self) -> int:
'''Temperature.'''
pass
@property
def scaled_temperature(self) -> float:
'''Scaled temperature.'''
pass
| 5 | 3 | 3 | 0 | 2 | 1 | 1 | 0.38 | 1 | 2 | 0 | 0 | 2 | 0 | 2 | 22 | 14 | 3 | 8 | 5 | 3 | 3 | 6 | 3 | 3 | 1 | 3 | 0 | 2 |
141,785 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.LockHandler
|
class LockHandler(APIHandler[Lock]):
"""Handler for fans."""
resource_group = ResourceGroup.LIGHT
resource_type = ResourceType.DOOR_LOCK
item_cls = Lock
async def set_state(self, id: str, lock: bool) -> dict[str, Any]:
"""Set state of lock.
Supported values:
- lock [bool] True/False.
"""
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/state",
json={"on": lock},
)
|
class LockHandler(APIHandler[Lock]):
'''Handler for fans.'''
async def set_state(self, id: str, lock: bool) -> dict[str, Any]:
'''Set state of lock.
Supported values:
- lock [bool] True/False.
'''
pass
| 2 | 2 | 11 | 1 | 6 | 4 | 1 | 0.5 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 16 | 18 | 3 | 10 | 5 | 8 | 5 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
141,786 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.RangeExtenderHandler
|
class RangeExtenderHandler(APIHandler[ConfigurationTool]):
"""Handler for range extender."""
resource_group = ResourceGroup.LIGHT
resource_type = ResourceType.RANGE_EXTENDER
item_cls = RangeExtender
|
class RangeExtenderHandler(APIHandler[ConfigurationTool]):
'''Handler for range extender.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,787 |
Kane610/deconz
|
pydeconz/interfaces/lights.py
|
pydeconz.interfaces.lights.SirenHandler
|
class SirenHandler(APIHandler[Siren]):
"""Handler for sirens."""
resource_group = ResourceGroup.LIGHT
resource_type = ResourceType.WARNING_DEVICE
item_cls = Siren
async def set_state(
self,
id: str,
on: bool,
duration: int | None = None,
) -> dict[str, Any]:
"""Turn on device.
Supported values:
- on [bool] True/False
- duration [int] 1/10th of a second
"""
data: dict[str, int | str] = {}
data["alert"] = LightAlert.LONG if on else LightAlert.NONE
if on and duration is not None:
data["ontime"] = duration
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/state",
json=data,
)
|
class SirenHandler(APIHandler[Siren]):
'''Handler for sirens.'''
async def set_state(
self,
id: str,
on: bool,
duration: int | None = None,
) -> dict[str, Any]:
'''Turn on device.
Supported values:
- on [bool] True/False
- duration [int] 1/10th of a second
'''
pass
| 2 | 2 | 23 | 3 | 15 | 5 | 3 | 0.32 | 1 | 6 | 1 | 0 | 1 | 0 | 1 | 16 | 30 | 5 | 19 | 11 | 12 | 6 | 10 | 6 | 8 | 3 | 2 | 1 | 3 |
141,788 |
Kane610/deconz
|
pydeconz/config.py
|
pydeconz.config.ConfigUpdateChannel
|
class ConfigUpdateChannel(enum.StrEnum):
"""Available update channels to use with the Gateway."""
ALPHA = "alpha"
BETA = "beta"
STABLE = "stable"
|
class ConfigUpdateChannel(enum.StrEnum):
'''Available update channels to use with the Gateway.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 3 | 0 | 0 |
141,789 |
Kane610/deconz
|
pydeconz/config.py
|
pydeconz.config.ConfigTimeFormat
|
class ConfigTimeFormat(enum.StrEnum):
"""Tells if the NTP time is "synced" or "unsynced"."""
FORMAT_12H = "12h"
FORMAT_24H = "24h"
|
class ConfigTimeFormat(enum.StrEnum):
'''Tells if the NTP time is "synced" or "unsynced".'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 5 | 1 | 3 | 3 | 2 | 1 | 3 | 3 | 2 | 0 | 3 | 0 | 0 |
141,790 |
Kane610/deconz
|
pydeconz/config.py
|
pydeconz.config.ConfigNTP
|
class ConfigNTP(enum.StrEnum):
"""Timeformat that can be used by other applications."""
SYNCED = "synced"
UNSYNCED = "unsynced"
|
class ConfigNTP(enum.StrEnum):
'''Timeformat that can be used by other applications.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 5 | 1 | 3 | 3 | 2 | 1 | 3 | 3 | 2 | 0 | 3 | 0 | 0 |
141,791 |
Kane610/deconz
|
pydeconz/models/sensor/switch.py
|
pydeconz.models.sensor.switch.TypedSwitch
|
class TypedSwitch(TypedDict):
"""Switch type definition."""
config: TypedSwitchConfig
state: TypedSwitchState
|
class TypedSwitch(TypedDict):
'''Switch type definition.'''
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 5 | 1 | 3 | 1 | 2 | 1 | 3 | 1 | 2 | 0 | 1 | 0 | 0 |
141,792 |
Kane610/deconz
|
pydeconz/models/sensor/switch.py
|
pydeconz.models.sensor.switch.SwitchWindowCoveringType
|
class SwitchWindowCoveringType(enum.IntEnum):
"""Set the covering type and starts calibration for Ubisys J1."""
ROLLER_SHADE = 0
ROLLER_SHADE_TWO_MOTORS = 1
ROLLER_SHADE_EXTERIOR = 2
ROLLER_SHADE_TWO_MOTORS_EXTERIOR = 3
DRAPERY = 4
AWNING = 5
SHUTTER = 6
TILT_BLIND_LIFT_ONLY = 7
TILT_BLIND_LIFT_AND_TILT = 8
PROJECTOR_SCREEN = 9
|
class SwitchWindowCoveringType(enum.IntEnum):
'''Set the covering type and starts calibration for Ubisys J1.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.09 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 55 | 13 | 1 | 11 | 11 | 10 | 1 | 11 | 11 | 10 | 0 | 3 | 0 | 0 |
141,793 |
Kane610/deconz
|
pydeconz/config.py
|
pydeconz.config.ConfigDeviceName
|
class ConfigDeviceName(enum.StrEnum):
"""Valid product names of the gateway."""
CONBEE = "ConBee"
RASPBEE = "RaspBee"
CONBEE_2 = "ConBee II"
RASPBEE_2 = "RaspBee II"
UNKNOWN = "unknown"
@classmethod
def _missing_(cls, value: object) -> ConfigDeviceName:
"""Set default enum member if an unknown value is provided."""
LOGGER.warning("Unexpected config device name %s", value)
return cls.UNKNOWN
|
class ConfigDeviceName(enum.StrEnum):
'''Valid product names of the gateway.'''
@classmethod
def _missing_(cls, value: object) -> ConfigDeviceName:
'''Set default enum member if an unknown value is provided.'''
pass
| 3 | 2 | 4 | 0 | 3 | 1 | 1 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 69 | 15 | 3 | 10 | 8 | 7 | 2 | 9 | 7 | 7 | 1 | 3 | 0 | 1 |
141,794 |
Kane610/deconz
|
pydeconz/models/sensor/switch.py
|
pydeconz.models.sensor.switch.SwitchMode
|
class SwitchMode(enum.StrEnum):
"""For Ubisys S1/S2, operation mode of the switch."""
MOMENTARY = "momentary"
ROCKER = "rocker"
|
class SwitchMode(enum.StrEnum):
'''For Ubisys S1/S2, operation mode of the switch.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.33 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 68 | 5 | 1 | 3 | 3 | 2 | 1 | 3 | 3 | 2 | 0 | 3 | 0 | 0 |
141,795 |
Kane610/deconz
|
pydeconz/config.py
|
pydeconz.config.Config
|
class Config:
"""deCONZ configuration representation.
Dresden Elektroniks documentation of config in deCONZ
http://dresden-elektronik.github.io/deconz-rest-doc/config/
"""
def __init__(
self,
raw: dict[str, Any],
request: Callable[..., Awaitable[dict[str, Any]]],
) -> None:
"""Set configuration about deCONZ gateway."""
self.raw = raw
self.request = request
@property
def api_version(self) -> str | None:
"""Version of the deCONZ Rest API."""
return self.raw.get("apiversion")
@property
def bridge_id(self) -> str:
"""Gateway unique identifier."""
return normalize_bridge_id(self.raw.get("bridgeid", UNINITIALIZED_BRIDGE_ID))
@property
def device_name(self) -> ConfigDeviceName:
"""Product name of the gateway.
Valid values are "ConBee", "RaspBee", "ConBee II" and "RaspBee II".
"""
return ConfigDeviceName(self.raw.get("devicename") or "")
@property
def dhcp(self) -> bool | None:
"""Whether the IP address of the bridge is obtained with DHCP."""
return self.raw.get("dhcp")
@property
def firmware_version(self) -> str | None:
"""Version of the ZigBee firmware."""
return self.raw.get("fwversion")
@property
def gateway(self) -> str | None:
"""IPv4 address of the gateway."""
return self.raw.get("gateway")
@property
def ip_address(self) -> str | None:
"""IPv4 address of the gateway."""
return self.raw.get("ipaddress")
@property
def link_button(self) -> bool | None:
"""Is gateway unlocked."""
return self.raw.get("linkbutton")
@property
def local_time(self) -> str | None:
"""Localtime of the gateway."""
return self.raw.get("localtime")
@property
def mac(self) -> str | None:
"""MAC address of gateway."""
return self.raw.get("mac")
@property
def model_id(self) -> str | None:
"""Model identifyer.
Fixed string "deCONZ".
"""
return self.raw.get("modelid")
@property
def name(self) -> str | None:
"""Name of the gateway."""
return self.raw.get("name")
@property
def network_mask(self) -> str | None:
"""Network mask of the gateway."""
return self.raw.get("netmask")
@property
def network_open_duration(self) -> int | None:
"""Duration in seconds used by lights and sensors search."""
return self.raw.get("networkopenduration")
@property
def ntp(self) -> ConfigNTP | None:
"""Tells if the NTP time is "synced" or "unsynced".
Only for gateways running on Linux.
"""
if "ntp" in self.raw:
return ConfigNTP(self.raw["ntp"])
return None
@property
def pan_id(self) -> int | None:
"""Zigbee pan ID of the gateway."""
return self.raw.get("panid")
@property
def portal_services(self) -> bool | None:
"""State of registration to portal service.
Is the bridge registered to synchronize data with a portal account.
"""
return self.raw.get("portalservices")
@property
def rf_connected(self) -> bool | None:
"""State of deCONZ connection to firmware and if Zigbee network is up."""
return self.raw.get("rfconnected")
@property
def software_update(self) -> dict[str, Any] | None:
"""Contains information related to software updates."""
return self.raw.get("swupdate")
@property
def software_version(self) -> str | None:
"""Software version of the gateway."""
return self.raw.get("swversion")
@property
def time_format(self) -> ConfigTimeFormat:
"""Timeformat used by gateway.
Supported values:
"12h" or "24h"
"""
return ConfigTimeFormat(self.raw["timeformat"])
@property
def time_zone(self) -> str | None:
"""Time zone used by gateway.
Only on Raspberry Pi.
"None" if not further specified.
"""
return self.raw.get("timezone")
@property
def utc(self) -> str | None:
"""UTC time of gateway in ISO 8601 format."""
return self.raw.get("utc")
@property
def uuid(self) -> str | None:
"""UPNP Unique ID of the gateway."""
return self.raw.get("uuid")
@property
def websocket_notify_all(self) -> bool | None:
"""All state changes will be signalled through the Websocket connection.
Default true.
"""
return self.raw.get("websocketnotifyall")
@property
def websocket_port(self) -> int | None:
"""Websocket port."""
return self.raw.get("websocketport")
@property
def whitelist(self) -> dict[str, Any]:
"""Array of whitelisted API keys."""
return cast(dict[str, Any], self.raw.get("whitelist", {}))
@property
def zigbee_channel(self) -> ConfigZigbeeChannel:
"""Wireless frequency channel."""
return ConfigZigbeeChannel(self.raw["zigbeechannel"])
async def set_config(
self,
discovery: bool | None = None,
group_delay: int | None = None,
light_last_seen_interval: int | None = None,
name: str | None = None,
network_open_duration: int | None = None,
otau_active: bool | None = None,
permit_join: int | None = None,
rf_connected: bool | None = None,
time_format: ConfigTimeFormat | None = None,
time_zone: str | None = None,
unlock: int | None = None,
update_channel: ConfigUpdateChannel | None = None,
utc: str | None = None,
zigbee_channel: ConfigZigbeeChannel | None = None,
websocket_notify_all: bool | None = None,
) -> dict[str, Any]:
"""Modify configuration parameters.
Supported values:
- discovery [bool]
Set gateway discovery over the internet active or inactive.
- group_delay [int] 0-5000
Time between two group commands in milliseconds.
- light_last_seen_interval [int] 1-65535 default 60
Sets the number of seconds where the timestamp for "lastseen"
is updated at the earliest for light resources. For any such update,
a seperate websocket event will be triggered.
- name [str] 0-16 characters
Name of the gateway.
- network_open_duration [int] 1-65535
Sets the lights and sensors search duration in seconds.
- otau_active [bool]
Set OTAU active or inactive
- permit_join [int] 0-255
Open the network so that other zigbee devices can join.
0 = network closed
255 = network open
1–254 = time in seconds the network remains open
The value will decrement automatically.
- rf_connected [bool]
Set to true to bring the Zigbee network up and false to bring it down.
This has the same effect as using the Join and Leave buttons in deCONZ.
- time_format [str] 12h|24h
Can be used to store the timeformat permanently.
- time_zone [str]
Set the timezone of the gateway (only on Raspberry Pi).
- unlock [int] 0-600 (seconds)
Unlock the gateway so that apps can register themselves to the gateway.
- update_channel [str] stable|alpha|beta
Set update channel.
- utc [str]
Set the UTC time of the gateway (only on Raspbery Pi)
in ISO 8601 format (yyyy-MM-ddTHH:mm:ss).
- zigbee_channel [int] 11|15|20|25
Set the zigbeechannel of the gateway.
Notify other Zigbee devices also to change their channel.
- websocket_notify_all [bool] default True
When true all state changes will be sent over the websocket connection.
"""
data = {
key: value
for key, value in {
"discovery": discovery,
"groupdelay": group_delay,
"lightlastseeninterval": light_last_seen_interval,
"name": name,
"networkopenduration": network_open_duration,
"otauactive": otau_active,
"permitjoin": permit_join,
"rfconnected": rf_connected,
"timezone": time_zone,
"unlock": unlock,
"utc": utc,
"websocketnotifyall": websocket_notify_all,
}.items()
if value is not None
}
if time_format is not None:
data["timeformat"] = time_format
if update_channel is not None:
data["updatechannel"] = update_channel
if zigbee_channel is not None:
data["zigbeechannel"] = zigbee_channel
return await self.request("put", path="/config", json=data)
|
class Config:
'''deCONZ configuration representation.
Dresden Elektroniks documentation of config in deCONZ
http://dresden-elektronik.github.io/deconz-rest-doc/config/
'''
def __init__(
self,
raw: dict[str, Any],
request: Callable[..., Awaitable[dict[str, Any]]],
) -> None:
'''Set configuration about deCONZ gateway.'''
pass
@property
def api_version(self) -> str | None:
'''Version of the deCONZ Rest API.'''
pass
@property
def bridge_id(self) -> str:
'''Gateway unique identifier.'''
pass
@property
def device_name(self) -> ConfigDeviceName:
'''Product name of the gateway.
Valid values are "ConBee", "RaspBee", "ConBee II" and "RaspBee II".
'''
pass
@property
def dhcp(self) -> bool | None:
'''Whether the IP address of the bridge is obtained with DHCP.'''
pass
@property
def firmware_version(self) -> str | None:
'''Version of the ZigBee firmware.'''
pass
@property
def gateway(self) -> str | None:
'''IPv4 address of the gateway.'''
pass
@property
def ip_address(self) -> str | None:
'''IPv4 address of the gateway.'''
pass
@property
def link_button(self) -> bool | None:
'''Is gateway unlocked.'''
pass
@property
def local_time(self) -> str | None:
'''Localtime of the gateway.'''
pass
@property
def mac(self) -> str | None:
'''MAC address of gateway.'''
pass
@property
def model_id(self) -> str | None:
'''Model identifyer.
Fixed string "deCONZ".
'''
pass
@property
def name(self) -> str | None:
'''Name of the gateway.'''
pass
@property
def network_mask(self) -> str | None:
'''Network mask of the gateway.'''
pass
@property
def network_open_duration(self) -> int | None:
'''Duration in seconds used by lights and sensors search.'''
pass
@property
def ntp(self) -> ConfigNTP | None:
'''Tells if the NTP time is "synced" or "unsynced".
Only for gateways running on Linux.
'''
pass
@property
def pan_id(self) -> int | None:
'''Zigbee pan ID of the gateway.'''
pass
@property
def portal_services(self) -> bool | None:
'''State of registration to portal service.
Is the bridge registered to synchronize data with a portal account.
'''
pass
@property
def rf_connected(self) -> bool | None:
'''State of deCONZ connection to firmware and if Zigbee network is up.'''
pass
@property
def software_update(self) -> dict[str, Any] | None:
'''Contains information related to software updates.'''
pass
@property
def software_version(self) -> str | None:
'''Software version of the gateway.'''
pass
@property
def time_format(self) -> ConfigTimeFormat:
'''Timeformat used by gateway.
Supported values:
"12h" or "24h"
'''
pass
@property
def time_zone(self) -> str | None:
'''Time zone used by gateway.
Only on Raspberry Pi.
"None" if not further specified.
'''
pass
@property
def utc(self) -> str | None:
'''UTC time of gateway in ISO 8601 format.'''
pass
@property
def uuid(self) -> str | None:
'''UPNP Unique ID of the gateway.'''
pass
@property
def websocket_notify_all(self) -> bool | None:
'''All state changes will be signalled through the Websocket connection.
Default true.
'''
pass
@property
def websocket_port(self) -> int | None:
'''Websocket port.'''
pass
@property
def whitelist(self) -> dict[str, Any]:
'''Array of whitelisted API keys.'''
pass
@property
def zigbee_channel(self) -> ConfigZigbeeChannel:
'''Wireless frequency channel.'''
pass
async def set_config(
self,
discovery: bool | None = None,
group_delay: int | None = None,
light_last_seen_interval: int | None = None,
name: str | None = None,
network_open_duration: int | None = None,
otau_active: bool | None = None,
permit_join: int | None = None,
rf_connected: bool | None = None,
time_format: ConfigTimeFormat | None = None,
time_zone: str | None = None,
unlock: int | None = None,
update_channel: ConfigUpdateChannel | None = None,
utc: str | None = None,
zigbee_channel: ConfigZigbeeChannel | None = None,
websocket_notify_all: bool | None = None,
) -> dict[str, Any]:
'''Modify configuration parameters.
Supported values:
- discovery [bool]
Set gateway discovery over the internet active or inactive.
- group_delay [int] 0-5000
Time between two group commands in milliseconds.
- light_last_seen_interval [int] 1-65535 default 60
Sets the number of seconds where the timestamp for "lastseen"
is updated at the earliest for light resources. For any such update,
a seperate websocket event will be triggered.
- name [str] 0-16 characters
Name of the gateway.
- network_open_duration [int] 1-65535
Sets the lights and sensors search duration in seconds.
- otau_active [bool]
Set OTAU active or inactive
- permit_join [int] 0-255
Open the network so that other zigbee devices can join.
0 = network closed
255 = network open
1–254 = time in seconds the network remains open
The value will decrement automatically.
- rf_connected [bool]
Set to true to bring the Zigbee network up and false to bring it down.
This has the same effect as using the Join and Leave buttons in deCONZ.
- time_format [str] 12h|24h
Can be used to store the timeformat permanently.
- time_zone [str]
Set the timezone of the gateway (only on Raspberry Pi).
- unlock [int] 0-600 (seconds)
Unlock the gateway so that apps can register themselves to the gateway.
- update_channel [str] stable|alpha|beta
Set update channel.
- utc [str]
Set the UTC time of the gateway (only on Raspbery Pi)
in ISO 8601 format (yyyy-MM-ddTHH:mm:ss).
- zigbee_channel [int] 11|15|20|25
Set the zigbeechannel of the gateway.
Notify other Zigbee devices also to change their channel.
- websocket_notify_all [bool] default True
When true all state changes will be sent over the websocket connection.
'''
pass
| 59 | 31 | 7 | 0 | 4 | 3 | 1 | 0.66 | 0 | 12 | 5 | 0 | 30 | 2 | 30 | 30 | 267 | 39 | 137 | 83 | 57 | 91 | 71 | 34 | 40 | 4 | 0 | 1 | 34 |
141,796 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.FireHandler
|
class FireHandler(APIHandler[Fire]):
"""Handler for fire sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_FIRE
item_cls = Fire
|
class FireHandler(APIHandler[Fire]):
'''Handler for fire sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,797 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.FormaldehydeHandler
|
class FormaldehydeHandler(APIHandler[Formaldehyde]):
"""Handler for formaldehyde sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_FORMALDEHYDE
item_cls = Formaldehyde
|
class FormaldehydeHandler(APIHandler[Formaldehyde]):
'''Handler for formaldehyde sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,798 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.GenericFlagHandler
|
class GenericFlagHandler(APIHandler[GenericFlag]):
"""Handler for generic flag sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.CLIP_GENERIC_FLAG
item_cls = GenericFlag
|
class GenericFlagHandler(APIHandler[GenericFlag]):
'''Handler for generic flag sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,799 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.GenericStatusHandler
|
class GenericStatusHandler(APIHandler[GenericStatus]):
"""Handler for generic status sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.CLIP_GENERIC_STATUS
item_cls = GenericStatus
|
class GenericStatusHandler(APIHandler[GenericStatus]):
'''Handler for generic status sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,800 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.HumidityHandler
|
class HumidityHandler(APIHandler[Humidity]):
"""Handler for humidity sensor."""
resource_group = ResourceGroup.SENSOR
resource_types = {
ResourceType.ZHA_HUMIDITY,
ResourceType.CLIP_HUMIDITY,
}
item_cls = Humidity
async def set_config(self, id: str, offset: int) -> dict[str, Any]:
"""Change config of humidity sensor.
Supported values:
- offset [int] -32768–32767
"""
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json={"offset": offset},
)
|
class HumidityHandler(APIHandler[Humidity]):
'''Handler for humidity sensor.'''
async def set_config(self, id: str, offset: int) -> dict[str, Any]:
'''Change config of humidity sensor.
Supported values:
- offset [int] -32768–32767
'''
pass
| 2 | 2 | 11 | 1 | 6 | 4 | 1 | 0.38 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 16 | 21 | 3 | 13 | 5 | 11 | 5 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
141,801 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.LightLevelHandler
|
class LightLevelHandler(APIHandler[LightLevel]):
"""Handler for light level sensor."""
resource_group = ResourceGroup.SENSOR
resource_types = {
ResourceType.ZHA_LIGHT_LEVEL,
ResourceType.CLIP_LIGHT_LEVEL,
}
item_cls = LightLevel
async def set_config(
self,
id: str,
threshold_dark: int | None = None,
threshold_offset: int | None = None,
) -> dict[str, Any]:
"""Change config of presence sensor.
Supported values:
- threshold_dark [int] 0-65534
- threshold_offset [int] 1-65534
"""
data = {
key: value
for key, value in {
"tholddark": threshold_dark,
"tholdoffset": threshold_offset,
}.items()
if value is not None
}
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json=data,
)
|
class LightLevelHandler(APIHandler[LightLevel]):
'''Handler for light level sensor.'''
async def set_config(
self,
id: str,
threshold_dark: int | None = None,
threshold_offset: int | None = None,
) -> dict[str, Any]:
'''Change config of presence sensor.
Supported values:
- threshold_dark [int] 0-65534
- threshold_offset [int] 1-65534
'''
pass
| 2 | 2 | 25 | 1 | 19 | 5 | 1 | 0.23 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 16 | 35 | 3 | 26 | 11 | 19 | 6 | 7 | 6 | 5 | 1 | 2 | 0 | 1 |
141,802 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.MoistureHandler
|
class MoistureHandler(APIHandler[Moisture]):
"""Handler for moisture sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_MOISTURE
item_cls = Moisture
async def set_config(self, id: str, offset: int) -> dict[str, Any]:
"""Change config of moisture sensor.
Supported values:
- offset [int] -32768–32767
"""
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json={"offset": offset},
)
|
class MoistureHandler(APIHandler[Moisture]):
'''Handler for moisture sensor.'''
async def set_config(self, id: str, offset: int) -> dict[str, Any]:
'''Change config of moisture sensor.
Supported values:
- offset [int] -32768–32767
'''
pass
| 2 | 2 | 11 | 1 | 6 | 4 | 1 | 0.5 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 16 | 18 | 3 | 10 | 5 | 8 | 5 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
141,803 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.OpenCloseHandler
|
class OpenCloseHandler(APIHandler[OpenClose]):
"""Handler for open/close sensor."""
resource_group = ResourceGroup.SENSOR
resource_types = {
ResourceType.ZHA_OPEN_CLOSE,
ResourceType.CLIP_OPEN_CLOSE,
}
item_cls = OpenClose
|
class OpenCloseHandler(APIHandler[OpenClose]):
'''Handler for open/close sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.14 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 9 | 1 | 7 | 4 | 6 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,804 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.ParticulateMatterHandler
|
class ParticulateMatterHandler(APIHandler[ParticulateMatter]):
"""Handler for particulate matter sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_PARTICULATE_MATTER
item_cls = ParticulateMatter
|
class ParticulateMatterHandler(APIHandler[ParticulateMatter]):
'''Handler for particulate matter sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,805 |
Kane610/deconz
|
pydeconz/config.py
|
pydeconz.config.ConfigZigbeeChannel
|
class ConfigZigbeeChannel(enum.IntEnum):
"""Available wireless frequency channels to use with the Gateway."""
CHANNEL_11 = 11
CHANNEL_15 = 15
CHANNEL_20 = 20
CHANNEL_25 = 25
|
class ConfigZigbeeChannel(enum.IntEnum):
'''Available wireless frequency channels to use with the Gateway.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 55 | 7 | 1 | 5 | 5 | 4 | 1 | 5 | 5 | 4 | 0 | 3 | 0 | 0 |
141,806 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.BadRequest
|
class BadRequest(pydeconzException):
"""The request was not formatted as expected or missing parameters."""
|
class BadRequest(pydeconzException):
'''The request was not formatted as expected or missing parameters.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,807 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.BridgeBusy
|
class BridgeBusy(pydeconzException):
"""The Bridge is busy, too many requests (more than 20)."""
|
class BridgeBusy(pydeconzException):
'''The Bridge is busy, too many requests (more than 20).'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,808 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.Forbidden
|
class Forbidden(pydeconzException):
"""The caller has no rights to access the requested URI."""
|
class Forbidden(pydeconzException):
'''The caller has no rights to access the requested URI.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,809 |
Kane610/deconz
|
pydeconz/interfaces/scenes.py
|
pydeconz.interfaces.scenes.Scenes
|
class Scenes(APIHandler[Scene]):
"""Represent scenes of a deCONZ group."""
item_cls = Scene
resource_group = ResourceGroup.SCENE
def _event_subscribe(self) -> None:
"""Register for group data events."""
self.gateway.groups.subscribe(
self.group_data_callback,
event_filter=(EventType.ADDED, EventType.CHANGED),
)
async def create_scene(self, group_id: str, name: str) -> dict[str, Any]:
"""Create a new scene.
The current state of each light will become the lights scene state.
Supported values:
- name [str]
"""
return await self.gateway.request(
"post",
path=f"/groups/{group_id}/scenes",
json={"name": name},
)
async def recall(self, group_id: str, scene_id: str) -> dict[str, Any]:
"""Recall scene to group."""
return await self.gateway.request_with_retry(
"put",
path=f"/groups/{group_id}/scenes/{scene_id}/recall",
json={},
)
async def store(self, group_id: str, scene_id: str) -> dict[str, Any]:
"""Store current group state in scene.
The actual state of each light in the group will become the lights scene state.
"""
return await self.gateway.request_with_retry(
"put",
path=f"/groups/{group_id}/scenes/{scene_id}/store",
json={},
)
async def set_attributes(
self, group_id: str, scene_id: str, name: str | None = None
) -> dict[str, Any]:
"""Change attributes of scene.
Supported values:
- name [str]
"""
data = {
key: value
for key, value in {
"name": name,
}.items()
if value is not None
}
return await self.gateway.request_with_retry(
"put",
path=f"/groups/{group_id}/scenes/{scene_id}",
json=data,
)
def group_data_callback(self, action: EventType, group_id: str) -> None:
"""Subscribe callback for new group data."""
self.process_item(group_id, {})
def process_item(self, id: str, raw: dict[str, Any]) -> None:
"""Pre-process scene data."""
group = self.gateway.groups[id]
for scene in group.raw["scenes"]:
super().process_item(f"{id}_{scene['id']}", cast(dict[str, Any], scene))
|
class Scenes(APIHandler[Scene]):
'''Represent scenes of a deCONZ group.'''
def _event_subscribe(self) -> None:
'''Register for group data events.'''
pass
async def create_scene(self, group_id: str, name: str) -> dict[str, Any]:
'''Create a new scene.
The current state of each light will become the lights scene state.
Supported values:
- name [str]
'''
pass
async def recall(self, group_id: str, scene_id: str) -> dict[str, Any]:
'''Recall scene to group.'''
pass
async def store(self, group_id: str, scene_id: str) -> dict[str, Any]:
'''Store current group state in scene.
The actual state of each light in the group will become the lights scene state.
'''
pass
async def set_attributes(
self, group_id: str, scene_id: str, name: str | None = None
) -> dict[str, Any]:
'''Change attributes of scene.
Supported values:
- name [str]
'''
pass
def group_data_callback(self, action: EventType, group_id: str) -> None:
'''Subscribe callback for new group data.'''
pass
def process_item(self, id: str, raw: dict[str, Any]) -> None:
'''Pre-process scene data.'''
pass
| 8 | 8 | 9 | 1 | 6 | 2 | 1 | 0.36 | 1 | 5 | 1 | 0 | 7 | 0 | 7 | 22 | 77 | 13 | 47 | 15 | 37 | 17 | 20 | 13 | 12 | 2 | 2 | 1 | 8 |
141,810 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.AirPurifierHandler
|
class AirPurifierHandler(APIHandler[AirPurifier]):
"""Handler for air purifier sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_AIR_PURIFIER
item_cls = AirPurifier
async def set_config(
self,
id: str,
fan_mode: AirPurifierFanMode | None = None,
filter_life_time: int | None = None,
led_indication: bool | None = None,
locked: bool | None = None,
) -> dict[str, Any]:
"""Set speed of fans/ventilators.
Supported values:
- fan_mode [AirPurifierFanMode]
- "off"
- "auto"
- "speed_1"
- "speed_2"
- "speed_3"
- "speed_4"
- "speed_5"
- filter_life_time [int] 0-65536
- led_indication [bool] True/False
- locked [bool] True/False
"""
data: dict[str, int | str] = {
key: value
for key, value in {
"filterlifetime": filter_life_time,
"ledindication": led_indication,
"locked": locked,
}.items()
if value is not None
}
if fan_mode is not None:
data["mode"] = fan_mode
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json=data,
)
|
class AirPurifierHandler(APIHandler[AirPurifier]):
'''Handler for air purifier sensor.'''
async def set_config(
self,
id: str,
fan_mode: AirPurifierFanMode | None = None,
filter_life_time: int | None = None,
led_indication: bool | None = None,
locked: bool | None = None,
) -> dict[str, Any]:
'''Set speed of fans/ventilators.
Supported values:
- fan_mode [AirPurifierFanMode]
- "off"
- "auto"
- "speed_1"
- "speed_2"
- "speed_3"
- "speed_4"
- "speed_5"
- filter_life_time [int] 0-65536
- led_indication [bool] True/False
- locked [bool] True/False
'''
pass
| 2 | 2 | 40 | 2 | 24 | 14 | 2 | 0.54 | 1 | 6 | 1 | 0 | 1 | 0 | 1 | 16 | 47 | 4 | 28 | 13 | 19 | 15 | 9 | 6 | 7 | 2 | 2 | 1 | 2 |
141,811 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.AirQualityHandler
|
class AirQualityHandler(APIHandler[AirQuality]):
"""Handler for air quality sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_AIR_QUALITY
item_cls = AirQuality
|
class AirQualityHandler(APIHandler[AirQuality]):
'''Handler for air quality sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,812 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.AlarmHandler
|
class AlarmHandler(APIHandler[Alarm]):
"""Handler for alarm sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_ALARM
item_cls = Alarm
|
class AlarmHandler(APIHandler[Alarm]):
'''Handler for alarm sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,813 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.AncillaryControlHandler
|
class AncillaryControlHandler(APIHandler[AncillaryControl]):
"""Handler for ancillary control sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_ANCILLARY_CONTROL
item_cls = AncillaryControl
|
class AncillaryControlHandler(APIHandler[AncillaryControl]):
'''Handler for ancillary control sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,814 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.BatteryHandler
|
class BatteryHandler(APIHandler[Battery]):
"""Handler for battery sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_BATTERY
item_cls = Battery
|
class BatteryHandler(APIHandler[Battery]):
'''Handler for battery sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,815 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.CarbonDioxideHandler
|
class CarbonDioxideHandler(APIHandler[CarbonDioxide]):
"""Handler for carbon dioxide sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_CARBON_DIOXIDE
item_cls = CarbonDioxide
|
class CarbonDioxideHandler(APIHandler[CarbonDioxide]):
'''Handler for carbon dioxide sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,816 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.CarbonMonoxideHandler
|
class CarbonMonoxideHandler(APIHandler[CarbonMonoxide]):
"""Handler for carbon monoxide sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_CARBON_MONOXIDE
item_cls = CarbonMonoxide
|
class CarbonMonoxideHandler(APIHandler[CarbonMonoxide]):
'''Handler for carbon monoxide sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,817 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.ConsumptionHandler
|
class ConsumptionHandler(APIHandler[Consumption]):
"""Handler for consumption sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_CONSUMPTION
item_cls = Consumption
|
class ConsumptionHandler(APIHandler[Consumption]):
'''Handler for consumption sensor.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.25 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 15 | 6 | 1 | 4 | 4 | 3 | 1 | 4 | 4 | 3 | 0 | 2 | 0 | 0 |
141,818 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.DoorLockHandler
|
class DoorLockHandler(APIHandler[DoorLock]):
"""Handler for door lock sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.ZHA_DOOR_LOCK
item_cls = DoorLock
async def set_config(self, id: str, lock: bool) -> dict[str, Any]:
"""Set config of the lock.
Supported values:
- Lock [bool] True/False.
"""
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json={"lock": lock},
)
|
class DoorLockHandler(APIHandler[DoorLock]):
'''Handler for door lock sensor.'''
async def set_config(self, id: str, lock: bool) -> dict[str, Any]:
'''Set config of the lock.
Supported values:
- Lock [bool] True/False.
'''
pass
| 2 | 2 | 11 | 1 | 6 | 4 | 1 | 0.5 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 16 | 18 | 3 | 10 | 5 | 8 | 5 | 6 | 5 | 4 | 1 | 2 | 0 | 1 |
141,819 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.pydeconzException
|
class pydeconzException(Exception):
"""Base error for pydeconz.
https://dresden-elektronik.github.io/deconz-rest-doc/errors/
"""
|
class pydeconzException(Exception):
'''Base error for pydeconz.
https://dresden-elektronik.github.io/deconz-rest-doc/errors/
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 9 | 0 | 0 | 0 | 10 | 5 | 1 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 3 | 0 | 0 |
141,820 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.Unauthorized
|
class Unauthorized(pydeconzException):
"""Authorization failed."""
|
class Unauthorized(pydeconzException):
'''Authorization failed.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,821 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.ResponseError
|
class ResponseError(pydeconzException):
"""Invalid response."""
|
class ResponseError(pydeconzException):
'''Invalid response.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,822 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.ResourceNotFound
|
class ResourceNotFound(pydeconzException):
"""The requested resource (light, group, ...) was not found."""
|
class ResourceNotFound(pydeconzException):
'''The requested resource (light, group, ...) was not found.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,823 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.RequestError
|
class RequestError(pydeconzException):
"""Unable to fulfill request.
Raised when host or API cannot be reached.
"""
|
class RequestError(pydeconzException):
'''Unable to fulfill request.
Raised when host or API cannot be reached.
'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 5 | 1 | 1 | 1 | 0 | 3 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,824 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.NotConnected
|
class NotConnected(pydeconzException):
"""The Hardware is not connected."""
|
class NotConnected(pydeconzException):
'''The Hardware is not connected.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,825 |
Kane610/deconz
|
pydeconz/errors.py
|
pydeconz.errors.LinkButtonNotPressed
|
class LinkButtonNotPressed(pydeconzException):
"""The Link button has not been pressed."""
|
class LinkButtonNotPressed(pydeconzException):
'''The Link button has not been pressed.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | 2 | 0 | 1 | 1 | 0 | 1 | 1 | 1 | 0 | 0 | 4 | 0 | 0 |
141,826 |
Kane610/deconz
|
pydeconz/interfaces/sensors.py
|
pydeconz.interfaces.sensors.DaylightHandler
|
class DaylightHandler(APIHandler[Daylight]):
"""Handler for daylight sensor."""
resource_group = ResourceGroup.SENSOR
resource_type = ResourceType.DAYLIGHT
item_cls = Daylight
async def set_config(
self,
id: str,
sunrise_offset: int | None = None,
sunset_offset: int | None = None,
) -> dict[str, Any]:
"""Set config of the daylight sensor.
Supported values:
- sunrise_offset [int] -120-120
- sunset_offset [int] -120-120
"""
data: dict[str, int] = {
key: value
for key, value in {
"sunriseoffset": sunrise_offset,
"sunsetoffset": sunset_offset,
}.items()
if value is not None
}
return await self.gateway.request_with_retry(
"put",
path=f"{self.path}/{id}/config",
json=data,
)
|
class DaylightHandler(APIHandler[Daylight]):
'''Handler for daylight sensor.'''
async def set_config(
self,
id: str,
sunrise_offset: int | None = None,
sunset_offset: int | None = None,
) -> dict[str, Any]:
'''Set config of the daylight sensor.
Supported values:
- sunrise_offset [int] -120-120
- sunset_offset [int] -120-120
'''
pass
| 2 | 2 | 25 | 1 | 19 | 5 | 1 | 0.26 | 1 | 4 | 0 | 0 | 1 | 0 | 1 | 16 | 32 | 3 | 23 | 11 | 16 | 6 | 7 | 6 | 5 | 1 | 2 | 0 | 1 |
141,827 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/syntax_highlighting_plugins/Pygments_Kappa_plugin/core/KappaStyle.py
|
core.KappaStyle.DemoStyle
|
class DemoStyle(Style):
"""This style showcases some of the subtleties in the lexer."""
default_style = ''
styles = {
Agent_Name: 'bold',
Site_Bond_State_Agent: 'bold',
Agent_Oper: 'underline #f00',
Site_Bond: '#cc00cc',
Site_Int: '#0000ff',
Site_Count: '#009999',
String: 'italic',
Site_Bond_Oper: 'underline',
Site_Int_Oper: 'underline',
Site_Count_Oper: 'underline',
Dec_Ag_Sign_Site_Bd: '#999999',
Pert_Keyword: 'bold',
Pert_Decor: 'italic',
Pert_Oper: 'bg:#ffcccc',
Comment: 'bg:#f2f2f2 italic',
Number: '#cc7a00',
Dec_Keyword: 'bold',
Misc_Keyword: 'bold',
Rule_Decor: '#009900',
# Comment: '#f00',
# Number: '#f00',
# String: '#f00',
# Number: '#f00',
# Operator: '#f00'
}
|
class DemoStyle(Style):
'''This style showcases some of the subtleties in the lexer.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.65 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 29 | 0 | 23 | 3 | 22 | 15 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
141,828 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/syntax_highlighting_plugins/Pygments_Kappa_plugin/core/KappaStyle.py
|
core.KappaStyle.EditNotationDeltasStyle
|
class EditNotationDeltasStyle(Style):
"""This style highlights edit notation operations."""
default_style = ''
styles = {
String: '#808080 italic',
Agent_Name: 'bold',
Site_Bond_Oper: 'bg:#c9f2d6',
Site_Int_Oper: 'bg:#c9e4f2',
Agent_Oper: 'bg:#f2c9e4',
Site_Count_Oper: 'bg:#f2d6c9',
Rule_Decor: '#cc0000',
Comment: 'bg:#b3b3b3'
}
|
class EditNotationDeltasStyle(Style):
'''This style highlights edit notation operations.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.67 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 13 | 0 | 12 | 3 | 11 | 8 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
141,829 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/syntax_highlighting_plugins/Pygments_Kappa_plugin/core/KappaLexer.py
|
core.KappaLexer.KappaLexer
|
class KappaLexer(RegexLexer):
"""Pygments lexer for the Kappa language (https://kappalanguage.org)"""
name = 'Kappa'
aliases = ['kappa']
filenames = ['*.ka']
integer = r'[0-9]+'
real = r'([0-9]+[eE][+-]?[0-9+])|((([0-9]+\.[0-9]*)|(\.[0-9]+))([eE][+-]?[0-9]+)?)'
ident = r'[_~][a-zA-Z0-9~+_]+|[a-zA-Z][a-zA-Z0-9_~+-]*'
tokens = {
'root': [
# comments
(r'//.*?$', Comment.Singleline),
(r'/\*', Comment.Multiline, 'comment'),
(r'\s+', Whitespace),
# agent name
(r'(' + ident + r')(\()', bygroups(Agent_Name, Agent_Decor), 'agent_rule'),
# various keywords
(r'(%agent:)(\s*)(' + ident + r')(\()', bygroups(Dec_Keyword, Whitespace, Dec_Ag_Name, Dec_Ag_Decor),
'agent_declaration'),
(r'(%token:)(\s*)(' + ident + r')', bygroups(Dec_Keyword, Whitespace, String)),
(words(('obs', 'init', 'var', 'plot', 'def'),
prefix='%', suffix=':'), Misc_Keyword),
(words(('?', ':', 'log', 'sin', 'cos', 'tan', 'exp', 'int', 'mod', 'sqrt', 'pi', 'max', 'min'),
prefix=r'\[\s*', suffix=r'\s*\]'), Misc_Func),
# perturbation language
(r'%mod:', Pert_Keyword),
(r';', Pert_Keyword),
(words(('INF', 'inf', 'alarm'),
prefix=r'\b', suffix=r'\b'), Pert_Constructs),
(words(('true', 'false', 'not', 'E', 'E+', 'T', 'Tsim', 'Emax', 'Tmax'),
prefix=r'\[\s*', suffix=r'\s*\]'), Pert_Constructs),
(words(('do', 'repeat'),
prefix=r'\b', suffix=r'\b'), Pert_Decor),
(words(('APPLY', 'DEL', 'ADD', 'SNAPSHOT', 'STOP', 'DIN', 'TRACK', 'UPDATE', 'PRINT', 'PRINTF', 'RUN',
'SPECIES_OF'),
prefix=r'\$', suffix=r'\b'), Pert_Oper),
(words(('&&', '||')), Pert_Constructs),
# double-quoted, unquoted, and single-quoted strings
(r'"[^"]+"', Pert_FileName),
(r"([_~][a-zA-Z0-9~+_]+|[a-zA-Z][a-zA-Z0-9_~+-]*)|('[^']*')", String),
# numbers
(real, Number),
(integer, Number),
# rule decorations & markers
(r'@|<->|->|{|}|:', Rule_Decor),
(r',', Rule_Decor),
(r'[-+/*^|><=()]', Alge_Oper),
(r'\.', Rule_Decor) # chemical notation placeholder marking agent creation/destruction
],
'comment': [
(r'[^*/]', Comment.Multiline),
(r'/\*', Comment.Multiline, '#push'),
(r'\*/', Comment.Multiline, '#pop'),
(r'[*/]', Comment.Multiline)
],
'agent_rule': [
# comments
(r'//.*?$', Comment.Singleline),
(r'/\*', Comment.Multiline, 'comment'),
# end of expression, agent edit operation
(r'(\))([+-]?)', bygroups(Agent_Decor, Agent_Oper), '#pop'),
# bond states
(r'(\[\s*)(\d+|_|#|\.)(\s*\])', # [99]
bygroups(Site_Bond_Decor, Site_Bond_State, Site_Bond_Decor)),
(r'(\[\s*)(' + ident + r')(.)(' + ident + r')(\s*\])', # [site.Agent]
bygroups(Site_Bond_Decor, Site_Bond_State_Site, Site_Bond_Decor, Site_Bond_State_Agent, Site_Bond_Decor)),
(r'(\[\s*)(\d+|_|#|\.)(\s*/\s*)(\d+|\.)(\s*\])', # [99/56]
bygroups(Site_Bond_Oper_Decor, Site_Bond_Oper_State, Site_Bond_Oper_Decor, Site_Bond_Oper_State, Site_Bond_Oper_Decor)),
(r'(\[\s*)(' + ident + r')(.)(' + ident + r')(\s*/\s*)(\d+|\.)(\s*\])', # [site.Agent/.]
bygroups(Site_Bond_Oper_Decor, Site_Bond_Oper_State_Site, Site_Bond_Oper_Decor, Site_Bond_Oper_State_Agent, Site_Bond_Oper_Decor, Site_Bond_Oper_State, Site_Bond_Oper_Decor)),
# internal states
(r'({\s*)(' + ident + r'|#)(\s*})', # {ph}
bygroups(Site_Int_Decor, Site_Int_State, Site_Int_Decor)),
(r'({\s*)(' + ident + r'|#)(\s*/\s*)(' + ident + r')(\s*})', # {ph/un}
bygroups(Site_Int_Oper_Decor, Site_Int_Oper_State, Site_Int_Oper_Decor, Site_Int_Oper_State, Site_Int_Oper_Decor)),
# counter states
(r'({\s*(?:>=|>|=)\s*)(\d+)(\s*})', # {>55}
bygroups(Site_Count_Decor, Site_Count_State, Site_Count_Decor)),
(r'({\s*=\s*)(' + ident + r')(\s*})', # {=x}
bygroups(Site_Count_Decor, Site_Count_State, Site_Count_Decor)),
(r'({\s*[-+]=\s*)(-?\d+)(\s*})', # {+= -55}
bygroups(Site_Count_Oper_Decor, Site_Count_Oper_State, Site_Count_Oper_Decor)),
(r'({\s*=\s*)(\d+)(\s*/\s*[+-]=\s*)(-?\d+)(\s*})', # {= 55 / += -3}
bygroups(Site_Count_Oper_Decor, Site_Count_Oper_State, Site_Count_Oper_Decor, Site_Count_Oper_State, Site_Count_Oper_Decor)),
# rest of components
(r'\s', Agent_Sign),
(r',', Agent_Sign_Decor),
(ident, Site_Name)
],
# the declaration pods exists because counter syntax is identical for edit notation in rules and for declaration
# statements in %agent:
# With it, I avoid issuing the wrong tokens (e.g. highlighting as edit operation statements in agent declaration
# statement), at the expense of more token types.
'agent_declaration' : [
# comments
(r'//.*?$', Comment.Singleline),
(r'/\*', Comment.Multiline, 'comment'),
# kappa
(r'\)', Dec_Ag_Decor, '#pop'), # end of expression
(r'({\s*=\s*)(\d+)(\s*/\s*[+-]=\s*)(-?\d+)(\s*})', # {= 55 / += 3} :: counters
bygroups(Dec_Ag_Sign_Site_Ct_d, Dec_Ag_Sign_Site_Ct_s, Dec_Ag_Sign_Site_Ct_d, Dec_Ag_Sign_Site_Ct_s, Dec_Ag_Sign_Site_Ct_d)),
(r'({\s*=\s*)(\d+)(\s*})', # {= 55 } :: counters_cont
bygroups(Dec_Ag_Sign_Site_Ct_d, Dec_Ag_Sign_Site_Ct_s, Dec_Ag_Sign_Site_Ct_d)),
(r'\[', Dec_Ag_Sign_Site_Bd_d, 'declaration_bond_type'), # change state
(r'{', Dec_Ag_Sign_Site_In_d, 'declaration_internal_list'), # change state
# rest of components
(r'\s+', Dec_Ag_Sign_Decor),
(r',', Dec_Ag_Sign_Decor),
(ident, Dec_Ag_Sign_Site_Name)
],
'declaration_bond_type' : [
# comments
(r'//.*?$', Comment.Singleline),
(r'/\*', Comment.Multiline, 'comment'),
# bond data
(r'\]', Dec_Ag_Sign_Site_Bd_d, '#pop'),
(r'(' + ident + r')(\.)(' + ident + r')', bygroups(Dec_Ag_Sign_Site_Bd_s, Dec_Ag_Sign_Site_Bd_d, Dec_Ag_Sign_Site_Bd_a)),
(r'\s+', Dec_Ag_Sign_Site_Bd_d),
(r',', Dec_Ag_Sign_Site_Bd_d)
],
'declaration_internal_list' : [
# comments
(r'//.*?$', Comment.Singleline),
(r'/\*', Comment.Multiline, 'comment'),
# internal state data
(r'}', Dec_Ag_Sign_Site_In_d, '#pop'),
(ident, Dec_Ag_Sign_Site_In_s),
(r'\s+', Dec_Ag_Sign_Site_In_d),
(r',', Dec_Ag_Sign_Site_In_d)
],
}
|
class KappaLexer(RegexLexer):
'''Pygments lexer for the Kappa language (https://kappalanguage.org)'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.43 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 29 | 133 | 2 | 106 | 8 | 105 | 46 | 8 | 8 | 7 | 0 | 5 | 0 | 0 |
141,830 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/syntax_highlighting_plugins/Pygments_Kappa_plugin/core/KappaStyle.py
|
core.KappaStyle.KaSimInBrowserStyle
|
class KaSimInBrowserStyle(Style):
"""This style mimics the CodeMirror interface used in the GUI / KappApp."""
default_style = ''
styles = {
Comment: '#a50',
Misc_Keyword: '#708',
Dec_Keyword: '#708',
Pert_Keyword: '#708',
Agent_Decor: '#05a',
Dec_Ag_Decor: '#05a',
Rule_Decor: '#05a',
Number: '#164',
Operator: '#05a',
Misc_Func: '#05a',
Pert_Oper: '#05a',
Pert_Decor: '#05a',
Pert_FileName: '#a11',
Pert_Constructs: '#708',
}
|
class KaSimInBrowserStyle(Style):
'''This style mimics the CodeMirror interface used in the GUI / KappApp.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.83 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 19 | 0 | 18 | 3 | 17 | 15 | 3 | 3 | 2 | 0 | 4 | 0 | 0 |
141,831 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/tests/kappy/test_snapshots.py
|
test_snapshots.KappaSnapshotTest
|
class KappaSnapshotTest(unittest.TestCase):
def test_parse_string(self):
dimer = kappy.KappaComplex.from_string("A(y[_\n], a[1]{u}), B(b{# }[1] /*lool*/x{ p},y)")
assert(len(dimer) == 2)
return
def test_embeddings(self):
# one agent
assert(kappy.KappaComplex.from_string("A(a[_])") in
kappy.KappaComplex.from_string("A(b[1] a[2]), A(b[3] a[2]), B(a[1] x{p}), B(a[3] x{u})"))
# negative
assert(not kappy.KappaComplex.from_string("A(b[.])") in
kappy.KappaComplex.from_string("A(b[1] a[2]), A(b[3] a[2]), B(a[1] x{p}), B(a[3] x{u})"))
assert(not kappy.KappaComplex.from_string("A(b[.])") in
kappy.KappaComplex.from_string("C(b[.])"))
# several agents
nasty=kappy.KappaComplex.from_string("A(b[1] a[2]), A(b[3] a[2]), B(a[1] x{p}), B(a[3] x{u})")
assert(len(nasty.find_pattern(kappy.KappaComplex.from_string("A(b[2]), B(a[2] x)"))) == 2)
assert(len(nasty.find_pattern(kappy.KappaComplex.from_string("A(b[2]), B(a[2] x{u})"))) == 1)
# symmetries
assert(len(nasty.find_pattern(kappy.KappaComplex.from_string("A(a[5]), A(a[5])"))) == 2)
# canonical representation killer
assert(nasty ==
kappy.KappaComplex.from_string("A(a[1] b[2]), A(a[1] b[3]), B(a[2] x{u}), B(a[3] x{p})"))
# with loops
assert(kappy.KappaComplex.from_string("A(b[1] c[2]), B(a[1] c[3]), C(a[2] b[3])") ==
kappy.KappaComplex.from_string("B(a[1] c[2]), A(b[1] c[3]), C(a[3] b[2])"))
def test_parse_1d(self):
with gzip.open(os.path.join(THIS_DIR,"snap_1d_polymers.json.gz")) as f:
snap = kappy.KappaSnapshot.from_JSONDecoder(json.load(f))
# check repr
re_entry = repr(snap)
# get number of complexes
num_complexes = len(snap.complexes)
assert(num_complexes == 10), "Expected 10 complexes in %s" %(fname)
# get the most abundant complex, which should exist in 10 copies
big_size,[(big_abun, big_comp)] = snap.get_largest_complexes()
# check that the biggest complex has abundance of 1
assert(big_abun == 1), \
"Expected biggest complex %s to have abundance of 1." %(big_comp)
small_abun,[small_comp] = snap.get_most_abundant_complexes()
# check that the smallest complex has abundance of 10
assert(small_abun == 10), \
"Expected smallest complex %s to have abundance of 10." %(small_comp)
return
|
class KappaSnapshotTest(unittest.TestCase):
def test_parse_string(self):
pass
def test_embeddings(self):
pass
def test_parse_1d(self):
pass
| 4 | 0 | 14 | 0 | 11 | 4 | 1 | 0.36 | 1 | 0 | 0 | 0 | 3 | 0 | 3 | 75 | 47 | 3 | 33 | 12 | 29 | 12 | 26 | 11 | 22 | 1 | 2 | 1 | 3 |
141,832 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/tests/kappy/test_std.py
|
test_std.StdClientTest
|
class StdClientTest(_KappaClientTest):
""" Integration test for kappa client"""
def getRuntime(self):
return kappy.KappaStd()
|
class StdClientTest(_KappaClientTest):
''' Integration test for kappa client'''
def getRuntime(self):
pass
| 2 | 1 | 2 | 0 | 2 | 0 | 1 | 0.33 | 1 | 0 | 0 | 0 | 1 | 0 | 1 | 79 | 5 | 1 | 3 | 2 | 1 | 1 | 3 | 2 | 1 | 1 | 3 | 0 | 1 |
141,833 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/tests/kappy/util.py
|
util._KappaClientTest
|
class _KappaClientTest(unittest.TestCase):
# Universal Tests =========================================================
def test_file_crud(self):
print("Getting the runtime object...")
runtime = self.getRuntime()
print("Creating the file...")
file_id = runtime.make_unique_id("test_file")
model_str = ''
runtime.add_model_string(model_str, 0, file_id)
print("Getting the file names")
file_names = [entry.id for entry in runtime.file_info()]
print("Running checks...")
self.assertIn(file_id, file_names)
self.assertEqual(runtime.file_get(file_id).get_content(), model_str)
runtime.file_delete(file_id)
try:
runtime.file_delete(file_id)
self.fail()
except kappy.KappaError:
pass
def test_parse_multiple_files(self):
runtime = self.getRuntime()
file_1_id = runtime.make_unique_id("file1.ka")
file_2_id = runtime.make_unique_id("file2.ka")
test_dir = path.join(MODELS_DIR, "..", "tests", "integration", "compiler",
"file_order")
f1_path = path.join(test_dir, 'file1.ka')
runtime.add_model_file(f1_path, 1, file_1_id)
f2_path = path.join(test_dir, 'file2.ka')
runtime.add_model_file(f2_path, 2, file_2_id)
with self.assertRaises(kappy.KappaError):
runtime.add_model_file(f2_path, 2, file_2_id)
file_names = [entry.id for entry in runtime.file_info()]
self.assertIn(file_1_id, file_names)
self.assertIn(file_2_id, file_names)
return
def test_run_simulation(self):
print("Getting runtime...")
runtime = self.getRuntime()
file_id = runtime.make_unique_id('abc-pert')
print("Adding model file %s..." % file_id)
fpath = path.join(MODELS_DIR, "abc-pert.ka")
runtime.add_model_file(fpath, 0, file_id)
print("Parse project...")
runtime.project_parse()
print("Start simulation...")
pause_condition = "[T] > 10.0"
runtime.set_default_sim_param(0.1, pause_condition)
runtime.simulation_start()
print("Waiting for simulation to stop...")
simulation_info = runtime.wait_for_simulation_stop()
print("Checking that no limit returns all entries...")
last_status = runtime.simulation_plot()
test_count = 101
self.assertEqual(test_count, len(last_status['series']))
print("Got simulation info at end:\n%s" % simulation_info)
print("Doing other checks...")
plot_limit_offset = 100
test_time = 10.0
test_count = 1
limit = kappy.PlotLimit(plot_limit_offset)
last_status = runtime.simulation_plot(limit)
self.assertEqual(test_count, len(last_status['series']))
self.assertEqual(test_time, last_status['series'][0][0])
plot_limit_offset = 10
plot_limit_points = 1
test_time = 1.0
test_count = 1
limit = kappy.PlotLimit(plot_limit_offset, plot_limit_points)
last_status = runtime.simulation_plot(limit)
self.assertEqual(test_count, len(last_status['series']))
self.assertEqual(test_time, last_status['series'][0][0])
plot_limit_offset = 50
test_time = 10.0
test_count = 51
limit = kappy.PlotLimit(plot_limit_offset)
last_status = runtime.simulation_plot(limit)
self.assertEqual(test_count, len(last_status['series']))
self.assertEqual(test_time, last_status['series'][0][0])
print("Continuing simulation...")
runtime.simulation_continue("[T] > 35")
print("Waiting for second simulation to end...")
runtime.wait_for_simulation_stop()
# test that no limit returns all entries
last_status = runtime.simulation_plot()
self.assertEqual(351, len(last_status['series']))
return
def test_export_snapshot(self):
print("Getting runtime...")
runtime = self.getRuntime()
model_file= "abc-cflow.ka"
print("Adding model file %s..." % model_file)
fpath = path.join(MODELS_DIR, model_file)
runtime.add_model_file(fpath)
print("Parse project...")
runtime.project_parse()
print("Start simulation...")
pause_condition = "[E] = 10005"
runtime.set_default_sim_param(0.1, pause_condition)
runtime.simulation_start()
print("Waiting for simulation to stop...")
simulation_info = runtime.wait_for_simulation_stop()
print("Check that expected snapshot had been generated...")
snap_name = "snap10.ka"
assert(snap_name in runtime.simulation_snapshots())
print(f"Snapshot is {runtime.simulation_snapshot(snap_name)}")
return
def test_parsing_consistency(self):
print("Getting runtime...")
runtime = self.getRuntime()
file_id = runtime.make_unique_id('abc-pert')
print("Adding model file %s..." % file_id)
fpath = path.join(MODELS_DIR, "abc-pert.ka")
runtime.add_model_file(fpath, 0, file_id)
print("Parse project...")
runtime.project_parse()
#print("removing file and overwriting ast")
#runtime.file_delete(file_id)
#runtime.project_overwrite(ast,"plus.ka")
print("getting the model text back en reparse it")
gen_file = runtime.file_get(file_id)#"plus.ka")
runtime.file_delete(file_id)#"plus.ka")
runtime.add_model_string(gen_file.file_content,file_id="final")
runtime.project_parse()
def test_static_analyses(self):
print("Getting runtime...")
runtime = self.getRuntime()
print("Adding model file %s..." % "abc.ka")
fpath = path.join(MODELS_DIR, "abc-pert.ka")
runtime.add_model_file(fpath, 0)
print("Parse project...")
runtime.project_parse()
print("Get contact_map...")
cm = runtime.analyses_contact_map()
print("Get high accuracy influence_map...")
im = runtime.analyses_influence_map("medium")
|
class _KappaClientTest(unittest.TestCase):
def test_file_crud(self):
pass
def test_parse_multiple_files(self):
pass
def test_run_simulation(self):
pass
def test_export_snapshot(self):
pass
def test_parsing_consistency(self):
pass
def test_static_analyses(self):
pass
| 7 | 0 | 27 | 5 | 22 | 1 | 1 | 0.05 | 1 | 0 | 0 | 1 | 6 | 0 | 6 | 78 | 172 | 36 | 131 | 43 | 124 | 7 | 130 | 43 | 123 | 2 | 2 | 1 | 7 |
141,834 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/syntax_highlighting_plugins/Pygments_Kappa_plugin/core/KappaStyle.py
|
core.KappaStyle.EditNotationDeltasStyleDark
|
class EditNotationDeltasStyleDark(Style):
"""An edit notation style sheet for dark backgrounds."""
default_style = ''
background_color = '#000'
styles = {
Token.Kappa: '#eee',
String: '#aaa italic',
Agent_Name: 'bold',
Site_Bond_Oper: '#fff bg:#0e750e',
Site_Int_Oper: '#fff bg:#0e0e75',
Site_Count_Oper: '#fff bg:#0e0e75',
Agent_Oper: '#fff bg:#750e0e',
Rule_Decor: '#a31414',
Comment: 'bg:#666'
}
|
class EditNotationDeltasStyleDark(Style):
'''An edit notation style sheet for dark backgrounds.'''
pass
| 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0.71 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 15 | 0 | 14 | 4 | 13 | 10 | 4 | 4 | 3 | 0 | 4 | 0 | 0 |
141,835 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_graph.py
|
kappy.kappa_graph.KappaSite
|
class KappaSite:
"""class for representing one site of a kappa agent (in a complex)"""
def __init__(self, *, links=None, internals=None,
future_link=None, future_internal=None):
self._links = links
self._internals = internals
self._future_link = future_link
self._future_internal = future_internal
def __repr__(self):
return "KappaSite({}{}{}{}{}{}{})".format(
"" if self._links is None else f"links={self._links!r}",
", " if self._links is not None and
(self._internals is not None or
self._future_link is not None or
self._future_internal is not None)
else "",
"" if self._internals is None
else f"internals={self._internals!r}",
", " if self._internals is not None and
(self._future_link is not None or self._future_internal is not None)
else "",
"" if self._future_link is None
else f"future_link={self._future_link!r}",
", " if self._future_link is not None and
self._future_internal is not None
else "",
"" if self._future_internal is None
else f"future_internal={self._future_internal!r}"
)
def is_more_specific_than(self, ref, *, mapping=None, todos=None):
if ref._internals is None or \
all(x in self._internals for x in ref._internals):
if ref._links is None:
return True
elif ref._links is True:
return not (self._links is None or self._links == [])
elif type(ref._links) is list:
if type(self._links) is list:
if len(ref._links) == 0:
return len(self._links) == 0
else:
assert len(ref._links) == 1, \
"Sigma graph compare not implemented"
if len(self._links) == 1:
assert mapping is not None, "Missing mapping"
(r_ag, r_si) = ref._links[0]
(ag, si) = self._links[0]
ag_dst = mapping.get(r_ag)
if not ag_dst:
ag_dst = ag
mapping[r_ag] = ag
todos.append((r_ag, ag))
return si == r_si and ag == ag_dst
else:
return False
else:
return False
else:
site = ref._links["site_name"]
ag = ref._links["agent_type"]
assert False, "Sorry, I can't deal with site_types."
else:
return False
def is_equal(self, ref, *, mapping=None, todos=None):
if (isinstance(ref._internals, type(self._internals))
and ref._internals == self._internals):
if type(ref._links) is list:
if type(self._links) is list:
if len(ref._links) == 0:
return len(self._links) == 0
else:
assert len(ref._links) == 1, \
"Sigma graph compare not implemented"
if len(self._links) == 1:
assert mapping is not None, "Missing mapping"
(r_ag, r_si) = ref._links[0]
(ag, si) = self._links[0]
ag_dst = mapping.get(r_ag)
if not ag_dst:
ag_dst = ag
mapping[r_ag] = ag
todos.append((r_ag, ag))
return si == r_si and ag == ag_dst
else:
return False
else:
return False
else:
return (isinstance(ref._links, type(self._links))
and ref._links == self._links)
else:
return False
@property
def internal_states(self):
return self._internals
def get_internal_state(self) -> str:
""":returns: if any, the internal state of the site when there can only \
be 1 by invarient (because it is a pattern/rule/snapshot/...). \
None if there is not.
"""
if self._internals is None:
return None
elif len(self._internals) == 0:
return None
else:
assert len(self._internals) == 1
return self._internals[0]
def has_link(self) -> bool:
""":returns: whether the link state is neither free nor unspecified?"""
return bool(self._links)
def neighbours_in_complex(self, complx):
""":returns: the list of ``KappaAgent`` connected to here in ``complx``
"""
if type(self._links) is list:
return [complx[a] for (a, s) in self._links]
else:
return []
@staticmethod
def __str_link_in_complex(line, row, site, trailing, dst):
out = trailing.pop((((line, row), site), dst), None)
if out is None:
free = trailing[None]
trailing[(dst, ((line, row), site))] = free
trailing[None] = free+1
return str(free)
else:
return str(out)
def __str_internals(self):
if self._internals is None:
if self._future_internal is None:
out = ""
else:
out = "{#/"+str(self._future_internal)+"}"
return out
elif len(self._internals) == 0:
assert (self._future_internal is None)
return ""
else:
head = "{" + ", ".join(self._internals)
if self._future_internal is None:
tail = "}"
else:
tail = "/"+str(self._future_internal)+"}"
return head+tail
def _str_in_complex(self, line, row, site, trailing):
if self._future_link is None:
mod = "]"
elif self._future_link is False:
mod = "/.]"
else:
mod = "/"+str(self.future_link)+"]"
if self._links is None:
if self._future_link is None:
return self.__str_internals()
else:
return "[#"+mod+self.__str_internals()
elif self._links is True:
return "[_"+mod+self.__str_internals()
elif type(self._links) is list:
if len(self._links) == 0:
return "[."+mod+self.__str_internals()
else:
links = ", ".join(
[self.__str_link_in_complex(line, row, site, trailing, x)
for x in self._links])
return "["+links+mod+self.__str_internals()
else:
site = self._links["site_name"]
ag = self._links["agent_type"]
return "["+site+"."+ag+links+mod+self.__str_internals()
@staticmethod
def __get_site_name(complx, x):
if type(x[0]) is list:
ag = complx[x[0][0]][x[0][1]]
else:
ag = complx[x[0]]
return ag["node_sites"][x[1]]["site_name"]
@classmethod
def from_JSONDecoder_in_complex(cls, data, complx, *, in_1d):
if data[0] != "port":
raise Exception("Can only handle port sites for now")
raw_links = data[1]["port_links"]
if type(raw_links) is not list:
links = raw_links
else:
if in_1d is None:
if len(raw_links) > 0 and type(raw_links[0][0]) is list:
links = [(tuple(x[0]), cls.__get_site_name(complx, x))
for x in raw_links]
else:
links = [((0, x[0]), cls.__get_site_name(complx, x))
for x in raw_links]
else:
links = [((0, x[0]), cls.__get_site_name(complx, x)) if in_1d
else (tuple(x[0]), cls.__get_site_name(complx, x))
for x in raw_links]
return cls(links=links, internals=data[1]["port_states"])
@classmethod
def from_string_in_complex(cls, expression: str,
position, dangling, completed):
# define patterns that make up a site
int_state_pat = \
r'(?: ?{ ?(' + ident_re + r'|#) ?(?: ?(/ ?)(' + ident_re + r') ?)?} ?)?'
bnd_state_pat = r' ?\[ ?(.|_|#|\d+) ?(?:(/ ?)(.|\d+) ?)?\] ?'
port_pat = r'^' + int_state_pat + bnd_state_pat + int_state_pat + r'$'
# parse assuming full site declaration, with bond state declared
g = re.match(port_pat, expression)
# if that fails, try parsing with bond state declared as a wildcard
if not g:
g = re.match(port_pat, expression + '[#]')
# if that fails, throw an error
if not g:
raise KappaSyntaxError('Invalid site declaration <'+expression+'>')
# figure out what type of bond operation is being performed
if g.group(4) == '.':
links = []
elif g.group(4) == '#':
links = None
elif g.group(4) == '_':
links = True
else:
link = int(g.group(4))
dst = dangling.pop(link, None)
if dst is None:
links = link
dangling[link] = position
else:
links = [dst]
completed[dst] = position
# if g.group(5): # if there's an operation
# self._future_link = g.group(6)
# figure out what type of internal state operation is being performed
internals = None
if g.group(1) and not g.group(1) == '#':
internals = [g.group(1)]
# self._future_internal = g.group(3) if g.group(3) else ''
elif g.group(7) and not g.group(7) == '#':
internals = [g.group(7)]
# self._future_int_state = g.group(9) if g.group(9) else ''
return cls(links=links, internals=internals)
|
class KappaSite:
'''class for representing one site of a kappa agent (in a complex)'''
def __init__(self, *, links=None, internals=None,
future_link=None, future_internal=None):
pass
def __repr__(self):
pass
def is_more_specific_than(self, ref, *, mapping=None, todos=None):
pass
def is_equal(self, ref, *, mapping=None, todos=None):
pass
@property
def internal_states(self):
pass
def get_internal_state(self) -> str:
''':returns: if any, the internal state of the site when there can only be 1 by invarient (because it is a pattern/rule/snapshot/...). None if there is not.
'''
pass
def has_link(self) -> bool:
''':returns: whether the link state is neither free nor unspecified?'''
pass
def neighbours_in_complex(self, complx):
''':returns: the list of ``KappaAgent`` connected to here in ``complx``
'''
pass
@staticmethod
def __str_link_in_complex(line, row, site, trailing, dst):
pass
def __str_internals(self):
pass
def _str_in_complex(self, line, row, site, trailing):
pass
@staticmethod
def __get_site_name(complx, x):
pass
@classmethod
def from_JSONDecoder_in_complex(cls, data, complx, *, in_1d):
pass
@classmethod
def from_string_in_complex(cls, expression: str,
position, dangling, completed):
pass
| 20 | 4 | 17 | 0 | 15 | 2 | 5 | 0.12 | 0 | 8 | 1 | 0 | 10 | 4 | 14 | 14 | 257 | 17 | 222 | 53 | 200 | 26 | 148 | 45 | 133 | 9 | 0 | 6 | 64 |
141,836 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_std.py
|
kappy.kappa_std.KappaStd
|
class KappaStd(KappaApi):
"""Kappa tools driver run locally.
kappa_bin_path -- where to find kappa executables
(None means use the binaries bundled in the package)
delimiter -- What to use to delimit messages (must not appears in
message body default '\\x1e')
args -- arguments to pass to kappa executables
"""
def __init__(self, kappa_bin_path=None, delimiter='\x1e', args=None):
self.delimiter = delimiter
if kappa_bin_path is None:
if BIN_DIR is None:
# binaries must either exist in kappy directory or
# their location must be passed to this class
raise KappaError("Kappa binaries not found.")
kappa_bin_path = BIN_DIR
switch_args = [os.path.join(kappa_bin_path, "KappaSwitchman"),
"--delimiter",
"\\x{:02x}".format(ord(self.delimiter))]
if args:
switch_args = switch_args + args
self.lock = threading.Lock()
self.message_id = 0
self.switch_agent = subprocess.Popen(switch_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return
def __del__(self):
self.shutdown()
def _get_message_id(self):
self.message_id += 1
return self.message_id
def _read_stdout(self, agent_to_read):
"""Read from stdout of an agent. This function reads the output in
large chunks (the default buffer size) until it encounters the
delimiter. This is more efficient than reading the output one
character at a time.
"""
buff = bytearray()
delim_val = self.delimiter.encode('utf-8')
c = agent_to_read.stdout.read1(DEFAULT_BUFFER_SIZE)
while (not c.endswith(delim_val)) and c:
buff.extend(c)
c = agent_to_read.stdout.read1(DEFAULT_BUFFER_SIZE)
# strip the end character
if c:
buff.extend(c[0:-1])
return buff
def _dispatch(self, data):
try:
self.lock.acquire()
message_id = self._get_message_id()
message = [message_id, data]
message = "{0}{1}".format(json.dumps(message), self.delimiter)
self.switch_agent.stdin.write(message.encode('utf-8'))
self.switch_agent.stdin.flush()
buff = self._read_stdout(self.switch_agent)
response = json.loads(buff.decode('utf-8'))
if isinstance(response, str):
raise KappaError(response)
elif response[0] != message_id:
raise KappaError(
"expect id {0} got {1}".format(response[0],
message_id)
)
else:
return self.projection(response[1])
finally:
self.lock.release()
def shutdown(self):
"""Shut down kappa instance.
Given a key to a kappa service shutdown a running kappa
instance.
"""
if hasattr(self, 'switch_agent'):
self.switch_agent.stdin.close()
self.switch_agent.stdout.close()
self.switch_agent.terminate()
self.switch_agent.wait()
def projection(self, result_data):
data = result_data[1]
if result_data[0] == "Ok":
return data
else:
raise KappaError(data)
# Standardized API methods. Docs are provided by parent.
def project_parse(self, sharing_level="compatible_patterns", **kwargs):
overwrites = list(kwargs.items())
self._dispatch(["ProjectParse", sharing_level, overwrites])
def project_overwrite(self, ast, file_id="model.ka"):
self._dispatch(["ProjectOverwrite", file_id, ast])
def file_create(self, file_):
return self._dispatch(
["FileCreate", file_.get_position(), file_.get_id(), file_.get_content()])
def file_delete(self, file_id):
return self._dispatch(["FileDelete", file_id])
def file_get(self, file_id):
f = self._dispatch(["FileGet", file_id])
return File(FileMetadata(file_id, f[1]), f[0])
def file_info(self):
info = self._dispatch(["FileCatalog"])
return FileMetadata.from_metadata_list(info)
def simulation_delete(self):
return self._dispatch(["SimulationDelete"])
def simulation_file_line(self, file_line_id):
return self._dispatch(["SimulationDetailFileLine", file_line_id])
def simulation_DIN(self, DIN_id):
return self._dispatch(["SimulationDetailDIN", DIN_id])
def simulation_log_messages(self):
return self._dispatch(["SimulationDetailLogMessage"])
def simulation_plot(self, limit=None):
if limit is not None:
parameter = limit.toJSON()
else:
parameter = PlotLimit().toJSON()
return self._dispatch(["SimulationDetailPlot", parameter])
def simulation_snapshot(self, snapshot_id):
return KappaSnapshot.from_JSONDecoder(
self._dispatch(["SimulationDetailSnapshot", snapshot_id])
)
def simulation_info(self):
return self._dispatch(["SimulationInfo"])
def simulation_info_file_line(self):
return self._dispatch(["SimulationCatalogFileLine"])
def simulation_DINs(self):
return self._dispatch(["SimulationCatalogDIN"])
def simulation_snapshots(self):
return self._dispatch(["SimulationCatalogSnapshot"])
def simulation_pause(self):
return self._dispatch(["SimulationPause"])
def simulation_intervention(self, intervention_code):
return self._dispatch(["SimulationIntervention", intervention_code])
def simulation_start(self, simulation_parameter=None):
if simulation_parameter is None:
simulation_parameter = self.get_default_sim_param()
return self._dispatch(["SimulationStart",
simulation_parameter.toJSON()])
def simulation_continue(self, pause_condition):
return self._dispatch(["SimulationContinue", pause_condition])
def analyses_dead_rules(self):
return self._dispatch(["DEAD_RULES"])
def analyses_constraints_list(self):
return self._dispatch(["CONSTRAINTS"])
def analyses_contact_map(self, accuracy=None):
cmd = ["CONTACT_MAP", accuracy]
return self._dispatch(cmd)
def analyses_influence_map(self, accuracy=None):
cmd = ["INFLUENCE_MAP", accuracy]
return self._dispatch(cmd)
def analyses_potential_polymers(
self, accuracy_cm="high", accuracy_scc="high"):
return self._dispatch(["POLYMERS", accuracy_cm, accuracy_scc])
|
class KappaStd(KappaApi):
'''Kappa tools driver run locally.
kappa_bin_path -- where to find kappa executables
(None means use the binaries bundled in the package)
delimiter -- What to use to delimit messages (must not appears in
message body default '\x1e')
args -- arguments to pass to kappa executables
'''
def __init__(self, kappa_bin_path=None, delimiter='\x1e', args=None):
pass
def __del__(self):
pass
def _get_message_id(self):
pass
def _read_stdout(self, agent_to_read):
'''Read from stdout of an agent. This function reads the output in
large chunks (the default buffer size) until it encounters the
delimiter. This is more efficient than reading the output one
character at a time.
'''
pass
def _dispatch(self, data):
pass
def shutdown(self):
'''Shut down kappa instance.
Given a key to a kappa service shutdown a running kappa
instance.
'''
pass
def projection(self, result_data):
pass
def project_parse(self, sharing_level="compatible_patterns", **kwargs):
pass
def project_overwrite(self, ast, file_id="model.ka"):
pass
def file_create(self, file_):
pass
def file_delete(self, file_id):
pass
def file_get(self, file_id):
pass
def file_info(self):
pass
def simulation_delete(self):
pass
def simulation_file_line(self, file_line_id):
pass
def simulation_DIN(self, DIN_id):
pass
def simulation_log_messages(self):
pass
def simulation_plot(self, limit=None):
pass
def simulation_snapshot(self, snapshot_id):
pass
def simulation_info(self):
pass
def simulation_info_file_line(self):
pass
def simulation_DINs(self):
pass
def simulation_snapshots(self):
pass
def simulation_pause(self):
pass
def simulation_intervention(self, intervention_code):
pass
def simulation_start(self, simulation_parameter=None):
pass
def simulation_continue(self, pause_condition):
pass
def analyses_dead_rules(self):
pass
def analyses_constraints_list(self):
pass
def analyses_contact_map(self, accuracy=None):
pass
def analyses_influence_map(self, accuracy=None):
pass
def analyses_potential_polymers(
self, accuracy_cm="high", accuracy_scc="high"):
pass
| 33 | 3 | 5 | 0 | 4 | 0 | 1 | 0.15 | 1 | 9 | 5 | 0 | 32 | 4 | 32 | 66 | 194 | 41 | 133 | 53 | 99 | 20 | 115 | 52 | 82 | 4 | 2 | 2 | 43 |
141,837 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_graph.py
|
kappy.kappa_graph.KappaSyntaxError
|
class KappaSyntaxError(ValueError):
pass
|
class KappaSyntaxError(ValueError):
pass
| 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 11 | 2 | 0 | 2 | 1 | 1 | 0 | 2 | 1 | 1 | 0 | 4 | 0 | 0 |
141,838 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_graph.py
|
kappy.kappa_graph.KappaSnapshot
|
class KappaSnapshot:
"""class for representing a kappa snapshot
The string representation is the corresponding Kappa code.
"""
def __init__(self, *, time: float, event: int,
complexes: list = [], tokens: dict = {}):
self._time = time
self._event = event
self._complexes = complexes
self._tokens = tokens
def __repr__(self):
return "KappaSnapshot(time={},event={},complexes={},tokens={})".format(
repr(self._time),
repr(self._event),
repr(self._complexes),
repr(self._tokens)
)
def __str__(self):
event = "// Snapshot [Event: {0:d}]\n".format(self._event)
time = '%def: "T0" "{0:f}"\n\n'.format(self._time)
complexes = "".join(
["%init: {0:d} {1}\n".format(n, c) for (n, c) in self._complexes]
)
tokens = "".join(
["%init: {0:d} {1}\n".format(self._tokens[t], t)
for t in self._tokens]
)
return event+time+complexes+tokens
@property
def time(self) -> float:
"""Get the simulation time at which the snapshot was taken
"""
return self._time
@property
def event(self) -> float:
"""Get after how many simulation event the snapshot was taken
"""
return self._time
@property
def complexes(self):
"""Get the list of complexes.
:returns: a list of pairs ``(abundance: int, complex : KappaComplex)``
"""
return self._complexes
def get_complexes_by_size(self):
"""Get complexes by size. Size here means the number of agents.
:returns: dict ``size -> list_of_pair_abundance_complexes_of_that_size``
"""
out = {}
for (abundance, complx) in self._complexes:
size = len(complx)
out.setdefault(size, []).append((abundance, complx))
return out
def get_complexes_by_abundance(self):
"""Get complexes by abundance. Abundance here means copy number.
:returns: dict ``abundance -> list_of_complexes_that_abundant``
"""
out = {}
for (abundance, complx) in self._complexes:
out.setdefault(abundance, []).append(complx)
return out
def get_largest_complexes(self):
""":returns: list of the largest KappaComplexes with their abundance.
"""
return (max(self.get_complexes_by_size().items(),
key=lambda c: c[0]))
def get_smallest_complexes(self):
""":returns: list of the smallest KappaComplexes with their adundance.
"""
return (min(self.get_complexes_by_size().items(),
key=lambda c: c[0]))
def get_most_abundant_complexes(self):
""":returns: list of the most abundant KappaComplexes."""
return (max(self.get_complexes_by_abundance().items(),
key=lambda c: c[0]))
def get_least_abundant_complexes(self):
""":returns: list of the least abundant KappaComplexes."""
return (min(self.get_complexes_by_abundance().items(),
key=lambda c: c[0]))
def get_size_distribution(self):
""":returns: dict ``size : int -> number_of_complexes_of_that_size``
"""
out = {}
for (abundance, complx) in self._complexes:
size = len(complx)
out[size] = out.get(size, 0) + abundance
return out
def get_total_mass(self) -> int:
"""Get the total number of agents"""
out = 0
for (abundance, complx) in self._complexes:
out += abundance * len(complx)
return out
@property
def tokens(self):
"""Get the dictionnary ``token : str -> abundance : int``
"""
return self._tokens
def get_token_abundance(self, token: str) -> int:
"""Get the abundance of ``token``
"""
return self._tokens[token]
@classmethod
def from_JSONDecoder(cls, data):
complexes = [(x[0], KappaComplex.from_JSONDecoder(x[1]))
for x in data["snapshot_agents"]]
tokens = dict([x[1], x[0]] for x in data["snapshot_tokens"])
return cls(time=data["snapshot_time"], event=data["snapshot_event"],
complexes=complexes, tokens=tokens)
|
class KappaSnapshot:
'''class for representing a kappa snapshot
The string representation is the corresponding Kappa code.
'''
def __init__(self, *, time: float, event: int,
complexes: list = [], tokens: dict = {}):
pass
def __repr__(self):
pass
def __str__(self):
pass
@property
def time(self) -> float:
'''Get the simulation time at which the snapshot was taken
'''
pass
@property
def event(self) -> float:
'''Get after how many simulation event the snapshot was taken
'''
pass
@property
def complexes(self):
'''Get the list of complexes.
:returns: a list of pairs ``(abundance: int, complex : KappaComplex)``
'''
pass
def get_complexes_by_size(self):
'''Get complexes by size. Size here means the number of agents.
:returns: dict ``size -> list_of_pair_abundance_complexes_of_that_size``
'''
pass
def get_complexes_by_abundance(self):
'''Get complexes by abundance. Abundance here means copy number.
:returns: dict ``abundance -> list_of_complexes_that_abundant``
'''
pass
def get_largest_complexes(self):
''':returns: list of the largest KappaComplexes with their abundance.
'''
pass
def get_smallest_complexes(self):
''':returns: list of the smallest KappaComplexes with their adundance.
'''
pass
def get_most_abundant_complexes(self):
''':returns: list of the most abundant KappaComplexes.'''
pass
def get_least_abundant_complexes(self):
''':returns: list of the least abundant KappaComplexes.'''
pass
def get_size_distribution(self):
''':returns: dict ``size : int -> number_of_complexes_of_that_size``
'''
pass
def get_total_mass(self) -> int:
'''Get the total number of agents'''
pass
@property
def tokens(self):
'''Get the dictionnary ``token : str -> abundance : int``
'''
pass
def get_token_abundance(self, token: str) -> int:
'''Get the abundance of ``token``
'''
pass
@classmethod
def from_JSONDecoder(cls, data):
pass
| 23 | 14 | 7 | 1 | 4 | 2 | 1 | 0.36 | 0 | 6 | 1 | 0 | 16 | 4 | 17 | 17 | 140 | 31 | 80 | 44 | 56 | 29 | 58 | 38 | 40 | 2 | 0 | 1 | 21 |
141,839 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_graph.py
|
kappy.kappa_graph.KappaComplexIterator
|
class KappaComplexIterator(abc.Iterator):
def __init__(self, v, *, with_key):
self._with_key = with_key
self._line_iter = iter(v)
self._line = 0
self._row_iter = None
def __next__(self):
if self._row_iter is None:
self._row = -1
self._row_iter = iter(next(self._line_iter))
try:
o = next(self._row_iter)
self._row += 1
while o is None:
o = next(self._row_iter)
self._row += 1
return ((self._line, self._row), o) if self._with_key else o
except StopIteration:
self._line += 1
self._row_iter = None
self.__next__()
|
class KappaComplexIterator(abc.Iterator):
def __init__(self, v, *, with_key):
pass
def __next__(self):
pass
| 3 | 0 | 10 | 0 | 10 | 0 | 3 | 0 | 1 | 1 | 0 | 0 | 2 | 5 | 2 | 27 | 23 | 2 | 21 | 9 | 18 | 0 | 21 | 9 | 18 | 5 | 5 | 2 | 6 |
141,840 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_graph.py
|
kappy.kappa_graph.KappaComplex
|
class KappaComplex(abc.Sequence):
"""Class for representing a Kappa connected component
The string representation is the corresponding Kappa code.
``abc.Sized``: ``len`` returns the number of agents in the complex
(the size).
``abc.Iterable``: ``iter`` returns an iterator on the agents it
contains. Use method ``items()`` to get an iterator over the
tuples ``(coordinates,agent)``.
``abc.Container``: ``x in y`` returns whether the pattern ``x``
occurs in ``y`` (in term of "Kappa embedding"). Use
``y.find_pattern(x)`` to get the embeddings.
Use ``self[coordinates]`` to get the agent at ``coordinates``.
"""
def __init__(self, agents):
self._agents = agents
self._nodes_by_type = {}
i = 0
for line in agents:
j = 0
for el in line:
if el:
self._nodes_by_type.setdefault(
el.get_type(), []).append((i, j))
j += 1
i += 1
def __repr__(self):
return "KappaComplex({})".format(repr(self._agents))
def __str__(self):
trailing = {None: 0}
lines = [[
"." if e is None else e._str_in_complex(l, r, trailing)
for (r, e) in enumerate(line)
] for (l, line) in enumerate(self._agents)]
return "\\ ".join(map(", ".join, lines))
def __getitem__(self, key):
if type(key) is tuple:
(l, r) = key
return self._agents[l][r]
else:
return self._agents[0][key]
def __iter__(self):
return KappaComplexIterator(self._agents, with_key=False)
def __len__(self):
r = 0
for line in self._agents:
for el in line:
if el:
r += 1
return r
def items(self):
"""
:returns: an Iterator where the items are turples (coordinates,agent)
"""
return KappaComplexIterator(self._agents, with_key=True)
def agent_ids_of_type(self, type: str):
""":returns: the list of coordinates of agents of type ``type``"""
return self._nodes_by_type[type]
def agent_ids_by_type(self):
""":returns: a dictionary from ``type : str`` to coordinates of agents \
of type ``type``
"""
return self._nodes_by_type
def contains_at_pos(self, id, ref, ref_id):
mapping = {ref_id: id}
todos = [(ref_id, id)]
while len(todos) > 0:
(rag, ag) = todos.pop()
if not self[ag].is_more_specific_than(ref[rag],
mapping=mapping,
todos=todos):
return None
return mapping
def __eq_rooted(self, id, ref, ref_id):
mapping = {ref_id: id}
todos = [(ref_id, id)]
while len(todos) > 0:
(rag, ag) = todos.pop()
if not self[ag].is_equal(ref[rag], mapping=mapping, todos=todos):
return None
return mapping
def find_pattern(self, ref):
""":returns: a list of dictionnary \
``coordinates -> coordinates``. Each dictionnary represents an \
embedding of ``ref`` in the complex.
"""
ag_ty, ref_ids = smallest_non_empty(ref._nodes_by_type)
candidates = self._nodes_by_type.get(
ag_ty, allocated_once_for_all_empty_list)
return [x for x in [self.contains_at_pos(cand, ref, ref_ids[0])
for cand in candidates]
if x]
def __contains__(self, pattern):
return not len(self.find_pattern(pattern)) == 0
def __same_sum_formula(a, b):
if len(a._nodes_by_type) != len(b._nodes_by_type):
return False
for ty in a._nodes_by_type:
if (len(b._nodes_by_type.get(ty, allocated_once_for_all_empty_list))
!= len(a._nodes_by_type[ty])):
return False
return True
def __eq__(a, b):
if a.__same_sum_formula(b):
ag_ty, ref_ids = smallest_non_empty(a._nodes_by_type)
ref_id = ref_ids[0]
for cand in b._nodes_by_type[ag_ty]:
if b.__eq_rooted(cand, a, ref_id):
return True
return False
@classmethod
def from_JSONDecoder(cls, data):
""" Build a KappaComplex from its JSON representation"""
if len(data) > 0 and type(data[0]) is dict:
return cls([[
KappaAgent.from_JSONDecoder_in_complex(x, data, in_1d=True)
for x in data
]])
else:
return cls([[
KappaAgent.from_JSONDecoder_in_complex(x, data, in_1d=False)
for x in line
] for line in data])
@classmethod
def from_string(cls, expression):
"""Build a KappaComplex from its Kappa syntax"""
# remove comments, new_lines, multiple spaces
expression = re.sub(whitespace_re, ' ', expression)
# get the set of agents making up this complex
agent_name_pat = r' ?' + ident_re
agent_sign_pat = r' ?\([^()]*\)'
matches = re.findall(agent_name_pat+agent_sign_pat, expression.strip())
if len(matches) == 0:
raise KappaSyntaxError('Complex <' + self._raw_expression +
'> appears to have zero agents.')
agent_list = []
dangling = {}
completed = {}
for id, item in enumerate(matches):
agent = KappaAgent.from_string_in_complex(item, (0, id),
dangling,
completed)
agent_list.append(agent)
if len(dangling) != 0:
raise KappaSyntaxError('Dangling link <' + str(dangling.popitem()) +
'> in complex <' + expression + '>.')
for (((col, row), si), dst) in completed.items():
site = agent_list[row][si]
agent_list[row]._sites[si] = KappaSite(links=[dst],
internals=site.internal_states)
return cls([agent_list])
|
class KappaComplex(abc.Sequence):
'''Class for representing a Kappa connected component
The string representation is the corresponding Kappa code.
``abc.Sized``: ``len`` returns the number of agents in the complex
(the size).
``abc.Iterable``: ``iter`` returns an iterator on the agents it
contains. Use method ``items()`` to get an iterator over the
tuples ``(coordinates,agent)``.
``abc.Container``: ``x in y`` returns whether the pattern ``x``
occurs in ``y`` (in term of "Kappa embedding"). Use
``y.find_pattern(x)`` to get the embeddings.
Use ``self[coordinates]`` to get the agent at ``coordinates``.
'''
def __init__(self, agents):
pass
def __repr__(self):
pass
def __str__(self):
pass
def __getitem__(self, key):
pass
def __iter__(self):
pass
def __len__(self):
pass
def items(self):
'''
:returns: an Iterator where the items are turples (coordinates,agent)
'''
pass
def agent_ids_of_type(self, type: str):
''':returns: the list of coordinates of agents of type ``type``'''
pass
def agent_ids_by_type(self):
''':returns: a dictionary from ``type : str`` to coordinates of agents of type ``type``
'''
pass
def contains_at_pos(self, id, ref, ref_id):
pass
def __eq_rooted(self, id, ref, ref_id):
pass
def find_pattern(self, ref):
''':returns: a list of dictionnary ``coordinates -> coordinates``. Each dictionnary represents an embedding of ``ref`` in the complex.
'''
pass
def __contains__(self, pattern):
pass
def __same_sum_formula(a, b):
pass
def __eq__(a, b):
pass
@classmethod
def from_JSONDecoder(cls, data):
''' Build a KappaComplex from its JSON representation'''
pass
@classmethod
def from_string(cls, expression):
'''Build a KappaComplex from its Kappa syntax'''
pass
| 20 | 7 | 8 | 0 | 7 | 1 | 2 | 0.22 | 1 | 9 | 4 | 0 | 15 | 2 | 17 | 52 | 176 | 26 | 123 | 54 | 103 | 27 | 98 | 52 | 80 | 5 | 6 | 3 | 40 |
141,841 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_graph.py
|
kappy.kappa_graph.KappaAgent
|
class KappaAgent(abc.Sequence):
"""class for representing one kappa agent inside a complex
``abc.Sized``: ``len`` returns its number of sites.
``abc.Iterable``: ``iter`` returns an iterator over the tuple
``(site_name : str, s : KappaSite)``
Use ``self[site_name]`` to get a site.
"""
def __init__(self, typ: str, node_id, sites: dict):
self._type = typ
self._node_id = node_id
self._sites = sites
def __repr__(self):
return "KappaAgent({},{},{})".format(
repr(self._type),
repr(self._node_id),
repr(self._sites)
)
def __len__(self):
return len(self._sites)
def __getitem__(self, key: str):
return self._sites[key]
def __iter__(self):
return iter(self._sites.items())
def is_more_specific_than(self, ref, *, mapping=None, todos=None):
if ref._type == self._type:
return all(self._sites.get(na, KappaSite()).
is_more_specific_than(ref._sites[na],
mapping=mapping,
todos=todos)
for na in ref._sites)
else:
return False
def is_equal(self, ref, *, mapping=None, todos=None):
if ref._type == self._type:
return all(self._sites.get(na, KappaSite()).
is_equal(ref._sites[na], mapping=mapping, todos=todos)
for na in ref._sites)
else:
return False
def get_type(self) -> str:
"""::returns: the type of the agent"""
return self._type
def get_node_id(self):
"""::returns: the id of the agent if present (else Null)"""
return self._node_id
def get_neighbours_in_complex(self, complx):
"""Destination of the edges.
:param KappaComplex complx: Complex ``self`` is part of
:returns: list of ``KappaAgent``
.. warning::
potential duplicates and self listing.
"""
return [el for (_, s) in self
for el in s.neighbours_in_complex(complx)]
def _str_in_complex(self, line, row, trailing):
sites = [n + self._sites[n]._str_in_complex(line, row, n, trailing)
for n in self._sites]
if self._node_id is not None:
witness = "x"+str(self._node_id)+":"
else:
witness = ""
return witness + self._type + "(" + " ".join(sites) + ")"
@classmethod
def from_JSONDecoder_in_complex(cls, data, complx, *, in_1d):
if data is None:
return None
else:
sites = dict([
x["site_name"],
KappaSite.from_JSONDecoder_in_complex(x["site_type"],
complx, in_1d=in_1d)
] for x in data["node_sites"])
return cls(data["node_type"], data.get("node_id"), sites)
@classmethod
def from_string_in_complex(cls, expression: str,
position, dangling, completed):
if re.match(r'^\.$', expression.strip()):
return None
else:
# Check if kappa expression's name & overall structure is valid
agent_name_pat = ident_re
agent_sign_pat = r'\(([^()]*)\)'
agent_oper_pat = r'(\+|-)?'
agent_pat = \
r'^(' + agent_name_pat + r')' + \
agent_sign_pat+agent_oper_pat + r'$'
matches = re.match(agent_pat, expression.strip())
if not matches:
matches = re.match(agent_pat, expression.strip() + '()')
if not matches:
raise KappaSyntaxError('Invalid agent declaration <' +
expression + '>')
# process & assign to variables
agent_name = matches.group(1)
# process agent signature
ag_signature = matches.group(2)
if ag_signature == '':
site_list = []
else:
site_block_re = r'('+ident_re + \
')((?:\[[^\]]+\]|{[^}]+})+) ?,? ?'
site_list = re.finditer(site_block_re, ag_signature)
agent_signature = {}
for id, match in enumerate(site_list):
name = match.group(1)
site = KappaSite.from_string_in_complex(match.group(2),
(position, name),
dangling,
completed)
agent_signature[name] = site
# process abundance operator, if present
# abundance_change = matches.group(3) if matches.group(3) else ''
return cls(agent_name, None, agent_signature)
|
class KappaAgent(abc.Sequence):
'''class for representing one kappa agent inside a complex
``abc.Sized``: ``len`` returns its number of sites.
``abc.Iterable``: ``iter`` returns an iterator over the tuple
``(site_name : str, s : KappaSite)``
Use ``self[site_name]`` to get a site.
'''
def __init__(self, typ: str, node_id, sites: dict):
pass
def __repr__(self):
pass
def __len__(self):
pass
def __getitem__(self, key: str):
pass
def __iter__(self):
pass
def is_more_specific_than(self, ref, *, mapping=None, todos=None):
pass
def is_equal(self, ref, *, mapping=None, todos=None):
pass
def get_type(self) -> str:
'''::returns: the type of the agent'''
pass
def get_node_id(self):
'''::returns: the id of the agent if present (else Null)'''
pass
def get_neighbours_in_complex(self, complx):
'''Destination of the edges.
:param KappaComplex complx: Complex ``self`` is part of
:returns: list of ``KappaAgent``
.. warning::
potential duplicates and self listing.
'''
pass
def _str_in_complex(self, line, row, trailing):
pass
@classmethod
def from_JSONDecoder_in_complex(cls, data, complx, *, in_1d):
pass
@classmethod
def from_string_in_complex(cls, expression: str,
position, dangling, completed):
pass
| 16 | 4 | 8 | 0 | 7 | 1 | 2 | 0.2 | 1 | 5 | 2 | 0 | 11 | 3 | 13 | 48 | 135 | 22 | 94 | 37 | 77 | 19 | 62 | 33 | 48 | 6 | 6 | 3 | 22 |
141,842 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_common.py
|
kappy.kappa_common.SimulationParameter
|
class SimulationParameter(object):
"""Parameters needed to run a simulation
:param plot_period: How often values of observables should be
computed during the simulation
:param pause_condition: (a boolean kappa expression) When the
simulation will stop itself and wait for further actions.
:param seed: specify the seed
of the random number generator used by the simulator
:param store_trace: Because simulation traces become huge, you
must specify before starting a simulation whether you may
query it later
"""
def __init__(self, plot_period: float, pause_condition: str,
seed: int = None, store_trace: bool = False):
self.plot_period = plot_period
self.pause_condition = pause_condition
self.seed = seed
self.store_trace = store_trace
def toJSON(self):
return {"plot_period": self.plot_period,
"pause_condition": self.pause_condition,
"store_trace": self.store_trace,
"seed": self.seed}
|
class SimulationParameter(object):
'''Parameters needed to run a simulation
:param plot_period: How often values of observables should be
computed during the simulation
:param pause_condition: (a boolean kappa expression) When the
simulation will stop itself and wait for further actions.
:param seed: specify the seed
of the random number generator used by the simulator
:param store_trace: Because simulation traces become huge, you
must specify before starting a simulation whether you may
query it later
'''
def __init__(self, plot_period: float, pause_condition: str,
seed: int = None, store_trace: bool = False):
pass
def toJSON(self):
pass
| 3 | 1 | 6 | 0 | 6 | 0 | 1 | 0.92 | 1 | 4 | 0 | 0 | 2 | 4 | 2 | 2 | 30 | 7 | 12 | 8 | 8 | 11 | 8 | 7 | 5 | 1 | 1 | 0 | 2 |
141,843 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_common.py
|
kappy.kappa_common.PlotLimit
|
class PlotLimit(object):
"""Parameters of plot query
:param points: maximum number of column that the reply should \
contains. (None means unlimited)
:param offset: At what column number the reply should start \
(None means return the end of the simulation)
"""
def __init__(self, offset=None, points=None):
self.offset = offset
self.points = points
def toURL(self):
if self.offset is not None:
url_offset = "&plot_limit_offset={0}".format(self.offset)
else:
url_offset = ""
if self.points is not None:
url_points = "&plot_limit_points={0}".format(self.points)
else:
url_points = ""
url_plot_limit = "{0}{1}".format(url_offset,
url_points)
return url_plot_limit
def toJSON(self):
return {"offset": self.offset,
"nb_points": self.points}
|
class PlotLimit(object):
'''Parameters of plot query
:param points: maximum number of column that the reply should contains. (None means unlimited)
:param offset: At what column number the reply should start (None means return the end of the simulation)
'''
def __init__(self, offset=None, points=None):
pass
def toURL(self):
pass
def toJSON(self):
pass
| 4 | 1 | 7 | 1 | 6 | 0 | 2 | 0.32 | 1 | 0 | 0 | 0 | 3 | 2 | 3 | 3 | 33 | 8 | 19 | 9 | 15 | 6 | 15 | 9 | 11 | 3 | 1 | 1 | 5 |
141,844 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_common.py
|
kappy.kappa_common.KappaError
|
class KappaError(Exception):
""" Error returned from the Kappa server"""
def __init__(self, errors):
Exception.__init__(self, errors)
self.errors = errors
|
class KappaError(Exception):
''' Error returned from the Kappa server'''
def __init__(self, errors):
pass
| 2 | 1 | 3 | 0 | 3 | 0 | 1 | 0.25 | 1 | 0 | 0 | 0 | 1 | 1 | 1 | 11 | 6 | 1 | 4 | 3 | 2 | 1 | 4 | 3 | 2 | 1 | 3 | 0 | 1 |
141,845 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_common.py
|
kappy.kappa_common.FileMetadata
|
class FileMetadata(object):
"""An object to hold the metadata for a file.
Note that it is commmon to initialized this function with a dict, in the
form FileMetaData(**metadata). If so, the dict must have arguments
matching those below, including at least 'id' and 'position'.
:param id: The id of corresponding file.
:param position: where the file should be inserted in the middle of the
other files of the model. When you add a file at position 'i'
in a model that contains 'k >= i' files, the new file is
indeed at position 'i' and all the files at position 'j>=i'
are pushed at position 'j+1'.
"""
def __init__(self, id, position):
self.id = id
self.position = position
return
@classmethod
def from_metadata_list(cls, metadata_list):
"""Get metadata objects from a list of metadata."""
return map(lambda info: cls(**info), metadata_list)
def toJSON(self):
"""Get a json dict of the attributes of this object."""
return {"id": self.id,
"position": self.position}
|
class FileMetadata(object):
'''An object to hold the metadata for a file.
Note that it is commmon to initialized this function with a dict, in the
form FileMetaData(**metadata). If so, the dict must have arguments
matching those below, including at least 'id' and 'position'.
:param id: The id of corresponding file.
:param position: where the file should be inserted in the middle of the
other files of the model. When you add a file at position 'i'
in a model that contains 'k >= i' files, the new file is
indeed at position 'i' and all the files at position 'j>=i'
are pushed at position 'j+1'.
'''
def __init__(self, id, position):
pass
@classmethod
def from_metadata_list(cls, metadata_list):
'''Get metadata objects from a list of metadata.'''
pass
def toJSON(self):
'''Get a json dict of the attributes of this object.'''
pass
| 5 | 3 | 4 | 0 | 3 | 1 | 1 | 1.18 | 1 | 1 | 0 | 0 | 2 | 2 | 3 | 3 | 31 | 7 | 11 | 7 | 6 | 13 | 9 | 6 | 5 | 1 | 1 | 0 | 3 |
141,846 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/kappy/kappa_common.py
|
kappy.kappa_common.File
|
class File(object):
"""An object that represents a kappa file.
:param metadata: this may be either a dict with keys matching the inits of
FileMetadata, or an existing FileMetadata object.
:param content: The content of the file.
"""
def __init__(self, metadata, content):
if isinstance(metadata, FileMetadata):
self.file_metadata = metadata
elif isinstance(metadata, dict):
self.file_metadata = FileMetadata(**metadata)
else:
raise KappaError("Incorrect type for metadata. "
"Require dict or FileMetadata object, but got "
"%s." % type(metadata))
self.file_content = content
return
@classmethod
def from_string(cls, content, position=1, file_id=None):
"""Convenience method to create a file from a string.
This file object's metadata will have the id 'inlined_input'.
:param content: the content of the file (a string).
:param position: rank among all files of the model while parsing
see FileMetadata
:param file_id: the file_id that will be used by kappa.
"""
if file_id is None:
file_id = 'inlined_input'
return cls(FileMetadata(file_id, position), content)
@classmethod
def from_file(cls, fpath, position=1, file_id=None):
"""Convience method to create a kappa file object from a file on disk
:param fpath: path to the file on disk
:param position: (default 1) rank among all files of the model
while parsing see FileMetadata
:param file_id: (default = fpath) the file_id that will be
used by kappa.
"""
if file_id is None:
file_id = fpath
with open(fpath) as f:
code = f.read()
file_content = str(code)
file_metadata = FileMetadata(file_id, position)
return cls(file_metadata, file_content)
def get_id(self):
"""Get the id of the file from the metadata."""
return self.file_metadata.id
def get_position(self):
"""Get the id of the file from the metadata."""
return self.file_metadata.position
def get_content(self):
"""Get the file's contents."""
return self.file_content
|
class File(object):
'''An object that represents a kappa file.
:param metadata: this may be either a dict with keys matching the inits of
FileMetadata, or an existing FileMetadata object.
:param content: The content of the file.
'''
def __init__(self, metadata, content):
pass
@classmethod
def from_string(cls, content, position=1, file_id=None):
'''Convenience method to create a file from a string.
This file object's metadata will have the id 'inlined_input'.
:param content: the content of the file (a string).
:param position: rank among all files of the model while parsing
see FileMetadata
:param file_id: the file_id that will be used by kappa.
'''
pass
@classmethod
def from_file(cls, fpath, position=1, file_id=None):
'''Convience method to create a kappa file object from a file on disk
:param fpath: path to the file on disk
:param position: (default 1) rank among all files of the model
while parsing see FileMetadata
:param file_id: (default = fpath) the file_id that will be
used by kappa.
'''
pass
def get_id(self):
'''Get the id of the file from the metadata.'''
pass
def get_position(self):
'''Get the id of the file from the metadata.'''
pass
def get_content(self):
'''Get the file's contents.'''
pass
| 9 | 6 | 9 | 2 | 5 | 3 | 2 | 0.69 | 1 | 5 | 2 | 0 | 4 | 2 | 6 | 6 | 70 | 16 | 32 | 15 | 23 | 22 | 26 | 12 | 19 | 3 | 1 | 1 | 10 |
141,847 |
Kappa-Dev/KaSim
|
Kappa-Dev_KaSim/setup.py
|
setup.MyBuildExtCommand
|
class MyBuildExtCommand(setuptools.command.build_ext.build_ext):
"""Compile Kappa agent in addition of standard build"""
def append_a_binary(self,bin_dir,name):
file_in_src = os.path.realpath(os.path.join('bin',name))
if os.path.isfile(file_in_src):
distutils.file_util.copy_file(file_in_src, os.path.join(bin_dir,name))
self.my_outputs.append(os.path.join(bin_dir, name))
def run(self):
self.my_outputs = []
self.run_command('build_agents')
bin_dir = os.path.join(self.build_lib, 'kappy/bin')
distutils.dir_util.mkpath(bin_dir)
self.append_a_binary(bin_dir,"KaSimAgent")
self.append_a_binary(bin_dir,"KappaSwitchman")
self.append_a_binary(bin_dir,"KaSaAgent")
self.append_a_binary(bin_dir,"KaMoHa")
setuptools.command.build_ext.build_ext.run(self)
def get_outputs(self):
outputs = setuptools.command.build_ext.build_ext.get_outputs(self)
outputs.extend(self.my_outputs)
return outputs
|
class MyBuildExtCommand(setuptools.command.build_ext.build_ext):
'''Compile Kappa agent in addition of standard build'''
def append_a_binary(self,bin_dir,name):
pass
def run(self):
pass
def get_outputs(self):
pass
| 4 | 1 | 6 | 0 | 6 | 0 | 1 | 0.05 | 0 | 0 | 0 | 0 | 3 | 1 | 3 | 3 | 25 | 4 | 20 | 8 | 16 | 1 | 20 | 8 | 16 | 2 | 0 | 1 | 4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.