11import socket
22import shlex
3+ import re
34from zeroconf import ServiceBrowser , Zeroconf
45
56
@@ -17,7 +18,9 @@ def __init__(self):
1718 self .line_us_name = ''
1819 self .info = {}
1920
20- def connect (self , line_us_name ):
21+ def connect (self , line_us_name = None ):
22+ if line_us_name is None :
23+ line_us_name = self .listener .get_first_line_us ()[2 ]
2124 self .__line_us = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
2225 try :
2326 self .__line_us .connect ((line_us_name , 1337 ))
@@ -71,13 +74,47 @@ def g01(self, x, y, z):
7174 self .__send_command (cmd )
7275 self .__read_response ()
7376
74- def send_gcode (self , gcode , parameters ):
77+ def send_gcode (self , gcode , parameters = '' ):
7578 cmd = gcode .encode ()
7679 cmd += b' '
7780 cmd += parameters .encode ()
7881 self .__send_command (cmd )
7982 return self .__read_response ()
8083
84+ def send_raw_gcode (self , gcode ):
85+ cmd = gcode .encode ()
86+ self .__send_command (cmd )
87+ return self .__read_response ()
88+
89+ def save_to_lineus (self , gcode , position ):
90+ self .send_gcode ('M28' , f'S{ position } ' )
91+ for line in gcode .splitlines ():
92+ self .send_raw_gcode (line )
93+ self .send_gcode ('M29' )
94+
95+ def list_lineus_files (self ):
96+ info = []
97+ raw_info = self .send_gcode ('M20' )
98+ fields = shlex .split (raw_info .decode ('utf-8' ))
99+ if fields .pop (0 ) != 'ok' :
100+ return None
101+ else :
102+ fields = re .split (':' , fields [0 ])
103+ if fields .pop (0 ) != 'FS' :
104+ return None
105+ else :
106+ fields = re .split (';' , fields [0 ])
107+ for field in fields :
108+ if field != '' :
109+ detail = re .split ('-' , field )
110+ file_number = detail [0 ].lstrip ('/' )
111+ file_number = file_number .lstrip ('0' )
112+ file_number = file_number .rstrip ('.txt' )
113+ file_size = detail [1 ]
114+ info .append ((file_number , file_size , detail [0 ]))
115+ return info
116+
117+
81118 def __read_response (self ):
82119 """Read from the socket one byte at a time until we get a null"""
83120 line = b''
@@ -134,11 +171,18 @@ def get_line_us_list(self):
134171
135172
136173if __name__ == '__main__' :
174+
175+ connected = False
176+
137177 def callback_func (line_us ):
178+ global connected
179+ connected = True
138180 print (f'callback: { line_us [0 ]} ' )
139181
140182
141183 my_line_us = LineUs ()
142184 my_line_us .on_found_line_us (callback_func )
143- while True :
185+ while not connected :
144186 pass
187+ my_line_us .connect ()
188+ print (my_line_us .list_lineus_files ())
0 commit comments