Beispiel #1
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()
Beispiel #2
0
def main():
    # configure the serial connections (the parameters differs on the device you are connecting to)
    global serial
    serial = serial.Serial(
        port='/dev/ttyUSB0',
        baudrate=19200,
        parity=serial.PARITY_NONE,
        stopbits=serial.STOPBITS_ONE,
        bytesize=serial.EIGHTBITS,
        timeout=0.5  # Timeout for reading data off serial port
    )

    serial.isOpen()

    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect("192.168.1.199", 1883, 60)

    # Blocking call that processes network traffic, dispatches callbacks and
    # handles reconnecting.
    # Other loop*() functions are available that give a threaded interface and a
    # manual interface.
    client.loop_forever()
Beispiel #3
0
            def inner(self):
                try:
                    if not serial.isOpen():
                        if not serial.open(QIODevice.ReadWrite):
                            self.error.emit(
                                "can't not open %s,error code:%d" %
                                (serial.portName(), serial.error()))
                            return
                    # locker = QMutexLocker(self.mutex) ## when wait for read can't wait for waitWritten
                    if serial.waitForReadyRead(10):
                        # if serial.bytesAvailable() > 0:
                        requestData = bytes()
                        requestData = serial.readAll()
                        while serial.waitForReadyRead(10):
                            requestData += serial.readAll()

                        bData = bytes(requestData)
                        hexData = ' '.join('{:02x}'.format(x) for x in bData)
                        # m = re.search('(7e.{31,31}e7)', hex)
                        # if m:
                        #     requestStr = m.group(0)
                        #     # requestStr = str(bytes(requestData))
                        #     self.request.emit(requestStr)
                        self.request.emit(hexData)
                    else:
                        self.timeout.emit("Wait read ready timeout %s" %
                                          (QTime.currentTime().toString()))
                except TypeError as e:
                    print('Got Error', e)
Beispiel #4
0
 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
Beispiel #5
0
def on_connect():
    print('连接成功')
    if serial.isOpen():
        time.sleep(8)
        serial.readlines()
        serial.flushOutput()
        printmessage_json = {
            'id': 1,
            'on_off': 1,
            'status': {
                'chambertemperature': 0,
                'bedtemperature': 0
            },
            'printing': ps.printing,
            'endprint': ps.endprint,
            'startprint': ps.startprint
        }
        sio.emit('status', printmessage_json)
        print("打印机上线,发送打印机状态:")
        print(printmessage_json)
    else:
        printmessage_json = {
            'id': 1,
            'on_off': 0,
            'status': {
                'chambertemperature': 0,
                'bedtemperature': 0,
            },
            'printing': ps.printing,
            'endprint': ps.endprint,
            'startprint': ps.startprint
        }
        sio.emit('status', printmessage_json)
        print("打印机连接失败")
        print(printmessage_json)
Beispiel #6
0
def openSerial():
    # ser=serial.Serial("COM2",19200,timeout=3600)
    th = threading.Thread(target=rcv_data)
    th.setDaemon(True)
    th.start()
    if serial.isOpen():
        print("open succeed >", "COM2")
    else:
        print("open failed >", "COM2")
Beispiel #7
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)))
Beispiel #8
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)
Beispiel #9
0
def receiveMessage(port, baudrate, desiredCountOfReceivedMessages):
    import serial

    # b'...' - a sequence of octets (integers between 0 and 255)

    #Connect the serial port
    serial = serial.Serial(port,
                           timeout=None,
                           baudrate=baudrate,
                           xonxoff=False,
                           rtscts=False,
                           dsrdtr=False,
                           bytesize=serial.EIGHTBITS,
                           stopbits=serial.STOPBITS_ONE,
                           parity=serial.PARITY_NONE)

    if serial.isOpen():
        print("waiting for new message")
    else:
        print("Serial port is not open")
        print(serial.name)  # check which port was really used

    #serial.write(mode)             # write a string

    #Get data from serial as fast as possible
    buffer = []
    canAppendToBuffer = 0
    messageComplete = 0
    countOfReceivedMessages = 0
    while messageComplete != 1:
        waiting = serial.in_waiting  # find num of bytes currently waiting in hardware
        for c in serial.read(waiting):  # read them, convert to ascii
            currentCharacter = chr(c)
            # special character - begining of command was found
            if (currentCharacter == '<'):
                canAppendToBuffer = 1
            # special character - end of message
            elif (currentCharacter == '>'):
                countOfReceivedMessages += 1
                if (countOfReceivedMessages == desiredCountOfReceivedMessages):
                    messageComplete = 1

            # normal data
            if (canAppendToBuffer == 1):
                buffer.append(currentCharacter)

    #write data into file
    receivedString = ''.join(buffer)
    receivedRows = receivedString.split('\n')

    #remove blank characters
    while ("" in receivedRows):
        receivedRows.remove("")

    return receivedRows
Beispiel #10
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)
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)
Beispiel #12
0
def write_to_ee(address,values):
	if type(values) != list:
		print 'Error, values must be a list of ints'
	msg = '\x01'
	msg += dec2hex(address)
	number = len(values) * 2
	msg += dec2hex(number)[1:2]
	for x in range(number/2):
		msg += dec2hex(values[x])
	if serial.isOpen():
		print "Writing:", msg.encode('hex')
		serial.write(msg)
	else:
		print 'Error, the serial port is not open.'
	return
Beispiel #13
0
def read_hex_from_ee(address):
	serial.flushOutput()
	serial.flushInput()
	msg = '\x02'
	msg += dec2hex(address)
	if serial.isOpen():
		serial.write(msg)
	else:
		print 'Error, the serial port is not open.'
		return
	value = serial.readline()
	if value == '':
		print 'Error, did not receive response from the Micro Controller.'
		return None
	value = value.strip()
	return value
Beispiel #14
0
def get_data():
    if serial.isOpen() :
        print("open success!"+'\n请输入: ')
    else :
        print("open failed")

    while True:
        data = serial.readall().decode('utf-8') #.strip().decode('utf-8')
        if data == '':
            continue
        else:
            break
        sleep(10)

    if data != b'' :
        data=re.findall(r"\d+\.?\d*",data)
        return data
Beispiel #15
0
def sendMessage(port, baudrate, message):
    import serial
    serial = serial.Serial(port,
                           timeout=None,
                           baudrate=baudrate,
                           xonxoff=False,
                           rtscts=False,
                           dsrdtr=False,
                           bytesize=serial.EIGHTBITS,
                           stopbits=serial.STOPBITS_ONE,
                           parity=serial.PARITY_NONE)
    if serial.isOpen():
        print("Sending command")
    else:
        print("command wasnt send")
        print(serial.name)  # check which port was really used

    serial.write(message)  # write a string
Beispiel #16
0
def Normalchaxun(serial, self):
    while self.scanTag == False:
        continue
    MyLog.info("ScanPortList Finished!")

    while self.ThreadTag:  #Main Loop is here!
        if serial.isOpen():
            if len(SharedMemory.LockList) > 0:
                for lock in SharedMemory.LockList:
                    self.ChaXun(lock.addr)
                    t.sleep(
                        0.05
                    )  #50ms等待时间,防止查询太快导致485紊乱,在Write和Recv中已有50ms延迟,此处可以省略
            else:
                MyLog.error(
                    'No Lock in the list from serial422.py Normalchaxun')
            t.sleep(self.ScanLockFreq)  #轮训间隔,每间隔N秒进行一次轮训获取连接车位锁的状态
    pass
Beispiel #17
0
def on_connect():
    global printing
    global endprint
    global startprint
    print('connection established')
    if serial.isOpen():  
        time.sleep(8)
        serial.readlines()
        serial.flushOutput()
        serial.write("M105\n".encode('ascii') )
        time.sleep(0.5)
        tem_message=serial.readline()  
        time.sleep(0.5)
        printmessage_json = {
                    'id': 1,
                    'on_off': 1,
                    'statue': {
                    'chambertemperature':random.randint(1,20),
                    'bedtemperature': random.randint(1,20)
                    },
                    'printing':printing,
                    'endprint':endprint,
                    'startprint':startprint
                    }
        sio.emit('state', printmessage_json)
        print("打印机上线")
        print(printmessage_json)
    else:
        printmessage_json = {
                    'id': 1,
                    'on_off': 0,
                    'statue': {
                    'chambertemperature':'',
                    'bedtemperature': '',
                    },
                    'printing':printing,
                    'endprint':endprint,
                    'startprint':startprint
                    }
        sio.emit('state', printmessage_json)
        print("打印机连接失败")
        print(printmessage_json)
Beispiel #18
0
            def inner(self):
                try:
                    if not serial.isOpen():
                        if not serial.open():
                            # self.error.emit("can't not open %s,error code:%d"%(serial.portName(),serial.error()))
                            return

                    if serial.inWaiting() == 0:
                        return

                    data = bytes()
                    requestData = bytes()
                    # print('wait:',serial.in_waiting)
                    requestData = serial.read(serial.inWaiting())
                    hexData = ' '.join('{:02x}'.format(x) for x in requestData)
                    self.request.emit(hexData)
                    # else:
                    #     self.timeout.emit("Wait read ready timeout %s"%(QTime.currentTime().toString()))
                except TypeError as e:
                    print('Got Error', e)
Beispiel #19
0
def readSerialPort():
    isOpen = serial.isOpen()
    if(isOpen) :
        print 'COM4 serial port is opened!'

    fmt = '!3h'
    while(1):
        header = ord(serial.read())
        if(header != 0x88 or header == -1):
            continue
        header = ord(serial.read())
        if(header != 0xAF or header == -1):
            continue
        header = ord(serial.read())
        if(header != 0x1C or header == -1):
            continue

        content = serial.read(29)
        roll,pitch,yaw = struct.unpack_from(fmt,content,18)

        print pitch / 100.0 , roll / 100.0,yaw / 10.0
Beispiel #20
0
def serial_send_data(send):
    import serial

    # 连接串口
    serial = serial.Serial('COM1', 9600, timeout=2)  # 端口号, 波特率, 超时
    if serial.isOpen():
        print('串口已打开')
        send = send.upper()  # 便于识别全部转换为大写
        send = str.encode(send)  # str转bytes
        # print('You Send Data:', msg)
        serial.write(send)  # 串口写数据

        while True:
            data = serial.read(40)  # 串口读200位数据
            time.sleep(0.5)
            break
        data = bytes.decode(data)
        data = re.findall('\n\r(.*)\n\r', data)
        if (re.findall('Temperature', data[0])):
            data[0] = data[0] + '℃'
        print('receive data is :', data[0])
        return data[0]
Beispiel #21
0
def main():
    iob=Io_board("Io_board_node")
    iob.Init_node()
    iob.Io_Sub("io_state")
    import serial
    serial = serial.Serial('/dev/ttyUSB2', 115200, timeout=0.5)  #/dev/ttyUSB0
    if serial.isOpen() :
        print("open port success")
    else :
        print("open port failed")
    rate = rospy.Rate(4)
    #rostopic pub /ur_driver/URScript std_msgs/String ""
    while not rospy.is_shutdown():
        #data =recv(serial)
        if len(iob.iostatebuff)!=0:
            iocmd=iob.iostatebuff[-1]
            print("receive : ",iocmd)
            time.sleep(1)
            serial.write(iocmd.decode("hex")) #数据写回
        else:
            pass
        # data ='55C81900000055'
        rate.sleep()
Beispiel #22
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)
Beispiel #23
0
        return False


file_time = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
#mk_time =   time.strftime("%Y_%m_%d",time.localtime())
#mkpath='./' + mk_time
day = get_utc_day()
mkpath = './' + day
mkdir(mkpath)
log_file = mkpath + '/' + 'user_' + file_time + '.bin'
print log_file

if __name__ == '__main__':
    #serial = serial.Serial(com_set, 115200, timeout=0.5)  #/dev/ttyUSB0
    serial = serial.Serial(com, 460800, timeout=1)
    if serial.isOpen():
        print("open success")
    else:
        print("open failed")

    while True:
        data = recv(serial)
        #print(data)
        #print("receive : ",data)
        if data != '' and file_init_flag == 0:
            fh = open(log_file, "wb")
            file_init_flag = 1
        if file_init_flag == 1:
            fh.write(data)
        #serial.write(data)
 def isConnected(self):
     return serial.isOpen()
Beispiel #25
0
            print "A necessary key is not specified: " + msg
            return

        mqttclient.publish('kh/temperatureSensor/' + data['id'] + '/rssi', rssi)
        mqttclient.publish('kh/temperatureSensor/' + data['id'] + '/temperature', data['temp'])
        mqttclient.publish('kh/temperatureSensor/' + data['id'] + '/battery', data['battpct'])
        mqttclient.publish('kh/temperatureSensor/' + data['id'] + '/batteryVoltage', data['batt'])
        mqttclient.publish('kh/temperatureSensor/' + data['id'] + '/humidity', data['rh'])
    else:
        print "Unknown HWType: " + msg
        return


serial = serial.Serial(serialPortName, serialPortBaud, timeout=None)

if serial.isOpen() != True:
    print "Port wasn't opened, exiting!"
    sys.exit

port = io.TextIOWrapper(io.BufferedRWPair(serial, serial, 1), newline = '\r\n', encoding = 'ascii')

mqttclient = mqtt.Client()
mqttclient.connect(mqttServer)

while 1:
    recv = port.readline()

    recv = re.sub('\r', '', recv)
    recv = re.sub('\n', '', recv)

    handleMessage(recv)
Beispiel #26
0
 def listenForEvents(self, serial):
     while(serial.isOpen()):
         event = serial.readline().decode('utf-8').strip()
         self.loop.run_in_executor(None, self.callback, event)
Beispiel #27
0
	def __init__(self,serial):
		self.serial = serial
		print serial.isOpen()
		self.waitingReply = False
Beispiel #28
0
        write.append(data[i])
        i += 1
    write[1] = 3 + write_len # data len
    set_checksun(write)
    sndmsg = bytearray(write)
    snd_bytearray_uart(sndmsg)
    return wait_dg_ack(CMD_WRITE_CH_ACK, 5)


if __name__ == "__main__":

    serial.port = "/dev/ttyUSB2"
    mac = "229900000003"

    serial.open()
    if serial.isOpen():
        try:
            signal.signal(signal.SIGINT, signal_handler)

            readThread = read_thread(serial)
            readThread.start()
            while not app_exit:

                #data = "220302010001"
                #sndmsg = binascii.a2b_hex(data)
                # let dg scan adv

                if dg_scan_ble(mac):
                    if dg_connect_device(mac):

                        # set listening , value's handler + 1 write [0x01 0x00]
    # Caso a temperatura lida por esse sensor seja maior do que o maximo esperado, envia para o robo o numero deste sensor
    def check_and_notify(self, serial, temp):
        if float(temp) > MAX_TEMP:
            print("warning robots")
            if serial:
                serial.write(
                    "{number}$".format(number=self.number[2]).encode("utf-8"))


if __name__ == "__main__":

    # Conexão com a porta serial para o XBee
    try:
        serial = serial.Serial(USB_PORT, 57600, timeout=1)

        if not serial.isOpen():
            serial.open()
    except SerialException:
        serial = None
        print("Serial não conectada")

    # Inicialização do socket para receber as conexões
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    server_socket.bind(('0.0.0.0', PORT))
    server_socket.listen(10)

    CONNECTION_LIST.append(server_socket)

    print("Server started on port " + str(PORT))
Beispiel #30
0
MAZE_SIZE_X = 8  # size of maze (number of tiles)
MAZE_SIZE_Y = 8
OBJ_COLOR_LOW = np.array([38, 70, 90])  #lower end of object/ball
OBJ_COLOR_HIGH = np.array([83, 195, 250])  # higher end
font = cv2.FONT_HERSHEY_PLAIN

cv2.namedWindow('src')  #create windows to display images
cv2.namedWindow('cpy')
cv2.namedWindow('solved')
cv2.moveWindow('src', 0, 0)  # move windows so they don't overlap
cv2.moveWindow('cpy', 500, 0)
cv2.moveWindow('solved', 1000, 0)

serial = serial.Serial('COM8', 9600)  #initialize serial
time.sleep(1)  # wait to make sure serial is initialized
print "\nSerial port is open?:", serial.isOpen()
brightness_led = 50  # brightness of leds located on top, 0-255

serial.write("15,15," + str(brightness_led) + ",")  #level out maze

#--------END OF SETUP--------

cap = cv2.VideoCapture(0)

_, img_src = cap.read()
path_list, img_maze_solved = mazeAnalysisAndStuff(
    img_src, 8,
    8)  # find path through maze; returns: list of path tiles, image with data
cv2.imshow('solved', img_maze_solved)
if path_list is None:
    sys.exit()
Beispiel #31
0
        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 - time1)
        collectTime = 30
        #print(collectTime)
        if (time2 - time1 == collectTime):
            print('close')

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

except Exception as e:
    print(e)

import numpy as np
import matplotlib.pylab as plt
import itertools

from collections import OrderedDict

frequency = 1250

per_qian = 0.2
per_zhong = 0.4
per_hou = 1 - per_qian - per_zhong