New version with service

This commit is contained in:
2022-04-26 00:19:22 +02:00
parent 69b43a1670
commit 50f897c55c
19 changed files with 291 additions and 90 deletions

1
.idea/.name generated
View File

@@ -1 +0,0 @@
My Second App

1
.idea/gradle.xml generated
View File

@@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="GradleMigrationSettings" migrationVersion="1" />
<component name="GradleSettings">
<option name="linkedExternalProjectsSettings">
<GradleProjectSettings>

20
.idea/jarRepositories.xml generated Normal file
View File

@@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
<remote-repository>
<option name="id" value="maven" />
<option name="name" value="maven" />
<option name="url" value="https://repo.eclipse.org/content/repositories/paho-snapshots/" />
</remote-repository>
</component>
</project>

3
.idea/misc.xml generated
View File

@@ -3,8 +3,9 @@
<component name="DesignSurface">
<option name="filePathToZoomLevelMap">
<map>
<entry key="app/src/main/res/drawable-v24/ic_launcher_foreground.xml" value="0.127" />
<entry key="app/src/main/res/layout/activity_display_message.xml" value="0.3527777777777778" />
<entry key="app/src/main/res/layout/activity_main.xml" value="0.375" />
<entry key="app/src/main/res/layout/activity_main.xml" value="0.18981481481481483" />
</map>
</option>
</component>

View File

@@ -21,6 +21,10 @@ android {
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/INDEX.LIST'
exclude 'META-INF/io.netty.versions.properties'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
@@ -35,4 +39,6 @@ dependencies {
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'com.hivemq:hivemq-mqtt-client:1.3.0'
}

View File

@@ -1,4 +1,4 @@
package com.example.mysecondapp;
package ch.luria.mq1;
import android.content.Context;

View File

@@ -1,6 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.mysecondapp">
package="ch.luria.mq1">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
@@ -8,19 +12,16 @@
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MySecondApp">
<activity
android:name=".DisplayMessageActivity"
android:exported="false" />
android:theme="@style/Theme.Mq1">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MqttService" />
</application>
</manifest>

View File

@@ -0,0 +1,89 @@
package ch.luria.mq1;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.ToggleButton;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
ToggleButton stateButton;
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String msg = intent.getStringExtra("STATE");
Log.i(TAG, "Received " + msg);
stateButton.setChecked(!msg.equals("OFF"));
}
};
private static final String TAG = "MainActivity";
private MqttService mService;
boolean mBound = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
stateButton = findViewById(R.id.toggleButton);
Intent intent = new Intent(this, MqttService.class);
startService(intent);
}
@Override
protected void onStart() {
Log.i(TAG, "onStart");
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("ch.luria.mq1");
registerReceiver(broadcastReceiver, intentFilter);
Intent bindIntent = new Intent(this, MqttService.class);
bindService(bindIntent, connection, Context.BIND_AUTO_CREATE);
}
@Override
protected void onStop() {
Log.i(TAG, "onStop");
super.onStop();
unregisterReceiver(broadcastReceiver);
unbindService(connection);
mBound = false;
}
public void toggleButtonState(View view) {
if (stateButton.isChecked()) {
mService.doToggle("{\"state\":\"ON\"}");
} else {
mService.doToggle("{\"state\":\"OFF\"}");
}
}
private final ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
// We've bound to LocalService, cast the IBinder and get LocalService instance
MqttService.LocalBinder binder = (MqttService.LocalBinder) service;
mService = binder.getService();
mBound = true;
mService.getStatus();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
}

View File

@@ -0,0 +1,134 @@
package ch.luria.mq1;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import com.hivemq.client.mqtt.mqtt5.Mqtt5AsyncClient;
import com.hivemq.client.mqtt.mqtt5.Mqtt5Client;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.UUID;
public class MqttService extends Service {
private Mqtt5AsyncClient client;
private static final String TAG = "MQTT Service";
private final IBinder binder = new LocalBinder();
public class LocalBinder extends Binder {
public MqttService getService() {
// Return this instance of MqttService so clients can call public methods
return MqttService.this;
}
}
@Override
public void onCreate() {
Log.i(TAG, "onCreate");
if (client == null) {
Log.i(TAG, "connecting");
client = Mqtt5Client.builder()
.identifier(UUID.randomUUID().toString())
.serverHost("192.168.178.64")
.serverPort(1883)
.buildAsync();
client.connectWith()
.send()
.whenComplete((connAck, throwable) -> {
if (throwable != null) {
// handle failure
Log.i(TAG, "could not connect");
} else {
Log.i(TAG, "connect ok");
subscribe();
}
});
}
}
@Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "onBind");
return binder;
}
public void doToggle(String what) {
publishMessage("zigbee2mqtt/Ampoule Chambre Isaac/set", what);
}
private void sendMessage(String msg) {
Intent intent = new Intent();
intent.setAction("ch.luria.mq1");
try {
final JSONObject obj = new JSONObject(msg);
String state = obj.getString("state");
intent.putExtra("STATE", state);
sendBroadcast(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void subscribe() {
client.subscribeWith()
.topicFilter("zigbee2mqtt/Ampoule Chambre Isaac")
.callback(publish -> {
// Process the received message
String msg = new String(publish.getPayloadAsBytes()) + " from " + publish.getTopic();
Log.i(TAG, "Received " + msg);
sendMessage(msg);
})
.send()
.whenComplete((subAck, throwable) -> {
if (throwable != null) {
// Handle failure to subscribe
Log.i(TAG, "subscribe failed");
} else {
// Handle successful subscription, e.g. logging or incrementing a metric
Log.i(TAG, "subscribe ok");
getStatus();
}
});
}
public void getStatus() {
if (client != null) {
client.publishWith()
.topic("zigbee2mqtt/Ampoule Chambre Isaac/get")
.payload("{\"state\":\"\"}".getBytes())
.send()
.whenComplete((mqtt3Publish, throwable) -> {
if (throwable != null) {
// handle failure to publish
Log.i(TAG, "could not publish");
} else {
// handle successful publish, e.g. logging or incrementing a metric
Log.i(TAG, "published");
}
});
}
}
private void publishMessage(String topic, String message) {
client.publishWith()
.topic(topic)
.payload(message.getBytes())
.send()
.whenComplete((mqtt3Publish, throwable) -> {
if (throwable != null) {
// handle failure to publish
Log.i(TAG, "could not publish");
} else {
// handle successful publish, e.g. logging or incrementing a metric
Log.i(TAG, "published " + message + " on " + topic);
getStatus();
}
});
}
}

View File

@@ -1,14 +0,0 @@
package com.example.mysecondapp;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class DisplayMessageActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
}
}

View File

@@ -1,28 +0,0 @@
package com.example.mysecondapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/** Called when the user taps the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editTextTextPersonName);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}

View File

@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".DisplayMessageActivity">
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -4,32 +4,31 @@
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
tools:context="ch.luria.mq1.MainActivity">
<Button
android:id="@+id/button"
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginEnd="16dp"
android:onClick="sendMessage"
android:text="@string/button_send"
app:layout_constraintBaseline_toBaselineOf="@+id/editTextTextPersonName"
android:text="@string/room_name"
android:textSize="24sp"
android:textStyle="italic"
app:layout_constraintBottom_toTopOf="@+id/toggleButton"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toEndOf="@+id/editTextTextPersonName" />
<EditText
android:id="@+id/editTextTextPersonName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:ems="10"
android:inputType="textPersonName"
android:text="@string/edit_message"
app:layout_constraintEnd_toStartOf="@+id/button"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="toggleButtonState"
android:textOff="@string/button_off"
android:textOn="@string/button_on"
android:textSize="48sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />
</androidx.constraintlayout.widget.ConstraintLayout>

View File

@@ -1,6 +1,6 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MySecondApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<style name="Theme.Mq1" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_200</item>
<item name="colorPrimaryVariant">@color/purple_700</item>

View File

@@ -1,5 +1,6 @@
<resources>
<string name="app_name">My Second App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
<string name="app_name">Mq1</string>
<string name="button_on">ALLUMEE</string>
<string name="button_off">ETEINTE</string>
<string name="room_name">Chambre d\'Isaac</string>
</resources>

View File

@@ -1,6 +1,6 @@
<resources xmlns:tools="http://schemas.android.com/tools">
<!-- Base application theme. -->
<style name="Theme.MySecondApp" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<style name="Theme.Mq1" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
<!-- Primary brand color. -->
<item name="colorPrimary">@color/purple_500</item>
<item name="colorPrimaryVariant">@color/purple_700</item>

View File

@@ -1,4 +1,4 @@
package com.example.mysecondapp;
package ch.luria.mq1;
import org.junit.Test;

View File

@@ -18,4 +18,5 @@ android.useAndroidX=true
# Enables namespacing of each library's R class so that its R class includes only the
# resources declared in the library itself and none from the library's dependencies,
# thereby reducing the size of the R class for that library
android.nonTransitiveRClass=true
android.nonTransitiveRClass=true
# android.enableJetifier=true

View File

@@ -12,5 +12,5 @@ dependencyResolutionManagement {
mavenCentral()
}
}
rootProject.name = "My Second App"
rootProject.name = "Mq1"
include ':app'