org.eclipse.paho.android.service.MqttAndroidClient Java Examples

The following examples show how to use org.eclipse.paho.android.service.MqttAndroidClient. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 6 votes vote down vote up
public MqttAndroidClient createClient(String id, String serverURI, String clientId) {
    MqttClientPersistence mqttClientPersistence = new MemoryPersistence();
    MqttAndroidClient client = new MqttAndroidClient(MyApplication.getContext(), serverURI, clientId, mqttClientPersistence);
    client.setCallback(new MqttCallback() {
        @Override
        public void connectionLost(Throwable cause) {
            LogUtil.e("connectionLost");
            EventBus.getDefault().post(new MQTTActionEvent(Constant.MQTTStatusConstant.CONNECTION_LOST, null, cause));

        }

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            LogUtil.d("topic is " + topic + ",message is " + message.toString() + ", qos is " + message.getQos());
            EventBus.getDefault().postSticky(new MessageEvent(new EmqMessage(topic, message)));

        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken token) {
            LogUtil.d("deliveryComplete");


        }
    });

    mClients.put(id, client);

    return client;

}
 
Example #2
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 6 votes vote down vote up
public boolean disconnect(MqttAndroidClient client) {
    if (!isConnected(client)) {
        return true;
    }

    try {
        client.disconnect();
        return true;
    } catch (MqttException e) {
        e.printStackTrace();
        return false;
    }
}
 
Example #3
Source File: Connection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a connection from persisted information in the database store, attempting
 * to create a {@link MqttAndroidClient} and the client handle.
 * @param clientId The id of the client
 * @param host the server which the client is connecting to
 * @param port the port on the server which the client will attempt to connect to
 * @param context the application context
 * @param tlsConnection true if the connection is secured by SSL
 * @return a new instance of <code>Connection</code>
 */
public static Connection createConnection(String clientHandle, String clientId, String host, int port, Context context, boolean tlsConnection){

    String uri;
    if(tlsConnection) {
        uri = "ssl://" + host + ":" + port;
    } else {
        uri = "tcp://" + host + ":" + port;
    }

    executor = Executors.newFixedThreadPool(1);

    MqttAndroidClient client = new MqttAndroidClient(context, uri, clientId);
    return new Connection(clientHandle, clientId, host, port, context, client, tlsConnection);
}
 
Example #4
Source File: Connection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
public void updateConnection(String clientId, String host, int port, boolean tlsConnection){
    String uri;
    if(tlsConnection) {
        uri = "ssl://" + host + ":" + port;
    } else {
        uri = "tcp://" + host + ":" + port;
    }

    this.clientId = clientId;
    this.host = host;
    this.port = port;
    this.tlsConnection = tlsConnection;
    this.client = new MqttAndroidClient(context, uri, clientId);
}
 
Example #5
Source File: Connection.java    From Sparkplug with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a connection object with the server information and the client
 * hand which is the reference used to pass the client around activities
 * @param clientHandle The handle to this <code>Connection</code> object
 * @param clientId The Id of the client
 * @param host The server which the client is connecting to
 * @param port The port on the server which the client will attempt to connect to
 * @param context The application context
 * @param client The MqttAndroidClient which communicates with the service for this connection
 * @param tlsConnection true if the connection is secured by SSL
 */
private Connection(String clientHandle, String clientId, String host,
                   int port, Context context, MqttAndroidClient client, boolean tlsConnection) {
    //generate the client handle from its hash code
    this.clientHandle = clientHandle;
    this.clientId = clientId;
    this.host = host;
    this.port = port;
    this.context = context;
    this.client = client;
    this.tlsConnection = tlsConnection;
    history = new ArrayList<String>();
    String sb = "Client: " +
            clientId +
            " created";
    addAction(sb);

    try {
        sparkplugMetrics.put("Analog 1", new MetricBuilder("Analog 1", MetricDataType.Double, 0D).createMetric());
        sparkplugMetrics.put("Analog 2", new MetricBuilder("Analog 2", MetricDataType.Double, 0D).createMetric());
        sparkplugMetrics.put("Analog 3", new MetricBuilder("Analog 3", MetricDataType.Double, 0D).createMetric());
        sparkplugMetrics.put("Analog 4", new MetricBuilder("Analog 4", MetricDataType.Double, 0D).createMetric());
        sparkplugMetrics.put("Boolean 1", new MetricBuilder("Boolean 1", MetricDataType.Boolean, false).createMetric());
        sparkplugMetrics.put("Boolean 2", new MetricBuilder("Boolean 2", MetricDataType.Boolean, false).createMetric());
        sparkplugMetrics.put("Boolean 3", new MetricBuilder("Boolean 3", MetricDataType.Boolean, false).createMetric());
        sparkplugMetrics.put("Boolean 4", new MetricBuilder("Boolean 4", MetricDataType.Boolean, false).createMetric());

        sparkplugMetrics.put("Scan Code", new MetricBuilder("Scan Code", MetricDataType.String, "").createMetric());
    } catch (Exception e) {
        Log.e(TAG, "Failed to set up metrics", e);
    }

    getGpsLocation();
}
 
Example #6
Source File: MainActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 5 votes vote down vote up
private void startConnect(String clientID, String serverIP, String port) {
    //服务器地址
    String  uri ="tcp://";
    uri=uri+serverIP+":"+port;
    Log.d("MainActivity",uri+"  "+clientID);
    /**
     * 连接的选项
     */
    MqttConnectOptions conOpt = new MqttConnectOptions();
    /**设计连接超时时间*/
    conOpt.setConnectionTimeout(3000);
    /**设计心跳间隔时间300秒*/
    conOpt.setKeepAliveInterval(300);
    /**
     * 创建连接对象
     */
     client = new MqttAndroidClient(this,uri, clientID);
    /**
     * 连接后设计一个回调
     */
    client.setCallback(new MqttCallbackHandler(this, clientID));
    /**
     * 开始连接服务器,参数:ConnectionOptions,  IMqttActionListener
     */
    try {
        client.connect(conOpt, null, new ConnectCallBackHandler(this));
    } catch (MqttException e) {
        e.printStackTrace();
    }

}
 
Example #7
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 4 votes vote down vote up
private void disconnectAllClient() {
    for (MqttAndroidClient client : mClients.values()) {
        disconnect(client);
    }
}
 
Example #8
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 4 votes vote down vote up
public boolean isConnected(MqttAndroidClient client) {
    return client != null && client.isConnected();
}
 
Example #9
Source File: MQTTManager.java    From EMQ-Android-Toolkit with Apache License 2.0 4 votes vote down vote up
public MqttAndroidClient getClient(String id) {
    return mClients.get(id);
}
 
Example #10
Source File: TrafficService.java    From AirMapSDK-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Initialize an TrafficService to receive traffic alerts and situational awareness
 *
 * @param context An Android Context
 */
public TrafficService(Context context) {
    String clientId = UUID.randomUUID().toString();
    client = new MqttAndroidClient(context, mqttBaseUrl, clientId);
    client.setCallback(new MqttEventCallback());
    options = new MqttConnectOptions();
    options.setCleanSession(true);
    options.setKeepAliveInterval(15);
    options.setPassword(AirMap.getInstance().getAuthToken().toCharArray());
    connectionState = ConnectionState.Disconnected;
    allTraffic = new CopyOnWriteArrayList<>(); //Thread safe list
    listeners = new ArrayList<>();
    checkForUpdatedFlight = false;
    currentFlightCallback = new CurrentFlightAirMapCallback();
    actionListener = new MqttActionCallback();
    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            clearOldTraffic();
            updateTrafficProjections();
        }
    }, 0, 1000); //Clear old traffic every second

    new Timer().scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            if (checkForUpdatedFlight) {
                AirMap.getCurrentFlight(new AirMapCallback<AirMapFlight>() {
                    @Override
                    public void onSuccess(AirMapFlight response) {
                        if (response != null && !response.getFlightId().equals(flightId)) {
                            connect();
                        }
                    }

                    @Override
                    public void onError(AirMapException e) {
                        e.printStackTrace();
                    }
                });
            }
        }
    }, 0, 1000 * 60); //Update current flight every minute

    handler = new Handler(Looper.getMainLooper());
}
 
Example #11
Source File: MainActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 4 votes vote down vote up
/**
 * 获取MqttAndroidClient实例
 * @return
 */
public static MqttAndroidClient getMqttAndroidClientInstace(){
    if(client!=null)
        return  client;
    return null;
}
 
Example #12
Source File: PublishActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_publish);
    ButterKnife.bind(this);
    setTitle("模拟服务器发布主题");
    initDate();

    /**1.开始发布*/
    btnStartPub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            /**获取发布的主题*/
            pubTopic = edPubTopic.getText().toString().trim();
            /**获取发布的消息*/
            pubMessage = edPubMessage.getText().toString().trim();
            /**消息的服务质量*/
            int qos=0;
            /**消息是否保持*/
            boolean retain=false;
            /**要发布的消息内容*/
            byte[] message=pubMessage.getBytes();
            if(pubTopic!=null&&!"".equals(pubTopic)){
                /**获取client对象*/
                MqttAndroidClient client = MainActivity.getMqttAndroidClientInstace();
                if(client!=null){
                    try {
                        /**发布一个主题:如果主题名一样不会新建一个主题,会复用*/
                        client.publish(pubTopic,message,qos,retain,null,new PublishCallBackHandler(PublishActivity.this));
                    } catch (MqttException e) {
                        e.printStackTrace();
                    }
                }else{
                    Log.e(PA,"MqttAndroidClient==null");
                }
            }else{
                Toast.makeText(PublishActivity.this,"发布的主题不能为空",Toast.LENGTH_SHORT).show();
            }
        }
    });
}
 
Example #13
Source File: SubscriberActivity.java    From ActiveMQ-MQTT-Android with Apache License 2.0 4 votes vote down vote up
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_subscriber);
    ButterKnife.bind(this);
    setTitle("订阅");
    
    initDate();

    btnStartSub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            /**获取订阅的主题*/
            topic = edTopic.getText().toString().trim();
            if(topic==null||"".equals(topic)) {
                Toast.makeText(SubscriberActivity.this,"请输入订阅的主题",Toast.LENGTH_SHORT).show();
                return;
            }
            String[] split = topic.split(",");
            /**一共有多少个主题*/
            int length = split.length;
            String [] topics=new String[length];/**订阅的主题*/
            int [] qos =new int [length];/**服务器的质量*/
            for(int i=0;i<length;i++){
                topics[i]=split[i];
                qos[i]=0;
            }
            /**获取client对象*/
            MqttAndroidClient client = MainActivity.getMqttAndroidClientInstace();
            if(client!=null){
                try {
                    if(length>1) {
                        /**订阅多个主题,服务的质量默认为0*/
                        Log.d(SA,"topics="+ Arrays.toString(topics));
                        client.subscribe(topics, qos, null, new SubcribeCallBackHandler(SubscriberActivity.this));
                    }else{
                        Log.d(SA,"topic="+topic);
                        /**订阅一个主题,服务的质量默认为0*/
                      client.subscribe(topic,0,null,new SubcribeCallBackHandler(SubscriberActivity.this));
                    }
                } catch (MqttException e) {
                    e.printStackTrace();
                }
            }else{
                Log.e(SA,"MqttAndroidClient==null");
            }

        }
    });

}
 
Example #14
Source File: Connection.java    From Sparkplug with Eclipse Public License 1.0 2 votes vote down vote up
/**
 * Gets the client which communicates with the org.eclipse.paho.android.service service.
 * @return the client which communicates with the org.eclipse.paho.android.service service
 */
public MqttAndroidClient getClient() {
    return client;
}