def probe(x,y): global points_on_plane serial_reply="" serial.flushInput() #clean buffer probe_point= "G30\r\n" #probing comand serial.write(probe_point) time.sleep(0.5) #give it some to to start probe_start_time = time.time() while not serial_reply[:22]=="echo:endstops hit: Z:": #issue G30 Xnn Ynn and waits reply. #Expected reply #endstops hit: Z: 0.0000 #couldn't probe point: = if (time.time() - probe_start_time>10): #10 seconds passed, no contact trace_msg="Could not probe "+str(x)+ "," +str(y) + " / " + str(deg) + " degrees" trace(trace_msg) #change safe-Z return False #leave the function,keep probing serial_reply=serial.readline().rstrip() #add safety timeout, exception management time.sleep(0.1) #wait pass #get the z position #print serial_reply z=float(serial_reply.split("Z:")[1].strip()) new_point = [x,y,z,1] points_on_plane = np.vstack([points_on_plane, new_point]) #append new point to the cloud. trace("Probed "+str(x)+ "," +str(y) + " / " + str(deg) + " degrees = " + str(z)) return True
def send(): serial.write(bytes(2, 'UTF-8')) print('发出指令成功') serial.flushInput()
def probe(x,y): global points_on_plane serial_reply="" serial.flushInput() serial.write("G30\r\n") probe_start_time = time.time() while not serial_reply[:22]=="echo:endstops hit: Z:": serial_reply=serial.readline().rstrip() #issue G30 Xnn Ynn and waits reply. if (time.time() - probe_start_time>90): #timeout management trace("Could not probe this point") return False break pass #get the z position z=float(serial_reply.split("Z:")[1].strip()) new_point = [x,y,z,1] points_on_plane = np.vstack([points_on_plane, new_point]) #append new point to the cloud. trace("Probed "+str(x)+ "," +str(y) + " / " + str(deg) + " degrees = " + str(z)) return True
def readSensor(serial): try: # request data 21 serial.flushInput() string = "5A E8 5A DF 5A CB" #Long range - Fast mode - Start periodic readout cmd_bytes = bytearray.fromhex(string) ser.write(cmd_bytes) msg_b = serial.read(8) encoded = str(base64.b16encode(msg_b)) encoded = encoded.replace("b'", "") encoded = encoded.replace("'", "") B = read_hex(encoded) #print(B) return B except (Exception, KeyboardInterrupt) as e: print('sensor communication broke down') print(str(e)) serial.flushInput() time.sleep(0.2) serial.flushOutput() time.sleep(0.2) serial.close() # Only executes once the loop exits sys.exit()
def readSensor(serial): try: # request data 21 serial.flushInput() serial.write('90 232'.encode('utf8')) serial.write('90 223'.encode('utf8')) serial.write('90 203'.encode('utf8')) #print(ser.out_waiting) msg_b = serial.read(8) encoded = str(base64.b16encode(msg_b)) encoded = encoded.replace("b'","") encoded = encoded.replace("'","") B = read_hex(encoded) #print(B) return B except (Exception,KeyboardInterrupt) as e: print('sensor communication broke down') print(str(e)) serial.flushInput() time.sleep(0.2) serial.flushOutput() time.sleep(0.2) serial.close() # Only executes once the loop exits sys.exit()
def macro(code,expected_reply,timeout,error_msg,delay_after,warning=False,verbose=True): global s_error global s_warning global s_skipped serial.flushInput() if s_error==0: serial_reply="" macro_start_time = time.time() serial.write(code+"\r\n") if verbose: trace(error_msg) time.sleep(0.3) #give it some tome to start while not (serial_reply==expected_reply or serial_reply[:4]==expected_reply): #Expected reply #no reply: if (time.time()>=macro_start_time+timeout+5): if serial_reply=="": serial_reply="<nothing>" if not warning: s_error+=1 trace(error_msg + ": Failed (" +serial_reply +")") else: s_warning+=1 trace(error_msg + ": Warning! ") return False #leave the function serial_reply=serial.readline().rstrip() #add safety timeout time.sleep(0.2) #no hammering pass time.sleep(delay_after) #wait the desired amount else: trace(error_msg + ": Skipped") s_skipped+=1 return False return serial_reply
def safety_callback(channel): try: code="" type="" if(GPIO.input(2) == GPIO.LOW): #todo type="emergency" serial.flushInput() serial.write("M730\r\n") reply=serial.readline() try: code=float(reply.split("ERROR : ")[1].rstrip()) except: code=100 if(GPIO.input(2) == GPIO.HIGH): #to do type="" code="" message = {'type': str(type), 'code': str(code)} ws.send(json.dumps(message)) write_emergency(json.dumps(message)) except Exception, e: logging.info(str(e))
def movement(self): speed = 6 rspeed = 30 if not self.wreck_start: if (self.moving_up and self.moving_left) or (self.moving_down and self.moving_left): speed *= 0.707 if (self.moving_up and self.moving_right) or (self.moving_down and self.moving_right): speed *= 0.707 # here we change the value of speed to depend on the joint if self.moving_up: readin = 0 buffer = '' while not buffer.endswith('\n'): try: buffer += arduino.read() serial.flushInput() readin = json.loads(bbuffer) buffer = '' except: print "json error" if readin: servoAngle = int(readin) else: servoAngle = 0 # normalizing 0-60 degrees from the servo to 8-15 speed for the chopper max_servo_angle = 10 min_grip_speed = 10 max_grip_speed = 20 grip_speed = (max_grip_speed - min_grip_speed) * ( servoAngle / max_servo_angle) + min_grip_speed #self.y -= grip_speed self.y -= rspeed # this will be removed once the above line is uncommented out if self.moving_left: self.x -= speed if self.moving_down: self.y += speed if self.moving_right: self.x += speed * 2 if self.x > 200: self.x -= speed * 2 elif self.x > 100: self.x -= speed / 2 if self.x < 0: self.x += speed elif self.x < 100: self.x += speed / 2 if self.y < 0: self.y = 0 if self.y > 430: self.health = 0
def send_gcode_str(gcode_str, serial): serial.flushInput() time.sleep(.01) gcode_str += "\n" serial.write(gcode_str.encode()) grbl_out = serial.readline() # Wait for grbl response with carriage return print(grbl_out.strip()) return(grbl_out.strip().decode("ascii"))
def recv(serial): while True: count = serial.inWaiting() if count != 0: data = serial.read(count) serial.flushInput() sleep(0.1) return data
def modem_terminal(serial,string,timeout): serial.flushInput() serial.write(string) while timeout>0: if serial.inWaiting()>0: sys.stdout.write(serial.read(serial.inWaiting())) time.sleep(0.001) timeout=timeout-1 print ""
def read_serial(gcode): serial.flushInput() serial.write(gcode + "\r\n") response="" while (response==""): response=serial.readline().rstrip if response!="": return response
def modem_terminal(serial, string, timeout): serial.flushInput() serial.write(string) while timeout > 0: if serial.inWaiting() > 0: sys.stdout.write(serial.read(serial.inWaiting())) time.sleep(0.001) timeout = timeout - 1 print ""
def recv(serial): while True: data = serial.read(1) serial.flushInput() # 当接收到字符时立即返回 if data != '': break time.sleep(1) return data
def recv(serial): while True: data = serial.read() if data == '': continue else: break sleep(0.02) serial.flushInput() return data
def serial_run(serial, sleep_stop, data, judag): byte = bytes.fromhex(data) serial.flushInput() serial_send(serial, byte) sleep(sleep_stop) serial_data = serial_read(serial) if serial_data[6:8] == judag: return 1 else: return 0
def initialization(serial): serial.flushInput() print "Please wait..." serial_line = serial.readline() while serial_line.find("Number of messages:") == -1: print serial_line serial_line = serial.readline() print "Ready to begin"
def ping(serial,message, box): add_text("\nPinging Igniter", box) serial.flushInput() serial.write(message) add_text("\nwaiting for reply", box) try: serial.readline() add_text("\n IGNITER: %s" % serial.readline(), box) except Exception as e: add_text( "\nIGNITER: could not read line", box) return
def jogToBedCorner(corner, height, feedrate): serial.flushInput() macro("M402","ok",2,"Retracting Probe (safety)",1, verbose=False) corner = corner.upper() if (corner=="LU"): macro("G0 X"+str(minXPhys)+" Y"+str(minYPhys)+" Z "+str(height)+" F"+str(feedrate),"ok",2,"Moving to left down corner point",0.1) if (corner=="LO"): macro("G0 X"+str(minXPhys)+" Y"+str(maxYPhys)+" Z "+str(height)+" F"+str(feedrate),"ok",2,"Moving to left upper corner point",0.1) if (corner=="RU"): macro("G0 X"+str(maxXPhys)+" Y"+str(minYPhys)+" Z "+str(height)+" F"+str(feedrate),"ok",2,"Moving to right lower corner point",0.1) if (corner=="RO"): macro("G0 X"+str(maxXPhys)+" Y"+str(maxYPhys)+" Z "+str(height)+" F"+str(feedrate),"ok",2,"Moving to right upper corner point",0.1)
def read_serial(gcode): serial.flushInput() serial.write(gcode + "\r\n") time.sleep(0.1) #return serial.readline().rstrip() response = serial.readline().rstrip() if response == "": return "NONE" else: return response
def read_serial(gcode): serial.flushInput() serial.write(gcode + "\r\n") time.sleep(0.1) #return serial.readline().rstrip() response=serial.readline().rstrip() if response=="": return "NONE" else: return response
def recv(self, serial): buffer = '' aux = '' while len(str(aux.encode('hex'))) == 0: aux = serial.read() while len(str(aux.encode('hex'))) > 0: buffer += aux aux = serial.read() serial.flushInput() print " ENCODED: %s" % buffer buffer = b64decode(buffer) print " ENCRYPTED: %s" % buffer.encode('hex') return buffer
def do_serial_command(serial_command): global serial serial_command += '\r' # Make sure we don't have any leftover garbage from the last command serial.flushInput() serial.write(serial_command) # Read number of bytes if they exist or wait for them to arrive until timeout response_bytes = serial.read( len(serial_command) + 11) # we are expecting " Command OK" which is 11 bytes response_str = response_bytes.decode("utf-8") if response_str.find("Command OK", len(serial_command)) == -1: print("Command failed. Got: " + response_str)
def readRobotStatus(serial): # clear input buffer serial.flushInput() # read line str = serial.readline() # check the quality of data if (checkQualityOfData(str)): readMotorData(str) getSonarData(str) readInletSensorData(str) #printRobotStatus() else: print("DATA NOT AVAILABLE")
def get_weight(): global prev time.sleep(0.1) response = serial.readline().decode('utf-8').rstrip()[:-3] serial.flushInput() if not response: response = prev else: prev = response return jsonify({ 'weight': response, 'odor': randint(30, 35), })
def recv(self,serial): buffer = '' aux = '' while len(str(aux.encode('hex'))) == 0: aux = serial.read() while len(str(aux.encode('hex'))) > 0: buffer += aux aux = serial.read() serial.flushInput() print " ENCODED: %s" % buffer buffer = b64decode ( buffer ) print " ENCRYPTED: %s" % buffer.encode('hex') return buffer
def ASK_Slave(serial, cmd_data): global recv_data, recv_n global abs_path timeout_count = 0 timeout_total = 0 print 'recv_n', recv_n print 'recv_data_B', recv_data while True: print "Motor is moving: ", timeout_count, " times" time.sleep(0.5) recv_n = serial.inWaiting() print cmd_data, '&& recv_n:', recv_n if recv_n >= 2: recv_data = serial.read(recv_n) print recv_n, ' && ', recv_data serial.flushInput() if 'OK' in recv_data and cmd_data[0] in recv_data: print 'recv_data_A', recv_data, '+', recv_n print 'Moving Finished.' recv_n = 0 recv_data = 'N' serial.flushOutput() time.sleep(0.5) # 1 # Journal = open(abs_path,'a') # Journal.write(cmd_data[0] + "->") # Journal.close() break else: print "Wrong Control,Break!" recv_n = 0 recv_data = 'N' serial.flushOutput() timeout_count += 1 if timeout_count >= 600: print "No response Slave,Repeat send cmd please." serial.write(cmd_data) timeout_total += timeout_count timeout_count = 0 Journal = open(abs_path, 'a') if timeout_total <= 600: Journal.write("\nSlave No response for CMD:" + cmd_data[0] + " " + str(timeout_total) + " times,Repeat Send CMD...\n") else: Journal.write("\nSlave No response for CMD:" + cmd_data[0] + " " + str(timeout_total) + " times,Shutdown System...\n") Journal.write("System died at: " + Get_time_str(':') + '.\n') os.system('sudo shudown -h now') Journal.close()
def recieve_message(self): readMsg = '' serial.flushInput() time.sleep(4) orig_time = time.time() while((time.time()-orig_time) < 5 ): readMsg = serial.read(serial.inWaiting()) #print("test") time.sleep(1) if readMsg != '': break else: raise("problem in recieving message") self.logger("Recieving package %s" % readMsg) return readMsg
def sendGcode(serial, sequence): #wake up printer and initialize serial.write("\n\n".encode('utf-8')) time.sleep(2) serial.flushInput() for line in sequence: l = removeComment(line) l = l.strip() if (l.isspace() == False and len(l) > 0): print("Sending: " + l) serial.write((l + "\n").encode('utf-8')) grbl_out = serial.readline() #wait for response from printer print(" > " + grbl_out.strip().decode('utf-8'))
def read_hex_from_ee(address): serial.flushOutput() serial.flushInput() msg = '\x02' msg += dec2hex(address) if serial.isOpen(): serial.write(msg) else: print 'Error, the serial port is not open.' return value = serial.readline() if value == '': print 'Error, did not receive response from the Micro Controller.' return None value = value.strip() return value
def udplink(socket_handle, addr, serial_handles): count = 0 while True: try: data = serialtodict(serial_handles) if socket_handle.sendto(data, addr): count += 1 print(data) if count == 600: gc.collect() count = 0 for serial in serial_handles: serial.flushInput() except Exception, e: print(str(e.message)) break
def tagRead(): import serial try: serial= serial.Serial("/dev/ttyACM0", baudrate=9600) n=0 serial.flushInput() serial.flushOutput() while True: data=serial.readline() n=n+1 if data[0:3]=="ISO" and n>3: myString1=data.find('[')+1 myString2=data.find(',') serial.flush() serial.close() return data[myString1:myString2] except Exception as e: return 0
def read_serial_data(serial): serial.flushInput() serial_data = [] readings_left = True timeout_reached = False while readings_left and not timeout_reached: serial_line = serial.readline() if serial_line == '': timeout_reached = True else: serial_data.append(serial_line) if len(serial_data) == max_num_readings: readings_left = False return serial_data
def read_serial_data(serial): """ Given a pyserial object (serial). Outputs a list of lines read in from the serial port """ serial.flushInput() serial_data = [] # serial_line = serial.readline() # serial_data.append(serial_line) # return serial_data bytesToRead = serial.inWaiting() serial.read(bytesToRead) return bytesToRead
def probe(x,y): serial_reply="" serial.flushInput() serial.write("G30\r\n") probe_start_time = time.time() while not serial_reply[:22]=="echo:endstops hit: Z:": serial_reply=serial.readline().rstrip() #issue G30 Xnn Ynn and waits reply. if (time.time() - probe_start_time>90): #timeout management trace("Could not probe this point") return False break pass #get the z position z=float(serial_reply.split("Z:")[1].strip()) new_point = [x,y,z,1] trace("Probed "+str(x)+ "," +str(y)) return True
def read_serial_data(serial): """ Given a pyserial object (serial). Outputs a list of lines read in from the serial port """ serial.flushInput() serial_data = [] readings_left = True timeout_reached = False while readings_left and not timeout_reached: serial_line = serial.readline() if serial_line == '': timeout_reached = True else: serial_data.append(serial_line) if len(serial_data) == max_num_readings: readings_left = False return serial_data
def probe(x,y): serial_reply="" serial.flushInput() serial.write("G30\r\n") probe_start_time = time.time() while not serial_reply[:22]=="echo:endstops hit: Z:": serial_reply=serial.readline().rstrip() #issue G30 Xnn Ynn and waits reply. if (time.time() - probe_start_time>90): #timeout management trace("Could not probe this point") return False break pass #get the z position z=float(serial_reply.split("Z:")[1].strip()) new_point = [x,y,z,1] #trace("Probed "+str(x)+ "," +str(y)) return True
def measurePointHeight(x, y, initialHeight, feedrate): macro("M402", "ok", 2, "Retracting Probe (safety)", 1, verbose=False) macro("G0 Z60 F5000", "ok", 5, "Moving to start Z height", 10) #mandatory! macro( "G0 X" + str(x) + " Y" + str(y) + " Z " + str(initialHeight) + " F10000", "ok", 2, "Moving to left down corner point", 10) macro("M401", "ok", 2, "Lowering Probe", 1, warning=True, verbose=False) serial.flushInput() serial_reply = "" probe_start_time = time.time() serial.write("G30 U" + str(feedrate) + "\r\n") while not serial_reply[:22] == "echo:endstops hit: Z:": serial_reply = serial.readline().rstrip() if (time.time() - probe_start_time > 80): #timeout management z = initialHeight serial.flushInput() return z pass if serial_reply != "": z = serial_reply.split("Z:")[1].strip() serial_reply = "" serial.flushInput() macro( "G0 X" + str(x) + " Y" + str(y) + " Z " + str(initialHeight) + " F10000", "ok", 2, "Moving to left down corner point", 10) macro("M402", "ok", 2, "Raising Probe", 1, warning=True, verbose=False) return z
def measurePointHeight(x, y, initialHeight, feedrate): macro("M402","ok",2,"Retracting Probe (safety)",1, verbose=False) macro("G0 Z60 F5000","ok",5,"Moving to start Z height",10) #mandatory! macro("G0 X"+str(x)+" Y"+str(y)+" Z "+str(initialHeight)+" F10000","ok",2,"Moving to left down corner point",10) macro("M401","ok",2,"Lowering Probe",1, warning=True, verbose=False) serial.flushInput() serial_reply = "" probe_start_time=time.time() serial.write("G30 U"+str(feedrate)+"\r\n") while not serial_reply[:22]=="echo:endstops hit: Z:": serial_reply=serial.readline().rstrip() if (time.time() - probe_start_time>80): #timeout management z = initialHeight serial.flushInput() return z pass if serial_reply!="": z=serial_reply.split("Z:")[1].strip() serial_reply="" serial.flushInput() macro("G0 X"+str(x)+" Y"+str(y)+" Z "+str(initialHeight)+" F10000","ok",2,"Moving to left down corner point",10) macro("M402","ok",2,"Raising Probe",1, warning=True, verbose=False) return z
def readSensor(serial): try: # request data 21 serial.flushInput() string = "5A E8 5A DF 5A CB" #Long range - Fast mode - Start periodic readout cmd_bytes = bytearray.fromhex(string) ser.write(cmd_bytes) msg_b = serial.read(8) encoded = str(base64.b16encode(msg_b)) encoded = encoded.replace("b'","") encoded = encoded.replace("'","") B = read_hex(encoded) #print(B) return B except KeyboardInterrupt: print("User interrupt encountered. Exiting...") time.sleep(3) serial.flushInput() serial.flushOutput() serial.close() sys.exit() except: # for all other kinds of error, but not specifying which one print("Device disconnected") time.sleep(3) serial.flushInput() serial.flushOutput() serial.close() sys.exit()
def probe(x, y): global points_on_plane serial_reply = "" serial.flushInput() #clean buffer probe_point = "G30\r\n" #probing comand serial.write(probe_point) time.sleep(0.5) #give it some to to start probe_start_time = time.time() while not serial_reply[:22] == "echo:endstops hit: Z:": #issue G30 Xnn Ynn and waits reply. #Expected reply #endstops hit: Z: 0.0000 #couldn't probe point: = if (time.time() - probe_start_time > 10): #10 seconds passed, no contact trace_msg = "Could not probe " + str(x) + "," + str( y) + " / " + str(deg) + " degrees" trace(trace_msg) #change safe-Z return False #leave the function,keep probing serial_reply = serial.readline().rstrip() #add safety timeout, exception management time.sleep(0.1) #wait pass #get the z position #print serial_reply z = float(serial_reply.split("Z:")[1].strip()) new_point = [x, y, z, 1] points_on_plane = np.vstack([points_on_plane, new_point]) #append new point to the cloud. trace("Probed " + str(x) + "," + str(y) + " / " + str(deg) + " degrees = " + str(z)) return True
def writeToTape(serial, array, maxvalue): print("Writing") print(array) data = "" if array[0] > 1e1: for x in array: towrite = [0, 0, 0] #rgb towrite[0] = x towrite[1] = 60 towrite[2] = 254 - x for x in towrite: capped = int(min(254,max(0,x))) data += chr(capped) else: # cleartape(serial) return # write control serial.write(data) serial.write(CONTROL) serial.flushInput() serial.flush()
## import sys import serial try: code_to_execute=str(sys.argv[1]) except: print "Warning - parameter <CODE> is required" sys.exit() if code_to_execute != "" : port = '/dev/ttyAMA0' baud = 115200 serial = serial.Serial(port, baud, timeout=0) serial.flushInput() serial.flushInput() serial.write(code_to_execute) data=serial.read(8) print data
def rfidFlush(serial): serial.read(serial.inWaiting()) serial.flushInput()
trace("Probed "+str(x)+ "," +str(y) + " / " + str(deg) + " degrees = " + str(z)) return True printlog(0,0) #create log vuoto trace("\n ---------- Initializing ---------- \n") '''#### SERIAL PORT COMMUNICATION ####''' serial_port = config.get('serial', 'port') serial_baud = config.get('serial', 'baud') serial = serial.Serial(serial_port, serial_baud, timeout=0.5) #initialize serial #serial = serial.Serial(port, baud, timeout=0.6) time.sleep(0.5) #sleep a while serial.flushInput() #clean buffer trace('PROBE MODULE STARTING') print 'scanning from' + str(x)+ "," +str(y)+ " to " +str(x1)+ "," +str(y1); print 'Total points : ', tot_probes print 'Probing density : ', probe_density , " points/mm" print 'Num of planes : ', slices print 'Start/End : ', begin ,' to ', end, 'deg' #ESTIMATED SCAN TIME ESTIMATION estimated=(slices*tot_probes*3)/60 if(estimated<1): estimated*=60 unit= "Seconds" else: unit= "Minutes"
} print "Reading file..." f = open("helpers.txt", "r+") for line in f: line = line.replace("\n", "") data = line.split(", ") helpers.append([data[0], data[1]]) f.close() print "Done. Ready to scan." while True: if serial.inWaiting() > 0: read_result = serial.read(12) rfid = format(read_result.decode(encoding="utf-8")) if len(rfid) == 12: rfid = rfid[1:11] print("Read card " + rfid) for student in helpers: if(rfid == student[0]): print "You are " + student[1] send_data["id"] = student[1] send["data"] = json.dumps(send_data) print requests.post(url, data=send).text else: print("Misread card") print("Please wait for 1 second..."); time.sleep(1) serial.flushInput() # ignore errors, no data else: time.sleep(0.1)