Untitled
unknown
plain_text
a year ago
6.0 kB
17
Indexable
import socket
import threading
import tkinter as tk
from tkinter import filedialog
from tkinter import ttk
import re
import os
import select
index = 0
newGcode = 0
def parse_gcode(file_path, status_var):
global newGcode
tcp_coords = []
z_position = 0
with open(file_path, 'r') as file:
lines = file.readlines()
total_lines = len(lines)
for idx, line in enumerate(lines):
line = line.strip()
status_var.set(f"Analyzing G-code: {idx + 1}/{total_lines}")
print(f"Analyzing G-code: {idx + 1}/{total_lines}")
if 'G0' in line or 'G1' in line:
x = y = None
match = re.search(r'X([-+]?[0-9]*\.?[0-9]+)', line)
if match:
x = float(match.group(1))
match = re.search(r'Y([-+]?[0-9]*\.?[0-9]+)', line)
if match:
y = float(match.group(1))
match = re.search(r'Z([-+]?[0-9]*\.?[0-9]+)', line)
if match:
z_position = float(match.group(1))
coord = [1, x or 0, y or 0, z_position, 180, 0, -90, 0, 0, 0]
tcp_coords.append(coord)
elif 'G2' in line or 'G3' in line:
arc_command = 2 if 'G2' in line else 3
x = y = i = j = None
match = re.search(r'X([-+]?[0-9]*\.?[0-9]+)', line)
if match:
x = float(match.group(1))
match = re.search(r'Y([-+]?[0-9]*\.?[0-9]+)', line)
if match:
y = float(match.group(1))
match = re.search(r'I([-+]?[0-9]*\.?[0-9]+)', line)
if match:
i = float(match.group(1))
match = re.search(r'J([-+]?[0-9]*\.?[0-9]+)', line)
if match:
j = float(match.group(1))
center_x = tcp_coords[-1][1] + i
center_y = tcp_coords[-1][2] + j
mid_x = (tcp_coords[-1][1] + x) / 2
mid_y = (tcp_coords[-1][2] + y) / 2
if arc_command == 2:
mid_x, mid_y = center_x, 2 * center_y - mid_y
else:
mid_x, mid_y = center_x, 2 * center_y - mid_y
coord = [2, mid_x, mid_y, z_position, 180, 0, -90, x or 0, y or 0, z_position]
tcp_coords.append(coord)
status_var.set("G-code analysis complete.")
print("G-code analysis complete. Result:")
for coord in tcp_coords:
print(coord)
newGcode = 1
# Create a simple G-code file and export it to the root directory
with open('simplified_gcode.txt', 'w') as outfile:
for coord in tcp_coords:
outfile.write(f'{coord}\n')
return tcp_coords
def handle_client(conn, addr, tcp_coords, progress_var, status_var):
global index, newGcode
print(f"Client connected: {addr}")
status_var.set(f"Client connected: {addr}")
conn.setblocking(0) # Set non-blocking mode
inputs = [conn]
while True:
readable, _, _ = select.select(inputs, [], [])
for s in readable:
if s is conn:
data = conn.recv(1024).decode()
if data:
print(f"Received data: {data}")
if newGcode == 1:
if data == 'get #real#13#' and index < len(tcp_coords):
data_package = f'<aCmd><{tcp_coords[index]}>'
conn.sendall(data_package.encode())
progress_var.set(int((index + 1) / len(tcp_coords) * 100))
index += 1
elif data == 'get #real#13#' and index >= len(tcp_coords):
conn.sendall('<aCmd><[3,0,0,0,0,0,0,0,0,0]>'.encode())
status_var.set("All data sent. Waiting for further instructions.")
else:
print(f"Unexpected data: {data}")
else:
return
def start_server(tcp_coords, progress_var, status_var):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('0.0.0.0', 9999))
server.listen(5)
print("Server started, waiting for connections...")
status_var.set("Server started, waiting for connections...")
while True:
conn, addr = server.accept()
client_thread = threading.Thread(target=handle_client, args=(conn, addr, tcp_coords, progress_var, status_var))
client_thread.start()
def upload_file(progress_var, status_var):
global index
file_path = filedialog.askopenfilename()
if file_path:
index = 0 # Reset the global index when a new file is uploaded
status_var.set("Analyzing G-code...")
print("Analyzing G-code...")
tcp_coords = parse_gcode(file_path, status_var)
# Start the server only if tcp_coords is populated
if tcp_coords:
# Pass tcp_coords as a parameter to start_server
server_thread = threading.Thread(target=start_server, args=(tcp_coords, progress_var, status_var))
server_thread.start()
else:
status_var.set("G-code analysis failed or empty.")
print("G-code analysis failed or empty.")
def main():
root = tk.Tk()
root.title("GCode to TCP Sender")
progress_var = tk.DoubleVar()
status_var = tk.StringVar()
progress_bar = ttk.Progressbar(root, variable=progress_var, maximum=100)
progress_bar.pack(pady=10)
status_label = tk.Label(root, textvariable=status_var)
status_label.pack(pady=10)
upload_button = tk.Button(root, text="Upload GCode File", command=lambda: upload_file(progress_var, status_var))
upload_button.pack(pady=10)
root.mainloop()
if __name__ == "__main__":
main()
Editor is loading...
Leave a Comment