示例#1
0
def summary():
	trace("SUMMARY:",log_trace)
	trace("Errors  : " + str(s_error),log_trace)

	if s_error==0:
		trace("Result  : No errors occurred.",log_trace)
	else:
		trace("Self Test FAILED",log_trace)


	if online==1:
		print "Saving results on remote server"
		url = 'http://plm.fabtotum.com/reports/add_report.php'
		files = {'file': open(log_trace, 'rb')}
		info={'ID':controller_serial_id, 'result':s_error}
		try:
			r = requests.post(url,info, files=files)
			trace("Self Test results saved online",log_trace)
		except:
			#print "Response: " + r.text
			trace("Could not contact remote support server, is Internet connectivity available?",log_trace)
	if s_error>0:
		#clean the buffer and leave
		#shutdown temps
		
		serial.write("M104 S0\r\n") #shutdown extruder (fast)
		serial.write("M140 S0\r\n") #shudown bed (fast)
		serial.flush()
		serial.close()
		write_json('1', status_json)
		call (['sudo php /var/www/fabui/script/finalize.php '+str(task_id)+" self_test"], shell=True)

		sys.exit()
示例#2
0
def send_ping_cmd(serial):
    #in python, we can simply write down the MessagePack message and it is automatically built
    #here is an order called "ping" which has a string as data
    msg = msgpack.packb({'ping': 'Hello there :-)'}, use_single_float=True)
    dtgrm = serial_datagram.encode(msg)
    serial.write(dtgrm)
    serial.flush()
示例#3
0
文件: bars.py 项目: Avnet/raspberrypi
 def __init__(self, serial, timeout=10, debug=False, dbgFileName=""):
     self.__dbgFileName = dbgFileName
     try:
         if dbgFileName <> "":
             self.__dbgOutput = open(dbgFileName, 'w+')
     except KeyboardInterrupt:
         exit(-1)
     except:
         print "Bad FILE name!"
         exit(-1)
     self.uart = serial
     self.timeout = timeout
     self.modem_type = "None"
     if serial.isOpen() == True:
         serial.flush()
         result = False
         # These are critical for getting the modem back after a reboot of the Pi
         self.send_mdm_cmd('\n', 1)
         self.send_mdm_cmd('AT', 1)
         self.send_mdm_cmd('\n', 1)
         self.send_mdm_cmd('AT', 1)
         self.send_mdm_cmd('\n', 1)
         self.send_mdm_cmd('AT', 1)
         result, resp = self.get_version()
         if debug == True:
             self.dbg = "Init type: " + str(resp)
         if result == False:
             print "AT ERR: " + resp
             if debug == True:
                 self.dbg = "Init AT ERR: " + str(resp)
         else:
             self.modem_type = resp
示例#4
0
def summary():
    trace("SUMMARY:",log_trace)
    trace("Errors  : " + str(s_error),log_trace)

    if s_error==0:
        trace("Result  : No errors occurred.",log_trace)
    else:
        trace("Self Test FAILED",log_trace)


    if online==1:
        print "Saving results on remote server"
        url = 'http://plm.fabtotum.com/reports/add_report.php'
        files = {'file': open(log_trace, 'rb')}
        info={'ID':controller_serial_id, 'result':s_error}
        try:
            r = requests.post(url,info, files=files)
            trace("Self Test results saved online",log_trace)
        except:
            #print "Response: " + r.text
            trace("Could not contact remote support server, is Internet connectivity available?",log_trace)
    if s_error>0:
        #clean the buffer and leave
        #shutdown temps
        
        serial.write("M104 S0\r\n") #shutdown extruder (fast)
        serial.write("M140 S0\r\n") #shudown bed (fast)
        serial.flush()
        serial.close()
        write_json('1', status_json)
        call (['sudo php /var/www/fabui/script/finalize.php '+str(task_id)+" self_test"], shell=True)

        sys.exit()
示例#5
0
def main():
    process_serial()
    drive_motors(100, 255, 1, 100, 255, 1)
    time.sleep(1)
    #drive_motors(100, 255, 0, 100, 255, 0)
    drive_motors(0, 0, 0, 0, 0, 0)
    #serial.write(OutgoingMessageType.debug, 0)
    #read_response_status(None, None)
    serial.flush()
示例#6
0
def get_sensor_datapoint(serial=ARDUINO):
    '''Gets sensor data from arduino.'''
    serial.flush()
    serial.read_all()
    serial.write('getTempHumidity\n'.encode())
    time.sleep(0.2)
    s = serial.readline().strip().decode()
    humidity, temp = s.split(',')
    return DataPoint(float(humidity), float(temp))
示例#7
0
def serial_cmd(cmd, serial):
    # send command to serial port
    serial.write(cmd + '\r')
    serial.reset_input_buffer()
    serial.reset_output_buffer()
    serial.flush()

    # read data from serial port
    c = serial.read(1300)
    return c
def write_packet(i, val):
    i = int(i)
    val = int(val)

    msb = (int(val) & 0xFF00) >> 8
    lsb = int(val) & 0xFF

    p = bytearray([i, msb, lsb])
    serial.write(p)
    serial.flush()
def write_packet(i, val):
    i = int(i)
    val = int(val)
    print ("SENDING {} {}".format(i, val))

    msb = (int(val) & 0xFF00) >> 8
    lsb = int(val) & 0xFF

    p = bytearray([i, msb, lsb])
    serial.write(p)
    serial.flush()
示例#10
0
def send_set_led_cmd(serial, led, action):
    #in python, we can simply write down the MessagePack message and it is automatically built
    #here is an order called "ping" which has a string as data
    #max uint8_t
    led = led & 255
    action = action & 255

    msg = msgpack.packb({'set_led': [led, action]}, use_single_float=True)
    dtgrm = serial_datagram.encode(msg)
    serial.write(dtgrm)
    serial.flush()
def moveTo(x, y):
    time.sleep(1)
    print("Moving to:", x, y)
    serial.write("moveTo".encode())
    time.sleep(3)
    xx = str(x)
    serial.write(xx.encode())
    done = serial.readline()
    print(done.decode())
    time.sleep(2)
    xx = str(y)
    serial.write(xx.encode())
    done = serial.readline()
    print(done.decode())
    print("written")
    time.sleep(1)

    done = serial.readline()
    print(done.decode())

    done = serial.readline()
    print(done.decode())

    done = serial.readline()
    print(done.decode())
    video = cv2.VideoCapture(0)
    ret, im = video.read()
    #cv2.imshow("test picutre", im)
    cv2.imwrite("test1.jpg", im)
    video.release()
    ''' config = {
    "apiKey": "AIzaSyAkRS3SPqdS2Jr4I4W_DKc7luoGpP33vQg",
    "authDomain": "cncproj-a880d.firebaseapp.com",
    "databaseURL": "https://sample-1886e.firebaseio.com/"''' "https://cncproj-a880d.firebaseio.com/", '''
    "storageBucket": "sample-1886e.appspot.com" ''' "cncproj-a880d.appspot.com" '''
    }'''

    config = {
        "apiKey": "AIzaSyAkRS3SPqdS2Jr4I4W_DKc7luoGpP33vQg",
        "authDomain": "sample-1886e.firebaseio.com",
        "databaseURL": "https://sample-1886e.firebaseio.com/",
        "storageBucket": "sample-1886e.appspot.com"
    }

    #print("here 1")
    firebase1 = pyrebase.initialize_app(config)
    #print("here 2")
    storage = firebase1.storage()
    #print("here 3")
    storage.child("example1.jpg").put(
        r"C:\Users\harsh\AppData\Local\Programs\Python\Python36\test1.jpg")
    serial.flush()
    #capture();
    return
示例#12
0
 def write(self, data, half_duplex=None):
     if half_duplex is None:
         half_duplex = self.half_duplex
     serial = self.serial
     data = self.encode(data)
     cnt = serial.write(data)
     serial.flush()
     if half_duplex:
         # Clean RX buffer in case of half duplex
         #   All written data is read into RX buffer
         serial.read(cnt)
示例#13
0
def serial_read(cmd, no, serial):
    # send command to serial port
    serial.write(cmd + '\r')
    #serial.reset_input_buffer()
    serial.reset_output_buffer()
    serial.flush()

    # read data from serial port
    c = serial.read(no)
    if (len(c) == 0):
        return 'NO CONN'
    else:
        return c
def initSerial(port, baudrate):
    serial.port = port
    serial.baudrate = baudrate
    serial.timeout = 1
    serial.writeTimeout = 1
    serial.open()
    serial.flush()
 
    logd( 'Opening port %s - %s' %(port, baudrate) )
    if serial.isOpen(): 
        logd('Success')
    else:
        logd('Failed')
        exit(2)
示例#15
0
def sendSignal(serial, data):
    """
    INPUT: string
    """
    serial.flush()  # wait for all the data is written

    # reformat data
    data = "<" + data + ">"
    # encode data
    encoded_data = str.encode(data)
    # send data
    serial.write(encoded_data)

    print(colored("SENT:\t ", 'red'), data)
示例#16
0
def initSerial(port, baudrate):
    serial.port = port
    serial.baudrate = baudrate
    serial.timeout = 1
    serial.writeTimeout = 1
    serial.open()
    serial.flush()

    logd('Opening port %s - %s' % (port, baudrate))
    if serial.isOpen():
        logd('Success')
    else:
        logd('Failed')
        exit(2)
示例#17
0
	def xmodem_send(self, serial, file):
		length = len(file.read()) / 128
		file.seek(0, 0)
		i = 1
		t, anim = 0, '|/-\\'
		serial.setTimeout(1)
		while 1:
			if serial.read(1) != NAK:
				t = t + 1
				print anim[t%len(anim)],'\r',
				if t == 60 : return False
			else:
				break

		p = 1
		s = file.read(128)
		while s:
			s = s + '\xFF'*(128 - len(s))
			chk = 0
			for c in s:
				chk+=ord(c)
			while 1:
				serial.write(SOH)
				serial.write(chr(p))
				serial.write(chr(255 - p))
				serial.write(s)
				serial.write(chr(chk%256))
				serial.flush()

				answer = serial.read(1)
				if  answer == NAK: continue
				if  answer == ACK: break
				return False
			s = file.read(128)
			p = (p + 1)%256
			
			# update progressbar
			progress = (100*i) / float(length)
			self.p["value"] = progress
			self.label2["text"] = str(round(progress, 2))+'%'
			self.win.update_idletasks()
			i += 1
			
		serial.write(EOT)
		if progress == 100:
			self.win.destroy()
			return True
		else:
			return False
示例#18
0
def readValue():
    line = (serial.readline()).decode()  # read a '\n' terminated line
    line = line[:-1]
    if (line == '1'):
        print('OK')
        inputVal_text.set('OK')
        intputVal.config(fg='green')
    elif (line == '2'):
        print('Alerte')
        inputVal_text.set('Alerte')
        intputVal.config(fg='red')
    else:
        print('distance de : ' + line + ' cm')
        outputVal_text.set('distance de : ' + line + ' cm')
    serial.flush()
示例#19
0
    def put(self, address, type, value):

        with self.__lock:

            result = None
            while result is None:
                serial = self.serial()

                try:
                    serial.write([address, 0, type, int(value)])
                    serial.flush()

                    result = True

                except Exception as e:
                    print e
                    self.__clean()
示例#20
0
    def put(self, address, type, value):

        with self.__lock:

            result = None
            while result is None:
                serial = self.serial()

                try:
                    serial.write([address, 0, type, int(value)])
                    serial.flush()

                    result = True

                except Exception as e:
                    print e
                    self.__clean()
示例#21
0
    def get(self, address, type):
        with self.__lock:

            result = None
            while result is None:
                serial = self.serial()

                try:
                    print type
                    serial.write([address, 1, type])
                    serial.flush()

                    result = struct.unpack('B', serial.read(1))[0]
                except Exception as e:
                    print e
                    self.__clean()

        return result
示例#22
0
    def get(self, address, type):
        with self.__lock:

            result = None
            while result is None:
                serial = self.serial()

                try:
                    print type
                    serial.write([address, 1, type])
                    serial.flush()

                    result = struct.unpack('B', serial.read(1))[0]
                except Exception as e:
                    print e
                    self.__clean()

        return result
示例#23
0
def initSerial(port, baudrate):
    # Serial port Configuration
    serial.port = "/dev/" + port
    serial.baudrate = baudrate
    serial.timeout = 1
    serial.writeTimeout = 1
    serial.open()
    serial.flush()

    logd('Opening port %s - %s' % (port, baudrate))

    serial.isOpen()

    if serial.isOpen():
        logd('Success')
    else:
        logd('Failed')
        exit(2)
示例#24
0
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
示例#25
0
def writeToSerial(serial, data):
    length = len(data)
    # initialize message buffer
    message = [0x00 for _ in range(length + 5)]
    # set first two start bytes
    message[0] = 0x10
    message[1] = 0x02
    # initialize checksum value (sum of start and end bytes)
    checksum = 0x25
    # fill message buffer with data and calculate checksum value
    for i in range(length):
        checksum += data[i]
        message[2 + i] = data[i]
    # set last two end bytes
    message[2 + length] = 0x10
    message[3 + length] = 0x03
    # add checksum value
    message[4 + length] = checksum & 0xFF  # truncate to one byte
    # write message
    serial.write(message)
    serial.flush()
示例#26
0
def getDistanceArray():

    # flush the buffer
    serial.flush()

    # This constant will request the values for all of the sensors
    sensorValsArray = []

    # Write that value to the Arduinos serial monitor
    amountOfSensors = 5

    # set inital value of i to the first sensor
    i = 1

    # set inital value of sensor val to 1 so the while loop is entered
    sensorVal = 1

    # while loop that asks for sensor values sequentially, converts them to an integer and adds them to an array
    while(sensorVal > -1):

        # ask for the sensor value from the arduino
        serial.write(str.encode(str(i)))

        # read the sensor value, conert it to an integer and store it in the temp variable
        sensorVal = int(serial.readline())

        # if the sensor was actually there store the value in the array
        if(sensorVal > -1):
            sensorValsArray.append(sensorVal)

        # delay
        time.sleep(0.01)

        # increment i to check for next sensor
        i += 1



    return sensorValsArray
示例#27
0
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()
示例#28
0
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()
示例#29
0
def to_arduino():
    working=0
    v=["99!","98!","97!","96!","95!","94!","93!","92!","91!","90!","89!","88!","87!","86!","85!","84!","83!","82!","81!","80!","79!","78!","77!","76!","75!","74!","73!","72!","71!","70!","69!","68!","67!","66!","65!","64!","63!","62!","61!","60!","59!","58!","57!","56!","55!","54!","53!","52!","51!","50!","49!","48!","47!","46!","45!","44!","43!","42!","41!","40!","39!","38!","37!","36!","35!","34!","33!","32!","31!","30!","29!","28!","27!","26!","25!","24!","23!","22!","21!","20!","19!","18!","17!","16!","15!","14!","13!","12!","11!","10!","9!","8!","7!","6!","5!","4!","3!","2!","2!","2!"]
    d=[7,7,7,7,7,6,6,6,6,6,5,5,5,5,5,4,4,4,4,4,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,2.5,2.5,2.5,2.5,2.5,2.25,2.25,2.25,2.25,2.25,2,2,2,2,2,1.85,1.85,1.85,1.85,1.85,1.75,1.75,1.75,1.75,1.75,1.6,1.6,1.6,1.6,1.6,1.5,1.5,1.5,1.5,1.5,1.35,1.35,1.35,1.35,1.35,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25,1.25]
    while True:
        if controller_h.state==1:
            try:
                controller_h.update()
                value = int(controller_h.dim)
                if value<0:
                    value=99
                delay=d[value]
                value=v[value].encode('UTF-8')
                if working == 0:
                    working =1
                    serial.close()
                    serial.open()
                    serial.write(value)
                    serial.flush()
                    serial.close()
                    time.sleep(delay)
                    working=0
            except:
                pass
示例#30
0
    time.sleep(dx * 0.02)  #take its time to move
    raspistill("_l")  #snap a pic with laser

    serial.write('M700 S0\r\n')  # Turn laser off
    raspistill("")  #snap a pic without laser

    percent = 100 * float(i) / float(slices)
    printlog(percent, i)
    pos += dx
    i += 1

#END of S_SCAN
serial.write('M700 S0\r\n')  # Turn laser off (you never know!)
serial.write('G0 X5 Y5\r\n')  #go to idle position

serial.write('M701 S255\r\n')  # Turn red on
serial.write('M702 S255\r\n')  # Turn green on
serial.write('M703 S255\r\n')  # Turn blue on

time.sleep(3)
serial.flush()
serial.close()  #close serial

print "Scan Completed!"

completed = 1
completed_time = float(time.time())
percent = 100
printlog(percent, i)

sys.exit()
def recieveSignal(serial):
    serial.flush()  # wait for all the data is written
    # Reading from arduino serial
    msg = serial.readline()
    print(colored("RECIEVED: ", 'blue'), msg)
    return msg
示例#32
0
udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
udp_socket.bind(udp_server_address)
if BROADCAST_MODE:
        udp_socket.setsockopt(socket.SOL_SOCKET,socket.SO_BROADCAST,1)

slip_processor=slip.slip()

while True:
        (rlist, wlist, xlist) = select.select([udp_socket,serial], [], [])
        if serial in rlist:
                serial_data = serial.read(1)
                slip_processor.append(serial_data)
                slip_packets=slip_processor.decode()
                for packet in slip_packets:
                        if BROADCAST_MODE:
                                udp_socket.sendto(packet,udp_broadcast)
                        else:
                                udp_socket.sendto(packet,udp_client_address)

        if udp_socket in rlist:
                udp_data,udp_client = udp_socket.recvfrom(MAX_UDP_PACKET)
                slip_data=slip_processor.encode(udp_data)
                serial.write(slip_data)
                serial.flush()
                udp_client_address=(udp_client[0],UDP_PORT_OUT)
                time.sleep(0.001) #avoid flooding the microcontroller (to be controlled)



示例#33
0
文件: updater.py 项目: burrrrrr/SDK
def xmodem_send(serial, file, quiet=True):
    SOH = bytes(bytearray([0x01]))
    EOT = bytes(bytearray([0x04]))
    ACK = bytes(bytearray([0x06]))
    NAK = bytes(bytearray([0x15]))
    NCG = b'C'
    DATA_SIZE = 128

    t = 0
    while True:
        if serial.read(1) != NCG:
            t = t + 1
            if t == 10:
                print('*', end='')
                sys.stdout.flush()
                return False
        else:
            break
    pn = 1
    file.seek(0)
    data = bytearray(file.read(DATA_SIZE))
    tx_size = 0
    while data:
        for i in range(DATA_SIZE - len(data)):
            data += bytes(bytearray([0xFF]))
        crc = calc_crc(data)
        MAX_RETRIES = 1
        retries = 0
        while True:
            serial.write(SOH)
            serial.write(bytes(bytearray([pn])))
            serial.write(bytes(bytearray([0xFF - pn])))
            serial.write(data)
            serial.write(bytes(bytearray([(crc & 0xFF00) >> 8])))
            serial.write(bytes(bytearray([crc & 0xFF])))
            serial.flush()
            answer = serial.read(1)
            if answer == NAK:
                if not quiet:
                    print('!', end='')
                    sys.stdout.flush()
                retries += 1
                if retries > MAX_RETRIES:
                    return False
                else:
                    continue
            if answer == ACK:
                retries = 0
                tx_size += DATA_SIZE
                if not tx_size % (1024 * 10):
                    print('.', end='')
                    sys.stdout.flush()
                break
            # If got nothing, exit
            serial.write(EOT)
            serial.flush()
            if not quiet:
                print('$', end='')
                sys.stdout.flush()
            return False
        data = bytearray(file.read(DATA_SIZE))
        pn = (pn + 1) % 256
    serial.write(EOT)
    serial.flush()
    answer = serial.read(1)
    if answer == NAK:
        return False
    return True
示例#34
0
def snd_bytearray_uart(msg):
    global serial
    byte = serial.write(msg)
    serial.flush()
    return byte
示例#35
0
while not rospy.is_shutdown():
    # main loop
    topOfFrame=time.time()
    # do our work
    # read data from the seral port if there is any
    serData = ser.read(1024)
    # process the data from the arduino
    # we don't want any blocking, so we use read and parse the lines ourselves
    holdBuffer = readBuffer(serData)
    #drive command
    com = ','  # comma symbol we use as a separator
    EOL = '\n'
    if robot.newCommand:
        ardCmd = "DRV"+str(robot.leftMotorCmd)+com+str(robot.rightMotorCmd)+EOL
        serial.write(ardCmd)
        serial.flush()  # output Now
    if frameKnt % (FRAMERATE/2)==0:  # twice per second
        hbMessage = "HBB"+com+str(time.time())+EOL
        serial.write(hbMessage)
        serial.flush()  # output Now
        
    frameKnt +=1
    frameKnt=min(FRAMERATE,frameKnt)  # just count number of frames in a second
    
    # done with work, now we make timing to get our frame rate to come out right
    #
    endOfWork = time.time()
    workTime = endOfWork - topOfFrame
    sleepTime = (FRAME-workTime)+ timeError
    time.sleep(sleepTime)
    endOfFrame = time.time()