Skip to content

Commit

Permalink
WIP: working of tcp gh-vscode
Browse files Browse the repository at this point in the history
  • Loading branch information
9and3 committed Jan 29, 2024
1 parent 4d96628 commit 379c84d
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 45 deletions.
3 changes: 3 additions & 0 deletions GH/PyGH/client_tst.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ def start_client():
# Send a message to the server
s.send("Hello server!".encode())

# print the received message
print(s.recv(1024).decode())

# Wait for 2 seconds
time.sleep(2)

Expand Down
71 changes: 35 additions & 36 deletions GH/PyGH/scriptsyncGH_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@
import os
import time


import contextlib
import io

import socket
import threading

import rhinoscriptsyntax as rs

# TODO: create an abc class for threads with utility methods
# and create a class for a new TCPThread


class ScriptSyncThread(threading.Thread):
def __init__(self,
Expand Down Expand Up @@ -71,10 +74,31 @@ def __init__(self):
self._var_output = []
ghenv.Component.Message = "ScriptSyncCPy"

self.is_success = False

self.vscode_server_ip = "127.0.0.1"
self.vscode_server_port = 58260
self.client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

self.thread_name = None
self.path = None
self.path_lock = threading.Lock()

# TODO: this should be implmeneted in a separate thread to
# continusly check if vscode is started, if not just raise a warning
def connect_to_vscode_server(self):
""" Connect to the VSCode server. """
try:
self.client_socket.connect((self.vscode_server_ip, self.vscode_server_port))
except ConnectionRefusedError:
print("script-sync::Connection refused by the vscode-server")
return False
except Exception as e:
print(f"script-sync::Error connecting to the vscode-server: {str(e)}")
return False
self.client_socket.send("Hello vscode from GHcomponent!".encode())
return True

def safe_exec(self, path, globals, locals):
"""
Execute Python3 code safely. It redirects the output of the code
Expand All @@ -101,6 +125,12 @@ def safe_exec(self, path, globals, locals):

def RunScript(self):
""" This method is called whenever the component has to be recalculated. """
self.is_success = False

# connect to the vscode server
if not self.connect_to_vscode_server():
raise Exception("script-sync::Error connecting to the vscode-server")

# check the file is path
self.path = r"F:\script-sync\GH\PyGH\test\runner_script.py" # <<<< test

Expand Down Expand Up @@ -129,41 +159,8 @@ def RunScript(self):
else:
self._var_output.append(None)





def AppendMenuItems(self, menu):
"""
This method is called by Grasshopper when the user right-clicks
on the component icon. By default it adds two items to the menu
that allow users to save and load a preset.
:param menu: The ToolStripDropDown to add items to.
"""
# menu.Items.Add("Save preset", None, self.Menu_SavePresetClicked)
# menu.Items.Add("Load preset", None, self.Menu_LoadPresetClicked)

# create a menu item that open a file explorer
ghenv.Component.MenuItems(self, menu)
image = None



def Menu_OpenFileClicked(self, sender, e):
""" Open a file explorer to select a file. """
# create a file dialog
dialog = System.Windows.Forms.OpenFileDialog()
dialog.Filter = "Python files (*.py)|*.py"
dialog.Title = "Select a Python file"
dialog.InitialDirectory = os.path.dirname(__file__)
if dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK:
self.path = dialog.FileName
self.thread_name : str = f"script-sync-thread::{ghenv.Component.InstanceGuid}"
if self.thread_name not in [t.name for t in threading.enumerate()]:
ScriptSyncThread(self.path, self.path_lock, self.thread_name).start()
print(f"script-sync::File selected: {self.path}")

self.is_success = True
# TODO: add a menu item to select the file to run


def AfterRunScript(self):
Expand All @@ -172,6 +169,8 @@ def AfterRunScript(self):
its calculation. It is used to load the GHComponent outputs
with the values created in the script.
"""
if not self.is_success:
return
outparam = [p for p in ghenv.Component.Params.Output]
outparam_names = [p.NickName for p in outparam]

Expand Down
23 changes: 14 additions & 9 deletions GH/PyGH/server_tst.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,20 @@
import socket
import threading
import os

def handle_client(client_socket):
while True:
# Receive data from the client
message = client_socket.recv(1024).decode()
if not message:
break
print(f"Received: {message}")

# Close the connection with the client
client_socket.close()
try:
while True:
# Receive data from the client
message = client_socket.recv(1024).decode()
if not message:
break
print(f"Received: {message}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
# Close the connection with the client
client_socket.close()

def start_server():
# Create a socket object
Expand Down Expand Up @@ -44,6 +48,7 @@ def start_server():
except KeyboardInterrupt:
print("\nServer is stopping due to keyboard interruption...")
server.close()
os._exit(1)

# Start the server
start_server()

0 comments on commit 379c84d

Please sign in to comment.