|
| 1 | +#! python3 |
| 2 | + |
| 3 | +from ghpythonlib.componentbase import executingcomponent as component |
| 4 | +import socket |
| 5 | +import threading |
| 6 | +import json |
| 7 | +import time |
| 8 | +import scriptcontext as sc |
| 9 | +import Rhino.Geometry as rg |
| 10 | +import System.Drawing as sd |
| 11 | +from diffCheck import df_gh_canvas_utils |
| 12 | +from Grasshopper.Kernel import GH_RuntimeMessageLevel as RML |
| 13 | + |
| 14 | +class DFTCPListener(component): |
| 15 | + def __init__(self): |
| 16 | + try: |
| 17 | + ghenv.Component.ExpireSolution(True) # noqa: F821 |
| 18 | + ghenv.Component.Attributes.PerformLayout() # noqa: F821 |
| 19 | + except NameError: |
| 20 | + pass |
| 21 | + |
| 22 | + for idx, label in enumerate(("Start", "Stop", "Load")): |
| 23 | + df_gh_canvas_utils.add_button( |
| 24 | + ghenv.Component, label, idx, x_offset=60) # noqa: F821 |
| 25 | + df_gh_canvas_utils.add_panel(ghenv.Component, "Host", "127.0.0.1", 3, 60, 20) # noqa: F821 |
| 26 | + df_gh_canvas_utils.add_panel(ghenv.Component, "Port", "5000", 4, 60, 20) # noqa: F821 |
| 27 | + |
| 28 | + def RunScript(self, |
| 29 | + i_start: bool, |
| 30 | + i_stop: bool, |
| 31 | + i_load: bool, |
| 32 | + i_host: str, |
| 33 | + i_port: int): |
| 34 | + |
| 35 | + prefix = 'tcp' |
| 36 | + |
| 37 | + # Sticky initialization |
| 38 | + sc.sticky.setdefault(f'{prefix}_server_sock', None) |
| 39 | + sc.sticky.setdefault(f'{prefix}_server_started', False) |
| 40 | + sc.sticky.setdefault(f'{prefix}_cloud_buffer_raw', []) |
| 41 | + sc.sticky.setdefault(f'{prefix}_latest_cloud', None) |
| 42 | + sc.sticky.setdefault(f'{prefix}_status_message', 'Waiting..') |
| 43 | + sc.sticky.setdefault(f'{prefix}_prev_start', False) |
| 44 | + sc.sticky.setdefault(f'{prefix}_prev_stop', False) |
| 45 | + sc.sticky.setdefault(f'{prefix}_prev_load', False) |
| 46 | + |
| 47 | + # Client handler |
| 48 | + def handle_client(conn: socket.socket) -> None: |
| 49 | + """ |
| 50 | + Reads the incoming bytes from a single TCP client socket and stores valid data in a shared buffer. |
| 51 | +
|
| 52 | + :param conn: A socket object returned by `accept()` representing a live client connection. |
| 53 | + The client is expected to send newline-delimited JSON-encoded data, where each |
| 54 | + message is a list of 6D values: [x, y, z, r, g, b]. |
| 55 | +
|
| 56 | + :returns: None |
| 57 | + """ |
| 58 | + buf = b'' |
| 59 | + with conn: |
| 60 | + while sc.sticky.get(f'{prefix}_server_started', False): |
| 61 | + try: |
| 62 | + chunk = conn.recv(4096) |
| 63 | + if not chunk: |
| 64 | + break |
| 65 | + buf += chunk |
| 66 | + while b'\n' in buf: |
| 67 | + line, buf = buf.split(b'\n', 1) |
| 68 | + try: |
| 69 | + raw = json.loads(line.decode()) |
| 70 | + except Exception: |
| 71 | + continue |
| 72 | + if isinstance(raw, list) and all(isinstance(pt, list) and len(pt) == 6 for pt in raw): |
| 73 | + sc.sticky[f'{prefix}_cloud_buffer_raw'] = raw |
| 74 | + except Exception: |
| 75 | + break |
| 76 | + time.sleep(0.05) # sleep briefly to prevent CPU spin |
| 77 | + |
| 78 | + # thread to accept incoming connections |
| 79 | + def server_loop(sock: socket.socket) -> None: |
| 80 | + """ |
| 81 | + Accepts a single client connection and starts a background thread to handle it. |
| 82 | +
|
| 83 | + :param sock: A bound and listening TCP socket created by start_server(). |
| 84 | + This socket will accept one incoming connection, then delegate it to handle_client(). |
| 85 | +
|
| 86 | + :returns: None. This runs as a background thread and blocks on accept(). |
| 87 | + """ |
| 88 | + try: |
| 89 | + conn, _ = sock.accept() |
| 90 | + handle_client(conn) |
| 91 | + except Exception: |
| 92 | + pass |
| 93 | + |
| 94 | + # Start TCP server |
| 95 | + def start_server() -> None: |
| 96 | + """ |
| 97 | + creates and binds a TCP socket on the given host/port, marks the server as started and then starts the accept_loop in a background thread |
| 98 | +
|
| 99 | + :returns: None. |
| 100 | + """ |
| 101 | + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) |
| 102 | + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) |
| 103 | + sock.bind((i_host, i_port)) |
| 104 | + sock.listen(1) |
| 105 | + sc.sticky[f'{prefix}_server_sock'] = sock |
| 106 | + sc.sticky[f'{prefix}_server_started'] = True |
| 107 | + sc.sticky[f'{prefix}_status_message'] = f'Listening on {i_host}:{i_port}' |
| 108 | + # Only accept one connection to keep it long-lived |
| 109 | + threading.Thread(target=server_loop, args=(sock,), daemon=True).start() |
| 110 | + |
| 111 | + def stop_server() -> None: |
| 112 | + """ |
| 113 | + Stops the running TCP server by closing the listening socket and resetting internal state. |
| 114 | +
|
| 115 | + :returns: None. |
| 116 | + """ |
| 117 | + sock = sc.sticky.get(f'{prefix}_server_sock') |
| 118 | + if sock: |
| 119 | + try: |
| 120 | + sock.close() |
| 121 | + except Exception: |
| 122 | + pass |
| 123 | + sc.sticky[f'{prefix}_server_sock'] = None |
| 124 | + sc.sticky[f'{prefix}_server_started'] = False |
| 125 | + sc.sticky[f'{prefix}_cloud_buffer_raw'] = [] |
| 126 | + sc.sticky[f'{prefix}_status_message'] = 'Stopped' |
| 127 | + |
| 128 | + # Start or stop server based on inputs |
| 129 | + if i_start and not sc.sticky[f'{prefix}_prev_start']: |
| 130 | + start_server() |
| 131 | + if i_stop and not sc.sticky[f'{prefix}_prev_stop']: |
| 132 | + stop_server() |
| 133 | + |
| 134 | + # Load buffered points into Rhino PointCloud |
| 135 | + if i_load and not sc.sticky[f'{prefix}_prev_load']: |
| 136 | + if not sc.sticky.get(f'{prefix}_server_started', False): |
| 137 | + sc.sticky[f'{prefix}_status_message'] = "Start Server First!" |
| 138 | + else: |
| 139 | + raw = sc.sticky.get(f'{prefix}_cloud_buffer_raw', []) |
| 140 | + if raw: |
| 141 | + pc = rg.PointCloud() |
| 142 | + for x, y, z, r, g, b in raw: |
| 143 | + pc.Add(rg.Point3d(x, y, z), sd.Color.FromArgb(int(r), int(g), int(b))) |
| 144 | + sc.sticky[f'{prefix}_latest_cloud'] = pc |
| 145 | + sc.sticky[f'{prefix}_status_message'] = f'Loaded pcd with {pc.Count} pts' |
| 146 | + else: |
| 147 | + sc.sticky[f'{prefix}_status_message'] = 'No data buffered' |
| 148 | + |
| 149 | + # Update previous states |
| 150 | + sc.sticky[f'{prefix}_prev_start'] = i_start |
| 151 | + sc.sticky[f'{prefix}_prev_stop'] = i_stop |
| 152 | + sc.sticky[f'{prefix}_prev_load'] = i_load |
| 153 | + |
| 154 | + # Update UI and output |
| 155 | + ghenv.Component.Message = sc.sticky[f'{prefix}_status_message'] # noqa: F821 |
| 156 | + |
| 157 | + o_cloud = sc.sticky[f'{prefix}_latest_cloud'] |
| 158 | + return [o_cloud] |
0 commit comments