首页 > 解决方案 > 让 XBee 在由 Node.js 启动的 python 脚本中连接

问题描述

我正在使用 Python 脚本连接到 Xbee。当从终端执行 python 脚本时,我已经设法让这个脚本正常工作并连接到 Xbee。我现在正在尝试使用名为“PythonShell”的 npm 包从 Node.js 执行脚本。

PythonShell 工作正常。当我运行其他脚本时,它工作正常,消息从 python shell 发送回节点。

当我尝试运行下面的脚本时,我似乎没有得到任何回报,或者似乎什么也没有发生。

Python脚本:


'''
-----------------------------------------------
|                                             |
|       RF Receive Data Python Script         |
|                                             |
-----------------------------------------------

Script used to connect to the XBee RF module to receive
incoming data and to save to separate csv files.

'''


from digi.xbee.devices import XBeeDevice
import time
from csv import writer
import datetime
import sys

baud_rate = 115200
COM_port = "/dev/ttyUSB0"

if sys.argv[1] != None and sys.argv[2] != None:
    baud_rate = sys.argv[1]
    COM_port = sys.argv[2]
    print(baud_rate)
    print(COM_port)


#Order of the CSV files and data variables

'''
AMS - AMS_Data.csv
ECU - ECU_Data.csv
INV - INV_Data.csv
POS - POS_Data.csv

data vars  | csv index ranges
̅̅̅‾‾‾‾‾‾‾‾‾‾‾|‾‾‾‾‾‾‾‾‾‾‾‾‾
AMS        |  [0] - [34]
ECU        |  [35] - [49]
INV        |  [50] - [96]
POS        |  [97] - 

'''

#XBee setup and config

print("connecting to Xbee device at")
print(COM_port)

device = XBeeDevice("/dev/ttyUSB0", baud_rate) #COM port and Baud rate

#device.open() #Open connection with the Xbee

device.execute_command("AP", bytearray('\x01', 'utf8'))
device.set_parameter("BD", bytearray('\x07', 'utf8'))
print("Connected to the Xbee Successfully!")
#Add a callback for when the XBee receives data
def my_data_received_callback(xbee_message):
    address = xbee_message.remote_device.get_64bit_addr()
    data = xbee_message.data.decode('utf8')
    #add a timestamp which will be appended to each of the files
    time = str(datetime.datetime.now().time()).split('.')[0] + "." + str(datetime.datetime.now().time()).split('.')[1][0:3]
    #Split the data up using the ',' delimiter
    message = data.split(",")

    #Now save data into the files based on the ranges shown in the table above
    #AMS Data being saved into the AMS_Data.csv file
    AMS_File = open("../public/AMS_Data.csv", "a")
    AMS_CSV_Writer = writer(AMS_File)
    AMS_array = message[0:34]
    AMS_array.append(time) #Append the time stamp to the end of the array
    AMS_CSV_Writer.writerow([i for i in AMS_array])
    AMS_File.close()

    #ECU Data being saved into the ECU_Data.csv file

    ECU_File = open("../public/ECU_Data.csv", "a")
    ECU_CSV_Writer = writer(ECU_File)
    ECU_array = message[35:49]
    ECU_array.append(time)
    ECU_CSV_Writer.writerow([i for i in ECU_array])
    ECU_File.close()

    #INV data being saved into the INV_Data.csv file

    INV_File = open("../public/INV_Data.csv", "a")
    INV_CSV_Writer = writer(INV_File)
    INV_array = message[50:96]
    INV_array.append(time)
    INV_CSV_Writer.writerow([i for i in INV_array])
    INV_File.close()

    #Need to add the POS and PRI data saving here!

#Add the callback to the device

device.add_data_received_callback(my_data_received_callback)

while True:
    time.sleep(0.01)

但是,如果我注释掉 device.open(),那么我设法将一些消息返回给 Node.js,但是它们是错误消息,指出“NoneType”对象没有属性“is_op_mode_valid”。我认为这个错误是因为 Xbee 没有连接。所以似乎 device.open() 命令似乎停止了 python 程序,并且不允许它向 node.js 发送任何消息。

这是我的 Node.js 代码:


app.post("/xbee/connect", function(req, res){
    var baudRate = req.body.baud_rate;
    var COMport = req.body.com_port;
    var XbeeID;
    
    if(xbee_connected === false && testing_status === false){
        xbeeShell = new PythonShell('./python_scripts/receive-telem.py', {args:[baudRate, COMport]});
        xbee_connected = true;
    }
    xbeeShell.on('message', function(message){
        io.to('Data-link Room').emit('log-data', {data:message});
    })
    xbeeShell.end(function(err) {
        if(err){
            console.log(err)
            io.to('Data-link Room').emit('log-data', {data:String(err)});
            xbee_connected = false;
        }
    })
    res.send("success");
})

任何帮助,将不胜感激。

标签: pythonhtmlcssnode.jsuser-interface

解决方案


为了让它发挥作用,

sys.stdout.flush()

在while循环的某个地方需要。这是因为程序进入了一个while循环。所以在循环中的某个地方需要刷新命令来刷新标准输出。


推荐阅读