Esempio n. 1
0
def change_speed(motor_num, speed):
	speed = int(speed)
	if (motor_num == 1):
		board_num = 0x80
		command = 35
		serial = ser_x80
	elif (motor_num == 2):
		board_num = 0x81
		command = 36
		serial = ser_x81
	elif (motor_num == 3):
		board_num = 0x80
		command = 36
		serial = ser_x80
	else:
		print "Not a possibility."
		
	speed_byte3 = speed & 0xff  #Least significant bit
	speed = speed >> 8
	speed_byte2 = speed & 0xff
	speed = speed >> 8
	speed_byte1 = speed & 0xff
	speed = speed >> 8
	speed_byte0 = speed & 0xff  # Most significant bit

	checksum = (board_num + command + speed_byte0 + speed_byte1 + speed_byte2 + speed_byte3) & 0x7f
	cmdList = [board_num, command, speed_byte0, speed_byte1, speed_byte2, speed_byte3, checksum]
	for i in range(len(cmdList)):
		serial.write(chr(cmdList[i]))
#		print cmdList[i]
	return 0;
Esempio n. 2
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))
Esempio n. 3
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
Esempio n. 4
0
def helpResponseProcessor(line):
    if line.find(' - ') != -1:
        parts = line.split(" - ")
        serial.write("help " + parts[0] + '\n')
        # serial.flush()
        incoming = serial.readlines()
        printLines(incoming)
Esempio n. 5
0
def GetData(line):
    if line.find(' - ') != -1 and line.startswith('Get'):
        parts = line.split(" - ")
        serial.write(parts[0] + '\n')
        # serial.flush()
        incoming = serial.readlines()
        printLines(incoming)
Esempio n. 6
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()
Esempio n. 7
0
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
Esempio n. 8
0
def printToConsole(serial, tx_encoder , string , millisecondsDelay):
    time.sleep(delay*millisecondsDelay)
    rospy.loginfo(string)
    
    serial.write(tx_encoder.encode(string))
    
    return
Esempio n. 9
0
def write_eeprom_long(str2parse, serial):
    try:
        items = str2parse.split(b',')
        if len(items) > 2:
            thekey = items[1].decode()
            if thekey in list(mem.keys()):
                addr = mem[thekey]
            else:
                addr = int(items[1])

            if items[2][:2] == '0x':
                val = int(items[2], 16)
            else:
                val = int(items[2])

            for i in range(4):
                outstr = b"w,%i,%i\n" % (addr + i, val & 0xff)
                val >>= 8
                serial.write(outstr)
                time.sleep(.25)
        else:
            print("Error: missing parameters")
    except:
        #print("Error")
        print(sys.exc_info())
Esempio n. 10
0
def Numero_ricevuto(numero):
    if numero == 33:
        #If 33 is received, Arduino blocked all comunications (Decidere cosa fare!!!)
        #os.system('reboot')
        print("Arduino blocked all the activities!")
    if numero == 107:
        serial.write('121')
Esempio n. 11
0
def write_eeprom_uint(str2parse, serial):
    try:
        items = str2parse.split(b',')
        if len(items) > 2:
            thekey = items[1].decode()
            if thekey in list(mem.keys()):
                addr = mem[thekey]
            else:
                addr = int(items[1])

            if items[2][:2] == '0x':
                val = int(items[2], 16)
            else:
                val = int(items[2])

            if addr >= 0 and addr < 511 and val >= 0 and val < pow(2, 16):
                outstr = b"w,%i,%i\n" % (addr, val & 0xff)  # LSB
                serial.write(outstr)
                time.sleep(.25)
                outstr = b"w,%i,%i\n" % (addr + 1, val >> 8)  # MSB
                serial.write(outstr)
            else:
                print("Error: icorrect value(s)")
        else:
            print("Error: missing parameters")
    except:
        #print "ERROR"
        print(sys.exc_info())
Esempio n. 12
0
def send_data(data, read_byte):  ##  sending data to herkulex Servo
    length = len(data) + 5
    data.insert(0, length)
    csm1 = checksum1(data)
    csm2 = checksum2(csm1)
    data.insert(0, 0xFF)
    data.insert(1, 0xFF)
    data.insert(5, csm1)
    data.insert(6, csm2)
    #print data

    stringtosend = ""
    for i in range(len(data)):
        byteformat = '%02X' % data[i]
        stringtosend = stringtosend + "\\x" + byteformat

    try:

        serial.write(stringtosend.decode('string-escape'))
        t = 13
        if (read_byte != 0):  ##reading data from servo ACK
            rxdata = serial.read(t)

        return rxdata
    except:
        return -1
Esempio n. 13
0
def show():
    # backforward
    forward()
    time.sleep(2)
    stop()

    time.sleep(1)
    # rudder
    turn_big_left()
    turn_big_right()
    turn_small_left()
    turn_small_right()

    time.sleep(1)

    turn_small_right()
    forward()
    time.sleep(2)
    stop()

    # loop
    while True:
        cmd = raw_input('Enter anycommand you like >> ')
        if cmd == 'Y':
            break
        else:
            serial.write(cmd)
            read()
Esempio n. 14
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
Esempio n. 15
0
def clear_display(serial):
    for row in range(1, 5):
        serial.write(b"".join([
            b'\xFE\x47\x01',
            chr(row).encode(),
            (" " * int(config['display']['WIDTH'])).encode()
        ]))
Esempio n. 16
0
def send_message(serial, msg_type, msg):
    print "Sending, id=0x%02X, len=%d" % (msg_type, len(msg))
    serial.write(chr(DEBUG_MAGIC_1))
    serial.write(chr(DEBUG_MAGIC_2))
    serial.write(chr(msg_type))
    serial.write(chr(len(msg)))
    serial.write(msg)
Esempio n. 17
0
def sendMessage(serial,message):
    if serial:
        serial.write(message.encode('utf-8'))
        time.sleep(0.07)
        return 1
    else:
        return 0
Esempio n. 18
0
def write_eeprom_int16(str2parse, serial):
    try:
        items = str2parse.split(b',')
        if len(items) > 2:
            if items[1] in list(mem.keys()):
                addr = mem[items[1]]
            else:
                addr = int(items[1])

            if items[2][:2] == '0x':
                val = int(items[2], 16)
            else:
                val = int(items[2])

            if addr >= 0 and addr < 511 and val > -pow(2, 15) and val < pow(
                    2, 15):
                outstr = b"wi,%i,%i\n" % (addr, val & 0xFFFF)
                serial.write(outstr)
                time.sleep(.25)
            else:
                print("Error: icorrect value(s)")
        else:
            print("Error: missing parameters")
    except:
        #print "ERROR"
        print(sys.exc_info())
Esempio n. 19
0
def serWrite(threadName, delay):
    if len(serialq) > 0:
        msg = serialq.popleft()
        serial.write(msg)
        print ("[Arduino | %s] serWrite > %s" %(time.ctime(time.time()), msg))

    real_delay_call(serWrite, delay, threadName, delay)
Esempio n. 20
0
def read_speed(motor_num):
	if (motor_num == 1):
		board_num = 0x80
		command = 30
		serial = ser_x80
	elif (motor_num == 2):
		board_num = 0x81
		command = 30
		serial = ser_x81
	elif (motor_num == 3):
		board_num = 0x80
		command = 31  ## OK, this is seriously a major WTF here. I need to see if the board is wired wrong or something.
		serial = ser_x80
	data = []
	serial.write(chr(board_num))
	serial.write(chr(command)) 
	for i in range(6):
		data.append(serial.read())


	speed = (data[0].encode("hex")) + (data[1].encode("hex")) + (data[2].encode("hex")) + (data[3].encode("hex"))
	speed = int(speed, 16)
	if ((ord(data[4]) == 1) and (speed != 0)):
		speed = ~(0xffffffff - speed) + 1
	rotations_per_second = float(speed) * 125 / 8192 	
	return rotations_per_second
Esempio n. 21
0
def dlt645_read_time(serial,addr,data_tag):
    #print 'dlt645_read_time ...'
    try:
        cmd2 = '\xfe\xfe\xfe\xfe' + encode_dlt645(addr,0x11,4,data_tag)
        serial.write(cmd2)
        time.sleep(0.5)
        resp = ''
        c = ''
        i = 0
        while c != '\x16' and i < SERIAL_TIMEOUT_CNT:
            c = serial.read(1)
            if len(c) > 0:
                resp += c
            else:
                print '.'
                i += 1
            
        if i >= SERIAL_TIMEOUT_CNT:
            return -1,0
            
        resp1 = dlt_645_rm_fe(resp)    
        ret,addr,data,ctl = decode_dlt645(resp1)
        #print data.encode('hex')
        # need to convert to Unix time stamp
        if ret == 0 and len(data) >= 7:
            list1 =  list(bcd2digits(data[4:7]))
            str1 = ''.join(str(e) for e in list1)
            return ret,str1
        else:
            return -1,0
    except:
        print 'dlt645_read_data exception!'
        return -1,0
Esempio n. 22
0
def start_app():
    '''Starts app
	'''
    C = [0x55, 0x55, ord('J'), ord('A'), 0x00]
    crc = calc_crc(
        C[2:4] +
        [0x00])  # for some reason must add a payload byte to get correct CRC
    crc_msb = (crc & 0xFF00) >> 8
    crc_lsb = (crc & 0x00FF)
    C.insert(len(C), crc_msb)
    C.insert(len(C), crc_lsb)
    serial.write(C)
    sleep(2)
    #print (C)

    #R = serial.read()   #7
    R = serial.read_all()
    print(len(R))
    '''
	if (R[0]) == 85 and (R[1]) == 85:
		packet_type =  R[2] + R[3]
		print(packet_type)
	'''
    if R[0] == 85 and R[1] == 85:
        packet_type = '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
        print(packet_type)
Esempio n. 23
0
def write_block(buf, data_len, addr):
    '''Executed WA command to write a block of new app code into memory
	'''
    print(data_len, addr)
    C = [0x55, 0x55, ord('W'), ord('A'), data_len + 5]
    addr_3 = (addr & 0xFF000000) >> 24
    addr_2 = (addr & 0x00FF0000) >> 16
    addr_1 = (addr & 0x0000FF00) >> 8
    addr_0 = (addr & 0x000000FF)
    C.insert(len(C), addr_3)
    C.insert(len(C), addr_2)
    C.insert(len(C), addr_1)
    C.insert(len(C), addr_0)
    C.insert(len(C), data_len)
    for i in range(data_len):
        #C.insert(len(C), ord(buf[i]))
        C.insert(len(C), buf[i])
    crc = calc_crc(C[2:C[4] + 5])
    crc_msb = int((crc & 0xFF00) >> 8)
    crc_lsb = int((crc & 0x00FF))
    C.insert(len(C), crc_msb)
    C.insert(len(C), crc_lsb)
    status = 0
    while (status == 0):
        serial.write(C)
        test = []
        for ele in C:
            test.insert(len(test), hex(ele))
        #print test
        #print len(C)
        #print('percent: {:.2%}'.format(addr/fs_len))
        print("upload progress: %.3f%%" % (float(addr) / float(fs_len) * 100))
        if addr == 0:
            sleep(8)
        else:
            #sleep(0.01)
            sleep(0.01)
        R = serial.read(12)  #longer response
        #test = ord(R[0])
        status = 1
        #print R[2]
        #print R[3]
        if len(R) > 1 and (R[0]) == 85 and (R[1]) == 85:
            #packet_type =  '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
            #packet_type = R[2] + R[3]
            #print(packet_type)
            packet_type = '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
            if packet_type == 'WA':
                status = 1
            else:
                sys.exit()
                print('retry 1')
                status = 0
        else:
            print(len(R))
            print(R)
            #self.reset_buffer()
            sleep(1)
            print('no packet')
            sys.exit()
Esempio n. 24
0
def start_bootloader():
    '''Starts bootloader
		:returns:
			True if bootloader mode entered, False if failed
	'''
    print("start")
    C = [0x55, 0x55, ord('J'), ord('I'), 0x00]
    crc = calc_crc(
        C[2:4] +
        [0x00])  # for some reason must add a payload byte to get correct CRC
    crc_msb = (crc & 0xFF00) >> 8
    crc_lsb = (crc & 0x00FF)
    C.insert(len(C), crc_msb)
    C.insert(len(C), crc_lsb)
    serial.write(C)
    time.sleep(2)  # must wait for boot loader to be ready
    #R = serial.read(5)
    R = serial.read_all()
    print(R)
    if R[0] == 85 and R[1] == 85:
        #packet_type =  '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
        packet_type = '{0:1c}'.format(R[2]) + '{0:1c}'.format(R[3])
        print(packet_type)
        if packet_type == 'JI':
            serial.read(R[4] + 2)
            print('bootloader ready')
            time.sleep(2)
            if boot_mode == 0:
                print('resync with device')
                time.sleep(2)
            return True
        else:
            return False
    else:
        return False
Esempio n. 25
0
def serWrite(threadName, delay):
    if len(serialq) > 0:
        msg = serialq.popleft()
        serial.write(msg)
        print("[Arduino | %s] serWrite > %s" % (time.ctime(time.time()), msg))

    real_delay_call(serWrite, delay, threadName, delay)
Esempio n. 26
0
def send_filter_status_req(serial):
    # request status data
    request = Digi18Com_pb2.Request()
    request.action_id = Digi18Com_pb2.GET_FILTERID
    start = request.SerializeToString()
    # write to the COM
    serial.write(wrap_content(start))
Esempio n. 27
0
def send_status_req(serial):
    # request status data
    request = Digi18Com_pb2.Request()
    request.action_id = Digi18Com_pb2.SAMPLER_STATUS
    start = request.SerializeToString()
    # write to the COM
    serial.write(wrap_content(start))
Esempio n. 28
0
def cmdx(serial, command, timeout=2, retry=2):
	''' send command to zigbee router and wait for response

	serial  : serial device
	command : command line
	timeout : wait time

	return  : the response list from zigbee router
	'''
	ret = []
	ind = 0
	# if time out and can't receive data, the retry
	while ind < retry:
		ind += 1
		serial.write(command)
		n = 0
		# wait for a while and record all the response
		while n < timeout*1:
			time.sleep(0.01)
			n += 1
			count = serial.inWaiting()
			if count > 0:
				recv = ser.read(count)
				ser.flushInput()
				ret.append(recv)
		if len(ret) > 0:
			break
	return ret
Esempio n. 29
0
    def _send_and_wait_for_ack(self, packet, serial):
        ack = 0
        MAX_RETRIES = 1

        while ack != 0x06 and int(chr(packet[4])) < MAX_RETRIES:
            serial.write(packet)
            ack = serial.read(1)

            # This violates the principle that we do high level
            # client-side and low level posbox-side but the retry
            # counter is always in a fixed position in the high level
            # message so it's safe to do it. Also it would be a pain
            # to have to throw this all the way back to js just so it
            # can increment the retry counter and then try again.
            packet = packet[:4] + str(int(packet[4]) + 1) + packet[5:]

            if ack:
                ack = ord(ack)
            else:
                _logger.warning("did not get ACK, retrying...")
                ack = 0

        if ack == 0x06:
            return True
        else:
            _logger.error("retried " + str(MAX_RETRIES) + " times without receiving ACK, is blackbox properly connected?")
            return False
Esempio n. 30
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
Esempio n. 31
0
def main():
    iob=Io_board("Io_board_node")
    iob.Init_node()
    iob.Io_Sub("io_state")
    import serial
    try:
        serial = serial.Serial('/dev/ttyUSB0', 115200, timeout=0.5)  #/dev/ttyUSB0
        if serial.isOpen() :
            rospy.loginfo("open port success")
        else :
            rospy.loginfo("open port failed")
    except:
        serial = serial.Serial('/dev/ttyUSB1', 115200, timeout=0.5)  #/dev/ttyUSB0
        if serial.isOpen() :
            rospy.loginfo("open port success")
        else :
            rospy.loginfo("open port failed")
    rate = rospy.Rate(4)
    #rostopic pub /io_state std_msgs/String "55C8070155"
    while not rospy.is_shutdown():
        #data =recv(serial)
        if len(iob.iostatebuff)!=0:
            iocmd=iob.iostatebuff[-1]
            rospy.loginfo("receive : %s",str(iocmd))
            time.sleep(1)
            serial.write(iocmd.decode("hex")) #数据写回
        else:
            pass
        # data ='55C81900000055'
        rate.sleep()
Esempio n. 32
0
def vibrate(serial: serial.Serial, degrees, distance):
    print('vibrate', degrees, distance)

    if serial is None:
        return

    serial.write("<{},{}>\n".format(round(degrees), round(distance)).encode('ascii'))
Esempio n. 33
0
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 check_update_status(serial, dev_id, retransmission_times=3):
    global responses_result_dict
    global timeCount
    global failed_to_exit
    res = None
    comannd = bytearray([0xf0, 0x01, 0x61, 0x08, 0x00, 0xf7])
    comannd[1] = dev_id
    checksum = 0
    for i in range(1, len(comannd) - 2):
        checksum = (checksum + comannd[i]) & 0x7f
    comannd[4] = checksum
    responses_result_dict["check_update_status"] = []
    responses_result_dict["universal_response"] = []
    serial.write(comannd)

    timeCount = 0
    number_of_retransmissions = 0
    while (len(responses_result_dict["check_update_status"]) < 2):
        if timeCount > 20:
            number_of_retransmissions = number_of_retransmissions + 1
            timeCount = 0
            print "retransmissions:" + str(number_of_retransmissions)
            serial.write(comannd)
        if number_of_retransmissions > retransmission_times:
            failed_to_exit = True
            break

    if len(responses_result_dict["check_update_status"]) > 1:
        res = []
        res.append(responses_result_dict["check_update_status"][0])
        res.append(responses_result_dict["check_update_status"][1])
    return res
def assign_id_command(serial, retransmission_times=3):
    global responses_result_dict
    global timeCount
    global failed_to_exit
    res = None
    comannd = bytearray([0xf0, 0xff, 0x10, 0x00, 0x0f, 0xf7])
    responses_result_dict["assign_id"] = []
    responses_result_dict["universal_response"] = []
    print "assign_id_command"
    serial.write(comannd)
    timeCount = 0
    number_of_retransmissions = 0
    while (len(responses_result_dict["assign_id"]) < 2):
        if timeCount > 10:
            number_of_retransmissions = number_of_retransmissions + 1
            timeCount = 0
            print "retransmissions:" + str(number_of_retransmissions)
            serial.write(comannd)
        if number_of_retransmissions > retransmission_times:
            break
    print responses_result_dict["assign_id"]
    if len(responses_result_dict["assign_id"]) > 1:
        res = []
        res.append(responses_result_dict["assign_id"][0])
        res.append(responses_result_dict["assign_id"][1])
        res.append(responses_result_dict["assign_id"][2])
    return res
def target_flash_start():

	file=open("../count/count.txt",'r+')
	count_ok=file.readline()
	count_ng=file.readline()
	count_ok=int(count_ok)
	count_ng=int(count_ng)
	file.close()
	sleep(1)
	child1=subprocess.Popen(["../tool/JLink.exe","-CommanderScript","flash_nrf.jlink"],stdout=subprocess.PIPE)
	out=child1.communicate()
#	print out[0]
	print("**************************")
	print("")
	if "Writing target memory failed" in out[0]:
		print "       flash error    "
		serial.write('Error\r\n')
		count_ng=count_ng+1
	elif "O.K." in out[0]:
		print("       flash ok       ")
		serial.write('OK\r\n')
		count_ok=count_ok+1
	else:
		print"Didn't flash any chip"

	WriteCount(count_ok,count_ng)
	print("%d/%d"%(count_ok,count_ng))
	print("**************************")
	target_flash_start_event.set()
Esempio n. 37
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
Esempio n. 38
0
def send():

    serial.write(bytes(2, 'UTF-8'))

    print('发出指令成功')

    serial.flushInput()
Esempio n. 39
0
def write_multiple_registers(serial, data, Params):
	start_reg = data[3]  #inicio de cadena

	if   start_reg == '\x00' :	#	Pesos
		Params.in_00 =   (ord(data[7]) << 8) + ord(data[8])
		print 'Recibido: $  %d.%d ' % ( Params.in_00/100, Params.in_00%100), repr(data[:])
		Params.in_01 = ( Params.in_00*100 / Params.in_02*100 )/100	# Multiplica litros por precio
	elif   start_reg == '\x01' :	#	Litros
		Params.in_01 =   (ord(data[7]) << 8) + ord(data[8])
		print 'Recibido: %d.%d   Litro(s)' % ( Params.in_01/100, Params.in_01%100), repr(data[:])
		Params.in_00 = ( Params.in_01 * (Params.in_02) )/100	# Multiplica litros por precio
	elif   start_reg == '\x02' :	#	Magna
		Params.in_02 =   (ord(data[7]) << 8) + ord(data[8])
		Params.in_00 = ( Params.in_01 * (Params.in_02) )/100	# Multiplica litros por precio
		print 'Recibido: $%d.%02d  Magna' % ( Params.in_02/100, Params.in_02%100), repr(data[:])
	elif   start_reg == '\x03' :	#	Premium
		Params.in_03 =   (ord(data[7]) << 8) + ord(data[8])
		#Params.in_00 = ( Params.in_01 * (Params.in_02) )/1000	# Multiplica litros por precio
		print 'Recibido: $%d.%02d  Premium' % ( Params.in_03/100, Params.in_03%100), repr(data[:])
	elif   start_reg == '\x1d' :	#	cadena de datos (30 caracteres)
		Params.str_00 = convert_st(data[7:37])
		print 'Cadena 0:  ', Params.str_00 ,  repr(data[:])
	elif   start_reg == '\x3b' :	#	cadena de datos (30 caracteres)
		Params.str_01 = convert_st(data[7:37])
		print 'Cadena 1:  ', Params.str_01 ,  repr(data[:])
	else:
		print 'Recibido   ',  repr(data[:])
	SRT  = "\x01\x10\x00\x00\x00\x04"
	SRT= add_chksum (SRT)
	serial.write(SRT)
Esempio n. 40
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
Esempio n. 41
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()
Esempio n. 42
0
    def _send_and_wait_for_ack(self, packet, serial):
        ack = 0
        MAX_RETRIES = 1

        while ack != 0x06 and int(chr(packet[4])) < MAX_RETRIES:
            serial.write(packet)
            ack = serial.read(1)

            # This violates the principle that we do high level
            # client-side and low level posbox-side but the retry
            # counter is always in a fixed position in the high level
            # message so it's safe to do it. Also it would be a pain
            # to have to throw this all the way back to js just so it
            # can increment the retry counter and then try again.
            packet = packet[:4] + str(int(packet[4]) + 1) + packet[5:]

            if ack:
                ack = ord(ack)
            else:
                _logger.warning("did not get ACK, retrying...")
                ack = 0

        if ack == 0x06:
            return True
        else:
            _logger.error("retried " + str(MAX_RETRIES) + " times without receiving ACK, is blackbox properly connected?")
            return False
Esempio n. 43
0
def dlt645_get_addr(serial):
    #print 'dlt645_get_addr ...'
    try:
        #cmd2 = '\xfe\xfe\xfe\xfe\x68\xaa\xaa\xaa\xaa\xaa\xaa\x68\x13\x00\xdf\x16'
        cmd2 = '\xfe\xfe\xfe\xfe' + encode_dlt645('\xaa\xaa\xaa\xaa\xaa\xaa',0x13,0,'')

        serial.write(cmd2)
        time.sleep(0.5)
        resp = ''
        c = ''
        i = 0
        while c != '\x16' and i < SERIAL_TIMEOUT_CNT:
            c = serial.read(1)
            if len(c) > 0:
                resp += c
            else:
                print '.'
                i += 1
        
        if i >= SERIAL_TIMEOUT_CNT:
            return -1,0
        
        resp1 = dlt_645_rm_fe(resp)

        #print 'resp1:',resp1

        ret,addr,data,ctl = decode_dlt645(resp1)
        if ret == 0:
            return ret,addr
            
        
    except:
        print 'dlt645_get_addr exception!'
        return -1,''
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 faceDetection () :
	camera.capture( imagePath )

	# Read the image
	image = cv2.imread( imagePath )
	gray = cv2.cvtColor( image, cv2.COLOR_BGR2GRAY )

	# Detect faces in the image
	faces = faceCascade.detectMultiScale (
	    gray,
	    scaleFactor = 1.1,
	    minNeighbors = 5,
	    minSize = ( 30, 30 ),
	    flags = cv2.cv.CV_HAAR_SCALE_IMAGE
	)

	for ( x, y, w, h ) in faces:
		centerX = x + ( w / 2 )
		centerY = y + ( h / 2 )

		print "Found face at: {0}, {0}".format( centerX, centerY )
		serial.write( "{0}, {0}".format( centerX, centerY ) );

		cv2.rectangle( image, ( x, y ), ( x + w, y + h ), ( 0, 255, 0), 3 )
		cv2.imwrite( imageFaceDetectionPath, image )

		break
  	
  	# recall fn
  	interval.enter( refreshTime, 1, faceDetection, () )
Esempio n. 46
0
def sendReceiveScript(serial, filename='init.lua'):
    receiveLua = \
    r"""tmr.stop(0)
        file.remove('%s')
        file.open('%s', 'w')
        uart.on('data', 255,
          function (d)
            tmr.stop(0)
            c = tonumber(d:sub(1, 4))
            d = d:sub(5, 4+c)
            file.write(d)
            if c ~= 251 then
                file.close()
                uart.write(0, 'Y')
                return
            end
            uart.write(0, 'Y')
          end, 0)"""
    receiveLua = ' '.join([line.strip() for line in receiveLua.split('\n')]).replace(', ', ',')

    save_command = receiveLua % (filename, filename) + '\r'

    assert len(save_command) < 256, 'Save_command too long: %s bytes' % len(save_command)

    writeV('Sending receive script to NodeMCU...')
    serial.write(save_command.encode())
    response = waitFor(prompt)
    #assert response == save_command + prompt, response
    writeLnV('ok!')
Esempio n. 47
0
def send_message(serial, msg_type, msg):
  print "Sending, id=0x%02X, len=%d" % (msg_type, len(msg))
  serial.write(chr(DEBUG_MAGIC_1))
  serial.write(chr(DEBUG_MAGIC_2))
  serial.write(chr(msg_type))
  serial.write(chr(len(msg)))
  serial.write(msg)
Esempio n. 48
0
	def move(self, angle):
		if(self.minAngle > angle):
			angle = self.minAngle
		if(self.maxAngle < angle):
			angle = self.maxAngle
		self.angle = angle
		serial.write('#' + str(self.ID) + ' P' + str(angle) + '\r')
Esempio n. 49
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()
Esempio n. 50
0
	def send(self,serial,data):
		# send it
		print "    ENCRYPTED: %s" % data.encode('hex')
		data = b64encode ( data )
		print "    ENCODED: %s" % data
		serial.write(data + '\x00');
		serial.flushOutput()
		print "\n"
Esempio n. 51
0
    def _worksession_start(self, seconds):
        serial = self._openSerial()
        
        minutes = int(seconds) / 60
        data = chr(minutes)
        serial.write(data)

        self._closeSerial(serial)
Esempio n. 52
0
    def sendto(self, serial):
        """
        Sends this message to `serial`

        :param serial: Serial interface to send this message to
        :type serial: :py:class:`serial.Serial`
        """
        serial.write(str(self))
Esempio n. 53
0
def cleartape(serial):
    zeros = [0, 0, 0] * (LED_NUMBER )
    print("Clearing tape")
    data = ""
    for x in zeros:
        data += chr(x)
    serial.write(data)
    serial.write(CONTROL)
Esempio n. 54
0
 def write_serial(self, command, *args, **kwargs):
     hex = self.COMMANDS[command] % kwargs
     if DEBUG:
         print 'writing to serialport: %s %s' % (command, hex)
     serial.write(Utilities.hex2chr(hex))
     #time.sleep(2)
     if DEBUG:
         print 'waiting at serialport: %i' % serial.inWaiting()
Esempio n. 55
0
 def set_gain(self):
     if self.is_open():
         o_str = 'p{}'.format(self.gain);
         b = o_str.encode()
         serial = self.get_serial();
         serial.write(b);
         return True
     else:
         return False
Esempio n. 56
0
 def set_differential(self):
     if self.is_open():
         o_str = 'd{}'.format(self.diff);
         b = o_str.encode()
         serial = self.get_serial();
         serial.write(b);
         return True
     else:
         return False
Esempio n. 57
0
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 ""
Esempio n. 58
0
def read_serial(gcode):
	serial.flushInput()
	serial.write(gcode + "\r\n")

	response=""
	while (response==""):
		response=serial.readline().rstrip
		if response!="":
			return response
Esempio n. 59
0
 def set_integral(self):
     if self.is_open():
         o_str = 'i{}'.format(self.integral);
         b = o_str.encode()
         serial = self.get_serial();
         serial.write(b);
         return True
     else:
         return False
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:])