Django 实现mqtt web 客户端

前端html

<!DOCTYPE html>
<html lang="en">
<head>   
    <meta  charset="utf-8">
        <title>MQTT客户端</title>
    <style>
        label{
            float: left;
            width: 100px;
            text-align: right;
            margin-right: 10px;
            height:20px;
        }
    </style>
</head>
<body>
<div style="margin-left:20px;">     
    <form action="/mqtt_client" method="get">
        <!-- 连接配置开始 -->
        <h3>连接配置</h3>
        <label for="">订阅主题:</label>
        <input name="issueTopic" value="ledStatus" type="text"><br>

        <label for="">IP地址:</label>
        <input name="address" type="text" value={{address}}><br>

        <!-- <li>端口号:<input class="port" type="text" value="1883"></li> -->
        <label for="">用户名:</label>
        <input name="username" type="text" value="user1"><br>
        <label for="">密码:</label>
        <input name="password" type="text" value={{password}}><br>

        <label for="">连接状态:</label>
        <span class="connect" style="">{{res}}</span>
        <input type="submit" value="连接" style="position: fixed;left: 257px;margin-top:2px;"><br>

        <label for="" style="margin-top:10px;" >发送消息:</label>
        <input name="msg" type="text" style="width:84px;margin-top:10px;" value={{msg}} >
        <input type="submit" value="发送消息"><br>

    </form>
        
</div>
</body>
</html>

2.后端代码

from django.http import HttpResponse

from django.shortcuts import render,redirect,reverse
import re
import json
import paho.mqtt.client as mqtt #MQTT库文件
import time

msg=''
TASK_TOPIC = ''  # 客户端发布消息主题
address=''       # IP地址
username=''      # 用户名
password=''      # 密码
client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
client = mqtt.Client(client_id, transport='tcp')
client.username_pw_set(username, password=password)
def clicent_main(message: str):
    """
    客户端发布消息
    :param message: 消息主体
    :return:
    """
    # time_now = time.strftime('%Y-%m-%d %H-%M-%S', time.localtime(time.time()))
    #payload = {"msg": "%s" % message, "data": "%s" % time_now}
    # publish(主题:Topic; 消息内容)
    client.publish(TASK_TOPIC, json.dumps(message, ensure_ascii=False))
    print("Successful send message!")
    return True

#检查IP地址
def check_ip(ipAddr):
  compile_ip=re.compile('^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$')
  if compile_ip.match(ipAddr):
    return True
  else:
    return False

def test(request):
    return render(request, 'test.html')
# 表单
def index(request):
    return render(request, 'index.html')


res = '无'
# 接收请求数据
def mqtt_client(request):
    request.encoding = 'utf-8'
    if 'issueTopic' in request.GET and request.GET['issueTopic']:
        global TASK_TOPIC,msg,address,username,password,res
        #message = '你搜索的内容为: ' + request.GET['issueTopic']
        message=request.GET['address']
        TASK_TOPIC=request.GET['issueTopic']
        address=request.GET['address']
        username=request.GET['username']
        password=request.GET['password']

        flag=''
        if (check_ip(address)):
            # 判断IP是否ping的通
            # try:
            client.connect_async(address, 1883, 60)  # 此处端口默认为1883,通信端口期keepalive默认60
            client.loop_start()
            res='连接成功'
            flag=1
        else:
            res='连接失败'
            flag=0
        if(flag):
            msg = request.GET['msg']
            clicent_main(msg)
        return render(request,'index.html',{'res':res,'address':address,'password':password,'msg':msg})
    else:
        message = '你提交了空表单'
    return HttpResponse(message)


 

  • 0
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值