Skip to content

Commit b30a365

Browse files
committed
Refactor into single package
1 parent baa5981 commit b30a365

27 files changed

+175
-129
lines changed

README.md

+7-3
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,16 @@ mkdir $HOME/.chip-storage/
3434
With the following command the server can be run directly from the source tree.
3535

3636
```
37-
python3 -m chip_ws_server
37+
python3 -m matter_server.server
3838
```
3939

40+
_On MacOs you will have to run above command with 'sudo' as it requires to interact with BLE._
41+
4042
The client does not need to be run in the Python CHIP Controller environment. It
4143
can be run from the source tree using:
4244

4345
```
44-
python3 -m chip_ws_server
46+
python3 -m matter_server.client
4547
```
4648

4749
### Build and install
@@ -64,9 +66,11 @@ Instruction on how to create a test device can be found [here](https://nabucasa.
6466
Currently the easiest way to set up a test device is using the Python CHIP REPL. Start it by pointing it at the same storage location as the servier will run off:
6567

6668
```
67-
sudo chip-repl --storagepath=$HOME/.chip-storage/python-kv.json
69+
chip-repl --storagepath=$HOME/.chip-storage/python-kv.json
6870
```
6971

72+
_On MacOs you will have to run above command with 'sudo' as it requires to interact with BLE._
73+
7074
Inside the Python REPL, configure your Wi-Fi credentials:
7175

7276
```python

main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import sys
22

3-
from chip_ws_server.__main__ import main
3+
from matter_server.server.__main__ import main
44

5-
if __name__ == '__main__':
5+
if __name__ == "__main__":
66
sys.exit(main())
File renamed without changes.
File renamed without changes.

chip_ws_client/__main__.py matter_server/client/__main__.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,9 @@
44
import sys
55

66
import aiohttp
7-
from chip.clusters import Objects as Clusters
7+
from matter_server.vendor.chip.clusters import Objects as Clusters
88

9-
from chip_ws_client.client import Client
9+
from matter_server.client.client import Client
1010

1111
logging.basicConfig(level=logging.DEBUG)
1212
_LOGGER = logging.getLogger(__name__)
@@ -44,20 +44,20 @@ async def toggle_happiness(client: Client, is_initialized: asyncio.Event):
4444
nodeid = 4335
4545

4646
# This (now) throws exceptions if it fails
47-
await client.driver.device_controller.ResolveNode(nodeid)
47+
# await client.driver.device_controller.ResolveNode(nodeid)
4848

49-
node = await client.driver.device_controller.Read(
50-
nodeid, attributes=[Clusters.OnOff], events="*", returnClusterObject=True
51-
)
52-
await asyncio.sleep(1)
49+
# node = await client.driver.device_controller.Read(
50+
# nodeid, attributes=[Clusters.OnOff], events="*", returnClusterObject=True
51+
# )
52+
# await asyncio.sleep(1)
5353

54-
node = await client.driver.device_controller.Read(
55-
nodeid, attributes="*", events="*", returnClusterObject=True
56-
)
54+
# node = await client.driver.device_controller.Read(
55+
# nodeid, attributes="*", events="*", returnClusterObject=True
56+
# )
5757

58-
from pprint import pprint
58+
# from pprint import pprint
5959

60-
pprint(node)
60+
# pprint(node)
6161

6262
while True:
6363
await asyncio.sleep(5)

chip_ws_client/client.py matter_server/client/client.py

+22-8
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,23 @@
1515
from types import TracebackType
1616
from typing import Any, DefaultDict, Dict, List, cast
1717

18-
from aiohttp import (ClientSession, ClientWebSocketResponse, WSMsgType,
19-
client_exceptions)
20-
from chip_ws_common.json_utils import CHIPJSONEncoder
18+
from aiohttp import ClientSession, ClientWebSocketResponse, WSMsgType, client_exceptions
2119

22-
from chip_ws_client.model.version import VersionInfoDataType
2320

21+
from ..common.json_utils import CHIPJSONEncoder
22+
from .model.version import VersionInfoDataType
2423
from .const import MAX_SERVER_SCHEMA_VERSION, MIN_SERVER_SCHEMA_VERSION
2524
from .event import Event
26-
from .exceptions import (CannotConnect, ConnectionClosed, ConnectionFailed,
27-
FailedCommand, InvalidMessage, InvalidServerVersion,
28-
InvalidState, NotConnected)
25+
from .exceptions import (
26+
CannotConnect,
27+
ConnectionClosed,
28+
ConnectionFailed,
29+
FailedCommand,
30+
InvalidMessage,
31+
InvalidServerVersion,
32+
InvalidState,
33+
NotConnected,
34+
)
2935
from .model.driver import Driver
3036
from .model.version import VersionInfo
3137

@@ -383,6 +389,12 @@ async def _send_json_message(self, message: Dict[str, Any]) -> None:
383389
cmd_dict = asdict(value)
384390
cls = type(value)
385391
cmd_dict["_type"] = f"{cls.__module__}.{cls.__qualname__}"
392+
393+
# Currently in client we have vendorized chip. Strip vendor prefix.
394+
strip_prefix = "matter_server.vendor."
395+
if cmd_dict["_type"].startswith(strip_prefix):
396+
cmd_dict["_type"] = cmd_dict["_type"][len(strip_prefix) :]
397+
386398
message["args"][arg] = cmd_dict
387399

388400
if self._record_messages and message["messageId"] not in LISTEN_MESSAGE_IDS:
@@ -398,7 +410,9 @@ async def _send_json_message(self, message: Dict[str, Any]) -> None:
398410
)
399411

400412
try:
401-
await self._client.send_json(message, dumps=partial(json.dumps, cls=CHIPJSONEncoder))
413+
await self._client.send_json(
414+
message, dumps=partial(json.dumps, cls=CHIPJSONEncoder)
415+
)
402416
except:
403417
self._logger.exception("Error sending JSON")
404418

File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

chip_ws_client/model/driver.py matter_server/client/model/driver.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
if TYPE_CHECKING:
55
from .. import client
66

7-
from chip.clusters import Objects as Clusters
7+
from matter_server.vendor.chip.clusters import Objects as Clusters
88

99
from .device_controller import DeviceController
1010

File renamed without changes.
File renamed without changes.

chip_ws_common/json_utils.py matter_server/common/json_utils.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,14 @@
33
import sys
44
from enum import Enum
55

6-
import chip.clusters.Objects
7-
from chip.clusters.Types import Nullable
6+
# Compatible both with vendorized and not-vendorized
7+
try:
8+
from chip.clusters import Objects as Clusters
9+
from chip.clusters.Types import Nullable
10+
except ImportError:
11+
from ..vendor.chip.clusters import Objects as Clusters
12+
from ..vendor.chip.clusters.Types import Nullable
13+
814

915
CLUSTER_TYPE_NAMESPACE = "chip.clusters.Objects"
1016

@@ -15,7 +21,7 @@ def default(self, obj):
1521
return None
1622
elif isinstance(obj, type):
1723
# Maybe we should restrict this to CHIP cluster types (see deserialization?)
18-
return { "_class": f"{obj.__module__}.{obj.__qualname__}"}
24+
return {"_class": f"{obj.__module__}.{obj.__qualname__}"}
1925
elif isinstance(obj, Enum):
2026
# Works for chip.clusters.Attributes.EventPriority,
2127
# might need more sophisticated solution for other Enums
@@ -39,19 +45,19 @@ def _get_class(self, type: str):
3945

4046
cluster_type = type.removeprefix(f"{CLUSTER_TYPE_NAMESPACE}.")
4147

42-
cluster_cls = sys.modules[CLUSTER_TYPE_NAMESPACE]
48+
cluster_cls = Clusters
4349
for cluster_subtype in cluster_type.split("."):
4450
cluster_cls = getattr(cluster_cls, cluster_subtype)
4551

4652
return cluster_cls
4753

4854
def object_hook(self, obj: dict):
49-
if type := obj.get('_type'):
55+
if type := obj.get("_type"):
5056
cls = self._get_class(type)
5157
# Delete the `_type` key as it isn't used in the dataclasses
52-
del obj['_type']
58+
del obj["_type"]
5359
return cls(**obj)
54-
elif cls := obj.get('_class'):
60+
elif cls := obj.get("_class"):
5561
return self._get_class(cls)
5662

5763
return obj

matter_server/server/__init__.py

Whitespace-only changes.

chip_ws_server/__main__.py matter_server/server/__main__.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,19 @@
1010
import aiohttp
1111
import aiohttp.web
1212
from chip.exceptions import ChipStackError
13-
from chip_ws_common.json_utils import CHIPJSONDecoder, CHIPJSONEncoder
1413

15-
from chip_ws_server.server import CHIPControllerServer
14+
from .server import CHIPControllerServer
15+
from ..common.json_utils import CHIPJSONDecoder, CHIPJSONEncoder
1616

1717
logging.basicConfig(level=logging.WARN)
1818
_LOGGER = logging.getLogger(__name__)
1919
_LOGGER.setLevel(logging.DEBUG)
2020

2121
HOST = os.getenv("CHIP_WS_SERVER_HOST", "0.0.0.0")
2222
PORT = int(os.getenv("CHIP_WS_SERVER_PORT", 8080))
23-
STORAGE_PATH = os.getenv("CHIP_WS_STORAGE", Path.joinpath(Path.home(), ".chip-storage/python-kv.json"))
23+
STORAGE_PATH = os.getenv(
24+
"CHIP_WS_STORAGE", Path.joinpath(Path.home(), ".chip-storage/python-kv.json")
25+
)
2426

2527

2628
def create_success_response(message, result):
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,14 @@
11
import logging
22

3-
import chip.clusters.Objects as Clusters
4-
import chip.FabricAdmin
3+
from chip.FabricAdmin import FabricAdmin
54
import chip.logging
65
import chip.native
76
import coloredlogs
8-
from chip.ChipStack import *
9-
from chip.tlv import float32, uint
10-
from chip_ws_common.json_utils import CHIPJSONDecoder
7+
from chip.ChipStack import ChipStack
118

129
_LOGGER = logging.getLogger(__name__)
1310

11+
1412
class CHIPControllerServer:
1513
def __init__(self):
1614
pass
@@ -22,7 +20,7 @@ def setup(self, storage_path):
2220
coloredlogs.install(level=logging.INFO)
2321
self._stack = ChipStack(persistentStoragePath=storage_path)
2422

25-
self._fabricAdmin = chip.FabricAdmin.FabricAdmin()
23+
self._fabricAdmin = FabricAdmin()
2624

2725
self.device_controller = self._fabricAdmin.NewController()
2826
_LOGGER.info("CHIP Controller Stack initialized")
@@ -31,16 +29,3 @@ def shutdown(self):
3129
_LOGGER.info("Shutdown CHIP Controller Server")
3230
self.device_controller.Shutdown()
3331
self._stack.Shutdown()
34-
35-
# async def send_command(
36-
# self,
37-
# nodeid: int,
38-
# endpoint: int,
39-
# payload: Clusters.ClusterCommand,
40-
# responseType=None,
41-
# timedRequestTimeoutMs: int = None,
42-
# ):
43-
# _LOGGER.info(
44-
# "Sending command to node id %d, endpoint %d: %s", nodeid, endpoint, payload
45-
# )
46-
# await self.device_controller.SendCommand(nodeid, endpoint, payload)

matter_server/vendor/__init__.py

Whitespace-only changes.
File renamed without changes.

matter_server/vendor/chip/__init__.py

Whitespace-only changes.

0 commit comments

Comments
 (0)