1024programmer Blog Two notes on dealing with the problems encountered by paho.MQTT_paho.mqtt.client_Link2Points Blog

Two notes on dealing with the problems encountered by paho.MQTT_paho.mqtt.client_Link2Points Blog

class=”markdown_views prism-tomorrow-night”>

Article directory


EMQX

Install Broker

docker run -d --name emqx -p 1883:1883 -p 8081:8081 -p 8083:8083 -p 8084:8084 -p 8883:8883 -p 18083:18083 emqx/emqx:4.3.8
 

Modified based on the original project
https://github.com/eclipse/paho.mqtt.python
https://github.com/eclipse/paho.mqtt.android

Written in Python

Download

pip install paho-mqtt
 

If the following problems occur during the process, you need to upgrade pip

Building wheels for collected packages: paho-mqtt
   Building wheel for paho-mqtt (setup.py) ... error
   ERROR: Command errored out with exit status 1:
    command: /root/django/venv_RTCS/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-req-build-yt56ry83/setup.py  '"'"'; __file__='"'"'/tmp/pip-req-build-yt56ry83/setup.py'"'"'; f=getattr(tokenize, '"'"'open'"'"'  , open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close(  );exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-0vih1nvj
        cwd: /tmp/pip-req-build-yt56ry83/
   Complete output (6 lines):
   usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
      or: setup.py --help [cmd1 cmd2 ...]
      or: setup.py --help-commands
      or: setup.py cmd --help
   error: invalid command 'bdist_wheel'
   ERROR: Failed building wheel for paho-mqtt
   Running setup.py clean for paho-mqtt
 Failed to build paho-mqtt
 
  • Upgrade pip
python -m pip install --upgrade pip
 

Code

#!/usr/bin/python
 # coding:utf-8

 import paho.mqtt.client as mqtt
 import json

 HOST = ""
 PORT = 1883
 user = "test"
 pw = "test"
 client_id = "test"

 class Project_Mqtt:
     # Establish connection
     def do_connect(self, HOST, user, pw,  span> client_id):
         self.client = mqtt.Client(client_id)
         self.client.username_pw_set(user, pw)
         self.client.connect(HOST, PORT, 60)
 	
 # Handle subscription messages
     def deal_on_message(self, client, userdata, msg)  span>:
         print(msg.topic + " " + msg.  span>payload.decode("utf-8"  ))
         messages = json.loads(msg.payload)

     # Subscribe
     def do_subscribe(self, topic, qos=0):
         self.client.subscribe(topic, qos=qos)
         self.client.on_message = self.deal_on_message
         self.client.loop_forever()

     # publish
     def do_publish(self, topic, message, qos=0):
         self.client.publish(topic, message, qos=qos  , retain=False)

     # stop
     def do_stop(self):
         self.client.loop_stop()
 

Android configuration writing and problem solving

A temporarily applicable method for higher versions of the SDK.

  • Solve the problem: localbroadcastmanager is not defined (higher version API is no longer supported), refer to Github issue, refer to the third-party package but it is invalid. Therefore, gradle.properties must be configured in the root directory

1. Under the root directory

  • Add
    android.enableJetifier=true to gradle.properties
     

2. Under the app directory

  • build.gradle add
    implementation 'com.android.support:support-v4:30+'
     implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.2.2'
     implementation 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'
     implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
     
  • build.gradle modify SDK31 to SDK30 insert picture description here
  • build.gradle sync

3. Add AndroidManifest.xml

Insert picture description here


     uses-permission   android:name="android.permission.WAKE_LOCK" />  
     uses-permission   android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
     uses-permission   android:name="android.permission.ACCESS_NETWORK_STATE" />  

     <!---->
     uses-permission   android:name="android.permission.READ_EXTERNAL_STORAGE" />  
     <uses-permission android:name="android.permission.INTERNET" /
 

 service android:name="org.eclipse.paho.android.service.MqttService"/>  
 

4. MainActivity.java

serverUri must be [host ip]

package com.example.mqtta;

 import android.widget.Toast;
 import androidx.appcompat.app.AppCompatActivity;AppCompatActivity;  span>
 import android.os.Bundle;
 import org.eclipse.paho.android.service.MqttAndroidClient;
 import org.eclipse.paho.oken string">"subscribe successfully", Toast.LENGTH_SHORT).show();
                 }

                 @Override
                 public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
     
                 }
             });
 //
 // // THIS DOES NOT WORK!
 // mqttAndroidClient.subscribe(subscriptionTopic, 0, new IMqttMessageListener() {
     
 // @Override
 // public void messageArrived(String topic, MqttMessage message) throws Exception {
     
 // // message Arrived!
 // System.out.println("Message: " + topic + " : " + new String(message.getPayload()));
 // }
 // });

         } catch (MqttException ex){
     
             System.err.println("Exception whilst subscribing"  );
             ex.printStackTrace();
         }
     }
 // publish
         public void publishMessage(){
     

             try {
     
                 MqttMessage message = new MqttMessage();
                 message.setPayload(publishMessage.getBytes()  );
                 mqttAndroidClient.publish(publishTopic, message);
                 Toast.makeText(MainActivity.thisthis, "Message Published", Toast.LENGTH_SHORT).show();

                 if(!mqttAndroidClient.isConnected()){
     
                     Toast.makeText(MainActivity.thisthis, "Lost of Connected", Toast.LENGTH_SHORT).show();
                 }
             } catch (MqttException e) {
     
                 System.err.println("Error Publishing: "   + e.getMessage());
                 e.printStackTrace();
             }
         }
 }
 

pan>show();

if(!mqttAndroidClient.isConnected()){

Toast.makeText(MainActivity.thisthis, “Lost of Connected”, Toast.LENGTH_SHORT).show();
}
} catch (MqttException e) {

System.err.println(“Error Publishing: “ + e.getMessage());
e.printStackTrace();
}
}
}

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/two-notes-on-dealing-with-the-problems-encountered-by-paho-mqtt_paho-mqtt-client_link2points-blog/

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索