houjie 4 years ago
parent
commit
c4000335a9

+ 30 - 0
common/util.js

@@ -104,6 +104,36 @@ function decodeBase64(text){
 	return resStr
 }
 
+function isEmpty (val) {
+	// null or undefined
+	if (val == null) return true;
+  
+	if (typeof val === 'boolean') return false;
+  
+	if (typeof val === 'number') return !val;
+  
+	if (val instanceof Error) return val.message === '';
+  
+	switch (Object.prototype.toString.call(val)) {
+	  // String or Array
+	  case '[object String]':
+	  case '[object Array]':
+		return !val.length;
+  
+	  // Map or Set or File
+	  case '[object File]':
+	  case '[object Map]':
+	  case '[object Set]': {
+		return !val.size;
+	  }
+	  // Plain Object
+	  case '[object Object]': {
+		return !Object.keys(val).length;
+	  }
+	}
+  
+	return false;
+  }
 
 
 module.exports = {

+ 1 - 1
components/deviceCard/deviceCard.vue

@@ -45,7 +45,7 @@ export default {
   flex-direction:column;
   justify-content: space-between;
   width: 35vw;
-  height: 22vw;
+  height: 18vw;
   border: 1rpx solid #333333;
 }
 .topBox{

+ 168 - 25
pages/index/device.vue

@@ -1,9 +1,10 @@
 <template>
   <view class="content">
-    <button @click="addDevice">添加设备</button>
-
-    <button @click="getPlayInfo">获取播放信息</button>
-    <button @click="getDeviceInfo">获取设备信息</button>
+    <view class="dbox">
+      <button @click="addDevice">添加设备</button>
+      <!-- <button @click="getPlayInfo">获取播放信息</button> -->
+      <button @click="getDeviceInfo">获取设备信息</button>
+    </view>
     <view class="dbox">
       <device-card
         v-for="(device, index) in deviceList"
@@ -14,6 +15,32 @@
         >{{ device.name }} {{ device.online }}</text
       > -->
     </view>
+    <view class="play-info">
+      <image class="play-thmub" :src="playInfo.albumURI" mode="aspectFit" />
+      <text style="margin-top: 30rpx">{{ playInfo.title }}</text>
+      <text style="margin-top: 30rpx">{{ playInfo.artist }}</text>
+    </view>
+    <view class="play-ctrl">
+      <image src="../../static/image/play/previous.png" class="next-icon" @click="previous"/>
+      <image
+        v-if="playInfo.PlayState != 1"
+        src="../../static/image/play/play.png"
+        class="next-icon"
+        @click="play"
+      />
+      <image
+        v-if="playInfo.PlayState == 1"
+        src="../../static/image/play/pause.png"
+        class="next-icon"
+        @click="pause"
+      />
+      <image src="../../static/image/play/next.png" class="next-icon" @click="next"/>
+      
+    </view>
+    <text style="margin-top: 30rpx; margin-left:50rpx">音量</text>
+    <slider value="20" class="progress"  min="0" max="100" step="1" @change="setVolume" show-value></slider>
+    <text style="margin-top: 30rpx; margin-left:50rpx">频道</text>
+    <slider :value="playInfo.channel" class="progress"  min="0" max="11" step="1" @change="setChannel" show-value></slider>
   </view>
 </template>
 
@@ -36,14 +63,14 @@ export default {
   },
   methods: {
     onofflineCallback(value) {
-      console.log("onofflineCallback");
+      //console.log("onofflineCallback");
     },
     //测试添加设备
     addDevice() {
       //添加设备
       this.$store.dispatch({
         type: "moduleMqtt/addDevice",
-        clientId: "wx_18126447015",
+        clientId: "wx_650633",
         device: {
           name: "MW-M3",
           uuid: "89860474192070498495",
@@ -52,26 +79,111 @@ export default {
     },
     //获取播放信息
     getPlayInfo() {
-      this.$store.dispatch({
-        type: "moduleMqtt/publishWithType",
-        mqttType: "get_position",
-      }).then((result) => {
-        
-      }).catch((err) => {
-        console.warn(err);
-      });
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "get_position",
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
     },
-    //获取播放信息
+    //获取设备信息
     getDeviceInfo() {
-      this.$store.dispatch({
-        type: "moduleMqtt/publishWithType",
-        mqttType: "get_dev_info",
-      }).then((result) => {
-        
-      }).catch((err) => {
-        console.warn(err);
-        
-      });
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "get_dev_info",
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+    },
+    //下一曲
+    next() {
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "next",
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+    },
+    //上一曲
+    previous() {
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "previous",
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+    },
+    //播放
+    play() {
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "play",
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+    },
+    //暂停
+    pause() {
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "pause",
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+    },
+    //设置音量
+    setVolume(event){
+      console.log(event.target.value);
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "volume_set",
+          other:{
+            'volume':event.target.value
+          }
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+
+    },
+    //设置频道
+    setChannel(event){
+      console.log(event.target.value);
+      this.$store
+        .dispatch({
+          type: "moduleMqtt/publishWithType",
+          mqttType: "play",
+          other:{
+            'user_id':'650633',
+            'timestamp':'1560652541',
+            'channel_id':event.target.value+''
+          }
+        })
+        .then((result) => {})
+        .catch((err) => {
+          console.warn(err);
+        });
+
     },
     godoBle() {
       //添加设备
@@ -97,6 +209,7 @@ export default {
     // },
     ...mapState({
       deviceList: (state) => state.moduleMqtt.deviceList,
+      playInfo: (state) => state.moduleMqtt.playInfo,
     }),
   },
 };
@@ -104,7 +217,14 @@ export default {
 
 <style>
 .content {
-  margin: 20rpx;
+  margin: 10rpx;
+  display: flex;
+  flex-direction: column;
+}
+.play-info {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
 }
 .dbox {
   display: flex;
@@ -117,4 +237,27 @@ export default {
   overflow: hidden;
   white-space: nowrap; */
 }
+.play-thmub {
+  display: flex;
+  align-self: center;
+  width: 300rpx;
+  height: 300rpx;
+  margin-top: 30rpx;
+}
+.play-ctrl {
+  display: flex;
+  flex-direction: row;
+  justify-content: space-around;
+  margin-top: 40rpx;
+}
+.next-icon {
+  width: 54rpx;
+  height: 60rpx;
+}
+.progress{
+  align-self: center;
+  width: 80vw;
+ 
+}
+
 </style>

+ 1 - 1
pages/index/index.vue

@@ -4,7 +4,7 @@
       <button type="primary" @click="connectOrDisconnect">
         {{ connectText }}
       </button>
-      <button type="primary" @click="addDevice">添加设备</button>
+      <!-- <button type="primary" @click="addDevice">添加设备</button> -->
     </view>
     <!-- <image class="logo" src="/static/logo.png"></image> -->
     <text class="title">发布消息</text>

BIN
static/image/play/next.png


BIN
static/image/play/pause.png


BIN
static/image/play/play.png


BIN
static/image/play/previous.png


+ 41 - 62
store/modules/moduleMqtt.js

@@ -1,5 +1,6 @@
 import mqtt from '../../common/mqtt.js'
 import Vue from 'vue'
+import parse from './mqttParse.js'
 //import mqtt from 'mqtt/dist/mqtt.js'
 
 const options = {
@@ -27,7 +28,7 @@ function subscribeDevicesStatus(dispatch,deviceList){
 
 //订阅消息
 function subscribeCurrDevice(dispatch,device){
-	if(typeof device !== 'undefined'){
+	if(device){
 		let topic = `/${device.uuid}/user/pub_response`
 		dispatch('subscribe',topic)
 	}
@@ -37,19 +38,33 @@ export default {
 	namespaced: true,
 	state: {
 		//当前选择的设备
-		currentDevice: undefined,
+		currentDevice: null,
 		//用户设备列表
 		deviceList: [],
 		//mqtt客户端
-		mqttClient: undefined,
+		mqttClient: null,
 		//收到的消息的历史记录
 		msgList:[],
+		//设备的播放信息
+		playInfo:{
+			title:"",
+			artist:"",
+			albumURI:"",
+			songInfoID:"",
+			songAlbumID:"",
+			Duration:0,
+			channel:1,
+			audioType:1,
+			PlayState:3,
+			PlayMode:0
+
+		}
 
 	},
 	getters: {
 		//mqtt连接状态
 		connected: state => {
-			return state.mqttClient !== undefined && state.mqttClient.connected
+			return state.mqttClient && state.mqttClient.connected
 		},
 
 	},
@@ -75,15 +90,19 @@ export default {
 		},
 		//token失效,退出登录,需要清除数据
 		release(state) {
-			deviceList = []
-			currentDevice = undefined
-			state.mqttClient = undefined
+			state.deviceList = []
+			state.currentDevice = null
+			state.mqttClient = null
 		},
 		//设置设备的在线状态
 		updateDeviceState(state,data){
 			Vue.set(state.deviceList,data.index,data.device)
 			//state.deviceList[data.index] = {...state.deviceList[data.index], online:data.online}
 			//state.deviceList[data.index].online = data.online
+		},
+		//更新播放信息
+		updatePlayInfo(state,playinfo){
+			state.playInfo = playinfo
 		}
 
 	},
@@ -98,7 +117,7 @@ export default {
 			let findDevice = state.deviceList.find((item) =>{
 				return item.uuid === device.uuid
 			})
-			if(typeof findDevice === 'undefined'){
+			if(findDevice == null){
 				if(state.deviceList.length === 0){
 					//设置当前的设备为添加的设备
 					commit('setCurrentDevice',device)
@@ -109,7 +128,7 @@ export default {
 				if(getters.connected){
 					//订阅设备是否在线
 					subscribeDevicesStatus(dispatch,[device])
-					if(typeof state.currentDevice !== 'undefined' && state.currentDevice.uuid === device.uuid){
+					if(state.currentDevice && state.currentDevice.uuid === device.uuid){
 						//订阅当前设备的消息
 						subscribeCurrDevice(dispatch,state.currentDevice)
 					}
@@ -127,7 +146,7 @@ export default {
 			let findDevice = state.deviceList.find((item) =>{
 				return item.uuid === device.uuid
 			})
-			if(typeof findDevice !== 'undefined'){
+			if(findDevice){
 				//取消此设备的订阅
 				let topic = `/${device.uuid}/status/onoffline`
 				dispatch('unsubscribe',topic)
@@ -136,20 +155,20 @@ export default {
 				//在设备列表中删除此设备
 				commit('removeDevice',findDevice)
 				//如果删除的是选中的设备
-				if(typeof state.currentDevice !== 'undefined' && state.currentDevice.uuid == device.uuid){
+				if(currentDevice && state.currentDevice.uuid == device.uuid){
 					//清除当前选中的设备 todo 还是自动选中在线的设备
-					commit('setCurrentDevice',undefined)
+					commit('setCurrentDevice',null)
 				}
 				
-				if(state.deviceList.length === 0 ){//所有的设备都已经删除
-					dispatch()
+				if(state.deviceList.length === 0 ){//所有的设备都已经删除,关闭连接
+					dispatch('disconnect')
 				}
 			}
 		},
 
 		//连接设备
 		connect({ state, dispatch,commit, getters }, clientId) {
-			if (typeof state.mqttClient === 'undefined') {
+			if (state.mqttClient == null) {
 				//连接服务器
 				commit('connect', clientId)
 				//连接成功回调
@@ -182,49 +201,9 @@ export default {
 				//收到消息的回调
 				state.mqttClient.on('message', function (topic, message) {
 					console.log(`message = ${message.toString()}`);
-					let arr = topic.split("/");
-					if(arr.length >1){
-						let fromDeviceUuid = arr[1]
-						
-						//设备在线和离线的消息
-						if(topic.endsWith('onoffline')){
-							let index = -1
-							for (var i = 0; i < state.deviceList.length; i++) {
-								if(state.deviceList[i].uuid === fromDeviceUuid){
-									index = i;
-									break
-								}
-							}
-							console.log(`state index = ${index}`);
-							if(index >= 0){
-								let stateJson = JSON.parse(message)
-								//console.log(stateJson);
-								let device = state.deviceList[i];
-								if(stateJson.state === 'online'){
-									device.online = true
-									commit('updateDeviceState',{index,device})
-									//commit('updateDeviceState',{index,online:true})
-									//state.deviceList[index].online = true
-									if(typeof state.currentDevice !== 'undefined' && state.currentDevice.uuid == device.uuid){
-										dispatch({
-											type:'publishWithType',
-											mqttType:'get_position',
-										})
-									}
-								}else{
-									device.online = false
-									commit('updateDeviceState',{index,device})
-									//commit('updateDeviceState',{index,online:true})
-									//state.deviceList[index].online = false
-								}
-								uni.$emit('mqtt_onoffline',stateJson)
-								// state.deviceList.forEach(element => {
-								// 	console.log(`online = ${element.online}`);
-								//   });
-							}
-							
-						}
-					}
+					//解析收到的消息
+					parse({state, dispatch,commit, getters },topic,message)
+					
 					//这是测试的
 					state.msgList.push({
 						topic: topic.toString(),
@@ -249,7 +228,7 @@ export default {
 		//断开mqtt的连接
 		disconnect({state,commit},isRelease) {
 			console.log('disconnect')
-			if (state.mqttClient !== undefined) {
+			if (state.mqttClient) {
 				state.mqttClient.end(false,() =>{
 					console.log(`state.mqttClient.connected = ${state.mqttClient.connected}`);
 				})
@@ -269,7 +248,7 @@ export default {
 				return new Promise((resolve, reject) => {
 					reject('连接已断开')
 				});
-			}else if(typeof state.currentDevice === undefined || !state.currentDevice.online){
+			}else if(!(state.currentDevice && state.currentDevice.online)){
 				return new Promise((resolve, reject) => {
 					reject('设备已经离线')
 				});
@@ -282,7 +261,7 @@ export default {
 				  'SrcDeviceName':options.clientId,
 				  'type':type,
 				}
-				if(typeof other !== 'undefined'){
+				if(other){
 					json.other = other
 				}
 				let payload = JSON.stringify(json)
@@ -302,7 +281,7 @@ export default {
 					//发布消息
 					state.mqttClient.publish(message.topic, message.payload, (err) => {
 						if (err) {
-							console.log(err);
+							console.warn(err);
 							reject(err)
 						} else {
 							resolve()

+ 129 - 0
store/modules/mqttParse.js

@@ -0,0 +1,129 @@
+function isEmpty(str){
+    if(str){
+        return true
+    }
+    if(!str.length){
+        return true
+    }
+    if(str == 'unknow'){
+        return true
+    }
+    return false
+
+}
+
+/**
+ * 收到设备在线和离线的消息
+ * @param {*} param0 
+ * @param {*} topic 
+ * @param {*} message 
+ */
+function receiveOnOffline({state, dispatch,commit},fromDeviceUuid, message){
+    
+    let index = -1
+    for (var i = 0; i < state.deviceList.length; i++) {
+        if(state.deviceList[i].uuid === fromDeviceUuid){
+            index = i;
+            break
+        }
+    }
+    console.log(`state index = ${index}`);
+    if(index >= 0){
+        let stateJson = JSON.parse(message)
+        //console.log(stateJson);
+        let device = state.deviceList[i];
+        //设备在线
+        if(stateJson.state === 'online'){
+            device.online = true
+            //更新设备状态信息
+            commit('updateDeviceState',{index,device})
+            //commit('updateDeviceState',{index,online:true})
+            //state.deviceList[index].online = true
+            if(state.currentDevice && state.currentDevice.uuid == device.uuid){ //当前设备在线
+                //延时获取播放信息
+                setTimeout(function() {
+                    dispatch({
+                        type:'publishWithType',
+                        mqttType:'get_position',
+                    })
+                }, 200);
+                
+            }
+        }else{
+            device.online = false
+            //更新设备状态信息
+            commit('updateDeviceState',{index,device})
+            //commit('updateDeviceState',{index,online:true})
+            //state.deviceList[index].online = false
+        }
+        //发送通知
+        uni.$emit('mqtt_onoffline',stateJson)
+        // state.deviceList.forEach(element => {
+        // 	console.log(`online = ${element.online}`);
+        //   });
+    }
+}
+
+/**
+ * 更新播放信息
+ * @param {*} param0 
+ * @param {*} jsonPayload 
+ */
+function updatePlayInfo({commit}, jsonPayload){
+    if(jsonPayload.other){
+        let playinfo = jsonPayload.other
+        
+        if(isEmpty(playinfo.title)){
+            playinfo.title = '猫王妙播'
+        }
+        if(isEmpty(playinfo.albumURI)){
+            playinfo.albumURI =  "https://airsmart-photo1.oss-cn-shanghai.aliyuncs.com/wx/bg_place_holder.png"
+        }
+
+        commit('updatePlayInfo',playinfo)
+    }
+}
+
+
+
+/**
+ * 解析收到的消息
+ * @param {*} param0 
+ * @param {*} topic     主题
+ * @param {*} message   playload
+ */
+function messageParse({state, dispatch,commit,getters},topic, message){
+    //console.log(`message = ${message.toString()}`);
+    let arr = topic.split("/");
+    if(arr.length >1){
+        let fromDeviceUuid = arr[1]
+        //设备在线和离线的消息
+        if(topic.endsWith('onoffline')){
+            receiveOnOffline({state, dispatch,commit},fromDeviceUuid, message)
+            
+        }else{
+            //收到设备发过来的数据
+            try{
+                let jsonObj = JSON.parse(message.toString())
+                if(jsonObj.type){
+                    //收到播放信息
+                    if(jsonObj.type == 'get_position'){
+                        //判断是否是当前选中的设备
+                        if(state.currentDevice && state.currentDevice.uuid == fromDeviceUuid){
+                            //更新播放信息
+                            updatePlayInfo({commit}, jsonObj)
+                        }
+                    }
+                }
+            }catch(e){
+                console.warn(e);
+            }
+            
+            
+        }
+    }
+}
+
+
+
+module.exports = messageParse