  <template>
         <view class="page">
                  <view>uni-app本地图片压缩+上传</view>
                  <view class="photo-box ">
                        <button type="primary" @tap="clickImg()">点击上传</button>
                        <view v-if="image">
                        <img :src="image" mode="aspectFit">
                        </view>
                        <view class="photo-txt">{{'压缩后图片地址: ' + imageInfo.target}}</view>
                        <view class="photo-txt">{{'压缩后图片size: '+ imageInfo.size}}</view>
                  </view> 
        <view>
            MQTT
            <button @click="mqtt('connect')">开启连接</button>
            <button @click="mqtt('subscribe')">订阅主题</button>
            <button @click="mqtt('unsubscribe')">取消订阅主题</button>
            <button @click="mqtt('send')">发送数据</button>
            <button @click="mqtt('close')">关闭连接</button>
            <button @click="mqtt('isConnected')">是否已连接</button>
        </view>
         <button @click="message = []">清空屏幕消息</button>
        <view class="msg">
            <div v-for="(item,index) in message" :key="index">{{JSON.stringify(item)}}</div>
        </view>
            </view>
      </template>


<script>
    const _MQTT = uni.requireNativePlugin("zad-socket-mqtt");
    function str2asc(str)
    {
        var n = UnicodeToAnsi(str.charCodeAt(0));
        var s = n.toString(16);
        return str.toUpperCase();
    }
    function urlEncode(str)
    {
        var ret = "";
        var strSpecial = "!\"#$%&’()*+,/:;<=>?[]^`{|}~%";
        var tt = "";
        for(var i = 0; i < str.length; i++)
        {
            var chr = str.charAt(i);
            var c = str2asc(chr);
            tt += chr + ":" + c + "n";
            if (parseInt("0x" + c) > 0x7f)
            {
                ret += "%" + c.slice(0,2) + "%" + c.slice(-2);
            }
            else
            {
                if (chr == " ")
                    ret += "+";
                else if (strSpecial.indexOf(chr) != -1)
                    ret += "%" + c.toString(16);
                else
                    ret += chr;
            }
        }
       
        return ret;
    }
    import base64 from "@/common/base64.js"
    import md5 from "@/common/hex_md5.js"
    // import {testToken, getToken} from "@/common/token"
    // // import { MyMqttManager } from '@/utssdk/mqtt/index.uts';
    // import { MyMqttManager } from '@/uni_modules/flight-mqtt';
    import {Onenet} from "@/common/onenet"
    const client = new Onenet("LTt3E9vn93", "865522079861164", "jdMvXePFKd3ZBZFn19GnsZ1pww3tbVFtyePlyXH3Ex0=", "Du4Q3aT7WSY4L5jJzG5i7wPLpvWEu18YLQmhuOS0idOT/Wk+UMBGWhz+djms87iHA5KaRh7ylOsSBjhbjzZlhg==","139522");
    client.connectMqttServer()
  export default {
        data() {
              return {
                image:"",
                imageInfo:{},
                message: [{ code: 200, data: 'Socket 插件测试' }],
                productId: "123",
                deviceName: "321",
                scret: "TVdiUWx0Ym12cVlRUEx1QUpRMnZlTzhaQzdHUU1yeFo=",
                version: "2018-10-31"
              };
        },
        onLoad() {
          setInterval(()=>{
            client.publishRealData(()=>{
              return {
                ConveyorBeltSwitch: "1",
                Voltage: 12.312
              }
            })
          }, 10000)
        },
        methods:{
              clickImg(){     //选择图片 
                    let _this=this
                    uni.chooseImage({
                          count: 1,
                          sizeType:['compressed'],
                          success(res) {
                                // _this.uploadFile(res.tempFilePaths[0])        // 上传图片到服务器
                                console.log("上传文件")
                                client.uploadFile(res.tempFilePaths[0]).then(console.log)
                                .catch(console.log)
                          }
                    })
              },
              //上传图片
              async uploadFile(image){
                    uni.showLoading({
                          mask:true,
                          title: '上传中...'
                    })
                    this.image=image
                    //开始上传，此处可先注释看压缩效果
                    uni.uploadFile({
                      url: 'http://115.28.187.9:8005/pest/image/upload', //仅为示例，此处填写后台的上传图片接口地址
                      filePath: plus.io.convertAbsoluteFileSystem("/storage/emulated/0/DCIM/Camera/IMG_20241108_015158.jpg"),
                      name: 'file',
                      formData: {
                        imei: "863418052126927"
                      },
                      // header:{'Authorization': `Bearer ${uni.getStorageSync('token')}`,},
                      success: (uploadFileRes) => {        //图片上传成功
                          uni.hideLoading()
                          // let img=JSON.parse(uploadFileRes.data)// console.log(img) 
                        console.log(uploadFileRes);
                      },
                      fail: (err) => {
                        console.log(err);
                          uni.hideLoading()// console.log('uploadImage fail', err);
                      }
                    });
              },
              //压缩图片
              compress(img){   
                    console.log('开始压缩');
                    let that=this
                    return new Promise((res) => {
                          // var localPath = plus.io.convertAbsoluteFileSystem(img);
                          plus.io.resolveLocalFileSystemURL(img, (entry) => {      //通过URL参数获取目录对象或文件对象
                          entry.file((file) => {       // 可通过entry对象操作图片 
                          console.log('压缩前图片信息:' + JSON.stringify(file)); //压缩前图片信息
                                if(file.size > 504800) {   //   如果大于500Kb进行压缩
                                      plus.zip.compressImage({    // 5+ plus.zip.compressImage 了解一下，有详细的示例
                                            src: img,          //src: 压缩原始图片的路径    
                                            dst: img.replace('.png', '2222.png').replace('.PNG', '2222.PNG').replace('.jpg','2222.jpg').replace('.JPG','2222.JPG'),
                                            width: '40%',      //dst: (String 类型 )压缩转换目标图片的路径，这里先在后面原始名后面加一个2222区分一下
                                            height: '40%',     //width,height: (String 类型 )缩放图片的宽度,高度
                                            quality: 10,      //quality: (Number 类型 )压缩图片的质量
                                            overwrite: true,  //overwrite: (Boolean 类型 )覆盖生成新文件
                                            // format:'jpg'   //format: (String 类型 )压缩转换后的图片格式
                                      }, (event) => {
                                            console.log('压缩后图片信息:' + JSON.stringify(event));// 压缩后图片信息
                                            this.imageInfo=event
                                            let newImg = event.target;
                                            res(newImg);  //返回新的图片地址，在uploadFile之前接收
                           }, function(err) {
                          // console.log('Resolve file URL failed: ' + err.message);
                           });
                                }else{//else小于500kb跳过压缩，直接返回现有的src
                                      res(img);
                                }
                          });
                          }, (e) => { // 返回错误信息
                                // console.log('Resolve file URL failed: ' + e.message);
                          });
                    })
              },
              connectParam(pid, dn, sk) {
                const res = `products/${pid}/devices/${dn}`;
                const token = getToken(res, "sha1", sk)
                
                return {
                  clientId: dn,
                  username: pid,
                  password: token
                }
              },
              pulishRealData(){
                
              },
              mqtt(method, param) {
                switch (method) {
                    case "connect": //连接
                        // _MQTT.event({
                        //     method: 'connect',
                        //     param: {
                        //         url: 'tcp://115.28.187.9:1883',
                        //         username: 'xph',
                        //         password: '87510227',
                        //         clientId: '8655220798611641',
                        //         // url: 'tcp://mqtts.heclouds.com:1883',
                        //         // username: 'LTt3E9vn93',
                        //         // password: "version=2018-10-31&res=products%2FLTt3E9vn93%2Fdevices%2F865522079861164&et=2084432555101&method=md5&sign=EMcSMAKxrWARVbh3o%2BVVAA%3D%3D",
                        //         // clientId: '865522079861164',
                        //         cleanSession : true,
                        //         mqttversion: 4,
                        //         keepalive: 60
                        //     }
                        // }, e => {
                        //     this.handleMessage(e)
                        // })
                        // 1. 设置收到消息后的处理逻辑
                        mqtt.on((topic, content) => {
                          console.log(topic, content)
                            // 注意：原生回调可能在非 UI 线程，Vue2 某些情况下需要处理
                            // this.messages.push({ topic, content, time: new Date().toLocaleTimeString() });
                        })
          
                        let param = this.connectParam("LTt3E9vn93", "865522079861164", "jdMvXePFKd3ZBZFn19GnsZ1pww3tbVFtyePlyXH3Ex0=")
                        // mqtt.connect("tcp://mqtts.heclouds.com:1883", param.clientId, param.username, param.password);
                        mqtt.connect("tcp://broker.emqx.io:1883", param.clientId, param.username, param.password);
                        // 3. 初始化回调监听
                        mqtt.initCallback();
                        
                        // 4. 订阅
                        setTimeout(() => {
                            mqtt.subscribe("test/topic/tt");
                        }, 2000); // 确保连接成功后再订阅，实际建议在 connect 的回调中处理
                        break;
                    case "isConnected": //是否已连接
                        // _MQTT.event({ method: 'isConnected' })
                        break;
                    case "subscribe": //订阅
                        mqtt.subscribe("test/topic/tt");
                        // _MQTT.event({ method: 'subscribe', param: { topic: '/device/location/abcdefg' } })
                        break;
                    case "unsubscribe": //取消订阅
                        // _MQTT.event({ method: 'unsubscribe', param: { topic: '/device/location/abcdefg' } })
                        break;
                    case "send": //发送消息
                        // _MQTT.event({
                        //     method: 'send',
                        //     param: { topic: '/device/location/abcdefg', message: '消息1', retained: false }
                        // })
                        mqtt.publish("test/topic/tt", "Hello from UTS!");
                        break;
                    case "close": //关闭
                        _MQTT.event({ method: 'close' })
                        break;
                }
            },
            handleMessage(e) {
                //e.code    400方法调用失败、200方法调用成功、0插件主动发送的消息、-1插件主动发送的异常消息
                //e.method  调用时传递的参数，可以根据method处理逻辑
                //e.data    返回数据体
                this.message.push(e)
                if (e.method == 'receive') {
                    //接收到服务端的消息
                    console.log(e.data)
                }
            },
        }
   }
</script>

<style>
  .canvas {
    max-width: 300px;
    max-height: 400px;
    transform: scale(0.01);
  }
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
