1.1 参考
注册Ngrok账号
开通隧道,可以选择免费的,也可以付费购买
购买之后会生成id号
对于去下载树莓派上使用的服务端
上传至树莓派上并解压,本文放置路径/home/pi/
解压后进入目录,会发现有一个可执行文件——“sunny”,执行命令"./sunny clientid <你的Ngrok隧道id>"进入下面界面,显示在线,说明服务部署成功。此时等到执行后面的index.py文件
本文想实现通过web远程控制树莓派,效果图如下:
点击函数通过正则表达式筛选出点击的按键,并通过$(post)将请求传至后台脚本index.py
$(function () {
$(".btn-trigger").click(function (){
var text = $(this).text().replace(/ /g, "").replace(/\n/g, "").replace(/\r/g, "").replace(/\t/g, "");
var cmd = "";
switch(text){
case "空调开":
cmd = "空调开";
break;
case "空调关":
cmd = "空调关";
break;
case "卧室灯开":
cmd = "卧室灯开";
break;
case "卧室灯关":
cmd = "卧室灯关";
break;
case "排气扇开":
cmd = "排气扇开";
break;
case "排气扇关":
cmd = "排气扇关";
break;
case "冰箱开":
cmd = "冰箱开";
break;
case "冰箱关":
cmd = "冰箱关";
break;
case "电饭煲开":
cmd = "电饭煲开";
break;
case "电饭煲关":
cmd = "电饭煲关";
break;
case "加湿器开":
cmd = "加湿器开";
break;
case "加湿器关":
cmd = "加湿器关";
break;
case "窗帘开":
cmd = "窗帘开";
break;
case "窗帘关":
cmd = "窗帘关";
break;
case "电视机开":
cmd = "电视机开";
break;
case "电视机关":
cmd = "电视机关";
break;
}
if(confirm("确定要执行该命令吗?")){
$.post("/cmd",cmd,function(data,status){});
}
});
})
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from bottle import get,post,run,request,template
@get("/")
def index():
return template("index")
@post("/cmd")
def cmd():
print ("按下了按钮: "+request.body.read().decode())
return "OK"
run(host="0.0.0.0")
将index.html和index.py上传到树莓派某个文件夹下面,执行python3 index.py
4 完整代码地址
喜欢的可以给个star鼓励一下~