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
Beispiel #2
0
def macro(code,expected_reply,timeout,error_msg,delay_after):
	global s_error	
	serial_reply=""
	macro_start_time = time.time()
	serial.write(code+"\r\n")
	time.sleep(0.3) #give it some toie 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):
			#trace_msg="failed macro (timeout):"+ code+ " expected "+ expected_reply+ ", got:"+ serial_reply
			trace(trace_msg,log_trace)
			if not error_msg=="":
				trace("FAILED : "+error_msg,log_trace)
				s_error+=1
				summary()
			#print "error!"
			return False #leave the function
			
		serial_reply=serial.readline().rstrip()
		#print serial_reply
		#add safety timeout
		time.sleep(0.1) #no hammering 
		pass

	trace("OK : " + error_msg,log_trace)	
	time.sleep(delay_after) #wait the desired amount
	return serial_reply
Beispiel #3
0
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 serializeFromSerial():
 serial.open()
 data = serial.readline() # Read the next line from serial
 serial.close()
 print(data) # Print the data to terminal for debugging purposes
 j = json.loads(data) # Load the raw string as JSON
 return j # Return the JSON
Beispiel #5
0
def get_demand_chunk(serial):
    # FIXME Bug where it never re-syncs if reads start mid-block. Needs a rewrite.

    buf = ''
    in_element = False
    closestring = '</InstantaneousDemand>'

    while True:
        in_buf = serial.readline()
        in_buf_stripped = in_buf.strip()
        log.debug('>' + in_buf_stripped)

        if not in_element:
            if in_buf_stripped == '<InstantaneousDemand>':
                in_element = True
                buf += in_buf
                closestring = '</InstantaneousDemand>'
                continue
            elif in_buf_stripped == '<CurrentSummationDelivered>':
                in_element = True
                buf += in_buf
                closestring = '</CurrentSummationDelivered>'
                continue
            else:
                continue

        if in_element:
            buf += in_buf

        if in_buf_stripped == closestring:
            log.debug('got end of xml')
            return buf
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
Beispiel #7
0
def get_demand_chunk(serial):

    buf = ""
    in_element = False
    closestring = "</InstantaneousDemand>"

    while True:
        in_buf = serial.readline()
        in_buf_stripped = in_buf.strip()
        log.debug(">" + in_buf_stripped)

        if not in_element:
            if in_buf_stripped == "<InstantaneousDemand>":
                in_element = True
                buf += in_buf
                closestring = "</InstantaneousDemand>"
                continue
            elif in_buf_stripped == "<CurrentSummationDelivered>":
                in_element = True
                buf += in_buf
                closestring = "</CurrentSummationDelivered>"
                continue
            else:  # Keep waiting for start of element we want
                continue

        if in_element:
            buf += in_buf

        if in_buf_stripped == closestring:
            log.debug("got end of xml")
            return buf
Beispiel #8
0
def updateData(serial):
    try:
        if serial.in_waiting > 0:
            linha_de_dados = serial.readline().decode('utf-8')
            print(linha_de_dados)

            if(linha_de_dados != ""):
                linha_de_dados = linha_de_dados.replace("\r\n", "")
                if linha_de_dados.startswith("!") and linha_de_dados.endswith("@"):
                    linha_de_dados = linha_de_dados.replace(" ", "")
                    linha_de_dados = linha_de_dados.replace("!", "")
                    linha_de_dados = linha_de_dados.replace("@", "")
                    dados = linha_de_dados.split(";")
                    receivedChecksum = 0
                    calculatedChecksum = 0
                    tempDicioDeDados = {}
                    for dado in dados:
                        try:
                            apelido, valor = dado.split("=")
                            if apelido == 'gyz':
                                print(valor)
                            if apelido != 'cks':
                                calculatedChecksum += float(valor)
                                tempDicioDeDados[apelido] = float(valor)
                            else:
                                receivedChecksum = valor
                        except:
                            pass

                        # if abs(float(receivedChecksum) - float(calculatedChecksum)) <=1:
                        #   dicioDeDados.update(tempDicioDeDados)
    except:
        pass
Beispiel #9
0
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))
Beispiel #10
0
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
Beispiel #11
0
def jsControl():
    buttonSelectMem = False
    zProbeDown = False
    
#     updateConsole(True, consoleStr)
    
    while 1:
        try:
            status = js.getStatus()
        except:
            console1.setPrependString('Joystick disconnected!\n')
            break
            
    
        if status['ButtonCircle']:
            console1.setPrependString('Joystick Jog aborted\n')
            break
        
        if status['ButtonTriangle']:
    		macro("M999", "ok", 1, "reset", 0)
    		
    
    		
    	''' Lower and raise z-probe with select button '''	
        if status['ButtonSelect'] and (not buttonSelectMem):
            buttonSelectMem = True
            if not zProbeDown:
#                 macro("M401","ok",1,"probe down",0)
                serial.write("M401\r\n")
                serial.readall()
                zProbeDown = True
            else:
#                 macro("M402","ok",1,"probe up",0)
                serial.write("M402\r\n")
                serial.readall()
                zProbeDown = False
        elif (not status['ButtonSelect']) and buttonSelectMem:
            buttonSelectMem = False
    		
    		
        gCode, move = calculateGcode(status)
    
        if move:
    
            serial.write(gCode + "\r\n")
            serial.readline().rstrip()
            console1.updatePosition(console1.stringToPos(gCode))
def receiveMessage ():
    global ser
    while True:
        findKeyPass()
       # if serInt > 0:
        #    serInt = randomKey
         #   receivedMessage = ser.read() 
    #receivedMessage = ser.readline() #Reads the incoming, wirelessly transmitted encrypted message from other device
    while True:
        if (keyPassFound == True):
            keyPassRead = serial.readline()
            print ("\nReceived encrypted message: ")
            print ("keyPassRead")
        sleep(.5)
        print("\nDecoding..")
    #chars = []
    #Loop through the message and print out the decoded values
    #for ch in receivedMessage:    #Messages are separated by spaces by default to distinguish words
     #   decodedMessage = decodedMessage + chr(ord(receivedMessage.split()[ch] - randomKey))   #Get the corresponding letter to Unicode number
        #codeMsg = eval(splitMsg)    #Converts digits to a number                           #and further decodes it with randomized key generated.
        #chars.append(chr(ord()code))     #Accumulates characters
    #decodedMessage = "".join(chars)           #Message is formed from characters
    for symbol in enterMessageToDecode:
            charCode = ord(symbol)
            randomKey1 = randomKey
            randomKey1 = int(randomKey * randomKey / 2)
            randomKey2 = int(randomKey1 / (randomKey / 3))
            randomKey3 = int(randomKey2) - abs(int(randomKey)) - abs(int(randomKey))
            randomKey3 -= int(abs(randomKey * 1.5))
            randomKey1 = randomKey3
            charCode -= randomKey1    
            if charCode > ord('z'):
                charCode -= 26
            if symbol.isupper():
                if charCode > ord('Z'):
                    charCode -= 26
                elif charCode < ord('A'):
                    charCode += 26    
            elif symbol.islower():
                if charCode > ord('z'):
                    charCode -= 26
                elif charCode < ord('a'):
                    charCode += 26 
                translated += chr(charCode)
            else:
                translated += symbol
    print("\n    Decrypted message: ")
    print(translated)
    seenMessage = input("\nContinue receiving messages? (Yes / No): \n\n")    #Asks if user wants to keep receiving messages or switch
    if (seenMessage == "Yes") & (seenMessage == "yes"):
        changeMode = False
        startInterface()                     #If yes, go back to main interface and skip setup screen
    elif (seenMessage == "No") & (seenMessage == "no"):
        changeMode = True
        startInterface()                     #If no, go back to main interface and set up sending / receiving
    else: 
        print("\nCommand not understood!\n\n")
        changeMode = False
        startInterface()
def motorThread(threadName, delay):
 count = 0
 while 1:
  print "Motor control thread started."
  motorRX = sys.stdin.readline()
  if motorRX is "RX":
    
    	sys.stdout.write(serial.readline())
def keypadThread(threadName, delay):
 count = 0
 while 1:
  print "Keypad thread started."
  keypadRX = sys.stdin.readline()
  if keypadRX is "RX":
    
    	sys.stdout.write(serial.readline())
Beispiel #15
0
def waitfordone(serial):
    while True:
        serialmsg = serial.readline().decode("UTF-8")
        print(serialmsg)
        if "Done" in serialmsg:
            return 0  # no error
        elif "Zero Error" in serialmsg:
            return 1  # error
Beispiel #16
0
def query_arduino():
    global serial
    serial = serial.Serial('/dev/ttyACM0', 9600)
    serial.write('1')
    query = serial.readline().strip('\r\n').split()
    fo = open('/etc/scripts/.arduino.db', 'wb')
    fo.write(','.join(query))
    fo.close()
Beispiel #17
0
def listener():
	global received
	global sent
	global resend
	
	global ext_temp
	global bed_temp
	global ext_temp_target
	global bed_temp_target
	
	serial_in=""	
	while not EOF:
		while serial_in=="":
			serial_in=serial.readline().rstrip()
			#time.sleep(0.05)
			pass #wait!
		
		#if there is serial in:
		#parse actions:
		
		##ok
		if serial_in=="ok":
			#print "received ok"
			received+=1
			#print "sent: "+str(sent) +" rec: " +str(received)

		##error
		if serial_in[:6]=="Resend":
			#resend line
			resend=serial_in.split(":")[1].rstrip()
			received-=1 #lost a line!
			trace("Error: Line no "+str(resend) + " has not been received correctly")
			
		##temperature report	
		if serial_in[:4]=="ok T":
			#Collected M105: Get Extruder & bed Temperature (reply)
			#EXAMPLE:
			#ok T:219.7 /220.0 B:26.3 /0.0 T0:219.7 /220.0 @:35 B@:0
			
			temps=serial_in.split(" ")
			ext_temp=float(temps[1].split(":")[1])
			ext_temp_target=float(temps[2].split("/")[1])

			bed_temp=float(temps[3].split(":")[1])
			bed_temp_target=float(temps[4].split("/")[1])
			received+=1
			
		## temp report (wait)	
		if serial_in[:2]==" T:":	
			#collected M109/M190 Snnn temp (Set temp and  wait until reached)
			# T:187.1 E:0 B:59
			temps=serial_in.split(" ")
			ext_temp=float(temps[0].split(":")[1])
			bed_temp=float(temps[2].split(":")[1])
			#ok is sent separately.
			
		#clear everything not recognized.
		serial_in=""
def send_string(serial, string):
    message = "{0}{1}{2}".format(
        chr(2),
        string,
        chr(13)
    ).encode()
    logger.debug("sending to serial %s: %s\n", serial.name, message)
    serial.write(message)
    return " ".join(serial.readline().decode().split()[1:])
	def RecieveSerial(self, device):
		for serial in self.serialPorts:
			if serial.port == device:
				print "Trying to read"
				serial.write(NEXT_DATA.encode())
				lastReadData = serial.readline().strip('\r\n')
				print "data read = " + lastReadData
				return lastReadData
		raise ErrorRecievingData("cannot recieve data from serial port {}".format(device))
Beispiel #20
0
def read_serial(gcode):
	serial.flushInput()
	serial.write(gcode + "\r\n")

	response=""
	while (response==""):
		response=serial.readline().rstrip
		if response!="":
			return response
Beispiel #21
0
def get_next_event():
    while True:
        if use_serial:
            line = serial.readline()
        else:
            line = raw_input()
        strings = line.split()
        if len(strings) != 2:
            continue
        return tuple(int(v) for v in line.split())
def get_data_from_serial(serial):
    serialOutput=serial.readline()
    # print serialOutput
    serialTuple=serialOutput.split(",")
    if len(serialTuple)!=3:
        return None
    for i in range(len(serialTuple)):
        try:serialTuple[i]=float(serialTuple[i].strip())
        except: return None
    x, y, z = serialTuple[0],serialTuple[1],serialTuple[2]
    t=time.time()
    return t,x,y,z
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
Beispiel #24
0
def main():
    print "Iniciado"
    while 1:
        command = serial.readline()
        print 'Recieved from NODEMcu: ' + command

        if command == 'respuesta\n':
            enviar = '04'
            print 'Send to Node: ' + str(enviar.decode("hex"))
            serial.write(enviar.decode("hex"))

    return
Beispiel #25
0
def listener():
    global received
    global sent
    global resend
    global EOF
    global ext_temp
    global bed_temp
    global ext_temp_target
    global bed_temp_target
    global tip
    global tipMessage
    global killed
    
    serial_in=""
    
    while not EOF:
        while serial_in=="":
            try:
                serial_in=serial.readline().rstrip()
                pass
            except SerialException as err:
                print "ERROR: " + str(err)
                trace(str(err))
        if serial_in=="ok":
            received+=1
        try: #''' READ SERIAL REPLYs '''
            if serial_in[:6]=="Resend":
                #resend line
                resend=serial_in.split(":")[1].rstrip()
                received-=1 #lost a line!
                trace("Error: Line no "+str(resend) + " has not been received correctly")
            elif serial_in[:4]=="ok T":
                temperatures = gcode_utils.read_temperature_line(serial_in)
                ext_temp = temperatures[0]
                ext_temp_target = temperatures[1]
                bed_temp = temperatures[2]
                bed_temp_target = temperatures[3]
                received+=1
            elif serial_in[:2]=="T:":
                temperatures = gcode_utils.red_wait_temperature_line(serial_in)
                ext_temp = temperatures[0]
                if temperatures[1] != '':
                    bed_temp = temperatures[1]
        except IndexError as err:
            trace(str(err))
        serial_in=""
        if(sent>20 and bed_temp < 45):
            tip=True
            tipMessage="the bed is cooling check connections"
        elif(sent>20 and bed_temp > 45):
            tip=False
            tipMessage=""
Beispiel #26
0
def sendGPSData(serial, queue):
#    print("serial: %s" % serial)
    soc = queue.get()
    count = 1
    while True:
        try:
#    print('s: %s' % s)
            msg = serial.readline().decode()
            if( count%150 == 0 ):
                print('gps msg: %s' % msg)
            count += 1
            nmea_msg = pynmea2.parse(msg)
#            print("%s\n" % nmea_msg)
#    nmea_msg = pynmea2.parse(s.readline().decode())
#    nmea_msg = pynmea2.parse(s.readline().decode())
#            print('nmea_msg: %s' % nmea_msg)
#    print('nmea_msg.sentence_type: %s' % nmea_msg.sentence_type)
            if nmea_msg.sentence_type == "RMC":
#                print("%s\n" %nmea_msg)
#                print('Latitude: %d, %s' % (nmea_msg.latitude, nmea_msg.lat_dir))
                # print('Longitude: %d, %s' % (nmea_msg.longitude, nmea_msg.lon_dir))
                # print('GPS Heading: %d' % nmea_msg.true_course)
                # print('Date/Time: %s\n' % datetime.datetime.combine(nmea_msg.datestamp, nmea_msg.timestamp).isoformat())
                soc.sendall(msg.encode())
#                soc.send(nmea_msg.encode('utf-8'))
                time.sleep(0.1)
            else:
                print('wrong msg: %s' % nmea_msg)
        except pynmea2.nmea.ChecksumError as ce:
#            print("ChecksumError: %s" % ce)
            pass
        except pynmea2.nmea.ParseError as pe:
#            print("ParseError: %s" % pe)
            pass
        except UnicodeDecodeError as ud:
            print("UnicodeDecodeError: %s" % ud)
            pass
        except AttributeError as ae:
#            print("AttributeError: %s" % ae)
            pass
        except ValueError as ve:
            print("ValueError: %s" % ve)
            pass
        except TypeError as te:
            print("TypeError: %s" % te)
            pass
        except:
            traceback.print_exc(file=sys.stdout)
            print("closing serial port")
            soc.close()
            serial.close()
            break
Beispiel #27
0
    def run(self):
        while not self._stop.isSet():
            line = serial.readline()
            if line == '':
                continue
            try:
                values = line.split()
                values = [int(v) for v in values]
                plots[0].value = values[0]
                plots[1].value = values[1]
            except:
                print 'Invalid', line

        print 'stopping'
def read(serial):
    temp_f = serial.readline()
    # Adjust the temperature according to the configured offset.
    temp_f_adjusted = temp_f + config["temp_offset"]
    temp = "{0:.2f}".format(temp_f_adjusted)

    date = datetime.utcnow()
    time = calendar.timegm(date.utctimetuple())

    # Send data to temperature logger.
    postTempData(config["sensor_id"], temp, time)

    # Log data to command line.
    print "{0}, {1}".format(date, temp.rstrip())
Beispiel #29
0
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
Beispiel #30
0
def listener():
    
    global received
    global sent
    global resend
    global EOF
    
    global killed
    
    serial_in=""    
    while not EOF:
        
        while serial_in=="":
            try:
                serial_in=serial.readline().rstrip()
            #time.sleep(0.05)
                pass #wait!
            except SerialException as err:
                trace(str(err))
        
        #if there is serial in:
        #parse actions:
        #print "rcv" + str(serial_in)
        
        ##ok
        if serial_in=="ok":
            #print "received ok"
            received+=1
            #print "sent: "+str(sent) +" rec: " +str(received)
        
        ##error
        
        try:
            if serial_in[:6]=="Resend":
                #resend line
                resend=serial_in.split(":")[1].rstrip()
                received-=1 #lost a line!
                trace("Error: Line no "+str(resend) + " has not been received correctly")
        
        except IndexError as err:
            trace(str(err))
        #print "BED: "+str(bed_temp) + " EXT: "+ str(ext_temp)
        #ok is sent separately.
        
    #clear everything not recognized.
        serial_in=""
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")
        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
                else:
                    s_warning += 1
                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
Beispiel #32
0
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
Beispiel #33
0
def on_state():
    serial.write("M105\n".encode('ascii'))
    time.sleep(0.5)
    tem_message = serial.readline()
    tem_message = bytes.decode(tem_message)
    tem = re.findall(r"\d+\.?\d*", tem_message)
    time.sleep(1)
    print(tem)
    if len(tem) == 0:
        tem = ['0', '0', '0', '0', '0']
    payload_json = {
        'id': 1,
        'status': {
            'chambertemperature': float(tem[0]),
            'bedtemperature': float(tem[2])
        },
        'on_off': 1,
        'printing': ps.printing,
        'endprint': ps.endprint,
        'startprint': ps.startprint
    }
    sio.emit('status', payload_json)
    print("打印机状态发送state")
Beispiel #34
0
def read_serial_data(serial):
    """
	Given a pyserial object (serial). Outputs a list of lines read in
	from the serial port
	"""

    serial.flushInput()

    readings_left = True
    timeout_reached = False

    sms = ""
    timeout = timeout_const

    while readings_left and not timeout_reached:
        serial_line = serial.readline()
        if serial_line.find("Temperature: ") == 0:
            sms = serial_line.partition(": ")[2]
        timeout -= 1
        if (timeout == 0):
            timeout_reached = True
    print sms
    return sms
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

    print(serial_data)

    return serial_data
Beispiel #36
0
def get_thresholds():
    message = ''
    values = []
    success = False

    pad_side = int(request.args.get('padSide'))
    if pad_side == 1 or pad_side == 2:
        try:
            if pad_side == 1:
                serial = serial_p1
            else:
                serial = serial_p2
            serial.write("thresholds".encode())
            s_resp = serial.readline().decode().strip()
            message = f"P{pad_side} Thresholds: {s_resp}"
            values = [int(x) for x in s_resp.split(',')]
            success = True
        except Exception as e:
            message = str(e)
    else:
        message = 'Must specify pad side 1 or 2.'

    return {'message': message, 'values': values, 'success': success}
Beispiel #37
0
def on_file(file):
    print("接收到打印文件")
    sio.emit('file', 'getting')
    fp = open("printfile.gcode", 'w')
    fp.writelines(file)
    fp.close()
    #sio.emit('file','got' )
    filename = "printfile.gcode"
    gcodelist = read_gcode(filename)
    ps.startprint = 1
    ps.printing = 1
    serial.write("M105\n".encode('ascii'))
    time.sleep(0.5)
    tem_message = serial.readline()
    tem_message = bytes.decode(tem_message)
    tem = re.findall(r"\d+\.?\d*", tem_message)
    time.sleep(0.5)
    print(tem)
    if len(tem) == 0:
        tem = ['0', '0', '0', '0', '0']
    payload_json = {
        'id': 1,
        'on_off': 1,
        'status': {
            'chambertemperature': float(tem[0]),
            'bedtemperature': float(tem[1])
        },
        'printing': ps.printing,
        'endprint': ps.endprint,
        'startprint': ps.startprint
    }
    sio.emit('status', payload_json)
    print(payload_json)
    ps.startprint = 0
    print("开始打印")
    print_model(gcodelist, serial, sio)
Beispiel #38
0
def readmeteo(serial):
    '''
        Read data from Meteo
        '''
    try:
        dane = serial.readline()

        ser.flushInput()
        ser.flushOutput()

        meteo = dane.split(',')[1:-2]
        U = meteo[0]
        V = meteo[1]
        p = meteo[2]
        temp = meteo[3]
        rh = meteo[4]
        td = meteo[5]
        volt = meteo[6]

        return [U, V, p, temp, rh, td, volt]

    except Exception as e:
        print("Meteo data read error: {}".format(e))
        return 1
def background_thread():
    serial = Arduino('/dev/ttyACM0', 9600)

    temp = DataType.get_or_create('Temperatura', 'float')
    hume = DataType.get_or_create('Humedad', 'int')
    pre = DataType.get_or_create('Presion', 'int')

    while True:
        data = serial.readline().strip()
        tm = datetime.now()
        if (data and data != 'fail'):
            data = data.split(',')
            captura = {'time': tm, 'temperatura': data[0], 'humedad': data[1],
                            'presion': data[2]}
            socketio.emit('EMA data', captura, namespace='/test')

            temp.data.append(Data(timestamp=tm, value=data[0]))
            hume.data.append(Data(timestamp=tm, value=data[1]))
            pre.data.append(Data(timestamp=tm, value=data[2]))
            temp.save()
            hume.save()
            pre.save()

        time.sleep(2)
Beispiel #40
0
def on_file(file):
    global printing
    global endprint
    global startprint
    print("接收到打印文件")
    sio.emit('file','getting' )
    fp = open("printfile.gcode",'w') 
    fp.writelines(file) 
    fp.close() 
    sio.emit('file','got' )
    filename = "printfile.gcode"
    gcodelist = read_gcode(filename)
    startprint = 1
    printing = 1
    receiving = 0
    serial.write("M105\n".encode('ascii') )
    time.sleep(0.5)
    tem_message=serial.readline()  
    time.sleep(0.5)
    payload_json = {
                    'id': 1,
                    'statue': {
                        'chambertemperature':random.randint(1,20),
                        'bedtemperature':random.randint(1,20)
                    },
                    'on_off': 1,
                    'printing':printing,
                    'endprint':endprint,
                    'startprint':startprint,
                    'receiving':receiving
                    }
    sio.emit('state', payload_json)
    startprint = 0
    print("开始打印")
    print(payload_json)
    print_model(gcodelist,serial,sio,printing,endprint,startprint)
Beispiel #41
0
def Radar_INIT(serial):
    log = open(INIT_FILE, "r")
    while True:
        line = log.readline()
        lenght = len(line)
        if(lenght>9):
            if line[10] is not '%' and line[0:10] == 'mmwDemo:/>':
                serial.write(line[10:lenght].encode("utf-8")+b'\n')
                t1 = time.perf_counter()
                while True:
                    res = serial.readline()
                    print(res)
                    if res == b'Done\n':
                        break
                    sleep(0.05)
                    #break
                    if time.perf_counter() > t1 + 0.3:  # wait 1 sec
                        serial.write(line[10:lenght].encode("utf-8") + b'\n') #repeat sending
                        t1 = time.perf_counter()

        if line[0] == 'q':
            print("END OF FILE")
            break
    log.close()
Beispiel #42
0
def rcv_data(queue):
    i = 0
    while True:
        rcv = serial.readline()
        rcv = rcv.decode()
        if rcv == "\r\n":
            time.sleep(0.1)
            continue
        print("收到消息: " + str(rcv[0:-2]))
        if queue.full():
            print("队列queue已满")
        else:
            if rcv[0:14] == "+CM2MCLIRECV: ":
                queue.put(rcv[14:])
                print("rcv_data: " + str(rcv[14:-2]))
            if rcv[0:10] == "+CM2MCLI: ":
                cm2mcli_code = rcv[10:-2]
                print("+CM2MCLI code: " + str(cm2mcli_code))
            if rcv == "ERROR":
                print("is ERROR")

        i = i + 1
        print("rcv_data循环次数: " + str(i))
        time.sleep(0.1)
Beispiel #43
0
def serial_read(serial):
    read = serial.readline().decode()
    #print('read "{}"'.format(read));
    return read
Beispiel #44
0

def initArduino(serialPort):
    try:
        print("Trying to connect on serial port " + serialPort)
        ser = serial.Serial(serialPort, baudrate=115200)
        print("Connection successful")
        return ser
    except:
        newSerialPort = input(
            "Connection failed. Input the name of your serial port and press enter : "
        )
        return initArduino(newSerialPort)


def processData(json):
    print(json)


if __name__ == "__main__":
    serial = initArduino(port)
    serial.flush()
    serial.readline()
    while True:
        try:
            command = serial.readline().decode('utf-8')
        except UnicodeDecodeError as e:
            print(e, file=sys.stderr)
        else:
            processData(command)
    def play_bass(self):
        bass = self.mixer.Sound('bass.wav')
        bass.play(loops=0, maxtime=0, fade_ms=0)

    def play_cymbal(self):
        cymbal = self.mixer.Sound('cymbal.wav')
        cymbal.play(loops=0, maxtime=0, fade_ms=0)


try:
    drums = Drums()
    # loop through the midi messages received
    while True:
        # read the midi msg
        midi_read = serial.readline()
        midi_read = midi_read.split(".")
        current_time = time.time()
        if midi_read[0] != "Starting":
            midi_msg = {
                'note_cmd':
                'note_on' if int(midi_read[0]) == 90 else 'note_off',
                'note': int(midi_read[1]),
                'velocity': int(midi_read[2]),
                'timedelta': int(current_time - start_time)
            }
        else:
            print "%s" % (midi_read[0])
            continue

        # print and append midi msg
Beispiel #46
0
def rcv_data():
    while True:
        rcv = serial.readline()
        rcv = rcv.decode()
        print("a" + str(rcv))
Beispiel #47
0
#!/usr/bin/env python

import serial
import time

serial = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
cpt = 0

while 1:
    serial.write('{}'.format(cpt))
    time.sleep(0.1)

    try:
        reading = serial.readline().decode()
        print 'esp: ' + reading
        cpt = cpt + 1
    except:
        print 'serial error'
Beispiel #48
0
def read_input(serial):
    '''Reads line from serial.'''
    line = serial.readline()
    symbol = line.decode('utf-8')
    symbol = symbol.strip()
    return symbol
def gpio_set_direction(serial, gpio, value):
    t = "gpio" + str(gpio) + ".direction " + hex(value) + "\r"
    serial.write(t.encode())
    serial.readline()
def ReadSerial(serial):

    return serial.readline().replace("\r\n", "")
Beispiel #51
0
import mysql.connector
import serial
import time
serial = serial.Serial('COM4', baudrate=9600, timeout=10)
#print "s"
while True:
    con = mysql.connector.connect(
        user="******", password="", host="localhost",
        database="db_traffic") or die("Gagal menyambunbgkan kedatabase")

    m = con.cursor()
    q = "SELECT * FROM informasi ORDER by id DESC LIMIT 1"
    m.execute(q)

    rez = m.fetchall()

    for el in rez:
        data = el[1] + "|" + el[2] + "|" + el[3]
        print data

    serial.write(bytes(data))
    try:

        a = serial.readline()
        print(a)
        con.close()
        time.sleep(2)
    except:
        print "Gagal"
Beispiel #52
0
def updateViaSerialPort(interval):
    data = serial.readline()
    updatePressure(data.decode('utf-8'))
import serial
import time

port = "/dev/ttyS0"  # Raspberry Pi 3

serial = serial.Serial(port, baudrate=9600, timeout=3)
print "starting"
text = ""
while (text != "exit\n"):
    text = serial.readline()
    if (text != ""):
        print("Android: " + text + "\n")

    send = raw_input()
    if (send != ""):
        serial.write("PC: " + send + " \r\n")
Beispiel #54
0
    # make stdin a non-blocking file
    fcntl.fcntl(sys.stdin, fcntl.F_SETFL, os.O_NONBLOCK)

    # post startup message to other XBee's and at stdout
    serial.writelines("RPi #1 is up and running.\r\n")
    print "RPi #1 is up and running."

    #switchColor(CMD_OUTPUT_TEXT)
    print "Entering loop to read and print messages (Ctrl-C to abort)..."

    try:
        while True:
            # read a line from XBee and convert it from b'xxx\r\n' to xxx and print at stdout
            #switchColor(TERM_OUTPUT_TEXT)

            line = serial.readline().decode('utf-8')
            if line:
                line = line.split('\n')[0]
                print line
                user = line.split(' ')[0].split('=')[1]
                humidity = line.split(' ')[1].split('=')[1]
                temperature = line.split(' ')[2].split('=')[1]
                gas = line.split(' ')[3].split('=')[1]

                print humidity
                print temperature
                print user
                #User entry exit status

                if user == '1':
                    print "hello........"
Beispiel #55
0
import sys
import serial
import serial.tools.list_ports
from time import sleep
import time

target_VCP_vidpid = '0403:6015'

ports = list(serial.tools.list_ports.comports())
for p in ports:
    if (p.hwid.find(target_VCP_vidpid) != -1):
        print p.device
        SLS_COMPORT = p.device

serial = serial.Serial(SLS_COMPORT, 115200, timeout=0)

while 1:

    try:
        message = serial.readline()
        sleep(0.05)
        if message != '':
            sys.stdout.write(message)
            sys.stdout.flush()
        if (message.find('Ready') != -1):
            serial.write("")

    except serial.SerialTimeoutException:
        print('Data could not be read')
Beispiel #56
0
import serial

serial = serial.Serial('COM3', baudrate=9600, timeout=1)

while 1:
    data = serial.readline().decode('ascii')
    print(data)
def gpio_write(serial, gpio, value):
    t = "gpio" + str(gpio) + ".write " + hex(value) + "\r"
    serial.write(t.encode())
    serial.readline()
    'Umidade média: ': None,
    'Luminosidade: ': None
}
temp_data = []
umi_data = []
lumi_data = []

while True:
    try:
        # serial_data = serial.readline()
        serial.flushInput()
        try:
            for num in range(1, 10):
                """ Desenvolver função para leitura, unpacking e decoding """

                decoded_data = decode_format(serial.readline())
                working_data1 = unpack_data(decoded_data)
                temp_data.append(
                    working_data1.get('Temperatura:')
                )  # Adiciona dado a lista para cálculo de média
                sleep(2)
                decoded_data = decode_format(serial.readline())
                working_data2 = unpack_data(decoded_data)
                umi_data.append(working_data2.get(
                    'Umidade:'))  # Adiciona dado a lista para cálculo de média
                sleep(2)
                decoded_data = decode_format(serial.readline())
                working_data3 = unpack_data(decoded_data)
                lumi_data.append(
                    working_data3.get('Luminosidade:')
                )  # Adiciona dado a lista para cálculo de média
Beispiel #59
0
        #Touches 4 times the bed in the same position
        probes = num_probes  #temp
        point[2] = ["" for x in range(num_probes)]  #np.empty(num_probes)

        if (
                p == 0
        ):  # This executes the measurement of the excluded measurements given by exclude_N_meas_first_point, which are well...excluded from the data returned
            for j in range(exclude_N_meas_first_point):
                serial_reply = ""
                serial.flushInput()
                #G38
                serial.write("G38 S" + str(feedrate) + "\r\n")
                #time.sleep(0.5)                        #give it some to to start
                probe_start_time = time.time()
                while not serial_reply[:22] == "echo:endstops hit:  Z:":
                    serial_reply = serial.readline().rstrip()
                    #issue G38 and waits reply.
                    if (time.time() - probe_start_time >
                            240):  #timeout management
                        break
                macro("G0 Z" + str(zp) + " F5000",
                      "ok",
                      10,
                      "Rising Bed",
                      0,
                      warning=True,
                      verbose=False)

        for i in range(0, num_probes):
            # Raise probe first, to level out errors of probe retracts?!?
            #			if (retractProbe == True):
Beispiel #60
0
def getScore(self):
    score = serial.readline()
    self.Fire.post('/scores', score, {'print': 'pretty'})