先下载github代码,下面的操作,都是基于这个版本来的!
https://github.com/987334176/Intelligent_toy/archive/v1.5.zip
注意:由于涉及到版权问题,此附件没有图片和音乐。请参考链接,手动采集一下!
请参考链接:
https://www.cnblogs.com/xiao987334176/p/9647993.html#autoid-3-4-0
一、玩具管理页面
点击下面的标签,页面还没有反应。
点击之后,需要进入玩具管理页面!
进入HBuilder项目MyApp,新建文件toy_info.html
修改 toy_info.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">玩具详情</h1>
</header>
<div class="mui-content">
<div class="mui-row" style="text-align: center;">
<img src="" id="avatar" style="width: 300px;height: 300px;border-radius: 50%;" />
</div>
<ul class="mui-table-view">
<li class="mui-table-view-cell">
玩具名称 :<span id="toy_name"></span>
</li>
<li class="mui-table-view-cell">
所属主人 :<span id="baby_name"></span>
</li>
<li class="mui-table-view-cell">
设备编号 :<span id="device_id"></span>
</li>
</ul> </div>
</body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview();
mui.post(
window.serv + "/toy_info", {
toy_id: Sdata.toy_id
},
function(data) {
console.log(JSON.stringify(data));
document.getElementById("avatar").src = "avatar/" + data.data.avatar;
document.getElementById("toy_name").innerText = data.data.toy_name;
document.getElementById("baby_name").innerText = data.data.baby_name;
document.getElementById("device_id").innerText = data.data.device_id; }
);
}) </script> </html>
修改 toy_manager.html,点击时,打开玩具管理页面
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">管理我的玩具</h1>
</header>
<div class="mui-content">
<ul class="mui-table-view" id="toy_list">
<li class="mui-table-view-cell mui-media">
<a id="add_toy">
<img class="mui-media-object mui-pull-left" src="data:images/add.png">
<div class="mui-media-body">
你还没有玩具
<p class="mui-ellipsis">点击此处扫描二维码添加玩具</p>
</div>
</a>
</li>
</ul>
</div>
</body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init();
mui.plusReady(function(){
// 发送POST请求,访问玩具列表
mui.post(
window.serv + "/toy_list",
{user_id:plus.storage.getItem("user")},
function(data){
console.log(JSON.stringify(data));
// for循环玩具列表
for (var i = 0; i < data.data.length; i++) {
// 调用自定义函数,渲染玩具列表
create_content(data.data[i]);
}
}
)
}); function create_content(content) { //玩具列表
var litag = document.createElement("li");
litag.className = "mui-table-view-cell mui-media";
var atag = document.createElement("a");
atag.id = content._id;
atag.onclick = function() {
console.log(this.id);
open_toy_info(this.id); //打开玩具管理页面
} var imgtag = document.createElement("img");
imgtag.className = "mui-media-object mui-pull-left";
imgtag.style = "border-radius: 50%;width: 45px;height: 45px; "
imgtag.src = "avatar/" + content.avatar; var divtag = document.createElement("div");
divtag.className = "mui-media-body";
divtag.innerText = content.baby_name;
var ptag = document.createElement("p");
ptag.className = "mui-ellipsis";
ptag.innerText = content.toy_name; litag.appendChild(atag);
atag.appendChild(imgtag);
atag.appendChild(divtag);
divtag.appendChild(ptag); document.getElementById("toy_list").appendChild(litag); } document.getElementById("add_toy").addEventListener("tap", function() {
mui.openWindow({
url: "qrcode.html",
id: "qrcode.html",
})
}); function open_toy_info(toy_id) { //打开玩具管理页面
mui.openWindow({
url: "toy_info.html",
id: "toy_info.html",
extras: {
toy_id: toy_id
}
})
}
</script> </html>
进入flask后端,修改 serv-->toys.py,增加接口
from flask import Blueprint, request, jsonify
from setting import MONGO_DB
from setting import RET
from bson import ObjectId toy = Blueprint("toy", __name__) @toy.route("/toy_list", methods=["POST"])
def toy_list(): # 玩具列表
user_id = request.form.get("user_id") # 用户id
# 查看用户信息
user_info = MONGO_DB.users.find_one({"_id": ObjectId(user_id)})
bind_toy = user_info.get("bind_toy") # 获取绑定的玩具
bind_toy_id = [] # 玩具列表
for toy_id in bind_toy: # 获取玩具列表中的所有玩具id
bind_toy_id.append(ObjectId(toy_id)) # 一次性查询多个玩具
toys_list = list(MONGO_DB.toys.find({"_id": {"$in": bind_toy_id}})) for index,item in enumerate(toys_list):
# 将_id转换为字符串
toys_list[index]["_id"] = str(item.get("_id")) RET["code"] = 0
RET["msg"] = ""
RET["data"] = toys_list return jsonify(RET) @toy.route("/device_toy_id", methods=["POST"])
def device_toy_id(): # 验证设备id
RET["code"] = 0
RET["msg"] = "开机成功"
RET["data"] = {} device_id = request.form.get("device_id") # 获取设备id # 判断设备id是否在设备表中
if MONGO_DB.devices.find_one({"device_id": device_id}):
# 查询设备id是否在玩具表中
toy_info = MONGO_DB.toys.find_one({"device_id": device_id})
if toy_info:
# RET添加键值,获取玩具id
RET["data"]["toy_id"] = str(toy_info.get("_id"))
# 音频文件
RET["data"]["audio"] = "success.mp3"
return jsonify(RET)
else:
# 已授权的设备,但是没有绑定主人
RET["msg"] = "找小主人"
RET["data"]["audio"] = "Nobind.mp3"
return jsonify(RET)
else:
# 不在设备表中,说明是未授权,或者是冒牌的!
RET["msg"] = "联系玩具厂"
RET["data"]["audio"] = "Nodevice.mp3"
return jsonify(RET) @toy.route("/toy_info", methods=["POST"])
def toy_info(): # 玩具管理页面
toy_id = request.form.get("toy_id")
toy = MONGO_DB.toys.find_one({"_id":ObjectId(toy_id)}) toy["_id"] = str(toy.get("_id")) RET["code"] = 0
RET["msg"] = ""
RET["data"] = toy return jsonify(RET)
重启 manager.py,使用模拟器访问,效果如下:
二、控制玩具通讯录
玩具管理页面,还需要展示 通讯录。
修改 toy_info.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">玩具详情</h1>
</header>
<div class="mui-content">
<div class="mui-row" style="text-align: center;">
<img src="" id="avatar" style="width: 300px;height: 300px;border-radius: 50%;" />
</div>
<ul class="mui-table-view">
<li class="mui-table-view-cell">
玩具名称 :<span id="toy_name"></span>
</li>
<li class="mui-table-view-cell">
所属主人 :<span id="baby_name"></span>
</li>
<li class="mui-table-view-cell">
设备编号 :<span id="device_id"></span>
</li>
</ul>
<div class="mui-row" style="text-align: center;">
玩具通讯录
</div>
<ul class="mui-table-view mui-grid-view" id="contacts">
<li class="mui-table-view-cell mui-media mui-col-xs-3">
<a id="add_friend">
<img class="mui-media-object" src="data:images/add.png" style="border-radius: 50%;width: 75px;height: 75px;">
<div class="mui-media-body">添加好友</div>
</a>
</li>
</ul>
</div>
</body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview();
mui.post(
window.serv + "/toy_info", {
toy_id: Sdata.toy_id
},
function(data) {
console.log(JSON.stringify(data));
document.getElementById("avatar").src = "avatar/" + data.data.avatar;
document.getElementById("toy_name").innerText = data.data.toy_name;
document.getElementById("baby_name").innerText = data.data.baby_name;
document.getElementById("device_id").innerText = data.data.device_id; for(var i = 0; i < data.data.friend_list.length; i++) {
create_friend(data.data.friend_list[i]);
} }
);
});
function create_friend(friend) {
var litag = document.createElement("li");
litag.className = "mui-table-view-cell mui-media mui-col-xs-3";
var atag = document.createElement("a");
atag.id = friend.friend_id
var imgtag = document.createElement("img");
imgtag.className = "mui-media-object";
imgtag.style.borderRadius = "50%";
imgtag.style.width = "75px";
imgtag.style.height = "75px"; imgtag.src = "avatar/" + friend.friend_avatar;
var divtag = document.createElement("div");
divtag.innerText = friend.friend_remark;
divtag.className = "mui-media-body"; litag.appendChild(atag);
atag.appendChild(imgtag);
atag.appendChild(divtag); document.getElementById("contacts").appendChild(litag); } </script> </html>
使用模拟器访问,效果如下:
三、基于请求的好友关系建立
加好友流程图
同意流程图
修改 qrcode.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">扫描玩具二维码</h1>
</header>
<div class="mui-content">
<div style="height: 550px;" id="qr"></div>
</div> </body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview();
// var barcode = new plus.barcode.Barcode('qr');
// // plus.webview.currentWebview().append(barcode);
// barcode.onmarked = chenggong;
// barcode.start(); chenggong(0,"864aad3ca55d9fe9bdcbef70e174fc3f")
}) function chenggong(type, code) {
mui.post(
window.serv + "/yanzheng_qr", {
device_id: code
},
function(data) {
console.log(JSON.stringify(data));
mui.toast(data.msg);
if(data.code == 2) {
mui.back();
}
if(data.code == 1) {
//加好友的小逻辑 跳转到加好友页面
if(Sdata.toy_id) {
//1.玩具 添加好友 toys toys
mui.openWindow({
url: "add_req.html",
id: "add_req.html",
extras: {
req_type: "toy",
user_id: Sdata.toy_id,
friend_id: data.data.toy_id
}
})
} else {
// 2.手机app 添加好友 users toys
mui.openWindow({
url: "add_req.html",
id: "add_req.html",
extras: {
req_type: "user",
user_id: plus.storage.getItem("user"),
friend_id: data.data.toy_id
}
})
} }
if(data.code == 0) {
//今天的逻辑 创建玩具 绑定用户 成为玩具的第一个好友
//1.创建玩具:打开创建玩具的页面
if(Sdata.toy_id) {
mui.back()
} else {
mui.openWindow({
url: "bind_toy.html",
id: "bind_toy.html",
extras: {
device_id: code
}
})
} }
}
)
}
</script> </html>
修改 toy_info.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">玩具详情</h1>
</header>
<div class="mui-content">
<div class="mui-row" style="text-align: center;">
<img src="" id="avatar" style="width: 300px;height: 300px;border-radius: 50%;" />
</div>
<ul class="mui-table-view">
<li class="mui-table-view-cell">
玩具名称 :<span id="toy_name"></span>
</li>
<li class="mui-table-view-cell">
所属主人 :<span id="baby_name"></span>
</li>
<li class="mui-table-view-cell">
设备编号 :<span id="device_id"></span>
</li>
</ul>
<div class="mui-row" style="text-align: center;">
玩具通讯录
</div>
<ul class="mui-table-view mui-grid-view" id="contacts">
<li class="mui-table-view-cell mui-media mui-col-xs-3">
<a id="add_friend">
<img class="mui-media-object" src="data:images/add.png" style="border-radius: 50%;width: 75px;height: 75px;">
<div class="mui-media-body">添加好友</div>
</a>
</li>
</ul>
</div>
</body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview();
mui.post(
window.serv + "/toy_info", {
toy_id: Sdata.toy_id
},
function(data) {
console.log(JSON.stringify(data));
document.getElementById("avatar").src = "avatar/" + data.data.avatar;
document.getElementById("toy_name").innerText = data.data.toy_name;
document.getElementById("baby_name").innerText = data.data.baby_name;
document.getElementById("device_id").innerText = data.data.device_id; for(var i = 0; i < data.data.friend_list.length; i++) {
create_friend(data.data.friend_list[i]);
}
}
);
}) function create_friend(friend) {
var litag = document.createElement("li");
litag.className = "mui-table-view-cell mui-media mui-col-xs-3";
var atag = document.createElement("a");
atag.id = friend.friend_id
var imgtag = document.createElement("img");
imgtag.className = "mui-media-object";
imgtag.style.borderRadius = "50%";
imgtag.style.width = "75px";
imgtag.style.height = "75px"; imgtag.src = "avatar/" + friend.friend_avatar;
var divtag = document.createElement("div");
divtag.innerText = friend.friend_remark;
divtag.className = "mui-media-body"; litag.appendChild(atag);
atag.appendChild(imgtag);
atag.appendChild(divtag); document.getElementById("contacts").appendChild(litag); } document.getElementById("add_friend").addEventListener("tap", function() {
mui.openWindow({
url: "qrcode.html",
id: "qrcode.html",
extras:{
toy_id:Sdata.toy_id
}
})
})
</script> </html>
进入flask项目,修改devices.py,修改 yanzheng_qr函数
from flask import Blueprint, request, jsonify
from setting import MONGO_DB
from setting import RET
from bson import ObjectId devs = Blueprint("devs", __name__) @devs.route("/yanzheng_qr", methods=["POST"])
def yanzheng_qr(): # 验证二维码
device_id = request.form.get("device_id") # 获取设备id
if MONGO_DB.devices.find_one({"device_id": device_id}): # 从数据库中查询设备id
# 查询该玩具是不是已被用户绑定
toy_info = MONGO_DB.toys.find_one({"device_id": device_id})
# 未绑定开启绑定逻辑
if not toy_info:
RET["code"] = 0
RET["msg"] = "感谢购买本公司产品"
RET["data"] = {} # 如果被绑定加好友逻辑开启
if toy_info:
RET["code"] = 1
RET["msg"] = "添加好友"
RET["data"] = {"toy_id": str(toy_info.get("_id"))} else:
RET["code"] = 2
RET["msg"] = "二货,这不是本公司设备,快去买正版!"
RET["data"] = {} return jsonify(RET) @devs.route("/bind_toy", methods=["POST"])
def bind_toy(): # 绑定玩具
chat_window = MONGO_DB.chat.insert_one({}) # 插入一个空数据
chat_id = chat_window.inserted_id # 获取聊天id user_id = request.form.get("user_id") # 用户id
res = MONGO_DB.users.find_one({"_id": ObjectId(user_id)}) # 查询用户id是否存在 device_id = request.form.get("device_id") # 设备id
toy_name = request.form.get("toy_name") # 玩具的昵称
baby_name = request.form.get("baby_name") # 小主人的名字
remark = request.form.get("remark") # 玩具主人对您的称呼
gender = request.form.get("gender") # 性别 toy_info = {
"device_id": device_id,
"toy_name": toy_name,
"baby_name": baby_name,
"gender": gender,
"avatar": "boy.jpg" if gender == 1 else "girl.jpg",
# 绑定用户
"bind_user": str(res.get("_id")),
# 第一个好友
"friend_list": [{
"friend_id": str(res.get("_id")), # 好友id
"friend_name": res.get("nickname"), # 好友昵称
"friend_remark": remark, # 好友称呼
"friend_avatar": res.get("avatar"), # 好友头像
"friend_chat": str(chat_id), # 好友聊天id
}]
} toy_res = MONGO_DB.toys.insert_one(toy_info) # 插入玩具表数据 if res.get("friend_list"): # 判断用户好友列表是否为空
# 追加好友
res["bind_toy"].append(str(toy_res.inserted_id))
res["friend_list"].append({
"friend_id": str(toy_res.inserted_id),
"friend_name": toy_name,
"friend_remark": baby_name,
"friend_avatar": toy_info.get("avatar"),
"friend_chat": str(chat_id),
})
else:
# 更新好友
res["bind_toy"] = [str(toy_res.inserted_id)]
res["friend_list"] = [{
"friend_id": str(toy_res.inserted_id),
"friend_name": toy_name,
"friend_remark": baby_name,
"friend_avatar": toy_info.get("avatar"),
"friend_chat": str(chat_id),
}] MONGO_DB.users.update_one({"_id": ObjectId(user_id)}, {"$set": res}) # 更新用户记录 # 更新聊天表
# user_list有2个值。第一个是玩具id,第2个是用户id
# 这样,用户和玩具就能通讯了
MONGO_DB.chat.update_one({"_id": chat_id},
{"$set":
{"user_list":
[str(toy_res.inserted_id),
str(res.get("_id"))]}}) RET["code"] = 0
RET["msg"] = "绑定成功"
RET["data"] = {} return jsonify(RET)
修改 serv-->friend.py,增加add_req函数
from flask import Blueprint, request, jsonify
from setting import MONGO_DB
from setting import RET
from bson import ObjectId fri = Blueprint("fri", __name__) @fri.route("/friend_list", methods=["POST"])
def friend_list(): # 好友列表
user_id = request.form.get("user_id")
# 查询用户id信息
res = MONGO_DB.users.find_one({"_id": ObjectId(user_id)})
friend_list = res.get("friend_list") # 获取好友列表 RET["code"] = 0
RET["msg"] = ""
RET["data"] = friend_list return jsonify(RET) @fri.route("/add_req", methods=["POST"])
def add_req():
user_id = request.form.get("user_id") # 有可能是 toy_id or user_id
friend_id = request.form.get("friend_id") # 100%是toy_id
req_type = request.form.get("req_type")
req_msg = request.form.get("req_msg") # 描述
remark = request.form.get("remark") # 备注 if req_type == "toy":
user_info = MONGO_DB.toys.find_one({"_id": ObjectId(user_id)})
else:
user_info = MONGO_DB.users.find_one({"_id": ObjectId(user_id)}) req_str = {
"req_user": str(user_info.get("_id")),
"req_type": req_type,
"req_toy": friend_id,
"req_msg": req_msg,
"avatar": user_info.get("avatar"),
"user_remark": remark,
# 昵称,玩具是没有的
"user_nick": user_info.get("nickname") if user_info.get("nickname") else user_info.get("baby_name"),
# 状态,1通过,2拒绝,0中间状态(可切换到1和2)。
"status": 0
} MONGO_DB.req.insert_one(req_str) RET["code"] = 0
RET["msg"] = "请求发送成功"
RET["data"] = {} return jsonify(RET)
进入HBuilder项目MyApp,新建文件add_req.html
修改 add_req.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">请求加为好友</h1>
</header>
<div class="mui-content">
<form class="mui-input-group">
<div class="mui-input-row">
<label>请求内容</label>
<input type="text" class="mui-input-clear" placeholder="快来打个招呼把" id="req_content">
</div>
<div class="mui-input-row">
<label>好友备注</label>
<input type="text" class="mui-input-clear" placeholder="给好友起的响亮的2B名字" id="remark">
</div>
<div class="mui-button-row">
<button type="button" class="mui-btn mui-btn-primary" id="send_req">发送请求</button>
<button type="button" class="mui-btn mui-btn-danger mui-action-back">取消</button>
</div>
</form>
</div>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview(); }) document.getElementById("send_req").addEventListener("tap", function() {
mui.post(
window.serv + "/add_req", {
user_id: Sdata.user_id,
req_type: Sdata.req_type,
friend_id: Sdata.friend_id,
req_msg: document.getElementById("req_content").value,
remark: document.getElementById("remark").value
},
function(data) {
console.log(JSON.stringify(data)); }
)
})
</script>
</body> </html>
修改 index.html,将 底部选项卡中的 邮件,改为 好友请求
<!DOCTYPE html>
<html> <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<script src="js/mui.js"></script>
<link href="css/mui.min.css" rel="stylesheet" />
</head> <body>
<!--底部选项卡-->
<nav class="mui-bar mui-bar-tab">
<a class="mui-tab-item mui-active" id="index">
<span class="mui-icon mui-icon-home"></span>
<span class="mui-tab-label">首页</span>
</a>
<a class="mui-tab-item" id="message">
<span class="mui-icon mui-icon-chat">
<span class="mui-badge mui-badge-red" id="msg_count">0</span>
</span>
<span class="mui-tab-label">消息</span>
</a>
<a class="mui-tab-item" id="req">
<span class="mui-icon mui-icon-email"></span>
<span class="mui-tab-label">好友请求</span>
</a>
<a class="mui-tab-item" id="login">
<span class="mui-icon mui-icon-gear"></span>
<span class="mui-tab-label">设置</span>
</a>
</nav>
</body>
<script type="text/javascript" charset="utf-8">
var ws = null; // websocket对象
var msg_data = null; // 消息数据
mui.init({
subpages: [{
url: "main.html",
id: "main.html",
styles: window.styles
}]
});
mui.plusReady(function() {
// console.log(JSON.stringify(plus.webview.currentWebview()))
if(plus.storage.getItem("user")) { // 判断是否登录
console.log('已结登录了!');
//连接websocket连接
ws = new WebSocket("ws://" + window.ws_serv + "/app/" + plus.storage.getItem("user")) // 发送post请求
console.log(window.serv + "/get_msg_list");
mui.post(
// 访问消息列表
window.serv + "/get_msg_list", {
user_id: plus.storage.getItem("user")
},
function(data) {
console.log(JSON.stringify(data));
// {"code":0,"data":{"5ba0f1f2e12532418089bf88":1,"count":1},"msg":""}
msg_data = data.data;
// 修改消息选项卡的角标数字
document.getElementById("msg_count").innerText = msg_data.count;
}
); // 客户端接收服务端数据时触发
ws.onmessage = function(data) {
console.log(data.data);
var msg = JSON.parse(data.data);
var chat = plus.webview.getWebviewById("chat.html");
mui.fire(chat, "new_msg", { // 向chat.html传值
data: msg
});
var msg_count = document.getElementById("msg_count");
// 当前页面加1
msg_count.innerText = parseInt(msg_count.innerText) + 1;
// 加1,用于message.html显示
msg_data[msg.from_user]++;
};
}
// 自动重连
ws.onclose = function() {
window.location.reload();
}
}); // 消息
document.getElementById("message").addEventListener("tap", function() {
mui.openWindow({
url: "message.html",
id: "message.html",
styles: window.styles,
extras: {
// 传输用户id,给message.html
user_id: plus.storage.getItem("user"),
msg_data: msg_data,
// "data":{"5ba0f1f2e12532418089bf88":1,"count":1}
}
})
}); document.getElementById("index").addEventListener("tap", function() {
mui.openWindow({
url: "main.html",
id: "main.html",
styles: window.styles
})
}) document.getElementById("req").addEventListener("tap", function() {
mui.openWindow({
url: "req_list.html",
id: "req_list.html",
styles: window.styles
})
}) document.getElementById("login").addEventListener("tap", function() {
// 自动登录,判断storage中的user存在,就跳转到user_info,否则跳转login
if(plus.storage.getItem("user")) {
mui.openWindow({
url: "user_info.html",
id: "user_info.html",
styles: window.styles,
extras: {
user_id: plus.storage.getItem("user")
}
})
} else {
mui.openWindow({
url: "login.html",
id: "login.html",
styles: window.styles
})
}
}) document.addEventListener("login", function(data) {
// fire事件接收消息,使用data.detail
// index是为做显示区分
mui.toast("index" + data.detail.msg)
}); document.addEventListener("send_music", function(data) { //监听send_music事件
var music_name = data.detail.music_name; //获取player.html使用fire发送的music_name值
var toy_id = data.detail.toy_id; //获取发送的玩具id send_str = { //构造数据
data: music_name,
to_user: toy_id, // 目标用户,这里统一格式
msg_type: "music", // 类型为音乐
}
// 发送数据给后端,注意要json序列化
ws.send(JSON.stringify(send_str));
}); document.addEventListener("send_msg", function(data) { //发送消息
var filename = data.detail.filename
var to_user = data.detail.to_user
send_str = {
to_user: to_user
}
ws.send(JSON.stringify(send_str))
plus.io.resolveLocalFileSystemURL(filename, function(entry) {
// 可通过entry对象操作test.html文件
entry.file(function(file) {
// FileReader文件系统中的读取文件对象,用于获取文件的内容
var fileReader = new plus.io.FileReader(); // alert("getFile:" + JSON.stringify(file));
// readAsDataURL: 以URL编码格式读取文件数据内容
fileReader.readAsDataURL(file, 'utf-8');
// onloadend: 文件读取操作完成时的回调函数
fileReader.onloadend = function(evt) {
console.log(evt.target.result);
var b = dataURLtoBlob(evt.target.result);
ws.send(b); // 发送blob数据 }
// alert(file.size + '--' + file.name)
});
}); }); // 监听cut_msg_count事件,由message.html向index.html执行fire
document.addEventListener("cut_msg_count", function(data) {
var msg_count = document.getElementById("msg_count");
var cut = parseInt(data.detail.cut); // parseInt表示强制转换
var count = parseInt(msg_count.innerText); // 默认获取innerText是字符串,需要强制转换
msg_count.innerText = count - cut; // 总数 减去 点击聊天会话的数量,比如小甜甜的
}); function dataURLtoBlob(dataurl) { // 数据转换为Blob
// 逻辑很复杂,这里不解释了。直接用就可以了!
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var a = new Blob([u8arr], {
type: mime
});
return a
}
</script> </html>
新建文件 req_list.html
修改 req_list.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<h1 class="mui-title">玩具的好友请求</h1>
</header>
<div class="mui-content" >
<ul class="mui-table-view" id="req_list"> </ul>
</div>
</body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
mui.plusReady(function(){
mui.post(
window.serv + "/req_list",
{user_id:plus.storage.getItem("user")},
function(data){
console.log(JSON.stringify(data));
for (var i = 0; i < data.data.length; i++) {
create_req(data.data[i])
}
}
)
}) function create_req(req){
var litag = document.createElement("li");
litag.className = "mui-table-view-cell mui-media";
var atag = document.createElement("a");
atag.id = req._id;
// 点击事件 周一把这儿写了 绑定事件
atag.onclick = function(){
console.log(this.id); open_req(this.id); } var imgtag = document.createElement("img");
imgtag.className = "mui-media-object mui-pull-left"; imgtag.src = "avatar/" + req.avatar; var divtag = document.createElement("div");
divtag.className = "mui-media-body";
divtag.innerText = req.user_nick;
var ptag = document.createElement("p");
ptag.className = "mui-ellipsis";
ptag.innerText = req.req_msg; litag.appendChild(atag);
atag.appendChild(imgtag);
atag.appendChild(divtag);
divtag.appendChild(ptag); document.getElementById("req_list").appendChild(litag); } function open_req(req_id){
mui.openWindow({
url:"acc_ref_req.html",
id:"acc_ref_req.html",
extras:{
req_id:req_id
}
})
}
</script>
</html>
进入 flask项目,修改 serv-->friend.py,增加函数 req_list
from flask import Blueprint, request, jsonify
from setting import MONGO_DB
from setting import RET
from bson import ObjectId fri = Blueprint("fri", __name__) @fri.route("/friend_list", methods=["POST"])
def friend_list(): # 好友列表
user_id = request.form.get("user_id")
# 查询用户id信息
res = MONGO_DB.users.find_one({"_id": ObjectId(user_id)})
friend_list = res.get("friend_list") # 获取好友列表 RET["code"] = 0
RET["msg"] = ""
RET["data"] = friend_list return jsonify(RET) @fri.route("/add_req", methods=["POST"])
def add_req(): # 添加好友请求
user_id = request.form.get("user_id") # 有可能是 toy_id or user_id
friend_id = request.form.get("friend_id") # 100%是toy_id
req_type = request.form.get("req_type")
req_msg = request.form.get("req_msg") # 描述
remark = request.form.get("remark") # 备注 if req_type == "toy":
user_info = MONGO_DB.toys.find_one({"_id": ObjectId(user_id)})
else:
user_info = MONGO_DB.users.find_one({"_id": ObjectId(user_id)}) req_str = {
"req_user": str(user_info.get("_id")),
"req_type": req_type,
"req_toy": friend_id,
"req_msg": req_msg,
"avatar": user_info.get("avatar"),
"user_remark": remark,
# 昵称,玩具是没有的
"user_nick": user_info.get("nickname") if user_info.get("nickname") else user_info.get("baby_name"),
# 状态,1通过,2拒绝,0中间状态(可切换到1和2)。
"status": 0
} MONGO_DB.req.insert_one(req_str) RET["code"] = 0
RET["msg"] = "请求发送成功"
RET["data"] = {} return jsonify(RET) @fri.route("/req_list", methods=["POST"])
def req_list(): # 添加请求列表
user_id = request.form.get("user_id")
user_info = MONGO_DB.users.find_one({"_id": ObjectId(user_id)})
bind_toy = user_info.get("bind_toy") reqs = list(MONGO_DB.req.find({"req_toy": {"$in": bind_toy}, "status": 0})) for index, req in enumerate(reqs):
reqs[index]["_id"] = str(req.get("_id")) RET["code"] = 0
RET["msg"] = ""
RET["data"] = reqs return jsonify(RET)
用户收到 添加好友请求后,还可以拒绝请求。
进入HBuilder项目MyApp,新建文件acc_ref_req.html
修改文件 acc_ref_req.html
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">处理好友请求</h1>
</header>
<div class="mui-content">
<ul class="mui-table-view">
<li class="mui-table-view-cell mui-media">
<a href="javascript:;">
<img class="mui-media-object mui-pull-left" src="" id="avatar">
<div class="mui-media-body">
<span id="user_nick"></span>
<p class="mui-ellipsis" id="req_msg"></p>
</div>
</a>
</li>
</ul> <form class="mui-input-group">
<div class="mui-input-row">
<label>好友备注</label>
<input type="text" class="mui-input-clear" placeholder="给好友起的响亮的2B名字" id="remark">
</div>
<div class="mui-button-row">
<button type="button" class="mui-btn mui-btn-primary" id="ido">I Do</button>
<button type="button" class="mui-btn mui-btn-danger mui-action-back" id="goodman">好人卡</button>
</div>
</form>
</div>
</body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview();
mui.post(
window.serv + "/get_req", {
req_id: Sdata.req_id
},
function(data) {
console.log(JSON.stringify(data));
document.getElementById("avatar").src = "avatar/" + data.data.avatar;
document.getElementById("user_nick").innerText = data.data.user_nick;
document.getElementById("req_msg").innerText = data.data.req_msg;
}
)
}) document.getElementById("ido").addEventListener("tap", function() {
var remark = document.getElementById("remark").value;
mui.post(
window.serv + "/acc_req", {
req_id: Sdata.req_id,
remark:remark
},
function(data) {
console.log(JSON.stringify(data));
}
)
}) document.getElementById("goodman").addEventListener("tap", function() {
mui.post(
window.serv + "/ref_req", {
req_id: Sdata.req_id
},
function(data) {
console.log(JSON.stringify(data));
}
)
})
</script> </html>
修改 qrcode.html,这里应该要扫描玩具二维码的。但是太麻烦了,直接固定设备编号!
固定设备编号为 小豆芽,发给后端。因为当前web玩具是小甜甜。它需要增加对方才行!
<!doctype html>
<html lang="en"> <head>
<meta charset="UTF-8" />
<title>Document</title>
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<link rel="stylesheet" type="text/css" href="css/mui.css" />
</head> <body>
<header class="mui-bar mui-bar-nav">
<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
<h1 class="mui-title">扫描玩具二维码</h1>
</header>
<div class="mui-content">
<div style="height: 550px;" id="qr"></div>
</div> </body>
<script src="js/mui.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
mui.init()
var Sdata = null;
mui.plusReady(function() {
Sdata = plus.webview.currentWebview();
// var barcode = new plus.barcode.Barcode('qr');
// // plus.webview.currentWebview().append(barcode);
// barcode.onmarked = chenggong;
// barcode.start();
// 临时改为小豆芽的设备id,从MongoDB中的toys表查询
chenggong(0,"02cc0fc7490b6ee08c31f38ac7a375eb")
}) function chenggong(type, code) {
mui.post(
window.serv + "/yanzheng_qr", {
device_id: code
},
function(data) {
console.log(JSON.stringify(data));
mui.toast(data.msg);
if(data.code == 2) {
mui.back();
}
if(data.code == 1) {
//加好友的小逻辑 跳转到加好友页面
if(Sdata.toy_id) {
//1.玩具 添加好友 toys toys
mui.openWindow({
url: "add_req.html",
id: "add_req.html",
extras: {
req_type: "toy",
user_id: Sdata.toy_id,
friend_id: data.data.toy_id
}
})
} else {
// 2.手机app 添加好友 users toys
mui.openWindow({
url: "add_req.html",
id: "add_req.html",
extras: {
req_type: "user",
user_id: plus.storage.getItem("user"),
friend_id: data.data.toy_id
}
})
} }
if(data.code == 0) {
//今天的逻辑 创建玩具 绑定用户 成为玩具的第一个好友
//1.创建玩具:打开创建玩具的页面
if(Sdata.toy_id) {
mui.back()
} else {
mui.openWindow({
url: "bind_toy.html",
id: "bind_toy.html",
extras: {
device_id: code
}
})
} }
}
)
}
</script> </html>
进入flask项目,修改 serv-->friend.py,增加函数get_req,acc_req,ref_req
from flask import Blueprint, request, jsonify
from setting import MONGO_DB
from setting import RET
from bson import ObjectId fri = Blueprint("fri", __name__) @fri.route("/friend_list", methods=["POST"])
def friend_list(): # 好友列表
user_id = request.form.get("user_id")
# 查询用户id信息
res = MONGO_DB.users.find_one({"_id": ObjectId(user_id)})
friend_list = res.get("friend_list") # 获取好友列表 RET["code"] = 0
RET["msg"] = ""
RET["data"] = friend_list return jsonify(RET) @fri.route("/add_req", methods=["POST"])
def add_req(): # 添加好友请求
user_id = request.form.get("user_id") # 有可能是 toy_id or user_id
friend_id = request.form.get("friend_id") # 100%是toy_id
req_type = request.form.get("req_type")
req_msg = request.form.get("req_msg") # 描述
remark = request.form.get("remark") # 备注 if req_type == "toy":
user_info = MONGO_DB.toys.find_one({"_id": ObjectId(user_id)})
else:
user_info = MONGO_DB.users.find_one({"_id": ObjectId(user_id)}) req_str = {
"req_user": str(user_info.get("_id")),
"req_type": req_type,
"req_toy": friend_id,
"req_msg": req_msg,
"avatar": user_info.get("avatar"),
"user_remark": remark,
# 昵称,玩具是没有的
"user_nick": user_info.get("nickname") if user_info.get("nickname") else user_info.get("baby_name"),
# 状态,1通过,2拒绝,0中间状态(可切换到1和2)。
"status": 0
} MONGO_DB.req.insert_one(req_str) RET["code"] = 0
RET["msg"] = "请求发送成功"
RET["data"] = {} return jsonify(RET) @fri.route("/req_list", methods=["POST"])
def req_list(): # 添加请求列表
user_id = request.form.get("user_id")
user_info = MONGO_DB.users.find_one({"_id": ObjectId(user_id)})
bind_toy = user_info.get("bind_toy") reqs = list(MONGO_DB.req.find({"req_toy": {"$in": bind_toy}, "status": 0})) for index, req in enumerate(reqs):
reqs[index]["_id"] = str(req.get("_id")) RET["code"] = 0
RET["msg"] = ""
RET["data"] = reqs return jsonify(RET) @fri.route("/get_req", methods=["POST"])
def get_req(): # 获取好友请求
req_id = request.form.get("req_id") req_info = MONGO_DB.req.find_one({"_id": ObjectId(req_id)}) req_info["_id"] = str(req_info.get("_id")) RET["code"] = 0
RET["msg"] = ""
RET["data"] = req_info return jsonify(RET) @fri.route("/acc_req", methods=["POST"])
def acc_req(): # 允许好友请求
req_id = request.form.get("req_id")
remark = request.form.get("remark") req_info = MONGO_DB.req.find_one({"_id": ObjectId(req_id)}) # 1. 为 user 或 toy 添加 toy
if req_info.get("req_type") == "toy":
user_info = MONGO_DB.toys.find_one({"_id": ObjectId(req_info.get("req_user"))})
else:
user_info = MONGO_DB.users.find_one({"_id": ObjectId(req_info.get("req_user"))}) toy = MONGO_DB.toys.find_one({"_id": ObjectId(req_info.get("req_toy"))}) chat_window = MONGO_DB.chat.insert_one({"user_list": [str(toy.get("_id")), str(user_info.get("_id"))]}) friend_info = {
"friend_id": str(toy.get("_id")),
"friend_name": toy.get("baby_name"),
"friend_remark": req_info.get("user_remark"),
"friend_avatar": toy.get("avatar"),
"friend_chat": str(chat_window.inserted_id)
} if req_info.get("req_type") == "toy":
MONGO_DB.toys.update_one({"_id": ObjectId(req_info.get("req_user"))},
{"$push": {"friend_list": friend_info}})
else:
MONGO_DB.users.update_one({"_id": ObjectId(req_info.get("req_user"))},
{"$push": {"friend_list": friend_info}}) # 2. 为 toy 添加 user 或 toy
user_name = user_info.get("nickname") if user_info.get("nickname") else user_info.get("baby_name")
friend_info2 = {
"friend_id": str(user_info.get("_id")),
"friend_name": user_name,
# 同意方的备注
"friend_remark": remark if remark else user_name,
"friend_avatar": user_info.get("avatar"),
"friend_chat": str(chat_window.inserted_id)
} MONGO_DB.toys.update_one({"_id": ObjectId(req_info.get("req_toy"))},
{"$push": {"friend_list": friend_info2}}) RET["code"] = 0
RET["msg"] = f"添加好友{remark}成功"
RET["data"] = {} MONGO_DB.req.update_one({"_id": ObjectId(req_id)}, {"$set": {"status": 1}}) return jsonify(RET) @fri.route("/ref_req", methods=["POST"])
def ref_req(): # 拒绝好友请
req_id = request.form.get("req_id") MONGO_DB.req.update_one({"_id": ObjectId(req_id)}, {"$set": {"status": 2}}) RET["code"] = 0
RET["msg"] = "已拒绝好友请求"
RET["data"] = {} return jsonify(RET)
重启 manager.py
使用模拟器访问,点击添加好友,效果如下:
输入表单数据,效果如下:
点击发送请求,查看Pycharm控制台输出:
192.168.11.25 - - [25/Sep/2018 20:49:47] "POST /add_req HTTP/1.1" 200 -
请求成功了
查看表 req,发现有一条记录
点击底部选项卡的 好友请求--> 小甜甜
输入好友备注,点击 I Do
查看Pycharm
192.168.11.25 - - [25/Sep/2018 21:05:46] "POST /acc_req HTTP/1.1" 200 -
返回管理我的玩具,点击小甜甜,效果如下:
发现多了一个好友
查看玩具表,查看 friend_list字段。有2个记录
/* 1 createdAt:2018/9/19 下午5:53:08*/
{
"_id" : ObjectId("5ba21c84e1253229c4acbd12"),
"device_id" : "02cc0fc7490b6ee08c31f38ac7a375eb",
"toy_name" : "豆芽",
"baby_name" : "小豆芽",
"gender" : "",
"avatar" : "girl.jpg",
"bind_user" : "5b9bb768e1253281608e96eb",
"friend_list" : [
{
"friend_id" : "5b9bb768e1253281608e96eb",
"friend_name" : "xiao",
"friend_remark" : "小鱼",
"friend_avatar" : "boy.jpg",
"friend_chat" : "5ba21c84e1253229c4acbd11",
"user_type" : "user"
},
{
"friend_id" : "5ba0f1f2e12532418089bf88",
"friend_name" : "小甜甜",
"friend_remark" : "小甜甜",
"friend_avatar" : "girl.jpg",
"friend_chat" : "5bab7c19e125327ffc804459",
"user_type" : "toy"
}
]
}, /* 2 createdAt:2018/9/18 下午8:39:14*/
{
"_id" : ObjectId("5ba0f1f2e12532418089bf88"),
"device_id" : "01f9bf1bac93eddd8397d0455abbeddb",
"toy_name" : "小可爱",
"baby_name" : "小甜甜",
"gender" : "",
"avatar" : "girl.jpg",
"bind_user" : "5b9bb768e1253281608e96eb",
"friend_list" : [
{
"friend_id" : "5b9bb768e1253281608e96eb",
"friend_name" : "xiao",
"friend_remark" : "小鱼",
"friend_avatar" : "boy.jpg",
"friend_chat" : "5ba21c84e1253229c4acbd11",
"user_type" : "user"
},
{
"friend_id" : "5ba21c84e1253229c4acbd12",
"friend_name" : "小豆芽",
"friend_remark" : "豆芽",
"friend_avatar" : "girl.jpg",
"friend_chat" : "5bab7c19e125327ffc804459",
"user_type" : "toy"
}
]
}
会发现,小甜甜和小豆芽,互为好友了!
今日总结:
1.玩具管理页面
mui组件 :
msl : 图文表格 2.控制玩具通讯录 3.基于请求的好友关系建立
发送请求:带上自己的所有信息 + 请求信息
接收请求:可以看到自己的所有消息
双方添加好友:
同意:
1.判断自己是玩具还是用户
2.查询好友的信息
3.建立好友的信息(friend_list 中的元素)
4.将建立的好友信息存放在自己的friend_list中
5.建立自己的信息(好友的friend_list 中的元素)
6.将建立的自己信息存放在好友的friend_list中
7.将请求的状态改为 1
完整代码,参考github:
https://github.com/987334176/Intelligent_toy/archive/v1.6.zip
注意:qrcode.html,固定设备编号为 小豆芽。需要修正一下!