// 获取应用实例 const app = getApp(); const { getBanner, login, listByDevice } = require('../../utils/api.js'); const { isCN } = require('../../utils/util.js'); const interval = null; // import routeUtil from '../../utils/route_util.js' import routeUtil from '../../utils/route_util' import route_constant from '../../utils/route_constant.js' Page({ data: { ///下午好 greeting: "", phone: "", nvabarData: { showCapsule: 0, //是否显示左上角图标 1表示显示 0表示不显示 title: 'OhPlay', //导航栏 中间的标题 }, bannerList: [], autoplay: true, interval: 3000, // 切换时间间隔 duration: 500, // 滑动动画时长 circular: true, // 衔接滑动 indexPage: 0, ///是否展示频道 showChannel: false, ////首页 navBarHeight: app.globalData.navBarHeight, MenuButtonheight: app.globalData.MenuButtonheight, MenuButtonTop: app.globalData.MenuButtonTop, actionIndex: null, luoma: ["Ⅰ", "Ⅱ", "Ⅲ", "Ⅳ", "Ⅴ", "Ⅵ", " Ⅶ", "Ⅷ", "Ⅸ", "Ⅹ", "Ⅺ", "Ⅻ"], channelData: [], deviceList: [], deviceListIndex: null, showLogin: false, isOneLoading: true, uid: null, isSetWake: false, thisDeviceMac: null, battery: 4, // 0≤电量<20,0格 newVersion: false, ////我的界面 loginStatus: true, nickname: "未登录", userPic: './../../img/head_pic.png', islogin: false, }, onLoad(options) { var that = this; var bannerList = wx.getStorageSync("homeBanner") || []; if (that.data.bannerList.length == 0) { that.setData({ bannerList: bannerList }); } that.onHomeLoad(); that.onMeLoad(); }, onShow() { var that = this; that.onHomeShow(); that.onMeLoad(); var nickname = that.data.nickname; var greeting = that.updateGreeting(); if (nickname != "" && nickname != "未登录") { greeting = greeting + ',' + nickname;; } that.setData({ greeting: greeting }); getBanner({}).then((res) => { that.setData({ bannerList: res }); wx.setStorageSync("homeBanner", res); }) }, updateGreeting() { const now = new Date(); const hour = now.getHours(); let greeting; if (hour >= 5 && hour < 12) { greeting = '上午好'; } else if (hour >= 12 && hour < 18) { greeting = '下午好'; } else { greeting = '晚上好'; } return greeting; }, onHomeLoad() { var that = this; // 版本自动更新代码 const updateManager = wx.getUpdateManager(); updateManager.onUpdateReady(function () { that.setData({ newVersion: true }); }) updateManager.onUpdateFailed(function () { // 新的版本下载失败 wx.showModal({ title: '已有新版本咯', content: '请您删除当前小程序,重新打开呦~', showCancel: false }) }) wx.showLoading({ title: '加载中', }); const str = setTimeout(() => { clearTimeout(str); if (that.data.isOneLoading) { that.setData({ isOneLoading: false, }); } }, 500); // 获取缓存的频道数据 wx.getStorage({ key: "channelData", success(res) { that.setData({ channelData: res.data }) } }); // 登录 that.login(); }, onMeLoad() { // wx.getStorage("userInfo") var that = this; wx.getStorage({ key: "userInfo", success(res) { var phone = res.data.phone; if (!phone) { return; }; var nickname = res.data.nickname || ""; var greeting = that.updateGreeting(); if (nickname != "" && nickname != "未登录") { greeting = greeting + ',' + nickname;; } that.setData({ phone: phone, greeting: greeting, nickname: nickname, userPic: res.data.headUrl || "", islogin: true, }); } }) }, onHomeShow() { var that = this; if ((!that.data.isOneLoading)) { wx.getStorage({ key: 'userInfo', fail(res) { // 取消订阅 if (that.data.thisDeviceMac !== null) { app.unsubscribe(`/${that.data.thisDeviceMac}/user/pub_response`); }; that.setData({ showLogin: true, }); }, success() { if (app.globalData.newDeviceId) { // 获取设备本地数据 that.getDeviceData(); } else if (that.data.deviceListIndex !== null) { // 更新 that.actionDevice(that.data.deviceListIndex); } } }); }; }, ////开始是home的 login() { var that = this; wx.login({ success: res => { let phone = undefined; try { var value = wx.getStorageSync('userInfo') if (value) { phone = value.phone || undefined; }; } catch (e) { // Do something when catch error }; // 请求登录 login({ code: res.code, phone }).then((res) => { app.globalData.userInfo = res; wx.setStorage({ key: "userInfo", data: res }); // 需要用授权登录 if ((res.isNewUser && res.isNewUser === true) || !phone) { that.setData({ showLogin: true, }); return; }; // 获取设备本地数据 that.getDeviceData(); that.setData({ showLogin: false, }); wx.setStorage({ key: "token", data: JSON.stringify({ id: res.userId, token: res.accessToken, }), }); }); }, }) }, ///开始时home的 getDeviceData() { var that = this; // 获取设备数据 wx.getStorage({ key: 'devicelist', success(res) { wx.hideLoading(); if (res.data) { const resData = JSON.parse(res.data); console.log("本地设备列表", resData) that.setData({ deviceList: resData }); // 连接mqtt if (app.globalData.client === null) { app.connect(); } else if (app.globalData.newDeviceId) { that.setData({ actionIndex: null, deviceListIndex: null, }); // 监听 let topic = `/AIrSMArT_${resData[0].name.split("BLUFI_")[1]}/status/onoffline`; app.subscribe(topic); const Timeout = setTimeout(() => { clearTimeout(Timeout); that.actionDevice(0); }, 1000); } // // 有新设备 // if(app.globalData.newDeviceId) { // that.setData({ // actionIndex: null, // deviceListIndex: null, // }); // let topic = `/AIrSMArT_${resData[0].name.split("BLUFI_")[1]}/status/onoffline`; // app.subscribe(topic); // } } }, fail(e) { wx.hideLoading(); } }); }, // 回调 mqttCallback(type, option) { // console.log("gadsfadsfqwerq===" + type + "===" + option); var that = this; let payloads = null; if (option) { payloads = JSON.parse(option.payload); }; switch (type) { case "connect": that.connectSuccess(); break; case "message_onoffline": that.online(payloads); break; case "message": // 接收设备播放信息 if (payloads.type === "get_position" && payloads.other) { let actionIndex = null; that.data.channelData.map((v, index) => { if (v.channelNum === payloads.other.channel) { actionIndex = index; } }); that.setData({ actionIndex, }); } else if (payloads.type === "play" || payloads.type === "play_state") { if (that.data.deviceListIndex === null) { return; } // 接收设备当前播放状态 const obj = { DstDeviceName: that.getThisDeviceID() } app.PubMsg({ type: "get_position", ...obj }); } else if (payloads.type === "get_dev_info") { // 接收设备当前信息 that.getchannelData(payloads.other.ProdModel); // 电量 that.setData({ battery: that._battery(payloads.other.Power), }) // 当前设备木有设置定时 that.setData({ isSetWake: false, }); payloads.other.alarm.map((v) => { if (v.enable === "1") { that.setData({ isSetWake: true }); } }); // 更新信息 that.data.deviceList.map((v, index) => { if (payloads.SrcDeviceName && payloads.SrcDeviceName.indexOf(v.name.split("BLUFI_")[1]) !== -1) { that.data.deviceList[index].ProdModel = payloads.other.ProdModel; that.data.deviceList[index].devName = payloads.other.devName; } }); // 更新缓存 wx.setStorage({ key: "devicelist", data: JSON.stringify(that.data.deviceList), success() { that.setData({ deviceList: that.data.deviceList }) } }); } else if (payloads.type === "battery" && payloads.other) { that.setData({ battery: that._battery(payloads.other.battery), }) } break; default: } }, // 格式化电量 _battery(battery) { let _battery = 0; if (battery < 20) { _battery = 0 } else if (20 <= battery && battery < 40) { _battery = 1 } else if (40 <= battery && battery < 60) { _battery = 2 } else if (60 <= battery && battery < 80) { _battery = 3 } else if (80 <= battery && battery <= 100) { _battery = 4 } else if (battery > 100) { _battery = 5 }; return _battery }, connectSuccess() { // 订阅设备在线信息 var that = this; that.subscribeDevicesStatus(); }, // [{"deviceId":"BLUFI_7cdfa1fcbb24","name":"BLUFI_7cdfa1fcbb24","state":"online","ProdModel":"MW-2AX(WIFI-N)","devName":"猫王小王子OTR-X"}] online(payloads) { // 设置在线状态 var that = this; that.data.deviceList.map((v, index) => { if (payloads.uuid && payloads.uuid.indexOf(v.name.split("BLUFI_")[1]) !== -1) { that.data.deviceList[index].state = payloads.state; } }); that.setData({ deviceList: that.data.deviceList, }); // 更新缓存 wx.setStorage({ key: "devicelist", data: JSON.stringify(that.data.deviceList) }); // 如没有选中,选中最新的 (() => { if (that.data.deviceListIndex === null) { let itue = false; that.data.deviceList.map((v, index) => { if (v.state === "online" && !itue) { itue = true; that.actionDevice(index); } }); } // else { // that.actionDevice(that.data.deviceListIndex); // }; })(); // 当前播放设备离线 if (that.data.deviceListIndex !== null && that.data.deviceList[that.data.deviceListIndex].state !== "online") { that.setData({ actionIndex: null, deviceListIndex: null, }); }; }, // 订阅设备在线状态 subscribeDevicesStatus() { var that = this; that.data.deviceList.forEach((value) => { let topic = `/AIrSMArT_${value.name.split("BLUFI_")[1]}/status/onoffline`; app.subscribe(topic); }) }, subscribeCurrDevice() { var that = this; if (!(app.globalData.client && app.globalData.client.connected)) { console.log("未连接MQTT服务器"); const str = setInterval(() => { clearInterval(str); that.subscribeCurrDevice(); }, 500); return; }; if (that.data.deviceList.length === 0 || that.data.deviceListIndex === null) { return }; let topic = `/AIrSMArT_${that.data.deviceList[that.data.deviceListIndex].name.split("BLUFI_")[1]}/user/pub_response`; app.subscribe(topic); const obj = { DstDeviceName: that.getThisDeviceID() }; app.PubMsg({ type: "get_dev_info", ...obj }); }, actionMusic(e) { var that = this; if (e.currentTarget.dataset.index === that.data.actionIndex) { return; }; if (that.data.deviceListIndex === null) { wx.showToast({ title: '请选择设备', icon: "none" }) return; }; that.setData({ actionIndex: e.currentTarget.dataset.index }); const other = { "url": "", "media_data": "", "user_id": `${app.globalData.userInfo.deviceUid}`, "timestamp": `${Math.round(new Date() / 1000)}`, "channel_id": `${that.data.channelData[e.currentTarget.dataset.index].channelNum}`, "order": "", "resource_from": "", "songAlbumID": "", "version": 3, "is_debug": app.globalData.is_debug }; app.PubMsg({ type: "play", DstDeviceName: that.getThisDeviceID(), other }); }, getThisDeviceID() { var that = this; return `AIrSMArT_${that.data.deviceList[that.data.deviceListIndex].name.split("BLUFI_")[1]}` }, getchannelData(clientType) { var that = this; if (that.data.deviceListIndex === null) { return; }; listByDevice({ clientType }).then((res) => { that.setData({ channelData: res }); // 接收设备当前播放状态 const obj = { DstDeviceName: that.getThisDeviceID() } app.PubMsg({ type: "get_position", ...obj }); wx.setStorage({ key: "channelData", data: res }); // 有新设备 if (app.globalData.newDeviceId) { app.globalData.newDeviceId = null; return; // 去掉此功能,先留着吧 // const other= { // "url": "", // "media_data": "", // "user_id": `${app.globalData.userInfo.deviceUid}`, // "timestamp": `${Math.round(new Date() / 1000)}`, // "channel_id": `${res[1].channelNum}`, // "order": "", // "resource_from": "", // "songAlbumID":"", // "version":3, // "is_debug": app.globalData.is_debug // }; // app.PubMsg({ // type: "play", // DstDeviceName: that.getThisDeviceID(), // other // }); } }) }, goChnnel() { var that = this; wx.setStorage({ key: "channelDeta", data: that.data.channelData[that.data.actionIndex], success() { wx.navigateTo({ url: './../channelDetails/channelDetails' }) } }) }, updata() { // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 wx.getUpdateManager().applyUpdate() }, updataClone() { var that = this; that.setData({ newVersion: false }) }, onUnload() { if (app.globalData.client === null) { return; }; app.globalData.client.end(true); app.globalData.client.end(true); app.globalData.client = null; }, onTapIndex(e) { var that = this; var index = e.currentTarget.dataset.index; var indexPage = that.data.indexPage; if (indexPage != index) { that.setData({ indexPage: index, }); } }, goMeAbout() { wx.navigateTo({ url: './../about/about', }) }, goMeLogin() { var that = this; if (that.data.islogin) { // 退出登录 wx.removeStorage({ key: 'userInfo', success(res) { var nickname = "未登录"; var greeting = that.updateGreeting(); if (nickname != "" && nickname != "未登录") { greeting = greeting + ',' + nickname;; } that.setData({ phone: "", greeting: greeting, islogin: false, nickname: nickname, userPic: "./../../img/head_pic.png", }); // wx.switchTab({ // url: `./../index/index` // }); } }); wx.removeStorage({ key: 'token', }) } else { // 登录 wx.navigateTo({ url: './../login/login', }); } }, addDevice() { var that = this; var phone = that.data.phone; var showLogin = that.data.showLogin; if (phone == "" || showLogin) { wx.navigateTo({ url: './../login/login' }); return; } that.goDeviceConnect(); }, goDeviceConnect() { wx.navigateTo({ url: './../deviceList/deviceList', }); }, ///点击item // [{"deviceId":"BLUFI_7cdfa1fcbb24","name":"BLUFI_7cdfa1fcbb24","state":"online","ProdModel":"MW-2AX(WIFI-N)","devName":"猫王小王子OTR-X"}] onTapIem(e) { var that = this; var item = e.currentTarget.dataset.item; var ProdModel = item.ProdModel; if (ProdModel == "猫王小王子OTR-X") { if (e.currentTarget.dataset.index === that.data.deviceListIndex) { that.goWake(); } else { that.actionDevice(e.currentTarget.dataset.index) } return; } ///去蓝牙连接处理 }, actionDevice(index) { var that = this; const device = that.data.deviceList[index]; if (device.state !== "online") { return; }; // 取消订阅 if (that.data.thisDeviceMac !== null) { app.unsubscribe(`/${that.data.thisDeviceMac}/user/pub_response`); }; that.setData({ deviceListIndex: index, thisDeviceMac: `AIrSMArT_${that.data.deviceList[index].name.split("BLUFI_")[1]}` }); // app.PubMsg({ // type: "get_dev_info", // DstDeviceName: that.getThisDeviceID() // }); that.subscribeCurrDevice(); }, goWake() { var that = this; if (that.data.deviceListIndex === null) { return; }; wx.navigateTo({ url: './../deviceWake/deviceWake?deviceId=' + that.data.deviceList[that.data.deviceListIndex].deviceId + "&clientType=" + that.data.deviceList[that.data.deviceListIndex].ProdModel, }); }, ///点击banner事件 onTapBanner() { var that = this; var item = e.currentTarget.dataset.item; }, deleteDevice(e) { var that = this; wx.showModal({ title: '确定删除?', success: function (res) { if (res.confirm) { if (element.ProdModel == "MW-2AX(WIFI-N)") {} const id = that.data.deviceList[e.currentTarget.dataset.index].deviceId; let name = that.data.deviceListIndex !== null ? that.data.deviceList[that.data.deviceListIndex].name : null; const deviceList = that.data.deviceList.filter((v, i) => { return id !== v.deviceId }); // 取消订阅 app.unsubscribe(`/AIrSMArT_${that.data.deviceList[e.currentTarget.dataset.index].name.split("BLUFI_")[1]}/user/pub_response`); wx.setStorage({ key: "devicelist", data: JSON.stringify(deviceList), success() { that.setData({ deviceList, thisDeviceMac: null }); // 当前没有设备 if (deviceList.length === 0) { that.setData({ actionIndex: null, deviceListIndex: null, }); } if (that.data.deviceListIndex === null) { return }; if (e.currentTarget.dataset.index === that.data.deviceListIndex) { let index_ = null; deviceList.map((v, index) => { if (v.state === "online" && index_ === null) { index_ = index; } }); if (index_ !== null) { that.actionDevice(index_); } else { that.setData({ actionIndex: null, deviceListIndex: null, }); }; } else { deviceList.map((v, index) => { if (v.name === name) { that.setData({ deviceListIndex: index, }); } }); } } }); } } }); }, // {"applicationType":"[0, 1]","deviceId":"DB:45:DD:76:42:15","img":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100711728016597.png","offlineImg":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100714667384264.png","connectImg":null,"name":"猫王音响·小王子 OTR-X","bluetoothName":"猫王音响·小王子 OTR-X","bluetoothNames":["猫王音响·小王子 OTR-X"],"isChannelsPlatforms":0,"platform":-1,"typeList":[{"is5g":0,"type":1,"connectType":1,"functionList":[1,3,6],"deviceLinkResp":{"icon1":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100644913162836.png","icon2":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20220909100648938942906.png","icon":null,"guideUrl":null}},{"is5g":0,"type":2,"connectType":3,"functionList":[1,3],"deviceLinkResp":{"icon1":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20230313155903515728925.png","icon2":"https://music-play.oss-cn-shenzhen.aliyuncs.com/device/20230313155910706032704.png","icon":null,"guideUrl":null}}],"clientType":"MW-2AX(WIFI)","firstVersion":"0.0.1","filter":null,"guideUrl":null,"manufacturer":"ShanJing","deviceType":0,"mac":"9b45dd76e2150000", /// deviceList /// 连接方式:bt-0,ble-1,upnp-2,mqtt-3 /// clientType // [{"deviceId":"BLUFI_7cdfa1fcbb24","name":"BLUFI_7cdfa1fcbb24","state":"online","ProdModel":"MW-2AX(WIFI-N)","devName":"猫王小王子OTR-X"}] addConnectDevice(connectDevice) { var that = this; var deviceList = that.data.deviceList; connectDevice.state = "online"; connectDevice.ProdModel = connectDevice.clientType; connectDevice.devName = connectDevice.name; connectDevice.name = connectDevice.deviceId; // deviceList.push(connectDevice); deviceList.unshift(connectDevice); var finalList = that.updateDeviceList(deviceList); var indexPage = that.data.indexPage; if (indexPage != 0) { that.setData({ indexPage: 0, deviceListIndex: 0, deviceList: finalList, }); } else { that.setData({ deviceListIndex: 0, deviceList: finalList, }); } // 更新缓存 wx.setStorage({ key: "devicelist", data: JSON.stringify(finalList) }); // console.log("dfadsfasdfasdfa==111==" + JSON.stringify(that.data.deviceList)) // console.log("dfadsfasdfasdfa==222==" + that.data.deviceList.length) }, updateDeviceList(deviceList) { if (deviceList.length == 0) return []; var finalList = []; finalList.push(deviceList[0]); var onLineList = []; var onNoLineList = []; for (var i = 0; i < deviceList.length; i++) { if (i > 0) { if (deviceList[i].state == "online") { onLineList.push(deviceList[i]) } else { onNoLineList.push(deviceList[i]) } } } onLineList.forEach(element => { if (element.ProdModel == "MW-2AX(WIFI-N)") { onLineList.push(element) } else { onNoLineList.push(element) } }); var onLineWifiList = []; var onLineNoWifiList = []; onNoLineList.forEach(element => { if (element.ProdModel == "MW-2AX(WIFI-N)") { onLineWifiList.push(element) } else { onLineNoWifiList.push(element) } }); finalList = finalList.concat(onLineWifiList); finalList = finalList.concat(onLineNoWifiList); var onNoLineWifiList = []; var onNoLineNoWifiList = []; onNoLineList.forEach(element => { if (element.ProdModel == "MW-2AX(WIFI-N)") { onNoLineWifiList.push(element) } else { onNoLineNoWifiList.push(element) } }); finalList = finalList.concat(onNoLineWifiList); finalList = finalList.concat(onNoLineWifiList); return finalList; }, })