def send_line(self, line): #devuelve True si se envio la linea, False si el buffer no lo permitio if not line.endswith("\n"): line = line + "\n" if self.parser == "grbl": if sum(self.grbl_sentchars) + len( line) >= BufferManager.GRBL_BUFFER_SIZE: return False else: grbl_sentchars.append(len(line)) elif self.parser == "tiny-g": linelen = line.replace("!", "").replace("~", "").replace( "%", "").strip() #el tiny-g no mete estos comandos al serial if (linelen #si la linea que va al serial tiene longitud y and (self.tiny_g_available_queue_buffer - self.tiny_g_unresponded_lines <= BufferManager.TINYG_QUEUE_BUFFER_MIN or not ThreadsafeSerial.get().cts or len(line) + BufferManager.TINYG_SERIAL_BUFFER_MIN > self.tiny_g_serial_buffer_available)): return False #no podemos meterla if linelen: #si la linea sin esos caracteres tiene longitud self.tiny_g_serial_buffer_available -= len(line) self.tiny_g_unresponded_lines += 1 ThreadsafeSerial.get().write(line) return True
def manage_response(self, data): if "local_connection_token" in data: spkserver.local_connection_token = data["local_connection_token"] if "channel_api_token" in data: self.channel_thread.connect(data["channel_api_token"]) if "command" in data: if data["command"] == "re_configure": common.set_id(None) self.channel_thread.disconnect() #common.restart_please() segun yo no es necesario if data["command"] == "invalidate_config_info": print u"Parece que hay un problema con la configuración, el servidor contestó: %s" % data[ "reason"] if data["command"] == "update_id": if "new_id" in data: common.set_id(data["new_id"]) elif data["command"] == "pause" or data["command"] == "unpause": if self.routine != None: self.routine.job.buffer_manager.send_line( "!" if data["command"] == "pause" else "~") elif data["command"] == "send_gcode": if self.routine is None: try: code = data.get("code", None) if code is None: parser = common.get_parser() code = data.get(parser, None) if code is not None: code = code.strip() + "\n" ThreadsafeSerial.get().write(code) if "success_message" in data: message = data["success_message"] try: self.show_message( "success", message.get("title", ""), message.get("description", ""), message.get("timeout", 5000)) except: pass except DeadSerialException: self.show_message( "error", "El puerto serial está desconectado") elif data["command"] == "stop_job": if self.routine != None: self.routine.status.stop_please() elif data["command"] == "run_queue": if "job_data" in data: self.start_routine("cut", job_id=data["job_data"]["job_id"], arguments=data["job_data"]["arguments"]) elif data["command"] == "do_homing": self.start_routine("home", arguments=data.get("arguments", None)) elif data["command"] == "do_probing": self.start_routine("probe", arguments=data.get("arguments", None))
def periodic(self): #esta función le pregunta el estado cada 300ms al GRBL, solita se reinicia if not self.periodic_continue: return try: ThreadsafeSerial.get().write(self.question) #ThreadsafeSerial.get().readline(timeout=.1) except DeadSerialException: pass t = threading.Timer(.3, self.periodic) #creamos un timer para dentro de 300ms t.daemon=True t.start()
def periodic( self ): #esta función le pregunta el estado cada 300ms al GRBL, solita se reinicia if not self.periodic_continue: return try: ThreadsafeSerial.get().write(self.question) #ThreadsafeSerial.get().readline(timeout=.1) except DeadSerialException: pass t = threading.Timer( .3, self.periodic) #creamos un timer para dentro de 300ms t.daemon = True t.start()
def exit_routine(): try: server_thread.server.shutdown() except: pass try: internet_thread.kill=True try: ThreadsafeSerial.get().close() except DeadSerialException:pass if internet_thread.channel_thread: internet_thread.channel_thread.kill=True except: pass
def manage_response(self,data): if "local_connection_token" in data: spkserver.local_connection_token=data["local_connection_token"] if "channel_api_token" in data: self.channel_thread.connect(data["channel_api_token"]) if "command" in data: if data["command"]=="re_configure": common.set_id(None) self.channel_thread.disconnect() #common.restart_please() segun yo no es necesario if data["command"]=="invalidate_config_info": print u"Parece que hay un problema con la configuración, el servidor contestó: %s"%data["reason"] if data["command"]=="update_id": if "new_id" in data: common.set_id(data["new_id"]) elif data["command"]=="pause" or data["command"]=="unpause": if self.routine!=None: self.routine.job.buffer_manager.send_line("!" if data["command"]=="pause" else "~") elif data["command"]=="send_gcode": if self.routine is None: try: code=data.get("code",None) if code is None: parser=common.get_parser() code=data.get(parser,None) if code is not None: code=code.strip()+"\n" ThreadsafeSerial.get().write(code) if "success_message" in data: message= data["success_message"] try: self.show_message("success",message.get("title",""),message.get("description",""),message.get("timeout",5000)) except: pass except DeadSerialException: self.show_message("error","El puerto serial está desconectado") elif data["command"]=="stop_job": if self.routine!=None: self.routine.status.stop_please() elif data["command"]=="run_queue": if "job_data" in data: self.start_routine("cut",job_id=data["job_data"]["job_id"],arguments=data["job_data"]["arguments"]) elif data["command"]=="do_homing": self.start_routine("home",arguments=data.get("arguments",None)) elif data["command"]=="do_probing": self.start_routine("probe",arguments=data.get("arguments",None))
def home(self): s = ThreadsafeSerial.get() self.status.set_can_stop(True) config_vars = self.arguments["config_vars"] if self.parser == "tiny-g": #lines=["G28.3X0Y0Z40\n"] #lines=["G28.2X0Y0Z0\n","G28.3X0Y0Z20\n","G0Z6\n"] lines = [ "G28.2X0Y0Z0\n", "G92X0Y0Z40\n", "G0Z%s\n" % config_vars["probe_security_plane"] ] self.send_lines_and_wait(lines) else: #lines=["$H\","G10L20P1X0Y0Z0\n"] s.write("$H\n") time.sleep(2) while True: intro = s.readline(timeout=1) self.exit_if_requested() if "ok" in intro: break # idle_count = 0 # while idle_count < 5: # intro = s.readline(timeout=1) # print intro # if "Idle" in intro: # idle_count += 1 s.write("G10L20P1X0Y0Z40\n") s.readline()
def readlines(self, lastlineid=None): s = ThreadsafeSerial.get() prevs = self._get_prev_lines(lastlineid) if prevs is not None: return prevs #checamos si no hay lineas guardadas with self.lock: #esperamos al lock de lectura prevs = self._get_prev_lines( lastlineid ) #volvemos a checar si no se guardaron lineas miesntras esperabamos el lock if prevs is not None: return prevs newlines = [] time_reading = time.time() while True: if common.internet_thread.routine is not None: break l = s.readline(timeout=1) if l.endswith("\n"): newlines.append(l[0:-1]) #leemos mas else: break if s.inWaiting() == 0 or time.time() - time_reading > 1: break if len(newlines): with self.dictlock: for newline in newlines: if len(self.lines) > 100: self.lines.popitem(False) self.lineid += 1 self.lines[self.lineid] = newline return self.lineid, newlines else: return lastlineid, None
def readlines(self,lastlineid=None): s=ThreadsafeSerial.get() prevs=self._get_prev_lines(lastlineid) if prevs is not None: return prevs #checamos si no hay lineas guardadas with self.lock:#esperamos al lock de lectura prevs=self._get_prev_lines(lastlineid) #volvemos a checar si no se guardaron lineas miesntras esperabamos el lock if prevs is not None: return prevs newlines=[] time_reading=time.time() while True: if common.internet_thread.routine is not None: break l =s.readline(timeout=1) if l.endswith("\n"): newlines.append(l[0:-1]) #leemos mas else: break if s.inWaiting()==0 or time.time()-time_reading>1: break if len(newlines): with self.dictlock: for newline in newlines: if len(self.lines)>100: self.lines.popitem(False) self.lineid+=1 self.lines[self.lineid]=newline return self.lineid,newlines else: return lastlineid,None
def home(self): s=ThreadsafeSerial.get() self.status.set_can_stop(True) config_vars=self.arguments["config_vars"] if self.parser=="tiny-g": #lines=["G28.3X0Y0Z40\n"] #lines=["G28.2X0Y0Z0\n","G28.3X0Y0Z20\n","G0Z6\n"] lines=["G28.2X0Y0Z0\n","G92X0Y0Z40\n","G0Z%s\n"%config_vars["probe_security_plane"]] self.send_lines_and_wait(lines) else: #lines=["$H\","G10L20P1X0Y0Z0\n"] s.write("$H\n") time.sleep(2) while True: intro = s.readline(timeout=1) self.exit_if_requested() if "ok" in intro: break # idle_count = 0 # while idle_count < 5: # intro = s.readline(timeout=1) # print intro # if "Idle" in intro: # idle_count += 1 s.write("G10L20P1X0Y0Z40\n") s.readline()
def send_gcode(self,lines,fase=False,start_line=0): usb = ThreadsafeSerial.get() if fase == "cutting": lines = ["N%s%s\n" % (i,lines[i]) if not "N" in lines[i] else lines[i] for i in range(len(lines))] current_line = 0 total_lines = len(lines) last_report_time=time.time() self.status.set_fase(fase) self.status.set_can_stop(False) self.status.set_line_total(total_lines+start_line) state=None #if self.parser == "tiny-g": # time.sleep(1) # self.buffer_manager.send_line(json.dumps({"sr":None}) + "\n") while True: while current_line < total_lines and self.buffer_manager.send_line(lines[current_line]): current_line+=1 self.exit_if_requested() if usb.inWaiting()==0: if state != "pause" and time.time()-last_report_time>5: raise Exception("El %s no responde, reincialo y vuelve a intentar" % self.parser) continue #para que se actualice el controlFlow del tiny lo antes posible last_report_time=time.time() rline = usb.readline(timeout=1) if rline: new_sate=self.parse_state(rline) state=new_sate if new_sate is not None else state if fase == "cutting": current_aprox=current_line+start_line-self.buffer_manager.lines_in_buffer if current_aprox>self.status.line: self.status.set_current_line(current_aprox) if fase == "homing" or fase == "probing": time.sleep(.5) if state=="pause": self.status.set_fase("paused") self.status.set_can_stop(True)#podemos detenernos elif state=="run": self.status.set_fase(fase) self.status.set_can_stop(False) elif state=="error": raise(Exception("Hubo un problema, la ultima linea enviada fue la %s"%current_line)) if current_line >= total_lines and (self.buffer_manager.buffer_is_empty() or state == "idle" or state == "cycling") and state != "homing" and state != "probing": break
def prepare_cnc(self): self.status.set_fase("preparing") s = ThreadsafeSerial.get() if self.parser == "grbl": s.flushInput() s.write("\x18\n") time.sleep(5) s.write("$x\n") s.flushInput() elif self.parser == "tiny-g": config_lines=["$ej=1\n"]+\ [json.dumps({k:v})+"\n" for k,v in {"fd":0,"sv":2,"si":250,"tv":1,"jv":1,"qv":2,"js":1,"ex":2}.iteritems()]+\ [json.dumps({"sr":{"stat":True,"n":True,"qr":True,"qo":True,"qi":True}})+"\n"] for retry in range(2): s.write("%\n") time.sleep(0.2) s.flushInput() if self.send_lines_and_wait(config_lines, 1): break self.buffer_manager.reset() else: raise Exception( "El %s no responde, reincialo y vuelve a intentar" % self.parser) s.flushInput() s.flushOutput()
def get_parser(): usb=ThreadsafeSerial.get() if "USB" in usb.getPort(): parser = "tiny-g" elif "ACM" in usb.getPort(): parser = "grbl" else: raise Exception(u"No se pudo identificar el procesador de código G") return parser
def probe(self): config_vars=self.arguments["config_vars"] self.status.set_can_stop(True) s=ThreadsafeSerial.get() if self.parser =="tiny-g": lines=["G0X%sY%s\n"%(config_vars["probe_x_pos"],config_vars["probe_y_pos"]),"G38.2F250Z-200\n","G92Z%s\n" % config_vars["probe_z_pos"],"G0Z%s\n"%config_vars["probe_security_plane"]] else: lines=["G0X%sY%s\n"%(config_vars["probe_x_pos"],config_vars["probe_y_pos"]),"G38.2F250Z-200\n","G10L20P1Z0\n","G0Z%s\n"%config_vars["probe_security_plane"]] self.send_lines_and_wait(lines)
def run(self): self.status.set_can_stop(True) try: usb= ThreadsafeSerial.get() usb.flushInput() usb.flushOutput() except DeadSerialException: raise Exception("El puerto serial está desconectado") self.parser=common.get_parser() self.buffer_manager = BufferManager(self.parser) self.prepare_cnc() if self.routine_type=="cut": self.status.set_fase('downloading') g_code= urllib2.urlopen(self.arguments["gcode_url"]).read() #descargamos el código G lines=clean_lines(g_code.split("\n"))#lista de líneas de código self.exit_if_requested() with PeriodicQuestion(self.parser): speed=self.arguments["speed"] if speed!= 1: lines=slow_down(lines, speed) start_line=self.arguments["start_line"] if start_line>len(lines): raise Exception("La línea inicial es %d, pero el archivo sólo tiene %d líneas."%(start_line,len(lines))) if start_line>0: previous_lines=lines[:start_line+1] #es mas uno para incluir la actual en las busqedas lines=lines[start_line:] previous_lines.reverse() last_G=extract_first_match(previous_lines,["G0","G1","G00","G01"]) last_X=extract_float(previous_lines, "X") last_Y=extract_float(previous_lines, "Y") last_Z=extract_float(previous_lines, "Z") last_F=extract_float(previous_lines, "F") last_S=extract_float(previous_lines, "S") for h in [HALF_FILE_CODE_FIRST]: header=h[:] header=replace_variable(header,"LAST_X","X"+last_X if last_X else "") header=replace_variable(header,"LAST_Y","Y"+last_Y if last_Y else "") header=replace_variable(header,"LAST_Z","Z"+last_Z if last_Z else "") header=replace_variable(header,"LAST_F","F"+last_F if last_F else "") header=replace_variable(header,"LAST_S","S"+last_S if last_S else "") header=replace_variable(header,"LAST_G",last_G if last_G else "") header=replace_variable(header,"SEC_PLANE",str(get_variable("security_plane"))) self.send_gcode(clean_lines(header),"preparing") self.send_gcode(lines,"cutting",start_line=start_line) elif self.routine_type=="home": self.home() elif self.routine_type=="probe": self.probe()
def send_line(self,line): #devuelve True si se envio la linea, False si el buffer no lo permitio if not line.endswith("\n"): line=line+"\n" if self.parser=="grbl": if sum(self.grbl_sentchars)+len(line) >=BufferManager.GRBL_BUFFER_SIZE: return False else: grbl_sentchars.append(len(line)) elif self.parser=="tiny-g": linelen=line.replace("!","").replace("~","").replace("%","").strip() #el tiny-g no mete estos comandos al serial if (linelen #si la linea que va al serial tiene longitud y and (self.tiny_g_available_queue_buffer-self.tiny_g_unresponded_lines<=BufferManager.TINYG_QUEUE_BUFFER_MIN or not ThreadsafeSerial.get().cts or len(line)+BufferManager.TINYG_SERIAL_BUFFER_MIN>self.tiny_g_serial_buffer_available)): return False #no podemos meterla if linelen: #si la linea sin esos caracteres tiene longitud self.tiny_g_serial_buffer_available-=len(line) self.tiny_g_unresponded_lines+=1 ThreadsafeSerial.get().write(line) return True
def exit_if_requested(self): if self.should_stop(): s = ThreadsafeSerial.get() if self.parser == "tiny-g": s.write("!\n") s.write("%\n") s.write("M5\n") else: s.write("!\n") s.write("\x18\n") time.sleep(2) s.write("$x\n") s.flushInput() s.flushOutput() exit() #salimos
def exit_if_requested(self): if self.should_stop(): s=ThreadsafeSerial.get() if self.parser == "tiny-g": s.write("!\n") s.write("%\n") s.write("M5\n") else: s.write("!\n") s.write("\x18\n") time.sleep(2) s.write("$x\n") s.flushInput() s.flushOutput() exit() #salimos
def send_lines_and_wait(self,lines,timeout=None): #envia las lineas y espera a que se procesen. #si se pasa timeout, devuleve True si se enviaron, #False si se paso el tiempo s=ThreadsafeSerial.get() start_time=time.time() for line in lines: while not self.buffer_manager.send_line(line): while s.inWaiting()!=0: self.exit_if_requested() self.buffer_manager.manage_report(s.readline(timeout=0.1)) if timeout is not None and time.time()-start_time> timeout: return False while not self.buffer_manager.buffer_is_empty(): self.exit_if_requested() if timeout is not None and time.time()-start_time> timeout: return False self.buffer_manager.manage_report(s.readline(timeout=0.1)) return True
def send_lines_and_wait(self, lines, timeout=None): #envia las lineas y espera a que se procesen. #si se pasa timeout, devuleve True si se enviaron, #False si se paso el tiempo s = ThreadsafeSerial.get() start_time = time.time() for line in lines: while not self.buffer_manager.send_line(line): while s.inWaiting() != 0: self.exit_if_requested() self.buffer_manager.manage_report(s.readline(timeout=0.1)) if timeout is not None and time.time() - start_time > timeout: return False while not self.buffer_manager.buffer_is_empty(): self.exit_if_requested() if timeout is not None and time.time() - start_time > timeout: return False self.buffer_manager.manage_report(s.readline(timeout=0.1)) return True
def probe(self): config_vars = self.arguments["config_vars"] self.status.set_can_stop(True) s = ThreadsafeSerial.get() if self.parser == "tiny-g": lines = [ "G0X%sY%s\n" % (config_vars["probe_x_pos"], config_vars["probe_y_pos"]), "G38.2F250Z-200\n", "G92Z%s\n" % config_vars["probe_z_pos"], "G0Z%s\n" % config_vars["probe_security_plane"] ] else: lines = [ "G0X%sY%s\n" % (config_vars["probe_x_pos"], config_vars["probe_y_pos"]), "G38.2F250Z-200\n", "G10L20P1Z0\n", "G0Z%s\n" % config_vars["probe_security_plane"] ] self.send_lines_and_wait(lines)
def prepare_cnc(self): self.status.set_fase("preparing") s=ThreadsafeSerial.get() if self.parser =="grbl": s.flushInput() s.write("\x18\n") time.sleep(5) s.write("$x\n") s.flushInput() elif self.parser=="tiny-g": config_lines=["$ej=1\n"]+\ [json.dumps({k:v})+"\n" for k,v in {"fd":0,"sv":2,"si":250,"tv":1,"jv":1,"qv":2,"js":1,"ex":2}.iteritems()]+\ [json.dumps({"sr":{"stat":True,"n":True,"qr":True,"qo":True,"qi":True}})+"\n"] for retry in range(2): s.write("%\n") time.sleep(0.2) s.flushInput() if self.send_lines_and_wait(config_lines,1): break self.buffer_manager.reset() else: raise Exception("El %s no responde, reincialo y vuelve a intentar" % self.parser) s.flushInput() s.flushOutput()
def run(self): self.status.set_can_stop(True) try: usb = ThreadsafeSerial.get() usb.flushInput() usb.flushOutput() except DeadSerialException: raise Exception("El puerto serial está desconectado") self.parser = common.get_parser() self.buffer_manager = BufferManager(self.parser) self.prepare_cnc() if self.routine_type == "cut": self.status.set_fase('downloading') g_code = urllib2.urlopen( self.arguments["gcode_url"]).read() #descargamos el código G lines = clean_lines(g_code.split("\n")) #lista de líneas de código self.exit_if_requested() with PeriodicQuestion(self.parser): speed = self.arguments["speed"] if speed != 1: lines = slow_down(lines, speed) start_line = self.arguments["start_line"] if start_line > len(lines): raise Exception( "La línea inicial es %d, pero el archivo sólo tiene %d líneas." % (start_line, len(lines))) if start_line > 0: previous_lines = lines[:start_line + 1] #es mas uno para incluir la actual en las busqedas lines = lines[start_line:] previous_lines.reverse() last_G = extract_first_match(previous_lines, ["G0", "G1", "G00", "G01"]) last_X = extract_float(previous_lines, "X") last_Y = extract_float(previous_lines, "Y") last_Z = extract_float(previous_lines, "Z") last_F = extract_float(previous_lines, "F") last_S = extract_float(previous_lines, "S") for h in [HALF_FILE_CODE_FIRST]: header = h[:] header = replace_variable( header, "LAST_X", "X" + last_X if last_X else "") header = replace_variable( header, "LAST_Y", "Y" + last_Y if last_Y else "") header = replace_variable( header, "LAST_Z", "Z" + last_Z if last_Z else "") header = replace_variable( header, "LAST_F", "F" + last_F if last_F else "") header = replace_variable( header, "LAST_S", "S" + last_S if last_S else "") header = replace_variable(header, "LAST_G", last_G if last_G else "") header = replace_variable( header, "SEC_PLANE", str(get_variable("security_plane"))) self.send_gcode(clean_lines(header), "preparing") self.send_gcode(lines, "cutting", start_line=start_line) elif self.routine_type == "home": self.home() elif self.routine_type == "probe": self.probe()
def send_gcode(self, lines, fase=False, start_line=0): usb = ThreadsafeSerial.get() if fase == "cutting": lines = [ "N%s%s\n" % (i, lines[i]) if not "N" in lines[i] else lines[i] for i in range(len(lines)) ] current_line = 0 total_lines = len(lines) last_report_time = time.time() self.status.set_fase(fase) self.status.set_can_stop(False) self.status.set_line_total(total_lines + start_line) state = None #if self.parser == "tiny-g": # time.sleep(1) # self.buffer_manager.send_line(json.dumps({"sr":None}) + "\n") while True: while current_line < total_lines and self.buffer_manager.send_line( lines[current_line]): current_line += 1 self.exit_if_requested() if usb.inWaiting() == 0: if state != "pause" and time.time() - last_report_time > 5: raise Exception( "El %s no responde, reincialo y vuelve a intentar" % self.parser) continue #para que se actualice el controlFlow del tiny lo antes posible last_report_time = time.time() rline = usb.readline(timeout=1) if rline: new_sate = self.parse_state(rline) state = new_sate if new_sate is not None else state if fase == "cutting": current_aprox = current_line + start_line - self.buffer_manager.lines_in_buffer if current_aprox > self.status.line: self.status.set_current_line(current_aprox) if fase == "homing" or fase == "probing": time.sleep(.5) if state == "pause": self.status.set_fase("paused") self.status.set_can_stop(True) #podemos detenernos elif state == "run": self.status.set_fase(fase) self.status.set_can_stop(False) elif state == "error": raise (Exception( "Hubo un problema, la ultima linea enviada fue la %s" % current_line)) if current_line >= total_lines and ( self.buffer_manager.buffer_is_empty() or state == "idle" or state == "cycling") and state != "homing" and state != "probing": break
def writeline(self, data): if data == "reset": ThreadsafeSerial.get().write("\x18\n") else: ThreadsafeSerial.get().write(data + "\n")
def writeline(self,data): if data == "reset": ThreadsafeSerial.get().write("\x18\n") else: ThreadsafeSerial.get().write(data+"\n")
def do_POST(self): # if self.path=="/send_web": # # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # self.send_response(200) # self.end_headers() # textout = ["Nombre red: %s", # "Pswd: %s\n", # "Tu raspberry se esta conectando...", # "Si cometiste algun error, conectate al cable de Ethernet recarga la pagina y repite los pasos.", # ] # # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (form["ssid"].value,form["psk"].value)) # # if not spkwifi.set_wifi_network(form["ssid"].value.strip(), form["psk"].value.strip()): # self.wfile.write("Algo salio mal...") # # # return # if self.path=="/send_cncid": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # cncid= form["cncid"].value # # try: # if cncid.startswith("sudo"): # cncid = cncid.split("\"")[1] # # f = open(main.NEWCNCIDFILENAME,"w") # f.write(cncid) # f.close # # self.send_response(200) # self.end_headers() # # textout = ["ID: %s\n", # "Recarga la pagina en unos momentos.", # "Tu raspberry se esta reiniciando...", # "Revisa tu nueva maquina en el taller correspondiente." # ] # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (cncid)) # # common.restart_please() # #system("reboot") # #execl(sys.executable, *([sys.executable]+sys.argv)) # # except: # self.send_response(200) # self.end_headers() # self.wfile.write("Error, revisa el contenido de tu id") # # # return # if self.path=="/reset_client": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("El script de spkclient se esta reiniciando, ve a la pagina principal y recargala.") # common.restart_please() # return # if self.path=="/reset_pi": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("La raspberrypi se reiniciara...") # system("reboot") # return # if self.path == "/spkwizardsetup": data = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) action = data.getfirst("action", None) origin = self.headers.get("Origin", None) if not origin in ALLOWED_CONFIG_ORIGINS: self.send_response(403) return self.send_response(200) self.send_header('Content-type', "application/json") self.send_header('Access-Control-Allow-Origin', origin) self.end_headers() if action == "marco": if common.get_id() != None: self.wfile.write( json.dumps({"status": "already_configured"})) else: self.wfile.write( json.dumps({ "status": "polo", "current_network": spkwifi.get_current_connected_network() })) elif action == "get_network_status": self.wfile.write( json.dumps({ "status": "success", "available_networks": [n.ssid for n in spkwifi.get_available_networks()], "current_network": spkwifi.get_current_connected_network() })) elif action == "set_wifi_network": ssid = data.getfirst("ssid", None) password = data.getfirst("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write( json.dumps({ "status": "success", "current_network": spkwifi.get_current_connected_network() })) else: self.wfile.write( json.dumps({ "status": "error", "current_network": spkwifi.get_current_connected_network() })) elif action == "send_workshop": config_data = json.loads(data.getfirst("config_data", "{}")) response = common.send_config_info(config_data) if "extra_info" in response: self.wfile.write( json.dumps({ "status": "success", "extra_info": response["extra_info"] })) else: self.wfile.write( json.dumps({ "status": "error", "reason": response.get("reason", "") })) else: self.wfile.write(json.dumps({"status": "error"})) elif self.path == "/spkcnclocalcommandreceiver": data = cgi.FieldStorage(fp=self.rfile, headers=self.headers, environ={ 'REQUEST_METHOD': 'POST', 'CONTENT_TYPE': self.headers['Content-Type'], }) origin = self.headers.get("Origin", None) local_token = data.getfirst("_local_token", None) prev_local_token = data.getfirst("_prev_local_token", None) if not origin in ALLOWED_CONFIG_ORIGINS or local_token == None or ( local_token != local_connection_token != prev_local_token): self.send_response(403) return self.send_response(200) self.send_header('Content-type', "application/json") self.send_header('Access-Control-Allow-Origin', origin) self.end_headers() message = json.loads(data.getfirst("message", None)) command = message.get("command", None) if command == "checking_same_network": self.wfile.write(json.dumps({"status": "sure :)"})) elif command == "lifeline": time.sleep(60) self.wfile.write(json.dumps({"status": "sure :)"})) elif command == "get_network_status": self.wfile.write( json.dumps({ "status": "success", "available_networks": [n.ssid for n in spkwifi.get_available_networks()], "current_network": spkwifi.get_current_connected_network() })) elif command == "get_current_network": self.wfile.write( json.dumps({ "status": "success", "current_network": spkwifi.get_current_connected_network() })) elif command == "set_wifi_network": ssid = message.get("ssid", None) password = message.get("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write( json.dumps({ "status": "success", "current_network": spkwifi.get_current_connected_network() })) else: self.wfile.write( json.dumps({ "status": "error", "current_network": spkwifi.get_current_connected_network() })) elif command == "get_script_status_change": while True: if common.internet_thread.routine is None or common.internet_thread.routine.status.as_dict( ) != message.get("last_status", None): break else: time.sleep(.01) if common.internet_thread.routine is not None: self.wfile.write( json.dumps({ "status": common.internet_thread.routine.status.as_dict() })) else: self.wfile.write( json.dumps({ "status": common.internet_thread.last_job_status.as_dict() if common.internet_thread.last_job_status is not None else None })) elif command == "send_console_line": if common.internet_thread.routine is None: try: self.console_manager.writeline(message.get("line", "")) except: pass self.wfile.write(json.dumps({})) elif command == "console_line_poll": try: lines = None lastid = message.get("lastlineid", None) counter = 0 response = {"status": "success"} while common.internet_thread.routine is None and lines is None and counter < 3: if message.get("i_think_there_is_no_serial", False): response["parser"] = common.get_parser() break #para que se quite el mensaje de que no hay serial lastid, lines = self.console_manager.readlines(lastid) counter += 1 response["lines"] = lines response["lastlineid"] = lastid self.wfile.write(json.dumps(response)) except DeadSerialException: self.wfile.write( json.dumps({ "status": "error", "reason": "no-serial" })) except: self.wfile.write(json.dumps({"status": "error"})) elif command == "jog_pressed_key": global current_jogging global jogging_cancel_timer try: if common.internet_thread.routine is None: key = message.get("key", None) pressed = message.get("pressed", None) possibles = { 38: "Y", 40: "Y-", 37: "X-", 39: "X", 33: "Z", 34: "Z-" } #http://keycode.info/ usb = ThreadsafeSerial.get() parser = common.get_parser() if key in possibles and pressed is not None: if jogging_cancel_timer is not None: jogging_cancel_timer.cancel() if not pressed or (current_jogging is not None and current_jogging != key): if parser == "tiny-g": usb.write("!%\n") #grbl mandar (! y ctrl x? cuando se frene?) current_jogging = None else: if message.get( "new_pressed", False) and current_jogging is None: if parser == "tiny-g": usb.write("G91 G0 " + possibles[key] + "1000\nG90\n") #grbl mandar lo mismo? current_jogging = key jogging_cancel_timer = threading.Timer( 0.5, lambda: usb.write("!%\n" if parser == "tiny-g" else "")) jogging_cancel_timer.start() usb.flushInput() except DeadSerialException: pass self.wfile.write(json.dumps({})) else: common.internet_thread.manage_response(message) self.wfile.write(json.dumps({}))
def do_POST(self): # if self.path=="/send_web": # # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # self.send_response(200) # self.end_headers() # textout = ["Nombre red: %s", # "Pswd: %s\n", # "Tu raspberry se esta conectando...", # "Si cometiste algun error, conectate al cable de Ethernet recarga la pagina y repite los pasos.", # ] # # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (form["ssid"].value,form["psk"].value)) # # if not spkwifi.set_wifi_network(form["ssid"].value.strip(), form["psk"].value.strip()): # self.wfile.write("Algo salio mal...") # # # return # if self.path=="/send_cncid": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # cncid= form["cncid"].value # # try: # if cncid.startswith("sudo"): # cncid = cncid.split("\"")[1] # # f = open(main.NEWCNCIDFILENAME,"w") # f.write(cncid) # f.close # # self.send_response(200) # self.end_headers() # # textout = ["ID: %s\n", # "Recarga la pagina en unos momentos.", # "Tu raspberry se esta reiniciando...", # "Revisa tu nueva maquina en el taller correspondiente." # ] # self.wfile.write("SPKClient:. \n\n" + "\n".join(textout) % (cncid)) # # common.restart_please() # #system("reboot") # #execl(sys.executable, *([sys.executable]+sys.argv)) # # except: # self.send_response(200) # self.end_headers() # self.wfile.write("Error, revisa el contenido de tu id") # # # return # if self.path=="/reset_client": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("El script de spkclient se esta reiniciando, ve a la pagina principal y recargala.") # common.restart_please() # return # if self.path=="/reset_pi": # form = cgi.FieldStorage( # fp=self.rfile, # headers=self.headers, # environ={'REQUEST_METHOD':'POST', # 'CONTENT_TYPE':self.headers['Content-Type'], # }) # # # self.send_response(200) # self.end_headers() # self.wfile.write("La raspberrypi se reiniciara...") # system("reboot") # return # if self.path=="/spkwizardsetup": data = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) action= data.getfirst("action", None) origin= self.headers.get("Origin",None) if not origin in ALLOWED_CONFIG_ORIGINS: self.send_response(403) return self.send_response(200) self.send_header('Content-type',"application/json") self.send_header('Access-Control-Allow-Origin',origin) self.end_headers() if action=="marco": if common.get_id()!=None: self.wfile.write(json.dumps({"status":"already_configured"})) else: self.wfile.write(json.dumps({"status":"polo","current_network":spkwifi.get_current_connected_network()})) elif action=="get_network_status": self.wfile.write(json.dumps({"status":"success","available_networks":[n.ssid for n in spkwifi.get_available_networks()],"current_network":spkwifi.get_current_connected_network()})) elif action=="set_wifi_network": ssid= data.getfirst("ssid", None) password= data.getfirst("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write(json.dumps({"status":"success","current_network":spkwifi.get_current_connected_network()})) else: self.wfile.write(json.dumps({"status":"error","current_network":spkwifi.get_current_connected_network()})) elif action=="send_workshop": config_data= json.loads(data.getfirst("config_data", "{}")) response=common.send_config_info(config_data) if "extra_info" in response: self.wfile.write(json.dumps({"status":"success","extra_info":response["extra_info"]})) else: self.wfile.write(json.dumps({"status":"error","reason":response.get("reason","")})) else: self.wfile.write(json.dumps({"status":"error"})) elif self.path=="/spkcnclocalcommandreceiver": data = cgi.FieldStorage( fp=self.rfile, headers=self.headers, environ={'REQUEST_METHOD':'POST', 'CONTENT_TYPE':self.headers['Content-Type'], }) origin= self.headers.get("Origin",None) local_token= data.getfirst("_local_token", None) prev_local_token= data.getfirst("_prev_local_token", None) if not origin in ALLOWED_CONFIG_ORIGINS or local_token==None or (local_token!=local_connection_token!=prev_local_token): self.send_response(403) return self.send_response(200) self.send_header('Content-type',"application/json") self.send_header('Access-Control-Allow-Origin',origin) self.end_headers() message= json.loads(data.getfirst("message", None)) command=message.get("command",None) if command=="checking_same_network": self.wfile.write(json.dumps({"status":"sure :)"})) elif command=="lifeline": time.sleep(60) self.wfile.write(json.dumps({"status":"sure :)"})) elif command=="get_network_status": self.wfile.write(json.dumps({"status":"success","available_networks":[n.ssid for n in spkwifi.get_available_networks()],"current_network":spkwifi.get_current_connected_network()})) elif command=="get_current_network": self.wfile.write(json.dumps({"status":"success","current_network":spkwifi.get_current_connected_network()})) elif command=="set_wifi_network": ssid= message.get("ssid", None) password= message.get("password", None) if spkwifi.set_wifi_network(ssid, password): self.wfile.write(json.dumps({"status":"success","current_network":spkwifi.get_current_connected_network()})) else: self.wfile.write(json.dumps({"status":"error","current_network":spkwifi.get_current_connected_network()})) elif command=="get_script_status_change": while True: if common.internet_thread.routine is None or common.internet_thread.routine.status.as_dict()!=message.get("last_status",None): break else: time.sleep(.01) if common.internet_thread.routine is not None: self.wfile.write(json.dumps({"status":common.internet_thread.routine.status.as_dict()})) else: self.wfile.write(json.dumps({"status":common.internet_thread.last_job_status.as_dict() if common.internet_thread.last_job_status is not None else None})) elif command=="send_console_line": if common.internet_thread.routine is None: try: self.console_manager.writeline(message.get("line","")) except: pass self.wfile.write(json.dumps({})) elif command=="console_line_poll": try: lines=None lastid=message.get("lastlineid",None) counter=0 response={"status":"success"} while common.internet_thread.routine is None and lines is None and counter <3: if message.get("i_think_there_is_no_serial",False): response["parser"]=common.get_parser() break #para que se quite el mensaje de que no hay serial lastid,lines=self.console_manager.readlines(lastid) counter+=1 response["lines"]=lines response["lastlineid"]=lastid self.wfile.write(json.dumps(response)) except DeadSerialException: self.wfile.write(json.dumps({"status":"error","reason":"no-serial"})) except: self.wfile.write(json.dumps({"status":"error"})) elif command =="jog_pressed_key": global current_jogging global jogging_cancel_timer try: if common.internet_thread.routine is None: key=message.get("key",None) pressed=message.get("pressed",None) possibles={38:"Y",40:"Y-",37:"X-",39:"X",33:"Z",34:"Z-"} #http://keycode.info/ usb=ThreadsafeSerial.get() parser=common.get_parser() if key in possibles and pressed is not None: if jogging_cancel_timer is not None: jogging_cancel_timer.cancel() if not pressed or (current_jogging is not None and current_jogging!=key): if parser=="tiny-g": usb.write("!%\n") #grbl mandar (! y ctrl x? cuando se frene?) current_jogging=None else: if message.get("new_pressed",False) and current_jogging is None: if parser=="tiny-g": usb.write("G91 G0 "+possibles[key]+"1000\nG90\n") #grbl mandar lo mismo? current_jogging=key jogging_cancel_timer=threading.Timer(0.5,lambda: usb.write("!%\n" if parser=="tiny-g" else "")) jogging_cancel_timer.start() usb.flushInput() except DeadSerialException: pass self.wfile.write(json.dumps({})) else: common.internet_thread.manage_response(message) self.wfile.write(json.dumps({}))