Zigbee 和 Python

Zigbee and Python

我设计了一个 Python GUI,它接受文本并将其显示在标签上,此外,我还有一个串行端口模块,可以接收该文本并将其发送到串行端口。我想在 CC2530 Zigbee 板的 LCD 中显示此文本,然后我必须使用 UART 端口,这是一个串行端口

我已经安装了最新版本的 pySerial 和 XBee,我正在使用 Python 3.4 那么有人可以帮助我将我的 GUI 与 Zigbee 连接并将文本显示到 LCD

这是我到目前为止的代码

import time
import serial
import sys
import os
import glob
import tkinter as tk
from tkinter import ttk
from tkinter import *
from tkinter import messagebox
from tkinter import filedialog
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
# from PIL import Image, ImageTk
try:
  import Tkinter              
  import ttk
except ImportError:
  import tkinter as Tkinter 
  import tkinter.ttk as ttk
from datetime import datetime, timedelta
from xbee import XBee,ZigBee

def Send_it():
   global set_ser
   TE=TextEntry.get()
   History(TE)
   In_commands = (TE) #"""/"+Real_PPort+"O"+str(valve)+"V"+str(Speed)+",1D"+str(volume)+",1R\r\n""")
   set_ser.write(In_commands.encode(encoding="utf-8", errors="strict"))

def History(message):
  now = time.strftime("%I:%M:%S", time.localtime())
  mGui.text.insert("end", now + " " + message.strip() + "\n")
  mGui.text.see("end")

def serial_ports():
    mGui.update()
    if sys.platform.startswith('win'):
        ports = ['COM' + str(i + 1) for i in range(256)]
    elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
        ports = glob.glob('/dev/tty[A-Za-z]*')
    elif sys.platform.startswith('darwin'):
        ports = glob.glob('/dev/tty.*')
    else:
        raise EnvironmentError('Unsupported platform')
    result = []
    for port in ports:
        try:
            s = serial.Serial(port)
            s.close()
            result.append(port)
        except (OSError, serial.SerialException):
            pass
    return result
    mGui.update()

def mON(): # BUTTON FUNCTION
  global set_ser
  set_ser = serial.Serial()
  comm = "COM1" #COM.get() com port
  set_ser.port= comm                                                                                                                                                #serial_port                      ##########################
  set_ser.baudrate=9600
  set_ser.parity = serial.PARITY_NONE
  set_ser.stopbits=serial.STOPBITS_ONE
  set_ser.bytesize = serial.EIGHTBITS
  set_ser.timeout=1
  set_ser.open()
  History("On connection")
  mGui.update()

mGui = Tk()
mGui.title("Zigbee GUI")
mGui.geometry('650x650+650+0')
TextEntry = StringVar()
TextDisplay = StringVar()
set_ser = 0                                      # Serial port has not been     turned on

# buttons on the gui
mGui.text = tk.Text(mGui, width=111, height=35,font=("calibri",8))                                                                               # creation of the text box that records the hystory of events
mGui.vsb = tk.Scrollbar(mGui, command=mGui.text.yview, width=50)                                                            # creation of scroolbar in the text box that records the hystory of events
mGui.text.configure(yscrollcommand=mGui.vsb.set)                                                                            # creation of the text box that records the hystory of events
mGui.vsb.place(x=630, y=50)                                                                                               # allocation of the scrollbar in the GUI
mGui.text.place(x=10, y=50)                                                                                                   # allocation of the text box in the GUI

CameraHere = Label(mGui, text='History of commands sent', wraplength=200, width = 100, height=1, bg = 'white', justify = LEFT)
CameraHere.place(x=10,y=10)
tText1 = Entry(mGui, textvariable = TextEntry, width = 100)
tText1.place(x=10,y=550)                                                       # Name for valve 1 


port = serial_ports()                                                                                                       # save in a variable the identification of the serial port used
serial_port = port[0]                                                                                                       # takes the first serial port detected as the pump serial port communication

mButtonSTC = Button(mGui, text = "ON", command = mON, fg = 'white', width = 12, bg = 'Green', justify=CENTER).place(x=0,y=600)
mButtonSPC = Button(mGui, text = "GUI OFF", command = mGui.destroy, fg = 'white',width = 12, bg = 'Red', justify=CENTER).place(x=100,y=600)
mButtonCIMJ = Button(mGui, text = "Send", command = Send_it, fg = 'white', width = 12, bg = 'black', justify=CENTER).place(x=200,y=600)
mButtonDIMJ = Button(mGui, text = "Disconnect ImageJ", command = mGui.destroy, fg = 'white', width = 12, bg = 'black', justify=CENTER).place(x=300,y=600)
mButtonObjD = Button(mGui, text = "Obj Detector", command = mGui.destroy, fg = 'white', width = 12, bg = 'black', justify=CENTER).place(x=400,y=600)
mButtonTkAc = Button(mGui, text = "Take acction", command = mGui.destroy, fg = 'white',width = 12, bg = 'black', justify=CENTER).place(x=500,y=600)

mGui.mainloop() # - PRIMARY LOOP

谢谢

我在 python 中的代码是正确的,我通过串口发送命令没有任何问题,问题是在需要接受和使用 UART 端口并显示数据的 Zigbee 板上在 LCD 上,为此我得到了一些外部帮助,我得到了这个信息

在 CC2530EB 中编程串口

正在设置

  1. 板子上的RS232口Enable开关要拨到ON。

  2. 端口配置:

可以从 Zstack v2.4 找到串行应用程序。复制这两个文件并包含在示例应用程序项目中。这两个文件是 “SerialApp.c” 和 “SerialApp.h”

在SerialApp中,定义了一个初始化函数。

void SerialApp_Init( uint8 task_id )
{
  halUARTCfg_t uartConfig;

  SerialApp_TaskID = task_id;
  SerialApp_RxSeq = 0xC3; // added by JW

  afRegister( (endPointDesc_t *)&SerialApp_epDesc );

  RegisterForKeys( task_id );

  uartConfig.configured           = TRUE;              // 2x30 don't care -     see uart driver.
  uartConfig.baudRate             = SERIAL_APP_BAUD;  
  uartConfig.flowControl          = TRUE;
  uartConfig.flowControlThreshold = SERIAL_APP_THRESH; // 2x30 don't care - see uart driver.
  uartConfig.rx.maxBufSize        = SERIAL_APP_RX_SZ;  // 2x30 don't care - see uart driver.
  uartConfig.tx.maxBufSize        = SERIAL_APP_TX_SZ;  // 2x30 don't care - see uart driver.
  uartConfig.idleTimeout          = SERIAL_APP_IDLE;   // 2x30 don't care - see uart driver.
  uartConfig.intEnable            = TRUE;              // 2x30 don't care - see uart driver.
  // uartConfig.callBackFunc         = SerialApp_CallBack;  // commented out by JW
  uartConfig.callBackFunc         = SerialApp_CallBack_JW;     // added by JW
  HalUARTOpen (SERIAL_APP_PORT, &uartConfig);

#if defined ( LCD_SUPPORTED )
  HalLcdWriteString( "SerialApp", HAL_LCD_LINE_2 );
#endif

  ZDO_RegisterForZDOMsg( SerialApp_TaskID, End_Device_Bind_rsp );
  ZDO_RegisterForZDOMsg( SerialApp_TaskID, Match_Desc_rsp );
}

这个函数应该从程序初始化阶段调用。 可以插入函数

void SampleApp_Init( uint8 task_id )
{
  ……  
  //Initialize the serial port added by JW
  SerialApp_Init( 0x7f );
}

端口设置是 波特率:38400 数据:8位 停止位:1 无奇偶校验 硬件流量控制:true

  1. 在 Win PC 上尝试使用超级终端。匹配CC2530EB上的设置。

  2. LCD的输出会被示例程序自动转储到串口。注释掉将停止倾销

    “MT_TASK.c”

    ifdef MT_UART_DEFAULT_PORT

      //HalUARTWrite ( MT_UART_DEFAULT_PORT, msg_ptr, len ); // Commented out by JW
    

    endif

  3. 将字符发送到 PC 调用函数

    extern uint16 HalUARTWrite(uint8 端口,uint8 *pBuffer,uint16 长度); 例如 actualWriteLen= HalUARTWrite(0, testBuf, 4 ); // 由 JW

  4. 添加
  5. 从 PC 接收字符 使用 SerialApp_Init 中指定的回调函数 例如

    SerialApp_CallBack_JW

每当调用此函数时,它都会尝试读取接收缓冲区

一个简单的例子

static void SerialApp_CallBack_JW(uint8 port, uint8 event)
{
  (void)port;
  uint8 localBuf[81];
  uint16 receivedUARTLen;
//  ….
//  if ( event & (HAL_UART_RX_FULL | HAL_UART_RX_ABOUT_FULL ))   
//….
  {
    // testing reading from the receiving buffer  By JW
   receivedUARTLen= HalUARTRead(SERIAL_APP_PORT, localBuf, SERIAL_APP_TX_MAX);
   HalLcdWriteStringValue( localBuf,  receivedUARTLen, 16, HAL_LCD_LINE_3 );  
  }
    }
  1. 似乎发送到PC COM的字符会回显到CC2530EB上的串口。

这对我有用希望它对你们有用,请在这个问题上拉我