forked from Kazuhito00/Image-Processing-Node-Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnode_websocket.py
More file actions
681 lines (556 loc) · 28.6 KB
/
Copy pathnode_websocket.py
File metadata and controls
681 lines (556 loc) · 28.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import asyncio
import json
import time
from datetime import datetime, timezone
from typing import Optional, Dict, Any, List
import threading
import queue
import dearpygui.dearpygui as dpg
from node_editor.util import dpg_get_value, dpg_set_value
from node.node_abc import DpgNodeABC
from node.basenode import Node as BaseNode
# Abstract WebSocket Connection Handler
class WebSocketConnectionHandler:
"""Abstract base class for handling WebSocket connections with different protocols."""
def __init__(self, url: str, api_key: str = "", log_callback=None):
self.url = url
self.api_key = api_key
self.is_connected = False
self.message_queue = queue.Queue(maxsize=100)
self.log_callback = log_callback # Callback function for logging to UI
self.message_count = 0 # Track number of messages received
self.unparseable_count = 0 # Track unparseable messages
async def connect(self):
"""Connect to the WebSocket server. To be implemented by subclasses."""
raise NotImplementedError("Subclasses must implement connect()")
def get_subscribe_message(self) -> Dict[str, Any]:
"""Get the subscription message for the WebSocket. To be implemented by subclasses."""
raise NotImplementedError("Subclasses must implement get_subscribe_message()")
def parse_message(self, message: str) -> Optional[Dict[str, Any]]:
"""Parse incoming WebSocket message. To be implemented by subclasses."""
raise NotImplementedError("Subclasses must implement parse_message()")
async def handle_messages(self):
"""Handle incoming messages from WebSocket."""
raise NotImplementedError("Subclasses must implement handle_messages()")
# AIS Stream Handler Implementation
class AISStreamHandler(WebSocketConnectionHandler):
"""Handler for AIS (Automatic Identification System) stream connections.
This handler connects to AIS streaming services and filters boat data based on
bounding box coordinates.
Example usage:
handler = AISStreamHandler(
url="wss://stream.aisstream.io/v0/stream",
api_key="YOUR_API_KEY_HERE",
bounding_box=[[[-90, -180], [-90, 180], [90, 180], [90, -180], [-90, -180]]]
)
"""
def __init__(self, url: str, api_key: str, bounding_box: Optional[List] = None, log_callback=None):
super().__init__(url, api_key, log_callback)
self.bounding_box = bounding_box or self._get_default_bounding_box()
self.websocket = None
def _log(self, message: str):
"""Log a message to UI if callback is available."""
if self.log_callback:
self.log_callback(message)
else:
print(message)
def _get_default_bounding_box(self) -> List:
"""Return a default bounding box covering the entire world.
Bounding box format: [[longitude, latitude], ...]
Example: Mediterranean Sea region
"""
return [[[-5, 36], [36, 36], [36, 46], [-5, 46], [-5, 36]]]
def get_subscribe_message(self) -> Dict[str, Any]:
"""Get the AIS stream subscription message.
Returns:
Dictionary with APIKey and BoundingBoxes for subscription
Example:
{
"APIKey": "YOUR_API_KEY_HERE",
"BoundingBoxes": [[[-90, -180], [-90, 180], [90, 180], [90, -180], [-90, -180]]]
}
"""
return {
"APIKey": self.api_key,
"BoundingBoxes": self.bounding_box
}
def parse_message(self, message: str) -> Optional[Dict[str, Any]]:
"""Parse AIS stream message and extract boat information.
Args:
message: Raw JSON message from AIS stream
Returns:
Parsed boat data with relevant fields or None if parsing fails
"""
try:
data = json.loads(message)
# Extract relevant boat information
if "Message" in data and "PositionReport" in data["Message"]:
position = data["Message"]["PositionReport"]
metadata = data.get("MetaData", {})
boat_info = {
"mmsi": metadata.get("MMSI", "Unknown"),
"ship_name": metadata.get("ShipName", "Unknown"),
"latitude": position.get("Latitude", 0.0),
"longitude": position.get("Longitude", 0.0),
"speed": position.get("Sog", 0.0), # Speed over ground
"course": position.get("Cog", 0.0), # Course over ground
"heading": position.get("TrueHeading", 0),
"timestamp": metadata.get("time_utc", datetime.now(timezone.utc).isoformat()),
"ship_type": metadata.get("ShipType", "Unknown"),
"destination": metadata.get("Destination", "Unknown")
}
return boat_info
return None
except json.JSONDecodeError:
return None
except Exception as e:
print(f"Error parsing AIS message: {e}")
return None
async def connect(self):
"""Connect to AIS stream WebSocket server."""
try:
# Import websockets only when needed
import websockets
self._log("Connecting to AIS server...")
# Log URL without query parameters to avoid exposing sensitive info
url_parts = self.url.split('?')
safe_url = url_parts[0] # Just protocol, domain, and path
if len(safe_url) > 50:
safe_url = safe_url[:50] + "..."
self._log(f"URL: {safe_url}")
async with websockets.connect(self.url) as websocket:
self.websocket = websocket
self.is_connected = True
self._log("✓ Connected to server")
# Send subscription message
subscribe_message = self.get_subscribe_message()
self._log("Sending subscription request...")
await websocket.send(json.dumps(subscribe_message))
self._log("✓ Subscription sent")
# Handle incoming messages
self._log("Waiting for server response...")
await self.handle_messages()
except ImportError:
error_msg = "Error: websockets not installed"
self._log(error_msg)
print("Error: 'websockets' package is not installed. Please run: pip install websockets")
self.is_connected = False
except Exception as e:
error_msg = f"Connection error: {str(e)}"
self._log(error_msg)
print(f"Error connecting to AIS stream: {e}")
self.is_connected = False
async def handle_messages(self):
"""Handle incoming AIS messages."""
if not self.websocket:
self._log("Error: No websocket connection")
return
try:
async for message in self.websocket:
# Log first message received
if self.message_count == 0:
self._log("✓ Receiving data from server")
boat_data = self.parse_message(message)
if boat_data:
self.message_count += 1
# Add to queue if not full
if not self.message_queue.full():
self.message_queue.put(boat_data)
# Log periodically (every 10 messages)
if self.message_count % 10 == 0:
self._log(f"Received {self.message_count} messages")
else:
# Log when queue is full
if self.message_count % 50 == 0:
self._log(f"Queue full, dropping data (received {self.message_count})")
else:
# Track unparseable messages
self.unparseable_count += 1
# Log when messages can't be parsed (first time and every 20th)
if self.unparseable_count == 1:
self._log("Server sent data but format unrecognized")
elif self.unparseable_count % 20 == 0:
self._log(f"Still receiving unparseable data ({self.unparseable_count} total)")
except Exception as e:
error_msg = f"Error receiving messages: {str(e)}"
self._log(error_msg)
print(f"Error handling AIS messages: {e}")
self.is_connected = False
class FactoryNode:
node_label = 'Websocket'
node_tag = 'Websocket'
def __init__(self):
pass
def add_node(self, parent, node_id, pos=[0, 0], callback=None, opencv_setting_dict=None):
"""Adds a WebSocket node with AIS stream support.
This node supports connecting to WebSocket services like AIS streams.
Example configuration:
- URL: wss://stream.aisstream.io/v0/stream
- API Key: YOUR_API_KEY_HERE
- Bounding Box: [[[-90, -180], [-90, 180], [90, 180], [90, -180], [-90, -180]]]
"""
# Generate tags for Node and its attributes
node = WebsocketNode()
node.tag_node_name = f"{node_id}:{node.node_tag}"
tag_input_url = f"{node.tag_node_name}:InputURL"
tag_start_button = f"{node.tag_node_name}:StartButton"
# URL input field
node.tag_node_input_text_name = node.tag_node_name + ':' + node.TYPE_TEXT + ':Input01'
node.tag_node_input_text_value_name = node.tag_node_name + ':' + node.TYPE_TEXT + ':Input01Value'
# API_KEY input field
node.tag_node_input_apikey_name = node.tag_node_name + ':' + node.TYPE_TEXT + ':InputAPIKey'
node.tag_node_input_apikey_value_name = node.tag_node_name + ':' + node.TYPE_TEXT + ':InputAPIKeyValue'
# Bounding box input field (JSON format)
node.tag_node_input_bbox_name = node.tag_node_name + ':' + node.TYPE_TEXT + ':InputBBox'
node.tag_node_input_bbox_value_name = node.tag_node_name + ':' + node.TYPE_TEXT + ':InputBBoxValue'
# Status and logs
node.tag_node_status_name = node.tag_node_name + ':Status'
node.tag_node_status_value_name = node.tag_node_name + ':StatusValue'
node.tag_node_logs_name = node.tag_node_name + ':Logs'
node.tag_node_logs_value_name = node.tag_node_name + ':LogsValue'
# Use node.node_tag instead of self.node_tag
tag_node_name = str(node_id) + ':' + node.node_tag
tag_node_output01_name = tag_node_name + ':' + node.TYPE_INT + ':Output01'
tag_node_output01_value_name = tag_node_name + ':' + node.TYPE_INT + ':Output01Value'
node.tag_node_output_audio_name = node.tag_node_name + ':' + node.TYPE_AUDIO + ':OutputAudio'
node.tag_node_output_audio_value_name = node.tag_node_name + ':' + node.TYPE_AUDIO + ':OutputAudioValue'
node.tag_node_output_json_name = node.tag_node_name + ':' + node.TYPE_JSON + ':OutputJson'
node.tag_node_output_json_value_name = node.tag_node_name + ':' + node.TYPE_JSON + ':OutputJsonValue'
small_window_w = 280
# Create yellow theme for buttons
with dpg.theme() as yellow_button_theme:
with dpg.theme_component(dpg.mvButton):
dpg.add_theme_color(dpg.mvThemeCol_Button, (255, 255, 153, 255)) # Yellow background
dpg.add_theme_color(dpg.mvThemeCol_ButtonHovered, (255, 255, 128, 255)) # Light yellow on hover
dpg.add_theme_color(dpg.mvThemeCol_ButtonActive, (255, 255, 64, 255)) # Darker yellow on press
dpg.add_theme_color(dpg.mvThemeCol_Text, (0, 0, 0, 255)) # Black text for better readability
# Outputs audio, json, float, elapsed time as disabled yellow buttons
def add_yellow_disabled_button(label, tag):
btn = dpg.add_button(
label=label,
tag=tag,
enabled=False,
width=small_window_w
)
dpg.bind_item_theme(btn, yellow_button_theme)
return btn
# Create node in the GUI
with dpg.node(tag=node.tag_node_name, parent=parent, label=node.node_label, pos=pos):
# Input field for WebSocket URL
with dpg.node_attribute(tag=node.tag_node_input_text_name, attribute_type=dpg.mvNode_Attr_Static):
dpg.add_input_text(
tag=node.tag_node_input_text_value_name,
width=small_window_w,
hint="wss://stream.aisstream.io/v0/stream",
default_value="wss://stream.aisstream.io/v0/stream"
)
# Input field for API_KEY
with dpg.node_attribute(tag=node.tag_node_input_apikey_name, attribute_type=dpg.mvNode_Attr_Static):
dpg.add_input_text(
tag=node.tag_node_input_apikey_value_name,
width=small_window_w,
hint="YOUR_API_KEY_HERE",
password=True
)
# Input field for bounding box (JSON format)
with dpg.node_attribute(tag=node.tag_node_input_bbox_name, attribute_type=dpg.mvNode_Attr_Static):
dpg.add_input_text(
tag=node.tag_node_input_bbox_value_name,
width=small_window_w,
hint='[[[-5, 36], [36, 36], [36, 46], [-5, 46], [-5, 36]]]',
multiline=True,
height=60,
default_value='[[[-5, 36], [36, 36], [36, 46], [-5, 46], [-5, 36]]]'
)
# Start button
with dpg.node_attribute(attribute_type=dpg.mvNode_Attr_Static):
btn = dpg.add_button(
label="Start",
tag=tag_start_button,
callback=WebsocketNode.start_button_callback,
user_data=(node, node_id),
width=small_window_w
)
dpg.bind_item_theme(btn, yellow_button_theme)
# Status display
with dpg.node_attribute(attribute_type=dpg.mvNode_Attr_Static):
dpg.add_text(
tag=node.tag_node_status_value_name,
default_value='Not connected',
)
# Logs zone
with dpg.node_attribute(attribute_type=dpg.mvNode_Attr_Static):
dpg.add_input_text(
tag=node.tag_node_logs_value_name,
default_value='',
multiline=True,
readonly=True,
width=small_window_w,
height=80,
)
# Outputs
with dpg.node_attribute(tag=node.tag_node_output_audio_name, attribute_type=dpg.mvNode_Attr_Output):
add_yellow_disabled_button("Audio", node.tag_node_output_audio_value_name)
with dpg.node_attribute(tag=node.tag_node_output_json_name, attribute_type=dpg.mvNode_Attr_Output):
add_yellow_disabled_button("JSON (Boats)", node.tag_node_output_json_value_name)
return node
class WebsocketNode(BaseNode):
"""WebSocket node for processing WebSocket connections with AIS boat tracking support.
This node implements an abstraction layer for WebSocket connections with specific
support for AIS (Automatic Identification System) streams that provide boat tracking data.
Features:
- Abstract WebSocket connection handling
- AIS stream integration with bounding box filtering
- JSON output with boat information
- Real-time data streaming
Example Configuration:
- URL: wss://stream.aisstream.io/v0/stream
- API Key: YOUR_API_KEY_HERE
- Bounding Box: [[[-5, 36], [36, 36], [36, 46], [-5, 46], [-5, 36]]]
(This example covers the Mediterranean Sea region)
The node outputs JSON data containing boat information:
{
"boats": [
{
"mmsi": "123456789",
"ship_name": "Example Ship",
"latitude": 40.7128,
"longitude": -74.0060,
"speed": 12.5,
"course": 90.0,
"heading": 85,
"timestamp": "2024-01-01T12:00:00Z",
"ship_type": "Cargo",
"destination": "New York"
}
]
}
"""
_ver = '0.0.2'
# Configuration constants
MAX_BOATS_STORED = 100 # Maximum number of boat entries to keep in memory
THREAD_SHUTDOWN_TIMEOUT = 2.0 # Timeout in seconds for thread shutdown
MAX_ERROR_MESSAGE_LENGTH = 50 # Maximum length for error messages in logs
def __init__(self):
super().__init__() # Call parent constructor
self.node_label = 'Websocket'
self.node_tag = 'Websocket'
self.connection_handler = None
self.connection_thread = None
self.boats_data = []
self.logs = [] # Store log messages
@staticmethod
def start_button_callback(sender, app_data, user_data):
"""Callback when Start button is clicked.
Args:
sender: Button widget that triggered the callback
app_data: Application data (not used)
user_data: Tuple of (node_instance, node_id)
"""
node, node_id = user_data
# Get values from input fields
tag_node_name = str(node_id) + ':' + node.node_tag
url_value_tag = tag_node_name + ':' + node.TYPE_TEXT + ':Input01Value'
apikey_value_tag = tag_node_name + ':' + node.TYPE_TEXT + ':InputAPIKeyValue'
bbox_value_tag = tag_node_name + ':' + node.TYPE_TEXT + ':InputBBoxValue'
url = dpg_get_value(url_value_tag)
api_key = dpg_get_value(apikey_value_tag)
bbox_str = dpg_get_value(bbox_value_tag)
# Start connection
node.start_connection(node_id, url, api_key, bbox_str)
def update(self, node_id, connection_list, node_image_dict, node_result_dict, node_audio_dict):
"""Update method called by the processing graph.
Returns:
Dictionary with image, json, and audio outputs
"""
# Collect boat data from the queue
new_data_count = 0
if self.connection_handler and self.connection_handler.is_connected:
while not self.connection_handler.message_queue.empty():
try:
boat_data = self.connection_handler.message_queue.get_nowait()
self.boats_data.append(boat_data)
new_data_count += 1
# Keep only last MAX_BOATS_STORED boats to avoid memory issues
if len(self.boats_data) > self.MAX_BOATS_STORED:
self.boats_data = self.boats_data[-self.MAX_BOATS_STORED:]
except queue.Empty:
break
# Return JSON output with boats list
json_output = {
"boats": self.boats_data,
"count": len(self.boats_data),
"timestamp": datetime.now(timezone.utc).isoformat()
}
# Update status text with data count (periodically)
if hasattr(self, '_last_status_update'):
if time.time() - self._last_status_update > 2.0: # Update every 2 seconds
tag_node_name = str(node_id) + ':' + self.node_tag
tag_node_status_value_name = tag_node_name + ':StatusValue'
if self.connection_handler and self.connection_handler.is_connected:
status_msg = f"Connected: {len(self.boats_data)} boats"
if hasattr(self.connection_handler, 'message_count'):
status_msg += f" ({self.connection_handler.message_count} msgs)"
dpg_set_value(tag_node_status_value_name, status_msg)
self._last_status_update = time.time()
else:
self._last_status_update = time.time()
return {"image": None, "json": json_output, "audio": None}
def add_log(self, message):
"""Add a log message to the logs list."""
timestamp = datetime.now(timezone.utc).strftime("%H:%M:%S")
log_entry = f"[{timestamp}] {message}"
self.logs.append(log_entry)
# Keep only last 10 log entries
if len(self.logs) > 10:
self.logs = self.logs[-10:]
def get_logs_text(self):
"""Get logs as a single string for display."""
return "\n".join(self.logs)
def _truncate_error(self, error_msg: str) -> str:
"""Truncate error message and add ellipsis if needed.
Args:
error_msg: Error message to truncate
Returns:
Truncated error message with ellipsis if truncated
"""
if len(error_msg) > self.MAX_ERROR_MESSAGE_LENGTH:
return error_msg[:self.MAX_ERROR_MESSAGE_LENGTH] + '...'
return error_msg
def start_connection(self, node_id, url, api_key, bounding_box_str):
"""Start the WebSocket connection and update status.
Args:
node_id: The node ID
url: WebSocket URL
api_key: API key for authentication
bounding_box_str: Bounding box as JSON string
"""
tag_node_name = str(node_id) + ':' + self.node_tag
tag_node_status_value_name = tag_node_name + ':StatusValue'
tag_node_logs_value_name = tag_node_name + ':LogsValue'
self.add_log("Starting connection...")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
try:
# Parse bounding box
if bounding_box_str:
try:
bounding_box = json.loads(bounding_box_str)
self.add_log(f"Bounding box: {len(bounding_box[0])} points")
except json.JSONDecodeError as e:
self.add_log(f"Error: Invalid bounding box JSON - {str(e)[:40]}")
dpg_set_value(tag_node_status_value_name, "Fail")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
return
else:
bounding_box = None
self.add_log("Using default bounding box")
# Check if URL and API key are provided
if not url:
self.add_log("Error: No URL provided")
dpg_set_value(tag_node_status_value_name, "Fail")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
return
if not api_key:
self.add_log("Warning: No API key provided")
# Create log callback that updates the UI
def log_to_ui(message):
self.add_log(message)
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
# Create connection handler with log callback
self.connection_handler = AISStreamHandler(
url=url,
api_key=api_key,
bounding_box=bounding_box,
log_callback=log_to_ui
)
# Start connection in a new thread
def run_connection():
try:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.connection_handler.connect())
loop.close()
# Update UI with final status
if self.connection_handler.is_connected:
self.add_log("✓ Connection active")
dpg_set_value(tag_node_status_value_name, "Connected")
else:
self.add_log("✗ Connection failed")
dpg_set_value(tag_node_status_value_name, "Failed")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
except Exception as e:
self.add_log(f"Error: {self._truncate_error(str(e))}")
dpg_set_value(tag_node_status_value_name, "Error")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
self.connection_thread = threading.Thread(target=run_connection, daemon=True)
self.connection_thread.start()
# Set initial status
self.add_log("Connection initiated...")
dpg_set_value(tag_node_status_value_name, "Connecting...")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
except Exception as e:
self.add_log(f"Setup error: {self._truncate_error(str(e))}")
dpg_set_value(tag_node_status_value_name, "Fail")
dpg_set_value(tag_node_logs_value_name, self.get_logs_text())
def close(self, node_id):
"""Clean up when node is closed."""
if self.connection_handler:
self.connection_handler.is_connected = False
if self.connection_thread and self.connection_thread.is_alive():
# Wait for thread to finish with configured timeout
self.connection_thread.join(timeout=self.THREAD_SHUTDOWN_TIMEOUT)
def get_setting_dict(self, node_id):
"""Get node settings for saving."""
tag_node_name = str(node_id) + ':' + self.node_tag
output_value_tag = tag_node_name + ':' + self.TYPE_INT + ':Output01Value'
# Tags for the input fields
url_value_tag = tag_node_name + ':' + self.TYPE_TEXT + ':Input01Value'
apikey_value_tag = tag_node_name + ':' + self.TYPE_TEXT + ':InputAPIKeyValue'
bbox_value_tag = tag_node_name + ':' + self.TYPE_TEXT + ':InputBBoxValue'
output_value = round((dpg_get_value(output_value_tag)), 3)
url_value_raw = dpg_get_value(url_value_tag)
url_value = url_value_raw if url_value_raw else ""
apikey_value_raw = dpg_get_value(apikey_value_tag)
apikey_value = apikey_value_raw if apikey_value_raw else ""
bbox_value_raw = dpg_get_value(bbox_value_tag)
bbox_value = bbox_value_raw if bbox_value_raw else ""
pos = dpg.get_item_pos(tag_node_name)
setting_dict = {}
setting_dict['ver'] = self._ver
setting_dict['pos'] = pos
setting_dict[output_value_tag] = output_value
setting_dict[url_value_tag] = url_value
setting_dict[apikey_value_tag] = apikey_value
setting_dict[bbox_value_tag] = bbox_value
return setting_dict
def set_setting_dict(self, node_id, setting_dict):
"""Restore node settings from saved data."""
tag_node_name = str(node_id) + ':' + self.node_tag
output_value_tag = tag_node_name + ':' + self.TYPE_INT + ':Output01Value'
# Tags for the input fields
url_value_tag = tag_node_name + ':' + self.TYPE_TEXT + ':Input01Value'
apikey_value_tag = tag_node_name + ':' + self.TYPE_TEXT + ':InputAPIKeyValue'
bbox_value_tag = tag_node_name + ':' + self.TYPE_TEXT + ':InputBBoxValue'
output_value = float(setting_dict[output_value_tag])
dpg_set_value(output_value_tag, output_value)
# Set the input field values if they exist in the setting dict
if url_value_tag in setting_dict:
dpg_set_value(url_value_tag, setting_dict[url_value_tag])
if apikey_value_tag in setting_dict:
dpg_set_value(apikey_value_tag, setting_dict[apikey_value_tag])
if bbox_value_tag in setting_dict:
dpg_set_value(bbox_value_tag, setting_dict[bbox_value_tag])
# Test code to verify that the node displays correctly
if __name__ == "__main__":
dpg.create_context()
with dpg.window(label="Test WebSocket Node", width=800, height=600):
with dpg.node_editor(label="Node Editor"):
factory = FactoryNode()
factory.add_node(parent=dpg.last_item(), node_id=1, pos=[100, 100])
dpg.create_viewport(title='Test WebSocket Node', width=900, height=700)
dpg.setup_dearpygui()
dpg.show_viewport()
dpg.start_dearpygui()
dpg.destroy_context()