当前位置:网站首页>mqtt send receive
mqtt send receive
2022-07-26 12:47:00 【51CTO】
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'
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
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>
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
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/"
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
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) {
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
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;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
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);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
- 130.
- 131.
- 132.
- 133.
- 134.
- 135.
- 136.
- 137.
- 138.
- 139.
- 140.
- 141.
- 142.
- 143.
- 144.
- 145.
- 146.
- 147.
- 148.
- 149.
- 150.
- 151.
- 152.
- 153.
- 154.
- 155.
- 156.
- 157.
- 158.
- 159.
- 160.
- 161.
- 162.
- 163.
- 164.
- 165.
- 166.
- 167.
- 168.
- 169.
- 170.
- 171.
- 172.
- 173.
- 174.
- 175.
- 176.
- 177.
- 178.
- 179.
- 180.
- 181.
- 182.
- 183.
- 184.
- 185.
- 186.
- 187.
- 188.
- 189.
- 190.
- 191.
- 192.
- 193.
- 194.
- 195.
- 196.
- 197.
- 198.
- 199.
- 200.
- 201.
- 202.
- 203.
- 204.
- 205.
- 206.
- 207.
- 208.
- 209.
- 210.
- 211.
- 212.
- 213.
- 214.
- 215.
- 216.
- 217.
- 218.
- 219.
- 220.
- 221.
- 222.
- 223.
- 224.
- 225.
- 226.
- 227.
- 228.
- 229.
- 230.
- 231.
- 232.
- 233.
- 234.
- 235.
- 236.
- 237.
- 238.
- 239.
- 240.
- 241.
- 242.
- 243.
- 244.
- 245.
- 246.
- 247.
- 248.
- 249.
- 250.
- 251.
- 252.
- 253.
- 254.
- 255.
- 256.
- 257.
- 258.
- 259.
- 260.
- 261.
- 262.
- 263.
- 264.
- 265.
- 266.
- 267.
- 268.
- 269.
- 270.
- 271.
- 272.
- 273.
- 274.
- 275.
- 276.
- 277.
- 278.
- 279.
- 280.
- 281.
- 282.
- 283.
- 284.
- 285.
- 286.
- 287.
- 288.
- 289.
- 290.
- 291.
- 292.
- 293.
- 294.
- 295.
- 296.
- 297.
- 298.
- 299.
- 300.
- 301.
- 302.
- 303.
- 304.
- 305.
- 306.
- 307.
- 308.
- 309.
- 310.
- 311.
- 312.
- 313.
- 314.
- 315.
- 316.
- 317.
- 318.
- 319.
- 320.
- 321.
- 322.
- 323.
- 324.
- 325.
- 326.
- 327.
- 328.
- 329.
- 330.
- 331.
- 332.
- 333.
- 334.
- 335.
- 336.
- 337.
- 338.
- 339.
- 340.
- 341.
- 342.
- 343.
- 344.
- 345.
- 346.
- 347.
- 348.
- 349.
- 350.
- 351.
- 352.
- 353.
- 354.
- 355.
- 356.
- 357.
- 358.
- 359.
- 360.
- 361.
- 362.
- 363.
- 364.
- 365.
- 366.
- 367.
- 368.
- 369.
- 370.
- 371.
- 372.
- 373.
- 374.
- 375.
- 376.
- 377.
- 378.
- 379.
- 380.
- 381.
- 382.
- 383.
- 384.
- 385.
- 386.
- 387.
- 388.
- 389.
- 390.
- 391.
- 392.
- 393.
- 394.
- 395.
- 396.
- 397.
- 398.
- 399.
- 400.
- 401.
- 402.
- 403.
- 404.
- 405.
- 406.
- 407.
- 408.
- 409.
- 410.
- 411.
- 412.
- 413.
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()
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
- 92.
- 93.
- 94.
- 95.
- 96.
- 97.
- 98.
- 99.
- 100.
- 101.
- 102.
- 103.
- 104.
- 105.
- 106.
- 107.
- 108.
- 109.
- 110.
- 111.
- 112.
- 113.
- 114.
- 115.
- 116.
- 117.
- 118.
- 119.
- 120.
- 121.
- 122.
- 123.
- 124.
- 125.
- 126.
- 127.
- 128.
- 129.
- 130.
- 131.
- 132.
- 133.
- 134.
- 135.
- 136.
- 137.
- 138.
- 139.
- 140.
- 141.
- 142.
- 143.
- 144.
- 145.
- 146.
- 147.
- 148.
- 149.
- 150.
- 151.
- 152.
- 153.
- 154.
- 155.
- 156.
- 157.
- 158.
- 159.
- 160.
- 161.
- 162.
- 163.
- 164.
- 165.
- 166.
- 167.
- 168.
- 169.
- 170.
- 171.
- 172.
- 173.
- 174.
- 175.
- 176.
- 177.
- 178.
- 179.
- 180.
- 181.
- 182.
- 183.
- 184.
- 185.
- 186.
- 187.
- 188.
- 189.
- 190.
- 191.
- 192.
- 193.
- 194.
- 195.
- 196.
- 197.
- 198.
- 199.
- 200.
- 201.
- 202.
- 203.
- 204.
- 205.
- 206.
- 207.
- 208.
- 209.
- 210.
- 211.
- 212.
- 213.
- 214.
- 215.
- 216.
- 217.
- 218.
- 219.
- 220.
- 221.
- 222.
step8:
step9:
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;
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.
- 72.
- 73.
- 74.
- 75.
- 76.
- 77.
- 78.
- 79.
- 80.
- 81.
- 82.
- 83.
- 84.
- 85.
- 86.
- 87.
- 88.
- 89.
- 90.
- 91.
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"
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
end
边栏推荐
- 历史上的今天:IBM 获得了第一项专利;Verizon 收购雅虎;亚马逊发布 Fire Phone...
- How to optimize a large number of if else [email protected] Detailed explanation of valib
- 2022 年要了解的新兴安全供应商
- LCD notes (4) analyze the LCD driver of the kernel
- mqtt send receive
- Kubernetes----PV和PVC的生命周期简介
- Shell变量和引用
- Shell variables and references
- 0基础编程资源大全(先收藏~慢慢看~)
- QT入门引导 及其 案例讲解
猜你喜欢

食品安全 | 这些常见食物小心有毒!速查自家餐桌

Backtracking - question 51 Queen n -- a classic backtracking problem that must be overcome

编程式导航路由跳转到当前路由(参数不变), 多次执行会抛出NavigationDuplicated的警告错误?

华为超融合FusionCube解决方案笔记

A super easy-to-use artifact apifox, throw swagger a few streets... (glory Collection Edition)

食品安全 | 网购的自制食品就是健康食品?莫要陷入这些误区

Vs code set the method of ctrl+s saving and automatic formatting

论文阅读-MLPD:Multi-Label Pedestrian Detector in Multispectral Domain(海康威视研究院实习项目)

食品安全 | 无菌蛋真的完全无菌吗?
![[wechat applet] read the article, data request](/img/9a/3b9aef6c5f5735b886252ec830798c.png)
[wechat applet] read the article, data request
随机推荐
“2022华为开发者大赛中国区东部赛区开幕式”在福州成功举办
Kubernetes----高级存储之PV和PVC简介
JDBC gets connections from the connection pool (Druid connection pool)
Transformer dominates the world? Depth wise conv has something to say
Vs code set the method of ctrl+s saving and automatic formatting
Paper reading MLPD: multi label pedestrian detector in multispectral domain (Internship Program of Hikvision Research Institute)
Notes....
UE5 官方案例Lyra 全特性详解 7.资源管理
今日睡眠质量记录75分
Kuzaobao: summary of Web3 encryption industry news on July 25
数据查询WHERE
Shell variables and references
华为超融合FusionCube解决方案笔记
Optical distance sensing chip 4530a combining ambient light, proximity sensing and infrared ranging
行业案例|指标中台如何助力银行业普惠金融可持续发展
回溯——131. 分割回文串
回溯——491. 递增子序列
新功能 | 智能开放搜索上线定制词权重模型
Commonly used list Why does isempty() suddenly report null?
Backtracking - 131. Split palindrome string