prototwin 0.2.2__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prototwin
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: The official python client interface for ProtoTwin Connect.
5
5
  Home-page: https://prototwin.com
6
6
  Author: ProtoTwin
@@ -0,0 +1 @@
1
+ from prototwin.client import Client, ConnectError, Pattern, start, attach
@@ -2,6 +2,8 @@ from typing import Self, Callable
2
2
  from ctypes.wintypes import LARGE_INTEGER
3
3
  from enum import IntEnum
4
4
  import asyncio
5
+ import json
6
+ import socket
5
7
  import time
6
8
  import platform
7
9
  import ctypes
@@ -9,6 +11,7 @@ import struct
9
11
  import prototwin_cmdbuff
10
12
 
11
13
  from websockets.client import connect
14
+ from websockets.exceptions import ConnectionClosed, InvalidHandshake
12
15
  from websockets.frames import OP_BINARY
13
16
 
14
17
  # Maximum buffer size
@@ -167,6 +170,10 @@ class Client:
167
170
  Args:
168
171
  environment_index (int): The index for the environment to reset.
169
172
  """
173
+ if _ws() > 12:
174
+ # Signal writes are queued (they are normally sent with the next step). The reset command replaces the
175
+ # command buffer, which would silently drop them, so send them first.
176
+ await self.sync()
170
177
  _re(environment_index)
171
178
  await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
172
179
  _c()
@@ -232,17 +239,30 @@ class Client:
232
239
  if st > 0:
233
240
  _sleep(st)
234
241
 
235
- async def start(location = "ProtoTwinConnect", *, port: int = 8084, dev: bool = False, tools: bool = False) -> Client|None:
242
+ class ConnectError(RuntimeError):
236
243
  """
237
- Starts an instance of ProtoTwin Connect.
244
+ ProtoTwin Connect could not be started or connected to. The message says why.
245
+ """
246
+
247
+
248
+ async def start(location = "ProtoTwinConnect", *, port: int = 8084, dev: bool = False, tools: bool = False, timeout: float = 60.0) -> Client:
249
+ """
250
+ Starts an instance of ProtoTwin Connect and connects to it.
238
251
 
239
252
  Args:
240
253
  location (str, optional): The path to the ProtoTwin Connect executable. Defaults to "ProtoTwinConnect".
254
+ port (int, optional): The port for the instance. Each running instance needs its own. Defaults to 8084.
241
255
  dev (bool, optional): Whether to use the development environment. Defaults to False.
256
+ timeout (float, optional): How long to wait for ProtoTwin Connect to become ready, in seconds. Defaults to 60.
242
257
 
243
258
  Returns:
244
- Client|None: The created client, connected to the ProtoTwin Connect instance.
259
+ Client: The created client, connected to the ProtoTwin Connect instance.
260
+
261
+ Raises:
262
+ ConnectError: If ProtoTwin Connect could not be started, exited, or did not become ready in time.
245
263
  """
264
+ if _port_in_use(port):
265
+ raise ConnectError(f"Port {port} is already in use, probably by another instance of ProtoTwin Connect. Close it, connect to it with attach(), or start this instance on a different port.")
246
266
  args = ["-runner"]
247
267
  if (dev):
248
268
  args.append("-dev")
@@ -250,27 +270,101 @@ async def start(location = "ProtoTwinConnect", *, port: int = 8084, dev: bool =
250
270
  args.append("-tools")
251
271
  if (port != 8084):
252
272
  args.append("-port=" + str(port))
253
- await asyncio.create_subprocess_exec(location, *args)
254
- await asyncio.sleep(2) # Allow a small amount of time to settle
255
273
  try:
256
- ws = await connect("ws://localhost:" + str(port), compression=None, user_agent_header="Python")
257
- await ws.recv() # Wait for ready signal
258
- client = Client(ws)
259
- return client
260
- except:
261
- return None
262
-
263
- async def attach(*, port: int = 8084) -> Client|None:
274
+ process = await asyncio.create_subprocess_exec(location, *args)
275
+ except FileNotFoundError:
276
+ raise ConnectError(f"ProtoTwin Connect was not found at {location!r}. Pass its path as the location argument.") from None
277
+ try:
278
+ return await _connect(port, timeout, process)
279
+ except BaseException:
280
+ # Don't leave behind an instance that holds the port.
281
+ if process.returncode is None:
282
+ process.kill()
283
+ raise
284
+
285
+
286
+ async def attach(*, port: int = 8084, timeout: float = 60.0) -> Client:
264
287
  """
265
288
  Creates a client attached to a currently running instance of ProtoTwin Connect.
266
289
 
290
+ Args:
291
+ port (int, optional): The instance's port. Defaults to 8084.
292
+ timeout (float, optional): How long to wait for the instance to become ready, in seconds. Defaults to 60.
293
+
267
294
  Returns:
268
- Client|None: The created client.
295
+ Client: The created client.
296
+
297
+ Raises:
298
+ ConnectError: If no instance is running on the port, or it did not become ready in time.
299
+ """
300
+ return await _connect(port, timeout, None)
301
+
302
+
303
+ async def _connect(port: int, timeout: float, process: asyncio.subprocess.Process|None) -> Client:
304
+ """
305
+ Connects to the instance on the port and waits for its ready signal, failing as soon as the instance exits or
306
+ reports that it can't become ready.
307
+ """
308
+ loop = asyncio.get_running_loop()
309
+ deadline = loop.time() + timeout
310
+ url = "ws://127.0.0.1:" + str(port)
311
+
312
+ # A starting instance takes a moment to listen on its port.
313
+ while True:
314
+ if process is not None and process.returncode is not None:
315
+ raise ConnectError(f"ProtoTwin Connect exited while starting (exit code {process.returncode}).")
316
+ try:
317
+ ws = await asyncio.wait_for(connect(url, compression=None, user_agent_header="Python"), max(0.1, deadline - loop.time()))
318
+ break
319
+ except (OSError, asyncio.TimeoutError, InvalidHandshake):
320
+ if process is None:
321
+ raise ConnectError(f"No instance of ProtoTwin Connect is running on port {port}.") from None
322
+ if loop.time() >= deadline:
323
+ raise ConnectError(f"ProtoTwin Connect did not start listening on port {port} within {timeout:.0f} seconds.") from None
324
+ await asyncio.sleep(0.25)
325
+
326
+ # The ready signal arrives once the model view has connected. While waiting, ask the instance whether it knows of a
327
+ # reason why that will never happen (for example, it is waiting for a sign-in), so as not to wait for nothing.
328
+ try:
329
+ while True:
330
+ remaining = deadline - loop.time()
331
+ if remaining <= 0:
332
+ problem = await _startup_problem(port)
333
+ raise ConnectError(f"ProtoTwin Connect did not become ready within {timeout:.0f} seconds" + (f": {problem}" if problem else "."))
334
+ try:
335
+ await asyncio.wait_for(ws.recv(), min(2.0, remaining))
336
+ return Client(ws)
337
+ except asyncio.TimeoutError:
338
+ pass
339
+ if process is not None and process.returncode is not None:
340
+ raise ConnectError(f"ProtoTwin Connect exited while starting (exit code {process.returncode}).")
341
+ problem = await _startup_problem(port)
342
+ if problem is not None:
343
+ raise ConnectError(f"ProtoTwin Connect can't become ready: {problem}")
344
+ except BaseException:
345
+ await ws.close()
346
+ raise
347
+
348
+
349
+ async def _startup_problem(port: int) -> str|None:
350
+ """
351
+ Asks the instance why its model view hasn't connected. Returns None when it doesn't know of a problem.
269
352
  """
270
353
  try:
271
- ws = await connect("ws://localhost:" + str(port), compression=None, user_agent_header="Python")
272
- await ws.recv() # Wait for ready signal
273
- client = Client(ws)
274
- return client
275
- except:
276
- return None
354
+ async with connect("ws://127.0.0.1:" + str(port), compression=None, user_agent_header="Python", open_timeout=5) as ws:
355
+ await ws.send(json.dumps({"id": 1, "type": "Status"}))
356
+ while True:
357
+ reply = await asyncio.wait_for(ws.recv(), 5.0)
358
+ if isinstance(reply, str):
359
+ break
360
+ error = json.loads(reply).get("data", {}).get("data", {}).get("error", "")
361
+ except (OSError, asyncio.TimeoutError, InvalidHandshake, ConnectionClosed, ValueError, AttributeError):
362
+ return None
363
+ prefix = "The model view can't connect: "
364
+ return error[len(prefix):] if error.startswith(prefix) else None
365
+
366
+
367
+ def _port_in_use(port: int) -> bool:
368
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
369
+ probe.settimeout(1.0)
370
+ return probe.connect_ex(("127.0.0.1", port)) == 0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: prototwin
3
- Version: 0.2.2
3
+ Version: 0.3.0
4
4
  Summary: The official python client interface for ProtoTwin Connect.
5
5
  Home-page: https://prototwin.com
6
6
  Author: ProtoTwin
@@ -9,7 +9,7 @@ with open("requirements.txt") as f:
9
9
  setup(
10
10
  name = "prototwin",
11
11
  packages = find_packages(include=["prototwin"]),
12
- version = "0.2.2",
12
+ version = "0.3.0",
13
13
  license = "MIT",
14
14
  description = "The official python client interface for ProtoTwin Connect.",
15
15
  long_description = long_description,
@@ -1 +0,0 @@
1
- from prototwin.client import Client, Pattern, start, attach
File without changes
File without changes
File without changes
File without changes
File without changes