示例#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 readSensor(serial):
    try:
        # request data   21
        serial.flushInput()
        string = "5A E8 5A DF 5A CB"  #Long range - Fast mode - Start periodic readout

        cmd_bytes = bytearray.fromhex(string)

        ser.write(cmd_bytes)

        msg_b = serial.read(8)
        encoded = str(base64.b16encode(msg_b))
        encoded = encoded.replace("b'", "")
        encoded = encoded.replace("'", "")
        B = read_hex(encoded)
        #print(B)
        return B

    except (Exception, KeyboardInterrupt) as e:
        print('sensor communication broke down')
        print(str(e))
        serial.flushInput()
        time.sleep(0.2)
        serial.flushOutput()
        time.sleep(0.2)

        serial.close()  # Only executes once the loop exits
        sys.exit()
def readSensor(serial): 
    try:
        # request data   21 
        serial.flushInput()
        string = "5A E8 5A DF 5A CB" #Long range - Fast mode - Start periodic readout
        
        cmd_bytes = bytearray.fromhex(string)
        
        ser.write(cmd_bytes)
        
        msg_b = serial.read(8)
        encoded = str(base64.b16encode(msg_b))
        encoded = encoded.replace("b'","")
        encoded = encoded.replace("'","")
        B = read_hex(encoded)
        #print(B)
        return B

    except KeyboardInterrupt:
        print("User interrupt encountered. Exiting...")
        time.sleep(3)
        serial.flushInput()
        serial.flushOutput()
        serial.close()
        sys.exit()
    except:
        # for all other kinds of error, but not specifying which one
        print("Device disconnected")
        time.sleep(3)
        serial.flushInput()
        serial.flushOutput()
        serial.close()
        sys.exit()
示例#4
0
    def save_result(self, serial, file_name, time_val=5):
        val = True
        text_file = open(file_name, 'w+')
        count = 0

        print('Readable =',serial.readable())
        start = time.time()
        print('Collecting data from serial', end='')

        while val is True:
            msg = str(serial.readline())
            msg = msg[2:-1]
            msg = msg.replace('\\r\\n', '\n')
            msg = msg.replace('\\t', '\t')
            # print(msg)
            text_file.write(msg)
            end = time.time()
            count += 1
            if (count % self.time*2) == 0:
                print('.', end='')

            if (end - start) >= time_val:
                print("Done collecting data from serial")
                val = False

        text_file.close()
        serial.close()
示例#5
0
def main():

    args = validateInput()
    serial = initSerial(args['SerialPort'], args['BaudRate'])
    freq = int(struct.unpack('h', serial.read(2))[0])
    scriptTime = int(freq * args['ExecTime'])

    timeCounter = 0
    while (timeCounter <= scriptTime or scriptTime == 0):
        timeCounter += 1
        try:
            dataLen = int(struct.unpack('B', serial.read(1))[0])
            rawData = serial.read(dataLen)
            data = struct.unpack(STRUCT_DATA, rawData)
            # Arquivo de log
            dataFile = open(args['FileName'], 'a')
            dataFileBin = open(args['FileName'] + 'bin', 'ab')
            dataFile.write(
                str(data[0]) + "\t" + str(data[1]) + "\t" + str(data[2]) +
                "\n")
            dataFileBin.write(rawData)
            dataFile.close()
            dataFileBin.close()

        except KeyboardInterrupt:
            break

    serial.close()
示例#6
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()
示例#7
0
 def __exit__(self, type, value, traceback):
     if not self.serial: return
     self._send("F00F00\n")
     serial = self.serial
     self.serial = None
     serial.close()
     print "closed serial port"
def user_choice(prompt, board=None, serial=None, thread_initiated=False):
    '''Awaits user's choice (yes or quit). 
    This function can be used to give the user some control'''

    user_res = ''
    while True:
        user_res = input(CYELLOW + prompt + CEND)
        if (user_res == 'y') and (not thread_initiated) and (
                not stop_event.is_set()):
            break
        if user_res == 'q':
            if thread_initiated:
                stop_event.set()  # message for threads to stop
                time.sleep(1)
            if board:
                try:
                    board.stop_stream()
                except brainflow.board_shim.BrainFlowError:
                    print(CRED + "Board is not streaming" + CEND)
                board.release_session()
            if serial:
                serial.write(
                    "c".encode())  # message for arduino to stop streaming
                time.sleep(1)
                serial.close()
            print('The end')
            time.sleep(1)
            sys.exit()
        else:
            continue
示例#9
0
def readSensor(serial): 
    try:
        # request data   21 
        serial.flushInput()
        serial.write('90 232'.encode('utf8'))
        serial.write('90 223'.encode('utf8'))
        serial.write('90 203'.encode('utf8'))
        #print(ser.out_waiting)
        msg_b = serial.read(8)
        encoded = str(base64.b16encode(msg_b))
        encoded = encoded.replace("b'","")
        encoded = encoded.replace("'","")
        B = read_hex(encoded)
        #print(B)
        return B

    except (Exception,KeyboardInterrupt) as e:
        print('sensor communication broke down')
        print(str(e))
        serial.flushInput()
        time.sleep(0.2)
        serial.flushOutput()
        time.sleep(0.2)
        
        serial.close() # Only executes once the loop exits
        sys.exit()
示例#10
0
def Main(args):
    global port
    if len(args) != 2:
        print("Invalid input arguments")
        return 1

    serial.port = args[1]
    serial.baudrate = 115200
    serial.timeout = 3
    serial.open()

    input("Press enter to send data...")
    
    nCmdsGood = 0

    print("Starting upload on " + args[1] + "...")
    while True:
        cmd = bytes([ (0x80 if ((nCmdsGood % 5) == 0) else 0) | (0x01 if ((nCmdsGood % 3) == 0) else 0), 0 ])
        serial.write(cmd)
        resp = serial.read(len(cmd))
        if len(resp) > 0:
            if resp == cmd:
                nCmdsGood += 1
            print(resp)
        else:
            print("Waited too long.")
            break

    input("Press enter to close serial port...")

    serial.close()
    print("Done!")
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
示例#12
0
def test_serial():
    try:
        serial = open_serial()
        serial.open()
        serial.close()
    except:
        syslog.syslog(syslog.LOG_CRIT, "Failed to open serial device")
        sys.exit(os.EX_UNAVAILABLE)
示例#13
0
def main():  # PRINCIPAL
    camera = PiCamera()  # INICIALIZANDO, E CONFIGURANDO A CAMERA
    camera.resolution = (640, 480)
    camera.framerate = 32
    rawCapture = PiRGBArray(camera, size=(640, 480))
    while True:
        for frame in camera.capture_continuous(rawCapture,
                                               format="bgr",
                                               use_video_port=True):
            OriginalFrame = frame.array
            #TRATANDO A IMAGEM COM FILTROS, E APLICANDO PROPRIEDADES DO OPEN CV
            gray = cv2.cvtColor(OriginalFrame, cv2.COLOR_BGR2GRAY)
            blurred = cv2.GaussianBlur(gray, (3, 3), 0)
            edges = auto_canny(blurred)
            cv2.imshow(
                "Contornos Destacados", edges
            )  #MOSTRANDO EM JANELA A IMAGEM DA CAMERA ( NÃO É NECESSARIO)
            cntr_frame, contours, hierarchy = cv2.findContours(
                edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            rawCapture.truncate(0)
            for cnt in contours:
                area = cv2.contourArea(cnt)
                if (
                        area > 15000
                ):  # DETECTA FORMAS SOMENTE MAIORES QUE 15000 PIXELS DE AREA ( PODE SER ALTERADO)
                    approx = cv2.approxPolyDP(cnt,
                                              0.02 * cv2.arcLength(cnt, True),
                                              True)
                    if len(approx
                           ) == 3:  #COMPARANDO ARESTAS PARA DESCOBRIR A FORMA
                        serial.write('t')  # ENVIANDO PARA O ARDUINO
                        time.sleep(1)
                        break
                    elif len(
                            approx
                    ) == 5:  #COMPARANDO ARESTAS PARA DESCOBRIR A FORMA
                        serial.write('p')  # ENVIANDO PARA O ARDUINO
                        time.sleep(1)
                        break
                    elif len(
                            approx
                    ) == 6:  #COMPARANDO ARESTAS PARA DESCOBRIR A FORMA
                        serial.write('h')  # ENVIANDO PARA O ARDUINO
                        time.sleep(1)
                        break
                    # COMO NESSE CASO NÃO HÁ FORMAS ACIMA DE HEXAGONO (OCTOGONO, DODECAGONO ),
                    #QUALQUER COISA ACIMA DE HEXAGONO ELE JA CONSIDERA CIRCULO, PARA EVTAR ERROS.
                    elif len(
                            approx
                    ) >= 8:  #COMPARANDO ARESTAS PARA DESCOBRIR A FORMA
                        serial.write('c')  # ENVIANDO PARA O ARDUINO
                        time.sleep(1)
                        break
        k = cv2.waitKey(1) & 0xFF
        if k == 27:  #ESC FINALIZA O SCRIPT
            break
    cv2.destroyAllWindows()
    serial.close()
示例#14
0
def reconnect(serial):
    print('re')
    try:
        serial.close()
        serial.open()
        status = 1
        return status
    except:
        status = 0
        return status
def run():
    # serial = serial.Serial('/dev/cu.SLAB_USBtoUART', 115200, timeout=10)
    # serial = start_serial('/dev/cu.SLAB_USBtoUART', 230400)
    serial = start_serial('COM3', 921600)
    sensor_num = 6

    #serial port for BT
    # serial2 = start_serial('/dev/cu.HC-05-DevB', 9600)

    # Change output format in euler
    # serial.write("<sof1>\r\n")

    date_stamp = time.strftime("%Y-%m-%d-%H-%M-%S", time.gmtime())
    with open('./' + date_stamp + '.csv', 'w') as csvfile:
        writer = csv.writer(csvfile, delimiter=',')
        # add index to the first row
        writer.writerow(['1_x','1_y','1_z','2_x','2_y','2_z','3_x','3_y','3_z',\
            '4_x','4_y','4_z','5_x','5_y','5_z','6_x','6_y','6_z','stop'])

        # init data to compare diff
        init_data = get_single_data(serial, sensor_num)
        print(init_data)

        previous_data = init_data
        stop_flag = False
        first_stop = True
        while True:
            # read new data
            unsorted_data = get_serial_data_set(serial, sensor_num)
            current_data = parse_in_writer_form(unsorted_data)

            # check if it is stop
            stop_flag = is_stop(previous_data, current_data)

            if stop_flag == True and first_stop == True:
                current_data.append('stop')

                print(current_data)
                writer.writerow(current_data)

                # remove 'stop' sign
                current_data.pop()
                first_stop = False

            elif stop_flag == False:

                print(current_data)
                writer.writerow(current_data)
                # init first_stop flag
                first_stop = True

            # update previous_data
            previous_data = current_data

    serial.close()
示例#16
0
def getWord(request):
    ser = serial.Serial("/dev/cu.usbmodem1411", 9600, timeout=1)
    read = ser.readline()
    print(read)
    feats = [int(x) for x in read.strip().split(b' ') if int(x) < 1000]
    while len(feats) < 10:
        read = ser.readline()
        feats = [int(x) for x in read.strip().split(b' ') if int(x) < 1000]
    word = predict("a.p", feats)
    serial.close()
    return HttpResponse("{word:" + word + "}")
示例#17
0
def read_xbee(serial):
    try:
        incoming = serial.readline().strip()
        if len(incoming) > 0:
            print 'Received %s' % incoming
        else:
            print 'Nothing received'
    except:
        serial.close()

    return incoming
示例#18
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
def require(message,timeout=1):
	try:
		print('tx:'+message)
		line_received_event.clear()
		serial.write(message+'\r\n')
	except IOError as e:
		print(e)
		serial.close()
		stop_event.set()
	if not line_received_event.wait(timeout):
		print('no response')
		return None
	return serial_received_line
def require(message, timeout=1):
    try:
        print('tx:' + message)
        line_received_event.clear()
        serial.write(message + '\r\n')
    except IOError as e:
        print(e)
        serial.close()
        stop_event.set()
    if not line_received_event.wait(timeout):
        print('no response')
        return None
    return serial_received_line
示例#21
0
def run_graph(ns):
    graph = GraphClass()

    while(1):
        time.sleep(0.1)
        graph.set_angle(ns.yaw)
        if ns.ping == 1:
            ns.ping = 0;
            graph.set_g3(ns.total,ns.yaw)
            graph.set_g1(ns.raw_arr, "r")
            graph.set_g1(ns.smth_arr, "g")
            graph.set_g1(ns.vel_arr, "b")

    serial.close()
示例#22
0
def run_graph(ns):
    graph = GraphClass()

    while (1):
        time.sleep(0.1)
        graph.set_angle(ns.yaw)
        if ns.ping == 1:
            ns.ping = 0
            graph.set_g3(ns.total, ns.yaw)
            graph.set_g1(ns.raw_arr, "r")
            graph.set_g1(ns.smth_arr, "g")
            graph.set_g1(ns.vel_arr, "b")

    serial.close()
示例#23
0
def controlar_bomba ():
    bomba = serial.Serial (
            '/dev/ttyUSB0',
            4800,
            parity=serial.PARITY_ODD,
            stopbits=serial.STOPBITS_ONE,
            bytesize=serial.SEVENBITS,
            #rtscts=True
            )
    # enviar o comando ENQ
    if True:
        comando = ENQ
        bomba.write (bytearray ([bytes (c) for c in comando]))
        bomba.flush ()
        print ('A espera da resposta do comando ')
        print_serial (comando)
        resposta = receive_frame (bomba) # bomba.readline ()
        print ('Resposta e')
        print_serial (resposta)
    if True:
        comando = STX + 'P99I' + CR
        bomba.write (bytearray ([bytes (c) for c in comando]))
        bomba.flush ()
        print ('A espera da resposta do comando ')
        print_serial (comando)
        resposta = receive_frame (bomba)
        print ('Resposta e')
        print_serial (resposta)

    comando = chr (2) + 'P' + '02' + 'R' + chr (13)
    bomba.write (comando)
    bomba.flush ()
    print ('A espera da resposta do comando ')
    print_serial (comando)
    # resposta = bomba.readline ()
    # print_serial (resposta)

    print ('Ligar bomba')
    comando = chr (2) + 'P' + '02' + 'S' + '+0001' + chr (13)
    bomba.write (comando)
    bomba.flush ()

    print ('Desligar bomba')
    input ('Carregue em ENTER')
    comando = chr (2) + 'P' + '01' + 'H' + chr (13)
    bomba.write (comando)
    bomba.flush ()
    serial.close ()
    print ('Fim do controlo da bomba')
示例#24
0
 def run(self):
   print (serial)
   print ("Starting " + self.name)
   while True:
       if not rxQueue.empty():
         rxqueueLock.acquire()
         msg = rxQueue.get()
         rxqueueLock.release()
         if EndTaskString in msg:
           break
       else:
         data = serial.readline()
         print (str(data))
   serial.close()
   print ("Exiting " + self.name)
示例#25
0
    def _findDevice(self, port, address=0):
        """
        Look for a compatible device
        port (str): pattern for the port name
        address (None or int): the address of the stage controller
        return (serial, int): the (opened) serial port used, and the actual address
        raises:
            IOError: if no device are found
        """
        if port.startswith("/dev/fake"):
            names = [port]
        elif os.name == "nt":
            raise NotImplementedError("Windows not supported")
        else:
            names = glob.glob(port)

        for n in names:
            try:
                serial = self._openSerialPort(n)
            except IOError as ex:
                # not possible to use this port? next one!
                logging.info("Skipping port %s, which is not available (%s)",
                             n, ex)
                continue

            # check whether it answers with the right address
            try:
                # If any garbage was previously received, make it discarded.
                self._serial = serial
                self._serial.flush()
                if 'PMD401 ' in self.getVersion(address):
                    self._port = n
                    return serial  # found it!
            except Exception as ex:
                logging.debug(
                    "Port %s doesn't seem to have a PMD device connected: %s",
                    n, ex)
            serial.close()  # make sure to close/unlock that port
        else:
            raise IOError(
                "Failed to find a PMD controller with adress %s on ports '%s'. "
                "Check that the device is turned on and "
                "connected to the computer." % (
                    address,
                    port,
                ))
示例#26
0
def read_data(serial):
    '''
    Read data from one serial port and store it into the database
    We need one mongo client per connection
    '''
    # Extract metadata
    serial_num = serial.readline().decode("utf-8")[:-1]
    temp_cal_30 = int(serial.readline().decode("utf-8")[:-1])
    temp_cal_110 = int(serial.readline().decode("utf-8")[:-1])
    vrefint_cal = int(serial.readline().decode("utf-8")[:-1])

    for _ in range(args['size']):

        mem_address = serial.readline().decode("utf-8")[:-1]
        vdd_raw = int(serial.readline().decode("utf-8")[:-1])
        temp_raw = int(serial.readline().decode("utf-8")[:-1])
        raw_data = serial.readline().decode("utf-8")

        raw_data = [int(b) for b in raw_data.split(' ')[:-1]]

        # There are some problems with some boards which don't have the calibration values.
        # In those cases just store the raw value and the calibration values will be
        # calculated from the rest of the boards
        if vrefint_cal == 0:
            vdd = vdd_raw
        else:
            vdd = (3300 * vrefint_cal / vdd_raw) * 0.001

        if temp_cal_30 == 0 or temp_cal_110 == 0:
            temp = temp_raw
        else:
            temp = ((110 - 30) / (temp_cal_110 - temp_cal_30)) \
                * (temp_raw - temp_cal_30) + 30.0

        dump_data = dump.Dump(serial_num, raw_data, mem_address, temp, vdd,
                              temp_cal_30, temp_cal_110, vrefint_cal)

        if args['more_verbose']:
            print(f'{serial_num} [{mem_address}] at {dump_data.Timestamp}')
            print(f'Temp: {temp:.6f} C, Vdd: {vdd:.8f} V')

        store_data(dump_data.__dict__, args['csv'])
    else:
        print(f'[DISCONNECTED] Board on port {serial.port}')
        serial.close()
示例#27
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
示例#28
0
def port():
    global data1, data2, data3

    try:
        if sr.is_open == True:
            a = sr.readline()
            a = a.decode()
            print(a[:])
            data1 = a[0] + a[1]
            data2 = a[2] + a[3].strip()
            data3 = a[4] + a[5]
            print("A phase:", data1)
            print("temperature:", data2)
            print("Humidity:", data3)


# add figure canvas
    except ValueError:
        sr.close()
def receive(count_ok, count_ng):
    print("ready to receive command...")
    while not stop_event.is_set():
        try:
            line = serial.readline()
            if line:
                print("rx: " + line)
            if line.startswith('start'):
                target_flash_start()
            if line.startswith('end'):
                target_flash_end()
            else:
                serial_received_line = line
                line_received_event.set()

        except IOError as e:
            print(e)
            serial.close()
            stop_event.set()
示例#30
0
def Main(args):
    global port
    if len(args) != 4:
        print("Invalid input arguments")
        return 1

    f = open(args[1], "rb")
    fout = open(args[2], "wb")
    cmds = UploadAndExecute(f.read())
    f.close()

    serial.port = args[3]
    serial.baudrate = 115200
    serial.timeout = 10
    serial.open()

    input("Press enter to send data.")

    nCmdsGood = 0

    print("Starting upload on " + args[3] + "...")
    for cmd in cmds:
        fout.write(cmd)
        serial.write(cmd)
        resp = serial.read(12)
        if len(resp) > 0:
            if resp == cmd:
                nCmdsGood += 1
            print(resp)
        else:
            print("Waited too long.")
            break

    if nCmdsGood == len(cmds):
        print("All commands transferred 'successfully'.")
    else:
        print("Error! # of commands: {0}   # of successes: {1}".format(
            len(cmds), nCmdsGood))
    input("Press enter to close serial port.")

    fout.close()
    serial.close()
    print("Done!")
def receive(count_ok,count_ng):
	print("ready to receive command...")
	while not stop_event.is_set():
		try:
			line=serial.readline()
			if line:
				print("rx: "+line)
			if line.startswith('start'):
				target_flash_start()
			if line.startswith('end'):
				target_flash_end()
			else:
				serial_received_line=line
				line_received_event.set()

		except IOError as e:
			print(e)
			serial.close()
			stop_event.set()
def program(_port):

    if (_port != ''):
        thisTitle = "SERIAL COMMUNICATION BY PORT " + _port
        os.system("title " + thisTitle)
        # Rotina principal do programa
        while (True):
            os.system("cls")
            print("********", thisTitle, "********\n")

            data = input("Enter the data to be sent by serial: ")

            if (data != 'out' and data != 'auto'):
                try:
                    serial.write((data + "\n").encode())
                    answer = serial.readline()

                    print("Data sent:", data)
                    print("Answer   :", answer)
                    input()

                except:  # O programa entrará nessa exceção se a porta for desconectada,
                    # ou seja, quando a conexão for interrompida.
                    print("Communication error in port " + _port + ".")
                    break

            elif (data == 'out'):
                serial.close()
                break

            elif (data == 'auto'):
                cicles = int(
                    input("Enter how many drill cycles will be done: "))
                print("")
                if (walk(_port, cicles) == False):
                    serial.close()
                    break

    else:  # Se não existir nenhuma porta ativa, então o programa é encerrado.
        print("No port found!")
    print("END!")
def animate(i):
    if sr.is_open == True:
        a = sr.readline()
        a = a.decode()
        print(a)
        print(a[0])
    global data1, data2
    ctd = 0
    try:
        # if(len(data) < 100):
        data1 = np.append(data1, int(a[0]))
        print(data1)
        data2 = np.append(data2, int(a[1]))
        print(data2)
        x = np.arange(0, len(data1))
        # t=np.arange(0,2*np.pi,0.1)

        # print(len(data1))
        ax1.plot(x, data2, "green", label="A Phase")
        ax2.plot(x, data1, "red", label="B Phase")
        freq = CountFrequency(data1)
        # print(freq)
        plt.gcf()

        ax1.set_title("ROTARY ENCODER",
                      color="red",
                      fontname='Comic Sans MS',
                      size=15)
        red_patch = mpatches.Patch(color='green',
                                   label='A phase:' + str(len(data1)))
        ax1.legend(handles=[red_patch], loc='upper right')
        Blue_patch = mpatches.Patch(color='blue',
                                    label='B phase:' + str(len(data1)))
        ax2.legend(handles=[Blue_patch], loc='upper right')
        ax1, ax2.set_xlim(0, len(data1))

    except ValueError:
        sr.close()
        sys.exit()
示例#34
0
def laser_record():
    global laser_filename
    global time_now
    print('laser record...')
    time_now = str(int(time.time()))
    print(serial.port)
    #file_dir = "./"
    laser_filename = save_dir['datadir'] + 'laser_' + time_now + '_' + fj_id[
        'id'] + '.txt'
    print(laser_filename)
    time1 = int(time.time())
    #laser_record_time = 5
    if not serial.is_open:
        print('open')
        serial.open()
    try:
        while True:
            Byte_H = serial.read(1)
            Byte_L = serial.read(1)

            res = (ord(Byte_H) & 0x7f) * 128 + (ord(Byte_L) & 0x7f)
            print(res)
            ss = str(res) + '\n'
            with open(laser_filename, 'a') as f:
                f.write(ss)
            time2 = int(time.time())
            #print(time2)
            #print(time1)
            print(time2 - time1)
            if (time2 - time1 == collectTime):
                print('close')

                serial.close()
                print(serial.isOpen())

    except Exception as e:
        print(e)
示例#35
0
def on_command(logger, SERVICES):
    logger.info("Querying quaternion values from IMU...")
    while True:
        input("pause")
        try:
            request = '''
            { 
                qua {
                    success
                    errors
                    quaData {
                        q1
                        q2
                        q3
                        q4
                    }
                } 
            }
            '''
            response = SERVICES.query(service="imu-service", query=request)
            result = response["qua"]
            success = result["success"]
            errors = result["errors"]
            quaData = result["quaData"]
            q1 = quaData["q1"]
            q2 = quaData["q2"]
            q3 = quaData["q3"]
            q4 = quaData["q4"]

            if success:
                logger.info('Quaternion: ({}, {}, {}, {})'.format(q1,q2,q3,q4))
            else:
                logger.warning("Unable to retrieve quaternion data: {}".format(errors))

            try:
                # open uart port
                serial.close()
                serial.open()

                if serial.isOpen():
                    message = (q1,q2,q3,q4)
                    # if uart port is open, try to send encoded string message
                    serial.write(str(message).encode('utf-8'))
                    serial.close()
                    logger.debug("UART port is open. Sent message: {}".format(str(message)))
                else:
                    # if could not open uart port, return failure
                    serial.close()
                    logger.warn("Could not open serial port")

            # return failure if exception during write/encoding
            except Exception as e:
                logger.warn("Error sending message {} over uart port: {}".format(str(message), str(e)))


        except Exception as e:
            logger.warning("Unsuccessful getting data from quaternion: {}-{}".format(type(e).__name__,str(e)))
示例#36
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
示例#37
0
def detect_COM_port():
    #+fred not working ptyhon3
    # List all the Serial COM Ports on Raspberry Pi
    #proc = subprocess.Popen(['ls /dev/tty[A-Za-z]*'], shell=True, stdout=subprocess.PIPE)
    proc = subprocess.Popen(['ls /dev/tty[A-Za-z]*'],
                            shell=True,
                            stdout=subprocess.PIPE)
    com_ports = str(proc.communicate()[0])
    com_ports_list = com_ports.split('\n')

    # Find the right port associated with the Voice Modem
    for com_port in com_ports_list:
        if 'ttyS0' in com_port:
            #if 'serial' in com_port:
            #Try to open the COM Port and execute AT Command
            try:
                # Set the COM Port Settings
                set_COM_port_settings(com_port)
                analog_modem.open()
            except:
                print("DETECT: Unable to open COM Port: " + com_port)
                pass
            else:
                #Try to put Modem in Voice Mode
                #if not exec_AT_cmd("AT+FCLASS=8", "OK"):
                if not exec_AT_cmd("AT", "OK"):
                    print("DETECT: Error: Failed to get AT.")
                    #if analog_modem.isOpen():
                    #analog_modem.close()
                    serial.close()
                else:
                    # Found the COM Port exit the loop
                    print("DETECT: Modem COM Port is: " + com_port)
                    analog_modem.flushInput()
                    analog_modem.flushOutput()
                    break
示例#38
0
 def change_vol(command):
     if command == "vol_down":
         serial.write(b"5")
         serial.close()
     elif command == "vol_up":
         serial.write(b"4")
         serial.close()
     elif command == "vol_mute":
         serial.write(b"3")
         serial.close()
     else:
         syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server")
示例#39
0
 def misc_commands(command):
     if command == "gain_sel":
         serial.write(b"f")
         serial.close()
     else:
         syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server")
示例#40
0
def	close_HMIPort( serial ):
	serial.close()
示例#41
0
 def _closeSerial(self, serial):
     serial.close()
示例#42
0
 def change_input(command):
     if command == "in_nxt":
         serial.write(b"1")
         serial.close()
     elif command == "in_prev":
         serial.write(b"2")
         serial.close()
     elif command == "in_usb":
         serial.write(b"a")
         serial.close()
     elif command == "in_opt1":
         serial.write(b"d")
         serial.close()
     elif command == "in_opt2":
         serial.write(b"e")
         serial.close()
     elif command == "in_coax1":
         serial.write(b"b")
         serial.close()
     elif command == "in_coax2":
         serial.write(b"c")
         serial.close()
     else:
         syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server")
示例#43
0
''' SERIAL FLUSH INPUT & OUTPUT BUFFER '''
import serial
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('/var/www/lib/serial.ini')

serial_port = config.get('serial', 'port')
serial_baud = config.get('serial', 'baud')

serial = serial.Serial(serial_port, serial_baud, timeout=0.5)
serial.flushInput()
serial.flushOutput()
serial.flush()
serial.close()
示例#44
0
        raspistill(id_string)       #snap a pic for current slice
        
        percent=100 * float(i)/float(slices)
        printlog(percent,i)
        pos+=deg #increase current pos + deg.
        i+=1
        #end of level
        
    j+=1 #level +1


    
#END of SCAN

serial.flush()
serial.close()    #close serial

print "Scan Completed."

print "Check for skipped images..."

if(len(SKIPPED_IMAGES)):
    print "CI SONO IMMAGINI NON TRASFERITE"
    
    
for image in SKIPPED_IMAGES:
    print "Resending: " + image
    manage(CREATE, image)


manage(FINISH, '')
示例#45
0
 def change_power(command):
     if command == "pwr_event":
         serial.write(b"6")
         serial.close()
     else:
         syslog.syslog(syslog.LOG_ERR, "Invalid data sent to server")
示例#46
0
 def close_uart(self):
     """
     Close the uart connnection.
     """
     serial.close()
 def GET(self):
     serial.open()
     serial.write("d")
     serial.close()
     return
示例#48
0
def set_attenuation_fix_value(vendor_channel_info, channel_value):
    """This keyword can change attenuation value once, with different kind of PA equipment

    | Input Parameters       | Man. | Description |
    | vendor_channel_info    | Yes  | vendor, connection type, and channels |
    | channel_value          | Yes  | the attenuation value you want to set, scope is 0~127 |

    Example
    For HuaXiang PA(serial port)
    | Set Attenuation Fix Value | HX:Com2 | 3 |
    For HuaXiang PA(Eth port)
    | Set Attenuation Fix Value | HX:192.168.1.18:2 | 3 |
    For HaoJing PA(Eth port)
    | Set Attenuation Fix Value | HJ:192.168.1.18,10001:2 | 3 |
    For HaoJing PA(serial port)
    | Set Attenuation Fix Value | HJ:COM2:2 | 3 |
    For JieXi PA (socket)
    | Set Attenuation Fix Value | JX:192.168.1.18,80:2 | 3 |
    """
    if vendor_channel_info == "":
        print "*INFO* There is no attenuator on you test bed, Return!"
        return
    channel_value = int(channel_value)

    tmp = vendor_channel_info.split(':')
    vendor = tmp[0]
    conn_type = tmp[1]

    if vendor == "HX" and not re.match('^\d+.\d+.\d+.\d+$', conn_type):
        serial = _serial_open(conn_type)
        try:
            if serial:
                set_value = _set_HX_channel_command(channel_value)
                ReadBackValue = _serial_write_and_read_HX(serial, set_value, 6)
                if hex(channel_value) == ReadBackValue[3] and \
                              hex(32) == ReadBackValue[2]:
                    print "Set channel_value %d Ok" % channel_value
                else:
                    raise Exception, "set_value Fail"
        finally:
            serial.close()

    elif vendor == 'HX' and re.match('^\d+.\d+.\d+.\d+$', conn_type):
        if channel_value < 0 or channel_value > 126:
            raise Exception, "Channel value most be in 0dB to 126dB, '%d' is invalid !" % channel_value
        ip = conn_type
        channel = int(tmp[2])
        value = channel_value * 2
        num = _dec2hex(channel)
        if value == 0:
            val = '0'
        else:
            val = _dec2hex(value)
        if channel < 16 and value < 16:
            inf = ['$HX,C,','0',num,'0',val,'*']
            cmd = ''
            cmd = ''.join(inf)
        if channel < 16 and value >= 16:
            inf = ['$HX,C,''0',num,val,'*']
            cmd = ''
            cmd = ''.join(inf)
        if channel >= 16 and value < 16:
            inf = ['$HX,C,',num,'0',val,'*']
            cmd = ''
            cmd = ''.join(inf)
        if channel >= 16 and value >= 16:
            inf = ['$HX,C,',num,val,'*']
            cmd = ''
            cmd = ''.join(inf)
        crc = _CRC8(0, cmd)
        crc = crc[2:4].upper()
        if len(crc) == 1:
            crc = '0' + crc
        cmd = cmd + crc
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((ip, 4001))
            sock.send(cmd)
            print "Cmd: ", cmd
            res=sock.recv(1024)
            print ">>>" , res
        finally:
            sock.close()

    elif vendor == 'HJ':
        channel = tmp[2]
        if conn_type.startswith('COM'):
            serial = _serial_open(conn_type)
            try:
                if serial:
                    read_back_msg = _serial_write_and_read_HJ(serial, \
                                     "ATT %s %d\r\n" % (channel, channel_value))
                    print read_back_msg
            finally:
                serial.close()
        else:
            sock = _socket_open(conn_type)
            try:
                if sock:
                    read_back_msg = _socket_write_and_read_HJ(sock, \
                                    "ATT %s %d\r\n" % (channel, channel_value))
                    print read_back_msg
            finally:
                sock.close()
    elif vendor.upper().strip() == "JX":
        port = conn_type.split(',')[1]
        if port == '80':
            with JieXi(conn_type) as s:
                s.socket_write("BO%s %s" %(tmp[2], channel_value))
        elif port == '1000':
            with JieXi(conn_type) as s:
                s.socket_write("SET:%s:%s" %(tmp[2], channel_value))
        else:
            raise Exception, "Wrong port input, 8pipe is 80, 16pipe is 1000."
        time.sleep(1)
    else:
        raise Exception, "Please check the argument1, sample as: \
示例#49
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()
示例#50
0
def change_attenuation_value_period(vendor_channel_info, min_value, max_value, step, delay = '1'):
    """This keyword can change attenuation value period, with different kind of PA equipment

    | Input Parameters      | Man. | Description |
    | vendor_channel_info   | Yes  | vendor, connection type, and channels |
    | min_value              | Yes  | the min value you want to set(0~127) |
    | max_value              | Yes  | the max value you want to set(0~127) |
    | step                  | Yes  | att. value change step, if step > zero |
    |                       |      | the value change from low to high, |
    |                       |      | otherwise change from high to low |
    | delay                 | No   | attenuation value change delay time, unit: s |

    Example
    For HuaXiang PA(serial port)
    | Change Attenuation Value Period | HX:Com116 | 3 | 20 | 3 | 2 |
    For HuaXiang PA(Eth port)
    | Change Attenuation Value Period | HX:192.168.1.18:2 | 3 | 20 | 3 | 2 |
    For HaoJing PA(Eth port)
    | Change Attenuation Value Period | HJ:192.168.1.18,10001:2 | 3 | 33  | 2 | 2 |
    For HaoJing PA(serial port)
    | Change Attenuation Value Period | HJ:COM1:2 | 3 | 33  | -2  | 1 |
    For JieXi PA (socket)
    | Change Attenuation Value Period | JX:192.168.0.80,10001:2 | 3 | 33  | 2 | 2 |

    """
    if vendor_channel_info == "":
        print "*INFO* There is no attenuator on you test bed, Return!"
        return
    step = int(step)
    min_value = int(min_value)
    max_value = int(max_value)
    delay = int(delay)

    if 0 == step:
        raise Exception, "The step should be non-zero, pls modify it!"

    if min_value > max_value:
        raise Exception, "Pls exchange value of min_value and max_value"

    if 0 < step:
        i = min_value
    else:
        i = max_value

    tmp = vendor_channel_info.split(':')
    vendor = tmp[0]
    conn_type = tmp[1]

    if vendor == "HX" and not re.match('^\d+.\d+.\d+.\d+$', conn_type):
        serial = _serial_open(conn_type)
        try:
            if serial:
                while(min_value <= i and  max_value >= i):
                    set_value = _set_HX_channel_command(i)
                    read_value = _serial_write_and_read_HX(serial, set_value, 6)

                    if  hex(i) == read_value[3] and hex(32) == read_value[2]:
                        print "Attenuation set value %d Ok" % i
                    else:
                        raise Exception, "Attenuation set value Failed!"
                    i += step
                    time.sleep(delay - 0.2)

        finally:
            serial.close()

    elif vendor == "HX" and re.match('^\d+.\d+.\d+.\d+$', conn_type):
        if min_value < 0 or max_value > 126:
            raise Exception, "Channel value most be in 0dB to 126dB !"
        ip = conn_type
        channel = int(tmp[2])
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.connect((ip, 4001))
            while(min_value <= i and  max_value >= i):
                value = i * 2
                num = _dec2hex(channel)
                if value == 0:
                    val = '0'
                else:
                    val = _dec2hex(value)
                if channel < 16 and value < 16:
                    inf = ['$HX,C,','0',num,'0',val,'*']
                    cmd = ''
                    cmd = ''.join(inf)
                if channel < 16 and value >= 16:
                    inf = ['$HX,C,''0',num,val,'*']
                    cmd = ''
                    cmd = ''.join(inf)
                if channel >= 16 and value < 16:
                    inf = ['$HX,C,',num,'0',val,'*']
                    cmd = ''
                    cmd = ''.join(inf)
                if channel >= 16 and value >= 16:
                    inf = ['$HX,C,',num,val,'*']
                    cmd = ''
                    cmd = ''.join(inf)
                crc = _CRC8(0, cmd)
                crc = crc[2:4].upper()
                if len(crc) == 1:
                    crc = '0' + crc
                cmd = cmd + crc
                sock.send(cmd)
                res=sock.recv(1024)
                i += step
                time.sleep(delay - 0.2)
        finally:
            sock.close()

    elif vendor == 'HJ':
        channel = tmp[2]
        if conn_type.startswith('COM'):
            serial = _serial_open(conn_type)
            try:
                if serial:
                    while(min_value <= i and  max_value >= i):
                        read_back_msg = _serial_write_and_read_HJ(serial, \
                                               "ATT %s %d\r\n" % (channel, i))
                        print read_back_msg
                        i += step
                        time.sleep(delay - 0.2)
            finally:
                serial.close()
        else:
            sock = _socket_open(conn_type)
            try:
                if sock:
                    while(min_value <= i and  max_value >= i):
                        read_back_msg = _socket_write_and_read_HJ(sock, \
                                               "ATT %s %d\r\n" % (channel, i))
                        print read_back_msg
                        i += step
                        time.sleep(delay - 0.2)
            finally:
                sock.close()
    elif vendor.upper().strip() == "JX":
        port = conn_type.split(',')[1]
        with JieXi(conn_type) as s:
            while (min_value <= i and  max_value >= i):
                if port == '80':
                    cmd = "BO%s %s" %(tmp[2], i)
                elif port == '1000':
                    cmd = "SET:%s:%s" %(tmp[2], i)
                else:
                    raise Exception, "Wrong port input, 8pipe is 80, 16pipe is 1000."
                s.socket_write(cmd)
                i += step
                time.sleep(delay - 0.2)

    else:
        raise Exception, "Please check the argument1, sample as: \