如何使用MQTT Android发布和订阅adafruit切换?

时间:2019-06-12 05:37:21

标签: java android mqtt adafruit

我从“ https://medium.com/@gaikwadchetan93/android-real-time-communication-using-mqtt-9ea42551475d”获得了一个代码,它与其他MQTT经纪人可以正常工作,但与adafruit不能一起工作。它已正确连接,但在尝试订阅其显示消息“对SalilPEkka ∕ feeds ∕ check的错误订阅失败:不是有效的主题格式”时,在发布其显示消息“对SalilPEkka ∕ feeds ∕ checks错误的发布失败:未授权发布,用户在网站和应用中被暂时阻止”,并在其消息中显示消息“ D / AlarmPingSender:向MqttServicepaho275649469618164取消警报接收器的注册”

  protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            tvshow=(TextView)findViewById(R.id.tvshow);
            String clientId = MqttClient.generateClientId();
            MqttAndroidClient client = new MqttAndroidClient(MainActivity.this, "tcp://io.adafruit.com:1883",clientId);
            connectToMqtt(client);
        }


        void connectToMqtt(final MqttAndroidClient client) {
            try {
                System.out.println("Inside connect");
                MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
                mqttConnectOptions.setAutomaticReconnect(true);
                mqttConnectOptions.setCleanSession(false);
                mqttConnectOptions.setUserName("USERNAME");
                mqttConnectOptions.setPassword("AIO_KEY".toCharArray());
                IMqttToken token = client.connect(mqttConnectOptions);
                token.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        // We are connected
                       // Log.w("On Mqtt connect success");
                        subscribeToMqttChannel(client);
                        System.out.println("connected");
                    }

                    @Override
                    public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                        // Something went wrong e.g. connection timeout or firewall problems
                       // Timber.d("On Mqtt connect failure %s",exception.getMessage());

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

        void subscribeToMqttChannel(MqttAndroidClient client) {
            System.out.println("Inside connect");
            String topic = "SalilPEkka∕feeds∕check";
            int qos = 1;
            try {
                IMqttToken subToken = client.subscribe(topic, qos, iMqttMessageListener);
                  publish(client);

               /* subToken.setActionCallback(new IMqttActionListener() {
                    @Override
                    public void onSuccess(IMqttToken asyncActionToken) {
                        // The message was published
                       // Timber.d("Mqtt channel subscribe success");
                        System.out.println("Inside connect");
                        Toast.makeText(MainActivity.this, asyncActionToken.getMessageId(), Toast.LENGTH_SHORT).show();
                    }
                    @Override
                    public void onFailure(IMqttToken asyncActionToken,
                                          Throwable exception) {
                       // Timber.d("Mqtt channel subscribe error %s",exception.getMessage());
                        // The subscription could not be performed, maybe the user was not
                        // authorized to subscribe on the specified topic e.g. using wildcards
                    }
                });*/

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

        IMqttMessageListener iMqttMessageListener = new IMqttMessageListener() {
            @Override
            public void messageArrived(String topic, MqttMessage message) throws Exception {
                //Timber.d("Message received %s",message);
                //JSONObject signallStatus = new JSONObject(message.toString());
                tvshow.setText(message.toString());

            }
        };

 void publish(MqttAndroidClient client)
    {
        byte[] encodedPayload = new byte[0];
        String payload = "OFF";
       try {
            if (client.isConnected())
                System.out.println("Connected ");
            encodedPayload = payload.getBytes("UTF-8");
            MqttMessage message = new MqttMessage(encodedPayload);
            message.setQos(0);
            message.setRetained(false);
            client.publish("SalilPEkka∕feeds∕check", message);
        } catch (MqttException e) {
            System.out.println(e);
        } catch (UnsupportedEncodingException e) {
            System.out.println(e);
        }
    }
}

0 个答案:

没有答案