prototwin 0.1.15__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.
@@ -0,0 +1,17 @@
1
+ MIT License
2
+ Copyright (c) 2018 YOUR NAME
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+ The above copyright notice and this permission notice shall be included in all
10
+ copies or substantial portions of the Software.
11
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include requirements.txt
2
+ include client.py
3
+ include __init__.py
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.1
2
+ Name: prototwin
3
+ Version: 0.1.15
4
+ Summary: The official python client interface for ProtoTwin Connect.
5
+ Home-page: https://prototwin.com
6
+ Author: ProtoTwin
7
+ License: MIT
8
+ Keywords: Industrial Simulation,Physics,Machine Learning,Robotics
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE.txt
16
+ Requires-Dist: asyncio
17
+ Requires-Dist: websockets
18
+ Requires-Dist: prototwin_cmdbuff
19
+
20
+ # ProtoTwin Connect Client
21
+
22
+ This package provides a simple client that can be used to interface with ProtoTwin Connect.
23
+
24
+ ## Basic Example
25
+
26
+ ```
27
+ # STEP 1: Import the ProtoTwin client
28
+ import prototwin
29
+ import asyncio
30
+ import math
31
+
32
+ # STEP 2: Define your signal addresses (obtain these from your ProtoTwin model)
33
+ simulation_time_address = 0
34
+ motor_target_velocity_address = 3
35
+
36
+ async def main():
37
+ # STEP 3: Start ProtoTwin Connect
38
+ client = await prototwin.start()
39
+
40
+ # STEP 4: Create the simulation loop
41
+ while True:
42
+ t = client.get(simulation_time_address) # Read signal values
43
+ client.set(motor_target_velocity_address, math.sin(t)) # Write signal values
44
+ await client.step() # Step the simulation forward in time
45
+
46
+ asyncio.run(main()) # Run the simulation loop
47
+ ```
@@ -0,0 +1,28 @@
1
+ # ProtoTwin Connect Client
2
+
3
+ This package provides a simple client that can be used to interface with ProtoTwin Connect.
4
+
5
+ ## Basic Example
6
+
7
+ ```
8
+ # STEP 1: Import the ProtoTwin client
9
+ import prototwin
10
+ import asyncio
11
+ import math
12
+
13
+ # STEP 2: Define your signal addresses (obtain these from your ProtoTwin model)
14
+ simulation_time_address = 0
15
+ motor_target_velocity_address = 3
16
+
17
+ async def main():
18
+ # STEP 3: Start ProtoTwin Connect
19
+ client = await prototwin.start()
20
+
21
+ # STEP 4: Create the simulation loop
22
+ while True:
23
+ t = client.get(simulation_time_address) # Read signal values
24
+ client.set(motor_target_velocity_address, math.sin(t)) # Write signal values
25
+ await client.step() # Step the simulation forward in time
26
+
27
+ asyncio.run(main()) # Run the simulation loop
28
+ ```
@@ -0,0 +1 @@
1
+ from prototwin.client import Client, Pattern, start, attach
@@ -0,0 +1,261 @@
1
+ from typing import Self, Callable
2
+ from ctypes.wintypes import LARGE_INTEGER
3
+ from enum import IntEnum
4
+ import asyncio
5
+ import time
6
+ import ctypes
7
+ import struct
8
+ import prototwin_cmdbuff
9
+
10
+ from websockets.client import connect
11
+ from websockets.frames import OP_BINARY
12
+
13
+ # Maximum buffer size
14
+ _sz = 65536 * 8
15
+
16
+ # Native command buffer functions
17
+ _g = prototwin_cmdbuff.get
18
+ _s = prototwin_cmdbuff.set
19
+ _c = prototwin_cmdbuff.clear
20
+ _ws = prototwin_cmdbuff.write_size
21
+ _rs = prototwin_cmdbuff.read_size
22
+ _t = prototwin_cmdbuff.tick
23
+ _y = prototwin_cmdbuff.sync
24
+ _r = prototwin_cmdbuff.reset
25
+ _i = prototwin_cmdbuff.initialize
26
+ _l = prototwin_cmdbuff.load
27
+ _ce = prototwin_cmdbuff.create_environments
28
+ _re = prototwin_cmdbuff.reset_environment
29
+ _u = prototwin_cmdbuff.update
30
+
31
+ kernel32 = ctypes.windll.kernel32
32
+
33
+ def _sleep(seconds):
34
+ """
35
+ Precise sleep.
36
+
37
+ Args:
38
+ seconds (float): The number of seconds to sleep.
39
+ """
40
+ handle = kernel32.CreateWaitableTimerExW(None, None, 0x00000002, 0x1F0003)
41
+ kernel32.SetWaitableTimer(handle, ctypes.byref(LARGE_INTEGER(int(seconds * -10000000))), 0, None, None, 0)
42
+ kernel32.WaitForSingleObject(handle, 0xFFFFFFFF)
43
+ kernel32.CancelWaitableTimer(handle)
44
+
45
+ class Pattern(IntEnum):
46
+ NONE = 0
47
+ LINEAR_X = 1,
48
+ LINEAR_Z = 2,
49
+ GRID = 3
50
+
51
+ class Client:
52
+ def __init__(self, ws) -> None:
53
+ """
54
+ ProtoTwin Connect Python Client.
55
+
56
+ Args:
57
+ ws (WebSocketClientPrototcol): The websocket client
58
+ """
59
+ self._ws = ws
60
+ self._wb = bytearray(_sz)
61
+ prototwin_cmdbuff.provide(self._wb, _sz)
62
+
63
+ def count(self) -> int:
64
+ """
65
+ The number of signals most recently received from ProtoTwin Connect.
66
+
67
+ Returns:
68
+ int: The number of signals.
69
+ """
70
+ return (_rs() - 12) / 8
71
+
72
+ def get(self, address: int) -> bool|int|float:
73
+ """
74
+ Reads the value of a signal at the specified address.
75
+
76
+ Args:
77
+ address (int): The signal address.
78
+
79
+ Returns:
80
+ bool|int|float: The signal value.
81
+ """
82
+ return _g(address)
83
+
84
+ def set(self, address: int, value: bool|int|float) -> None:
85
+ """
86
+ Writes a value to a signal at the specified address.
87
+
88
+ Args:
89
+ address (int): The signal address.
90
+ value (bool | int | float): The value to write.
91
+ """
92
+ return _s(address, value)
93
+
94
+ async def load(self, path: str) -> None:
95
+ """
96
+ Loads a model.
97
+
98
+ Args:
99
+ path (str): The path to the model.
100
+ """
101
+ _l(path)
102
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
103
+ _c()
104
+ await self._ws.recv()
105
+
106
+ async def reset(self) -> None:
107
+ """
108
+ Resets the simulation.
109
+ """
110
+ _r()
111
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
112
+ _c()
113
+ await self._ws.recv()
114
+
115
+ async def initialize(self) -> None:
116
+ """
117
+ Manually initializes the simulation.
118
+ """
119
+ _i()
120
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
121
+ _c()
122
+ self._rb = await self._ws.recv()
123
+ _u(self._rb)
124
+
125
+ async def create_environments(self, entity_name: str, environment_count: int, *, pattern: Pattern = Pattern.NONE, spacing: float = 1) -> tuple[int, int]:
126
+ """
127
+ Creates multiple environments as duplicates of the entity with the specified name.
128
+
129
+ Args:
130
+ entity_name (str): The name of the entity to serve as the source for the environments.
131
+ environment_count (int): The number of environments to create.
132
+ pattern (Pattern, optional): The layout pattern that should be used when creating the environments. Defaults to Pattern.NONE.
133
+ spacing (float, optional): The pattern spacing between environments. Defaults to 0.
134
+
135
+ Returns:
136
+ tuple[int, int, int, int]: The sgnal offset and stride for the environments along with the first and last signal address for the source environment.
137
+ """
138
+ _ce(entity_name, environment_count, pattern, spacing)
139
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
140
+ _c()
141
+ data = await self._ws.recv()
142
+ offset = struct.unpack("I", data[12:16])[0]
143
+ stride = struct.unpack("I", data[16:20])[0]
144
+ first = struct.unpack("I", data[20:24])[0]
145
+ last = struct.unpack("I", data[24:28])[0]
146
+ return (offset, stride, first, last)
147
+
148
+ async def reset_environment(self, environment_index: int) -> None:
149
+ """
150
+ Resets a specific environment back to its initial state.
151
+
152
+ Args:
153
+ environment_index (int): The index for the environment to reset.
154
+ """
155
+ _re(environment_index)
156
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
157
+ _c()
158
+ self._rb = await self._ws.recv()
159
+ _u(self._rb)
160
+
161
+ async def sync(self) -> None:
162
+ """
163
+ Synchronizes signals without stepping the simulation.
164
+ """
165
+ _y()
166
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
167
+ _c()
168
+ self._rb = await self._ws.recv()
169
+ _u(self._rb)
170
+
171
+ async def step(self) -> None:
172
+ """
173
+ Steps the simulation forward in time by one time-step.
174
+ """
175
+ _t()
176
+ await self._ws.write_frame(True, OP_BINARY, memoryview(self._wb)[:_ws()])
177
+ _c()
178
+ self._rb = await self._ws.recv()
179
+ _u(self._rb)
180
+
181
+ async def start_step(self) -> None:
182
+ """
183
+ Starts the process of stepping the simulation forward in time.
184
+
185
+ This may be used in combination with :func:`prototwin.Client.step_completed`
186
+ to do some computation whilst the simulation is stepping.
187
+ """
188
+ _t()
189
+ await self._ws.write_frame(True, OP_BINARY, self._wb)
190
+ _c()
191
+
192
+ async def step_completed(self) -> None:
193
+ """
194
+ Waits for the step to complete.
195
+
196
+ Must only be called after :func:`prototwin.Client.start_step`
197
+ """
198
+ self._rb = await self._ws.recv()
199
+ _u(self._rb)
200
+
201
+ async def run(self, cb: Callable[[Self, float, float], bool|None]) -> None:
202
+ """
203
+ Runs the simulation a real-time speed.
204
+
205
+ Args:
206
+ cb (Callable[[Self, float, float], bool | None]): The callback function, executed every time-step.
207
+ """
208
+ start = time.perf_counter()
209
+ t = 0
210
+ dt = 0.01
211
+ while True:
212
+ await self.step()
213
+ if cb(self, dt, t) == False:
214
+ return
215
+ t += dt
216
+ st = t - (time.perf_counter() - start)
217
+ if st > 0:
218
+ _sleep(st)
219
+
220
+ async def start(location = "ProtoTwinConnect", *, port: int = 8084, dev: bool = False, tools: bool = False) -> Client|None:
221
+ """
222
+ Starts an instance of ProtoTwin Connect.
223
+
224
+ Args:
225
+ location (str, optional): The path to the ProtoTwin Connect executable. Defaults to "ProtoTwinConnect".
226
+ dev (bool, optional): Whether to use the development environment. Defaults to False.
227
+
228
+ Returns:
229
+ Client|None: The created client, connected to the ProtoTwin Connect instance.
230
+ """
231
+ args = ["-runner"]
232
+ if (dev):
233
+ args.append("-dev")
234
+ if (tools):
235
+ args.append("-tools")
236
+ if (port != 8084):
237
+ args.append("-port=" + str(port))
238
+ await asyncio.create_subprocess_exec(location, *args)
239
+ await asyncio.sleep(2) # Allow a small amount of time to settle
240
+ try:
241
+ ws = await connect("ws://localhost:" + str(port), compression=None, user_agent_header="Python")
242
+ await ws.recv() # Wait for ready signal
243
+ client = Client(ws)
244
+ return client
245
+ except:
246
+ return None
247
+
248
+ async def attach(*, port: int = 8084) -> Client|None:
249
+ """
250
+ Creates a client attached to a currently running instance of ProtoTwin Connect.
251
+
252
+ Returns:
253
+ Client|None: The created client.
254
+ """
255
+ 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
@@ -0,0 +1,47 @@
1
+ Metadata-Version: 2.1
2
+ Name: prototwin
3
+ Version: 0.1.15
4
+ Summary: The official python client interface for ProtoTwin Connect.
5
+ Home-page: https://prototwin.com
6
+ Author: ProtoTwin
7
+ License: MIT
8
+ Keywords: Industrial Simulation,Physics,Machine Learning,Robotics
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Programming Language :: Python :: 3
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE.txt
16
+ Requires-Dist: asyncio
17
+ Requires-Dist: websockets
18
+ Requires-Dist: prototwin_cmdbuff
19
+
20
+ # ProtoTwin Connect Client
21
+
22
+ This package provides a simple client that can be used to interface with ProtoTwin Connect.
23
+
24
+ ## Basic Example
25
+
26
+ ```
27
+ # STEP 1: Import the ProtoTwin client
28
+ import prototwin
29
+ import asyncio
30
+ import math
31
+
32
+ # STEP 2: Define your signal addresses (obtain these from your ProtoTwin model)
33
+ simulation_time_address = 0
34
+ motor_target_velocity_address = 3
35
+
36
+ async def main():
37
+ # STEP 3: Start ProtoTwin Connect
38
+ client = await prototwin.start()
39
+
40
+ # STEP 4: Create the simulation loop
41
+ while True:
42
+ t = client.get(simulation_time_address) # Read signal values
43
+ client.set(motor_target_velocity_address, math.sin(t)) # Write signal values
44
+ await client.step() # Step the simulation forward in time
45
+
46
+ asyncio.run(main()) # Run the simulation loop
47
+ ```
@@ -0,0 +1,13 @@
1
+ LICENSE.txt
2
+ MANIFEST.in
3
+ README.md
4
+ requirements.txt
5
+ setup.cfg
6
+ setup.py
7
+ prototwin/__init__.py
8
+ prototwin/client.py
9
+ prototwin.egg-info/PKG-INFO
10
+ prototwin.egg-info/SOURCES.txt
11
+ prototwin.egg-info/dependency_links.txt
12
+ prototwin.egg-info/requires.txt
13
+ prototwin.egg-info/top_level.txt
@@ -0,0 +1,3 @@
1
+ asyncio
2
+ websockets
3
+ prototwin_cmdbuff
@@ -0,0 +1 @@
1
+ prototwin
@@ -0,0 +1,3 @@
1
+ asyncio
2
+ websockets
3
+ prototwin_cmdbuff
@@ -0,0 +1,9 @@
1
+ [metadata]
2
+ description_file = README.md
3
+ long_description_content_type = text/markdown
4
+ home_page = https://prototwin.com
5
+
6
+ [egg_info]
7
+ tag_build =
8
+ tag_date = 0
9
+
@@ -0,0 +1,28 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r") as fh:
4
+ long_description = fh.read()
5
+
6
+ with open("requirements.txt") as f:
7
+ required = f.read().splitlines()
8
+
9
+ setup(
10
+ name = "prototwin",
11
+ packages = find_packages(include=["prototwin"]),
12
+ version = "0.1.15",
13
+ license = "MIT",
14
+ description = "The official python client interface for ProtoTwin Connect.",
15
+ long_description = long_description,
16
+ long_description_content_type = "text/markdown",
17
+ author = "ProtoTwin",
18
+ url = "https://prototwin.com",
19
+ keywords = ["Industrial Simulation", "Physics", "Machine Learning", "Robotics"],
20
+ install_requires = required,
21
+ classifiers = [
22
+ "Development Status :: 4 - Beta",
23
+ "Intended Audience :: Developers",
24
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
25
+ "License :: OSI Approved :: MIT License",
26
+ "Programming Language :: Python :: 3"
27
+ ]
28
+ )