7度加冰

冰冻三尺,非一日之寒。

MQTT基本

package vhcom.cn.smallcontrol.mqtt;

import android.annotation.SuppressLint;
import android.os.*;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.MqttClient;

public class MqttBase implements Runnable {
    //配置信息
    private String gHost = "tcp://192.168.1.166:1883";
    private String gUserName = "esp8266";
    private String gPassWord = "esp8266";
    private String gClientId = "AndroidClient1";
    private String gStrTopic;
    private String gMsg = "msg";

    // 定义变量
    org.eclipse.paho.client.mqttv3.MqttClient gMqttClient;
    MqttConnectOptions gMqttConnectOptions;
    Handler gHandler,mChildHandler;


    // 初始化
    public MqttBase(Handler handler, String str) {
        gHandler = handler;
        gClientId = str.substring(0, 10);

        gLog("配置:");
        gLog("客户ID:" + gClientId);
    }

    // 发送消息到界面
    public void gLog(String str1)
    {
        Message gMessage = new Message();
        Bundle gBundle = new Bundle();
        gMessage.what = 3;
        gBundle.putString("log", str1);
        gMessage.setData(gBundle);
        gHandler.sendMessage(gMessage);

    }


    // 主线程handle 接收消息

    @SuppressLint("HandlerLeak")
    private void childHandler() {
        mChildHandler = new Handler() {
            @Override
            public void handleMessage(Message message)
            {
                String topic=message.getData().getString("topic");
                String msg=message.getData().getString("msg");

                if(message.what==1){
                    subscription(topic);
                }
                if(message.what==2){
                    unsubscription(topic);
                }
                if(message.what==3){
                   publist(topic,msg);
                }

            }
        };
    }

    // 发送消息到子线程handle    1-2-3  订阅,取消订阅,发送
    public void childLog(int flag,String topic,String msg)
    {
        Message gMessage = new Message();
        Bundle gBundle = new Bundle();
        gMessage.what = flag;

        gBundle.putString("topic", topic);
        gBundle.putString("msg", msg);

        gMessage.setData(gBundle);
        if(mChildHandler!=null){
            mChildHandler.sendMessage(gMessage);
        }


    }


    // 连接
    private void connect() {
        options();
            if (gMqttClient != null && !gMqttClient.isConnected()) {
                try {
                    gMqttClient.connect(gMqttConnectOptions);
                    gLog("连接成功");

                } catch (Exception e) {
                    e.printStackTrace();
                    gLog("连接异常");
                }

            }
    }

    //断开
    private void mqtt_disconnect() {
        if (gMqttClient.isConnected()) {
            try {
                gMqttClient.disconnect();
                gLog("断开成功");
            } catch (Exception e) {
                e.printStackTrace();
                gLog("断开异常");
            }

        }
    }

    //订阅
    private void subscription(String topic) {
        if (gMqttClient.isConnected()) {
                try {
                    gMqttClient.subscribe(topic);
                    gLog("订阅成功");
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }

    }

    //取消订阅
    private void unsubscription(String topic) {
        if (gMqttClient.isConnected()) {
            try {
                gMqttClient.unsubscribe(topic);
                gLog("取消订阅成功");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //推送消息
    private void publist(String topic,String msg){

        if (gMqttClient.isConnected()) {
            try {
                MqttMessage message = new MqttMessage(msg.getBytes());
                message.setQos(1);
                gMqttClient.getTopic(topic).publish(message);
            } catch (MqttException e) {

            }
        }

    }

    // 参数设定
    public void options() {
        try {

            // host为主机名,test为clientid即连接MQTT的客户端ID,一般以客户端唯一标识符表示,MemoryPersistence设置clientid的保存形式,默认为以内存保存
            gMqttClient = new MqttClient(gHost, gClientId, null);
            // MQTT的连接设置
            gMqttConnectOptions = new MqttConnectOptions();
            // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,这里设置为true表示每次连接到服务器都以新的身份连接
            gMqttConnectOptions.setCleanSession(true);
            // 设置连接的用户名
            gMqttConnectOptions.setUserName(gUserName);
            // 设置连接的密码
            gMqttConnectOptions.setPassword(gPassWord.toCharArray());
            // 设置超时时间 单位为秒
            gMqttConnectOptions.setConnectionTimeout(5);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线,但这个方法并没有重连的机制
            gMqttConnectOptions.setKeepAliveInterval(20);
            // 设置回调
            gMqttClient.setCallback(mqttCallback);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void connectionLost(Throwable throwable) {
            gLog(throwable.toString());
        }

        @Override
        public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
            String str1 = new String(mqttMessage.getPayload());
            gLog(topic + "--"+str1);
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            gLog("send ok");
        }
    };


    //线程
    @Override
    public void run() {



        // 初始化消息循环队列,需要在Handler创建之前
        Looper.prepare();
        connect();
        // 接收其他线程消息
        childHandler();
        gLog("init is ok");
        // 启动子线程消息循环队列
        Looper.loop();

    }


    public void  onSubscription(String topic){
        childLog(1,topic,"");
    }
    public void  onUnSubscription(String topic){
        childLog(2,topic,"");
    }

    public void onpublish(String topic,String msg){
       childLog(3,topic,msg);
    }

    public void onDestroy()
    {
        mChildHandler.getLooper().quit();
    }




}


网站分类
控制面板
您好,欢迎到访网站!
  查看权限
搜索
文章归档

Powered By Z-BlogPHP 1.5.2 Zero

964379568@qq.com