diff --git a/.gitignore b/.gitignore
index 0250fe5..72a39ff 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,6 +30,8 @@ res/values/com_crashlytics_export_strings.xml
SECRET.md
TODO.md
+mainActivity/release/
+
# IntelliJ
*.iml
.gradle/
diff --git a/.idea/modules.xml b/.idea/modules.xml
index e8853cb..476da80 100644
--- a/.idea/modules.xml
+++ b/.idea/modules.xml
@@ -2,9 +2,9 @@
-
-
-
+
+
+
\ No newline at end of file
diff --git a/Privacy Policy.pdf b/Privacy Policy.pdf
new file mode 100644
index 0000000..97e6577
Binary files /dev/null and b/Privacy Policy.pdf differ
diff --git a/build.gradle b/build.gradle
index bbe9eb2..ab7f0f5 100644
--- a/build.gradle
+++ b/build.gradle
@@ -1,15 +1,19 @@
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
+ ext.kotlin_version = '1.2.21'
repositories {
jcenter()
+ google()
}
dependencies {
- classpath 'com.android.tools.build:gradle:2.1.3'
+ classpath 'com.android.tools.build:gradle:3.2.0-alpha05'
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
jcenter()
+ google()
}
}
diff --git a/comcrashlyticssdkandroid_crashlytics/comcrashlyticssdkandroid_crashlytics.iml b/comcrashlyticssdkandroid_crashlytics/comcrashlyticssdkandroid_crashlytics.iml
index ee4c648..192d03a 100644
--- a/comcrashlyticssdkandroid_crashlytics/comcrashlyticssdkandroid_crashlytics.iml
+++ b/comcrashlyticssdkandroid_crashlytics/comcrashlyticssdkandroid_crashlytics.iml
@@ -1,5 +1,5 @@
-
+
@@ -13,9 +13,9 @@
-
-
-
+
+
+
@@ -27,7 +27,6 @@
-
-
+
\ No newline at end of file
diff --git a/mainActivity/build.gradle b/mainActivity/build.gradle
index c05f4b7..3843e48 100644
--- a/mainActivity/build.gradle
+++ b/mainActivity/build.gradle
@@ -1,4 +1,5 @@
buildscript {
+ ext.anko_version = '0.10.0'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
@@ -8,22 +9,27 @@ buildscript {
}
}
apply plugin: 'com.android.application'
+apply plugin: 'kotlin-android'
apply plugin: 'io.fabric'
+apply plugin: 'kotlin-android-extensions'
repositories {
maven { url 'https://maven.fabric.io/public' }
+ maven {
+ url "https://repo.eclipse.org/content/repositories/paho-snapshots/"
+ }
+ mavenCentral()
}
android {
- compileSdkVersion 22
- buildToolsVersion '24.0.1'
+ compileSdkVersion 27
defaultConfig {
applicationId 'com.sierrawireless.avphone'
minSdkVersion 22
- targetSdkVersion 22
- versionName '1.0.6'
+ targetSdkVersion 27
+ versionName '2.0.1'
}
buildTypes {
@@ -38,13 +44,26 @@ android {
}
dependencies {
- compile project(':comcrashlyticssdkandroid_crashlytics')
- compile 'com.android.support:support-v4:22.0.0'
- compile 'com.android.support:appcompat-v7:22.0.0'
- compile 'com.google.code.gson:gson:2.2.4'
- compile files('libs/mqtt-client-0.4.0.jar')
- compile files('libs/okhttp-1.2.1-jar-with-dependencies.jar')
- compile('com.crashlytics.sdk.android:crashlytics:2.6.1@aar') {
- transitive = true;
+ implementation 'com.android.support:support-v4:27.0.2'
+ implementation 'com.android.support:appcompat-v7:27.0.2'
+ implementation 'com.google.code.gson:gson:2.8.0'
+ implementation 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2'
+ implementation 'com.baoyz.swipemenulistview:library:1.3.0'
+ implementation files('libs/okhttp-1.2.1-jar-with-dependencies.jar')
+ implementation('com.crashlytics.sdk.android:crashlytics:2.9.0@aar') {
+ transitive = true
+ }
+ implementation('com.crashlytics.sdk.android:crashlytics-ndk:2.0.1@aar') {
+ transitive = true
}
+ implementation 'com.android.support.constraint:constraint-layout:1.0.2'
+ implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
+ implementation "org.jetbrains.anko:anko-common:$anko_version"
+ implementation "org.jetbrains.kotlin:kotlin-reflect:1.2.21"
+}
+
+crashlytics {
+ enableNdk true
+ androidNdkOut 'src/main/obj'
+ androidNdkLibsOut 'src/main/libs'
}
diff --git a/mainActivity/src/main/AndroidManifest.xml b/mainActivity/src/main/AndroidManifest.xml
index 75859f5..57425cf 100644
--- a/mainActivity/src/main/AndroidManifest.xml
+++ b/mainActivity/src/main/AndroidManifest.xml
@@ -1,48 +1,52 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java
deleted file mode 100644
index 2b28ddf..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java
+++ /dev/null
@@ -1,147 +0,0 @@
-package com.sierrawireless.avphone;
-
-import android.annotation.SuppressLint;
-import android.app.Activity;
-import android.content.Intent;
-import android.os.Bundle;
-import android.util.Log;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.webkit.CookieManager;
-import android.webkit.CookieSyncManager;
-import android.webkit.WebView;
-import android.webkit.WebViewClient;
-import android.widget.Button;
-import android.widget.RadioButton;
-import android.widget.RadioGroup;
-
-import com.sierrawireless.avphone.auth.Authentication;
-
-import net.airvantage.utils.AirVantageClient;
-import net.airvantage.utils.AuthenticationUrlParser;
-import net.airvantage.utils.AvPhonePrefs;
-import net.airvantage.utils.PreferenceUtils;
-
-import java.util.Date;
-
-public class AuthorizationActivity extends Activity {
-
- private static final String LOGTAG = AuthorizationActivity.class.getName();
-
- public static final String AUTHENTICATION_TOKEN = "token";
- public static final String AUTHENTICATION_EXPIRATION_DATE = "expirationDate";
-
- public static final String AUTHENTICATION_LISTENER = "listener";
-
- public static final int REQUEST_AUTHORIZATION = 1;
-
-
- private WebView webview;
-
- private AuthenticationUrlParser authUrlParser = new AuthenticationUrlParser();
-
- private Button btnCustom;
- private Button btnEu;
- private Button btnNa;
-
- private PreferenceUtils.Server currentServer;
-
- private final class OnHostClickListener implements OnClickListener {
-
- private final PreferenceUtils.Server server;
-
- public OnHostClickListener(final PreferenceUtils.Server targetServer) {
- server = targetServer;
- }
-
- @Override
- public void onClick(final View v) {
- if (currentServer != server) {
- currentServer = server;
- PreferenceUtils.setServer(server, AuthorizationActivity.this);
- openAuthorizationPage();
- }
- }
-
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_authorization);
-
- btnNa = (RadioButton) this.findViewById(R.id.auth_btn_na);
- btnEu = (RadioButton) this.findViewById(R.id.auth_btn_eu);
- btnCustom = (RadioButton) this.findViewById(R.id.auth_btn_custom);
-
- btnNa.setOnClickListener(new OnHostClickListener(PreferenceUtils.Server.NA));
- btnEu.setOnClickListener(new OnHostClickListener(PreferenceUtils.Server.EU));
- btnCustom.setOnClickListener(new OnHostClickListener(PreferenceUtils.Server.CUSTOM));
-
- if (PreferenceUtils.isCustomDefined(this)) {
- final RadioGroup parentRadioGroup = (RadioGroup) btnCustom.getParent();
- parentRadioGroup.check(btnCustom.getId());
- } else {
- btnCustom.setVisibility(Button.GONE);
- }
-
- openAuthorizationPage();
- }
-
-
- @SuppressLint("SetJavaScriptEnabled")
- private void openAuthorizationPage() {
-
- AvPhonePrefs avPhonePrefs = PreferenceUtils.getAvPhonePrefs(this);
-
- final String serverHost = avPhonePrefs.serverHost;
- final String clientId = avPhonePrefs.clientId;
-
- webview = (WebView) findViewById(R.id.authorization_webview);
- webview.getSettings().setJavaScriptEnabled(true);
- // attach WebViewClient to intercept the callback url
- webview.setWebViewClient(new WebViewClient() {
- @Override
- public boolean shouldOverrideUrlLoading(WebView view, String url) {
-
- final Authentication auth = authUrlParser.parseUrl(url, new Date());
-
- if (auth != null) {
- Log.d(AuthorizationActivity.class.getName(), "Access token: " + auth.getAccessToken());
- Log.d(AuthorizationActivity.class.getName(), "Expiration date : " + auth.getExpirationDate());
-
- sendAuthentication(auth);
-
- }
-
- return super.shouldOverrideUrlLoading(view, url);
- }
-
- });
- String authUrl = AirVantageClient.buildImplicitFlowURL(serverHost, clientId);
- Log.d(AuthorizationActivity.class.getName(), "Auth URL: " + authUrl);
-
- // The 'authorize' page from AirVantage will store a cookie ;
- // if this cookie is passed between calls, the 'authorize' page
- // will not be displayed at all.
- CookieSyncManager.createInstance(this);
- CookieManager cookieManager = CookieManager.getInstance();
- cookieManager.removeAllCookie();
-
- // Example :
- // https://na.airvantage.net/api/oauth/authorize?client_id=54d4faa5343d49fba03f2a2ec1f210b9&response_type=token&redirect_uri=oauth://airvantage
- webview.loadUrl(authUrl);
- }
-
- private void sendAuthentication(Authentication auth) {
-
- Intent resultIntent = new Intent();
-
- resultIntent.putExtra(AUTHENTICATION_TOKEN, auth.getAccessToken());
- resultIntent.putExtra(AUTHENTICATION_EXPIRATION_DATE, auth.getExpirationDate().getTime());
-
- setResult(Activity.RESULT_OK, resultIntent);
- finish();
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java
deleted file mode 100644
index 1a6e950..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java
+++ /dev/null
@@ -1,89 +0,0 @@
-package com.sierrawireless.avphone;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.app.Fragment;
-import android.text.Spanned;
-import android.view.View;
-import android.widget.TextView;
-import android.widget.Toast;
-
-import com.sierrawireless.avphone.auth.AuthenticationManager;
-import com.sierrawireless.avphone.message.IMessageDisplayer;
-import com.sierrawireless.avphone.task.SyncWithAvListener;
-
-public abstract class AvPhoneFragment extends Fragment implements IMessageDisplayer {
-
- protected AuthenticationManager authManager;
-
- protected SyncWithAvListener syncListener;
-
- public AvPhoneFragment() {
- super();
- }
-
-
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
-
- if (activity instanceof AuthenticationManager) {
- setAuthManager((AuthenticationManager) activity);
- }
-
- if (activity instanceof SyncWithAvListener) {
- this.syncListener = (SyncWithAvListener) activity;
- }
- }
-
- public void setAuthManager(AuthenticationManager authManager) {
- this.authManager = authManager;
- }
-
- @Override
- public void showError(int id, Object... params) {
- this.showErrorMessage(id, params);
- }
-
- @Override
- public void showSuccess(int id, Object... params) {
- this.hideErrorMessage();
- this.toast(id);
- }
-
- public void showErrorMessage(int id, Object... params) {
- showErrorMessage(getActivity().getString(id, params));
- }
-
- public void showErrorMessage(String message) {
- TextView errorMessageView = getErrorMessageView();
- errorMessageView.setText(message);
- errorMessageView.setVisibility(View.VISIBLE);
- }
-
- public void showErrorMessage(Spanned spanned) {
- TextView errorMessageView = getErrorMessageView();
- errorMessageView.setText(spanned);
- errorMessageView.setVisibility(View.VISIBLE);
- }
-
- public void hideErrorMessage() {
- getErrorMessageView().setVisibility(View.GONE);
- }
-
- private void toast(int id) {
- toast(getActivity().getString(id));
- }
-
- private void toast(String message) {
- Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
- }
-
- protected void requestAuthentication() {
- Intent intent = new Intent(this.getActivity(), AuthorizationActivity.class);
- this.startActivityForResult(intent, AuthorizationActivity.REQUEST_AUTHORIZATION);
- }
-
- protected abstract TextView getErrorMessageView();
-
-}
\ No newline at end of file
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.kt
new file mode 100644
index 0000000..107d035
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.kt
@@ -0,0 +1,84 @@
+package com.sierrawireless.avphone
+
+import android.app.Fragment
+import android.content.Context
+import android.content.Intent
+import android.text.Spanned
+import android.view.View
+import android.widget.TextView
+import com.sierrawireless.avphone.activity.AuthorizationActivity
+import com.sierrawireless.avphone.auth.AuthenticationManager
+import com.sierrawireless.avphone.message.IMessageDisplayer
+import com.sierrawireless.avphone.task.SyncWithAvListener
+import org.jetbrains.anko.toast
+
+abstract class AvPhoneFragment : Fragment(), IMessageDisplayer {
+
+ var authManager: AuthenticationManager? = null
+
+ var syncListener: SyncWithAvListener? = null
+
+ abstract var errorMessageView: TextView?
+
+
+ override fun onAttach(context: Context) {
+ super.onAttach(context)
+
+ if (context is AuthenticationManager) {
+ authManager = context
+ }
+
+ }
+
+
+ override fun showError(id: Int, vararg params: Any) {
+ this.showErrorMessage(id, *params)
+ }
+
+ override fun showSuccess(id: Int, vararg params: Any) {
+ this.hideErrorMessage()
+ this.lToast(id)
+ }
+
+ override fun showSuccess(name: String, vararg params: Any) {
+ this.hideErrorMessage()
+ this.lToast(name)
+ }
+
+ private fun showErrorMessage(id: Int, vararg params: Any) {
+ showErrorMessage(activity.getString(id, *params))
+ }
+
+ private fun showErrorMessage(message: String) {
+ val errorMessageView = errorMessageView
+ errorMessageView?.text = message
+ errorMessageView?.visibility = View.VISIBLE
+ }
+
+ override fun showErrorMessage(spanned: Spanned) {
+ val errorMessageView = errorMessageView
+ errorMessageView?.text = spanned
+ errorMessageView?.visibility = View.VISIBLE
+ }
+
+ fun hideErrorMessage() {
+ errorMessageView?.visibility = View.GONE
+ }
+
+ private fun lToast(id: Int) {
+ toast(activity.getString(id))
+ }
+
+ private fun lToast(name: String) {
+ toast(name)
+ }
+
+ protected fun requestAuthentication() {
+
+ val intent = Intent(this.activity, AuthorizationActivity::class.java)
+ this.startActivityForResult(intent, AuthorizationActivity.REQUEST_AUTHORIZATION)
+ }
+
+
+
+}
\ No newline at end of file
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java
deleted file mode 100644
index 9be3362..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java
+++ /dev/null
@@ -1,193 +0,0 @@
-package com.sierrawireless.avphone;
-
-import net.airvantage.utils.AvPhonePrefs;
-import net.airvantage.utils.PreferenceUtils;
-
-import android.content.Intent;
-import android.os.Bundle;
-import android.text.Editable;
-import android.text.TextWatcher;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.EditText;
-import android.widget.TextView;
-
-import com.sierrawireless.avphone.auth.AuthUtils;
-import com.sierrawireless.avphone.auth.Authentication;
-import com.sierrawireless.avphone.message.IMessageDisplayer;
-import com.sierrawireless.avphone.model.CustomDataLabels;
-import com.sierrawireless.avphone.task.IAsyncTaskFactory;
-import com.sierrawireless.avphone.task.SyncWithAvListener;
-import com.sierrawireless.avphone.task.SyncWithAvParams;
-import com.sierrawireless.avphone.task.SyncWithAvResult;
-import com.sierrawireless.avphone.task.SyncWithAvTask;
-
-public class ConfigureFragment extends AvPhoneFragment {
-
- private Button saveBt;
-
- private EditText customData1EditText;
- private EditText customData2EditText;
- private EditText customData3EditText;
- private EditText customData4EditText;
- private EditText customData5EditText;
- private EditText customData6EditText;
-
- private View view;
-
- private String deviceId;
- private String imei;
-
- private IAsyncTaskFactory taskFactory;
-
- public ConfigureFragment() {
- super();
- }
-
- public void setTaskFactory(IAsyncTaskFactory taskFactory) {
- this.taskFactory = taskFactory;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
- view = inflater.inflate(R.layout.fragment_configure, container, false);
-
- // phone identifier
- deviceId = DeviceInfo.getUniqueId(this.getActivity());
- ((TextView) view.findViewById(R.id.phoneid_value)).setText(deviceId);
-
- // try to get the IMEI for GSM phones
- imei = DeviceInfo.getIMEI(this.getActivity());
-
- // Register button
- saveBt = (Button) view.findViewById(R.id.save_bt);
- saveBt.setOnClickListener(new View.OnClickListener() {
- @Override
- public void onClick(View view) {
- onRegisterClicked();
- }
- });
-
- // Fields for custom data
- customData1EditText = buildCustomLabelEditText(view, R.id.custom1_value, R.string.pref_custom1_label_key,
- R.string.pref_custom1_label_default);
- customData2EditText = buildCustomLabelEditText(view, R.id.custom2_value, R.string.pref_custom2_label_key,
- R.string.pref_custom2_label_default);
- customData3EditText = buildCustomLabelEditText(view, R.id.custom3_value, R.string.pref_custom3_label_key,
- R.string.pref_custom3_label_default);
- customData4EditText = buildCustomLabelEditText(view, R.id.custom4_value, R.string.pref_custom4_label_key,
- R.string.pref_custom4_label_default);
- customData5EditText = buildCustomLabelEditText(view, R.id.custom5_value, R.string.pref_custom5_label_key,
- R.string.pref_custom5_label_default);
- customData6EditText = buildCustomLabelEditText(view, R.id.custom6_value, R.string.pref_custom6_label_key,
- R.string.pref_custom6_label_default);
-
- return view;
- }
-
- private EditText buildCustomLabelEditText(View view, int id, final int prefKeyId, int labelDefaultKeyId) {
- EditText res = (EditText) view.findViewById(id);
-
- res.setText(PreferenceUtils.getPreference(getActivity(), prefKeyId, labelDefaultKeyId));
-
- res.addTextChangedListener(new TextWatcher() {
-
- @Override
- public void onTextChanged(CharSequence s, int start, int before, int count) {
- }
-
- @Override
- public void beforeTextChanged(CharSequence s, int start, int count, int after) {
- }
-
- @Override
- public void afterTextChanged(Editable s) {
- PreferenceUtils.setPreference(getActivity(), getActivity().getString(prefKeyId), s.toString());
- }
- });
- return res;
- }
-
- private boolean checkCredentials() {
-
- AvPhonePrefs prefs = PreferenceUtils.getAvPhonePrefs(getActivity());
-
- if (!prefs.checkCredentials()) {
- PreferenceUtils.showMissingPrefsDialog(getActivity());
- return false;
- }
-
- return true;
-
- }
-
- protected void onRegisterClicked() {
- if (checkCredentials()) {
- Authentication auth = authManager.getAuthentication();
- if (auth != null && !auth.isExpired()) {
- syncWithAv(auth.getAccessToken());
- } else {
- requestAuthentication();
- }
- }
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- Authentication auth = AuthUtils.activityResultAsAuthentication(requestCode, resultCode, data);
- if (auth != null) {
- authManager.onAuthentication(auth);
- syncWithAv(auth.getAccessToken());
- }
- }
-
- private void syncWithAv(String token) {
-
- AvPhonePrefs prefs = PreferenceUtils.getAvPhonePrefs(getActivity());
-
- final IMessageDisplayer display = this;
-
- final SyncWithAvTask syncTask = taskFactory.syncAvTask(prefs.serverHost, token);
-
- SyncWithAvParams syncParams = new SyncWithAvParams();
- syncParams.deviceId = deviceId;
- syncParams.imei = imei;
- syncParams.mqttPassword = prefs.password;
- syncParams.customData = getCustomDataLabels();
-
- syncTask.execute(syncParams);
-
- syncTask.addProgressListener(new SyncWithAvListener() {
- @Override
- public void onSynced(SyncWithAvResult result) {
- syncTask.showResult(result, display, getActivity());
-
- if (!result.isError()) {
- syncListener.onSynced(result);
- }
-
- }
- });
-
- }
-
- protected CustomDataLabels getCustomDataLabels() {
- CustomDataLabels customData = new CustomDataLabels();
- customData.customUp1Label = customData1EditText.getText().toString();
- customData.customUp2Label = customData2EditText.getText().toString();
- customData.customDown1Label = customData3EditText.getText().toString();
- customData.customDown2Label = customData4EditText.getText().toString();
- customData.customStr1Label = customData5EditText.getText().toString();
- customData.customStr2Label = customData6EditText.getText().toString();
- return customData;
- }
-
- public TextView getErrorMessageView() {
- return (TextView) view.findViewById(R.id.configure_error_message);
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.kt
new file mode 100644
index 0000000..5fcf5af
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.kt
@@ -0,0 +1,301 @@
+package com.sierrawireless.avphone
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.content.Intent
+import android.os.Bundle
+import android.util.Log
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.AdapterView
+import android.widget.Button
+import android.widget.ImageButton
+import android.widget.TextView
+import com.sierrawireless.avphone.activity.AuthorizationActivity
+import com.sierrawireless.avphone.activity.MainActivity
+import com.sierrawireless.avphone.activity.ObjectConfigureActivity
+import com.sierrawireless.avphone.adapter.ObjectAdapter
+import com.sierrawireless.avphone.auth.AuthUtils
+import com.sierrawireless.avphone.task.IAsyncTaskFactory
+import com.sierrawireless.avphone.task.SyncWithAvParams
+import com.sierrawireless.avphone.task.UpdateParams
+import com.sierrawireless.avphone.tools.DeviceInfo
+import kotlinx.android.synthetic.main.fragment_configure.*
+import net.airvantage.utils.PreferenceUtils
+import java.util.*
+
+open class ConfigureFragment : AvPhoneFragment() {
+ override var errorMessageView: TextView? = null
+
+ private var objectsManager: ObjectsManager? = null
+ private var menu: ArrayList = ArrayList()
+ enum class Mode {
+ DELETE,
+ SYNC,
+ UPDATE
+
+ }
+ internal var delete: Mode = Mode.SYNC
+
+ private var lView: View? = null
+
+ var current = 0
+
+
+ private var taskFactory: IAsyncTaskFactory? = null
+
+ fun setTaskFactory(taskFactory: IAsyncTaskFactory) {
+ this.taskFactory = taskFactory
+ }
+
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
+
+
+ lView = inflater.inflate(R.layout.fragment_configure, container, false)
+
+
+
+ return lView
+ }
+
+ private fun reloadMenu(){
+ menu = ArrayList()
+
+ for (obj in objectsManager!!.objects) {
+ menu.add(obj.name!!)
+ }
+
+
+ val adapter = ObjectAdapter(activity, R.layout.menu_objects, menu)
+ objectConfigure.adapter = adapter
+ }
+ override fun onStart() {
+ instance = this
+ super.onStart()
+ objectsManager = ObjectsManager.getInstance()
+ errorMessageView = configure_error_message
+
+
+ reloadMenu()
+
+ objectConfigure.onItemClickListener = AdapterView.OnItemClickListener { _, view, i, _ ->
+ val deleteActionBtn: Button = view.findViewById(R.id.menuDeleteActionBtn)
+ if (deleteActionBtn.visibility == View.VISIBLE) {
+ val deleteBtn:ImageButton = view.findViewById(R.id.menuDeleteBtn)
+ deleteBtn.visibility = View.VISIBLE
+ deleteActionBtn.visibility = View.GONE
+ } else {
+ startObjectConfigure(i)
+ }
+ }
+
+ doneConfigureBtn.setOnClickListener { (activity as MainActivity).goLastFragment() }
+
+ addConfigureBtn.setOnClickListener { _ ->
+ startObjectConfigure(-1)
+ }
+
+ resync.setOnClickListener { _ ->
+ resyncAll()
+ }
+ }
+
+ private fun startObjectConfigure(position: Int) {
+
+ //Open a new intent with the selected Object
+ val intent = Intent(view.context, ObjectConfigureActivity::class.java)
+ intent.putExtra(INDEX, position)
+
+ startActivityForResult(intent, CONFIGURE)
+ }
+
+ override fun onStop() {
+ super.onStop()
+ instance = null
+ }
+
+ private fun checkCredentials(): Boolean {
+
+ val prefs = PreferenceUtils.getAvPhonePrefs(activity)
+
+ if (!prefs.checkCredentials()) {
+ PreferenceUtils.showMissingPrefsDialog(activity)
+ return false
+ }
+
+ return true
+
+ }
+
+ private fun resyncAll() {
+ current = 0
+ // first check credential
+ if (checkCredentials()) {
+ val auth = authManager!!.authentication
+ if (!auth!!.isExpired) {
+ updateAllSystem(auth.accessToken!!)
+ } else {
+ this.delete = Mode.UPDATE
+ requestAuthentication()
+ }
+ }
+ }
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
+ if (data == null) {
+ Log.e(TAG, "data is null ??? why ????")
+ return
+ }
+ if (requestCode == AuthorizationActivity.REQUEST_AUTHORIZATION) {
+
+ val auth = AuthUtils.activityResultAsAuthentication(requestCode, resultCode, data)
+ if (auth != null) {
+ authManager!!.onAuthentication(auth)
+
+ when (delete) {
+ Mode.DELETE -> deleteSysten(auth.accessToken!!)
+ Mode.SYNC -> syncWithAv(auth.accessToken!!)
+ Mode.UPDATE -> updateAllSystem(auth.accessToken!!)
+ }
+ }
+ } else if (requestCode == CONFIGURE) {
+ if (resultCode == Activity.RESULT_OK) {
+ this.delete = Mode.SYNC
+ val position = data.getIntExtra(POS, -1)
+ //set current and start synchronization
+
+ objectsManager!!.setSavedPosition(position)
+
+ if (checkCredentials()) {
+ val auth = authManager!!.authentication
+ if (!auth!!.isExpired) {
+ syncWithAv(auth.accessToken!!)
+ } else {
+ this.delete = Mode.SYNC
+ requestAuthentication()
+ }
+ }
+ }
+ MainActivity.instance.loadMenu(false)
+ reloadMenu()
+ objectConfigure.invalidate()
+
+ }
+ }
+
+ internal fun delete() {
+ if (checkCredentials()) {
+ val auth = authManager!!.authentication
+ if (!auth!!.isExpired) {
+ deleteSysten(auth.accessToken!!)
+ } else {
+ this.delete = Mode.DELETE
+ requestAuthentication()
+ }
+ }
+ }
+
+ private fun updateAllSystem(token: String) {
+
+ if (current >= objectsManager!!.objects.size) return
+
+ objectsManager!!.setSavedPosition(current)
+
+ val prefs = PreferenceUtils.getAvPhonePrefs(activity)
+
+ val display = this
+
+ val updateTask = taskFactory!!.updateTask(prefs.serverHost!!, token)
+
+ val updateParams = UpdateParams()
+ updateParams.deviceId = DeviceInfo.getUniqueId(activity)
+ updateParams.imei = DeviceInfo.getIMEI(activity)
+ updateParams.deviceName = DeviceInfo.deviceName
+ updateParams.iccid = DeviceInfo.getICCID(activity)
+ updateParams.mqttPassword = prefs.password
+ updateParams.customData = PreferenceUtils.getCustomDataLabels(activity)
+
+ updateTask.execute(updateParams)
+
+ updateTask.addProgressListener { result ->
+
+ updateTask.showResult(result, objectsManager!!.savedObjectName!!, display, activity)
+ // Update next system
+ current++
+ updateAllSystem(token)
+
+
+ }
+
+
+ }
+
+ private fun deleteSysten(token: String) {
+ val prefs = PreferenceUtils.getAvPhonePrefs(activity)
+
+ val display = this
+
+ val deleteTask = taskFactory!!.deleteSystemTak(prefs.serverHost!!, token)
+ deleteTask.execute()
+
+ deleteTask.addProgressListener({ result ->
+ if (delete == Mode.DELETE) {
+ objectsManager!!.removeSavedObject()
+ }
+
+ deleteTask.showResult(result, display, activity)
+ MainActivity.instance.loadMenu(false)
+ reloadMenu()
+ objectConfigure.invalidate()
+
+ })
+
+
+ }
+
+ private fun syncWithAv(token: String) {
+
+ val prefs = PreferenceUtils.getAvPhonePrefs(activity)
+
+ val display = this
+
+ val syncTask = taskFactory!!.syncAvTask(prefs.serverHost!!, token)
+
+ val syncParams = SyncWithAvParams()
+ syncParams.deviceId = DeviceInfo.getUniqueId(activity)
+ syncParams.imei = DeviceInfo.getIMEI(activity)
+ syncParams.deviceName = DeviceInfo.deviceName
+ syncParams.iccid = DeviceInfo.getICCID(activity)
+ syncParams.mqttPassword = prefs.password
+ syncParams.customData = PreferenceUtils.getCustomDataLabels(activity)
+
+ syncTask.execute(syncParams)
+
+ syncTask.addProgressListener { result ->
+ if (delete == Mode.DELETE) {
+ objectsManager!!.removeSavedObject()
+ }
+
+ syncTask.showResult(result, display, activity)
+ MainActivity.instance.loadMenu(false)
+
+ if (!result.isError) {
+ syncListener!!.invoke(result)
+ }
+ }
+
+ }
+
+ companion object {
+ var INDEX = "index"
+ var CONFIGURE = 0
+ var POS = "position"
+ @SuppressLint("StaticFieldLeak")
+ var instance: ConfigureFragment? = null
+ private val TAG = ConfigureFragment::class.simpleName
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java
deleted file mode 100644
index de3193e..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.sierrawireless.avphone;
-
-public interface CustomLabelsListener {
- public void onCustomLabelsChanged();
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java
deleted file mode 100644
index e8fd3fe..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java
+++ /dev/null
@@ -1,5 +0,0 @@
-package com.sierrawireless.avphone;
-
-public interface CustomLabelsManager {
- public void setCustomLabelsListener(CustomLabelsListener listener);
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.kt
new file mode 100644
index 0000000..e78736d
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.kt
@@ -0,0 +1,7 @@
+package com.sierrawireless.avphone
+
+import com.sierrawireless.avphone.listener.CustomLabelsListener
+
+interface CustomLabelsManager {
+ fun setCustomLabelsListener(listener: CustomLabelsListener)
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java
deleted file mode 100644
index 595a18a..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java
+++ /dev/null
@@ -1,175 +0,0 @@
-package com.sierrawireless.avphone;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-import java.util.Locale;
-
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.view.View;
-import android.widget.Switch;
-import android.widget.TextView;
-
-import com.sierrawireless.avphone.service.LogMessage;
-import com.sierrawireless.avphone.service.NewData;
-
-/**
- * A component in charge of listening for service events (new data, logs) and updating the view accordingly.
- */
-public class DataViewUpdater extends BroadcastReceiver {
-
- private DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss", Locale.FRENCH);
-
- private final View view;
-
- public DataViewUpdater(View view) {
- this.view = view;
- }
-
- @Override
- public void onReceive(Context context, Intent intent) {
-
- if (intent instanceof NewData) {
- setNewData((NewData) intent);
- } else if (intent instanceof LogMessage) {
- setLogMessage(((LogMessage) intent).getMessage(), System.currentTimeMillis());
- }
- }
-
- public void onStart(Long startedSince, NewData lastData, String logMsg, Long lastRun) {
- this.setStartedSince(startedSince);
- this.setNewData(lastData);
- this.setLogMessage(logMsg, lastRun);
-
- // activate alarm button
- view.findViewById(R.id.alarm_switch).setEnabled(true);
- }
-
- public void onStop() {
- this.setStartedSince(null);
-
- // deactivate alarm button
- view.findViewById(R.id.alarm_switch).setEnabled(false);
- }
-
- private void setLogMessage(String log, Long timestamp) {
- TextView logView = findView(R.id.service_log);
- if (log != null) {
- logView.setText(hourFormat.format(timestamp != null ? new Date(timestamp) : new Date()) + " - " + log);
- logView.setVisibility(View.VISIBLE);
- } else {
- logView.setVisibility(View.GONE);
- }
- }
-
- private void setStartedSince(Long startedSince) {
- TextView startedTextView = findView(R.id.started_since);
- if (startedSince != null) {
- startedTextView.setText(view.getContext().getString(R.string.started_since) + " "
- + new SimpleDateFormat("dd/MM HH:mm:ss", Locale.FRENCH).format(new Date(startedSince)));
- startedTextView.setVisibility(View.VISIBLE);
- } else {
- startedTextView.setVisibility(View.GONE);
- }
- }
-
- private void setNewData(NewData data) {
-
- if (data.getRssi() != null) {
- findView(R.id.signal_strength_value).setText(data.getRssi() + " dBm (RSSI)");
- } else if (data.getRsrp() != null) {
- findView(R.id.signal_strength_value).setText(data.getRsrp() + " dBm (RSRP)");
- }
-
- if (data.getBatteryLevel() != null) {
- findView(R.id.battery_value).setText((int) (data.getBatteryLevel() * 100) + "%");
- }
-
- if (data.getOperator() != null) {
- findView(R.id.operator_value).setText(data.getOperator());
- }
-
- if (data.getImei() != null) {
- findView(R.id.imei_value).setText(data.getImei());
- }
-
- if (data.getNetworkType() != null) {
- findView(R.id.network_type_value).setText(data.getNetworkType());
- }
-
- if (data.getLatitude() != null && data.getLongitude() != null) {
- findView(R.id.latitude_value).setText(data.getLatitude().toString());
- findView(R.id.longitude_value).setText(data.getLongitude().toString());
- }
-
- if (data.getBytesReceived() != null) {
- findView(R.id.bytes_received_value).setText(((data.getBytesReceived()) / (1024F * 1024F)) + " Mo");
- }
-
- if (data.getBytesSent() != null) {
- findView(R.id.bytes_sent_value).setText(((data.getBytesSent()) / (1024F * 1024F)) + " Mo");
- }
-
- if (data.getMemoryUsage() != null) {
- findView(R.id.memory_usage_value).setText((int) (data.getMemoryUsage() * 100) + "%");
- }
-
- if (data.getRunningApps() != null) {
- findView(R.id.running_apps_value).setText(data.getRunningApps().toString());
- }
-
- if (data.isWifiActive() != null) {
- findView(R.id.active_wifi_value).setText(data.isWifiActive() ? "On" : "Off");
- }
-
- if (data.getAndroidVersion() != null) {
- findView(R.id.android_version_value).setText(data.getAndroidVersion());
- }
-
- if (data.isAlarmActivated() != null) {
- ((Switch) view.findViewById(R.id.alarm_switch)).setChecked(data.isAlarmActivated());
- }
-
- setCustomDataValues(data);
-
- }
-
- private void setCustomDataValues(NewData data) {
- if (data.getCustomIntUp1() != null) {
- TextView valueView = (TextView) view.findViewById(R.id.run_custom1_value);
- valueView.setText(String.valueOf(data.getCustomIntUp1()));
- }
-
- if (data.getCustomIntUp2() != null) {
- TextView valueView = (TextView) view.findViewById(R.id.run_custom2_value);
- valueView.setText(String.valueOf(data.getCustomIntUp2()));
- }
-
- if (data.getCustomIntDown1() != null) {
- TextView valueView = (TextView) view.findViewById(R.id.run_custom3_value);
- valueView.setText(String.valueOf(data.getCustomIntDown1()));
- }
-
- if (data.getCustomIntDown2() != null) {
- TextView valueView = (TextView) view.findViewById(R.id.run_custom4_value);
- valueView.setText(String.valueOf(data.getCustomIntDown2()));
- }
-
- if (data.getCustomStr1() != null) {
- TextView valueView = (TextView) view.findViewById(R.id.run_custom5_value);
- valueView.setText(String.valueOf(data.getCustomStr1()));
- }
-
- if (data.getCustomStr2() != null) {
- TextView valueView = (TextView) view.findViewById(R.id.run_custom6_value);
- valueView.setText(String.valueOf(data.getCustomStr2()));
- }
- }
-
- private TextView findView(int id) {
- return (TextView) view.findViewById(id);
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.kt
new file mode 100644
index 0000000..3ffb86d
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.kt
@@ -0,0 +1,193 @@
+package com.sierrawireless.avphone
+
+import android.annotation.SuppressLint
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+import android.util.Log
+import android.view.View
+import android.widget.ListView
+import android.widget.TextView
+import com.sierrawireless.avphone.activity.MainActivity
+import com.sierrawireless.avphone.adapter.RunListViewAdapter
+import com.sierrawireless.avphone.model.AvPhoneObjectData
+import com.sierrawireless.avphone.service.LogMessage
+import com.sierrawireless.avphone.service.NewData
+import com.sierrawireless.avphone.tools.Tools
+import java.text.SimpleDateFormat
+import java.util.*
+
+/**
+ * A component in charge of listening for service events (new data, logs) and updating the view accordingly.
+ */
+class DataViewUpdater(val view: View, private val activity: MainActivity) : BroadcastReceiver() {
+
+ private val hourFormat = SimpleDateFormat("HH:mm:ss", Locale.FRENCH)
+ private var objectsManager: ObjectsManager? = null
+
+ init {
+ objectsManager = ObjectsManager.getInstance()
+ }
+
+ override fun onReceive(context: Context, intent: Intent) {
+
+ if (intent is NewData) {
+ setNewData(intent)
+ } else if (intent is LogMessage) {
+ setLogMessage(intent.message, System.currentTimeMillis(), intent.alarm)
+ }
+ }
+
+ fun onStart(startedSince: Long?, lastData: NewData, logMsg: String?, alarmLogMsg: String?, lastRun: Long?) {
+ this.setStartedSince(startedSince)
+ Log.d(TAG, "lastData " + lastData)
+ this.setNewData(lastData)
+ this.setLogMessage(logMsg, lastRun, false)
+ this.setLogMessage(alarmLogMsg, lastRun, true)
+
+ // activate alarm button
+ //view.findViewById(R.id.alarm_switch).setEnabled(true);
+ }
+
+ fun onStop() {
+ this.setStartedSince(null)
+
+ // deactivate alarm button
+ //view.findViewById(R.id.alarm_switch).setEnabled(false);
+ }
+
+ @SuppressLint("SetTextI18n")
+ private fun setLogMessage(log: String?, timestamp: Long?, alarm: Boolean) {
+ val logView: TextView = if (alarm) {
+ findView(R.id.alarm_log)
+ } else {
+ findView(R.id.service_log)
+ }
+ if (log != null) {
+ logView.text = hourFormat.format(if (timestamp != null) Date(timestamp) else Date()) + " - " + log
+ logView.visibility = View.VISIBLE
+ } else {
+ logView.visibility = View.GONE
+ }
+ }
+
+ @SuppressLint("SetTextI18n")
+ private fun setStartedSince(startedSince: Long?) {
+ val startedTextView = findView(R.id.started_since)
+ if (startedSince != null) {
+ startedTextView.text = (view.context.getString(R.string.started_since) + " "
+ + SimpleDateFormat("dd/MM HH:mm:ss", Locale.FRENCH).format(Date(startedSince)))
+ startedTextView.visibility = View.VISIBLE
+ } else {
+ startedTextView.visibility = View.GONE
+ }
+ }
+
+ fun setNewData(data: NewData) {
+
+ val phoneListView = view.findViewById(R.id.phoneListView)
+ val listPhone = ArrayList>()
+
+ val rssi: String = when {
+ data.rssi != null -> data.rssi!!.toString() + " dBm"
+ data.rsrp != null -> data.rsrp!!.toString() + " dBm"
+ else -> "Unknown"
+ }
+
+ var temp: HashMap = HashMap()
+
+ temp[Tools.NAME] = "RSSI"
+ temp[Tools.VALUE] = rssi
+ listPhone.add(temp)
+
+ temp = HashMap()
+ temp[Tools.NAME] = "Operator"
+ if (data.operator == null) {
+ temp[Tools.VALUE] = ""
+ } else {
+ temp[Tools.VALUE] = data.operator!!
+ }
+ listPhone.add(temp)
+
+ temp = HashMap()
+ temp[Tools.NAME] = "Bytes Sent"
+ if (data.bytesSent == null) {
+ temp[Tools.VALUE] = "0 Mo"
+ } else {
+ temp[Tools.VALUE] = (data.bytesSent!! / (1024f * 1024f)).toString() + " Mo"
+ }
+ listPhone.add(temp)
+
+ temp = HashMap()
+ temp[Tools.NAME] = "Bytes Received"
+ if (data.bytesReceived == null) {
+ temp[Tools.VALUE] = "0 Mo"
+ } else {
+ temp[Tools.VALUE] = (data.bytesReceived!! / (1024f * 1024f)).toString() + " Mo"
+ }
+ listPhone.add(temp)
+
+ temp = HashMap()
+ temp[Tools.NAME] = "Network Type"
+ if (data.networkType == null) {
+ temp[Tools.VALUE] = ""
+ } else {
+ temp[Tools.VALUE] = data.networkType!!
+ }
+ listPhone.add(temp)
+
+ temp = HashMap()
+ temp[Tools.NAME] = "Latitude"
+ if (data.latitude == null) {
+ temp[Tools.VALUE] = ""
+ } else {
+ temp[Tools.VALUE] = data.latitude!!.toString()
+ }
+ listPhone.add(temp)
+
+ temp = HashMap()
+ temp[Tools.NAME] = "Longitude"
+ if (data.longitude == null) {
+ temp[Tools.VALUE] = ""
+ } else {
+ temp[Tools.VALUE] = data.longitude!!.toString()
+ }
+ listPhone.add(temp)
+ val adapter = RunListViewAdapter(activity, listPhone)
+ Log.d(TAG, "set Phone data " + listPhone)
+ phoneListView.adapter = adapter
+ phoneListView.invalidateViews()
+
+ setCustomDataValues()
+ }
+
+ private fun setCustomDataValues() {
+ val objectListView = view.findViewById(R.id.objectLstView)
+ objectsManager = ObjectsManager.getInstance()
+ val obj = objectsManager!!.currentObject
+ var temp: HashMap
+ val listObject = ArrayList>()
+ for (ldata in obj!!.datas) {
+ temp = HashMap()
+ temp[Tools.NAME] = ldata.name
+ if (ldata.mode != AvPhoneObjectData.Mode.None) {
+ temp[Tools.VALUE] = ldata.current.toString()
+ } else {
+ temp[Tools.VALUE] = ldata.defaults
+ }
+ listObject.add(temp)
+ }
+ val adapter = RunListViewAdapter(activity, listObject)
+ objectListView.adapter = adapter
+ objectListView.invalidateViews()
+ }
+
+ private fun findView(id: Int): TextView {
+ return view.findViewById(id) as TextView
+ }
+
+ companion object {
+ private val TAG = DataViewUpdater::class.simpleName
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java
deleted file mode 100644
index a176f03..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java
+++ /dev/null
@@ -1,58 +0,0 @@
-package com.sierrawireless.avphone;
-
-import android.annotation.SuppressLint;
-import android.content.Context;
-import android.telephony.TelephonyManager;
-
-public class DeviceInfo {
-
-
- /**
- * Serial number is in `syncParams.deviceId`, why not using it?
- *
- * - It is not available running emulator
- * - It is not available to our iOs counterpart
- *
- * So to be AV Phone iOs compatible and able to run emulator, we use: uppercase(userUid + "-" + systemType)
- */
- @SuppressLint("DefaultLocale")
- public static String generateSerial(final String userUid, final String systemType) {
- return (userUid + "-" + systemType).toUpperCase();
- }
-
- @SuppressLint("DefaultLocale")
- public static String getUniqueId(final Context context) {
-
- if (context instanceof MainActivity) {
- final MainActivity mainActivity = (MainActivity) context;
- return mainActivity.getSystemSerial();
- }
-
- return null;
- }
-
- /**
- * Is this SN one of the common ones used by cheap phones (eg wiko)?
- *
- * Currently we had issues with :
- *
- * - "123456789ABCD"
- * - "0123456789ABCDEF"
- *
- * We simply check if "123456789ABCD" is a substring, this should do for a while.
- */
- @SuppressLint("DefaultLocale")
- private static boolean isCommonSerialNumber(final String serialNumber) {
- return serialNumber.toUpperCase().contains("123456789ABCD");
- }
-
- public static String getIMEI(final Context context) {
-
- final TelephonyManager telManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
- if (telManager != null && telManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
- return telManager.getDeviceId();
- }
-
- return null;
- }
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java
deleted file mode 100644
index fcb1a69..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java
+++ /dev/null
@@ -1,243 +0,0 @@
-package com.sierrawireless.avphone;
-
-import net.airvantage.model.AvError;
-import net.airvantage.utils.AvPhonePrefs;
-import net.airvantage.utils.PreferenceUtils;
-
-import android.app.Activity;
-import android.content.Intent;
-import android.os.AsyncTask;
-import android.os.Bundle;
-import android.text.Html;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.View.OnClickListener;
-import android.view.ViewGroup;
-import android.widget.Button;
-import android.widget.TextView;
-
-import com.crashlytics.android.Crashlytics;
-import com.sierrawireless.avphone.auth.AuthUtils;
-import com.sierrawireless.avphone.auth.Authentication;
-import com.sierrawireless.avphone.message.IMessageDisplayer;
-import com.sierrawireless.avphone.task.IAsyncTaskFactory;
-import com.sierrawireless.avphone.task.SyncWithAvListener;
-import com.sierrawireless.avphone.task.SyncWithAvParams;
-import com.sierrawireless.avphone.task.SyncWithAvResult;
-import com.sierrawireless.avphone.task.SyncWithAvTask;
-
-public class HomeFragment extends AvPhoneFragment implements IMessageDisplayer {
-
- private static final String LOGTAG = HomeFragment.class.getName();
-
- private View view;
-
- private Authentication authForSync;
- private boolean retrySync;
-
- private Button btnLogin;
- private Button btnLogout;
-
- private IAsyncTaskFactory taskFactory;
-
- public HomeFragment() {
- super();
- retrySync = false;
- taskFactory = null;
- }
-
- public void setTaskFactory(IAsyncTaskFactory taskFactory) {
- this.taskFactory = taskFactory;
- if (retrySync) {
- retrySync = false;
- syncWithAv(authForSync);
- }
- }
-
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
-
- syncListener = (SyncWithAvListener) activity;
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
- view = inflater.inflate(R.layout.fragment_home, container, false);
-
- TextView loginMessage = (TextView) view.findViewById(R.id.home_login_message);
- loginMessage.setText(Html.fromHtml(getString(R.string.home_login_message)));
-
- btnLogin = (Button) view.findViewById(R.id.login_btn);
-
- btnLogout = (Button) view.findViewById(R.id.logout_btn);
-
- btnLogin.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View arg0) {
- requestAuthentication();
- }
- });
-
- btnLogout.setOnClickListener(new OnClickListener() {
-
- @Override
- public void onClick(View v) {
- logout();
- }
- });
-
- if (authManager.isLogged()) {
- showLoggedInState();
- } else {
- showLoggedOutState();
- }
-
- return view;
- }
-
- @Override
- public void onResume() {
- super.onResume();
-
- if (authManager.isLogged()) {
- showLoggedInState();
- } else {
- showLoggedOutState();
- }
- }
-
- private TextView getInfoMessageView() {
- TextView infoMessageView = (TextView) view.findViewById(R.id.home_info_message);
- return infoMessageView;
- }
-
- private void showCurrentServer() {
- AvPhonePrefs phonePrefs = PreferenceUtils.getAvPhonePrefs(getActivity());
- TextView infoMessageView = getInfoMessageView();
-
- String message = null;
- if (phonePrefs.usesNA()) {
- message = getString(R.string.logged_on_na);
- } else if (phonePrefs.usesEU()) {
- message = getString(R.string.logged_on_eu);
- } else {
- message = getString(R.string.logged_on_custom, phonePrefs.serverHost);
- }
-
- infoMessageView.setText(message);
- infoMessageView.setVisibility(View.VISIBLE);
- }
-
- private void hideCurrentServer() {
- TextView infoMessageView = getInfoMessageView();
- infoMessageView.setVisibility(View.GONE);
- infoMessageView.setText("");
- }
-
- @Override
- public void onActivityResult(int requestCode, int resultCode, Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
-
- Authentication auth = AuthUtils.activityResultAsAuthentication(requestCode, resultCode, data);
- if (auth != null) {
- syncWithAv(auth);
- }
- }
-
- private void syncWithAv(final Authentication auth) {
-
- hideErrorMessage();
-
- AvPhonePrefs avPhonePrefs = PreferenceUtils.getAvPhonePrefs(getActivity());
-
- // Without task factory, try later
- if (taskFactory == null) {
- authForSync = auth;
- retrySync = true;
- return;
- }
-
- final IMessageDisplayer displayer = this;
- final SyncWithAvTask syncAvTask = taskFactory.syncAvTask(avPhonePrefs.serverHost, auth.getAccessToken());
-
- syncAvTask.addProgressListener(new SyncWithAvListener() {
- @Override
- public void onSynced(SyncWithAvResult result) {
- if (result.isError()) {
- authManager.forgetAuthentication();
- showLoggedOutState();
- syncAvTask.showResult(result, displayer, getActivity());
- } else {
- authManager.onAuthentication(auth);
- showLoggedInState();
- syncListener.onSynced(result);
- }
-
- }
- });
-
- final SyncWithAvParams params = new SyncWithAvParams();
-
- params.deviceId = DeviceInfo.getUniqueId(getActivity());
- params.imei = DeviceInfo.getIMEI(getActivity());
- params.mqttPassword = avPhonePrefs.password;
- params.customData = PreferenceUtils.getCustomDataLabels(getActivity());
-
- syncAvTask.execute(params);
-
- }
-
- private void showLoggedInState() {
- showCurrentServer();
- showLogoutButton();
- }
-
- private void showLoggedOutState() {
- hideLogoutButton();
- hideCurrentServer();
- }
-
- private void logout() {
-
- AvPhonePrefs avPhonePrefs = PreferenceUtils.getAvPhonePrefs(getActivity());
-
- String accessToken = authManager.getAuthentication().getAccessToken();
-
- AsyncTask logoutTask = taskFactory.logoutTask(avPhonePrefs.serverHost, accessToken);
-
- logoutTask.execute();
-
- try {
- logoutTask.get();
- } catch (Exception e) {
- Log.w(LOGTAG, "Exception while logging out");
- Crashlytics.logException(e);
- } finally {
- authManager.forgetAuthentication();
-
- showLoggedOutState();
- }
-
- }
-
- private void showLogoutButton() {
- btnLogout.setVisibility(View.VISIBLE);
- btnLogin.setVisibility(View.GONE);
- view.findViewById(R.id.home_login_message).setVisibility(View.GONE);
- }
-
- private void hideLogoutButton() {
- btnLogout.setVisibility(View.GONE);
- btnLogin.setVisibility(View.VISIBLE);
-
- view.findViewById(R.id.home_login_message).setVisibility(View.VISIBLE);
- }
-
- public TextView getErrorMessageView() {
- return (TextView) view.findViewById(R.id.home_error_message);
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.kt
new file mode 100644
index 0000000..dca3667
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.kt
@@ -0,0 +1,192 @@
+package com.sierrawireless.avphone
+
+import android.content.Context
+import android.content.Intent
+import android.os.Build
+import android.os.Bundle
+import android.text.Html
+import android.util.Log
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import com.crashlytics.android.Crashlytics
+import com.sierrawireless.avphone.activity.MainActivity
+import com.sierrawireless.avphone.auth.AuthUtils
+import com.sierrawireless.avphone.auth.Authentication
+import com.sierrawireless.avphone.message.IMessageDisplayer
+import com.sierrawireless.avphone.task.IAsyncTaskFactory
+import com.sierrawireless.avphone.task.SyncWithAvListener
+import com.sierrawireless.avphone.task.SyncWithAvParams
+import com.sierrawireless.avphone.tools.DeviceInfo
+import kotlinx.android.synthetic.main.fragment_home.*
+import net.airvantage.model.User
+import net.airvantage.utils.PreferenceUtils
+
+class HomeFragment : AvPhoneFragment(), IMessageDisplayer {
+ private var lView: View? = null
+ private var authForSync: Authentication? = null
+ private var retrySync: Boolean = false
+ private var taskFactory: IAsyncTaskFactory? = null
+ private var user: User? = null
+ private val infoMessageView: TextView?
+ get() = home_info_message
+
+ override var errorMessageView: TextView?
+ get() = home_error_message
+ set(textView) {
+ }
+
+ fun setTaskFactory(taskFactory: IAsyncTaskFactory) {
+ this.taskFactory = taskFactory
+ if (retrySync) {
+ retrySync = false
+ syncWithAv(authForSync)
+ }
+ }
+
+ override fun onAttach(context: Context) {
+ super.onAttach(context)
+
+ @Suppress("UNCHECKED_CAST")
+ syncListener = context as SyncWithAvListener
+ }
+
+ @SuppressWarnings("deprecation")
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
+
+ lView = inflater.inflate(R.layout.fragment_home, container, false)
+
+ return lView
+ }
+
+ override fun onStart() {
+ super.onStart()
+ val loginMessage = home_login_message
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
+ loginMessage.text = Html.fromHtml(getString(R.string.home_login_message_str), Html.FROM_HTML_MODE_LEGACY)
+ }else{
+ @Suppress("DEPRECATION")
+ loginMessage.text = Html.fromHtml(getString(R.string.home_login_message_str))
+ }
+
+ login_btn.setOnClickListener { requestAuthentication() }
+ logout_btn.setOnClickListener { logout() }
+
+ showLoggedOutState()
+ }
+
+ override fun onResume() {
+ super.onResume()
+
+ showLoggedOutState()
+ }
+
+ private fun hideCurrentServer() {
+ infoMessageView?.visibility = View.GONE
+ home_login.visibility = View.GONE
+ infoMessageView?.text = ""
+ }
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
+ super.onActivityResult(requestCode, resultCode, data)
+
+ if (data != null) {
+
+
+ val auth = AuthUtils.activityResultAsAuthentication(requestCode, resultCode, data)
+ if (auth != null) {
+ syncWithAv(auth)
+ }
+ MainActivity.instance.onAuthentication(auth!!)
+ MainActivity.instance.readAuthenticationFromPreferences()
+ MainActivity.instance.loadMenu(true)
+ }
+ }
+
+ private fun syncWithAv(auth: Authentication?) {
+ hideErrorMessage()
+
+ val avPhonePrefs = PreferenceUtils.getAvPhonePrefs(activity)
+
+ // Without task factory, try later
+ if (taskFactory == null) {
+ authForSync = auth
+ retrySync = true
+ return
+ }
+
+ val displayer = this
+ val syncAvTask = taskFactory!!.syncAvTask(avPhonePrefs.serverHost!!, auth!!.accessToken!!)
+
+ syncAvTask.addProgressListener { result ->
+ if (result.isError) {
+ authManager!!.forgetAuthentication()
+ showLoggedOutState()
+ syncAvTask.showResult(result, displayer, activity)
+ } else {
+ authManager!!.onAuthentication(auth)
+ showLoggedInState()
+ user = result.user
+ syncListener!!.invoke(result)
+ }
+ }
+
+ val params = SyncWithAvParams()
+
+ params.deviceId = DeviceInfo.getUniqueId(activity)
+ params.imei = DeviceInfo.getIMEI(activity)
+ params.deviceName = DeviceInfo.deviceName
+ params.iccid = DeviceInfo.getICCID(activity)
+ params.mqttPassword = avPhonePrefs.password
+ params.customData = PreferenceUtils.getCustomDataLabels(activity)
+ // params.current = ((MainActivity)getActivity()).current;
+ params.activity = activity as MainActivity
+
+ syncAvTask.execute(params)
+ }
+
+ private fun showLoggedInState() {
+
+ }
+
+ private fun showLoggedOutState() {
+ hideLogoutButton()
+ hideCurrentServer()
+ }
+
+ private fun logout() {
+ val avPhonePrefs = PreferenceUtils.getAvPhonePrefs(activity)
+
+ if (authManager == null || authManager!!.authentication == null || taskFactory == null) {
+ return
+ }
+
+ val accessToken = authManager!!.authentication!!.accessToken
+
+ val logoutTask = taskFactory!!.logoutTask(avPhonePrefs.serverHost!!, accessToken!!)
+
+ logoutTask.execute()
+ try {
+ logoutTask.get()
+ } catch (e: Exception) {
+ Log.w(TAG, "Exception while logging out")
+ Crashlytics.logException(e)
+ } finally {
+ authManager!!.forgetAuthentication()
+
+ showLoggedOutState()
+ }
+ }
+
+ private fun hideLogoutButton() {
+ logout_btn.visibility = View.GONE
+ login_btn.visibility = View.VISIBLE
+
+ home_login_message.visibility = View.VISIBLE
+ }
+
+ companion object {
+ private val TAG = HomeFragment::class.simpleName
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java b/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java
deleted file mode 100644
index 546a5bc..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java
+++ /dev/null
@@ -1,7 +0,0 @@
-package com.sierrawireless.avphone;
-
-public interface LoginListener {
-
- public void OnLoginChanged(boolean logged);
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java
deleted file mode 100644
index 0ef8477..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java
+++ /dev/null
@@ -1,489 +0,0 @@
-package com.sierrawireless.avphone;
-
-import android.annotation.SuppressLint;
-import android.app.ActionBar;
-import android.app.ActivityManager;
-import android.app.ActivityManager.RunningServiceInfo;
-import android.app.AlarmManager;
-import android.app.Fragment;
-import android.app.PendingIntent;
-import android.content.ComponentName;
-import android.content.Context;
-import android.content.Intent;
-import android.content.ServiceConnection;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
-import android.content.res.Configuration;
-import android.os.Bundle;
-import android.os.IBinder;
-import android.preference.PreferenceManager;
-import android.support.annotation.Nullable;
-import android.support.v4.app.FragmentActivity;
-import android.support.v4.widget.DrawerLayout;
-import android.support.v7.app.ActionBarDrawerToggle;
-import android.util.Log;
-import android.view.Gravity;
-import android.view.MenuItem;
-import android.view.View;
-import android.widget.AdapterView;
-import android.widget.ArrayAdapter;
-import android.widget.ListView;
-
-import com.crashlytics.android.Crashlytics;
-import com.sierrawireless.avphone.auth.Authentication;
-import com.sierrawireless.avphone.auth.AuthenticationManager;
-import com.sierrawireless.avphone.service.MonitoringService;
-import com.sierrawireless.avphone.service.MonitoringService.ServiceBinder;
-import com.sierrawireless.avphone.task.AsyncTaskFactory;
-import com.sierrawireless.avphone.task.IAsyncTaskFactory;
-import com.sierrawireless.avphone.task.SyncWithAvListener;
-import com.sierrawireless.avphone.task.SyncWithAvResult;
-
-import net.airvantage.model.AvSystem;
-import net.airvantage.model.User;
-import net.airvantage.utils.AvPhonePrefs;
-import net.airvantage.utils.PreferenceUtils;
-
-import java.util.Collection;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
-
-import io.fabric.sdk.android.Fabric;
-
-/**
- * The main activity, handling drawer and Fragments
- */
-public class MainActivity extends FragmentActivity
- implements LoginListener, AuthenticationManager, OnSharedPreferenceChangeListener,
- MonitorServiceManager, CustomLabelsManager, SyncWithAvListener {
-
- private static final String PREFERENCE_SYSTEM_NAME = "systemName";
- private static final String PREFERENCE_SYSTEM_SERIAL = "systemSerial";
- private static final String PREFERENCE_USER_NAME = "userName";
- private static final String PREFERENCE_USER_UID = "userUid";
-
- private static String LOGTAG = MainActivity.class.getName();
-
- private ActionBar actionBar;
- private AlarmManager alarmManager;
- private IAsyncTaskFactory taskFactory;
- private Authentication auth;
- private SharedPreferences prefs;
-
- boolean boundToMonitoringService = false;
- MonitoringService monitoringService;
- private MonitorServiceListener monitoringServiceListener = null;
-
- private CustomLabelsListener customLabelsListener = null;
- private DrawerLayout drawerLayout;
- private ListView drawerListView;
- private ActionBarDrawerToggle drawerToggle;
-
- private final static String FRAGMENT_HOME = "Home";
- private final static String FRAGMENT_RUN = "Run";
- private final static String FRAGMENT_CONFIGURE = "Configure";
- private final static String FRAGMENT_SETTINGS = "Settings";
-
- private ConfigureFragment configureFragment;
- private HomeFragment homeFragment;
- private RunFragment runFragment;
-
- private final static String[] FRAGMENT_LIST = new String[]{
- FRAGMENT_HOME,
- FRAGMENT_RUN,
- FRAGMENT_CONFIGURE,
- FRAGMENT_SETTINGS,
- };
-
- public void setCustomLabelsListener(CustomLabelsListener customLabelsListener) {
- this.customLabelsListener = customLabelsListener;
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- Fabric.with(this, new Crashlytics());
-
- setContentView(R.layout.activity_main);
-
- prefs = PreferenceManager.getDefaultSharedPreferences(this);
- prefs.registerOnSharedPreferenceChangeListener(this);
-
- readAuthenticationFromPreferences();
-
- taskFactory = new AsyncTaskFactory(MainActivity.this);
-
- drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
- drawerListView = (ListView) findViewById(R.id.left_drawer);
- drawerListView.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_item, FRAGMENT_LIST));
-
- // Set the list's click listener
- drawerListView.setOnItemClickListener(new ListView.OnItemClickListener() {
- @Override
- public void onItemClick(AdapterView parent, View view, int position, long id) {
- selectItem(position);
- }
- });
-
- alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
-
- drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.drawer_open,
- R.string.drawer_close);
- drawerLayout.setDrawerListener(drawerToggle);
-
- final Map fragments = initFragments();
- final Fragment currentFragment;
- if (isLogged()) {
-
- currentFragment = fragments.get(FRAGMENT_RUN);
- unlockDrawer();
- if (isServiceRunning()) {
- connectToService();
- }
-
- } else {
-
- currentFragment = fragments.get(FRAGMENT_HOME);
- lockDrawer();
- if (isServiceRunning()) {
- // The token is probably expired.
- // We stop the service since the "stop" button is not available anymore.
- this.stopMonitoringService();
- }
-
- }
-
- selectItem(currentFragment);
- }
-
- @Override
- protected void onPostCreate(@Nullable Bundle savedInstanceState) {
- super.onPostCreate(savedInstanceState);
- drawerToggle.syncState();
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- return // Handle it ourselves
- drawerToggle.onOptionsItemSelected(item)
- // Or just go with defaults
- || super.onOptionsItemSelected(item);
- }
-
- @Override
- public void onConfigurationChanged(Configuration newConfig) {
- super.onConfigurationChanged(newConfig);
- drawerToggle.onConfigurationChanged(newConfig);
- }
-
- private void lockDrawer() {
-
- actionBar = getActionBar();
- if (actionBar != null) {
- actionBar.setDisplayHomeAsUpEnabled(false);
- actionBar.setHomeButtonEnabled(false);
- }
-
- if (drawerLayout != null) {
- drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
- }
-
- if (drawerToggle != null) {
- drawerToggle.setDrawerIndicatorEnabled(false);
- }
- }
-
- private void unlockDrawer() {
-
- actionBar = getActionBar();
- if (actionBar != null) {
- actionBar.setDisplayHomeAsUpEnabled(true);
- actionBar.setHomeButtonEnabled(true);
- }
-
- if (drawerLayout != null) {
- drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
- drawerLayout.openDrawer(Gravity.LEFT);
- }
-
- if (drawerToggle != null) {
- drawerToggle.setDrawerIndicatorEnabled(true);
- }
- }
-
- private void readAuthenticationFromPreferences() {
- this.auth = PreferenceUtils.readAuthentication(this);
- }
-
- @Override
- public void OnLoginChanged(boolean logged) {
- }
-
- public boolean isLogged() {
- return (this.auth != null && !this.auth.isExpired(new Date()));
- }
-
- @Override
- public void onAuthentication(Authentication auth) {
-
- this.auth = auth;
- unlockDrawer();
-
- saveAuthenticationInPreferences(auth);
- }
-
- @Override
- public Authentication getAuthentication() {
- return this.auth;
- }
-
- private void saveAuthenticationInPreferences(Authentication auth) {
- PreferenceUtils.saveAuthentication(this, auth);
- }
-
- public void forgetAuthentication() {
-
- lockDrawer();
- PreferenceUtils.resetAuthentication(this);
- this.auth = null;
-
- if (this.isServiceRunning()) {
- this.stopMonitoringService();
- }
-
- }
-
- @Override
- public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
-
- if (PreferenceUtils.PREF_SERVER_KEY.equals(key) || PreferenceUtils.PREF_CLIENT_ID_KEY.equals(key)) {
-
- this.stopMonitoringService();
- this.forgetAuthentication();
-
- } else if (PreferenceUtils.PREF_PERIOD_KEY.equals(key) || PreferenceUtils.PREF_PASSWORD_KEY.equals(key)) {
-
- this.restartMonitoringService();
-
- } else if (key.indexOf("pref_data_custom") != -1) {
-
- if (this.customLabelsListener != null) {
- this.customLabelsListener.onCustomLabelsChanged();
- }
- }
-
- }
-
- public boolean isServiceRunning() {
- ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
- for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
- if (MonitoringService.class.getName().equals(service.service.getClassName())) {
- return true;
- }
- }
- return false;
- }
-
- private void connectToService() {
- Intent intent = new Intent(this, MonitoringService.class);
- boundToMonitoringService = this.bindService(intent, connection, Context.BIND_AUTO_CREATE);
- }
-
- private void disconnectFromService() {
- if (boundToMonitoringService) {
- this.unbindService(connection);
- boundToMonitoringService = false;
- if (monitoringServiceListener != null) {
- monitoringServiceListener.onServiceStopped(monitoringService);
- }
- }
- }
-
- ServiceConnection connection = new ServiceConnection() {
-
- @Override
- public void onServiceConnected(ComponentName arg0, IBinder binder) {
- Log.d(LOGTAG, "Connected to the monitoring service");
- monitoringService = ((ServiceBinder) binder).getService();
-
- if (monitoringServiceListener != null) {
- monitoringServiceListener.onServiceStarted(monitoringService);
- }
-
- }
-
- @Override
- public void onServiceDisconnected(ComponentName arg0) {
- Log.d(LOGTAG, "Disconnected from the monitoring service");
- boundToMonitoringService = false;
- }
-
- };
-
- public void sendAlarmEvent(boolean activated) {
- if (boundToMonitoringService && monitoringService != null) {
- monitoringService.sendAlarmEvent(activated);
- }
- }
-
- @Override
- public void startMonitoringService() {
- AvPhonePrefs avPrefs = PreferenceUtils.getAvPhonePrefs(this);
-
- Intent intent = new Intent(this, MonitoringService.class);
- intent.putExtra(MonitoringService.DEVICE_ID, DeviceInfo.getUniqueId(this));
- intent.putExtra(MonitoringService.SERVER_HOST, avPrefs.serverHost);
- intent.putExtra(MonitoringService.PASSWORD, avPrefs.password);
-
- PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
- PendingIntent.FLAG_CANCEL_CURRENT);
- // registering our pending intent with alarm manager
- alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0,
- Integer.valueOf(avPrefs.period) * 60 * 1000, pendingIntent);
-
- connectToService();
- }
-
- @Override
- public void stopMonitoringService() {
- Intent intent = new Intent(this, MonitoringService.class);
- PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent,
- PendingIntent.FLAG_CANCEL_CURRENT);
- alarmManager.cancel(pendingIntent);
- this.stopService(intent);
-
- disconnectFromService();
- }
-
- private void restartMonitoringService() {
- stopMonitoringService();
- startMonitoringService();
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- disconnectFromService();
- }
-
- @Override
- public MonitoringService getMonitoringService() {
- return this.monitoringService;
- }
-
- public void setMonitoringServiceListener(MonitorServiceListener listener) {
- this.monitoringServiceListener = listener;
- }
-
- @SuppressLint("DefaultLocale")
- @Override
- public void onSynced(SyncWithAvResult result) {
-
- final AvSystem system = result.getSystem();
- prefs.edit().putString("systemUid", system.uid).apply();
- prefs.edit().putString(PREFERENCE_SYSTEM_NAME, system.name).apply();
-
- final User user = result.getUser();
- prefs.edit().putString(PREFERENCE_USER_UID, user.uid).apply();
- prefs.edit().putString(PREFERENCE_USER_NAME, user.name).apply();
-
- final String deviceSerial = DeviceInfo.generateSerial(user.uid, system.type);
- prefs.edit().putString(PREFERENCE_SYSTEM_SERIAL, deviceSerial).apply();
-
- if (runFragment != null) {
- String systemUid = this.getSystemUid();
- String systemName = this.getSystemName();
- runFragment.setLinkToSystem(systemUid, systemName);
- } else {
- Log.w(LOGTAG, "RunFragment reference is null when onSynced is called");
- }
-
- }
-
- public String getSystemUid() {
- return prefs.getString("systemUid", null);
- }
-
- public String getSystemSerial() {
- return prefs.getString(PREFERENCE_SYSTEM_SERIAL, null);
- }
-
- public String getSystemName() {
- return prefs.getString(PREFERENCE_SYSTEM_NAME, null);
- }
-
- @SuppressLint("DefaultLocale")
- public void setSystemSerial(final String serial) {
- prefs.edit().putString(PREFERENCE_SYSTEM_SERIAL, serial.toUpperCase()).apply();
- }
-
- /**
- * Swaps fragments in the main content view
- */
- private void selectItem(final int position) {
-
- final Fragment fragment = getFragment(position);
- if (fragment == null) {
- return;
- }
-
- // Insert the fragment by replacing any existing fragment
- getFragmentManager()
- .beginTransaction()
- .replace(R.id.content_frame, fragment)
- .commit();
-
- // Highlight the selected item, update the title, and close the drawer
- drawerListView.setItemChecked(position, true);
- setTitle(FRAGMENT_LIST[position]);
- drawerListView.setSelection(position);
- drawerLayout.closeDrawer(drawerListView);
- }
-
- private void selectItem(final Fragment fragment) {
- final Iterator fragmentsIterator = initFragments().values().iterator();
- for (int position = 0; fragmentsIterator.hasNext(); position++) {
- final Fragment currentFragment = fragmentsIterator.next();
- if (fragment.getId() == currentFragment.getId()) {
- selectItem(position);
- return;
- }
- }
- }
-
-
- private Map initFragments() {
-
- if (configureFragment == null) {
- configureFragment = new ConfigureFragment();
- configureFragment.setTaskFactory(taskFactory);
- }
-
- if (homeFragment == null) {
- homeFragment = new HomeFragment();
- homeFragment.setTaskFactory(taskFactory);
- }
-
- if (runFragment == null) {
- runFragment = new RunFragment();
- }
-
- final HashMap fragmentsMapping = new HashMap<>();
- fragmentsMapping.put(FRAGMENT_CONFIGURE, configureFragment);
- fragmentsMapping.put(FRAGMENT_HOME, homeFragment);
- fragmentsMapping.put(FRAGMENT_SETTINGS, new SettingsActivity.SettingsFragment());
- fragmentsMapping.put(FRAGMENT_RUN, runFragment);
-
- return fragmentsMapping;
- }
-
- @Nullable
- private Fragment getFragment(final int fragmentPosition) {
- final String fragmentName = FRAGMENT_LIST[fragmentPosition];
- final Map fragmentMap = initFragments();
- return fragmentMap.containsKey(fragmentName) ? fragmentMap.get(fragmentName) : null;
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java
deleted file mode 100644
index 2290d3a..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java
+++ /dev/null
@@ -1,10 +0,0 @@
-package com.sierrawireless.avphone;
-
-import com.sierrawireless.avphone.service.MonitoringService;
-
-public interface MonitorServiceListener {
-
- public void onServiceStarted(MonitoringService service);
-
- public void onServiceStopped(MonitoringService service);
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java
deleted file mode 100644
index eac52fd..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java
+++ /dev/null
@@ -1,13 +0,0 @@
-package com.sierrawireless.avphone;
-
-import com.sierrawireless.avphone.service.MonitoringService;
-
-
-public interface MonitorServiceManager {
- public boolean isServiceRunning();
- public void stopMonitoringService();
- public void startMonitoringService();
- public void sendAlarmEvent(boolean activated);
- public void setMonitoringServiceListener(MonitorServiceListener listener);
- public MonitoringService getMonitoringService();
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.kt
new file mode 100644
index 0000000..123a86f
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.kt
@@ -0,0 +1,132 @@
+package com.sierrawireless.avphone
+
+
+import android.content.Context
+import com.sierrawireless.avphone.activity.MainActivity
+import com.sierrawireless.avphone.model.AvPhoneObject
+import com.sierrawireless.avphone.model.AvPhoneObjectData
+import com.sierrawireless.avphone.tools.MyPreference
+import java.util.*
+
+class ObjectsManager private constructor() {
+ private var mainActivity: MainActivity? = null
+ var current: Int = 0
+ private var savedPosition = -1
+
+ internal var objects: ArrayList
+
+ val savecObject: AvPhoneObject
+ get() = objects[savedPosition]
+
+ val savedObjectName: String?
+ get() = objects[savedPosition].name
+
+ val currentObject: AvPhoneObject?
+ get() = if (objects.isEmpty()) {
+ null
+ } else objects[current]
+
+ init {
+ objects = ArrayList()
+ }
+
+ internal fun init(activity: MainActivity) {
+ this.mainActivity = activity
+ val pref = MyPreference(activity.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE))
+
+
+ objects = pref.getListObject(MODELS, AvPhoneObject::class.java)
+ current = pref.getInt(ACTIVE)
+
+ if (objects.isEmpty()) {
+ // Create the default model here
+ val model = AvPhoneObject()
+ model.name = "Printer"
+ var data = AvPhoneObjectData("A6 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "1", null)
+ model.add(data)
+ data = AvPhoneObjectData("A4 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "2", null)
+ model.add(data)
+ data = AvPhoneObjectData("Black Cartridge S/N", "", "NTOQN-7HUL9-NEPFL-13IOA", AvPhoneObjectData.Mode.None, "3", null)
+ model.add(data)
+ data = AvPhoneObjectData("Black lnk Level", "%", "100", AvPhoneObjectData.Mode.DOWN, "4",null)
+ model.add(data)
+ data = AvPhoneObjectData("Color Cartridge S/N", "", "629U7-XLT5H-6SCGJ-@CENZ", AvPhoneObjectData.Mode.None, "5",null)
+ model.add(data)
+ data = AvPhoneObjectData("Color lnk Level", "%", "100", AvPhoneObjectData.Mode.DOWN, "6",null)
+ model.add(data)
+ objects.add(model)
+ current = 0
+ saveOnPref()
+ }
+ if (savedPosition == -1) {
+ savedPosition = current
+ }
+ }
+
+ internal fun removeSavedObject() {
+ objects.removeAt(savedPosition)
+ savedPosition = current
+ saveOnPref()
+ }
+
+ fun saveOnPref() {
+ val pref = MyPreference(mainActivity!!.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE))
+ // Save the list for later
+ pref.putListObject(MODELS, objects)
+ pref.putInt(ACTIVE, current)
+ }
+
+ internal fun reload() {
+
+ val pref = MyPreference(mainActivity!!.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE))
+
+
+ objects = pref.getListObject(MODELS, AvPhoneObject::class.java)
+ current = pref.getInt(ACTIVE)
+
+ }
+
+
+ fun changeCurrent(name: String) {
+ for ((index, obj) in objects.withIndex()) {
+ if (obj.name == name) {
+ current = index
+ saveOnPref()
+ return
+ }
+ }
+ }
+
+ internal fun setSavedPosition(position: Int) {
+ savedPosition = position
+ }
+
+ internal fun getObjectByIndex(position: Int): AvPhoneObject? {
+ return if (position > objects.size) {
+ null
+ } else objects[position]
+ }
+
+ fun getObjectByName(name: String): AvPhoneObject? {
+ return objects.firstOrNull { it.name == name }
+ }
+
+ internal fun save() {
+ saveOnPref()
+
+ }
+
+ companion object {
+ private var lInstance:ObjectsManager? = null
+ private const val SHARED_PREFS_FILE = "SavedModels"
+ private const val MODELS = "models"
+ private const val ACTIVE = "active"
+
+ fun getInstance(): ObjectsManager {
+ if (lInstance == null) {
+ lInstance = ObjectsManager()
+ }
+ return lInstance!!
+ }
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java
deleted file mode 100644
index b29f063..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java
+++ /dev/null
@@ -1,248 +0,0 @@
-package com.sierrawireless.avphone;
-
-import net.airvantage.utils.AvPhonePrefs;
-import net.airvantage.utils.PreferenceUtils;
-
-import android.app.Activity;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.support.v4.content.LocalBroadcastManager;
-import android.support.v7.widget.SwitchCompat;
-import android.text.Html;
-import android.text.method.LinkMovementMethod;
-import android.util.Log;
-import android.view.LayoutInflater;
-import android.view.View;
-import android.view.ViewGroup;
-import android.widget.CompoundButton;
-import android.widget.CompoundButton.OnCheckedChangeListener;
-import android.widget.TextView;
-
-import com.sierrawireless.avphone.model.CustomDataLabels;
-import com.sierrawireless.avphone.service.LogMessage;
-import com.sierrawireless.avphone.service.MonitoringService;
-import com.sierrawireless.avphone.service.NewData;
-
-public class RunFragment extends AvPhoneFragment implements MonitorServiceListener, CustomLabelsListener {
-
- private static final String LOGTAG = RunFragment.class.getName();
-
- private DataViewUpdater viewUpdater;
-
- private View view;
-
- private MonitorServiceManager monitorServiceManager;
-
- private CustomLabelsManager customLabelsManager;
- private String systemUid;
- private String systemName;
-
- @Override
- public void onAttach(Activity activity) {
- super.onAttach(activity);
-
- if (activity instanceof MonitorServiceManager) {
- this.setMonitorServiceManager((MonitorServiceManager) activity);
- }
-
- if (activity instanceof CustomLabelsManager) {
- this.setCustomLabelsManager((CustomLabelsManager) activity);
- }
- }
-
- protected void setMonitorServiceManager(MonitorServiceManager manager) {
- this.monitorServiceManager = manager;
- this.monitorServiceManager.setMonitoringServiceListener(this);
- }
-
- protected void setCustomLabelsManager(CustomLabelsManager manager) {
- this.customLabelsManager = manager;
- this.customLabelsManager.setCustomLabelsListener(this);
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
-
- view = inflater.inflate(R.layout.fragment_run, container, false);
- viewUpdater = new DataViewUpdater(view);
-
- CustomDataLabels customLabels = PreferenceUtils.getCustomDataLabels(getActivity());
- setCustomDataLabels(customLabels);
-
- // register service listener
- LocalBroadcastManager.getInstance(getActivity()).registerReceiver(viewUpdater,
- new IntentFilter(NewData.NEW_DATA));
- LocalBroadcastManager.getInstance(getActivity()).registerReceiver(viewUpdater,
- new IntentFilter(LogMessage.LOG_EVENT));
-
- boolean isServiceRunning = monitorServiceManager.isServiceRunning();
-
- SwitchCompat serviceSwitch = (SwitchCompat) view.findViewById(R.id.service_switch);
- serviceSwitch.setChecked(isServiceRunning);
-
- serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- if (isChecked) {
- startMonitoringService();
- } else {
- stopMonitoringService();
- }
- }
- });
-
- if (isServiceRunning) {
- MonitoringService service = monitorServiceManager.getMonitoringService();
- if (service != null) {
- this.onServiceStarted(service);
- } else {
- // the activity is not yet connected to the service.
- // as a MonitorServiceListener, this fragment will be notified when the service is available
- }
- }
-
- // Alarm button
- SwitchCompat alarmButton = (SwitchCompat) view.findViewById(R.id.alarm_switch);
- alarmButton.setOnCheckedChangeListener(onAlarmClick);
-
- // Make links clickable in info view.
- TextView infoMessageView = (TextView) view.findViewById(R.id.run_info_message);
- infoMessageView.setLinksClickable(true);
- infoMessageView.setMovementMethod(LinkMovementMethod.getInstance());
-
- // Might had those before initialization
- if (systemUid != null && systemName != null) {
- setLinkToSystem(systemUid, systemName);
- }
-
- return view;
- }
-
- public void setLinkToSystem(String systemUid, String systemName) {
-
- if (view == null || getActivity() == null) {
- // View is unavailable, bear it in mind for later
- this.systemUid = systemUid;
- this.systemName = systemName;
- return;
- }
-
- final TextView infoMessageView = (TextView) view.findViewById(R.id.run_info_message);
-
- String infoMessage = null;
- if (systemUid != null) {
-
- AvPhonePrefs avPhonePrefs = PreferenceUtils.getAvPhonePrefs(getActivity());
- String link = String.format("https://%s/monitor/systems/systemDetails?uid=%s", avPhonePrefs.serverHost,
- systemUid);
-
- infoMessage = getString(R.string.run_info_message_link, link, systemName);
- infoMessageView.setText(Html.fromHtml(infoMessage));
-
- } else {
- infoMessage = getString(R.string.run_info_message, DeviceInfo.getUniqueId(getActivity()));
- infoMessageView.setText(infoMessage);
- }
-
- }
-
- @Override
- public void onResume() {
- super.onResume();
-
- boolean isServiceRunning = monitorServiceManager.isServiceRunning();
- SwitchCompat serviceSwitch = getServiceSwitch();
- serviceSwitch.setChecked(isServiceRunning);
-
- String systemUid = ((MainActivity) getActivity()).getSystemUid();
- String systemName = ((MainActivity) getActivity()).getSystemName();
-
- this.setLinkToSystem(systemUid, systemName);
-
- }
-
- private SwitchCompat getServiceSwitch() {
- return (SwitchCompat) view.findViewById(R.id.service_switch);
- }
-
- private void startMonitoringService() {
- AvPhonePrefs avPrefs = PreferenceUtils.getAvPhonePrefs(getActivity());
- if (!avPrefs.checkCredentials()) {
- PreferenceUtils.showMissingPrefsDialog(getActivity());
- SwitchCompat serviceSwitch = getServiceSwitch();
- serviceSwitch.setChecked(false);
- } else {
- this.monitorServiceManager.startMonitoringService();
- }
-
- }
-
- private void stopMonitoringService() {
- this.monitorServiceManager.stopMonitoringService();
- }
-
- protected void setCustomDataLabels(CustomDataLabels customDataLabels) {
- TextView labelView = (TextView) view.findViewById(R.id.run_custom1_label);
- labelView.setText(customDataLabels.customUp1Label);
-
- labelView = (TextView) view.findViewById(R.id.run_custom2_label);
- labelView.setText(customDataLabels.customUp2Label);
-
- labelView = (TextView) view.findViewById(R.id.run_custom3_label);
- labelView.setText(customDataLabels.customDown1Label);
-
- labelView = (TextView) view.findViewById(R.id.run_custom4_label);
- labelView.setText(customDataLabels.customDown2Label);
-
- labelView = (TextView) view.findViewById(R.id.run_custom5_label);
- labelView.setText(customDataLabels.customStr1Label);
-
- labelView = (TextView) view.findViewById(R.id.run_custom6_label);
- labelView.setText(customDataLabels.customStr2Label);
- }
-
- // Alarm button
-
- OnCheckedChangeListener onAlarmClick = new OnCheckedChangeListener() {
-
- @Override
- public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
- Log.d(LOGTAG, "On alarm button click");
-
- monitorServiceManager.sendAlarmEvent(isChecked);
-
- }
- };
-
- protected TextView getErrorMessageView() {
- return (TextView) view.findViewById(R.id.run_error_message);
- }
-
- @Override
- public void onServiceStarted(MonitoringService service) {
- view.findViewById(R.id.toggle_to_start).setVisibility(View.GONE);
- view.findViewById(R.id.started_since).setVisibility(View.VISIBLE);
- view.findViewById(R.id.service_log).setVisibility(View.VISIBLE);
- viewUpdater.onStart(service.getStartedSince(), service.getLastData(), service.getLastLog(),
- service.getLastRun());
- }
-
- @Override
- public void onServiceStopped(MonitoringService service) {
- view.findViewById(R.id.toggle_to_start).setVisibility(View.VISIBLE);
- view.findViewById(R.id.started_since).setVisibility(View.GONE);
- view.findViewById(R.id.service_log).setVisibility(View.GONE);
- viewUpdater.onStop();
- }
-
- @Override
- public void onCustomLabelsChanged() {
- // The activity can be null if the change is done while the fragment is not active.
- // This can wait for the activity to be resumed.
- if (getActivity() != null) {
- CustomDataLabels customLabels = PreferenceUtils.getCustomDataLabels(getActivity());
- setCustomDataLabels(customLabels);
- }
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.kt
new file mode 100644
index 0000000..b68d4a3
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.kt
@@ -0,0 +1,473 @@
+package com.sierrawireless.avphone
+
+import android.annotation.TargetApi
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.content.IntentFilter
+import android.net.Uri
+import android.os.Bundle
+import android.support.v4.content.ContextCompat
+import android.support.v4.content.LocalBroadcastManager
+import android.util.Log
+import android.view.LayoutInflater
+import android.view.View
+import android.view.ViewGroup
+import android.widget.TextView
+import com.sierrawireless.avphone.activity.AuthorizationActivity
+import com.sierrawireless.avphone.activity.MainActivity
+import com.sierrawireless.avphone.adapter.RunListViewAdapter
+import com.sierrawireless.avphone.auth.AuthUtils
+import com.sierrawireless.avphone.listener.CustomLabelsListener
+import com.sierrawireless.avphone.listener.MonitorServiceListener
+import com.sierrawireless.avphone.model.AvPhoneObjectData
+import com.sierrawireless.avphone.service.LogMessage
+import com.sierrawireless.avphone.service.MonitorServiceManager
+import com.sierrawireless.avphone.service.MonitoringService
+import com.sierrawireless.avphone.service.NewData
+import com.sierrawireless.avphone.task.IAsyncTaskFactory
+import com.sierrawireless.avphone.task.SyncWithAvParams
+import com.sierrawireless.avphone.tools.DeviceInfo
+import com.sierrawireless.avphone.tools.Tools
+import kotlinx.android.synthetic.main.fragment_run.*
+import net.airvantage.utils.PreferenceUtils
+import org.jetbrains.anko.alert
+import java.util.*
+import kotlin.concurrent.schedule
+
+
+@Suppress("DEPRECATION")
+open class RunFragment : AvPhoneFragment(), MonitorServiceListener, CustomLabelsListener {
+ private var viewUpdater: DataViewUpdater? = null
+ private var lView: View? = null
+ private var monitorServiceManager: MonitorServiceManager? = null
+ private var systemUid: String? = null
+ private var systemName: String? = null
+ private var taskFactory: IAsyncTaskFactory? = null
+ private var objectName: String? = null
+ private var objectsManager: ObjectsManager = ObjectsManager.getInstance()
+
+ private var timer:TimerTask? = null
+
+ // Alarm button
+ private var onAlarmClick: View.OnClickListener = View.OnClickListener {
+ if (this.monitorServiceManager!!.isServiceStarted(objectName!!)) {
+ objectsManager = ObjectsManager.getInstance()
+ val obj = objectsManager.currentObject!!
+ obj.alarm = !obj.alarm
+ if (!monitorServiceManager!!.sendAlarmEvent(obj.alarm)) {
+ obj.alarm = !obj.alarm
+ } else {
+ objectsManager.saveOnPref()
+ setAlarmButton()
+ }
+ }else{
+ alert("A run already exist for " + MainActivity.instance.startObjectName, "Alert") {
+ positiveButton("OK") {
+
+ }
+ }.show()
+ }
+ }
+
+ private fun setAlarmButton() {
+ val obj = objectsManager.currentObject!!
+ alarm_btn.text = if (obj.alarm) {
+ getString(R.string.cancel)
+ }else{
+ getString(R.string.reaise)
+ }
+ }
+
+ override var errorMessageView: TextView?
+ get() = run_error_message
+ set(textView) {
+
+ }
+
+ fun setTaskFactory(taskFactory: IAsyncTaskFactory) {
+ this.taskFactory = taskFactory
+ }
+
+ fun setObjectName(name: String) {
+ this.objectName = name
+ }
+
+ @Suppress("OverridingDeprecatedMember")
+ override fun onAttach(activity:Activity) {
+ super.onAttach(activity)
+
+ Log.d(TAG, "OnAttach Called")
+
+ if (activity is MonitorServiceManager) {
+ this.setMonitorServiceManager(activity as MonitorServiceManager)
+ }
+
+ if (activity is CustomLabelsManager) {
+ this.setCustomLabelsManager(activity as CustomLabelsManager)
+ }
+ }
+
+ @TargetApi(23)
+ override fun onAttach(context: Context) {
+ super.onAttach(context)
+
+ Log.d(TAG, "OnAttach Called")
+
+ if (context is MonitorServiceManager) {
+ this.setMonitorServiceManager(context as MonitorServiceManager)
+ }
+
+ if (context is CustomLabelsManager) {
+ this.setCustomLabelsManager(context as CustomLabelsManager)
+ }
+ }
+
+ override fun onDetach() {
+ super.onDetach()
+ Log.d(TAG, "On detach called")
+ }
+
+ private fun setMonitorServiceManager(manager: MonitorServiceManager) {
+ Log.d(TAG, "Set monitoring service")
+ this.monitorServiceManager = manager
+ this.monitorServiceManager!!.setMonitoringServiceListener(this)
+ }
+
+ private fun setCustomLabelsManager(manager: CustomLabelsManager) {
+ manager.setCustomLabelsListener(this)
+ }
+
+ override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
+
+ lView = inflater.inflate(R.layout.fragment_run, container, false)
+
+ return lView
+ }
+
+ override fun onStart() {
+ super.onStart()
+ objectsManager = ObjectsManager.getInstance()
+ if (objectName != null) {
+ objectsManager.changeCurrent(objectName!!)
+ }else{
+ Log.d(TAG, "retrieve canceled objectName")
+ objectName = MainActivity.instance.fragmentsList!![MainActivity.instance.lastPosition].name
+ }
+ viewUpdater = DataViewUpdater(lView!!, activity as MainActivity)
+
+
+ // register service listener
+ LocalBroadcastManager.getInstance(activity).registerReceiver(viewUpdater!!,
+ IntentFilter(NewData.NEW_DATA))
+ LocalBroadcastManager.getInstance(activity).registerReceiver(viewUpdater!!,
+ IntentFilter(LogMessage.LOG_EVENT))
+
+ /* if service is running and it's myself or that is not running */
+ if (monitorServiceManager != null &&
+ ((monitorServiceManager!!.isServiceRunning() && monitorServiceManager!!.isServiceRunning(objectName!!)) ||
+ !monitorServiceManager!!.isServiceRunning())){
+ if (!this.monitorServiceManager!!.isServiceStarted(objectName!!)) {
+ if (this.monitorServiceManager!!.oneServiceStarted()) {
+ //stop the service
+ this.monitorServiceManager!!.stopMonitoringService()
+ }
+ //registerNewDevice();
+ this.monitorServiceManager!!.startMonitoringService(objectName!!)
+ }
+ }
+ val isServiceRunning = if (monitorServiceManager != null) {
+ monitorServiceManager!!.isServiceRunning(objectName!!)
+ }else{
+ false
+ }
+ service_switch.isChecked = isServiceRunning
+
+ service_switch.setOnCheckedChangeListener { _, isChecked ->
+ if (isChecked) {
+ startMonitoringService()
+ } else {
+ stopMonitoringService()
+ }
+ }
+
+ if (isServiceRunning) {
+ val service = monitorServiceManager!!.monitoringService
+ if (service != null) {
+ this.onServiceStarted(service)
+ }
+ }
+
+
+ // Alarm button
+ alarm_btn.setOnClickListener(onAlarmClick)
+
+ // Make links clickable in info view.
+
+ // Might had those before initialization
+ if (systemUid != null && systemName != null) {
+ setLinkToSystem(systemUid, systemName)
+ }
+
+ obj.text = objectName
+ phone.setBackgroundColor(ContextCompat.getColor(MainActivity.instance.baseContext, R.color.grey_1))
+ phoneListView.visibility = View.VISIBLE
+ objectLstView.visibility = View.GONE
+
+ phone.setOnClickListener {
+ phoneListView.visibility = View.VISIBLE
+ objectLstView.visibility = View.GONE
+ phone.isSelected = true
+ phone.isPressed = true
+ phone.setBackgroundColor(ContextCompat.getColor(MainActivity.instance.baseContext, R.color.grey_1))
+ obj.isSelected = false
+ obj.isPressed = false
+ obj.setBackgroundColor(ContextCompat.getColor(MainActivity.instance.baseContext, R.color.grey_4))
+ }
+
+ obj.setOnClickListener {
+ phoneListView.visibility = View.GONE
+ objectLstView.visibility = View.VISIBLE
+ phone.isSelected = false
+ phone.isPressed = false
+ phone.setBackgroundColor(ContextCompat.getColor(MainActivity.instance.baseContext, R.color.grey_4))
+ obj.isSelected = true
+ obj.isPressed = true
+ obj.setBackgroundColor(ContextCompat.getColor(MainActivity.instance.baseContext, R.color.grey_1))
+ }
+
+ setCustomDataLabels()
+ setPhoneDataLabels()
+ }
+
+ override fun onResume() {
+ Log.d(TAG, "On Resume Called")
+ super.onResume()
+ if (monitorServiceManager == null){
+ // We have to restart monitorServiceManager
+ Log.d(TAG, "MonitoringServiceManager is null")
+ return
+ }
+ if (objectName == null) {
+ Log.d(TAG, "objectName is null retreive it from objectManager")
+ objectName = objectsManager.currentObject!!.name
+ }
+ val isServiceRunning = monitorServiceManager!!.isServiceRunning(objectName!!)
+ service_switch.isChecked = isServiceRunning
+ val systemUid = (activity as MainActivity).systemUid
+ val systemName = (activity as MainActivity).systemName
+
+ this.setLinkToSystem(systemUid, systemName)
+ startTimer()
+ monitorServiceManager?.start()
+ setAlarmButton()
+ setPhoneDataLabels()
+ }
+
+ override fun onPause() {
+ Log.d(TAG, "on Pause Called")
+ super.onPause()
+ stopTimer()
+ this.monitorServiceManager?.cancel()
+ }
+
+
+ override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
+ super.onActivityResult(requestCode, resultCode, data)
+
+ if (requestCode == AuthorizationActivity.REQUEST_AUTHORIZATION) {
+ val auth = AuthUtils.activityResultAsAuthentication(requestCode, resultCode, data)
+ if (auth != null) {
+ authManager!!.onAuthentication(auth)
+ syncWithAv(auth.accessToken)
+ }
+ }
+ }
+
+ private fun syncWithAv(token: String?) {
+
+ val prefs = PreferenceUtils.getAvPhonePrefs(activity)
+ val display = this
+
+ val syncAvTask = taskFactory!!.syncAvTask(prefs.serverHost!!, token!!)
+
+
+ val params = SyncWithAvParams()
+
+ params.deviceId = DeviceInfo.getUniqueId(activity)
+ params.imei = DeviceInfo.getIMEI(activity)
+ params.deviceName = DeviceInfo.deviceName
+ params.iccid = DeviceInfo.getICCID(activity)
+ params.mqttPassword = prefs.password
+ params.customData = PreferenceUtils.getCustomDataLabels(activity)
+ // params.current = ((MainActivity)getActivity()).current;
+ params.activity = activity as MainActivity
+
+ syncAvTask.execute(params)
+ syncAvTask.addProgressListener { result ->
+ syncAvTask.showResult(result, display, activity)
+
+ if (!result.isError) {
+ syncListener!!.invoke(result)
+ }
+ }
+ }
+
+ private fun setLinkToSystem(systemUid: String?, systemName: String?) {
+
+ if (lView == null || activity == null) {
+ // View is unavailable, bear it in mind for later
+ this.systemUid = systemUid
+ this.systemName = systemName
+ }
+ val avPhonePrefs = PreferenceUtils.getAvPhonePrefs(MainActivity.instance)
+ objectsManager = ObjectsManager.getInstance()
+ val obj = objectsManager.currentObject!!
+ val link = String.format("https://%s/monitor/systems/systemDetails?uid=%s", avPhonePrefs.serverHost, obj.systemUid)
+
+ airvantage.setOnClickListener {
+ val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
+ startActivity(browserIntent)
+ }
+
+ // set button to open Airvantage
+
+ return
+ }
+
+ private fun startMonitoringService() {
+ val avPrefs = PreferenceUtils.getAvPhonePrefs(activity)
+ if (!avPrefs.checkCredentials()) {
+ PreferenceUtils.showMissingPrefsDialog(activity)
+ service_switch.isChecked = false
+ } else {
+ if (this.monitorServiceManager!!.startSendData(objectName!!)) {
+ this.monitorServiceManager!!.monitoringService!!.startSendData()
+ }else{
+ service_switch.isChecked = false
+ }
+ }
+
+ }
+
+ private fun stopMonitoringService() {
+ this.monitorServiceManager!!.stopSendData()
+ this.monitorServiceManager!!.monitoringService!!.stopSendData()
+ }
+
+
+
+
+ private fun setPhoneDataLabels() {
+ Log.d(TAG, "setPhoneDataLabels called for " + objectName)
+ val adapter = RunListViewAdapter(activity, arrayListOf(
+ hashMapOf(Tools.NAME to "RSSI",
+ Tools.VALUE to "0 dBm"),
+ hashMapOf(Tools.NAME to "Operator",
+ Tools.VALUE to "Unknown"),
+ hashMapOf(Tools.NAME to "Bytes Sent",
+ Tools.VALUE to "0 Mo"),
+ hashMapOf(Tools.NAME to "Bytes received",
+ Tools.VALUE to "0 Mo"),
+ hashMapOf(Tools.NAME to "Network Type",
+ Tools.VALUE to "Unknown"),
+ hashMapOf(Tools.NAME to "Latitude",
+ Tools.VALUE to "Unknown"),
+ hashMapOf(Tools.NAME to "Longitude",
+ Tools.VALUE to "Unknown")))
+ phoneListView.adapter = adapter
+ phoneListView.invalidateViews()
+
+ }
+
+ private fun setCustomDataLabels() {
+ val listObject = ArrayList>()
+
+ objectsManager = ObjectsManager.getInstance()
+ val obj = objectsManager.getObjectByName(objectName!!)
+ var temp: HashMap
+ for (data in obj!!.datas) {
+ temp = HashMap()
+ temp[Tools.NAME] = data.name
+ if (data.mode != AvPhoneObjectData.Mode.None) {
+ temp[Tools.VALUE] = data.current!!.toString()
+ } else {
+ temp[Tools.VALUE] = data.defaults
+ }
+ listObject.add(temp)
+ }
+ val adapter = RunListViewAdapter(activity, listObject)
+ objectLstView?.adapter = adapter
+ objectLstView?.invalidateViews()
+ }
+
+ override fun onServiceStarted(service: MonitoringService) {
+ Log.d(TAG, "OnServiceStarted for " + objectName)
+ toggle_to_start?.visibility = View.GONE
+ started_since?.visibility = View.VISIBLE
+ service_log?.visibility = View.VISIBLE
+ alarm_log?.visibility = View.VISIBLE
+ viewUpdater?.onStart(service.startedSince, service.lastData, service.lastLog, service.lastAlarmLog,
+ service.lastRun)
+ }
+
+ override fun onServiceStopped(service: MonitoringService) {
+ toggle_to_start?.visibility = View.VISIBLE
+ started_since?.visibility = View.GONE
+ service_log?.visibility = View.GONE
+ alarm_log?.visibility = View.GONE
+ viewUpdater?.onStop()
+ }
+
+ override fun onCustomLabelsChanged() {
+ // The activity can be null if the change is done while the fragment is not active.
+ // This can wait for the activity to be resumed.
+ if (activity != null) {
+ setCustomDataLabels()
+ }
+ }
+
+
+ // Manage object data for action
+
+
+ private fun startTimer() {
+ // Log.i(TAG, "custom data timer started for " + objectName)
+
+ timer = Timer().schedule(Tools.rand(1000, 5000)) {
+ execMode()
+ }
+ }
+
+ private fun stopTimer() {
+ // Log.i(TAG, "custom data timer stopped for " + objectName)
+ if (timer != null) {
+ timer!!.cancel()
+ }
+ }
+
+ private fun execMode() {
+ val obj = objectsManager.getObjectByName(objectName!!)!!
+
+ // The return code is not used
+ // As for the default we don't change the value
+ // We don't need anything is for this the ""
+ for (data in obj.datas) {
+ @Suppress("UNUSED_EXPRESSION")
+ when (data.mode){
+ AvPhoneObjectData.Mode.UP -> if (Tools.rand(0, 2000) > 500) data.execMode()
+ AvPhoneObjectData.Mode.DOWN -> if (Tools.rand(0, 2000) > 1500) data.execMode()
+ AvPhoneObjectData.Mode.RANDOM -> if (Tools.rand(0, 2000) > 500) data.execMode()
+ else -> ""
+ }
+
+ }
+ objectsManager.saveOnPref()
+ startTimer()
+ }
+
+ companion object {
+ private val TAG = RunFragment::class.simpleName
+ }
+}
+
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/SettingsActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/SettingsActivity.java
deleted file mode 100644
index ed5ba29..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/SettingsActivity.java
+++ /dev/null
@@ -1,50 +0,0 @@
-package com.sierrawireless.avphone;
-
-import net.airvantage.utils.PreferenceUtils;
-import android.content.SharedPreferences;
-import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
-import android.os.Bundle;
-import android.preference.ListPreference;
-import android.preference.PreferenceActivity;
-import android.preference.PreferenceFragment;
-
-public class SettingsActivity extends PreferenceActivity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();
- }
-
- public static class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener {
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
-
- // Load the preferences from an XML resource
- addPreferencesFromResource(R.xml.preferences);
-
- onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), null);
- }
-
- @Override
- public void onResume() {
- super.onResume();
- getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
- }
-
- @Override
- public void onPause() {
- super.onPause();
- getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
- }
-
- @Override
- public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
- // period
- ListPreference periodPref = (ListPreference) findPreference(PreferenceUtils.PREF_PERIOD_KEY);
- periodPref.setSummary(periodPref.getEntry());
- }
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/activity/AuthorizationActivity.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/AuthorizationActivity.kt
new file mode 100644
index 0000000..21a1642
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/AuthorizationActivity.kt
@@ -0,0 +1,170 @@
+package com.sierrawireless.avphone.activity
+
+import android.annotation.SuppressLint
+import android.annotation.TargetApi
+import android.app.Activity
+import android.content.Intent
+import android.graphics.Bitmap
+import android.os.Bundle
+import android.util.Log
+import android.view.View
+import android.view.View.OnClickListener
+import android.webkit.CookieManager
+import android.webkit.WebResourceRequest
+import android.webkit.WebView
+import android.webkit.WebViewClient
+import android.widget.Button
+import android.widget.RadioGroup
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.auth.Authentication
+import kotlinx.android.synthetic.main.activity_authorization.*
+import net.airvantage.utils.AirVantageClient
+import net.airvantage.utils.AuthenticationUrlParser
+import net.airvantage.utils.PreferenceUtils
+import java.util.*
+
+class AuthorizationActivity : Activity() {
+
+ private val authUrlParser = AuthenticationUrlParser()
+ private var currentServer: PreferenceUtils.Server? = null
+
+
+ private inner class OnHostClickListener (private val server: PreferenceUtils.Server) : OnClickListener {
+
+ override fun onClick(v: View) {
+ if (currentServer != server) {
+ currentServer = server
+ PreferenceUtils.setServer(server, this@AuthorizationActivity)
+ openAuthorizationPage()
+ }
+ }
+ }
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_authorization)
+
+ auth_btn_na.setOnClickListener(OnHostClickListener(PreferenceUtils.Server.NA))
+ auth_btn_eu.setOnClickListener(OnHostClickListener(PreferenceUtils.Server.EU))
+ auth_btn_custom.setOnClickListener(OnHostClickListener(PreferenceUtils.Server.CUSTOM))
+
+ if (PreferenceUtils.isCustomDefined(this)) {
+ val parentRadioGroup = auth_btn_custom.parent as RadioGroup
+ parentRadioGroup.check(auth_btn_custom.id)
+ } else {
+ auth_btn_custom.visibility = Button.GONE
+ }
+
+ openAuthorizationPage()
+ }
+
+
+ @Suppress("DEPRECATION")
+ @SuppressLint("SetJavaScriptEnabled")
+ private fun openAuthorizationPage() {
+
+ val avPhonePrefs = PreferenceUtils.getAvPhonePrefs(this)
+
+ when {
+ avPhonePrefs.usesNA() -> {
+ auth_btn_na.isChecked = true
+ auth_btn_custom.isChecked = false
+ auth_btn_eu.isChecked = false
+ }
+ avPhonePrefs.usesEU() -> {
+ auth_btn_na.isChecked = false
+ auth_btn_custom.isChecked = false
+ auth_btn_eu.isChecked = true
+ }
+ else -> {
+ auth_btn_na.isChecked = false
+ auth_btn_custom.isChecked = true
+ auth_btn_eu.isChecked = false
+ }
+ }
+
+ val serverHost = avPhonePrefs.serverHost
+ val clientId = avPhonePrefs.clientId
+
+ val webview = findViewById(R.id.authorization_webview)
+ webview.settings.javaScriptEnabled = true
+ // attach WebViewClient to intercept the callback url
+ webview.webViewClient = object : WebViewClient() {
+ override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
+ showProgressDialog()
+ super.onPageStarted(view, url, favicon)
+ }
+
+ override fun onPageFinished(view: WebView?, url: String?) {
+ hideProgressDialog()
+ Log.d(TAG, "Loaded " + url.toString() )
+
+ super.onPageFinished(view, url)
+ }
+
+ @TargetApi(24)
+ override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
+ Log.d(TAG, "UrlLoading")
+ val auth = authUrlParser.parseUrl(request.url.toString(), Date())
+
+ if (auth != null) {
+ Log.i(TAG, "Access token: " + auth.accessToken!!)
+ Log.i(TAG, "Expiration date : " + auth.expirationDate!!)
+ sendAuthentication(auth)
+ }
+ return super.shouldOverrideUrlLoading(view, request)
+ }
+
+ @Suppress("OverridingDeprecatedMember")
+ override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
+ Log.d(TAG, "UrlLoading")
+ val auth = authUrlParser.parseUrl(url, Date())
+
+ if (auth != null) {
+ Log.i(TAG, "Access token: " + auth.accessToken!!)
+ Log.i(TAG, "Expiration date : " + auth.expirationDate!!)
+ sendAuthentication(auth)
+ }
+ return super.shouldOverrideUrlLoading(view, url)
+ }
+ }
+ val authUrl = AirVantageClient.buildImplicitFlowURL(serverHost!!, clientId!!)
+ Log.i(TAG, "Auth URL: " + authUrl)
+
+ // The 'authorize' page from AirVantage will store a cookie ;
+ // if this cookie is passed between calls, the 'authorize' page
+ // will not be displayed at all.
+ val cookieManager = CookieManager.getInstance()
+ cookieManager.removeAllCookies(null)
+
+ // Example :
+ // https://na.airvantage.net/api/oauth/authorize?client_id=54d4faa5343d49fba03f2a2ec1f210b9&response_type=token&redirect_uri=oauth://airvantage
+ webview.loadUrl(authUrl)
+ progressBar.visibility = View.GONE
+ }
+
+ private fun showProgressDialog() {
+ progressBar.visibility = View.VISIBLE
+ }
+
+ private fun hideProgressDialog() {
+ progressBar.visibility = View.GONE
+ }
+
+ private fun sendAuthentication(auth: Authentication?) {
+ val resultIntent = Intent()
+
+ resultIntent.putExtra(AUTHENTICATION_TOKEN, auth!!.accessToken)
+ resultIntent.putExtra(AUTHENTICATION_EXPIRATION_DATE, auth.expirationDate!!.time)
+
+ setResult(Activity.RESULT_OK, resultIntent)
+ finish()
+ }
+
+ companion object {
+ const val AUTHENTICATION_TOKEN = "token"
+ const val AUTHENTICATION_EXPIRATION_DATE = "expirationDate"
+ const val REQUEST_AUTHORIZATION = 1
+ private val TAG = AuthorizationActivity::class.simpleName
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/activity/MainActivity.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/MainActivity.kt
new file mode 100644
index 0000000..8597a59
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/MainActivity.kt
@@ -0,0 +1,858 @@
+package com.sierrawireless.avphone.activity
+
+import android.Manifest
+import android.annotation.SuppressLint
+import android.app.ActivityManager
+import android.app.AlarmManager
+import android.app.Fragment
+import android.app.PendingIntent
+import android.content.*
+import android.content.SharedPreferences.OnSharedPreferenceChangeListener
+import android.content.pm.PackageManager
+import android.content.res.Configuration
+import android.net.Uri
+import android.os.Bundle
+import android.os.Handler
+import android.os.IBinder
+import android.os.SystemClock
+import android.preference.PreferenceManager
+import android.support.v4.app.ActivityCompat
+import android.support.v4.app.FragmentActivity
+import android.support.v4.app.FragmentManager
+import android.support.v4.content.ContextCompat
+import android.support.v4.widget.DrawerLayout
+import android.support.v7.app.ActionBarDrawerToggle
+import android.util.Log
+import android.view.MenuItem
+import android.widget.ListView
+import com.crashlytics.android.Crashlytics
+import com.crashlytics.android.ndk.CrashlyticsNdk
+import com.sierrawireless.avphone.*
+import com.sierrawireless.avphone.adapter.MenuAdapter
+import com.sierrawireless.avphone.adapter.MenuEntry
+import com.sierrawireless.avphone.adapter.MenuEntryType
+import com.sierrawireless.avphone.auth.Authentication
+import com.sierrawireless.avphone.auth.AuthenticationManager
+import com.sierrawireless.avphone.listener.CustomLabelsListener
+import com.sierrawireless.avphone.listener.LoginListener
+import com.sierrawireless.avphone.listener.MonitorServiceListener
+import com.sierrawireless.avphone.service.MonitorServiceManager
+import com.sierrawireless.avphone.service.MonitoringService
+import com.sierrawireless.avphone.service.MonitoringService.ServiceBinder
+import com.sierrawireless.avphone.task.*
+import com.sierrawireless.avphone.tools.DeviceInfo
+import io.fabric.sdk.android.Fabric
+import kotlinx.android.synthetic.main.activity_main.*
+import net.airvantage.model.User
+import net.airvantage.utils.PreferenceUtils
+import org.jetbrains.anko.alert
+import org.jetbrains.anko.longToast
+import java.util.*
+
+/**
+ * The main activity, handling drawer and Fragments
+ */
+class MainActivity : FragmentActivity(), LoginListener, AuthenticationManager, OnSharedPreferenceChangeListener, MonitorServiceManager, CustomLabelsManager, SyncWithAvListener {
+ override var monitoringService: MonitoringService? = null
+ private var objectName: String? = null
+ internal var startObjectName: String? = null
+
+ private var alarmManager: AlarmManager? = null
+ private var taskFactory: IAsyncTaskFactory? = null
+ override var authentication: Authentication? = null
+ set(value) {
+ field = value
+ }
+ private var prefs: SharedPreferences? = null
+
+ internal var boundToMonitoringService = false
+ private var monitoringServiceListener: MonitorServiceListener? = null
+
+ private var customLabelsListener: CustomLabelsListener? = null
+
+ private var drawerToggle: ActionBarDrawerToggle? = null
+
+ private var configureFragment: ConfigureFragment? = null
+ private var homeFragment: HomeFragment? = null
+ private var runFragment: ArrayList? = null
+
+ internal var lastPosition = 0
+ internal var stopped = false
+
+ private var serviceSendData: Boolean? = false
+ internal lateinit var objectsManager: ObjectsManager
+ var user: User? = null
+ private var fragmentsMapping = HashMap()
+ internal var fragmentsList: ArrayList? = null
+
+ override val isLogged: Boolean
+ get() = this.authentication != null && !this.authentication!!.isExpired(Date())
+
+ private var connection: ServiceConnection = object : ServiceConnection {
+
+ override fun onServiceConnected(arg0: ComponentName, binder: IBinder) {
+ monitoringService = (binder as ServiceBinder).service
+
+ if (monitoringServiceListener != null) {
+ runOnUiThread {
+ monitoringServiceListener!!.onServiceStarted(monitoringService!!)
+ }
+ }
+
+ }
+
+ override fun onServiceDisconnected(arg0: ComponentName) {
+ boundToMonitoringService = false
+ }
+ }
+
+ val systemUid: String?
+ get() = prefs!!.getString("systemUid", null)
+
+ var systemSerial: String?
+ get() = prefs!!.getString(PREFERENCE_SYSTEM_SERIAL, null)
+ @SuppressLint("DefaultLocale")
+ set(serial) = prefs!!.edit().putString(PREFERENCE_SYSTEM_SERIAL, serial!!.toUpperCase()).apply()
+
+ val systemName: String?
+ get() = prefs!!.getString(PREFERENCE_SYSTEM_NAME, null)
+
+ private fun buildFragmentList(): ArrayList {
+ val tmp = ArrayList()
+ if (user != null) {
+ tmp.add(MenuEntry("LOGGED AS", MenuEntryType.TITLE))
+ tmp.add(MenuEntry(user!!.name!!, MenuEntryType.USER, drawable = ContextCompat.getDrawable(this, R.drawable.ic_user)))
+ tmp.add(MenuEntry(user!!.profile!!.name!!, MenuEntryType.USER, drawable = ContextCompat.getDrawable(this, R.drawable.ic_group)))
+ tmp.add(MenuEntry(user!!.company!!.name!!, MenuEntryType.USER, drawable = ContextCompat.getDrawable(this, R.drawable.ic_departement)))
+ tmp.add(MenuEntry(user!!.server!!, MenuEntryType.USER, drawable = ContextCompat.getDrawable(this, R.drawable.ic_domain)))
+ }
+ tmp.add(MenuEntry("SIMULATED OBJECTS", MenuEntryType.TITLE, button = true))
+ objectsManager.objects.mapTo(tmp) {
+ if (it.name != null) {
+ MenuEntry(it.name!!, MenuEntryType.COMMAND, drawable = ContextCompat.getDrawable(this, R.drawable.ic_object))
+ }else{
+ MenuEntry("KO", MenuEntryType.COMMAND, drawable = ContextCompat.getDrawable(this, R.drawable.ic_object))
+ }
+ }
+ // tmp.add(MenuEntry(FRAGMENT_CONFIGURE, MenuEntryType.COMMAND))
+
+ //tmp.add(FRAGMENT_SETTINGS);
+ tmp.add(MenuEntry("NEED HELP", MenuEntryType.TITLE))
+ tmp.add(MenuEntry(FRAGMENT_FAQ, MenuEntryType.COMMAND))
+ tmp.add(MenuEntry("", MenuEntryType.TITLE))
+ tmp.add(MenuEntry(FRAGMENT_SETTINGS, MenuEntryType.COMMAND))
+ if (isLogged) {
+ tmp.add(MenuEntry(FRAGMENT_LOGOUT, MenuEntryType.COMMAND))
+ } else {
+ tmp.add(MenuEntry(FRAGMENT_LOGIN, MenuEntryType.COMMAND))
+ }
+ return tmp
+ }
+
+ override fun setCustomLabelsListener(listener: CustomLabelsListener) {
+ this.customLabelsListener = listener
+ }
+
+ //Get user
+ private fun syncGetUser(auth: Authentication?) {
+
+ val avPhonePrefs = PreferenceUtils.getAvPhonePrefs(this)
+
+ val getUserTask = taskFactory!!.getUserTak(avPhonePrefs.serverHost!!, auth!!.accessToken!!)
+
+ getUserTask.addProgressListener { result ->
+ if (!result.isError) {
+ user = result.user
+ user!!.server = avPhonePrefs.serverHost
+ loadMenu(true)
+ }else{
+ if (! stopped ) {
+ if (result.error!!.errorParameters.size == 1 && result.error!!.errorParameters[0] == "No Connection") {
+ stopped = true
+ alert("You don't have any data connection. The application will be stopped", "Alert") {
+ positiveButton("YES") {
+ finish()
+ }
+ }.show()
+ }else{
+ logout()
+ }
+ }
+ }
+ }
+ val params = GetUserParams()
+ getUserTask.execute(params)
+ }
+
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ instance = this
+ // Initialization og Object Manager
+ objectsManager = ObjectsManager.getInstance()
+ objectsManager.init(this)
+ super.onCreate(savedInstanceState)
+ Fabric.with(this, Crashlytics(), CrashlyticsNdk())
+
+ setContentView(R.layout.activity_main)
+ prefs = PreferenceManager.getDefaultSharedPreferences(this)
+ prefs!!.registerOnSharedPreferenceChangeListener(this)
+
+ //Auth is set here if exist
+ readAuthenticationFromPreferences()
+
+ taskFactory = AsyncTaskFactory(this@MainActivity)
+ if (isLogged) {
+ if (user == null) {
+ syncGetUser(authentication)
+ }
+ }
+
+ loadMenu(true)
+
+ left_drawer.setOnItemClickListener { _, _, position, _ -> selectItem(position) }
+
+ alarmManager = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager
+
+ drawerToggle = ActionBarDrawerToggle(this, drawer_layout, R.string.drawer_open,
+ R.string.drawer_close)
+ drawer_layout!!.addDrawerListener(drawerToggle!!)
+
+ // Verify Permission
+
+ when {
+ ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED -> {
+ Log.d(TAG, "Ask for READ PHONE STATE")
+ ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.READ_PHONE_STATE), 1)
+ }
+ ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED -> {
+ Log.d(TAG, "Ask for COARSE LOCATION STATE")
+ ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 2)
+ }
+ ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED -> {
+ Log.d(TAG, "Ask for FINE LOCATION STATE")
+ ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 3)
+ }
+ }
+ }
+
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array, grantResults: IntArray) {
+ when (requestCode) {
+ 1 -> {
+ if (grantResults.isNotEmpty()) {
+
+ if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
+
+ Log.w(TAG, "onRequestPermissionsResult: READ_PHONE_STATE answer ko")
+ longToast("Permission not granted please grant permission")
+ } else {
+ Log.d(TAG, " for READ PHONE STATE ok")
+ if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ Log.d(TAG, "Ask for COARSE LOCATION STATE")
+ ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), 2)
+ } else if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
+ Log.d(TAG, "Ask for FINE LOCATION STATE")
+ ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 3)
+ }
+ }
+ }
+ }
+ 2 -> {
+ if (grantResults.isNotEmpty()) {
+
+ if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
+
+ Log.w(TAG, "onRequestPermissionsResult: ACCESS_COARSE_LOCATION answer ko")
+ longToast("Permission not granted please grant permission")
+ } else {
+ Log.d(TAG, " for COARSE LOCATION ok")
+ if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ) {
+ Log.d(TAG, "Ask for FINE LOCATION STATE")
+ ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), 3)
+ }
+ }
+ }
+ }
+ 3 -> {
+ if (grantResults.isNotEmpty()) {
+ if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
+
+ Log.w(TAG, "onRequestPermissionsResult: answer ACCESS_FINE_LOCATION ko")
+ longToast("Permission not granted please grant permission")
+ }else{
+ Log.d(TAG, "for FINE LOCATION STATE ok")
+ }
+ }
+ }
+ else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
+ }
+ }
+
+
+ fun loadMenu(changeFragment:Boolean) {
+ fragmentsList = buildFragmentList()
+
+
+ val adapter = MenuAdapter(this, buildFragmentList())
+
+ left_drawer.adapter = adapter
+
+ left_drawer.choiceMode = ListView.CHOICE_MODE_SINGLE
+ // Set the list's click listener
+ left_drawer.invalidateViews()
+
+ if (isLogged) {
+ if (user == null) {
+ syncGetUser(authentication)
+ }
+
+ unlockDrawer()
+ if (isServiceRunning()) {
+ connectToService()
+ }
+ initFragments()
+ if (changeFragment)
+ goLastFragment()
+ } else {
+ lockDrawer()
+ if (isServiceRunning()) {
+ // The token is probably expired.
+ // We stop the service since the "stop" button is not available anymore.
+ this.stopMonitoringService()
+ }
+ initFragments()
+ if (changeFragment)
+ goHomeFragment()
+ }
+ }
+
+ override fun onResume() {
+ super.onResume()
+ left_drawer.requestFocusFromTouch()
+ left_drawer.setItemChecked(lastPosition, true)
+ left_drawer.setSelection(lastPosition)
+ left_drawer.refreshDrawableState()
+
+ }
+
+ override fun onPostCreate(savedInstanceState: Bundle?) {
+ super.onPostCreate(savedInstanceState)
+ drawerToggle!!.syncState()
+ }
+
+ override fun onOptionsItemSelected(item: MenuItem): Boolean {
+ return (drawerToggle!!.onOptionsItemSelected(item)
+ // Or just go with defaults
+ || super.onOptionsItemSelected(item))
+ }
+
+ override fun onConfigurationChanged(newConfig: Configuration) {
+ super.onConfigurationChanged(newConfig)
+ drawerToggle!!.onConfigurationChanged(newConfig)
+ }
+
+ private fun lockDrawer() {
+
+ if (actionBar != null) {
+ actionBar!!.setDisplayHomeAsUpEnabled(false)
+ actionBar!!.setHomeButtonEnabled(false)
+ }
+
+ drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED)
+
+ if (drawerToggle != null) {
+ drawerToggle!!.isDrawerIndicatorEnabled = false
+ }
+ }
+
+ private fun unlockDrawer() {
+ if (actionBar != null) {
+ actionBar!!.setDisplayHomeAsUpEnabled(true)
+ actionBar!!.setHomeButtonEnabled(true)
+ }
+
+ drawer_layout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED)
+
+ if (drawerToggle != null) {
+ drawerToggle!!.isDrawerIndicatorEnabled = true
+ }
+ }
+
+ internal fun readAuthenticationFromPreferences() {
+ this.authentication = PreferenceUtils.readAuthentication(this)
+ }
+
+ override fun onAuthentication(auth: Authentication) {
+
+ this.authentication = auth
+ unlockDrawer()
+
+ saveAuthenticationInPreferences(auth)
+ }
+
+ private fun saveAuthenticationInPreferences(auth: Authentication) {
+ PreferenceUtils.saveAuthentication(this, auth)
+ }
+
+ override fun forgetAuthentication() {
+
+ lockDrawer()
+ PreferenceUtils.resetAuthentication(this)
+ this.authentication = null
+
+ if (this.isServiceRunning()) {
+ this.stopMonitoringService()
+ }
+
+ }
+
+ override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
+
+ if (PreferenceUtils.PREF_SERVER_KEY == key || PreferenceUtils.PREF_CLIENT_ID_KEY == key) {
+
+ this.stopMonitoringService()
+ this.forgetAuthentication()
+
+ } else if (PreferenceUtils.PREF_PERIOD_KEY == key || PreferenceUtils.PREF_PASSWORD_KEY == key) {
+
+ this.restartMonitoringService()
+
+ } else if (key.contains("pref_data_custom")) {
+
+ if (this.customLabelsListener != null) {
+ this.customLabelsListener!!.onCustomLabelsChanged()
+ }
+ }
+ }
+
+ override fun isServiceRunning(name: String?): Boolean {
+ //return serviceSendData;
+
+ val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
+
+ @Suppress("DEPRECATION")
+ return if (name == null) {
+ if (manager.getRunningServices(Integer.MAX_VALUE).any { MonitoringService::class.java.name == it.service.className }) serviceSendData!! else false
+ }else{
+ if (manager.getRunningServices(Integer.MAX_VALUE).any { MonitoringService::class.java.name == it.service.className }) (serviceSendData!! && startObjectName == name) else false
+
+ }
+ }
+
+ override fun isServiceStarted(name: String): Boolean {
+ if (this.objectName == null) {
+ return false
+ }
+ if (this.objectName != name) {
+ return false
+ }
+ //return serviceSendData;
+
+ val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
+
+ @Suppress("DEPRECATION")
+ return manager.getRunningServices(Integer.MAX_VALUE).any { MonitoringService::class.java.name == it.service.className }
+ }
+
+ override fun oneServiceStarted(): Boolean {
+ //return serviceSendData;
+
+ val manager = this.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
+
+ @Suppress("DEPRECATION")
+ return manager.getRunningServices(Integer.MAX_VALUE).any { MonitoringService::class.java.name == it.service.className }
+
+ }
+
+ private fun connectToService() {
+ val intent = Intent(this, MonitoringService::class.java)
+ boundToMonitoringService = this.bindService(intent, connection, Context.BIND_AUTO_CREATE)
+ }
+
+ private fun disconnectFromService() {
+ if (boundToMonitoringService) {
+ this.unbindService(connection)
+ boundToMonitoringService = false
+ if (monitoringServiceListener != null) {
+ monitoringServiceListener!!.onServiceStopped(monitoringService!!)
+ }
+ }
+ }
+
+ override fun cancel() {
+ monitoringService?.cancel()
+ }
+ override fun start() {
+ monitoringService?.start()
+ }
+
+ override fun sendAlarmEvent(on:Boolean):Boolean {
+ //if (boundToMonitoringService && monitoringService != null) {
+ return monitoringService!!.sendAlarmEvent(on)
+ // }
+ }
+
+ override fun startMonitoringService(name: String) {
+ this.objectName = name
+ val avPrefs = PreferenceUtils.getAvPhonePrefs(this)
+
+ val intent = Intent(this, MonitoringService::class.java)
+ intent.putExtra(MonitoringService.DEVICE_ID, DeviceInfo.getUniqueId(this))
+ intent.putExtra(MonitoringService.SERVER_HOST, avPrefs.serverHost)
+ intent.putExtra(MonitoringService.PASSWORD, avPrefs.password)
+ intent.putExtra(MonitoringService.CONNECT, false)
+ intent.putExtra(MonitoringService.OBJECT_NAME, name)
+
+ val pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_CANCEL_CURRENT)
+ // registering our pending intent with alarm manager
+ alarmManager!!.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent)
+
+ connectToService()
+ }
+
+ internal fun setAlarm(timer:Int?) {
+ val avPrefs = PreferenceUtils.getAvPhonePrefs(this)
+ val intent = Intent(this, MonitoringService::class.java)
+ Log.d(TAG, "Set intent")
+ intent.putExtra(MonitoringService.DEVICE_ID, DeviceInfo.getUniqueId(this))
+ intent.putExtra(MonitoringService.SERVER_HOST, avPrefs.serverHost)
+ intent.putExtra(MonitoringService.PASSWORD, avPrefs.password)
+ intent.putExtra(MonitoringService.CONNECT, true)
+ val pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_CANCEL_CURRENT)
+ // registering our pending intent with alarm manager
+
+ val wait = if (timer == null) {
+ SystemClock.elapsedRealtime() +(Integer.valueOf(avPrefs.period)!! * 60 * 1000).toLong()
+ }else {
+ SystemClock.elapsedRealtime() + 100
+ }
+ alarmManager!!.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, wait, pendingIntent)
+ }
+
+ override fun startSendData(name: String):Boolean {
+ if (startObjectName == null || name == startObjectName!!) {
+ setAlarm(0)
+ startObjectName = name
+ serviceSendData = true
+ }else{
+ alert("A run already exist for $startObjectName.", "Alert") {
+ positiveButton("OK") {
+
+ }
+ }.show()
+ return false
+ }
+ return true
+ }
+
+ override fun stopSendData() {
+ val intent = Intent(this, MonitoringService::class.java)
+ val pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_CANCEL_CURRENT)
+ alarmManager!!.cancel(pendingIntent)
+ serviceSendData = false
+ startObjectName = null
+ }
+
+ override fun stopMonitoringService() {
+ val intent = Intent(this, MonitoringService::class.java)
+ val pendingIntent = PendingIntent.getService(this, 0, intent,
+ PendingIntent.FLAG_CANCEL_CURRENT)
+ alarmManager!!.cancel(pendingIntent)
+ this.stopService(intent)
+
+ disconnectFromService()
+ }
+
+ private fun restartMonitoringService() {
+ if (objectName != null) {
+ stopMonitoringService()
+ startMonitoringService(objectName!!)
+ }
+ }
+
+ public override fun onDestroy() {
+ super.onDestroy()
+ disconnectFromService()
+ }
+
+ override fun setMonitoringServiceListener(listener: MonitorServiceListener) {
+ this.monitoringServiceListener = listener
+ }
+
+ @SuppressLint("DefaultLocale")
+ override fun invoke(result: SyncWithAvResult) {
+
+ val system = result.system ?: return
+ prefs!!.edit().putString("systemUid", system.uid).apply()
+ prefs!!.edit().putString(PREFERENCE_SYSTEM_NAME, system.name).apply()
+
+ val user = result.user
+ prefs!!.edit().putString(PREFERENCE_USER_UID, user!!.uid).apply()
+ prefs!!.edit().putString(PREFERENCE_USER_NAME, user.name).apply()
+
+ val deviceSerial = DeviceInfo.generateSerial(user.uid!!)
+ prefs!!.edit().putString(PREFERENCE_SYSTEM_SERIAL, deviceSerial).apply()
+
+ }
+
+ private fun clearStack() {
+ //Here we are clearing back stack fragment entries
+ fragmentManager.popBackStack("HOME", FragmentManager.POP_BACK_STACK_INCLUSIVE)
+// val backStackEntry = fragmentManager.backStackEntryCount
+// if (backStackEntry > 0) {
+// for (i in 0 until backStackEntry) {
+// fragmentManager.popBackStackImmediate()
+// }
+// }
+
+ }
+
+
+ override fun onBackPressed() {
+ if (isLogged) {
+ super.onBackPressed()
+ }
+ }
+
+ /**
+ * Swaps fragments in the main content view
+ */
+ private fun logout() {
+ val avPhonePrefs = PreferenceUtils.getAvPhonePrefs(this)
+
+ // Already logout if authentication is null
+ if (authentication == null) {
+ return
+ }
+
+ val accessToken = authentication!!.accessToken
+
+ val logoutTask = taskFactory!!.logoutTask(avPhonePrefs.serverHost!!, accessToken!!)
+
+ logoutTask.execute()
+ try {
+ logoutTask.get()
+ } catch (e: Exception) {
+ Log.w(TAG, "Exception while logging out")
+ Crashlytics.logException(e)
+ } finally {
+ forgetAuthentication()
+
+ clearStack()
+ //fragmentManager.popBackStackImmediate(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
+
+ // In this case we have no menu
+ loadMenu(true)
+
+ }
+ }
+
+ private fun selectItem(position: Int) {
+
+ val fragment = getFragment(position)
+ val entry = fragmentsList!![position]
+ if (fragment == null) {
+ //No item check if the position is valid
+ if (entry.name == FRAGMENT_FAQ) {
+ val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://source.sierrawireless.com/airvantage/av/avphone_faq/"))
+ startActivity(browserIntent)
+ left_drawer.setSelection(lastPosition)
+ drawer_layout.closeDrawer(left_drawer)
+ }
+ return
+ }
+ if (entry.name == FRAGMENT_LOGOUT) {
+
+ alert("Are you sure ?","Logout") {
+ positiveButton("YES") {
+ logout()
+ }
+ negativeButton("NO") {
+ drawer_layout.closeDrawer(left_drawer)
+
+ }
+ }.show()
+ return
+ }
+ if (entry.type == MenuEntryType.COMMAND) {
+ // We have not selected this fragment now do it
+ if (lastPosition != position) {
+ // Insert the fragment by replacing any existing fragment
+ fragmentManager
+ .beginTransaction()
+ .replace(R.id.content_frame, fragment)
+ .addToBackStack(null)
+ .commit()
+ // Highlight the selected item, update the title, and close the drawer
+ left_drawer.setItemChecked(position, true)
+ title = entry.name
+ left_drawer.setSelection(position)
+ lastPosition = position
+ left_drawer.invalidateViews()
+ }
+ drawer_layout.closeDrawer(left_drawer)
+ }
+ }
+
+ private fun goHomeFragment() {
+ val fragment = if (fragmentsMapping.containsKey(FRAGMENT_LOGIN)) fragmentsMapping[FRAGMENT_LOGIN] else null
+ goFragment(fragment!!, FRAGMENT_LOGIN)
+ }
+
+
+ fun goLastFragment() {
+ var fragmentName = objectsManager.objects[objectsManager.current].name
+ var fragment = if (fragmentsMapping.containsKey(fragmentName)) fragmentsMapping[fragmentName] else null
+ if (fragment == null) {
+ fragmentName = objectsManager.objects[0].name
+ fragment = if (fragmentsMapping.containsKey(fragmentName)) fragmentsMapping[fragmentName] else null
+ }
+
+ goFragment(fragment!!, fragmentName!!)
+ }
+
+ private fun goFragment(fragment:Fragment, fragmentName:String) {
+
+ var position:Int? = 0
+ for ((current, entry) in fragmentsList!!.withIndex()) {
+ if (entry.name == fragmentName) {
+ position = current
+ }
+ }
+
+ // Insert the fragment by replacing any existing fragment
+ try {
+
+ val backStackEntry = fragmentManager.backStackEntryCount
+
+ if (backStackEntry == 0) {
+ val homeFragment = fragmentsMapping[FRAGMENT_LOGIN]
+ if (homeFragment != null) {
+ Handler().post({
+ fragmentManager
+ .beginTransaction()
+ .add(R.id.content_frame, homeFragment)
+ .addToBackStack("HOME")
+ .commitAllowingStateLoss()
+ })
+ }
+ }
+
+ Handler().post({
+ fragmentManager
+ .beginTransaction()
+ .replace(R.id.content_frame, fragment)
+ .addToBackStack(null)
+ .commitAllowingStateLoss()
+ })
+ // Highlight the selected item, update the title, and close the drawer
+ left_drawer.setItemChecked(position!!, true)
+ title = fragmentsList!![position].name
+ left_drawer.setSelection(position)
+ drawer_layout.closeDrawer(left_drawer)
+ lastPosition = position
+ }catch(e:IllegalStateException){
+ Log.e(TAG, "GO last fragment CATCH************************", e)
+ }
+ }
+
+
+ fun goConfigureFragment() {
+ val fragment = fragmentsMapping[FRAGMENT_CONFIGURE]
+ // Insert the fragment by replacing any existing fragment
+ fragmentManager
+ .beginTransaction()
+ .replace(R.id.content_frame, fragment)
+ .addToBackStack(null)
+ .commit()
+ var position:Int? = null
+ fragmentsList!!.forEachIndexed {
+ index, menuEntry -> if (menuEntry.name == FRAGMENT_CONFIGURE) {
+ position = index
+ }
+ }
+
+ if (position != null) {
+ // Highlight the selected item, update the title, and close the drawer
+ left_drawer.setItemChecked(position!!, true)
+ left_drawer.setItemChecked(position!!, true)
+ title = fragmentsList!![position!!].name
+ left_drawer.setSelection(position!!)
+ lastPosition = position!!
+ }
+ drawer_layout.closeDrawer(left_drawer)
+
+
+ }
+
+ private fun initFragments(): Map {
+
+ if (configureFragment == null) {
+ configureFragment = ConfigureFragment()
+ configureFragment!!.setTaskFactory(taskFactory!!)
+ configureFragment!!.syncListener = this
+ }
+
+ if (homeFragment == null) {
+ homeFragment = HomeFragment()
+ homeFragment!!.setTaskFactory(taskFactory!!)
+ }
+
+ runFragment = ArrayList()
+
+ var tmp: RunFragment
+ for (obj in objectsManager.objects) {
+ tmp = RunFragment()
+ tmp.setTaskFactory(taskFactory!!)
+ if (obj.name != null) {
+ tmp.setObjectName(obj.name!!)
+ runFragment!!.add(tmp)
+ }
+ }
+
+
+ fragmentsMapping = HashMap()
+ fragmentsMapping[FRAGMENT_CONFIGURE] = configureFragment!!
+ if (isLogged) {
+ fragmentsMapping[FRAGMENT_LOGOUT] = homeFragment!!
+ } else {
+ fragmentsMapping[FRAGMENT_LOGIN] = homeFragment!!
+ }
+ fragmentsMapping[FRAGMENT_SETTINGS] = SettingsActivity.SettingsFragment()
+ for ((pos, obj) in objectsManager.objects.withIndex()) {
+ fragmentsMapping[obj.name!!] = runFragment!![pos]
+ }
+
+ return fragmentsMapping
+ }
+
+ private fun getFragment(fragmentPosition: Int): Fragment? {
+ val fragmentName = fragmentsList!![fragmentPosition].name
+ val fragmentMap = initFragments()
+ return if (fragmentMap.containsKey(fragmentName)) fragmentMap[fragmentName] else null
+ }
+
+ companion object {
+ private const val PREFERENCE_SYSTEM_NAME = "systemName"
+ private const val PREFERENCE_SYSTEM_SERIAL = "systemSerial"
+ private const val PREFERENCE_USER_NAME = "userName"
+ private const val PREFERENCE_USER_UID = "userUid"
+
+ private const val FRAGMENT_LOGOUT = "Logout"
+
+ private const val FRAGMENT_LOGIN = "Login"
+ private const val FRAGMENT_CONFIGURE = "Add/Modify/Delete"
+ private const val FRAGMENT_SETTINGS = "Settings"
+ private const val FRAGMENT_FAQ = "FAQ"
+
+
+
+ @SuppressLint("StaticFieldLeak")
+ internal lateinit var instance: MainActivity
+
+ private val TAG = MainActivity::class.simpleName
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/activity/ObjectConfigureActivity.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/ObjectConfigureActivity.kt
new file mode 100644
index 0000000..3ae8a9a
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/ObjectConfigureActivity.kt
@@ -0,0 +1,153 @@
+package com.sierrawireless.avphone.activity
+
+import android.annotation.SuppressLint
+import android.app.Activity
+import android.content.Context
+import android.content.Intent
+import android.os.Bundle
+import android.view.View
+import android.widget.AdapterView
+import com.sierrawireless.avphone.ConfigureFragment
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.adapter.ObjectDataAdapter
+import com.sierrawireless.avphone.model.AvPhoneObject
+import kotlinx.android.synthetic.main.activity_object_configure.*
+import org.jetbrains.anko.alert
+import java.util.*
+
+class ObjectConfigureActivity : Activity() {
+ internal var objectsManager: ObjectsManager = ObjectsManager.getInstance()
+ private var menu: ArrayList = ArrayList()
+ private var position: Int = 0
+ private var add = false
+ internal var obj: AvPhoneObject? = null
+
+ private var context: Context? = null
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_object_configure)
+ instance = this
+
+ objectsManager = ObjectsManager.getInstance()
+
+ context = this
+
+
+
+
+
+ val intent = intent
+ position = intent.getIntExtra(ConfigureFragment.INDEX, -1)
+ add = position == -1
+
+ cancel.setOnClickListener {
+ cancel()
+ }
+
+ save.setOnClickListener {
+ if (objectNameEdit.visibility != View.GONE || add) {
+ obj!!.name = objectNameEdit.text.toString()
+ }
+ if (obj!!.name!!.isEmpty()) {
+ // open an alert to force to define the nane before to add value
+ alert(getString(R.string.objectSaveConfigure), getString(R.string.alert)) {
+ positiveButton("OK") {
+ }
+ }.show()
+ }else {
+ obj!!.datas
+ .filter { it.isInteger }
+ .forEach { it.current = it.defaults.toInt() }
+
+ objectsManager.save()
+ val i = Intent()
+ i.putExtra(ConfigureFragment.POS, position)
+ setResult(Activity.RESULT_OK, i)
+ finish()
+ }
+ }
+
+
+ listView.onItemClickListener = AdapterView.OnItemClickListener { _, view, i, _ ->
+ if (add)
+ obj!!.name = objectNameEdit.text.toString()
+ if (obj!!.name!!.isEmpty()) {
+ // open an alert to force to define the nane before to add value
+ alert(getString(R.string.nameBeforeAddObjectConfigure), getString(R.string.alert)) {
+ positiveButton("OK") {
+ }
+ }.show()
+ } else {
+ val lIntent = Intent(view.context, ObjectDataActivity::class.java)
+ lIntent.putExtra(OBJECT_POSITION, position)
+ lIntent.putExtra(OBJECT_NAME, obj!!.name)
+ lIntent.putExtra(DATA_POSITION, i)
+ if (i == menu.size - 1) {
+ lIntent.putExtra(ADD, true)
+ } else {
+ lIntent.putExtra(ADD, false)
+ }
+ startActivity(lIntent)
+ }
+ }
+
+ }
+
+ private fun cancel() {
+ //reload object from list
+ objectsManager.reload()
+ val i = Intent()
+ setResult(Activity.RESULT_CANCELED, i)
+ finish()
+ }
+
+ override fun onBackPressed() = cancel()
+
+
+ override fun onDestroy() {
+ super.onDestroy()
+ instance = null
+ }
+
+ override fun onResume() {
+ super.onResume()
+ if (position == -1) {
+ obj = AvPhoneObject()
+ obj!!.name = ""
+ titleObject.setText(R.string.add_new_object)
+ objectsManager.objects.add(obj!!)
+ position = objectsManager.objects.size - 1
+ } else {
+ obj = objectsManager.getObjectByIndex(position)
+ if (!add) {
+ nameObject.visibility = View.GONE
+ objectNameEdit.visibility = View.GONE
+ }
+ titleObject.text = obj!!.name
+ }
+ menuGeneration()
+ }
+
+ fun menuGeneration() {
+ menu = ArrayList()
+ for (data in obj!!.datas) {
+ menu.add(data.name)
+ }
+ menu.add(getString(R.string.add_new_data))
+ val adapter = ObjectDataAdapter(this, R.layout.menu_objects, menu)
+
+ listView.adapter = adapter
+ listView.invalidateViews()
+ }
+
+ companion object {
+ var OBJECT_POSITION = "object_pos"
+ var DATA_POSITION = "data_position"
+ var OBJECT_NAME = "name"
+ var ADD = "add"
+ @SuppressLint("StaticFieldLeak")
+ var instance:ObjectConfigureActivity? = null
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/activity/ObjectDataActivity.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/ObjectDataActivity.kt
new file mode 100644
index 0000000..20afda3
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/ObjectDataActivity.kt
@@ -0,0 +1,172 @@
+package com.sierrawireless.avphone.activity
+
+import android.app.Activity
+import android.os.Bundle
+import android.text.TextUtils
+import android.view.View
+import android.widget.AdapterView
+import android.widget.ArrayAdapter
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.model.AvPhoneObject
+import com.sierrawireless.avphone.model.AvPhoneObjectData
+import com.sierrawireless.avphone.tools.Tools
+import kotlinx.android.synthetic.main.activity_object_data.*
+import org.jetbrains.anko.alert
+
+class ObjectDataActivity : Activity(), AdapterView.OnItemSelectedListener {
+
+ internal var objectsManager: ObjectsManager = ObjectsManager.getInstance()
+ private var obj: AvPhoneObject? = null
+ internal var data: AvPhoneObjectData? = null
+ private var objectPosition: Int = 0
+ private var dataPosition: Int = 0
+ private lateinit var objname: String
+ internal var add: Boolean = false
+
+ override fun onCreate(savedInstanceState: Bundle?) {
+ val menuList = arrayOf("None", "Increase indefinitely", "Decrease to zero", "Random")
+
+
+ super.onCreate(savedInstanceState)
+ setContentView(R.layout.activity_object_data)
+ val intent = intent
+ objectPosition = intent.getIntExtra(ObjectConfigureActivity.OBJECT_POSITION, -1)
+ dataPosition = intent.getIntExtra(ObjectConfigureActivity.DATA_POSITION, -1)
+ add = intent.getBooleanExtra(ObjectConfigureActivity.ADD, true)
+ objname = intent.getStringExtra(ObjectConfigureActivity.OBJECT_NAME)
+
+ if (objectPosition == -1 || dataPosition == -1) {
+ return
+ }
+
+
+ objectsManager = ObjectsManager.getInstance()
+ obj = objectsManager.getObjectByIndex(objectPosition)
+
+ // Create an ArrayAdapter using the string array and a default spinner layout
+ val adapter = ArrayAdapter(this,
+ android.R.layout.simple_spinner_item, menuList)
+ // Specify the layout to use when the list of choices appears
+ adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
+ // Apply the adapter to the spinner
+
+ spinner.adapter = adapter
+ spinner.onItemSelectedListener = this
+
+ if (!add) {
+ name.visibility = View.INVISIBLE
+ nameText.visibility = View.GONE
+ data = obj!!.datas[dataPosition]
+ titleMenu.text = data!!.name
+ unitText.setText(data!!.unit)
+ defaultText.setText(data!!.defaults)
+ spinner.setSelection(data!!.modePosition(), false)
+ if (data!!.path != null) {
+ path.setText(data!!.path)
+ }else{
+ path.setText(Tools.buildDefaultPath(objname, dataPosition))
+ // path.setText("default")
+ }
+ } else {
+ titleMenu.setText(R.string.add_new_data)
+ path.setText(Tools.buildDefaultPath(objname, dataPosition))
+ }
+
+ cancelData.setOnClickListener { finish() }
+
+ saveData.setOnClickListener {
+ val mode = AvPhoneObjectData.modeFromPosition(spinner.selectedItemPosition)
+ if (add) {
+ if (!validateEntry()) return@setOnClickListener
+ data = if (!path.text.isEmpty() && path.text.toString() == "default") {
+ AvPhoneObjectData(
+ nameText.text.toString(),
+ unitText.text.toString(),
+ defaultText.text.toString(),
+ mode, "1", null)
+ }else {
+ AvPhoneObjectData(
+ nameText.text.toString(),
+ unitText.text.toString(),
+ defaultText.text.toString(),
+ mode, "1",
+ path.text.toString())
+ }
+ obj!!.datas.add(data!!)
+ } else {
+ if (!validateEntry()) return@setOnClickListener
+ data!!.unit = unitText.text.toString()
+ data!!.defaults = defaultText.text.toString()
+ data!!.mode = mode
+ if (!path.text.isEmpty() && path.text.toString() != "default") {
+ data!!.path = path.text.toString()
+ }else{
+ data!!.path = null
+ }
+ }
+
+ finish()
+ }
+
+ }
+
+ private fun validateEntry():Boolean {
+ val mode = AvPhoneObjectData.modeFromPosition(spinner.selectedItemPosition)
+ if (add) {
+ if (nameText.text.toString().isEmpty()) {
+ alert(getString(R.string.nameOnbjectDataEmpty), getString(R.string.alert)) {
+ positiveButton("OK") {
+ }
+ }.show()
+ return false
+ }
+ }
+ if (mode == AvPhoneObjectData.Mode.RANDOM) {
+ // Is this case we must verify the default entry
+ val defaults = defaultText.text.toString().split(",")
+ if (defaults.size != 2) {
+ alert(getString(R.string.InvalidRandomDefaultComma), getString(R.string.alert)) {
+ positiveButton("OK") {
+ }
+ }.show()
+ return false
+ }
+ if ((!(!defaults[0].isEmpty() && TextUtils.isDigitsOnly(defaults[0]))) or
+ (!(!defaults[1].isEmpty() && TextUtils.isDigitsOnly(defaults[1])))) {
+ alert(
+ getString(R.string.MinMaxRandomDataObject),
+ getString(R.string.alert)
+ ) {
+ positiveButton("OK") {
+ }
+ }.show()
+ return false
+ }
+ }
+ if (mode == AvPhoneObjectData.Mode.DOWN || mode == AvPhoneObjectData.Mode.UP) {
+ // check the default value must be a number
+ if (!(!defaultText.text.toString().isEmpty() && TextUtils.isDigitsOnly(defaultText.text.toString()))) {
+ alert(getString(R.string.InvalidDefaultUpDown), getString(R.string.alert)) {
+ positiveButton("OK") {
+ }
+ }.show()
+ return false
+ }
+ }
+ return true
+ }
+
+ override fun onBackPressed() = finish()
+
+ override fun onItemSelected(parent: AdapterView<*>, view: View,
+ pos: Int, id: Long) {
+ // An item was selected. You can retrieve the selected item using
+ // parent.getItemAtPosition(pos)
+ }
+
+ override fun onNothingSelected(parent: AdapterView<*>) {
+ // Another interface callback
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/activity/SettingsActivity.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/SettingsActivity.kt
new file mode 100644
index 0000000..d5012e5
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/SettingsActivity.kt
@@ -0,0 +1,46 @@
+package com.sierrawireless.avphone.activity
+
+import net.airvantage.utils.PreferenceUtils
+import android.content.SharedPreferences
+import android.content.SharedPreferences.OnSharedPreferenceChangeListener
+import android.os.Bundle
+import android.preference.ListPreference
+import android.preference.PreferenceActivity
+import android.preference.PreferenceFragment
+import com.sierrawireless.avphone.R
+
+class SettingsActivity : PreferenceActivity() {
+
+ public override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ fragmentManager.beginTransaction().replace(android.R.id.content, SettingsFragment()).commit()
+ }
+
+ class SettingsFragment : PreferenceFragment(), OnSharedPreferenceChangeListener {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+
+ // Load the preferences from an XML resource
+ addPreferencesFromResource(R.xml.preferences)
+
+ onSharedPreferenceChanged(preferenceScreen.sharedPreferences, null)
+ }
+
+ override fun onResume() {
+ super.onResume()
+ preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
+ }
+
+ override fun onPause() {
+ super.onPause()
+ preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
+ }
+
+ override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String?) {
+ // period
+ val periodPref = findPreference(PreferenceUtils.PREF_PERIOD_KEY) as ListPreference
+ periodPref.summary = periodPref.entry
+ }
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/TestFragmentActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/TestFragmentActivity.java
similarity index 76%
rename from mainActivity/src/main/java/com/sierrawireless/avphone/TestFragmentActivity.java
rename to mainActivity/src/main/java/com/sierrawireless/avphone/activity/TestFragmentActivity.java
index 85e74f5..7082983 100644
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/TestFragmentActivity.java
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/activity/TestFragmentActivity.java
@@ -1,8 +1,10 @@
-package com.sierrawireless.avphone;
+package com.sierrawireless.avphone.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
+import com.sierrawireless.avphone.R;
+
public class TestFragmentActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle arg0) {
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/MenuAdapter.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/MenuAdapter.kt
new file mode 100644
index 0000000..8e8dac5
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/MenuAdapter.kt
@@ -0,0 +1,88 @@
+package com.sierrawireless.avphone.adapter
+
+import android.app.Activity
+import android.graphics.Color
+import android.graphics.Typeface
+import android.support.v4.content.ContextCompat
+import android.view.View
+import android.view.ViewGroup
+import android.widget.BaseAdapter
+import android.widget.Button
+import android.widget.TextView
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.activity.MainActivity
+import java.util.*
+
+class MenuAdapter internal constructor(private val activity: Activity, var list: ArrayList) : BaseAdapter() {
+ val objectsManager:ObjectsManager? = ObjectsManager.getInstance()
+
+ override fun getCount(): Int {
+ return list.size
+ }
+
+ override fun getItem(position: Int): Any {
+ return list[position]
+ }
+
+ override fun getItemId(position: Int): Long {
+ return 0
+ }
+
+
+ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
+ val lConvertView: View?
+
+
+ val inflater = activity.layoutInflater
+
+
+ val name: TextView
+ lConvertView = convertView ?: inflater.inflate(R.layout.menu_layout, parent, false)
+ val entry = list[position]
+ if (entry.type == MenuEntryType.TITLE) {
+ name = lConvertView!!.findViewById(R.id.text1)
+ name.text = entry.name
+ name.setTypeface(name.typeface, Typeface.BOLD)
+ name.setBackgroundColor(ContextCompat.getColor(lConvertView.context, R.color.navy))
+ name.setTextColor(Color.WHITE)
+ // name.setCompoundDrawablesWithIntrinsicBounds(ContextCompat.getDrawable(lConvertView.context, android.R.drawable.ic_lock_silent_mode), null, null, null)
+
+ } else {
+ name = lConvertView!!.findViewById(R.id.text1)
+ name.text = entry.name
+ if (MainActivity.instance.lastPosition != 0 && position != list.size - 1 && position == MainActivity.instance.lastPosition) {
+ name.setBackgroundColor(Color.LTGRAY)
+ }else {
+ if (entry.type == MenuEntryType.COMMAND) {
+ name.setBackgroundColor(Color.WHITE)
+ }else{
+ name.setTypeface(null, Typeface.ITALIC)
+ name.setBackgroundColor(ContextCompat.getColor(lConvertView.context, R.color.turquoise))
+ }
+ }
+ name.setTextColor(ContextCompat.getColor(lConvertView.context, R.color.navy))
+ if (entry.type == MenuEntryType.USER) {
+ name.setTypeface(null, Typeface.ITALIC)
+ }
+ }
+ if (entry.drawable != null) {
+ name.setCompoundDrawablesWithIntrinsicBounds(entry.drawable, null, null, null)
+ }
+ val menuButton:Button = lConvertView.findViewById(R.id.menu_button)
+
+ menuButton.visibility = if (entry.button) {
+ View.VISIBLE
+ }else{
+ View.GONE
+ }
+ if (entry.button) {
+ menuButton.setOnClickListener {
+ MainActivity.instance.goConfigureFragment()
+ }
+ }
+
+ return lConvertView
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/MenuEntry.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/MenuEntry.kt
new file mode 100644
index 0000000..ac7456b
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/MenuEntry.kt
@@ -0,0 +1,11 @@
+package com.sierrawireless.avphone.adapter
+
+import android.graphics.drawable.Drawable
+
+internal enum class MenuEntryType {
+ TITLE,
+ USER,
+ COMMAND
+}
+
+class MenuEntry internal constructor(var name: String, var type: MenuEntryType, var drawable:Drawable? = null, var button:Boolean = false)
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.kt
new file mode 100644
index 0000000..1f8397b
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.kt
@@ -0,0 +1,70 @@
+package com.sierrawireless.avphone.adapter
+
+import android.app.Activity
+import android.view.View
+import android.view.ViewGroup
+import android.widget.*
+import com.sierrawireless.avphone.ConfigureFragment
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.R
+import java.util.*
+
+
+class ObjectAdapter(private val activity: Activity, private val resource: Int, var list: ArrayList) : BaseAdapter() {
+ private var name: TextView? = null
+
+ private val objectsManager: ObjectsManager = ObjectsManager.getInstance()
+
+ override fun getCount(): Int {
+ return list.size
+ }
+
+ override fun getItem(position: Int): Any {
+ return list[position]
+ }
+
+ override fun getItemId(position: Int): Long {
+ return 0
+ }
+
+
+ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
+ var lConvertView = convertView
+
+
+ val inflater = activity.layoutInflater
+
+ if (convertView == null) {
+
+ lConvertView = inflater.inflate(resource, null)
+
+ name = lConvertView!!.findViewById(R.id.text)
+ }
+ val deleteBtn:ImageButton = lConvertView!!.findViewById(R.id.menuDeleteBtn)
+ val deleteActionBtn: Button = lConvertView.findViewById(R.id.menuDeleteActionBtn)
+ deleteActionBtn.tag = position
+ deleteBtn.setOnClickListener {
+ deleteBtn.visibility = View.GONE
+ deleteActionBtn.visibility = View.VISIBLE
+ deleteActionBtn.setOnClickListener{
+ val objectsManager = ObjectsManager.getInstance()
+ val lPosition = it.tag as Int
+ //delete
+ objectsManager.setSavedPosition(lPosition)
+ ConfigureFragment.instance!!.delete()
+ ConfigureFragment.instance!!.delete = ConfigureFragment.Mode.DELETE
+
+ }
+ }
+
+ if (position == objectsManager.current) {
+ deleteBtn.visibility = View.GONE
+ } else {
+ deleteBtn.visibility = View.VISIBLE
+ }
+ name!!.text = list[position]
+
+ return lConvertView
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectDataAdapter.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectDataAdapter.kt
new file mode 100644
index 0000000..feeeff0
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectDataAdapter.kt
@@ -0,0 +1,84 @@
+package com.sierrawireless.avphone.adapter
+
+import android.app.Activity
+import android.support.v4.content.ContextCompat
+import android.view.View
+import android.view.ViewGroup
+import android.widget.BaseAdapter
+import android.widget.Button
+import android.widget.ImageButton
+import android.widget.TextView
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.activity.ObjectConfigureActivity
+import java.util.*
+
+
+class ObjectDataAdapter(private val activity: Activity, private val resource: Int, var list: ArrayList) : BaseAdapter() {
+ private var name: TextView? = null
+
+ override fun getCount(): Int {
+ return list.size
+ }
+
+ override fun getItem(position: Int): Any {
+ return list[position]
+ }
+
+ override fun getItemId(position: Int): Long {
+ return 0
+ }
+
+ override fun getViewTypeCount(): Int {
+ // menu type count
+ return 2
+ }
+
+ override fun getItemViewType(position: Int): Int {
+ // current menu type
+ // The last item must not be deleted
+ return if (position == list.size - 1) {
+ 1
+ } else {
+ 0
+ }
+ }
+
+
+ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
+ var lConvertView = convertView
+
+
+ val inflater = activity.layoutInflater
+
+ if (convertView == null) {
+
+ lConvertView = inflater.inflate(resource, null)
+
+ name = lConvertView!!.findViewById(R.id.text)
+ }
+
+ val deleteBtn: ImageButton = lConvertView!!.findViewById(R.id.menuDeleteBtn)
+
+ if (position == list.size - 1) {
+ deleteBtn.visibility = View.GONE
+ name!!.setCompoundDrawablesWithIntrinsicBounds(null, null, ContextCompat.getDrawable(lConvertView.context, R.drawable.ic_add_data),null)
+ }else {
+ @Suppress("NAME_SHADOWING")
+ val deleteBtn: ImageButton = lConvertView.findViewById(R.id.menuDeleteBtn)
+ val deleteActionBtn: Button = lConvertView.findViewById(R.id.menuDeleteActionBtn)
+ deleteActionBtn.tag = position
+ deleteBtn.setOnClickListener {
+ deleteBtn.visibility = View.GONE
+ deleteActionBtn.visibility = View.VISIBLE
+ deleteActionBtn.setOnClickListener {
+ ObjectConfigureActivity.instance!!.obj!!.datas.removeAt(position)
+ ObjectConfigureActivity.instance!!.menuGeneration()
+ }
+ }
+ }
+
+ name!!.text = list[position]
+
+ return lConvertView
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.kt
new file mode 100644
index 0000000..7a6caf4
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.kt
@@ -0,0 +1,48 @@
+package com.sierrawireless.avphone.adapter
+
+import android.app.Activity
+import android.view.View
+import android.view.ViewGroup
+import android.widget.BaseAdapter
+import android.widget.TextView
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.tools.Tools
+import java.util.*
+
+class RunListViewAdapter(private val activity: Activity, var list: ArrayList>) : BaseAdapter() {
+ private var name: TextView? = null
+ private var value: TextView? = null
+
+ override fun getCount(): Int {
+ return list.size
+ }
+
+ override fun getItem(position: Int): Any {
+ return list[position]
+ }
+
+ override fun getItemId(position: Int): Long {
+ return 0
+ }
+
+
+ override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
+ var lConvertView = convertView
+
+ val inflater = activity.layoutInflater
+
+ if (convertView == null) {
+
+ lConvertView = inflater.inflate(R.layout.run_column_row, parent, false)
+
+ name = lConvertView!!.findViewById(R.id.name)
+ value = lConvertView.findViewById(R.id.value)
+ }
+
+ val map = list[position]
+ name!!.text = map[Tools.NAME]
+ value!!.text = map[Tools.VALUE]
+
+ return lConvertView!!
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthUtils.java b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthUtils.java
deleted file mode 100644
index 396df51..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthUtils.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.sierrawireless.avphone.auth;
-
-import java.util.Date;
-
-import com.sierrawireless.avphone.AuthorizationActivity;
-
-import android.app.Activity;
-import android.content.Intent;
-
-public class AuthUtils {
-
- public static Authentication activityResultAsAuthentication(int requestCode, int resultCode, Intent data) {
- Authentication res = null;
- switch (requestCode) {
- case (AuthorizationActivity.REQUEST_AUTHORIZATION): {
- if (resultCode == Activity.RESULT_OK) {
- String accessToken = data.getStringExtra(AuthorizationActivity.AUTHENTICATION_TOKEN);
- long expiresAtMs = data.getLongExtra(AuthorizationActivity.AUTHENTICATION_EXPIRATION_DATE, 0);
- res = new Authentication();
- res.setAccessToken(accessToken);
- res.setExpirationDate(new Date(expiresAtMs));
- }
- break;
- }
- }
- return res;
- }
-
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthUtils.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthUtils.kt
new file mode 100644
index 0000000..c4d440d
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthUtils.kt
@@ -0,0 +1,29 @@
+package com.sierrawireless.avphone.auth
+
+import java.util.Date
+
+import com.sierrawireless.avphone.activity.AuthorizationActivity
+
+import android.app.Activity
+import android.content.Intent
+
+object AuthUtils {
+
+ fun activityResultAsAuthentication(requestCode: Int, resultCode: Int, data: Intent): Authentication? {
+ var res: Authentication? = null
+ when (requestCode) {
+ AuthorizationActivity.REQUEST_AUTHORIZATION -> {
+ if (resultCode == Activity.RESULT_OK) {
+ val accessToken = data.getStringExtra(AuthorizationActivity.AUTHENTICATION_TOKEN)
+ val expiresAtMs = data.getLongExtra(AuthorizationActivity.AUTHENTICATION_EXPIRATION_DATE, 0)
+ res = Authentication()
+ res.accessToken = accessToken
+ res.expirationDate = Date(expiresAtMs)
+ }
+ }
+ }
+ return res
+ }
+
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java
deleted file mode 100644
index 81b3a00..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java
+++ /dev/null
@@ -1,34 +0,0 @@
-package com.sierrawireless.avphone.auth;
-
-import java.util.Date;
-
-public class Authentication {
- public String code;
- private String accessToken;
- public String refreshToken;
- private Date expirationDate;
-
- public String getAccessToken() {
- return accessToken;
- }
-
- public void setAccessToken(String accessToken) {
- this.accessToken = accessToken;
- }
-
- public boolean isExpired(Date date) {
- return date.after(this.expirationDate);
- }
-
- public boolean isExpired() {
- return isExpired(new Date());
- }
-
- public Date getExpirationDate() {
- return this.expirationDate;
- }
-
- public void setExpirationDate(Date date) {
- this.expirationDate = date;
- }
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.kt
new file mode 100644
index 0000000..db19f43
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.kt
@@ -0,0 +1,15 @@
+package com.sierrawireless.avphone.auth
+
+import java.util.Date
+
+class Authentication {
+ var accessToken: String? = null
+ var expirationDate: Date? = null
+
+ val isExpired: Boolean
+ get() = isExpired(Date())
+
+ fun isExpired(date: Date): Boolean {
+ return date.after(this.expirationDate)
+ }
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java
deleted file mode 100644
index ed6167b..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package com.sierrawireless.avphone.auth;
-
-public interface AuthenticationManager {
- public void onAuthentication(Authentication auth);
- public void forgetAuthentication();
- public boolean isLogged();
- public Authentication getAuthentication();
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.kt
new file mode 100644
index 0000000..88fc6ab
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.kt
@@ -0,0 +1,8 @@
+package com.sierrawireless.avphone.auth
+
+interface AuthenticationManager {
+ val isLogged: Boolean
+ var authentication: Authentication?
+ fun onAuthentication(auth: Authentication)
+ fun forgetAuthentication()
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/listener/CustomLabelsListener.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/listener/CustomLabelsListener.kt
new file mode 100644
index 0000000..58138c0
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/listener/CustomLabelsListener.kt
@@ -0,0 +1,5 @@
+package com.sierrawireless.avphone.listener
+
+interface CustomLabelsListener {
+ fun onCustomLabelsChanged()
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/listener/LoginListener.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/listener/LoginListener.kt
new file mode 100644
index 0000000..df85c5c
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/listener/LoginListener.kt
@@ -0,0 +1,3 @@
+package com.sierrawireless.avphone.listener
+
+internal interface LoginListener
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/listener/MonitorServiceListener.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/listener/MonitorServiceListener.kt
new file mode 100644
index 0000000..d5e34d1
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/listener/MonitorServiceListener.kt
@@ -0,0 +1,10 @@
+package com.sierrawireless.avphone.listener
+
+import com.sierrawireless.avphone.service.MonitoringService
+
+interface MonitorServiceListener {
+
+ fun onServiceStarted(service: MonitoringService)
+
+ fun onServiceStopped(service: MonitoringService)
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java b/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java
deleted file mode 100644
index 17f2f94..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.sierrawireless.avphone.message;
-
-import android.text.Spanned;
-
-/**
- * Generic interface for anything that can display success / error messages.
- */
-public interface IMessageDisplayer {
-
- public void showError(int id, Object... params);
-
- public void showSuccess(int id, Object... params);
-
- public void showErrorMessage(Spanned spanned);
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.kt
new file mode 100644
index 0000000..3a31618
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.kt
@@ -0,0 +1,17 @@
+package com.sierrawireless.avphone.message
+
+import android.text.Spanned
+
+/**
+ * Generic interface for anything that can display success / error messages.
+ */
+interface IMessageDisplayer {
+
+ fun showError(id: Int, vararg params: Any)
+
+ fun showSuccess(id: Int, vararg params: Any)
+
+ fun showSuccess(name:String, vararg params: Any)
+
+ fun showErrorMessage(spanned: Spanned)
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AutoResizeTextView.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AutoResizeTextView.kt
new file mode 100644
index 0000000..7fe304b
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AutoResizeTextView.kt
@@ -0,0 +1,276 @@
+package com.sierrawireless.avphone.model
+
+import android.annotation.TargetApi
+import android.content.Context
+import android.content.res.Resources
+import android.graphics.RectF
+import android.os.Build
+import android.text.Layout.Alignment
+import android.text.StaticLayout
+import android.text.TextPaint
+import android.util.AttributeSet
+import android.util.Log
+import android.util.SparseIntArray
+import android.util.TypedValue
+import android.widget.TextView
+
+class AutoResizeTextView : TextView {
+ private val mTextRect = RectF()
+ private var mAvailableSpaceRect: RectF? = null
+ private var mTextCachedSizes: SparseIntArray? = null
+ private var mPaint: TextPaint? = null
+ private var mMaxTextSize: Float = 0.toFloat()
+ private var mSpacingMult = 1.0f
+ private var mSpacingAdd = 0.0f
+ private var mMinTextSize = 20f
+ private var mWidthLimit: Int = 0
+ private var mMaxLines: Int = 0
+ private var mEnableSizeCache = true
+ private var mInitialized: Boolean = false
+ private val mSizeTester = object : SizeTester {
+ @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
+ override fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int {
+ mPaint!!.textSize = suggestedSize.toFloat()
+ val text = text.toString()
+ val singleline = maxLines == 1
+ if (singleline) {
+ mTextRect.bottom = mPaint!!.fontSpacing
+ mTextRect.right = mPaint!!.measureText(text)
+ } else {
+ val layout = StaticLayout(text, mPaint,
+ mWidthLimit, Alignment.ALIGN_NORMAL, mSpacingMult,
+ mSpacingAdd, true)
+ // return early if we have more lines
+ if (maxLines != NO_LINE_LIMIT && layout.lineCount > maxLines) {
+ return 1
+ }
+ mTextRect.bottom = layout.height.toFloat()
+ var maxWidth = -1
+ (0 until layout.lineCount)
+ .asSequence()
+ .filter { maxWidth < layout.getLineWidth(it) }
+ .forEach { maxWidth = layout.getLineWidth(it).toInt() }
+ mTextRect.right = maxWidth.toFloat()
+ }
+
+ mTextRect.offsetTo(0f, 0f)
+ return if (availableSpace.contains(mTextRect)) {
+ // may be too small, don't worry we will find the best match
+ -1
+ } else {
+ // too big
+ 1
+ }
+ }
+ }
+
+ private interface SizeTester {
+ /**
+ *
+ * @param suggestedSize
+ * Size of text to be tested
+ * @param availableSpace
+ * available space in which text must fit
+ * @return an integer < 0 if after applying `suggestedSize` to
+ * text, it takes less space than `availableSpace`, > 0
+ * otherwise
+ */
+ fun onTestSize(suggestedSize: Int, availableSpace: RectF): Int
+ }
+
+ constructor(context: Context) : super(context) {
+ initialize()
+ }
+
+ constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
+ initialize()
+ }
+
+ constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs, defStyle) {
+ initialize()
+ }
+
+ private fun initialize() {
+ mPaint = TextPaint(paint)
+ mMaxTextSize = textSize
+ mAvailableSpaceRect = RectF()
+ mTextCachedSizes = SparseIntArray()
+ if (mMaxLines == 0) {
+ // no value was assigned during construction
+ mMaxLines = NO_LINE_LIMIT
+ }
+ mInitialized = true
+ }
+
+ override fun setText(text: CharSequence?, type: TextView.BufferType) {
+ super.setText(text, type)
+ if (text != null) {
+ adjustTextSize()
+ }
+ }
+
+ override fun setTextSize(size: Float) {
+ mMaxTextSize = size
+ mTextCachedSizes!!.clear()
+ adjustTextSize()
+ }
+
+ override fun setMaxLines(maxlines: Int) {
+ super.setMaxLines(maxlines)
+ mMaxLines = maxlines
+ reAdjust()
+ }
+
+ override fun getMaxLines(): Int {
+ return mMaxLines
+ }
+
+ override fun setSingleLine() {
+ super.setSingleLine()
+ mMaxLines = 1
+ reAdjust()
+ }
+
+ override fun setSingleLine(singleLine: Boolean) {
+ super.setSingleLine(singleLine)
+ mMaxLines = if (singleLine) {
+ 1
+ } else {
+ NO_LINE_LIMIT
+ }
+ reAdjust()
+ }
+
+ override fun setLines(lines: Int) {
+ super.setLines(lines)
+ mMaxLines = lines
+ reAdjust()
+ }
+
+ override fun setTextSize(unit: Int, size: Float) {
+ val c = context
+ val r: Resources
+
+ r = if (c == null)
+ Resources.getSystem()
+ else
+ c.resources
+ mMaxTextSize = TypedValue.applyDimension(unit, size,
+ r.displayMetrics)
+ mTextCachedSizes!!.clear()
+ adjustTextSize()
+ }
+
+ override fun setLineSpacing(add: Float, mult: Float) {
+ super.setLineSpacing(add, mult)
+ mSpacingMult = mult
+ mSpacingAdd = add
+ }
+
+ /**
+ * Set the lower text size limit and invalidate the view
+ *
+ * @param minTextSize
+ */
+ fun setMinTextSize(minTextSize: Float) {
+ mMinTextSize = minTextSize
+ reAdjust()
+ }
+
+ private fun reAdjust() {
+ adjustTextSize()
+ }
+
+ private fun adjustTextSize() {
+ if (!mInitialized) {
+ return
+ }
+ val startSize = mMinTextSize.toInt()
+ val heightLimit = (measuredHeight - compoundPaddingBottom
+ - compoundPaddingTop)
+ mWidthLimit = (measuredWidth - compoundPaddingLeft
+ - compoundPaddingRight)
+ mAvailableSpaceRect!!.right = mWidthLimit.toFloat()
+ mAvailableSpaceRect!!.bottom = heightLimit.toFloat()
+ super.setTextSize(
+ TypedValue.COMPLEX_UNIT_PX,
+ efficientTextSizeSearch(startSize, mMaxTextSize.toInt(),
+ mSizeTester, mAvailableSpaceRect!!).toFloat())
+ }
+
+ /**
+ * Enables or disables size caching, enabling it will improve performance
+ * where you are animating a value inside TextView. This stores the font
+ * size against getText().length() Be careful though while enabling it as 0
+ * takes more space than 1 on some fonts and so on.
+ *
+ * @param enable
+ * enable font size caching
+ */
+ fun enableSizeCache(enable: Boolean) {
+ mEnableSizeCache = enable
+ mTextCachedSizes!!.clear()
+ adjustTextSize()
+ }
+
+ private fun efficientTextSizeSearch(start: Int, end: Int,
+ sizeTester: SizeTester, availableSpace: RectF): Int {
+ if (!mEnableSizeCache) {
+ return binarySearch(start, end, sizeTester, availableSpace)
+ }
+ val text = text.toString()
+ val key = text.length
+ var size = mTextCachedSizes!!.get(key)
+ if (size != 0) {
+ return size
+ }
+ size = binarySearch(start, end, sizeTester, availableSpace)
+ mTextCachedSizes!!.put(key, size)
+ return size
+ }
+
+ override fun onTextChanged(text: CharSequence, start: Int,
+ before: Int, after: Int) {
+ super.onTextChanged(text, start, before, after)
+ reAdjust()
+ }
+
+ override fun onSizeChanged(width: Int, height: Int, oldwidth: Int,
+ oldheight: Int) {
+ mTextCachedSizes!!.clear()
+ super.onSizeChanged(width, height, oldwidth, oldheight)
+ if (width != oldwidth || height != oldheight) {
+ reAdjust()
+ }
+ }
+
+ companion object {
+ private const val NO_LINE_LIMIT = -1
+
+ private fun binarySearch(start: Int, end: Int, sizeTester: SizeTester,
+ availableSpace: RectF): Int {
+ var lastBest = start
+ var lo = start
+ var hi = end - 1
+ var mid: Int
+ while (lo <= hi) {
+ mid = (lo + hi).ushr(1)
+ val midValCmp = sizeTester.onTestSize(mid, availableSpace)
+ when {
+ midValCmp < 0 -> {
+ lastBest = lo
+ lo = mid + 1
+ }
+ midValCmp > 0 -> {
+ hi = mid - 1
+ lastBest = hi
+ }
+ else -> return mid
+ }
+ }
+ // make sure to return last best
+ // this is what should always be returned
+ return lastBest
+ }
+ }
+}
\ No newline at end of file
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java
deleted file mode 100644
index 1cf7457..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java
+++ /dev/null
@@ -1,130 +0,0 @@
-package com.sierrawireless.avphone.model;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-
-import net.airvantage.model.alert.v1.AlertRule;
-import net.airvantage.model.Application;
-import net.airvantage.model.ApplicationData;
-import net.airvantage.model.Command;
-import net.airvantage.model.alert.v1.Condition;
-import net.airvantage.model.Data;
-import net.airvantage.model.Parameter;
-import net.airvantage.model.Protocol;
-import net.airvantage.model.Variable;
-
-public class AvPhoneApplication {
-
- public static final String ALERT_RULE_NAME = "AV Phone raised an alert";
-
- public static Application createApplication(final String userName) {
- Application application = new Application();
- application.name = AvPhoneApplication.appName(userName);
- application.type = AvPhoneApplication.appType(userName);
- application.revision = "0.0.0";
- return application;
- }
-
- public static List createProtocols() {
- Protocol mqtt = new Protocol();
- mqtt.type = "MQTT";
- mqtt.commIdType = "SERIAL";
- return Arrays.asList(mqtt);
- }
-
- public static List createApplicationData(CustomDataLabels customData) {
-
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
- //
-
- ApplicationData applicationData = new ApplicationData();
- applicationData.id = "0";
- applicationData.label = "AV Phone Demo";
- applicationData.encoding = "MQTT";
- applicationData.elementType = "node";
- applicationData.data = new ArrayList();
-
- Data asset = new Data("phone", "Phone", "node");
- asset.data = new ArrayList();
-
- asset.data.add(new Variable(AvPhoneData.RSSI, "RSSI", "int"));
- asset.data.add(new Variable(AvPhoneData.RSRP, "RSRP", "int"));
- asset.data.add(new Variable(AvPhoneData.SERVICE, "Service type", "string"));
- asset.data.add(new Variable(AvPhoneData.OPERATOR, "Operator", "string"));
- asset.data.add(new Variable(AvPhoneData.IMEI, "IMEI", "string"));
- asset.data.add(new Variable(AvPhoneData.LAT, "Latitude", "double"));
- asset.data.add(new Variable(AvPhoneData.LONG, "Longitude", "double"));
- asset.data.add(new Variable(AvPhoneData.BATTERY, "Battery level", "double"));
- asset.data.add(new Variable(AvPhoneData.BYTES_RECEIVED, "Bytes received", "double"));
- asset.data.add(new Variable(AvPhoneData.BYTES_SENT, "Bytes sent", "double"));
- asset.data.add(new Variable(AvPhoneData.MEMORY_USAGE, "Memory usage", "double"));
- asset.data.add(new Variable(AvPhoneData.RUNNING_APPS, "Running applications", "int"));
- asset.data.add(new Variable(AvPhoneData.ACTIVE_WIFI, "Active Wi-Fi", "boolean"));
- asset.data.add(new Variable(AvPhoneData.ANDROID_VERSION, "Android Version", "string"));
-
- asset.data.add(new Variable(AvPhoneData.ALARM, "Active alarm", "boolean"));
-
- asset.data.add(new Variable(AvPhoneData.CUSTOM_1, customData.customUp1Label, "int"));
- asset.data.add(new Variable(AvPhoneData.CUSTOM_2, customData.customUp2Label, "int"));
- asset.data.add(new Variable(AvPhoneData.CUSTOM_3, customData.customDown1Label, "int"));
- asset.data.add(new Variable(AvPhoneData.CUSTOM_4, customData.customDown2Label, "int"));
- asset.data.add(new Variable(AvPhoneData.CUSTOM_5, customData.customStr1Label, "string"));
- asset.data.add(new Variable(AvPhoneData.CUSTOM_6, customData.customStr2Label, "string"));
-
- Command c = new Command(AvPhoneData.NOTIFY, "Notify");
- Parameter p = new Parameter("message", "string");
- c.parameters = Arrays.asList(p);
-
- asset.data.add(c);
-
- applicationData.data.add(asset);
-
- return Arrays.asList(applicationData);
-
- }
-
- public static String appName(final String userName) {
- return "av_phone_demo_" + userName;
- }
-
- public static String appType(final String userName) {
- return "av.phone.demo." + userName;
- }
-
- public static AlertRule createAlertRule() {
- AlertRule rule = new AlertRule();
-
- rule.active = true;
- rule.name = ALERT_RULE_NAME;
- rule.eventType = "event.system.incoming.communication";
-
- Condition alarmCondition = new Condition();
- alarmCondition.eventProperty = "communication.data.value";
- alarmCondition.eventPropertyKey = AvPhoneData.ALARM;
- alarmCondition.operator = "EQUALS";
- alarmCondition.value = "true";
-
- rule.conditions = Arrays.asList(alarmCondition);
-
- return rule;
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.kt
new file mode 100644
index 0000000..258bfa9
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.kt
@@ -0,0 +1,155 @@
+package com.sierrawireless.avphone.model
+
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.tools.Tools
+import net.airvantage.model.*
+import net.airvantage.model.alert.v1.AlertRule
+import net.airvantage.model.alert.v1.Condition
+
+object AvPhoneApplication {
+
+ const val ALERT_RULE_NAME = "raised an alert"
+ private var objectsManager: ObjectsManager? = null
+
+ fun createApplication(userName: String, phoneName:String): Application {
+ val application = Application()
+ application.name = AvPhoneApplication.appName(userName, phoneName)
+ application.type = AvPhoneApplication.appType(userName, phoneName)
+ application.revision = "0.0.0"
+ return application
+ }
+
+ fun createProtocols(): List {
+ val mqtt = Protocol()
+ mqtt.type = "MQTT"
+ mqtt.commIdType = "SERIAL"
+ return listOf(mqtt)
+ }
+
+ fun createApplicationData(customData: ArrayList, obj: String): List {
+
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+ //
+
+ val applicationData = ApplicationData()
+ applicationData.id = "0"
+ applicationData.label = "AV Phone Demo"
+ applicationData.encoding = "MQTT"
+ applicationData.elementType = "node"
+ applicationData.data = ArrayList()
+
+ val asset = Data("phone", "Phone", "node")
+ asset.data = ArrayList()
+
+ asset.data!!.add(Variable(AvPhoneData.ALARM, "Active alarm", "boolean"))
+
+ var pos = 1
+ for (data in customData) {
+ val type: String = if (data.mode != AvPhoneObjectData.Mode.None) {
+ "int"
+ } else {
+ "string"
+ }
+
+ if (data.path == null) {
+ asset.data!!.add(Variable(obj + "." + AvPhoneData.CUSTOM + pos.toString(), data.name, type))
+ }else{
+ asset.data!!.add(Variable(data.path!!, data.name, type))
+ }
+ pos++
+ }
+
+ val c = Command(AvPhoneData.NOTIFY, "Notify")
+ val p = Parameter("message", "string")
+ c.parameters = listOf(p)
+
+ asset.data!!.add(c)
+
+ applicationData.data!!.add(asset)
+
+ return listOf(applicationData)
+
+ }
+
+ private fun appName(userName: String, phoneName: String): String {
+ objectsManager = ObjectsManager.getInstance()
+
+ return phoneName.replace(" ", "_") + "_av_phone_" + objectsManager!!.savecObject.name + "_" + userName
+ }
+
+ fun appType(userName: String, phoneName: String): String {
+ objectsManager = ObjectsManager.getInstance()
+ return phoneName.replace(" ", ".") + ".av.phone.demo." + objectsManager!!.savecObject.name + userName
+ }
+
+ fun createAlertRule(system: AvSystem): AlertRule {
+ val rule = AlertRule()
+
+ rule.active = true
+ rule.name = Tools.buildAlertName()
+ rule.eventType = "event.system.incoming.communication"
+
+ val alarmCondition = Condition()
+ alarmCondition.eventProperty = "communication.data.value"
+ alarmCondition.eventPropertyKey = AvPhoneData.ALARM
+ alarmCondition.operator = "EQUALS"
+ alarmCondition.value = "true"
+
+ val systemCondition = Condition()
+ systemCondition.eventProperty = "system.data.value"
+ systemCondition.eventPropertyKey = "system.id"
+ systemCondition.operator = "EQUALS"
+ systemCondition.value = system.uid
+
+
+ val tmp = ArrayList()
+ tmp.add(alarmCondition)
+ tmp.add(systemCondition)
+ rule.conditions = tmp
+
+ return rule
+ }
+
+ fun updateAlertRule(system: AvSystem, alertRule: AlertRule) {
+
+ alertRule.active = true
+ alertRule.name = Tools.buildAlertName()
+ alertRule.eventType = "event.system.incoming.communication"
+
+ val alarmCondition = Condition()
+ alarmCondition.eventProperty = "communication.data.value"
+ alarmCondition.eventPropertyKey = AvPhoneData.ALARM
+ alarmCondition.operator = "EQUALS"
+ alarmCondition.value = "true"
+
+ val systemCondition = Condition()
+ systemCondition.eventProperty = "system.data.value"
+ systemCondition.eventPropertyKey = "system.id"
+ systemCondition.operator = "EQUALS"
+ systemCondition.value = system.uid
+
+
+ val tmp = ArrayList()
+ tmp.add(alarmCondition)
+ tmp.add(systemCondition)
+ alertRule.conditions = tmp
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java
deleted file mode 100644
index ece7ab9..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java
+++ /dev/null
@@ -1,30 +0,0 @@
-package com.sierrawireless.avphone.model;
-
-public class AvPhoneData {
-
- public static final String RSSI = "phone.rssi";
- public static final String RSRP = "phone.rsrp";
- public static final String BATTERY = "phone.batterylevel";
- public static final String OPERATOR = "phone.operator";
- public static final String IMEI = "phone.imei";
- public static final String SERVICE = "phone.service";
- public static final String LAT = "phone.latitude";
- public static final String LONG = "phone.longitude";
- public static final String BYTES_RECEIVED = "phone.bytesreceived";
- public static final String BYTES_SENT = "phone.bytessent";
- public static final String ACTIVE_WIFI = "phone.activewifi";
- public static final String RUNNING_APPS = "phone.runningapps";
- public static final String MEMORY_USAGE = "phone.memoryusage";
- public static final String ANDROID_VERSION = "phone.androidversion";
- public static final String CUSTOM_1 = "phone.custom.1";
- public static final String CUSTOM_2 = "phone.custom.2";
- public static final String CUSTOM_3 = "phone.custom.3";
- public static final String CUSTOM_4 = "phone.custom.4";
- public static final String CUSTOM_5 = "phone.custom.5";
- public static final String CUSTOM_6 = "phone.custom.6";
-
- public static final String ALARM = "phone.alarm";
-
- public static final String NOTIFY = "phone.notify";
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.kt
new file mode 100644
index 0000000..3f791d9
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.kt
@@ -0,0 +1,11 @@
+package com.sierrawireless.avphone.model
+
+object AvPhoneData {
+
+ const val CUSTOM = "phone.custom."
+
+ const val ALARM = "phone.alarm"
+
+ internal const val NOTIFY = "phone.notify"
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObject.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObject.kt
new file mode 100644
index 0000000..8b03ab2
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObject.kt
@@ -0,0 +1,35 @@
+package com.sierrawireless.avphone.model
+
+import java.util.ArrayList
+
+class AvPhoneObject {
+ var name: String? = null
+ var systemUid: String? = null
+
+ var alarm: Boolean = false
+ var datas: ArrayList = ArrayList()
+
+ fun add(data: AvPhoneObjectData) {
+ datas.add(data)
+ }
+
+ override fun toString(): String {
+ val returned = StringBuilder("{")
+ returned.append("\"name\" : \"").append(name).append("\",")
+ returned.append("\"alarm\" : ").append(alarm).append(",")
+
+ returned.append("\"datas\":[")
+ for (data in datas) {
+ returned.append(data.toString()).append(",")
+ }
+ returned.append("]}")
+ return returned.toString()
+ }
+
+ fun exec() {
+ for (data in datas) {
+ data.execMode()
+ }
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObjectData.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObjectData.kt
new file mode 100644
index 0000000..9b77a53
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObjectData.kt
@@ -0,0 +1,130 @@
+package com.sierrawireless.avphone.model
+
+import android.text.TextUtils
+import com.sierrawireless.avphone.tools.Tools
+
+
+class AvPhoneObjectData(var name: String, var unit: String, var defaults: String, mode: Mode, private val label:String?, var path: String?) {
+ var mode: Mode = Mode.None
+ var current: Int? = null
+ private var min: Int? = null
+ private var max: Int? = null
+
+ val isInteger: Boolean
+ get() = !defaults.isEmpty() && TextUtils.isDigitsOnly(defaults)
+
+ enum class Mode {
+ None,
+ UP,
+ DOWN,
+ RANDOM
+ }
+
+ init {
+ if (isInteger) {
+ this.mode = mode
+ current = Integer.parseInt(defaults)
+ } else {
+ if (mode == Mode.RANDOM) {
+ val value = defaults.split(",")
+ if (value.size == 2) {
+ if (!value[0].isEmpty() && TextUtils.isDigitsOnly(value[0]) &&
+ !value[1].isEmpty() && TextUtils.isDigitsOnly(value[1])) {
+ min = Integer.parseInt(value[0])
+ max = Integer.parseInt(value[1])
+ this.mode = mode
+ current = Tools.rand(min!!, max!!).toInt()
+ } else {
+ this.mode = Mode.None
+ }
+ } else {
+ this.mode = Mode.None
+ }
+ }else{
+ this.mode = Mode.None
+ }
+ }
+ }
+
+ override fun toString(): String {
+ var returned = "{"
+ returned = "$returned\"name\": \"$name\","
+ returned = "$returned\"unit\": \"$unit\","
+ returned = "$returned\"defaults\": \"$defaults\","
+ returned = returned + "\"mode\": \"" + modeToString(mode) + "\""
+ returned = if (path == null) {
+ returned + "}"
+ }else {
+ ",$returned\"path\": \"$path\"}"
+ }
+ return returned
+ }
+
+ fun execMode(): String {
+ return when {
+ this.mode == Mode.UP -> increment()
+ this.mode == Mode.DOWN -> decrement()
+ this.mode == Mode.RANDOM -> random()
+ else -> defaults
+ }
+ }
+
+ private fun modeToString(mode: Mode): String {
+ return when (mode) {
+ AvPhoneObjectData.Mode.UP -> "Increase indefinitely"
+ AvPhoneObjectData.Mode.DOWN -> "Decrease to zero"
+ AvPhoneObjectData.Mode.None -> "None"
+ AvPhoneObjectData.Mode.RANDOM -> "Random"
+ }
+ }
+
+ private fun increment(): String {
+ if (current == null) {
+ current = Integer.parseInt(defaults)
+ }
+ current = current!! + 1
+ return current!!.toString()
+ }
+
+ private fun decrement(): String {
+ if (current == null) {
+ current = Integer.parseInt(defaults)
+ }
+ if (current!! > 0)
+ current = current!! - 1
+ else if (current == 0) {
+ current = Integer.parseInt(defaults)
+
+ }
+ return current!!.toString()
+ }
+
+ private fun random(): String {
+ current = Tools.rand(min!!, max!!).toInt()
+ return current!!.toString()
+ }
+
+ fun modePosition(): Int {
+ return when (mode) {
+ AvPhoneObjectData.Mode.None -> 0
+ AvPhoneObjectData.Mode.UP -> 1
+ AvPhoneObjectData.Mode.DOWN -> 2
+ AvPhoneObjectData.Mode.RANDOM -> 3
+ }
+ }
+
+ companion object {
+
+ fun modeFromPosition(position: Int): Mode {
+ when (position) {
+ 0 -> return Mode.None
+ 1 -> return Mode.UP
+ 2 -> return Mode.DOWN
+ 3 -> return Mode.RANDOM
+ }
+ return Mode.None
+ }
+ }
+
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/CustomDataLabels.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/CustomDataLabels.java
deleted file mode 100644
index ec78083..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/CustomDataLabels.java
+++ /dev/null
@@ -1,11 +0,0 @@
-package com.sierrawireless.avphone.model;
-
-public class CustomDataLabels {
-
- public String customUp1Label;
- public String customUp2Label;
- public String customDown1Label;
- public String customDown2Label;
- public String customStr1Label;
- public String customStr2Label;
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/CustomDataLabels.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/model/CustomDataLabels.kt
new file mode 100644
index 0000000..d7718f2
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/CustomDataLabels.kt
@@ -0,0 +1,11 @@
+package com.sierrawireless.avphone.model
+
+class CustomDataLabels {
+
+ var customUp1Label: String? = null
+ var customUp2Label: String? = null
+ var customDown1Label: String? = null
+ var customDown2Label: String? = null
+ var customStr1Label: String? = null
+ var customStr2Label: String? = null
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/CustomDataSource.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/CustomDataSource.java
deleted file mode 100644
index 8375f04..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/CustomDataSource.java
+++ /dev/null
@@ -1,108 +0,0 @@
-package com.sierrawireless.avphone.service;
-
-import java.util.Date;
-
-public class CustomDataSource {
-
- // Rate of growth (in units / seconds)
- private static final float UP1_RATE = 0.2F;
- private static final float UP2_RATE = 0.05F;
-
- // Rate of decrease (in units / seconds) ; when 0 is reached, values
- // go back to 100.
- private static final float DOWN1_RATE = 0.2F;
- private static final float DOWN2_RATE = 0.05F;
-
- // How often (in seconds) should strings be changed ?
- private static final int STR1_DELAY = 3600;
- private static final int STR2_DELAY = 2 * 3600;
-
- public int customUp1 = 0;
- public int customUp2 = 0;
- public int customDown1 = 100;
- public int customDown2 = 100;
-
- public String customStr1 = "";
- public String customStr2 = "";
-
- public int customStr1Life = 0;
- public int customStr2Life = 0;
-
- private long lastTick;
-
- public CustomDataSource(Date date) {
- this.lastTick = date.getTime();
- updateStrs();
- }
-
- private void updateStrs() {
- updateStr1();
- updateStr2();
- }
-
- private void updateStr1() {
- customStr1 = "SN" + (lastTick / 10000);
- }
-
- private void updateStr2() {
- customStr2 = "SN" + ((lastTick / 10000) + ((int) Math.random() * 4200));
- }
-
- public Integer getCustomIntUp1() {
- return customUp1;
- }
-
- public Integer getCustomIntUp2() {
- return customUp2;
- }
-
- public Integer getCustomIntDown1() {
- return customDown1;
- }
-
- public Integer getCustomIntDown2() {
- return customDown2;
- }
-
- public String getCustomStr1() {
- return customStr1;
- }
-
- public String getCustomStr2() {
- return customStr2;
- }
-
- public void next(Date date) {
- long now = date.getTime();
-
- long delay = (long) ((now - lastTick) / 1000);
-
- customUp1 = customUp1 + (int) (delay * UP1_RATE);
- customUp2 = customUp2 + (int) (delay * UP2_RATE);
-
- customDown1 = customDown1 - (int) (delay * DOWN1_RATE);
- if (customDown1 < 0) {
- customDown1 = 100;
- }
-
- customDown2 = customDown2 - (int) (delay * DOWN2_RATE);
- if (customDown2 < 0) {
- customDown2 = 100;
- }
-
- customStr1Life += delay;
- customStr2Life += delay;
-
- lastTick = now;
-
- if (customStr1Life > STR1_DELAY) {
- updateStr1();
- }
-
- if (customStr2Life > STR2_DELAY) {
- updateStr2();
- }
-
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/LocationListenerAdapter.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/LocationListenerAdapter.java
deleted file mode 100644
index e48a32a..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/LocationListenerAdapter.java
+++ /dev/null
@@ -1,25 +0,0 @@
-package com.sierrawireless.avphone.service;
-
-import android.location.Location;
-import android.location.LocationListener;
-import android.os.Bundle;
-
-public class LocationListenerAdapter implements LocationListener {
-
- @Override
- public void onLocationChanged(Location location) {
- }
-
- @Override
- public void onProviderDisabled(String provider) {
- }
-
- @Override
- public void onProviderEnabled(String provider) {
- }
-
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/LocationListenerAdapter.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/service/LocationListenerAdapter.kt
new file mode 100644
index 0000000..8a250c3
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/LocationListenerAdapter.kt
@@ -0,0 +1,16 @@
+package com.sierrawireless.avphone.service
+
+import android.location.Location
+import android.location.LocationListener
+import android.os.Bundle
+
+open class LocationListenerAdapter : LocationListener {
+
+ override fun onLocationChanged(location: Location) {}
+
+ override fun onProviderDisabled(provider: String) {}
+
+ override fun onProviderEnabled(provider: String) {}
+
+ override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/LogMessage.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/LogMessage.java
deleted file mode 100644
index 3109f1c..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/LogMessage.java
+++ /dev/null
@@ -1,22 +0,0 @@
-package com.sierrawireless.avphone.service;
-
-import android.content.Intent;
-
-public class LogMessage extends Intent {
-
- public static final String LOG_EVENT = "com.sierrawireless.avphone.event.log";
-
- // keys used for broadcasting log events
- private static final String LOG = "log";
-
- public LogMessage(String message) {
- super(LOG_EVENT);
-
- this.putExtra(LOG, message);
- }
-
- public String getMessage() {
- return this.getStringExtra(LOG);
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/LogMessage.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/service/LogMessage.kt
new file mode 100644
index 0000000..1814beb
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/LogMessage.kt
@@ -0,0 +1,27 @@
+package com.sierrawireless.avphone.service
+
+import android.content.Intent
+
+class LogMessage(message: String, alarm: Boolean) : Intent(LOG_EVENT) {
+
+ val message: String
+ get() = this.getStringExtra(LOG)
+ val alarm: Boolean
+ get() = this.getBooleanExtra(ALARM, false)
+
+ init {
+
+ this.putExtra(LOG, message)
+ this.putExtra(ALARM, alarm)
+ }
+
+ companion object {
+
+ const val LOG_EVENT = "com.sierrawireless.avphone.event.log"
+
+ // keys used for broadcasting log events
+ const val LOG = "log"
+ private const val ALARM = "alarm"
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitorServiceManager.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitorServiceManager.kt
new file mode 100644
index 0000000..027f387
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitorServiceManager.kt
@@ -0,0 +1,20 @@
+package com.sierrawireless.avphone.service
+
+import com.sierrawireless.avphone.listener.MonitorServiceListener
+
+
+interface MonitorServiceManager {
+ //val isServiceRunning: Boolean
+ var monitoringService: MonitoringService?
+ fun isServiceStarted(name: String): Boolean
+ fun oneServiceStarted(): Boolean
+ fun stopMonitoringService()
+ fun startMonitoringService(name: String)
+ fun startSendData(name: String):Boolean
+ fun stopSendData()
+ fun sendAlarmEvent(on: Boolean):Boolean
+ fun setMonitoringServiceListener(listener: MonitorServiceListener)
+ fun isServiceRunning(name: String? = null): Boolean
+ fun cancel()
+ fun start()
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java
deleted file mode 100644
index c6daf3a..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java
+++ /dev/null
@@ -1,443 +0,0 @@
-package com.sierrawireless.avphone.service;
-
-import android.app.ActivityManager;
-import android.app.ActivityManager.MemoryInfo;
-import android.app.Notification;
-import android.app.NotificationManager;
-import android.app.PendingIntent;
-import android.app.Service;
-import android.app.TaskStackBuilder;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.location.Criteria;
-import android.location.Location;
-import android.location.LocationListener;
-import android.location.LocationManager;
-import android.location.LocationProvider;
-import android.net.ConnectivityManager;
-import android.net.TrafficStats;
-import android.os.BatteryManager;
-import android.os.Binder;
-import android.os.Build;
-import android.os.IBinder;
-import android.support.v4.content.LocalBroadcastManager;
-import android.telephony.CellInfo;
-import android.telephony.CellInfoGsm;
-import android.telephony.CellInfoLte;
-import android.telephony.CellInfoWcdma;
-import android.telephony.TelephonyManager;
-import android.util.Log;
-
-import com.crashlytics.android.Crashlytics;
-import com.google.gson.Gson;
-import com.sierrawireless.avphone.MainActivity;
-import com.sierrawireless.avphone.R;
-
-import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
-import org.eclipse.paho.client.mqttv3.MqttCallback;
-import org.eclipse.paho.client.mqttv3.MqttException;
-import org.eclipse.paho.client.mqttv3.MqttMessage;
-
-import java.util.Arrays;
-import java.util.Date;
-import java.util.List;
-import java.util.Map;
-
-public class MonitoringService extends Service {
-
- private static final String LOGTAG = MonitoringService.class.getName();
-
- // system services
- private TelephonyManager telephonyManager;
- private ActivityManager activityManager;
- private ConnectivityManager connManager;
-
- // Unique Identification Number for the Notification.
- private int NOTIFICATION = R.string.notif_title;
-
- // Intent extra keys
- public static final String DEVICE_ID = "device_id";
- public static final String SERVER_HOST = "server_host";
- public static final String PASSWORD = "password";
-
- private MqttPushClient client = null;
-
- private Long startedSince;
-
- private Long lastRun;
- private String lastLog;
- private NewData lastData = new NewData();
- /* the date of the last location reading */
- private long lastLocation;
-
- private CustomDataSource customDataSource;
-
- // FIXME(pht) for testing, to compare with "last known location"
- private Location networkLocation = null;
- private Location gpsLocation = null;
- private LocationListener networkLocationListener;
- private LocationListener gpsLocationListener;
-
- @Override
- public void onCreate() {
-
- // Display a notification icon
-
- // Create an intent to start the activity when clicking the notification
- Intent resultIntent = new Intent(this, MainActivity.class);
- TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
- stackBuilder.addParentStack(MainActivity.class);
- stackBuilder.addNextIntent(resultIntent);
- PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
-
- Notification notification = new Notification.Builder(this.getApplicationContext()) //
- .setContentTitle(getText(R.string.notif_title)) //
- .setContentText(getText(R.string.notif_desc)) //
- .setSmallIcon(R.drawable.ic_notif) //
- .setOngoing(true) //
- .setContentIntent(resultPendingIntent) //
- .build();
-
- startForeground(NOTIFICATION, notification);
-
- telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
- activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
- connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
-
- customDataSource = new CustomDataSource(new java.util.Date());
-
- startedSince = System.currentTimeMillis();
-
- }
-
- @Override
- public int onStartCommand(Intent intent, int flags, int startId) {
-
- lastRun = System.currentTimeMillis();
-
- try {
-
- if (this.client == null) {
-
- //
- // Ensure intent is valid
- //
- final String deviceId = intent.getStringExtra(DEVICE_ID);
- final String password = intent.getStringExtra(PASSWORD);
- final String serverHost = intent.getStringExtra(SERVER_HOST);
-
- final List intentValuesList = Arrays.asList(deviceId, password, serverHost);
- if (intentValuesList.contains(null)) {
- // Stop service when unable to start MQTT client
- stopSelfResult(startId);
- return Service.START_STICKY;
- }
-
- // Now, create client
- client = new MqttPushClient(deviceId, password, serverHost, mqttCallback);
- }
-
- if (!client.isConnected()) {
- client.connect();
- }
-
- Location location = getLastKnownLocation();
-
- // retrieve data
- NewData data = new NewData();
-
- List cellInfos = telephonyManager.getAllCellInfo();
- if (cellInfos != null && !cellInfos.isEmpty()) {
- CellInfo cellInfo = cellInfos.get(0);
- if (cellInfo instanceof CellInfoGsm) {
- data.setRssi(((CellInfoGsm) cellInfo).getCellSignalStrength().getDbm());
- } else if (cellInfo instanceof CellInfoWcdma) {
- // RSSI ?
- // data.setRssi(((CellInfoWcdma) cellInfo).getCellSignalStrength().getDbm());
- } else if (cellInfo instanceof CellInfoLte) {
- data.setRsrp(((CellInfoLte) cellInfo).getCellSignalStrength().getDbm());
- }
- }
-
- if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
- data.setImei(telephonyManager.getDeviceId());
- }
-
- data.setOperator(telephonyManager.getNetworkOperatorName());
-
- switch (telephonyManager.getNetworkType()) {
- case TelephonyManager.NETWORK_TYPE_GPRS:
- data.setNetworkType("GPRS");
- break;
- case TelephonyManager.NETWORK_TYPE_EDGE:
- data.setNetworkType("EDGE");
- break;
- case TelephonyManager.NETWORK_TYPE_UMTS:
- data.setNetworkType("UMTS");
- break;
- case TelephonyManager.NETWORK_TYPE_HSDPA:
- data.setNetworkType("HSDPA");
- break;
- case TelephonyManager.NETWORK_TYPE_HSPAP:
- data.setNetworkType("HSPA+");
- break;
- case TelephonyManager.NETWORK_TYPE_HSPA:
- data.setNetworkType("HSPA");
- break;
- case TelephonyManager.NETWORK_TYPE_HSUPA:
- data.setNetworkType("HSUPA");
- break;
- case TelephonyManager.NETWORK_TYPE_LTE:
- data.setNetworkType("LTE");
- break;
- // to be continued
- default:
- }
-
- data.setActiveWifi(connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
- data.setRunningApps(activityManager.getRunningAppProcesses().size());
- data.setAndroidVersion(Build.VERSION.RELEASE);
-
- MemoryInfo mi = new MemoryInfo();
- activityManager.getMemoryInfo(mi);
- data.setMemoryUsage((float) ((mi.totalMem - mi.availMem) / ((Long) mi.totalMem).doubleValue()));
-
- // battery level
- final IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
- final Intent batteryStatus = this.registerReceiver(null, iFilter);
- if (batteryStatus != null) {
- final int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
- final int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
- data.setBatteryLevel(level / (float) scale);
- }
-
- // location
- if (location != null && location.getTime() != lastLocation) {
- data.setLatitude(location.getLatitude());
- data.setLongitude(location.getLongitude());
- lastLocation = location.getTime();
- }
-
- // bytes sent/received
- data.setBytesReceived(TrafficStats.getMobileRxBytes());
- data.setBytesSent(TrafficStats.getMobileTxBytes());
-
- // Custom data
- data.setCustomIntUp1(customDataSource.getCustomIntUp1());
- data.setCustomIntUp2(customDataSource.getCustomIntUp2());
- data.setCustomIntDown1(customDataSource.getCustomIntDown1());
- data.setCustomIntDown2(customDataSource.getCustomIntDown2());
- data.setCustomStr1(customDataSource.getCustomStr1());
- data.setCustomStr2(customDataSource.getCustomStr2());
-
- customDataSource.next(new Date());
-
- // save new data values
- lastData.putExtras(data.getExtras());
-
- // dispatch new data event to update the activity UI
- LocalBroadcastManager.getInstance(this).sendBroadcast(data);
-
- this.client.push(data);
- lastLog = data.size() + " data pushed to the server";
- LocalBroadcastManager.getInstance(this).sendBroadcast(new LogMessage(lastLog));
-
- setUpLocationListeners();
-
-
- } catch (Exception e) {
- Crashlytics.logException(e);
- Log.e(LOGTAG, "error", e);
- lastLog = "ERROR: " + e.getMessage();
- LocalBroadcastManager.getInstance(this).sendBroadcast(new LogMessage(lastLog));
- }
-
-
- return Service.START_NOT_STICKY;
- }
-
- @Override
- public void onDestroy() {
- Log.d("MonitoringService", "Stopping service");
-
- if (this.client != null) {
- try {
- this.client.disconnect();
- } catch (MqttException e) {
- Crashlytics.logException(e);
- Log.e(LOGTAG, "error", e);
- }
- }
-
- // Cancel the persistent notification.
- stopForeground(true);
-
- stopLocationListeners();
- }
-
- private void setUpLocationListeners() {
- final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- LocationProvider networkLocationProvider = locManager.getProvider(LocationManager.NETWORK_PROVIDER);
- if (networkLocationProvider != null) {
- networkLocationListener = new LocationListenerAdapter() {
- @Override
- public void onLocationChanged(Location location) {
- Log.d(LOGTAG, "Received Network location update " + location.getLatitude() + ";" + location.getLongitude());
- networkLocation = location;
- }
- };
- locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60 * 1000, 5, networkLocationListener);
- }
- LocationProvider gpsLocationProvider = locManager.getProvider(LocationManager.GPS_PROVIDER);
- if (gpsLocationProvider != null) {
- gpsLocationListener = new LocationListenerAdapter() {
- @Override
- public void onLocationChanged(Location location) {
- Log.d(LOGTAG, "Received GPS location update " + location.getLatitude() + ";" + location.getLongitude());
- gpsLocation = location;
- }
- };
- locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60 * 1000, 5, gpsLocationListener);
- }
- }
-
- private void stopLocationListeners() {
- final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- if (networkLocationListener != null) {
- locManager.removeUpdates(networkLocationListener);
- }
- if (gpsLocationListener != null) {
- locManager.removeUpdates(gpsLocationListener);
- }
- }
-
-
- private Location getLastKnownLocation() {
- final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
- final String locationProvider = locManager.getBestProvider(new Criteria(), true);
- Log.d(LOGTAG, "Getting last known location from provider: " + locationProvider);
-
- Location location = null;
- if (locationProvider != null) {
- location = locManager.getLastKnownLocation(locationProvider);
- if (location != null) {
- Log.d(LOGTAG, "Last known location : " + location.getLatitude() + "," + location.getLongitude());
- } else {
- Log.d(LOGTAG, "Read null location");
- }
- if (networkLocation != null) {
- Log.d(LOGTAG, "Last Network Location : " + networkLocation.getLatitude() + "," + networkLocation.getLongitude());
- } else {
- Log.d(LOGTAG, "No known network location");
- }
- if (gpsLocation != null) {
- Log.d(LOGTAG, "Last GPS Location : " + gpsLocation.getLatitude() + "," + gpsLocation.getLongitude());
- } else {
- Log.d(LOGTAG, "No known GPSlocation");
- }
- }
- return location;
- }
-
- public void sendAlarmEvent(boolean activated) {
-
- if (this.client == null) {
- // TODO: Propagate error message when client is not available yet
- return;
- }
-
- NewData data = new NewData();
- data.setAlarmActivated(activated);
-
- // save alarm state
- lastData.putExtras(data.getExtras());
-
- try {
- this.client.push(data);
- } catch (MqttException e) {
- // TODO display something
- Crashlytics.logException(e);
- Log.e(LOGTAG, "Could not push the alarm event", e);
- }
- }
-
- // Service binding
-
- private ServiceBinder binder = new ServiceBinder();
-
- @Override
- public IBinder onBind(Intent arg0) {
- return binder;
- }
-
- public class ServiceBinder extends Binder {
-
- public MonitoringService getService() {
- return MonitoringService.this;
- }
- }
-
- public long getStartedSince() {
- return startedSince;
- }
-
- public NewData getLastData() {
- return lastData;
- }
-
- public String getLastLog() {
- return lastLog;
- }
-
- public Long getLastRun() {
- return lastRun;
- }
-
- // MQTT client callback
-
- @SuppressWarnings("unused")
- private MqttCallback mqttCallback = new MqttCallback() {
-
- class Message {
- String uid;
- long timestamp;
- Command command;
- }
-
- class Command {
- String id;
- Map params;
- }
-
- @Override
- public void messageArrived(String topic, MqttMessage msg) throws Exception {
- Log.d(LOGTAG, "MQTT msg received: " + new String(msg.getPayload()));
-
- // parse json payload
- Message[] messages = new Gson().fromJson(new String(msg.getPayload(), "UTF-8"), Message[].class);
-
- // display a new notification
- Notification notification = new Notification.Builder(MonitoringService.this.getApplicationContext()) //
- .setContentTitle(getText(R.string.notif_new_message)) //
- .setContentText(messages[0].command.params.get("message")) //
- .setSmallIcon(R.drawable.ic_notif) //
- .setAutoCancel(true) //
- .build();
-
- NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
- mNotificationManager.notify((int) messages[0].timestamp, notification);
- }
-
- @Override
- public void deliveryComplete(IMqttDeliveryToken arg0) {
- //
- }
-
- @Override
- public void connectionLost(Throwable arg0) {
- //
- }
- };
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.kt
new file mode 100644
index 0000000..ba90874
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.kt
@@ -0,0 +1,540 @@
+package com.sierrawireless.avphone.service
+
+import android.annotation.SuppressLint
+import android.app.*
+import android.content.Context
+import android.content.Intent
+import android.graphics.Color
+import android.location.Criteria
+import android.location.Location
+import android.location.LocationListener
+import android.location.LocationManager
+import android.net.ConnectivityManager
+import android.net.TrafficStats
+import android.os.Binder
+import android.os.Build
+import android.os.IBinder
+import android.support.annotation.RequiresApi
+import android.support.v4.app.NotificationCompat
+import android.support.v4.content.LocalBroadcastManager
+import android.telephony.*
+import android.util.Log
+import com.crashlytics.android.Crashlytics
+import com.google.gson.Gson
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.R
+import com.sierrawireless.avphone.activity.MainActivity
+import com.sierrawireless.avphone.task.SendDataParams
+import com.sierrawireless.avphone.task.SendDataTask
+import com.sierrawireless.avphone.tools.DeviceInfo
+import com.sierrawireless.avphone.tools.Tools
+import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken
+import org.eclipse.paho.client.mqttv3.MqttCallback
+import org.eclipse.paho.client.mqttv3.MqttException
+import org.eclipse.paho.client.mqttv3.MqttMessage
+import org.jetbrains.anko.toast
+import java.nio.charset.Charset
+import java.util.*
+import kotlin.concurrent.fixedRateTimer
+
+class MonitoringService : Service() {
+
+ // system services
+ private var telephonyManager: TelephonyManager? = null
+ private var activityManager: ActivityManager? = null
+ private var connManager: ConnectivityManager? = null
+ var set: Boolean? = false
+
+ private var client: MqttPushClient? = null
+
+ var startedSince: Long? = null
+
+ var lastRun: Long? = null
+ private set
+ var lastLog: String? = null
+ private set
+ var lastAlarmLog: String? = null
+ private set
+
+ val lastData = NewData()
+ /* the date of the last location reading */
+ private var lastLocation: Long = 0
+
+ private var networkLocation: Location? = null
+ private var gpsLocation: Location? = null
+ private var networkLocationListener: LocationListener? = null
+ private var gpsLocationListener: LocationListener? = null
+ private var objectsManager: ObjectsManager? = null
+
+ private var phoneStateListener: PhoneStateListener? = null
+
+ private var dbm: Int? = null
+
+ private var timer:Timer? = null
+
+
+ private val lastKnownLocation: Location?
+ @SuppressLint("MissingPermission")
+ get() {
+ val locManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
+
+ val locationProvider = locManager.getBestProvider(Criteria(), true)
+ Log.i(TAG, "Getting last known location from provider: " + locationProvider!!)
+
+ val location: Location? = locManager.getLastKnownLocation(locationProvider)
+ if (location != null) {
+ Log.i(TAG, "Last known location : " + location.latitude + "," + location.longitude)
+ } else {
+ Log.i(TAG, "Read null location")
+ }
+ if (networkLocation != null) {
+ Log.i(TAG, "Last Network Location : " + networkLocation!!.latitude + "," + networkLocation!!.longitude)
+ } else {
+ Log.i(TAG, "No known network location")
+ }
+ if (gpsLocation != null) {
+ Log.i(TAG, "Last GPS Location : " + gpsLocation!!.latitude + "," + gpsLocation!!.longitude)
+ } else {
+ Log.i(TAG, "No known GPSlocation")
+ }
+
+ return location
+ }
+
+ // Service binding
+
+ private val binder = ServiceBinder()
+
+ // MQTT client callback
+
+ private val mqttCallback = object : MqttCallback {
+
+ internal inner class Message {
+ var timestamp: Long = 0
+ var command: Command? = null
+ }
+
+ internal inner class Command {
+ var params: Map? = null
+ }
+
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun createNotificationChannel(): String{
+ val channelId = "messageArrived"
+ val channelName = "messageArrived"
+ val chan = NotificationChannel(channelId,
+ channelName, NotificationManager.IMPORTANCE_NONE)
+ chan.lightColor = Color.BLUE
+ chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
+ val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ service.createNotificationChannel(chan)
+ return channelId
+ }
+
+ @Throws(Exception::class)
+ override fun messageArrived(topic: String, msg: MqttMessage) {
+ Log.i(TAG, "MQTT msg received: " + String(msg.payload))
+
+ // parse json payload
+ val messages = Gson().fromJson(String(msg.payload, Charset.forName("UTF-8")), Array::class.java)
+
+ val channelId =
+ if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ createNotificationChannel()
+ } else {
+ // If earlier version channel ID is not used
+ // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
+ ""
+ }
+ val notification = NotificationCompat.Builder(this@MonitoringService.applicationContext, channelId) //
+ .setContentTitle(getText(R.string.notif_new_message)) //
+ .setContentText(messages[0].command!!.params!!["message"]) //
+ .setSmallIcon(R.drawable.ic_notif) //
+ .setAutoCancel(true) //
+ .build()
+
+ val mNotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ mNotificationManager.notify(messages[0].timestamp.toInt(), notification)
+ }
+
+ override fun deliveryComplete(arg0: IMqttDeliveryToken) {
+ //
+ }
+
+ override fun connectionLost(arg0: Throwable) {
+ //
+ }
+ }
+
+ override fun onCreate() {
+ // Unique Identification Number for the Notification.
+ objectsManager = ObjectsManager.getInstance()
+
+ // Display a notification icon
+
+
+ telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
+ activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
+ connManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+
+ phoneStateListener = object : PhoneStateListener() {
+ override fun onSignalStrengthsChanged(signalStrength: SignalStrength?) {
+ super.onSignalStrengthsChanged(signalStrength)
+ if (signalStrength == null)
+ return
+ if (telephonyManager!!.networkType == TelephonyManager.NETWORK_TYPE_LTE) {
+ val parts = signalStrength.toString().split(" ")
+ dbm = parts[8].toInt() - 240
+ }else{
+ if (signalStrength.gsmSignalStrength != 99) {
+ dbm = -113 + 2 * signalStrength.gsmSignalStrength
+ }
+ }
+
+ }
+
+ }
+
+
+ telephonyManager!!.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS)
+
+
+ startedSince = System.currentTimeMillis()
+ start()
+
+ }
+
+ fun start() {
+ //protect multiple start
+ if (timer == null) {
+ //periodic timer of 5 s do avoid
+ timer = fixedRateTimer("UItimer", false, 0, 2000L) {
+ setCustomDataForUi()
+ }
+ }
+ //setUpLocationListeners()
+ }
+
+
+ @RequiresApi(Build.VERSION_CODES.O)
+ private fun createNotificationChannel(): String{
+ val channelId = "startSend"
+ val channelName = getText(R.string.notif_title)
+ val chan = NotificationChannel(channelId,
+ channelName, NotificationManager.IMPORTANCE_NONE)
+ chan.lightColor = Color.BLUE
+ chan.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
+ val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
+ service.createNotificationChannel(chan)
+ return channelId
+ }
+
+ fun startSendData() {
+ val notif = R.string.notif_title
+ // Create an intent to start the activity when clicking the notification
+ val resultIntent = Intent(this, MainActivity::class.java)
+ val stackBuilder = TaskStackBuilder.create(this)
+ stackBuilder.addParentStack(MainActivity::class.java)
+ stackBuilder.addNextIntent(resultIntent)
+ val resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
+
+ val channelId =
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ createNotificationChannel()
+ } else {
+ // If earlier version channel ID is not used
+ // https://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#NotificationCompat.Builder(android.content.Context)
+ ""
+ }
+
+
+ val notification = NotificationCompat.Builder(this.applicationContext, channelId)//
+ .setContentTitle(getText(R.string.notif_title)) //
+ .setContentText(getText(R.string.notif_desc)) //
+ .setSmallIcon(R.drawable.ic_notif) //
+ .setOngoing(true) //
+ .setContentIntent(resultPendingIntent) //
+ .build()
+
+ startForeground(notif, notification)
+ setUpLocationListeners()
+
+ }
+
+ fun stopSendData() {
+
+ // Cancel the persistent notification.
+ stopForeground(true)
+ stopLocationListeners()
+ }
+
+ @Suppress("DEPRECATION")
+ @SuppressLint("MissingPermission")
+ private fun setCustomDataForUi():NewData {
+ val location = lastKnownLocation
+
+ // retrieve data
+ val data = NewData()
+
+ if (dbm != null) {
+ data.rssi = dbm!!
+ }else {
+
+ val cellInfos = telephonyManager!!.allCellInfo
+ if (cellInfos != null && !cellInfos.isEmpty()) {
+ val cellInfo = cellInfos[0]
+ if (cellInfo is CellInfoGsm) {
+ data.rssi = cellInfo.cellSignalStrength.dbm
+ // } else if (cellInfo instanceof CellInfoWcdma) {
+ // RSSI ?
+ // data.setRssi(((CellInfoWcdma) cellInfo).getCellSignalStrength().getDbm());
+ } else if (cellInfo is CellInfoLte) {
+ data.rsrp = cellInfo.cellSignalStrength.dbm
+ }
+ }
+ }
+
+ if (telephonyManager!!.phoneType == TelephonyManager.PHONE_TYPE_GSM) {
+ @Suppress("DEPRECATION")
+ data.imei = telephonyManager!!.deviceId
+ }
+
+ data.operator = telephonyManager!!.networkOperatorName
+
+ when (telephonyManager!!.networkType) {
+ TelephonyManager.NETWORK_TYPE_GPRS -> data.networkType = "GPRS"
+ TelephonyManager.NETWORK_TYPE_EDGE -> data.networkType = "EDGE"
+ TelephonyManager.NETWORK_TYPE_UMTS -> data.networkType = "UMTS"
+ TelephonyManager.NETWORK_TYPE_HSDPA -> data.networkType = "HSDPA"
+ TelephonyManager.NETWORK_TYPE_HSPAP -> data.networkType = "HSPA+"
+ TelephonyManager.NETWORK_TYPE_HSPA -> data.networkType = "HSPA"
+ TelephonyManager.NETWORK_TYPE_HSUPA -> data.networkType = "HSUPA"
+ TelephonyManager.NETWORK_TYPE_LTE -> data.networkType = "LTE"
+ }// to be continued
+
+
+ // location
+ if (location != null) {
+ data.latitude = location.latitude
+ data.longitude = location.longitude
+ lastLocation = location.time
+ }
+ val connManager: ConnectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
+ val mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
+ val mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
+
+ when {
+ mWifi.isConnected -> {
+ // bytes sent/received
+ data.bytesReceived = TrafficStats.getTotalRxBytes()
+ data.bytesSent = TrafficStats.getTotalTxBytes()
+ }
+ mMobile.isConnected -> {
+ data.bytesReceived = TrafficStats.getMobileRxBytes()
+ data.bytesSent = TrafficStats.getMobileTxBytes()
+ }
+ else -> {
+ data.bytesReceived = 0
+ data.bytesSent = 0
+ }
+ }
+ //execute action on current object datas
+ //objectsManager!!.execOnCurrent()
+ // Custom data
+ data.setCustom()
+
+ // dispatch new data event to update the activity UI
+ LocalBroadcastManager.getInstance(this).sendBroadcast(data)
+ return data
+ }
+
+ @SuppressLint("HardwareIds", "MissingPermission")
+ override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
+
+ lastRun = System.currentTimeMillis()
+ objectsManager = ObjectsManager.getInstance()
+ val obj = objectsManager!!.currentObject
+
+ Log.d(TAG, "alarm received")
+
+ try {
+ val mustConnect = intent.getBooleanExtra(CONNECT, false)
+
+ /* First we have to create the system if it doesn't exist */
+
+ if (this.client == null) {
+
+ //
+ // Ensure intent is valid
+ //
+ val deviceID = intent.getStringExtra(DEVICE_ID)
+ if (deviceID == null) {
+
+ }
+ val deviceId = Tools.buildSerialNumber(intent.getStringExtra(DEVICE_ID), obj!!.name!!, DeviceInfo.deviceName!!)
+ val password = intent.getStringExtra(PASSWORD)
+ val serverHost = intent.getStringExtra(SERVER_HOST)
+
+ val intentValuesList = Arrays.asList(deviceId, password, serverHost)
+ if (intentValuesList.contains(null)) {
+ // Stop service when unable to start MQTT client
+ stopSelfResult(startId)
+ return Service.START_STICKY
+ }
+
+ // Now, create client
+ client = MqttPushClient(deviceId, password, serverHost, mqttCallback)
+ }
+
+
+ if (mustConnect) {
+
+ val data = setCustomDataForUi()
+
+
+ // save new data values
+ if (data.extras != null) {
+ lastData.putExtras(data.extras!!)
+ }
+
+
+ val sendDataTask = SendDataTask()
+ val params = SendDataParams()
+ params.client = client
+ params.data = data
+ params.context = this
+ params.alarm = false
+
+ sendDataTask.execute(params)
+ MainActivity.instance.setAlarm(null)
+
+ sendDataTask.addProgressListener { result -> lastLog = result.lastLog }
+
+ // setUpLocationListeners()
+ }
+
+ } catch (e: Exception) {
+ Crashlytics.logException(e)
+ Log.e(TAG, "error", e)
+ lastLog = "ERROR: " + e.message
+ LocalBroadcastManager.getInstance(this).sendBroadcast(LogMessage(lastLog!!, false))
+ }
+
+ // MainActivity.instance.setAlarm()
+ return Service.START_NOT_STICKY
+ }
+
+ override fun onDestroy() {
+ try {
+ this.client?.disconnect()
+ } catch (e: MqttException) {
+ Crashlytics.logException(e)
+ Log.e(TAG, "error", e)
+ }
+
+ // Cancel the persistent notification.
+ stopForeground(true)
+
+ stopLocationListeners()
+ timer?.cancel()
+ }
+
+ fun cancel(){
+ timer?.cancel()
+ // stopLocationListeners()
+ timer = null
+ }
+
+ @SuppressLint("MissingPermission")
+ private fun setUpLocationListeners() {
+ val locManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
+
+ val networkLocationProvider = locManager.getProvider(LocationManager.NETWORK_PROVIDER)
+ if (networkLocationProvider != null) {
+ networkLocationListener = object : LocationListenerAdapter() {
+ override fun onLocationChanged(location: Location) {
+ Log.i(TAG, "Received Network location update " + location.latitude + ";" + location.longitude)
+ networkLocation = location
+ }
+ }
+
+ locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, (60 * 1000).toLong(), 5f, networkLocationListener)
+ }
+ val gpsLocationProvider = locManager.getProvider(LocationManager.GPS_PROVIDER)
+ if (gpsLocationProvider != null) {
+ gpsLocationListener = object : LocationListenerAdapter() {
+ override fun onLocationChanged(location: Location) {
+ Log.i(TAG, "Received GPS location update " + location.latitude + ";" + location.longitude)
+ gpsLocation = location
+ }
+ }
+ locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, (60 * 1000).toLong(), 5f, gpsLocationListener)
+ }
+ }
+
+ private fun stopLocationListeners() {
+ val locManager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
+
+ if (networkLocationListener != null) {
+ locManager.removeUpdates(networkLocationListener)
+ }
+ if (gpsLocationListener != null) {
+ locManager.removeUpdates(gpsLocationListener)
+ }
+ }
+
+ fun sendAlarmEvent(on:Boolean):Boolean {
+
+ if (this.client == null) {
+ toast("Alarm client is not available,wait...")
+ return false
+ }
+
+ val data = NewData()
+ set = on
+ data.isAlarmActivated = on
+
+ // save alarm state
+ // if (data.getExtras() != null) {
+ // lastData.putExtras(data.getExtras());
+ // }
+
+ val sendDataTask = SendDataTask()
+ val params = SendDataParams()
+ params.client = client
+ params.data = data
+ params.context = this
+ params.alarm = true
+ params.value = on
+
+ sendDataTask.execute(params)
+
+
+ sendDataTask.addProgressListener { result ->
+ lastAlarmLog = result.alarmLog
+ }
+ return true
+ }
+
+ override fun onBind(arg0: Intent): IBinder? {
+ return binder
+ }
+
+ inner class ServiceBinder : Binder() {
+
+ val service: MonitoringService
+ get() = this@MonitoringService
+ }
+
+ companion object {
+ // Intent extra keys
+ const val DEVICE_ID = "device_id"
+ const val SERVER_HOST = "server_host"
+ const val PASSWORD = "password"
+ const val CONNECT = "connect"
+ const val OBJECT_NAME = "objname"
+ private val TAG = MonitoringService::class.simpleName
+ const val CHANNEL_ID = "Channel one"
+ }
+
+}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java
deleted file mode 100644
index 0752139..0000000
--- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java
+++ /dev/null
@@ -1,201 +0,0 @@
-package com.sierrawireless.avphone.service;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.eclipse.paho.client.mqttv3.MqttCallback;
-import org.eclipse.paho.client.mqttv3.MqttClient;
-import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
-import org.eclipse.paho.client.mqttv3.MqttException;
-import org.eclipse.paho.client.mqttv3.MqttMessage;
-import org.eclipse.paho.client.mqttv3.MqttSecurityException;
-import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
-
-import android.annotation.SuppressLint;
-import android.util.Log;
-
-import com.google.gson.Gson;
-import com.sierrawireless.avphone.model.AvPhoneData;
-
-public class MqttPushClient {
-
- private static final String LOGTAG = MqttPushClient.class.getName();
-
- private MqttClient client;
- private MqttConnectOptions opt;
-
- private Gson gson = new Gson();
-
- @SuppressLint("DefaultLocale")
- public MqttPushClient(String clientId, String password, String serverHost, MqttCallback callback)
- throws MqttException {
-
- Log.d(LOGTAG, "new client: " + clientId + " - " + password + " - " + serverHost);
-
- this.client = new MqttClient("tcp://" + serverHost + ":1883", MqttClient.generateClientId(),
- new MemoryPersistence());
- client.setCallback(callback);
-
- this.opt = new MqttConnectOptions();
- opt.setUserName(clientId.toUpperCase());
- opt.setPassword(password.toCharArray());
- opt.setKeepAliveInterval(30);
- }
-
- public boolean isConnected() {
- return client.isConnected();
- }
-
- public void connect() throws MqttSecurityException, MqttException {
- Log.d(LOGTAG, "connecting");
- client.connect(opt);
- }
-
- public void disconnect() throws MqttException {
- if (client.isConnected()) {
- client.disconnect();
- }
- }
-
- public void push(NewData data) throws MqttException {
- if (client.isConnected()) {
- Log.i(LOGTAG, "Pushing data to the server : " + data);
- String message = this.convertToJson(data);
-
- Log.d(LOGTAG, "Rest content : " + message);
-
- MqttMessage msg = null;
- try {
- msg = new MqttMessage(message.getBytes("UTF-8"));
- } catch (UnsupportedEncodingException e) {
- // won't happen, UTF-8 is available
- }
- msg.setQos(0);
-
- this.client.publish(opt.getUserName() + "/messages/json", msg);
- }
- }
-
- private String convertToJson(NewData data) {
- long timestamp = System.currentTimeMillis();
-
- Map> values = new HashMap>();
-
- if (data.getRssi() != null) {
- values.put(AvPhoneData.RSSI, Collections.singletonList(new DataValue(timestamp, data.getRssi())));
- values.put("_RSSI", Collections.singletonList(new DataValue(timestamp, data.getRssi())));
- }
-
- if (data.getRsrp() != null) {
- values.put(AvPhoneData.RSRP, Collections.singletonList(new DataValue(timestamp, data.getRsrp())));
- values.put("_RSRP", Collections.singletonList(new DataValue(timestamp, data.getRsrp())));
- }
-
- if (data.getBatteryLevel() != null) {
- values.put(AvPhoneData.BATTERY,
- Collections.singletonList(new DataValue(timestamp, data.getBatteryLevel())));
- }
-
- if (data.getOperator() != null) {
- values.put(AvPhoneData.OPERATOR, Collections.singletonList(new DataValue(timestamp, data.getOperator())));
- }
-
- if (data.getImei() != null) {
- values.put(AvPhoneData.IMEI, Collections.singletonList(new DataValue(timestamp, data.getImei())));
- }
-
- if (data.getNetworkType() != null) {
- values.put(AvPhoneData.SERVICE, Collections.singletonList(new DataValue(timestamp, data.getNetworkType())));
- // hack for data mapping
- values.put("_NETWORK_SERVICE_TYPE",
- Collections.singletonList(new DataValue(timestamp, data.getNetworkType())));
- }
-
- if (data.getLatitude() != null) {
- values.put(AvPhoneData.LAT, Collections.singletonList(new DataValue(timestamp, data.getLatitude())));
- // hack for data mapping
- values.put("_LATITUDE", Collections.singletonList(new DataValue(timestamp, data.getLatitude())));
- }
-
- if (data.getLongitude() != null) {
- values.put(AvPhoneData.LONG, Collections.singletonList(new DataValue(timestamp, data.getLongitude())));
- // hack for data mapping
- values.put("_LONGITUDE", Collections.singletonList(new DataValue(timestamp, data.getLongitude())));
- }
-
- if (data.getBytesReceived() != null) {
- // hack for data mapping
- values.put(AvPhoneData.BYTES_RECEIVED,
- Collections.singletonList(new DataValue(timestamp, data.getBytesReceived())));
- values.put("_BYTES_RECEIVED", Collections.singletonList(new DataValue(timestamp, data.getBytesReceived())));
- }
-
- if (data.getBytesSent() != null) {
- // hack for data mapping
- values.put(AvPhoneData.BYTES_SENT, Collections.singletonList(new DataValue(timestamp, data.getBytesSent())));
- values.put("_BYTES_SENT", Collections.singletonList(new DataValue(timestamp, data.getBytesSent())));
- }
-
- if (data.isWifiActive() != null) {
- values.put(AvPhoneData.ACTIVE_WIFI, Collections.singletonList(new DataValue(timestamp, data.isWifiActive())));
- }
-
- if (data.getRunningApps() != null) {
- values.put(AvPhoneData.RUNNING_APPS, Collections.singletonList(new DataValue(timestamp, data.getRunningApps())));
- }
-
- if (data.getMemoryUsage() != null) {
- values.put(AvPhoneData.MEMORY_USAGE, Collections.singletonList(new DataValue(timestamp, data.getMemoryUsage())));
- }
-
- if (data.getAndroidVersion() != null) {
- values.put(AvPhoneData.ANDROID_VERSION,
- Collections.singletonList(new DataValue(timestamp, data.getAndroidVersion())));
- // values.put("_FIRMWARE_VERSION", Collections.singletonList(new DataValue(timestamp,
- // data.getAndroidVersion())));
- }
-
- if (data.isAlarmActivated() != null) {
- values.put(AvPhoneData.ALARM,
- Collections.singletonList(new DataValue(timestamp, data.isAlarmActivated())));
- }
-
- if (data.getCustomIntUp1() != null) {
- values.put(AvPhoneData.CUSTOM_1, Collections.singletonList(new DataValue(timestamp, data.getCustomIntUp1())));
- }
- if (data.getCustomIntUp2() != null) {
- values.put(AvPhoneData.CUSTOM_2, Collections.singletonList(new DataValue(timestamp, data.getCustomIntUp2())));
- }
- if (data.getCustomIntDown1() != null) {
- values.put(AvPhoneData.CUSTOM_3,
- Collections.singletonList(new DataValue(timestamp, data.getCustomIntDown1())));
- }
- if (data.getCustomIntDown2() != null) {
- values.put(AvPhoneData.CUSTOM_4,
- Collections.singletonList(new DataValue(timestamp, data.getCustomIntDown2())));
- }
- if (data.getCustomStr1() != null) {
- values.put(AvPhoneData.CUSTOM_5, Collections.singletonList(new DataValue(timestamp, data.getCustomStr1())));
- }
- if (data.getCustomStr2() != null) {
- values.put(AvPhoneData.CUSTOM_6, Collections.singletonList(new DataValue(timestamp, data.getCustomStr2())));
- }
-
- return gson.toJson(Collections.singletonList(values));
- }
-
- class DataValue {
-
- DataValue(long timestamp, Object value) {
- this.timestamp = timestamp;
- this.value = value;
- }
-
- long timestamp;
- Object value;
- }
-
-}
diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.kt b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.kt
new file mode 100644
index 0000000..2737519
--- /dev/null
+++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.kt
@@ -0,0 +1,138 @@
+package com.sierrawireless.avphone.service
+
+import android.annotation.SuppressLint
+import android.util.Log
+import com.google.gson.Gson
+import com.sierrawireless.avphone.tools.DeviceInfo
+import com.sierrawireless.avphone.ObjectsManager
+import com.sierrawireless.avphone.model.AvPhoneData
+import com.sierrawireless.avphone.model.AvPhoneObjectData
+import org.eclipse.paho.client.mqttv3.*
+import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
+import java.io.UnsupportedEncodingException
+import java.util.*
+
+class MqttPushClient @SuppressLint("DefaultLocale")
+@Throws(MqttException::class)
+internal constructor(clientId: String, password: String, serverHost: String, callback: MqttCallback) {
+ private val client: MqttClient
+ private val opt: MqttConnectOptions
+ private val gson = Gson()
+ private val objectsManager: ObjectsManager
+ val isConnected: Boolean
+ get() = client.isConnected
+
+ init {
+
+ DeviceInfo.generateSerial("")
+ Log.i(TAG, "new client: $clientId - $password - $serverHost")
+
+ this.client = MqttClient("tcp://$serverHost:1883", MqttClient.generateClientId(),
+ MemoryPersistence())
+ client.setCallback(callback)
+
+ this.opt = MqttConnectOptions()
+ opt.userName = clientId.toUpperCase()
+ opt.password = password.toCharArray()
+ opt.keepAliveInterval = 30
+ objectsManager = ObjectsManager.getInstance()
+ }
+
+ @Throws(MqttException::class)
+ fun connect() {
+ client.connect(opt)
+ }
+
+ @Throws(MqttException::class)
+ internal fun disconnect() {
+ if (client.isConnected) {
+ client.disconnect()
+ }
+ }
+
+ @Throws(MqttException::class)
+ fun push(data: NewData) {
+ if (client.isConnected) {
+ Log.i(TAG, "Pushing data to the server : " + data)
+ val message = this.convertToJson(data)
+ Log.i(TAG, "push: message " + message)
+
+ var msg: MqttMessage? = null
+ try {
+ msg = MqttMessage(message.toByteArray(charset("UTF-8")))
+ } catch (e: UnsupportedEncodingException) {
+ // won't happen, UTF-8 is available
+ }
+
+ if (msg != null) {
+ msg.qos = 0
+ }
+ this.client.publish(opt.userName + "/messages/json", msg)
+ }
+ }
+
+ private fun convertToJson(data: NewData): String {
+ val timestamp = System.currentTimeMillis()
+
+ val values = HashMap>()
+
+ if (data.rssi != null) {
+ values["_RSSI"] = listOf(DataValue(timestamp, data.rssi!!))
+ }
+
+ if (data.rsrp != null) {
+ values["_RSRP"] = listOf(DataValue(timestamp, data.rsrp!!))
+ }
+
+ if (data.operator != null) {
+ values["_NETWORK_OPERATOR"] = listOf(DataValue(timestamp, data.operator!!))
+ }
+
+
+ if (data.networkType != null) {
+ values["_NETWORK_SERVICE_TYPE"] = listOf(DataValue(timestamp, data.networkType!!))
+ }
+
+ if (data.latitude != null) {
+ values["_LATITUDE"] = listOf(DataValue(timestamp, data.latitude!!))
+ }
+
+ if (data.longitude != null) {
+ values["_LONGITUDE"] = listOf(DataValue(timestamp, data.longitude!!))
+ }
+
+ if (data.bytesReceived != null) {
+ values["_BYTES_RECEIVED"] = listOf(DataValue(timestamp, data.bytesReceived!!))
+ }
+
+ if (data.bytesSent != null) {
+ values["_BYTES_SENT"] = listOf(DataValue(timestamp, data.bytesSent!!))
+ }
+
+ if (data.isAlarmActivated != null) {
+ values[AvPhoneData.ALARM] = listOf(DataValue(timestamp, data.isAlarmActivated!!))
+ } else {
+ val obj = objectsManager.currentObject
+ var pos: Int? = 1
+ var key: String?
+ for (ldata in obj!!.datas) {
+ key = ldata.path ?: obj.name + "." + AvPhoneData.CUSTOM + pos!!.toString()
+ if (ldata.mode != AvPhoneObjectData.Mode.None) {
+ values[key] = listOf(DataValue(timestamp, ldata.current!!))
+ } else {
+ values[key] = listOf(DataValue(timestamp, ldata.defaults))
+ }
+ pos = pos!! + 1
+ }
+ }
+ return gson.toJson(listOf
+
+
-
\ No newline at end of file
+
\ No newline at end of file
diff --git a/mainActivity/src/main/res/layout/activity_fortests.xml b/mainActivity/src/main/res/layout/activity_fortests.xml
index 7b5bb0c..b2dbe92 100644
--- a/mainActivity/src/main/res/layout/activity_fortests.xml
+++ b/mainActivity/src/main/res/layout/activity_fortests.xml
@@ -9,5 +9,5 @@
android:layout_height="fill_parent"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
- />
+ android:orientation="horizontal" />
\ No newline at end of file
diff --git a/mainActivity/src/main/res/layout/activity_main.xml b/mainActivity/src/main/res/layout/activity_main.xml
index f804c0d..143e49b 100644
--- a/mainActivity/src/main/res/layout/activity_main.xml
+++ b/mainActivity/src/main/res/layout/activity_main.xml
@@ -10,12 +10,11 @@
+ android:dividerHeight="0dp" />
diff --git a/mainActivity/src/main/res/layout/activity_object_configure.xml b/mainActivity/src/main/res/layout/activity_object_configure.xml
new file mode 100644
index 0000000..b311ba1
--- /dev/null
+++ b/mainActivity/src/main/res/layout/activity_object_configure.xml
@@ -0,0 +1,78 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/mainActivity/src/main/res/layout/activity_object_data.xml b/mainActivity/src/main/res/layout/activity_object_data.xml
new file mode 100644
index 0000000..007e9bd
--- /dev/null
+++ b/mainActivity/src/main/res/layout/activity_object_data.xml
@@ -0,0 +1,164 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/mainActivity/src/main/res/layout/drawer_item.xml b/mainActivity/src/main/res/layout/drawer_item.xml
index 7e361fe..cb5895c 100644
--- a/mainActivity/src/main/res/layout/drawer_item.xml
+++ b/mainActivity/src/main/res/layout/drawer_item.xml
@@ -1,8 +1,9 @@
\ No newline at end of file
diff --git a/mainActivity/src/main/res/layout/fragment_configure.xml b/mainActivity/src/main/res/layout/fragment_configure.xml
index 9ef35c2..5892f6f 100644
--- a/mainActivity/src/main/res/layout/fragment_configure.xml
+++ b/mainActivity/src/main/res/layout/fragment_configure.xml
@@ -1,5 +1,7 @@
-
-
-
+
+ app:layout_constraintTop_toBottomOf="@+id/resync" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ android:layout_marginEnd="8dp"
+ android:layout_marginTop="8dp"
+ android:text="@string/add"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintTop_toTopOf="parent" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
+
+
+
+
\ No newline at end of file
diff --git a/mainActivity/src/main/res/layout/fragment_home.xml b/mainActivity/src/main/res/layout/fragment_home.xml
index cddb95f..2bcce19 100644
--- a/mainActivity/src/main/res/layout/fragment_home.xml
+++ b/mainActivity/src/main/res/layout/fragment_home.xml
@@ -10,7 +10,7 @@
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:showDividers="middle"
- tools:context=".MainActivity" >
+ tools:context=".activity.MainActivity" >
-
+
+
+
@@ -92,7 +106,7 @@
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:gravity="center"
- android:text="@string/home_login_message" />
+ android:text="@string/home_login_message_str" />
+ tools:context=".activity.MainActivity" >
+ android:orientation="vertical">
-
+ android:text="AirVantage" />
+
+
+ android:textColor="@android:color/white"
+ android:visibility="gone" />
+ android:orientation="horizontal">
+ android:orientation="vertical">
+ android:textOff="@string/off"
+ android:textOn="@string/on"
+ android:theme="@style/Switch" />
+
+
+ android:orientation="vertical">
-
+ android:background="@color/grey_4"
+ android:baselineAligned="false"
+ android:text="@string/send"
+ android:textAlignment="center" />
+
+
@@ -98,493 +120,63 @@
android:gravity="center"
android:text="@string/toggle_to_start"
android:textSize="12sp" />
-
+
-
-
-
-
-
+ android:textSize="12sp"
+ android:visibility="gone" />
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+
-
+
-
-
-
-
+ android:background="@color/grey_4"
+ android:text="@string/phone"
+ app:layout_constraintBaseline_toBaselineOf="@+id/obj"
+ app:layout_constraintEnd_toStartOf="@+id/obj"
+ app:layout_constraintStart_toStartOf="parent" />
-
+ android:background="@color/grey_4"
+ app:layout_constraintEnd_toEndOf="parent"
+ app:layout_constraintStart_toEndOf="@+id/phone"
+ app:layout_constraintTop_toTopOf="parent" />
+
-
-
-
-
-
-
-
-
-
-
+
+
-
+
+
+
\ No newline at end of file
diff --git a/mainActivity/src/main/res/layout/menu_layout.xml b/mainActivity/src/main/res/layout/menu_layout.xml
new file mode 100644
index 0000000..8650c2b
--- /dev/null
+++ b/mainActivity/src/main/res/layout/menu_layout.xml
@@ -0,0 +1,35 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/mainActivity/src/main/res/layout/menu_objects.xml b/mainActivity/src/main/res/layout/menu_objects.xml
new file mode 100644
index 0000000..fc3f153
--- /dev/null
+++ b/mainActivity/src/main/res/layout/menu_objects.xml
@@ -0,0 +1,49 @@
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/mainActivity/src/main/res/layout/run_column_row.xml b/mainActivity/src/main/res/layout/run_column_row.xml
new file mode 100644
index 0000000..542cab5
--- /dev/null
+++ b/mainActivity/src/main/res/layout/run_column_row.xml
@@ -0,0 +1,25 @@
+
+
+
+
+
+
+
+
diff --git a/mainActivity/src/main/res/menu/main.xml b/mainActivity/src/main/res/menu/main.xml
index c002028..d122a4b 100644
--- a/mainActivity/src/main/res/menu/main.xml
+++ b/mainActivity/src/main/res/menu/main.xml
@@ -1,9 +1,9 @@
-
+
diff --git a/mainActivity/src/main/res/values/colors.xml b/mainActivity/src/main/res/values/colors.xml
index cb25aba..9c2b1b7 100644
--- a/mainActivity/src/main/res/values/colors.xml
+++ b/mainActivity/src/main/res/values/colors.xml
@@ -1,18 +1,18 @@
-
-
-
- #E53B30
-
- #666666
- #6A8E9A
- #99B1B9
- #A0ACAF
-
- #F7781E
- #621B4B
-
- #00AEAF
- #00677A
- #003640
- #87B527
-
+
+
+
+ #E53B30
+
+ #666666
+ #6A8E9A
+ #99B1B9
+ #A0ACAF
+
+ #F7781E
+ #621B4B
+
+ #00AEAF
+ #00677A
+ #003640
+ #87B527
+
diff --git a/mainActivity/src/main/res/values/strings.xml b/mainActivity/src/main/res/values/strings.xml
index 1772630..8826191 100644
--- a/mainActivity/src/main/res/values/strings.xml
+++ b/mainActivity/src/main/res/values/strings.xml
@@ -87,14 +87,14 @@
Logout
Welcome to AV Phone
+
+
-
-
- Simulate any object with your phone
+ Simulate any object with your phone.\nClick on menu\nClick on simulated object to go on simulation page
- Create a simulated object automatically in your AirVantage account]]>
+ Create a simulated object automatically in your AirVantage account]]>
- Login to your Airvantage account
+ Login to your AirVantage accountAmericaEurope
@@ -117,6 +117,7 @@
Creating applicationChecking systemCreating system
+ Updating systemChecking alert ruleCreating alert ruleUpdating alert rule
@@ -124,21 +125,21 @@
Adding applicationDone
- Error : A system already exists with this serial number (maybe in another company.)
- Error : A gateway already exists with this serial number (maybe in another company.)
- Error : An application with type %1$s already exists (maybe in another company)
+ Error : A system already exists with this serial number (maybe in another company).
+ Error : A gateway already exists with this serial number (maybe in another company).
+ Error : An application with type %1$s already exists (maybe in another company).Error : There are too many alert rules registered in your company.
- Error : You don\'t have the right to create application. Contact your administrator
+ Error : You don\'t have the right to create application. Contact your administrator.
- Error : You don\'t have the right to create a system. Contact your administrator
- Error : You don\'t have the right to create an alert rule. Contact your administrator
+ Error : You don\'t have the right to create a system. Contact your administrator.
+ Error : You don\'t have the right to create an alert rule. Contact your administrator.Error : You don\'t have the right to update an application. Contact your administrator
- Error : You don\'t have the right to update a system. Contact your administrator
- Error : You are not allowed to %1$s on URL %2$s
+ Error : You don\'t have the right to update a system. Contact your administrator.
+ Error : You are not allowed to %1$s on URL %2$s.Error : Unable to get user data.
- Error : Unexpected error (%1$s)
+ Error : Unexpected error (%1$s).
- Synchronized with AirVantage
+ Synchronized with AirVantage.Your phone is registered on AirVantage as gateway %1$s.
@@ -148,7 +149,7 @@
]]>
Send Data
- Send Alarm
+ Raise/Cancel Alarm
@@ -177,5 +178,35 @@
Create and edit an alert ruleAV Phone navigation is availableAV Phone navigation is no longer available
+ Welcome
+ Add new system
+ Add new data
+ Deleting alert rule
+ Deleting system
+ menuicon
+ Edit
+ delete
+ none
+ OFF
+ ON
+ Send
+ Phone
+ Cancel
+ Save
+ Name
+ Add
+ Done
+ Raise
+ Unit
+ Default Value. For random mode enter: min,max value.
+ Simulation Type
+ An object name must be specified before to save it.
+ Alert
+ An object name must be specified before to add data.
+ An object data name must be specified before to save it.
+ Mode is RANDOM, but the default entry is not valid (min,max)
+ Mode is UP or DOWN, but the default entry is not a number.
+ Mode is RANDOM, but the default entry is not valid (min,max)\n.Min and max must be numbers.
+ Resync All
\ No newline at end of file