<script>
	import  mqtt  from "@/static/js/mqtt.min.js"
	var client=null;
	const options={
			          connectTimeout:4000,
			          clientID:'mqttjs_6b226889',
			          port:8084,
			          username:'dc28105bf9f662c97141407cd1d55fca',
			          password:'a123456'
			        };
	var topic = "/iot/4133/wx";	
	var topic_stm32 = "/iot/4133/stm32";
				
	export default {
		globalData:{
				value:{
	"ht":	100,
	"htup":	200,
	"htdw":	600,
	"s2":	60,
	"s2up":	99,
	"s2dw":	80,
	"tpup":	40,
	"tpdw":	10,
	"bs":	0,
	"G_N":	0,
	"tp":	0,
	"G_E":	0,
	"ph":""
}
		},
		onLaunch: function() {
			console.log('App Launch')
			// let client = mqtt.connect("mqtt://test.mosquitto.org");
			this.connectmqtt();
		},
		onShow: function() {
			console.log('App Show')
		},
		onHide: function() {
			console.log('App Hide')
		},
		methods:{
			/**mqtt连接,不支持发送16进制buffer数据，暂弃用*/
			  connectmqtt() {
			     var that = this
			        
			     client=mqtt.connect('wxs://t.yoyolife.fun/mqtt',options),
			        client.on('connect',(e)=>{
			          console.log('服务器连接成功')
			          client.subscribe(topic,{qos:1},function(err){
			            if(!err)
			            console.log('订阅成功')
						// that.mqttSend(JSON.stringify(getApp().globalData.value))
			          })
			        })
			        //信息监听事件
			        client.on('message',function(topic,message){
			          console.log("-->message-->",message)
			          let tem = {}
			          tem = JSON.parse(message)
					  getApp().globalData.value = tem;
			          console.log(tem)
					  uni.$emit("value",tem);
			          if(tem.temp)
			          {
			            // that.setData({
			            //   getTemp:tem.temp,
			            //   getLight:tem.light,
			            //   getHumid:tem.humi
			            // })
			          }
			    
			          
			          console.log('收到'+message.toString())
			        })
			        client.on('reconnect',(error)=>{
			          console.log('正在重新连接',error)
			        })
			        client.on('error',(error)=>{
			          console.log('连接失败',error)
			        })
				// this.mqttSend("你好");
			  },
			  //mqtt发送数据，只支持string，不支持16进制buffer
			  mqttSend(msg) {
				  client.publish(topic_stm32,JSON.stringify(msg),{ qos: 1 },function(err){
				         if(!err)
				         {
				           console.log('成功发送',JSON.stringify(msg))
				         }
				       })
			    // this.globalData.client.publish(topic, msg, { qos: 1 }, function (err) {
			    //   console.log('send', err)
			    // })
			  },
			  /**将ArrayBuffer转换成字符串*/
			  ab2hex(buffer){
			    var hexArr = Array.prototype.map.call(
			      new Uint8Array(buffer),
			        function (bit) {
			          return ('00' + bit.toString(16)).slice(-2)
			        }
			      )
			      return hexArr.join('');
			  }
		}
		
		
	}
</script>

<style>
	/*每个页面公共css */
</style>
