Search code examples
pythontkinterzigbee

Zigbee and Python


I have designed a Python GUI, that accepts a text and display it on a label, also, I have a serial port module that takes that text and send it to a serial port. I want to display this text in a CC2530 Zigbee board, in the LCD, then I have to use the UART port, which is a Serial port

I have installed pySerial, and XBee, latest versions, and I am using Python 3.4 then can somebody help me connecting my GUI with Zigbee and display the text into the LCD

this is my code so far

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

Thanks


Solution

  • My code in python is right, and i was sending the commands through he serial port without any issues, the thing was in the Zigbee board that needed to accept and use the UART port and display the data on the LCD, for that I got some external help and I got this info

    Program the Serial Port in the CC2530EB

    Setting UP

    1. The RS232 port Enable switch on the board should be switched to ON .

    2. Port Configuration:

    A Serial application can be found from Zstack v2.4 . Copy the two files and include in the sample application project. These two files are “SerialApp.c” and “SerialApp.h”

    In SerialApp, an initialization function is defined.

    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 );
    }
    

    This function should be called from the program initialization phase. It can be inserted to the function

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

    The Port setup is Baud rate: 38400 Data : 8 bit Stop bit: 1 No Parity check HW Flow control: true

    1. Try with HyperTerminal from a Win PC. Match the set up on the CC2530EB.

    2. The output to LCD will automatically dumped to the serial port by the sample program. Comment that out will stop the dumping

      “MT_TASK.c”

      ifdef MT_UART_DEFAULT_PORT

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

      endif

    3. To send character(s) to PC Call the function

      extern uint16 HalUARTWrite ( uint8 port, uint8 *pBuffer, uint16 length ); Eg actualWriteLen= HalUARTWrite(0, testBuf, 4 ); // added by JW

    4. Receive character(s) from PC Use the call back function specified in the SerialApp_Init Eg

      SerialApp_CallBack_JW

    Whenever this function is called, it try to read the receiving buffer

    A simple example

    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. It seems that the characters sent to PC COM will be echoed back to the serial Port on the CC2530EB.

    this worked for me hope it will work for you guys, please pull me up in this question