Skip to content

Commit

Permalink
Merge pull request #1 from lf-edge/Basecode
Browse files Browse the repository at this point in the history
Base code for Android support for Home Edge
  • Loading branch information
suresh-lc authored Sep 27, 2022
2 parents e442ab3 + 2aaf83e commit 36a0acc
Show file tree
Hide file tree
Showing 52 changed files with 2,421 additions and 0 deletions.
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Home-Edge-Android

As a continous process to support Home Edge (Linux) to multiple platforms, this project caters to support Home Edge for Android. There are various smart home devices and Android has been making its presence in many of these devices. The most essential part of the ecosystem has been Smart phone and specifically Android based smart phones. There are large number of applications developed to support user needs across various domains. Some of the service applications would need compute intensive or containerized applications which are not available on the Android phones. This project helps the service applications on the android phones to leverage on the service offered by devices in the same network.

Home Edge helps the Android phone to discover the other nearby devices on same network and there capabilities/services offered. It is REST based peer to peer communication between all the devices. Every device in the network is a Home Edge node. Based on the CPU capability, memory, network bandwidth a score would be calculated by all the devices. The service application on Android requests to Home Edge for a service in nearby devices. Home Edge in turn communicates with other Linux based devices running Home Edge to check on the availability of the service. When there are more than one device offering the same service, the score helps in electing the device to offload the service.

**Note :** Currently the Android can consume the services offered by other Linux based Home Edge devices. But in turn services offered by Android would not be discoverable by Linux Home Edge. This has been constraint version and would be worked upon as the project matures.

# How to work
## Request to execute a service container on Linux Home Edge :
- Android application requests to Android HE :
- POST
- IP:56001/api/v1/orchestration/services
- Body:
```
{
"ServiceName": "hello-world",
"ServiceInfo": [
{
"ExecutionType": "container",
"ExecCmd": [
"docker",
"run",
"-v", "/var/run:/var/run:rw",
"hello-world"
]
}]
}
```
# License
The Edge Orchestration source code is distributed under the Apache License, Version 2.0 open source license.
# Contributing
If you want to contribute to the Edge Orchestration project and make it better, your help is very welcome. Contributing is also a great way to learn more about social coding on GitHub, new technologies and their ecosystems.
1 change: 1 addition & 0 deletions app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/build
51 changes: 51 additions & 0 deletions app/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
plugins {
id 'com.android.application'
}

android {
compileSdk 32

defaultConfig {
applicationId "org.lfedge.homeedge"
minSdk 30
targetSdk 32
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

testOptions {
unitTests.includeAndroidResources = true
}
}

dependencies {
def room_version = "2.4.3"

implementation 'androidx.appcompat:appcompat:1.5.1'
implementation 'com.google.android.material:material:1.6.1'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'org.nanohttpd:nanohttpd:2.3.1'
implementation 'org.nanohttpd:nanohttpd-nanolets:2.3.1'
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
//Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
21 changes: 21 additions & 0 deletions app/proguard-rules.pro
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html

# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable

# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
/****************************************************************************
Copyright 2022 Samsung Electronics All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.lfedge.homeedge;

import android.content.Context;

import androidx.test.platform.app.InstrumentationRegistry;

import org.junit.Test;
import org.lfedge.homeedge.database.DeviceDatabase;
import org.lfedge.homeedge.model.Device;

import static org.junit.Assert.*;

import java.util.ArrayList;
import java.util.List;

/**
* Instrumented test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleInstrumentedTest {
@Test
public void useAppContext() {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
assertEquals("com.example.test", appContext.getPackageName());
}

@Test
public void insertDeviceEntry(){
Device device = new Device("Test","107.108.1.1","8080","android", "android");
DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).deviceDao().insert(device);

List<Device> devices = DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().getAllDevices();

assertEquals("Match", "107.108.1.1", devices.get(0).getIp());

DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().deleteAll();
}

@Test
public void getDeviceEntry(){
Device device = new Device("Test","107.108.1.1","8080","android", "android");
DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).deviceDao().insert(device);

Device tempdevice = DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().getDevicebyId("Test");

assertEquals("Match", "107.108.1.1", tempdevice.getIp());

DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().deleteAll();
}

@Test
public void updateDeviceEntry(){
Device device = new Device("Test","107.108.1.1","8080","android", "android");
DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).deviceDao().insert(device);

List<String> serv1 = new ArrayList<>();
serv1.add("AI");
serv1.add("FaceRecog");

DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().update("Test", serv1);

Device tempdevice = DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().getDevicebyId("Test");

assertEquals("Match", "Docker", tempdevice.getPlatform());

DeviceDatabase.getDatabase(InstrumentationRegistry.getInstrumentation().getTargetContext()).
deviceDao().deleteAll();
}
}
31 changes: 31 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="org.lfedge.homeedge">
<uses-permission android:name="android.permission.INTERNET" android:required="true" />
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true" />
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Test"
android:usesCleartextTraffic="true"
tools:targetApi="31">
<activity
android:name="org.lfedge.homeedge.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="org.lfedge.homeedge.HomeEdgeService"/>
</application>

</manifest>
145 changes: 145 additions & 0 deletions app/src/main/java/org/lfedge/homeedge/HomeEdgeService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/****************************************************************************
Copyright 2022 Samsung Electronics All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package org.lfedge.homeedge;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import org.lfedge.homeedge.common.Utils;
import org.lfedge.homeedge.server.HTTPServer;

import java.io.IOException;

public class HomeEdgeService extends Service {
public static final String TAG="HomeEdgeService";
public static Context mContext;
NsdHelper mNsdHelperHelper;
HTTPServer httpServer;
private BroadcastReceiver broadcastReceiverNetworkState;
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
HomeEdgeService getService() {
return HomeEdgeService.this;
}
}

@Override
public void onCreate() {
mContext = this;
// INIT BROADCAST RECEIVER TO LISTEN NETWORK STATE CHANGED
initBroadcastReceiverNetworkStateChanged();
}
private void initBroadcastReceiverNetworkStateChanged() {
final IntentFilter filters = new IntentFilter();
filters.addAction("android.net.wifi.WIFI_STATE_CHANGED");
filters.addAction("android.net.wifi.STATE_CHANGE");
broadcastReceiverNetworkState = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG,"Wifi states has changed");
String IP = Utils.getDeviceIP(context);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if (!wifiManager.isWifiEnabled()) {
Log.d(TAG,"The wifi is not connected");
//no connection
if(httpServer!=null && httpServer.isAlive())
{
httpServer.stop();
}
httpServer = null;
return;
}
//Connected to another network
if(httpServer!= null && httpServer.isAlive()) {
Log.d(TAG,"HTTP Server is not null");
String oldIP = httpServer.getDeviceIP();
Log.d(TAG,"The IP now is " + IP);

if(IP!=null && !IP.equals(oldIP)){
Log.i(TAG,"IP has changed!!!");
httpServer.stop();
httpServer = null;
//Starting the server
serverStart(IP,Utils.API.EXTERNAL_PORT);
serverStart(IP,Utils.API.INTERNAL_PORT);
}
}else{
//Starting the fresh instance or after the network is lost and reconnected
Log.d(TAG,"Starting server");
if(IP!=null) {
serverStart(IP, Utils.API.EXTERNAL_PORT);
serverStart(IP, Utils.API.INTERNAL_PORT);
}
}
}
};
super.registerReceiver(broadcastReceiverNetworkState, filters);
}
private void serverStart(String hostname,int port){
httpServer = new HTTPServer(hostname,port);
try {
if(httpServer.isAlive())
Log.i(TAG,"HttpServer is already alive");
else {
Log.d(TAG,"Staring the Server");
httpServer.start();
Log.d(TAG,"The Server is running on "+httpServer.getHostname());
}
} catch (IOException e) {
Log.e(TAG,"IOException Raised" + e.getMessage());
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mNsdHelperHelper = new NsdHelper(this);
mNsdHelperHelper.initializeNsd();
//Not required so commented
// mNsdHelperHelper.registerService(Utils.API.PORT);
mNsdHelperHelper.discoverServices();
return START_NOT_STICKY;
}

@Override
public void onDestroy() {
Log.d(TAG, "Being destroyed.");
if(httpServer != null)
httpServer.stop();
super.onDestroy();
//unregistering the receiver on App Kill
super.unregisterReceiver(broadcastReceiverNetworkState);
Log.d(TAG, "Being stopped.");
if (mNsdHelperHelper != null){
mNsdHelperHelper.tearDown();
mNsdHelperHelper = null;
}

}

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

}
Loading

0 comments on commit 36a0acc

Please sign in to comment.