0
# Communication and Networking
1
2
WebSocket-based communication functions that enable the Python library to connect to and interact with the VS Code extension viewer. These functions handle real-time data transfer, command execution, and bidirectional messaging between the Python environment and the browser-based 3D viewer.
3
4
## Capabilities
5
6
### Port Management
7
8
Functions for configuring and querying the communication port used for WebSocket connections.
9
10
```python { .api }
11
def set_port(port):
12
"""
13
Set the port number for viewer communication.
14
15
Parameters:
16
port (int): Port number for WebSocket communication.
17
Must match the port used by the VS Code extension viewer.
18
Typically in range 3939-49152.
19
20
Note:
21
The VS Code extension automatically tries ports starting from 3939
22
if the default port is unavailable. Use this function to specify
23
a different port or match the extension's selected port.
24
"""
25
26
def get_port():
27
"""
28
Get the currently configured communication port.
29
30
Returns:
31
int: Current port number for WebSocket communication (default: 3939)
32
"""
33
```
34
35
**Usage Examples:**
36
37
```python
38
from ocp_vscode import set_port, get_port, show
39
40
# Check current port
41
current_port = get_port()
42
print(f"Using port: {current_port}")
43
44
# Set custom port (must match VS Code extension)
45
set_port(3940)
46
47
# Display objects using the custom port
48
show(objects)
49
50
# Port is remembered for subsequent calls
51
show(more_objects) # Uses port 3940
52
```
53
54
### Data Communication
55
56
Functions for sending display data and objects to the viewer.
57
58
```python { .api }
59
def send_data(data, port=None, timeit=False):
60
"""
61
Send display data to the viewer via WebSocket.
62
63
Parameters:
64
data (dict): Data dictionary containing tessellated CAD objects,
65
configuration, and metadata. Typically generated by
66
internal tessellation functions.
67
68
port (int, optional): Override port for this transmission.
69
Uses get_port() if None.
70
71
timeit (bool): Enable timing measurement for transmission (default: False)
72
73
Returns:
74
Any: Response from viewer, or None if connection failed
75
76
Note:
77
This is typically called internally by show() functions.
78
Direct use is for advanced scenarios or custom data formats.
79
"""
80
```
81
82
**Usage Examples:**
83
84
```python
85
from ocp_vscode import send_data
86
import json
87
88
# Custom data format (advanced usage)
89
custom_data = {
90
"type": "data",
91
"config": {"axes": True, "transparent": True},
92
"data": tessellated_geometry,
93
"count": 5
94
}
95
96
# Send to viewer
97
result = send_data(custom_data, timeit=True)
98
99
# Check if successful
100
if result is not None:
101
print("Data sent successfully")
102
else:
103
print("Failed to send data - is viewer running?")
104
```
105
106
### Command Communication
107
108
Functions for sending commands and queries to the viewer.
109
110
```python { .api }
111
def send_command(data, port=None, timeit=False):
112
"""
113
Send command to viewer and receive response.
114
115
Parameters:
116
data (str or dict): Command name or command data to send.
117
Common commands: "status", "config"
118
119
port (int, optional): Override port for this transmission.
120
Uses get_port() if None.
121
122
timeit (bool): Enable timing measurement for command (default: False)
123
124
Returns:
125
dict: Response data from viewer
126
None: If connection failed or command invalid
127
128
Raises:
129
Exception: If communication error occurs
130
"""
131
```
132
133
**Usage Examples:**
134
135
```python
136
from ocp_vscode import send_command
137
138
# Query viewer status
139
status_response = send_command("status")
140
if status_response:
141
print(f"Viewer status: {status_response}")
142
last_pick = status_response.get("lastPick")
143
if last_pick:
144
print(f"Last picked object: {last_pick['name']}")
145
146
# Query viewer configuration
147
config_response = send_command("config")
148
if config_response:
149
print(f"Tree width: {config_response['tree_width']}")
150
print(f"Glass mode: {config_response['glass']}")
151
152
# Send custom command
153
custom_response = send_command({
154
"action": "highlight",
155
"object_id": "part_001"
156
})
157
```
158
159
### Listener System
160
161
Functions for receiving real-time updates and events from the viewer.
162
163
```python { .api }
164
def listener(callback):
165
"""
166
Create a listener function for receiving viewer updates.
167
168
Parameters:
169
callback (function): Function to call when updates are received.
170
Signature: callback(changes, message_type)
171
- changes (dict): Changed configuration values
172
- message_type (MessageType): Type of message received
173
174
Returns:
175
function: Listener function that can be run in a separate thread
176
or event loop to monitor viewer updates
177
178
Note:
179
The listener maintains a WebSocket connection to receive real-time
180
updates about configuration changes, user interactions, and viewer state.
181
"""
182
183
class MessageType(IntEnum):
184
"""
185
Enumeration of WebSocket message types for communication protocol.
186
"""
187
data = 1 # Display data messages (CAD objects, tessellation)
188
command = 2 # Command messages (status queries, config requests)
189
updates = 3 # Update messages (configuration changes, user interactions)
190
listen = 4 # Listener registration messages
191
```
192
193
**Usage Examples:**
194
195
```python
196
from ocp_vscode import listener, MessageType
197
import threading
198
199
# Define callback for viewer updates
200
def on_viewer_update(changes, msg_type):
201
if msg_type == MessageType.updates:
202
print(f"Viewer configuration changed: {changes}")
203
204
# React to specific changes
205
if 'transparent' in changes:
206
print(f"Transparency changed to: {changes['transparent']}")
207
208
if 'lastPick' in changes:
209
picked = changes['lastPick']
210
print(f"User picked object: {picked.get('name')}")
211
212
# Create and start listener
213
listen_func = listener(on_viewer_update)
214
listener_thread = threading.Thread(target=listen_func, daemon=True)
215
listener_thread.start()
216
217
# Continue with main program
218
# Listener will receive updates in background
219
show(objects)
220
221
# Listener automatically receives updates when user interacts with viewer
222
```
223
224
### Connection Management and Error Handling
225
226
The communication system handles connection failures gracefully and provides debugging information.
227
228
```python
229
from ocp_vscode import send_data, send_command, set_port
230
import time
231
232
# Connection retry logic
233
def robust_send(data, max_retries=3):
234
"""Example of robust communication with retry logic"""
235
236
for attempt in range(max_retries):
237
try:
238
result = send_data(data)
239
if result is not None:
240
return result
241
242
# Try next port if connection failed
243
current_port = get_port()
244
set_port(current_port + 1)
245
print(f"Retrying with port {get_port()}")
246
247
except Exception as e:
248
print(f"Attempt {attempt + 1} failed: {e}")
249
time.sleep(1)
250
251
print("Failed to establish communication after all retries")
252
return None
253
254
# Usage
255
result = robust_send(display_data)
256
```
257
258
### WebSocket Protocol Details
259
260
The communication uses a custom WebSocket protocol with message prefixes:
261
262
```python
263
# Message format examples:
264
265
# Data message (CAD objects, configuration)
266
"D:" + json_data # Prefix 'D:' indicates data message
267
268
# Command message (queries, requests)
269
"C:" + json_data # Prefix 'C:' indicates command message
270
271
# Listener registration
272
"L:register" # Special registration message for updates
273
274
# Response format (commands only)
275
{
276
"status": "success" | "error",
277
"data": response_data,
278
"message": "description"
279
}
280
```
281
282
### Performance Optimization
283
284
Communication functions support timing measurements for performance analysis:
285
286
```python
287
from ocp_vscode import send_data, show
288
289
# Enable timing for all communication
290
show(large_assembly, timeit=True)
291
292
# This will output timing information:
293
# - JSON serialization time
294
# - WebSocket transmission time
295
# - Overall communication time
296
297
# For custom data sending
298
send_data(custom_data, timeit=True)
299
```
300
301
### Network Configuration
302
303
The system uses localhost WebSocket connections by default:
304
305
```python
306
# Default configuration (internal constants)
307
CMD_URL = "ws://127.0.0.1" # Localhost WebSocket URL
308
CMD_PORT = 3939 # Default starting port
309
310
# Connection string format: "ws://127.0.0.1:3939"
311
```
312
313
**Security Notes:**
314
- Connections are limited to localhost (127.0.0.1) for security
315
- No external network access or remote connections
316
- Communication is between local Python process and local VS Code extension only
317
- WebSocket protocol provides message framing and error detection