Python: SerialException: попытка использовать порт, который не открыт

Я использую ниже код python для связи с Xbee + Arduino от моего координатора MAC+XBee. Но я получаю ошибку port not open при попытке отправить пакет через последовательный.

Сообщение об ошибке

Sending LOAD
Traceback (most recent call last):
&nbsp; File "xbeeTxRx.py", line 139, in <module>
&nbsp; &nbsp; main()
&nbsp; File "xbeeTxRx.py", line 109, in main
&nbsp; &nbsp; sendPacket(WHERE, LOADString)
&nbsp; File "xbeeTxRx.py", line 49, in sendPacket
&nbsp; &nbsp; data = what)
&nbsp; File "/Library/Python/2.7/site-packages/xbee/base.py", line 399, in send
&nbsp; &nbsp; self._write(self._build_command(cmd, **kwargs))
&nbsp; File "/Library/Python/2.7/site-packages/xbee/base.py", line 91, in _write
&nbsp; &nbsp; self.serial.write(frame)
&nbsp; File "/Library/Python/2.7/site-packages/serial/serialposix.py", line 517, in write
&nbsp; &nbsp; raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open

Код ниже. Проблема возникает, как только я добавляю Def main. Если нет Def main, и я вызываю sendPacket (где, LOADString), то он работает хорошо.

#this port address will change
PORT = '/dev/tty.usbserial-A104IC2U'            
BAUD_RATE = 9600


WHERE = 'x00x13xA2x00x40xF7x43xC1'


UNKNOWN = 'xffxfe' # This is the 'I don't know' 16 bit address
dataString='LOAD'
LOADString='LOAD:T1name=-60.00&T2name=-40.00&T3name=-20.00&T4name=0.00&T5name=+20.00&T6name=+60.00'
STOPString='STOP'

packets = Queue.Queue()

# Open serial port
ser = serial.Serial(PORT, BAUD_RATE) 

def message_received(data):
        packets.put(data, block=False)
        print 'gotta packet'

def sendPacket(where, what):
        zb.send('tx',
                dest_addr_long = where,
                dest_addr = UNKNOWN,
                data = what)
        print 'Sent Packet'

def sendQueryPacket():
        sendPacket(WHERE, dataString)
        print 'Sent Query Packet'   

def handlePacket(data):
        print 'In handlePacket: ',
        print data['id'],
        if data['id'] == 'tx_status':
                print data['deliver_status'].encode('hex')
        elif data['id'] == 'rx':
                print data 
                print repr(data['source_addr_long'])
                print data['rf_data']
        elif data['id'] == 'rx_long_addr':
                print data 
                print repr(data['source_addr_long'])
                print data['rf_data']
        else:
                print 'Unimplemented frame type'



# Create XBee library API object, which spawns a new thread
zb = ZigBee(ser, callback=message_received)

def main():
        print ("Sending LOAD")
        #send load command
        sendPacket(WHERE, LOADString)
        while True:
                try:
                        time.sleep(0.1)
                        if packets.qsize() > 0:
                                print 'packet availabe'
                                newPacket = packets.get_nowait()
                                handlePacket(newPacket)
                except KeyboardInterrupt:
                        print("Sending STOP")
                        sendPacket(WHERE, STOPString)
                        break

zb.halt()
ser.close()

if __name__ == "__main__":
    main()

1 ответ

  1. Чувак ты должен поставить zb.halt()и see.close()после последнего если заявление куда ты звонишь своему главному.