]> git.graph-it.com Git - graphit/controlpi-graph.git/commitdiff
Ruff and Ty linting and bump to 0.4.0 master v0.4.0
authorBenjamin Braatz <bb@bbraatz.eu>
Tue, 31 Mar 2026 10:17:50 +0000 (12:17 +0200)
committerBenjamin Braatz <bb@bbraatz.eu>
Tue, 31 Mar 2026 10:17:50 +0000 (12:17 +0200)
controlpi_plugins/graph.py
controlpi_plugins/graph_connection.py
setup.py
test_graph_connection.py

index 4d7b56c998e26b32ef5a89472f4d0cb8b196dca5..2174dbadb160c629c3ba39a213ca73213be86c17 100644 (file)
@@ -1,4 +1,5 @@
 """Provide Graph Connections as ControlPi Plugin."""
 """Provide Graph Connections as ControlPi Plugin."""
+
 import json
 from controlpi import BasePlugin, Message, MessageTemplate
 
 import json
 from controlpi import BasePlugin, Message, MessageTemplate
 
@@ -8,48 +9,59 @@ from controlpi_plugins.graph_connection import GraphConnection
 class Graph(BasePlugin):
     """Graph connection plugin."""
 
 class Graph(BasePlugin):
     """Graph connection plugin."""
 
-    CONF_SCHEMA = {'properties':
-                   {'url': {'type': 'string'},
-                    'crt': {'type': 'string'},
-                    'name': {'type': 'string'},
-                    'filter': {'type': 'array',
-                               'items': {'type': 'object'}}},
-                   'required': ['url', 'crt', 'name', 'filter']}
+    CONF_SCHEMA = {
+        "properties": {
+            "url": {"type": "string"},
+            "crt": {"type": "string"},
+            "name": {"type": "string"},
+            "filter": {"type": "array", "items": {"type": "object"}},
+        },
+        "required": ["url", "crt", "name", "filter"],
+    }
 
     def process_conf(self) -> None:
         """Register plugin as bus client."""
 
     def process_conf(self) -> None:
         """Register plugin as bus client."""
-        self.graph_connection = GraphConnection(self.conf['url'],
-                                                self.conf['crt'])
+        self.graph_connection = GraphConnection(self.conf["url"], self.conf["crt"])
         self.messages: list[Message] = []
         self.messages: list[Message] = []
-        self.bus.register(self.name, 'Graph',
-                          [],
-                          [([MessageTemplate({'target': {'const': self.name},
-                                              'command': {'const': 'sync'}})],
-                            self.sync),
-                           (self.conf['filter'], self.receive)])
+        self.bus.register(
+            self.name,
+            "Graph",
+            [],
+            [
+                (
+                    [
+                        MessageTemplate(
+                            {
+                                "target": {"const": self.name},
+                                "command": {"const": "sync"},
+                            }
+                        )
+                    ],
+                    self.sync,
+                ),
+                (self.conf["filter"], self.receive),
+            ],
+        )
 
     async def send(self, messages: list[Message]) -> None:
         """Send a list of messages to configured graph."""
         async with self.graph_connection as gc:
 
     async def send(self, messages: list[Message]) -> None:
         """Send a list of messages to configured graph."""
         async with self.graph_connection as gc:
-            coroot_guid = await gc.call('attributsknoten',
-                                        ['coroot_name',
-                                         self.conf['name']])
+            coroot_guid = await gc.call(
+                "attributsknoten", ["coroot_name", self.conf["name"]]
+            )
             if coroot_guid:
             if coroot_guid:
-                comessage_guid = await gc.call('erzeuge', ['comessage'])
+                comessage_guid = await gc.call("erzeuge", ["comessage"])
                 if comessage_guid:
                 if comessage_guid:
-                    await gc.call('verknuepfe', [comessage_guid,
-                                                 coroot_guid])
-                    await gc.call('setze', [comessage_guid,
-                                            'comessage_json',
-                                            json.dumps(messages)])
-                    await gc.call('setze', [comessage_guid,
-                                            'comessage_ready',
-                                            True])
+                    await gc.call("verknuepfe", [comessage_guid, coroot_guid])
+                    await gc.call(
+                        "setze",
+                        [comessage_guid, "comessage_json", json.dumps(messages)],
+                    )
+                    await gc.call("setze", [comessage_guid, "comessage_ready", True])
                 else:
                     raise Exception("Could not create comessage instance")
             else:
                 else:
                     raise Exception("Could not create comessage instance")
             else:
-                raise Exception("Did not find coroot instance"
-                                f" '{self.conf['name']}'.")
+                raise Exception(f"Did not find coroot instance '{self.conf['name']}'.")
 
     async def sync(self, message: Message) -> None:
         """Sync cached messages to configured graph."""
 
     async def sync(self, message: Message) -> None:
         """Sync cached messages to configured graph."""
@@ -60,9 +72,11 @@ class Graph(BasePlugin):
                 await self.send(messages)
             except Exception as e:
                 self.messages.extend(messages)
                 await self.send(messages)
             except Exception as e:
                 self.messages.extend(messages)
-                print(f"Graph connection '{self.name}'"
-                      f" to {self.conf['url']}:"
-                      f" Exception in 'sync()': {e}")
+                print(
+                    f"Graph connection '{self.name}'"
+                    f" to {self.conf['url']}:"
+                    f" Exception in 'sync()': {e}"
+                )
 
     async def receive(self, message: Message) -> None:
         """Receive message through controlpi bus."""
 
     async def receive(self, message: Message) -> None:
         """Receive message through controlpi bus."""
@@ -71,9 +85,10 @@ class Graph(BasePlugin):
     async def run(self) -> None:
         """Get coroot instance for name and send connection opened event."""
         try:
     async def run(self) -> None:
         """Get coroot instance for name and send connection opened event."""
         try:
-            await self.send([Message(self.name,
-                                     {'event': 'connection opened'})])
+            await self.send([Message(self.name, {"event": "connection opened"})])
         except Exception as e:
         except Exception as e:
-            print(f"Graph connection '{self.name}'"
-                  f" to {self.conf['url']}:"
-                  f" Exception in 'run()': {e}")
+            print(
+                f"Graph connection '{self.name}'"
+                f" to {self.conf['url']}:"
+                f" Exception in 'run()': {e}"
+            )
index 86d707bc862e9c1a6074078657f7677a6143d56c..b76d07525117de932712e02e9b37499afc423357 100644 (file)
@@ -1,7 +1,8 @@
 """Provide an asynchronous context manager for graph connections."""
 """Provide an asynchronous context manager for graph connections."""
+
 import asyncio
 from dataclasses import dataclass
 import asyncio
 from dataclasses import dataclass
-import msgpack  # type: ignore
+import msgpack
 import os.path
 import ssl
 import struct
 import os.path
 import ssl
 import struct
@@ -30,7 +31,7 @@ class GraphConnection:
         """Initialise with graph URL and TLS certificate."""
         self.url = url
         parsed_url = urllib.parse.urlparse(url)
         """Initialise with graph URL and TLS certificate."""
         self.url = url
         parsed_url = urllib.parse.urlparse(url)
-        if parsed_url.scheme != 'tls':
+        if parsed_url.scheme != "tls":
             raise Exception("Only implemented scheme is 'tls'.")
         self.hostname = parsed_url.hostname
         self.port = parsed_url.port
             raise Exception("Only implemented scheme is 'tls'.")
         self.hostname = parsed_url.hostname
         self.port = parsed_url.port
@@ -42,19 +43,19 @@ class GraphConnection:
             self.connections[self.url] = GraphConnectionData(asyncio.Lock())
         self.connection = self.connections[self.url]
 
             self.connections[self.url] = GraphConnectionData(asyncio.Lock())
         self.connection = self.connections[self.url]
 
-    async def __aenter__(self) -> 'GraphConnection':
+    async def __aenter__(self) -> "GraphConnection":
         """Open connection if first context."""
         async with self.connection.lock:
             if self.connection.contexts == 0:
                 # Open connection:
         """Open connection if first context."""
         async with self.connection.lock:
             if self.connection.contexts == 0:
                 # Open connection:
-                (r, w) = await asyncio.open_connection(self.hostname,
-                                                       self.port,
-                                                       ssl=self.ssl)
+                (r, w) = await asyncio.open_connection(
+                    self.hostname, self.port, ssl=self.ssl
+                )
                 self.connection.opened += 1
                 # Read banner:
                 size_bytes = await r.readexactly(4)
                 self.connection.opened += 1
                 # Read banner:
                 size_bytes = await r.readexactly(4)
-                size_int = struct.unpack('<i', size_bytes)[0]
-                message = await r.readexactly(size_int)
+                size_int = struct.unpack("<i", size_bytes)[0]
+                _message = await r.readexactly(size_int)
                 # Set reader and writer in data:
                 self.connection.reader = r
                 self.connection.writer = w
                 # Set reader and writer in data:
                 self.connection.reader = r
                 self.connection.writer = w
@@ -88,38 +89,43 @@ class GraphConnection:
             if reader is not None and writer is not None:
                 self.connection.message_count += 1
                 # Build and send request:
             if reader is not None and writer is not None:
                 self.connection.message_count += 1
                 # Build and send request:
-                request = {'jsonrpc': '2.0', 'method': method,
-                           'params': params,
-                           'id': self.connection.message_count}
+                request = {
+                    "jsonrpc": "2.0",
+                    "method": method,
+                    "params": params,
+                    "id": self.connection.message_count,
+                }
                 message = msgpack.packb(request)
                 message = msgpack.packb(request)
-                size_bytes = struct.pack('<i', len(message))
+                size_bytes = struct.pack("<i", len(message))
                 writer.write(size_bytes)
                 writer.write(message)
                 await writer.drain()
                 # Receive and unpack response:
                 size_bytes = await reader.readexactly(4)
                 writer.write(size_bytes)
                 writer.write(message)
                 await writer.drain()
                 # Receive and unpack response:
                 size_bytes = await reader.readexactly(4)
-                size_int = struct.unpack('<i', size_bytes)[0]
+                size_int = struct.unpack("<i", size_bytes)[0]
                 message = await reader.readexactly(size_int)
                 response = msgpack.unpackb(message)
                 # Raise errors:
                 message = await reader.readexactly(size_int)
                 response = msgpack.unpackb(message)
                 # Raise errors:
-                if ('jsonrpc' not in response or
-                        response['jsonrpc'] != request['jsonrpc']):
-                    raise Exception("Not a JSON-RPC 2.0 response:"
-                                    f" '{response}'")
-                if 'error' in response:
-                    raise Exception("JSON-RPC remote error:"
-                                    f" {response['error']}")
-                if 'id' not in response:
+                if (
+                    "jsonrpc" not in response
+                    or response["jsonrpc"] != request["jsonrpc"]
+                ):
+                    raise Exception(f"Not a JSON-RPC 2.0 response: '{response}'")
+                if "error" in response:
+                    raise Exception(f"JSON-RPC remote error: {response['error']}")
+                if "id" not in response:
                     raise Exception("JSON-RPC id missing.")
                     raise Exception("JSON-RPC id missing.")
-                if response['id'] != request['id']:
+                if response["id"] != request["id"]:
                     raise Exception("JSON-RPC id invalid.")
                 # Return result:
                     raise Exception("JSON-RPC id invalid.")
                 # Return result:
-                return response['result']
+                return response["result"]
             else:
             else:
-                raise Exception("Reader or writer missing.\n"
-                                "Open contexts:"
-                                f" {self.connection.contexts}"
-                                " Connections opened since start: "
-                                f" {self.connection.opened}"
-                                " Connections closed since start: "
-                                f" {self.connection.closed}")
+                raise Exception(
+                    "Reader or writer missing.\n"
+                    "Open contexts:"
+                    f" {self.connection.contexts}"
+                    " Connections opened since start: "
+                    f" {self.connection.opened}"
+                    " Connections closed since start: "
+                    f" {self.connection.closed}"
+                )
index 872d0d34b2212106b34c811062e85e9d2c2db468..11816f7049d1632bbe45420bd16c7ee529cf8331 100644 (file)
--- a/setup.py
+++ b/setup.py
@@ -5,7 +5,7 @@ with open("README.md", "r") as readme_file:
 
 setuptools.setup(
     name="controlpi-graph",
 
 setuptools.setup(
     name="controlpi-graph",
-    version="0.2.0",
+    version="0.4.0",
     author="Graph-IT GmbH",
     author_email="info@graph-it.com",
     description="ControlPi Plugin for Graph Connections",
     author="Graph-IT GmbH",
     author_email="info@graph-it.com",
     description="ControlPi Plugin for Graph Connections",
index bf668a47601fec2161df3a554bcbc62cfd618642..e546386af03dba1983c6ae73c5d02d4148033a7b 100644 (file)
@@ -1,5 +1,4 @@
 import asyncio
 import asyncio
-import json
 from pprint import pprint
 
 from controlpi_plugins.graph_connection import GraphConnection
 from pprint import pprint
 
 from controlpi_plugins.graph_connection import GraphConnection