基于tziota实现的简单聊天室

目录

  • 基于tziota实现的简单聊天室
    • 环境
    • 说明
    • 源码
    • 运行效果

基于tziota实现的简单聊天室

本文博客链接:http://blog.csdn.net/jdh99,作者:jdh,转载请注明.

环境

  • python版本:3.5

说明

首先需要安装tziota包:

pip install tziota

关于tziota可以参考:《TZ-IOT发布Python SDK:tziota》

源码

import socket
import threading
import tziota
import tkinter as tk


_ia = 0
_pwd = 0
_dst_ia = 0
_app = None


def main():
    threading.Thread(target=gui_thread).start()

    while _ia == 0 or _pwd == 0 or _dst_ia == 0:
        pass

    param = tziota.Param()
    param.local_ip = "0.0.0.0"
    param.local_port = 14155
    while True:
        if is_open(param.local_ip, param.local_port):
            param.local_port += 1
        else:
            break
    print(param.local_port)
    param.local_ia = _ia
    param.pwd = _pwd
    param.server_ip = "115.28.86.171"
    param.server_port = 14129
    param.server_ia = 0x2140000000000002
    tziota.init(param)
    tziota.register_callback_rx(deal_rx)


def gui_thread():
    global _app

    root = tk.Tk()
    _app = App(root)
    root.mainloop()


class App:
    def __init__(self, root):
        frame = tk.Frame(root)
        frame.pack()
        root.title('聊天室')

        self.text = tk.Text(frame)
        self.text.grid(row=0, column=0)

        self.group = tk.LabelFrame(frame)
        self.group.grid(row=0, column=1)

        tk.Label(self.group, text='IA:').grid(row=0, column=0)
        self.v_ia = tk.StringVar()
        tk.Entry(self.group, textvariable=self.v_ia).grid(row=0, column=1)

        tk.Label(self.group, text='密码:').grid(row=1, column=0)
        self.v_pwd = tk.StringVar()
        tk.Entry(self.group, textvariable=self.v_pwd).grid(row=1, column=1)

        tk.Label(self.group, text='对方IA:').grid(row=2, column=0)
        self.v_dst_ia = tk.StringVar()
        tk.Entry(self.group, textvariable=self.v_dst_ia).grid(row=2, column=1)

        tk.Button(self.group, text='确定', command=self.set_param).grid(row=3, column=0, columnspan=2)

        self.v_input = tk.StringVar()
        tk.Entry(self.group, textvariable=self.v_input).grid(row=4, column=0, columnspan=2)
        tk.Button(self.group, text='发送', command=self.send).grid(row=4, column=2)

    def set_param(self):
        global _ia, _pwd, _dst_ia
        _ia = int(self.v_ia.get(), base=16)
        _pwd = self.v_pwd.get()
        _dst_ia = int(self.v_dst_ia.get(), base=16)

    def send(self):
        if len(self.v_input.get()) > 0:
            tziota.send(_dst_ia, self.v_input.get().encode())


def is_open(ip, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        s.bind((ip, port))
        s.close()
        return False
    except:
        return True


def deal_rx(ia, data):
    global _app
    _app.text.insert(tk.END, 'IA:0x%016x %s\n' % (ia, data.decode()))


if __name__ == '__main__':
    main()

运行效果

可以使用以下两个测试账号:

  • 2140:0000:0000:0100,密码:“123”
  • 2140:0000:0000:0101,密码:“456”

基于tziota实现的简单聊天室_第1张图片

你可能感兴趣的:(TZ-IOT,python)