svg2gcode/gcode_simulator.py

95 lines
3.3 KiB
Python
Executable File

#!/usr/bin/python
from tkinter import Tk, Canvas, Frame, BOTH, EventType, ALL
import argparse
gcode_file_path = " "
bedsizex = 0
bedsizey = 0
scale_factor = 1.0
x_offset = 24.0
y_offset = 24.0
laser_on = False
last_position = {"x": x_offset, "y": 720-y_offset} #set to initial start at home pos
global canvas
debug = True
def parse_arguments():
global gcode_file_path
global bedsizex
global bedsizey
parser = argparse.ArgumentParser(description='Simulate gcode for laser plotter.')
parser.add_argument("-i", "--input", dest='inputfile', metavar='data.gcode', help="path to gcode file", required=True)
parser.add_argument("-bx", "--bedsizex", dest='bedsizex', default="376", help="x size of bed in mm", required=False)
parser.add_argument("-by", "--bedsizey", dest='bedsizey', default="315", help="y size of bed in mm", required=False)
args = parser.parse_args()
gcode_file_path = args.inputfile
bedsizex = int(args.bedsizex)
bedsizey = int(args.bedsizey)
def plot_paths(canvas):
gcode_file = open(gcode_file_path, "r")
for line in gcode_file.readlines():
if(not line.startswith(';')): #filter comments
#print(line)
if(line.startswith('M5')):
if(debug): print("[decoder] laser off")
laser_on = False
if(line.startswith('M3')):
if(debug): print("[decoder] laser on")
laser_on = True
if(line.startswith('G1')):
x = float(line[(int(line.find('X'))+1):(int(line.find('Y')-1))]) * (scale_factor*1) + x_offset
y = (720-y_offset) - (float(line[(int(line.find('Y'))+1):(int(line.find(';')-1))])* (scale_factor*1))
if(debug): print("[decoder] movement to " + str(x) + " " + str(y))
if(laser_on == True):
canvas.create_line(last_position["x"], last_position["y"], x, y, width=5, fill='red')
else:
canvas.create_line(last_position["x"], last_position["y"], x, y, width=3, fill='green')
last_position["x"] = x
last_position["y"] = y
class SimulatorView(Frame):
def __init__(self):
global canvas
super().__init__()
canvas = Canvas(self)
#canvas.bind("<B1-Motion>", lambda event: canvas.scan_dragto(event.x, event.y, gain=1))
self.initUI()
def initUI(self):
self.master.title("gcode simulator")
self.pack(fill=BOTH, expand=1)
canvas.create_line(x_offset, y_offset, x_offset, (720-y_offset), width=2, fill='black')
canvas.create_line(1280-x_offset, y_offset, 1280-x_offset, (720-y_offset), width=2, fill='black')
canvas.create_line(x_offset, y_offset, 1280-x_offset, y_offset, width=2, fill='black')
canvas.create_line(x_offset, (720-y_offset), 1280-x_offset, (720-y_offset), width=2, fill='black')
plot_paths(canvas)
canvas.pack(fill=BOTH, expand=1)
def main():
parse_arguments()
if(bedsizex < bedsizey):
scale_factor = float(720/bedsizey)
else:
scale_factor = float(1280/bedsizex)
print("scale factor: " + str(scale_factor))
#plot_paths(0)
root = Tk()
ex = SimulatorView()
root.geometry(str(1280+int(x_offset))+"x"+str(720+int(y_offset))+"+300+300")
root.mainloop()
if __name__ == '__main__':
main()