当前位置:网站首页>Mqtt instruction send receive request subscription
Mqtt instruction send receive request subscription
2022-07-27 07:55:00 【Kamchatka Bear Man】
describe : Recently iot equipment , Meet a need ,app yes c End , Hardware device embedded program is d End , The server is responsible for communication , then c Send the command of distribution network at the end ,d End receives instruction , Enter the distribution network state , Then the remote control sends infrared commands , Hardware sensor receives infrared command , then d Send message to c End ,c The end receives instructions , And respond to .
Have a problem : I app Of c End , Don't get d End the instructions sent to me , I always thought there was something wrong with the framework , Because the web log can see that the hardware sending and receiving instructions are normal , Looking for a long time , Find out app You must first subscribe d End , Then you can receive it d End instruction , Otherwise, I can't receive , It's very embarrassing , Then I subscribed d End instruction , Ask again , succeed .
lesson : Be sure to understand mqtt The mechanism and principle of , Then do logical interaction , Otherwise you will waste a lot of time , I don't know , Turn around in circles .
step1:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.example.demoanalytic"
minSdkVersion 19
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
ndk {
abiFilters 'arm64-v8a'
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-core:16.0.9'
implementation project(':andmqtt')
implementation 'com.blankj:utilcode:1.22.0'
implementation("org.greenrobot:eventbus:3.3.1")
implementation 'com.google.code.gson:gson:2.8.0'
}
apply plugin: 'com.google.gms.google-services'
step2: D:\project\push\Infrared\mqtt\one_fice\v7\kotlin\DemoAnalytic\app\src\main\AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.demoanalytic">
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!--ZXING END-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<!--esp touch-->
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<!-- Intercom permission -->
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<!-- Detect network status permissions -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme">
<service android:name="com.example.demoanalytic.MQTTService" />
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
step3:
package com.example.demoanalytic
const val MQTT_SERVICE = "tcp://1.48.180"
const val MQTT_PORT = 180803
const val PLUG_TOPIC_REC = "/%s/%s/C1/"
const val SET_SWITCH = "WY+SWITCH=%s"
const val SET_IR_SMART = "WY+IR=match_start"
const val SET_IR_SMART_END = "WY+IR=match_end"
const val PLUG_TOPIC = "/%s/%s/D1/"
step4:
package com.example.demoanalytic
import android.content.Intent
import android.os.Build
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.blankj.utilcode.util.ServiceUtils
import kotlinx.android.synthetic.main.activity_main.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class MainActivity : AppCompatActivity() {
private val productId = "zcz004"
private val equipmentId = "zcz004100629"
// https://github.com/Rairmmd/AndMqtt.git Refer to the website , need lib Download by yourself
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
EventBus.getDefault().register(this)
EventBus.getDefault().postSticky(MqttMsg(true))
if (ServiceUtils.isServiceRunning(MQTTService::class.java.name)) {
ServiceUtils.stopService(MQTTService::class.java.name)
}
val intent = Intent(this@MainActivity, MQTTService::class.java)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
this@MainActivity.startForegroundService(intent)
} else {
startService(intent)
}
btn_pub_d.setOnClickListener {
EventBus.getDefault().post(
MqttBean(
String.format(
PLUG_TOPIC,
productId,
equipmentId
), true
)
)
}
btn_open.setOnClickListener {
EventBus.getDefault().post(
MqttBean(
String.format(PLUG_TOPIC_REC, productId, equipmentId),
String.format(SET_SWITCH, "1")
)
)
}
btn_close.setOnClickListener {
EventBus.getDefault().post(
MqttBean(
String.format(PLUG_TOPIC_REC, productId, equipmentId),
String.format(SET_SWITCH, "0")
)
)
}
btn_smart_sure.setOnClickListener {
/* * The connection must be normal Did I not subscribe d End data So I can't receive it So here comes the question How should I subscribe * */
EventBus.getDefault().post(
MqttBean(
String.format(
PLUG_TOPIC_REC,
productId,
equipmentId
), SET_IR_SMART
)
)
}
btn_smart_cancel.setOnClickListener {
EventBus.getDefault().post(
MqttBean(
String.format(
PLUG_TOPIC_REC,
productId,
equipmentId
), SET_IR_SMART_END
)
)
EventBus.getDefault().post(StopService(true))
EventBus.getDefault().post(
MqttBean(
String.format(
PLUG_TOPIC,
productId,
equipmentId
), "", true
)
)
}
}
override fun onDestroy() {
try {
Log.e("TAG", "onDestroy: " + ServiceUtils.stopService(MQTTService::class.java.name))
Log.e(
"TAG",
"onDestroy: " + ServiceUtils.stopService("org.eclipse.paho.android.service.MqttService")
)
} catch (e: java.lang.Exception) {
e.toString()
}
super.onDestroy()
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun showMsgDialog(showMsg: ShowMsg) {
}
}
step5:
package com.example.demoanalytic;
import java.io.Serializable;
public class MqttBean implements Serializable {
public String topic;
public String message;
public boolean register;
public boolean isUnregister;
public MqttBean(String topic, String message, boolean isUnregister) {
this.topic = topic;
this.message = message;
this.isUnregister = isUnregister;
}
public MqttBean(String topic, String message) {
this.topic = topic;
this.message = message;
}
public MqttBean(String topic, boolean register) {
this.topic = topic;
this.register = register;
}
}
step6:
package com.example.demoanalytic;
import java.io.Serializable;
public class MqttMsg implements Serializable {
public String topic;
public String message;
public float Pm25_Data;//0-500
public float Temperature;//0-80
public float CO2_Data;//0-2000
public float TVOC_Data;//0-2
public float HCHO_Data;//0-1
public float Humidity;//0-100
public int ModeState;//0 Turn off 1 Monitoring lamp 2 Aerobic light
public int light;//1--6
public int ScreenStatus;//0 Close the screen 1 The tail
private int Pm25Level;
private int TemperatureLevel;
private int CO2Level;
private int TVOCLevel;
private int HCHOLevel;
private int HumidityLevel;
private int AllLevel;
private String Pm25LevelText;
private String TemperatureLevelText;
private String CO2LevelText;
private String TVOCLevelText;
private String HCHOLevelText;
private String HumidityLevelText;
private String AllLevelText;
private boolean isClosed;
private String clock1;
private String clock2;
private String clock3;
private boolean clock1On;
private boolean clock2On;
private boolean clock3On;
public String plug;
private static final String TAG = "MqttMsg";
public String getClock1() {
return clock1;
}
public void setClock1(String clock1) {
this.clock1 = clock1;
}
public String getClock2() {
return clock2;
}
public void setClock2(String clock2) {
this.clock2 = clock2;
}
public String getClock3() {
return clock3;
}
public void setClock3(String clock3) {
this.clock3 = clock3;
}
public boolean isClock1On() {
return clock1On;
}
public void setClock1On(boolean clock1On) {
this.clock1On = clock1On;
}
public boolean isClock2On() {
return clock2On;
}
public void setClock2On(boolean clock2On) {
this.clock2On = clock2On;
}
public boolean isClock3On() {
return clock3On;
}
public void setClock3On(boolean clock3On) {
this.clock3On = clock3On;
}
public MqttMsg(boolean isClosed) {
this.isClosed = isClosed;
}
public boolean isClosed() {
return isClosed;
}
public void setClosed(boolean closed) {
isClosed = closed;
}
public String equipmentId;
public String productId;
public MqttMsg(String topic, String message, String equipmentId) {
this.topic = topic;
this.message = message;
this.equipmentId = equipmentId;
}
public String getEquipmentId() {
return equipmentId;
}
public void setEquipmentId(String equipmentId) {
this.equipmentId = equipmentId;
}
public String getTopic() {
return topic;
}
public String getMessage() {
return message;
}
public float getPm25_Data() {
return Pm25_Data;
}
public float getTemperature() {
return Temperature;
}
public float getCO2_Data() {
return CO2_Data;
}
public float getTVOC_Data() {
return TVOC_Data;
}
public float getHCHO_Data() {
return HCHO_Data;
}
public float getHumidity() {
return Humidity;
}
public int getPm25Level() {
if (Pm25_Data <= 35) {
Pm25Level = 1;
} else if (Pm25_Data <= 75) {
Pm25Level = 2;
} else if (Pm25_Data <= 115) {
Pm25Level = 3;
} else if (Pm25_Data <= 150) {
Pm25Level = 4;
} else if (Pm25_Data > 150) {
Pm25Level = 5;
}
return Pm25Level;
}
public int getCO2Level() {
if (CO2_Data <= 350 && CO2_Data >= 250) {
CO2Level = 1;
} else if (CO2_Data > 350 && CO2_Data <= 1000) {
CO2Level = 2;
} else if (CO2_Data > 1000) {
CO2Level = 3;
} else if (CO2_Data > 1500) {
CO2Level = 4;
} else if (CO2_Data > 2000) {
CO2Level = 5;
}
return CO2Level;
}
public int getTVOCLevel() {
if (TVOC_Data <= 0.3) {
TVOCLevel = 1;
} else if (TVOC_Data > 0.3 && TVOC_Data <= 0.6) {
TVOCLevel = 2;
} else if (TVOC_Data > 0.6 && TVOC_Data <= 1) {
TVOCLevel = 3;
} else if (TVOC_Data > 1 && TVOC_Data <= 1.6) {
TVOCLevel = 4;
} else if (TVOC_Data > 1.6) {
TVOCLevel = 5;
}
return TVOCLevel;
}
public int getHCHOLevel() {
if (HCHO_Data <= 0.05) {
HCHOLevel = 1;
} else if (HCHO_Data > 0.05 && HCHO_Data <= 0.1) {
HCHOLevel = 2;
} else if (HCHO_Data > 0.1 && HCHO_Data <= 0.2) {
HCHOLevel = 3;
} else if (HCHO_Data > 0.2 && HCHO_Data <= 0.3) {
HCHOLevel = 4;
} else if (HCHO_Data > 0.3) {
HCHOLevel = 5;
}
return HCHOLevel;
}
public int getAllLevel() {
int[] level = new int[4];
level[0] = getPm25Level();
level[1] = getCO2Level();
level[2] = getTVOCLevel();
level[3] = getHCHOLevel();
int max = level[0];// Assign the first element of the array to max
int min = level[0];// Assign the first element of the array to min
for (int i = 1; i < level.length; i++) {
// Assign values from the second element of the array , Compare in turn
if (level[i] > max) {
// If arr[i] Greater than the maximum , will arr[i] Assign the maximum value
max = level[i];
}
if (level[i] < min) {
// If arr[i] Less than the minimum , will arr[i] Assign to the minimum
min = level[i];
}
}
return max;
}
public String getPm25LevelText() {
TemperatureLevelText = " Unknown ";
if (isClosed) return "...";
if (Pm25_Data <= 35) {
Pm25LevelText = " optimal ";
} else if (Pm25_Data <= 75) {
Pm25LevelText = " good ";
} else if (Pm25_Data <= 115) {
Pm25LevelText = " light ";
} else if (Pm25_Data <= 150) {
Pm25LevelText = " Moderate ";
} else if (Pm25_Data > 150) {
Pm25LevelText = " Moderate ";
}
return Pm25LevelText;
}
public String getTemperatureLevelText() {
if (isClosed) return "...";
TemperatureLevelText = " Unknown ";
if (Temperature >= 12 && Temperature <= 24) {
TemperatureLevelText = " comfortable ";
} else if (Temperature >= -10 && Temperature < 12) {
TemperatureLevelText = " It's cold ";
} else if (Temperature < -12) {
TemperatureLevelText = " severe cold ";
} else if (Temperature <= 38 && Temperature > 24) {
TemperatureLevelText = " Partial heat ";
} else if (Temperature > 38) {
TemperatureLevelText = " Scorching hot ";
}
return TemperatureLevelText;
}
public String getCO2LevelText() {
if (isClosed) return "...";
CO2LevelText = " Unknown ";
if (CO2_Data <= 350) {
CO2LevelText = " Pure and fresh ";
} else if (CO2_Data > 350 && CO2_Data <= 1000) {
CO2LevelText = " good ";
} else if (CO2_Data > 1000) {
CO2LevelText = " Relatively turbid ";
} else if (CO2_Data > 1500) {
CO2LevelText = " Muddy ";
} else if (CO2_Data > 2000) {
CO2LevelText = " serious ";
}
return CO2LevelText;
}
public String getTVOCLevelText() {
if (isClosed) return "...";
TVOCLevelText = " Unknown ";
if (TVOC_Data <= 0.3) {
TVOCLevelText = " good ";
} else if (TVOC_Data > 0.3 && TVOC_Data <= 0.6) {
TVOCLevelText = " good ";
} else if (TVOC_Data > 0.6 && TVOC_Data <= 1) {
TVOCLevelText = " light ";
} else if (TVOC_Data > 1 && TVOC_Data <= 1.6) {
TVOCLevelText = " Moderate ";
} else if (TVOC_Data > 1.6) {
TVOCLevelText = " severe ";
}
return TVOCLevelText;
}
public String getHCHOLevelText() {
if (isClosed) return "...";
HCHOLevelText = " Unknown ";
if (HCHO_Data <= 0.05) {
HCHOLevelText = " optimal ";
} else if (HCHO_Data > 0.05 && HCHO_Data <= 0.1) {
HCHOLevelText = " good ";
} else if (HCHO_Data > 0.1 && HCHO_Data <= 0.2) {
HCHOLevelText = " light ";
} else if (HCHO_Data > 0.2 && HCHO_Data <= 0.3) {
HCHOLevelText = " Moderate ";
} else if (HCHO_Data > 0.3) {
HCHOLevelText = " severe ";
}
return HCHOLevelText;
}
public String getAllLevelText() {
if (isClosed) return "...";
AllLevelText = " Unknown ";
int[] level = new int[4];
level[0] = getPm25Level();
level[1] = getCO2Level();
level[2] = getTVOCLevel();
level[3] = getHCHOLevel();
int max = level[0];// Assign the first element of the array to max
for (int i = 1; i < level.length; i++) {
// Assign values from the second element of the array , Compare in turn
if (level[i] > max) {
// If arr[i] Greater than the maximum , will arr[i] Assign the maximum value
max = level[i];
}
}
if (max == 1) {
AllLevelText = " optimal ";
} else if (max == 2) {
AllLevelText = " good ";
} else if (max == 3) {
AllLevelText = " in ";
} else if (max == 4) {
AllLevelText = " Poor ";
} else if (max == 5) {
AllLevelText = " Bad ";
}
return AllLevelText;
}
public String getHumidityLevelText() {
if (isClosed) return "...";
if (Humidity <= 30) {
HumidityLevelText = " Partial dryness ";
} else if (Humidity > 30 && Humidity <= 60) {
HumidityLevelText = " comfortable ";
} else if (Humidity > 60) {
HumidityLevelText = " Partial humidity ";
}
return HumidityLevelText;
}
@Override
public String toString() {
return "MqttMsg{" +
"topic='" + topic + '\'' +
", message='" + message + '\'' +
", Pm25_Data=" + Pm25_Data +
", Temperature=" + Temperature +
", CO2_Data=" + CO2_Data +
", TVOC_Data=" + TVOC_Data +
", HCHO_Data=" + HCHO_Data +
", Humidity=" + Humidity +
", ModeState=" + ModeState +
", light=" + light +
", ScreenStatus=" + ScreenStatus +
", Pm25Level=" + Pm25Level +
", TemperatureLevel=" + TemperatureLevel +
", CO2Level=" + CO2Level +
", TVOCLevel=" + TVOCLevel +
", HCHOLevel=" + HCHOLevel +
", HumidityLevel=" + HumidityLevel +
", AllLevel=" + AllLevel +
", Pm25LevelText='" + Pm25LevelText + '\'' +
", TemperatureLevelText='" + TemperatureLevelText + '\'' +
", CO2LevelText='" + CO2LevelText + '\'' +
", TVOCLevelText='" + TVOCLevelText + '\'' +
", HCHOLevelText='" + HCHOLevelText + '\'' +
", HumidityLevelText='" + HumidityLevelText + '\'' +
", AllLevelText='" + AllLevelText + '\'' +
", isClosed=" + isClosed +
", clock1='" + clock1 + '\'' +
", clock2='" + clock2 + '\'' +
", clock3='" + clock3 + '\'' +
", clock1On=" + clock1On +
", clock2On=" + clock2On +
", clock3On=" + clock3On +
", plug='" + plug + '\'' +
", equipmentId='" + equipmentId + '\'' +
'}';
}
@Override
public int hashCode() {
return equipmentId.length();
}
@Override
public boolean equals(Object obj) {
return this.equipmentId.equals(((MqttMsg) obj).equipmentId);
}
}
step7:
package com.example.demoanalytic
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.support.v4.app.NotificationCompat
import android.text.TextUtils
import android.util.Log
import com.blankj.utilcode.util.ServiceUtils
import com.blankj.utilcode.util.TimeUtils
import com.rairmmd.andmqtt.*
import org.eclipse.paho.android.service.MqttTraceHandler
import org.eclipse.paho.client.mqttv3.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
class MQTTService : Service() {
private var mqttMsg: MqttMsg? = null
private var isStop = false
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val notificationManager =
getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(
NotificationChannel(
"faceId",
"mqtt",
NotificationManager.IMPORTANCE_DEFAULT
)
)
val builder = NotificationCompat.Builder(this, "faceId")
startForeground(1, builder.build())
}
EventBus.getDefault().register(this)
if (UserZone.isLogin(this)) {
Log.e("MQTTService", "onCreate Start connecting ")
initMqtt2()
}
}
private fun initMqtt2() {
AndMqtt.getInstance().init(applicationContext)
AndMqtt.getInstance().connect(
MqttConnect().setClientId(UserZone.getClientId(this))
.setPort(MQTT_PORT).setAutoReconnect(true)
.setCleanSession(true).setServer(MQTT_SERVICE)
.setTraceCallback(object : MqttTraceHandler {
override fun traceDebug(tag: String, message: String) {
Log.e("MQTTService", " Debugging information :$tag,$message")
}
override fun traceError(tag: String, message: String) {
Log.e("MQTTService", " error message :$tag,$message")
}
override fun traceException(
tag: String,
message: String,
e: java.lang.Exception
) {
Log.e("MQTTService", " Abnormal information :$tag,$message,$e")
}
}).setMessageListener(object : MqttCallbackExtended {
override fun connectComplete(
reconnect: Boolean,
serverURI: String
) {
//reconnect If it is true , Then the connection is the result of automatic reconnection
Log.e("MQTTService", " Connection complete :$reconnect,$serverURI")
}
override fun connectionLost(cause: Throwable) {
Log.e("MQTTService", " Lost connection :$cause")
}
@Throws(java.lang.Exception::class)
override fun messageArrived(
topic: String,
message: MqttMessage
) {
Log.e("MQTTService", " Receive the data of the server :$topic,$message")
}
override fun deliveryComplete(token: IMqttDeliveryToken) {
Log.e("MQTTService", " When the delivery of the message is completed :$token")
}
}), object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.e("Rair", "(MainActivity.java:51)-onSuccess:-> Successful connection ")
}
override fun onFailure(
asyncActionToken: IMqttToken,
exception: Throwable
) {
Log.e("Rair", "(MainActivity.java:56)-onFailure:-> The connection fails ")
}
})
}
private fun writeLog(log: String) {
// FileUtils.writeFileFromString("/sdcard/mindor.txt", log, true)
}
private fun publish(msg: String, topic: String) {
if (!AndMqtt.getInstance().isConnect) {
// Toaster.show(" Abnormal connection of equipment , Please restart the app or try again later ")
Log.e("MQTTService", "publish Start connecting ")
initMqtt2()
return
}
// Release
AndMqtt.getInstance().publish(MqttPublish()
.setMsg(msg)
.setQos(0)
.setTopic(topic), object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.e("publish onSuccess", topic + " Successful release " + msg + asyncActionToken.isComplete)
val log = TimeUtils.getNowString() + " Send successfully --> Infrared theme ${topic}--- news ${msg}\n\n"
writeLog(log)
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
Log.e("publish onSuccess", " Failed to publish onFailure")
}
})
}
private fun subscribe(topic: String) {
if (!AndMqtt.getInstance().isConnect) {
//Toaster.show(" Abnormal connection of equipment , Please restart the app or try again later ")
Log.e("MQTTService", "subscribe Start connecting ")
initMqtt2()
return
}
// subscribe
AndMqtt.getInstance().subscribe(MqttSubscribe()
.setTopic(topic)
.setQos(0), object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.e("MQTTService", "(MainActivity.java:63)-onSuccess:-> Subscription succeeded ")
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
Log.e("MQTTService", "(MainActivity.java:68)-onFailure:-> Subscription failed ")
}
})
}
@Subscribe(threadMode = ThreadMode.MAIN)
fun publishMsg(mqtt: MqttBean) {
Log.e("MQTTService", " Send instructions publishMsg:${mqtt.topic}")
if (mqtt.register) {
subscribe(mqtt.topic)
return
}
if (mqtt.isUnregister) {
unSubscribe(mqtt.topic)
return
}
publish(mqtt.message, mqtt.topic)
}
private fun unSubscribe(topic: String?) {
try {
if (!AndMqtt.getInstance().isConnect) {
return
}
if (TextUtils.isEmpty(topic)) return
AndMqtt.getInstance().unSubscribe(MqttUnSubscribe()
.setTopic(topic), object : IMqttActionListener {
override fun onSuccess(asyncActionToken: IMqttToken) {
Log.e("MQTTService", topic + "(MainActivity.java:93)-onSuccess:-> Unsubscribe succeeded ")
}
override fun onFailure(asyncActionToken: IMqttToken, exception: Throwable) {
Log.e("MQTTService", topic + "(MainActivity.java:98)-onFailure:-> Unsubscribe failed ")
}
})
} catch (e: Exception) {
}
}
override fun onDestroy() {
super.onDestroy()
EventBus.getDefault().unregister(this)
}
@Subscribe()
fun stopService(stopService: StopService) {
this.isStop = stopService.isStop
}
@Subscribe
fun loginSuccess(userInfo: UserInfo) {
Log.e("MQTTService", "loginSuccess Start connecting ")
initMqtt2()
}
}
step8:
package com.example.demoanalytic;
import java.io.Serializable;
public class ShowMsg implements Serializable {
}
step9:
package com.example.demoanalytic;
import java.io.Serializable;
public class StopService implements Serializable {
public boolean isStop;
public StopService(boolean isStop) {
this.isStop = isStop;
}
}
step10:
package com.example.demoanalytic;
import java.io.Serializable;
public class UserInfo implements Serializable {
/** * birthday : 2018-2-5 * phone : 110 * sex : 0 * address : Beijing * nickName : 12 * userId : minApp100001 * headPortrait : null */
private String birthday;
private String phone;
private String sex;
private String address;
private String nickName;
private String userId;
private String headPortrait;
private String ClientId;
public String getClientId() {
return ClientId;
}
public void setClientId(String clientId) {
ClientId = clientId;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getHeadPortrait() {
return headPortrait;
}
public void setHeadPortrait(String headPortrait) {
this.headPortrait = headPortrait;
}
}
step11:
package com.example.demoanalytic
import android.content.Context
import android.text.TextUtils
import com.google.gson.Gson
object UserZone {
/** * Are you logged in * */
fun isLogin(context: Context): Boolean {
return true
}
/** * Get the current login user id * */
fun getClientId(context: Context): String {
/*return if (TextUtils.isEmpty(clientId)) { userId } else { clientId!! }*/
return "minApp125106"
}
}
end
边栏推荐
- C language: random number + Hill sort
- C语言:随机生成数+插入排序
- Can Linux install sqlserver
- 3D laser slam: Interpretation of logo-loam paper --- Abstract
- What other methods are available for MySQL index analysis besides explain
- Usage scenarios for automated testing
- 3D激光SLAM:LeGO-LOAM论文解读---摘要
- CommonTitleBar hide left right
- Redison 3.17.5 release, officially recommended redis client
- ADC噪声全面分析 -02- ADC 噪声测量方法和相关参数
猜你喜欢

OpenGL shader learning notes: varying variables

Apifox安装及使用
![[resolved] SSO forwarding succeeded, and there was an unexpected error (type=internal server error, status=500) caused by parameters in the forwarding URL](/img/05/41f48160fa7895bc9e4f314ec570c5.png)
[resolved] SSO forwarding succeeded, and there was an unexpected error (type=internal server error, status=500) caused by parameters in the forwarding URL

SQL labs SQL injection platform - level 1 less-1 get - error based - Single Quotes - string (get single quote character injection based on errors)

【万字长文】吃透负载均衡,和阿里大牛的技术面谈

DEMO:PA30 银行国家码默认CN 增强

SETTA 2020 国际学术会议即将召开,欢迎大家参加!

Zero training platform course-1. SQL injection Foundation

这次龙蜥展区玩的新花样,看看是谁的 DNA 动了?

What is the real HTAP? (2) Challenge article
随机推荐
yhb_ sysbench
[golang learning notes 2.0] arrays and slices in golang
想让照片中的云飘起来?视频编辑服务一键动效3步就能实现
The first open source MySQL native HTAP database in China will be released soon! Look at the three highlights first, limited to the surrounding areas, waiting for you~
帮个忙呗~不关注不登录,不到一分钟的一个问卷
国内首款开源MySQL原生HTAP数据库即将发布!三大亮点抢先看,限量周边等你来~
MCU multi-level menu
HU相关配置
An open source OA office automation system
什么是真正的HTAP?(一)背景篇
API 版本控制【 Eolink 翻译】
北京五日游记
小程序支付管理-新版支付对接流程
Chromedriver download - self use
Stored procedures and functions
JS存取cookie示例
[stonedb class] introductory lesson 1: popular science of database knowledge
一体化实时HTAP数据库StoneDB,如何替换MySQL并实现近百倍分析性能的提升
Comprehensive cases
浅谈数据安全