From 3b4f15b54cb10da874089ef5fd52e69d97776b27 Mon Sep 17 00:00:00 2001 From: Jean-bernard Damiano Date: Wed, 24 Jan 2018 13:17:01 +0100 Subject: [PATCH 01/60] Fix Alarm, Add FAQ, Add issue with selected option in menu, Rework the system register to prepare the object add Application is now registered as UserID+"-ANDROID-"+TYPE TYPE is the object TYPE. Only printer. --- build.gradle | 2 +- mainActivity/build.gradle | 23 +- .../avphone/AuthorizationActivity.java | 7 +- .../avphone/CustomLabelsListener.java | 2 +- .../avphone/CustomLabelsManager.java | 2 +- .../avphone/DataViewUpdater.java | 8 +- .../sierrawireless/avphone/DeviceInfo.java | 51 +++- .../sierrawireless/avphone/HomeFragment.java | 7 +- .../sierrawireless/avphone/LoginListener.java | 2 +- .../sierrawireless/avphone/MainActivity.java | 116 ++++++- .../avphone/MonitorServiceListener.java | 4 +- .../avphone/MonitorServiceManager.java | 15 +- .../sierrawireless/avphone/RunFragment.java | 28 +- .../avphone/message/IMessageDisplayer.java | 6 +- .../avphone/model/AvPhoneApplication.java | 22 +- .../avphone/service/MonitoringService.java | 282 +++++++++++------- .../avphone/service/MqttPushClient.java | 73 ++--- .../avphone/task/AsyncTaskFactory.java | 4 +- .../avphone/task/ISystemClient.java | 2 +- .../avphone/task/SyncWithAvParams.java | 2 + .../avphone/task/SyncWithAvTask.java | 9 +- .../avphone/task/SystemClient.java | 10 +- .../java/net/airvantage/model/AvSystem.java | 2 +- .../airvantage/utils/AirVantageClient.java | 19 ++ .../net/airvantage/utils/PreferenceUtils.java | 2 + .../apptheme_switch_inner_holo_light.xml | 1 + .../main/res/drawable/listitem_selector.xml | 7 + .../src/main/res/layout/activity_main.xml | 3 +- .../src/main/res/layout/drawer_item.xml | 1 + .../src/main/res/layout/fragment_run.xml | 14 +- 30 files changed, 477 insertions(+), 249 deletions(-) create mode 100644 mainActivity/src/main/res/drawable/listitem_selector.xml diff --git a/build.gradle b/build.gradle index bbe9eb2..e4467f8 100644 --- a/build.gradle +++ b/build.gradle @@ -4,7 +4,7 @@ buildscript { jcenter() } dependencies { - classpath 'com.android.tools.build:gradle:2.1.3' + classpath 'com.android.tools.build:gradle:3.0.1' } } diff --git a/mainActivity/build.gradle b/mainActivity/build.gradle index c05f4b7..ee5cb5e 100644 --- a/mainActivity/build.gradle +++ b/mainActivity/build.gradle @@ -12,12 +12,14 @@ apply plugin: 'io.fabric' repositories { maven { url 'https://maven.fabric.io/public' } + maven { + url "https://repo.eclipse.org/content/repositories/paho-snapshots/" + } } android { compileSdkVersion 22 - buildToolsVersion '24.0.1' defaultConfig { applicationId 'com.sierrawireless.avphone' @@ -38,13 +40,22 @@ 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 'com.android.support:support-v4:22.2.1' + compile 'com.android.support:appcompat-v7:22.2.1' + compile 'com.google.code.gson:gson:2.8.0' + compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2' + //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; } + compile('com.crashlytics.sdk.android:crashlytics-ndk:2.0.1@aar') { + transitive = true; + } +} + +crashlytics { + enableNdk true + androidNdkOut 'src/main/obj' + androidNdkLibsOut 'src/main/libs' } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java index 2b28ddf..93ece8d 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java @@ -3,6 +3,7 @@ import android.annotation.SuppressLint; import android.app.Activity; import android.content.Intent; +import android.os.Build; import android.os.Bundle; import android.util.Log; import android.view.View; @@ -50,7 +51,7 @@ private final class OnHostClickListener implements OnClickListener { private final PreferenceUtils.Server server; - public OnHostClickListener(final PreferenceUtils.Server targetServer) { + private OnHostClickListener(final PreferenceUtils.Server targetServer) { server = targetServer; } @@ -124,9 +125,9 @@ public boolean shouldOverrideUrlLoading(WebView view, String url) { // 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(); + cookieManager.removeAllCookies(null); + // Example : // https://na.airvantage.net/api/oauth/authorize?client_id=54d4faa5343d49fba03f2a2ec1f210b9&response_type=token&redirect_uri=oauth://airvantage diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java index de3193e..7dc7aa4 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsListener.java @@ -1,5 +1,5 @@ package com.sierrawireless.avphone; public interface CustomLabelsListener { - public void onCustomLabelsChanged(); + void onCustomLabelsChanged(); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java index e8fd3fe..ea382c4 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/CustomLabelsManager.java @@ -1,5 +1,5 @@ package com.sierrawireless.avphone; public interface CustomLabelsManager { - public void setCustomLabelsListener(CustomLabelsListener listener); + void setCustomLabelsListener(CustomLabelsListener listener); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java index 595a18a..45c8b88 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java @@ -9,7 +9,6 @@ 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; @@ -44,14 +43,14 @@ public void onStart(Long startedSince, NewData lastData, String logMsg, Long las this.setLogMessage(logMsg, lastRun); // activate alarm button - view.findViewById(R.id.alarm_switch).setEnabled(true); + //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); + //view.findViewById(R.id.alarm_switch).setEnabled(false); } private void setLogMessage(String log, Long timestamp) { @@ -128,9 +127,6 @@ private void setNewData(NewData data) { 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); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java index a176f03..727bf39 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java @@ -1,11 +1,51 @@ package com.sierrawireless.avphone; import android.annotation.SuppressLint; +import android.content.ContentResolver; import android.content.Context; +import android.os.Build; +import android.telephony.SubscriptionInfo; +import android.telephony.SubscriptionManager; import android.telephony.TelephonyManager; +import android.text.TextUtils; +import android.util.Log; + +import java.util.List; public class DeviceInfo { + private static final String TAG = "DeviceInfo"; + + /** Returns the consumer friendly device name */ + public static String getDeviceName() { + String manufacturer = Build.MANUFACTURER; + String model = Build.MODEL; + if (model.toUpperCase().startsWith(manufacturer.toUpperCase())) { + return capitalize(model); + } + return capitalize(manufacturer) + " " + model; + } + + private static String capitalize(String str) { + if (TextUtils.isEmpty(str)) { + return str; + } + char[] arr = str.toCharArray(); + boolean capitalizeNext = true; + StringBuilder phrase = new StringBuilder(); + for (char c : arr) { + if (capitalizeNext && Character.isLetter(c)) { + phrase.append(Character.toUpperCase(c)); + capitalizeNext = false; + continue; + } else if (Character.isWhitespace(c)) { + capitalizeNext = true; + } + phrase.append(c); + } + + return phrase.toString(); + } /** * Serial number is in `syncParams.deviceId`, why not using it? @@ -17,7 +57,8 @@ public class DeviceInfo { */ @SuppressLint("DefaultLocale") public static String generateSerial(final String userUid, final String systemType) { - return (userUid + "-" + systemType).toUpperCase(); + Log.d(TAG, "generateSerial*****************: system_id is " + getDeviceName()); + return (userUid); } @SuppressLint("DefaultLocale") @@ -55,4 +96,12 @@ public static String getIMEI(final Context context) { return null; } + + public static String getICCID(final Context context) { + SubscriptionManager sm = SubscriptionManager.from(context); + List sis = sm.getActiveSubscriptionInfoList(); + SubscriptionInfo si = sis.get(0); + return si.getIccId(); + + } } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java index fcb1a69..35cca94 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java @@ -110,15 +110,14 @@ public void onResume() { } private TextView getInfoMessageView() { - TextView infoMessageView = (TextView) view.findViewById(R.id.home_info_message); - return infoMessageView; + return (TextView) view.findViewById(R.id.home_info_message); } private void showCurrentServer() { AvPhonePrefs phonePrefs = PreferenceUtils.getAvPhonePrefs(getActivity()); TextView infoMessageView = getInfoMessageView(); - String message = null; + String message; if (phonePrefs.usesNA()) { message = getString(R.string.logged_on_na); } else if (phonePrefs.usesEU()) { @@ -183,6 +182,8 @@ public void onSynced(SyncWithAvResult result) { params.deviceId = DeviceInfo.getUniqueId(getActivity()); params.imei = DeviceInfo.getIMEI(getActivity()); + params.deviceName = DeviceInfo.getDeviceName(); + params.iccid = DeviceInfo.getICCID(getActivity()); params.mqttPassword = avPhonePrefs.password; params.customData = PreferenceUtils.getCustomDataLabels(getActivity()); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java b/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java index 546a5bc..6960001 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/LoginListener.java @@ -2,6 +2,6 @@ public interface LoginListener { - public void OnLoginChanged(boolean logged); + 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 index 0ef8477..d8d6221 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java @@ -14,6 +14,7 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.content.res.Configuration; +import android.net.Uri; import android.os.Bundle; import android.os.IBinder; import android.preference.PreferenceManager; @@ -28,8 +29,10 @@ import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; +import android.widget.Toast; import com.crashlytics.android.Crashlytics; +import com.crashlytics.android.ndk.CrashlyticsNdk; import com.sierrawireless.avphone.auth.Authentication; import com.sierrawireless.avphone.auth.AuthenticationManager; import com.sierrawireless.avphone.service.MonitoringService; @@ -44,7 +47,6 @@ 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; @@ -56,16 +58,16 @@ * The main activity, handling drawer and Fragments */ public class MainActivity extends FragmentActivity + implements LoginListener, AuthenticationManager, OnSharedPreferenceChangeListener, MonitorServiceManager, CustomLabelsManager, SyncWithAvListener { + private static final String TAG = "MainActivity"; 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; @@ -85,16 +87,22 @@ public class MainActivity extends FragmentActivity private final static String FRAGMENT_RUN = "Run"; private final static String FRAGMENT_CONFIGURE = "Configure"; private final static String FRAGMENT_SETTINGS = "Settings"; + private final static String FRAGMENT_FAQ = "FAQ"; private ConfigureFragment configureFragment; private HomeFragment homeFragment; private RunFragment runFragment; + private int lastPosition = 0; + + private Boolean serviceSendData = false; + private final static String[] FRAGMENT_LIST = new String[]{ FRAGMENT_HOME, FRAGMENT_RUN, FRAGMENT_CONFIGURE, FRAGMENT_SETTINGS, + FRAGMENT_FAQ, }; public void setCustomLabelsListener(CustomLabelsListener customLabelsListener) { @@ -104,7 +112,7 @@ public void setCustomLabelsListener(CustomLabelsListener customLabelsListener) { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); - Fabric.with(this, new Crashlytics()); + Fabric.with(this, new Crashlytics(), new CrashlyticsNdk()); setContentView(R.layout.activity_main); @@ -119,6 +127,7 @@ protected void onCreate(Bundle savedInstanceState) { drawerListView = (ListView) findViewById(R.id.left_drawer); drawerListView.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_item, FRAGMENT_LIST)); + drawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Set the list's click listener drawerListView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override @@ -158,6 +167,18 @@ public void onItemClick(AdapterView parent, View view, int position, long id) { selectItem(currentFragment); } + @Override + protected void onResume() { + super.onResume(); + Toast.makeText(getApplicationContext(), "On resume "+ lastPosition, Toast.LENGTH_SHORT).show(); + drawerListView.requestFocusFromTouch(); + drawerListView.setItemChecked(lastPosition, true); + drawerListView.setSelection(lastPosition); + Toast.makeText(getApplicationContext(), "On resume "+ lastPosition + " " + drawerListView.getCheckedItemPosition(), Toast.LENGTH_SHORT).show(); + drawerListView.refreshDrawableState(); + //drawerListView.setSelection(); + } + @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); @@ -205,7 +226,7 @@ private void unlockDrawer() { if (drawerLayout != null) { drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED); - drawerLayout.openDrawer(Gravity.LEFT); + drawerLayout.openDrawer(Gravity.START); } if (drawerToggle != null) { @@ -232,7 +253,7 @@ public void onAuthentication(Authentication auth) { unlockDrawer(); saveAuthenticationInPreferences(auth); - } + } @Override public Authentication getAuthentication() { @@ -267,7 +288,7 @@ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, Strin this.restartMonitoringService(); - } else if (key.indexOf("pref_data_custom") != -1) { + } else if (key.contains("pref_data_custom")) { if (this.customLabelsListener != null) { this.customLabelsListener.onCustomLabelsChanged(); @@ -277,16 +298,42 @@ public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, Strin } public boolean isServiceRunning() { + //return serviceSendData; + + ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); + if (manager == null) { + Log.e(TAG, "isServiceRunning: can't get activity service"); + Toast.makeText(getApplicationContext(), "can't get activity service" ,Toast.LENGTH_SHORT).show(); + return false; + } + for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (MonitoringService.class.getName().equals(service.service.getClassName())) { + return serviceSendData; + } + } + return false; + + } + + public boolean isServiceStarted() { + //return serviceSendData; + ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); + if (manager == null) { + Log.e(TAG, "isServiceRunning: can't get activity service"); + Toast.makeText(getApplicationContext(), "can't get activity service" ,Toast.LENGTH_SHORT).show(); + return false; + } for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { if (MonitoringService.class.getName().equals(service.service.getClassName())) { return true; } } return false; + } - private void connectToService() { + public void connectToService() { Intent intent = new Intent(this, MonitoringService.class); boundToMonitoringService = this.bindService(intent, connection, Context.BIND_AUTO_CREATE); } @@ -305,7 +352,7 @@ private void disconnectFromService() { @Override public void onServiceConnected(ComponentName arg0, IBinder binder) { - Log.d(LOGTAG, "Connected to the monitoring service"); + Log.d(TAG, "Connected to the monitoring service"); monitoringService = ((ServiceBinder) binder).getService(); if (monitoringServiceListener != null) { @@ -316,16 +363,16 @@ public void onServiceConnected(ComponentName arg0, IBinder binder) { @Override public void onServiceDisconnected(ComponentName arg0) { - Log.d(LOGTAG, "Disconnected from the monitoring service"); + Log.d(TAG, "Disconnected from the monitoring service"); boundToMonitoringService = false; } }; public void sendAlarmEvent(boolean activated) { - if (boundToMonitoringService && monitoringService != null) { + //if (boundToMonitoringService && monitoringService != null) { monitoringService.sendAlarmEvent(activated); - } + // } } @Override @@ -336,14 +383,45 @@ public void startMonitoringService() { 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); + 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, + alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent); + + connectToService(); + } + + @Override + public void startSendData(){ + 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); + intent.putExtra(MonitoringService.CONNECT, true); + + PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, + PendingIntent.FLAG_CANCEL_CURRENT); + // registering our pending intent with alarm manager + alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 5000, Integer.valueOf(avPrefs.period) * 60 * 1000, pendingIntent); - connectToService(); + // connectToService(); + serviceSendData = true; + + } + + @Override + public void stopSendData(){ + Intent intent = new Intent(this, MonitoringService.class); + PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, + PendingIntent.FLAG_CANCEL_CURRENT); + alarmManager.cancel(pendingIntent); + serviceSendData = false; } @Override @@ -397,7 +475,7 @@ public void onSynced(SyncWithAvResult result) { String systemName = this.getSystemName(); runFragment.setLinkToSystem(systemUid, systemName); } else { - Log.w(LOGTAG, "RunFragment reference is null when onSynced is called"); + Log.w(TAG, "RunFragment reference is null when onSynced is called"); } } @@ -426,6 +504,13 @@ private void selectItem(final int position) { final Fragment fragment = getFragment(position); if (fragment == null) { + //No item check if the position is valid + if (FRAGMENT_LIST[position] == FRAGMENT_FAQ) { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://doc.airvantage.net/alms/")); + startActivity(browserIntent); + drawerListView.setSelection(lastPosition); + drawerLayout.closeDrawer(drawerListView); + } return; } @@ -440,6 +525,7 @@ private void selectItem(final int position) { setTitle(FRAGMENT_LIST[position]); drawerListView.setSelection(position); drawerLayout.closeDrawer(drawerListView); + lastPosition = position; } private void selectItem(final Fragment fragment) { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java index 2290d3a..c95a59c 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceListener.java @@ -4,7 +4,7 @@ public interface MonitorServiceListener { - public void onServiceStarted(MonitoringService service); + void onServiceStarted(MonitoringService service); - public void onServiceStopped(MonitoringService service); + 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 index eac52fd..e4ef5b5 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java @@ -4,10 +4,13 @@ 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(); + boolean isServiceRunning(); + boolean isServiceStarted(); + void stopMonitoringService(); + void startMonitoringService(); + void startSendData(); + void stopSendData(); + void sendAlarmEvent(boolean activated); + void setMonitoringServiceListener(MonitorServiceListener listener); + MonitoringService getMonitoringService(); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java index b29f063..0a98f8a 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java @@ -14,6 +14,7 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; @@ -80,6 +81,10 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa SwitchCompat serviceSwitch = (SwitchCompat) view.findViewById(R.id.service_switch); serviceSwitch.setChecked(isServiceRunning); + if (!this.monitorServiceManager.isServiceStarted()) { + this.monitorServiceManager.startMonitoringService(); + } + serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { @@ -95,15 +100,13 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 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); + Button alarmButton = (Button) view.findViewById(R.id.alarm_btn); + alarmButton.setOnClickListener(onAlarmClick); // Make links clickable in info view. TextView infoMessageView = (TextView) view.findViewById(R.id.run_info_message); @@ -129,7 +132,7 @@ public void setLinkToSystem(String systemUid, String systemName) { final TextView infoMessageView = (TextView) view.findViewById(R.id.run_info_message); - String infoMessage = null; + String infoMessage; if (systemUid != null) { AvPhonePrefs avPhonePrefs = PreferenceUtils.getAvPhonePrefs(getActivity()); @@ -172,13 +175,13 @@ private void startMonitoringService() { SwitchCompat serviceSwitch = getServiceSwitch(); serviceSwitch.setChecked(false); } else { - this.monitorServiceManager.startMonitoringService(); + this.monitorServiceManager.startSendData(); } } private void stopMonitoringService() { - this.monitorServiceManager.stopMonitoringService(); + this.monitorServiceManager.stopSendData(); } protected void setCustomDataLabels(CustomDataLabels customDataLabels) { @@ -202,15 +205,12 @@ protected void setCustomDataLabels(CustomDataLabels customDataLabels) { } // Alarm button - - OnCheckedChangeListener onAlarmClick = new OnCheckedChangeListener() { - + View.OnClickListener onAlarmClick = new View.OnClickListener() { @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + public void onClick(View view) { Log.d(LOGTAG, "On alarm button click"); - monitorServiceManager.sendAlarmEvent(isChecked); - + monitorServiceManager.sendAlarmEvent(true); } }; diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java b/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java index 17f2f94..8a2eb3e 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/message/IMessageDisplayer.java @@ -7,9 +7,9 @@ */ public interface IMessageDisplayer { - public void showError(int id, Object... params); + void showError(int id, Object... params); - public void showSuccess(int id, Object... params); + void showSuccess(int id, Object... params); - public void showErrorMessage(Spanned spanned); + void showErrorMessage(Spanned spanned); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java index 1cf7457..f63c2af 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java @@ -17,6 +17,7 @@ public class AvPhoneApplication { public static final String ALERT_RULE_NAME = "AV Phone raised an alert"; + private static String type = "Printer"; public static Application createApplication(final String userName) { Application application = new Application(); @@ -64,22 +65,7 @@ public static List createApplicationData(CustomDataLabels custo 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")); @@ -102,11 +88,11 @@ public static List createApplicationData(CustomDataLabels custo } public static String appName(final String userName) { - return "av_phone_demo_" + userName; + return "av_phone_" + type + "_" + userName; } public static String appType(final String userName) { - return "av.phone.demo." + userName; + return "av.phone.demo." + type + userName; } public static AlertRule createAlertRule() { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java index c6daf3a..4755d23 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java @@ -28,11 +28,15 @@ import android.telephony.CellInfoWcdma; import android.telephony.TelephonyManager; import android.util.Log; +import android.widget.Toast; import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import com.sierrawireless.avphone.MainActivity; import com.sierrawireless.avphone.R; +import com.sierrawireless.avphone.auth.Authentication; + +import net.airvantage.utils.PreferenceUtils; import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken; import org.eclipse.paho.client.mqttv3.MqttCallback; @@ -45,21 +49,20 @@ import java.util.Map; public class MonitoringService extends Service { - - private static final String LOGTAG = MonitoringService.class.getName(); - + private static final String TAG = "MonitoringService"; + // 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"; + public static final String CONNECT = "connect"; private MqttPushClient client = null; @@ -81,6 +84,8 @@ public class MonitoringService extends Service { @Override public void onCreate() { + // Unique Identification Number for the Notification. + int NOTIFICATION = R.string.notif_title; // Display a notification icon @@ -117,13 +122,22 @@ public int onStartCommand(Intent intent, int flags, int startId) { lastRun = System.currentTimeMillis(); try { + final Boolean mustConnect = intent.getBooleanExtra(CONNECT, true); + Log.e(TAG, "onStartCommand: mustConnect here " + mustConnect ); + + /* First we have to create the system if it doesn't exist */ + + Authentication auth = PreferenceUtils.readAuthentication(getApplicationContext()); + + if (this.client == null) { + Log.e(TAG, "onStartCommand: Start connect" ); // // Ensure intent is valid // - final String deviceId = intent.getStringExtra(DEVICE_ID); + final String deviceId = intent.getStringExtra(DEVICE_ID) + "-ANDROID-" + "PRINTER"; final String password = intent.getStringExtra(PASSWORD); final String serverHost = intent.getStringExtra(SERVER_HOST); @@ -137,118 +151,122 @@ public int onStartCommand(Intent intent, int flags, int startId) { // Now, create client client = new MqttPushClient(deviceId, password, serverHost, mqttCallback); } - if (!client.isConnected()) { + Log.e(TAG, "onStartCommand: client connect called"); 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 (mustConnect) { + Log.e(TAG, "onStartCommand: Send Data Called"); + 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: - } + if (telephonyManager.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) { + data.setImei(telephonyManager.getDeviceId()); + } - 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); - } + 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: + } - // location - if (location != null && location.getTime() != lastLocation) { - data.setLatitude(location.getLatitude()); - data.setLongitude(location.getLongitude()); - lastLocation = location.getTime(); - } + 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); + } - // bytes sent/received - data.setBytesReceived(TrafficStats.getMobileRxBytes()); - data.setBytesSent(TrafficStats.getMobileTxBytes()); + // location + if (location != null && location.getTime() != lastLocation) { + data.setLatitude(location.getLatitude()); + data.setLongitude(location.getLongitude()); + lastLocation = location.getTime(); + } - // 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()); + // bytes sent/received + data.setBytesReceived(TrafficStats.getMobileRxBytes()); + data.setBytesSent(TrafficStats.getMobileTxBytes()); - customDataSource.next(new Date()); + // 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()); - // save new data values - lastData.putExtras(data.getExtras()); + customDataSource.next(new Date()); - // dispatch new data event to update the activity UI - LocalBroadcastManager.getInstance(this).sendBroadcast(data); + // save new data values + if (data.getExtras() != null) { + lastData.putExtras(data.getExtras()); + } - this.client.push(data); - lastLog = data.size() + " data pushed to the server"; - LocalBroadcastManager.getInstance(this).sendBroadcast(new LogMessage(lastLog)); + // dispatch new data event to update the activity UI + LocalBroadcastManager.getInstance(this).sendBroadcast(data); - setUpLocationListeners(); + 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); + Log.e(TAG, "error", e); lastLog = "ERROR: " + e.getMessage(); LocalBroadcastManager.getInstance(this).sendBroadcast(new LogMessage(lastLog)); } @@ -266,7 +284,7 @@ public void onDestroy() { this.client.disconnect(); } catch (MqttException e) { Crashlytics.logException(e); - Log.e(LOGTAG, "error", e); + Log.e(TAG, "error", e); } } @@ -278,12 +296,17 @@ public void onDestroy() { private void setUpLocationListeners() { final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (locManager == null) { + Log.e(TAG, "setUpLocationListeners: Can't get the location service"); + Toast.makeText(getApplicationContext(), "can't get location service", Toast.LENGTH_SHORT).show(); + return; + } 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()); + Log.d(TAG, "Received Network location update " + location.getLatitude() + ";" + location.getLongitude()); networkLocation = location; } }; @@ -294,7 +317,7 @@ public void onLocationChanged(Location location) { gpsLocationListener = new LocationListenerAdapter() { @Override public void onLocationChanged(Location location) { - Log.d(LOGTAG, "Received GPS location update " + location.getLatitude() + ";" + location.getLongitude()); + Log.d(TAG, "Received GPS location update " + location.getLatitude() + ";" + location.getLongitude()); gpsLocation = location; } }; @@ -304,6 +327,11 @@ public void onLocationChanged(Location location) { private void stopLocationListeners() { final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (locManager == null) { + Log.e(TAG, "setUpLocationListeners: Can't get the location service"); + Toast.makeText(getApplicationContext(), "can't get location service", Toast.LENGTH_SHORT).show(); + return; + } if (networkLocationListener != null) { locManager.removeUpdates(networkLocationListener); } @@ -315,26 +343,31 @@ private void stopLocationListeners() { private Location getLastKnownLocation() { final LocationManager locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); + if (locManager == null) { + Log.e(TAG, "setUpLocationListeners: Can't get the location service"); + Toast.makeText(getApplicationContext(), "can't get location service", Toast.LENGTH_SHORT).show(); + return null; + } final String locationProvider = locManager.getBestProvider(new Criteria(), true); - Log.d(LOGTAG, "Getting last known location from provider: " + locationProvider); + Log.d(TAG, "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()); + Log.d(TAG, "Last known location : " + location.getLatitude() + "," + location.getLongitude()); } else { - Log.d(LOGTAG, "Read null location"); + Log.d(TAG, "Read null location"); } if (networkLocation != null) { - Log.d(LOGTAG, "Last Network Location : " + networkLocation.getLatitude() + "," + networkLocation.getLongitude()); + Log.d(TAG, "Last Network Location : " + networkLocation.getLatitude() + "," + networkLocation.getLongitude()); } else { - Log.d(LOGTAG, "No known network location"); + Log.d(TAG, "No known network location"); } if (gpsLocation != null) { - Log.d(LOGTAG, "Last GPS Location : " + gpsLocation.getLatitude() + "," + gpsLocation.getLongitude()); + Log.d(TAG, "Last GPS Location : " + gpsLocation.getLatitude() + "," + gpsLocation.getLongitude()); } else { - Log.d(LOGTAG, "No known GPSlocation"); + Log.d(TAG, "No known GPSlocation"); } } return location; @@ -343,22 +376,38 @@ private Location getLastKnownLocation() { public void sendAlarmEvent(boolean activated) { if (this.client == null) { - // TODO: Propagate error message when client is not available yet + Toast.makeText(getApplicationContext(), "Alarm client is not available,wait...", Toast.LENGTH_SHORT).show(); return; } + if (!client.isConnected()) { + Log.e(TAG, "onStartCommand: client connect called"); + try { + client.connect(); + } + catch (Exception e) { + Crashlytics.logException(e); + Log.e(TAG, "error", e); + lastLog = "ERROR: " + e.getMessage(); + LocalBroadcastManager.getInstance(this).sendBroadcast(new LogMessage(lastLog)); + } + } + + NewData data = new NewData(); data.setAlarmActivated(activated); // save alarm state - lastData.putExtras(data.getExtras()); + if (data.getExtras() != null) { + lastData.putExtras(data.getExtras()); + } try { this.client.push(data); } catch (MqttException e) { - // TODO display something + Toast.makeText(getApplicationContext(), "Can't send Alarm ", Toast.LENGTH_SHORT).show(); Crashlytics.logException(e); - Log.e(LOGTAG, "Could not push the alarm event", e); + Log.e(TAG, "Could not push the alarm event", e); } } @@ -412,7 +461,7 @@ class Command { @Override public void messageArrived(String topic, MqttMessage msg) throws Exception { - Log.d(LOGTAG, "MQTT msg received: " + new String(msg.getPayload())); + Log.d(TAG, "MQTT msg received: " + new String(msg.getPayload())); // parse json payload Message[] messages = new Gson().fromJson(new String(msg.getPayload(), "UTF-8"), Message[].class); @@ -426,6 +475,11 @@ public void messageArrived(String topic, MqttMessage msg) throws Exception { .build(); NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); + if (mNotificationManager == null) { + Log.e(TAG, "setUpLocationListeners: Can't get the notification service"); + Toast.makeText(getApplicationContext(), "can't get notification service for incoming data", Toast.LENGTH_SHORT).show(); + return; + } mNotificationManager.notify((int) messages[0].timestamp, notification); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java index 0752139..ad3db83 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java @@ -18,11 +18,11 @@ import android.util.Log; import com.google.gson.Gson; +import com.sierrawireless.avphone.DeviceInfo; import com.sierrawireless.avphone.model.AvPhoneData; public class MqttPushClient { - - private static final String LOGTAG = MqttPushClient.class.getName(); + private static final String TAG = "MqttPushClient"; private MqttClient client; private MqttConnectOptions opt; @@ -33,7 +33,8 @@ public class MqttPushClient { public MqttPushClient(String clientId, String password, String serverHost, MqttCallback callback) throws MqttException { - Log.d(LOGTAG, "new client: " + clientId + " - " + password + " - " + serverHost); + DeviceInfo.generateSerial("", ""); + Log.d(TAG, "new client: " + clientId + " - " + password + " - " + serverHost); this.client = new MqttClient("tcp://" + serverHost + ":1883", MqttClient.generateClientId(), new MemoryPersistence()); @@ -50,7 +51,7 @@ public boolean isConnected() { } public void connect() throws MqttSecurityException, MqttException { - Log.d(LOGTAG, "connecting"); + Log.d(TAG, "connecting"); client.connect(opt); } @@ -62,10 +63,12 @@ public void disconnect() throws MqttException { public void push(NewData data) throws MqttException { if (client.isConnected()) { - Log.i(LOGTAG, "Pushing data to the server : " + data); + Log.i(TAG, "Pushing data to the server : " + data); String message = this.convertToJson(data); - Log.d(LOGTAG, "Rest content : " + message); + Log.d(TAG, "push: json data" + message); + + Log.d(TAG, "Rest content : " + message); MqttMessage msg = null; try { @@ -85,78 +88,78 @@ private String convertToJson(NewData data) { Map> values = new HashMap>(); if (data.getRssi() != null) { - values.put(AvPhoneData.RSSI, Collections.singletonList(new DataValue(timestamp, data.getRssi()))); + // 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(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.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()))); + values.put("_NETWORK_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.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()))); + //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()))); + //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()))); + //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(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(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.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.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.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()))); + // 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, diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/AsyncTaskFactory.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/AsyncTaskFactory.java index ccbb0a7..0c3fe67 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/AsyncTaskFactory.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/AsyncTaskFactory.java @@ -4,8 +4,10 @@ import net.airvantage.utils.AirVantageClient; import android.content.Context; import android.os.AsyncTask; +import android.util.Log; public class AsyncTaskFactory implements IAsyncTaskFactory { + private static final String TAG = "AsyncTaskFactory"; private Context context; @@ -21,7 +23,7 @@ public SyncWithAvTask syncAvTask(String serverHost, String token) { ISystemClient systemClient = new SystemClient(avClient); IAlertRuleClient alertRuleClient = new AlertRuleClient(avClient); IUserClient userClient = new UserClient(avClient); - + return new ProgressSyncWithAvTask(appClient, systemClient, alertRuleClient, userClient, context); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java index da6a5c2..d8b2508 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java @@ -9,7 +9,7 @@ public interface ISystemClient { AvSystem getSystem(String serialNumber) throws IOException, AirVantageException; - AvSystem createSystem(String serialNumber, String imei, String type, String mqttPassword, String applicationUid) + AvSystem createSystem(String serialNumber, String iccid, String type, String mqttPassword, String applicationUid, String deviceName, String userName, String imei) throws IOException, AirVantageException; } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java index cd75c1e..a7ad6c9 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java @@ -6,5 +6,7 @@ public class SyncWithAvParams { public String deviceId; public String imei; public String mqttPassword; + public String iccid; + public String deviceName; public CustomDataLabels customData; } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java index c66d344..21ff76f 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java @@ -27,6 +27,7 @@ import net.airvantage.model.alert.v1.AlertRule; public class SyncWithAvTask extends AsyncTask { + private static final String TAG = "SyncWithAvTask"; private IApplicationClient applicationClient; @@ -66,15 +67,17 @@ protected SyncWithAvResult doInBackground(SyncWithAvParams... params) { return new SyncWithAvResult(new AvError(AvError.MISSING_RIGHTS, missingRights)); } - final String systemType = "Android"; + final String systemType = "Printer"; final SyncWithAvParams syncParams = params[0]; final User user = userClient.getUser(); final String imei = syncParams.imei; + final String iccid = syncParams.iccid; + final String deviceName = syncParams.deviceName; final String mqttPassword = syncParams.mqttPassword; final CustomDataLabels customData = syncParams.customData; // For emulator and iOs compatibility sake, using generated serial. - final String serialNumber = DeviceInfo.generateSerial(user.uid ,systemType); + final String serialNumber = DeviceInfo.generateSerial(user.uid, systemType); // Save Device serial in context if (context instanceof MainActivity) { @@ -93,7 +96,7 @@ protected SyncWithAvResult doInBackground(SyncWithAvParams... params) { publishProgress(SyncProgress.CREATING_SYSTEM); - system = systemClient.createSystem(serialNumber, imei, systemType, mqttPassword, application.uid); + system = systemClient.createSystem(serialNumber, iccid, "Printer", mqttPassword, application.uid, deviceName, user.name, imei); } publishProgress(SyncProgress.CHECKING_ALERT_RULE); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java index 3f594b2..63a4867 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java @@ -28,13 +28,17 @@ public net.airvantage.model.AvSystem getSystem(final String serialNumber) throws } @Override - public net.airvantage.model.AvSystem createSystem(String serialNumber, String imei, String type, String mqttPassword, - String applicationUid) throws IOException, AirVantageException { + public net.airvantage.model.AvSystem createSystem(String serialNumber, String iccid, String type, String mqttPassword, + String applicationUid, String deviceName, String userName, String imei) throws IOException, AirVantageException { net.airvantage.model.AvSystem system = new net.airvantage.model.AvSystem(); + client.getGateway(serialNumber + "-" + type); + net.airvantage.model.AvSystem.Gateway gateway = new net.airvantage.model.AvSystem.Gateway(); - gateway.serialNumber = serialNumber; + gateway.serialNumber = serialNumber + "-ANDROID-" + type; gateway.imei = imei; + gateway.type = type; + system.name = deviceName + " de " + userName + "(" + type + ")"; system.gateway = gateway; diff --git a/mainActivity/src/main/java/net/airvantage/model/AvSystem.java b/mainActivity/src/main/java/net/airvantage/model/AvSystem.java index 652533b..c862671 100644 --- a/mainActivity/src/main/java/net/airvantage/model/AvSystem.java +++ b/mainActivity/src/main/java/net/airvantage/model/AvSystem.java @@ -32,11 +32,11 @@ public static class Data { public static class Gateway { public String uid; public String imei; - public String macAddress; public String serialNumber; public String type; } + public static Predicate hasSerialNumber(final String serialNumber) { return new Predicate() { @Override diff --git a/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java b/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java index a2cb6bb..03598a7 100644 --- a/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java +++ b/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java @@ -40,6 +40,7 @@ import java.util.Map; public class AirVantageClient implements IAirVantageClient, IAlertAdapterFactoryListener { + private static final String TAG = "AirVantageClient"; private static final String SCHEME = "https://"; @@ -237,6 +238,24 @@ public List getSystemsBySerialNumber(String seria return gson.fromJson(new InputStreamReader(in), SystemsList.class).items; } + public void getGateway(String serialNumber) throws IOException, AirVantageException { + String urlString = buildEndpoint("/gateways"); + Log.d(TAG, "getGateway: urlString " + urlString); + URL url = new URL(urlString); + InputStream in = this.get(url); + BufferedReader reader = new BufferedReader(new InputStreamReader(in)); + StringBuilder sb = new StringBuilder(); + String line = null; + + while ((line = reader.readLine()) != null) { + sb.append(line); + } + + in.close(); + + Log.d(TAG, "getGateway: answer " + sb.toString()); + } + public net.airvantage.model.AvSystem createSystem(net.airvantage.model.AvSystem system) throws IOException, AirVantageException { URL url = new URL(buildEndpoint("/systems")); diff --git a/mainActivity/src/main/java/net/airvantage/utils/PreferenceUtils.java b/mainActivity/src/main/java/net/airvantage/utils/PreferenceUtils.java index 790cd48..c5d4061 100644 --- a/mainActivity/src/main/java/net/airvantage/utils/PreferenceUtils.java +++ b/mainActivity/src/main/java/net/airvantage/utils/PreferenceUtils.java @@ -14,12 +14,14 @@ import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; +import android.widget.Toast; import com.sierrawireless.avphone.R; import com.sierrawireless.avphone.auth.Authentication; import com.sierrawireless.avphone.model.CustomDataLabels; public class PreferenceUtils { + private static final String TAG = "PreferenceUtils"; private static String LOGTAG = PreferenceUtils.class.getName(); diff --git a/mainActivity/src/main/res/drawable/apptheme_switch_inner_holo_light.xml b/mainActivity/src/main/res/drawable/apptheme_switch_inner_holo_light.xml index afb2823..bd47e8b 100644 --- a/mainActivity/src/main/res/drawable/apptheme_switch_inner_holo_light.xml +++ b/mainActivity/src/main/res/drawable/apptheme_switch_inner_holo_light.xml @@ -17,6 +17,7 @@ + diff --git a/mainActivity/src/main/res/drawable/listitem_selector.xml b/mainActivity/src/main/res/drawable/listitem_selector.xml new file mode 100644 index 0000000..202788f --- /dev/null +++ b/mainActivity/src/main/res/drawable/listitem_selector.xml @@ -0,0 +1,7 @@ + + + + + + + \ 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..12b324b 100644 --- a/mainActivity/src/main/res/layout/activity_main.xml +++ b/mainActivity/src/main/res/layout/activity_main.xml @@ -14,8 +14,7 @@ android:layout_height="match_parent" android:layout_gravity="start" android:choiceMode="singleChoice" - android:background="@color/navy" - android:listSelector="@color/sierrared" + android:background="@drawable/listitem_selector" android:divider="@android:color/transparent" android:dividerHeight="0dp"/> diff --git a/mainActivity/src/main/res/layout/drawer_item.xml b/mainActivity/src/main/res/layout/drawer_item.xml index 7e361fe..fc53523 100644 --- a/mainActivity/src/main/res/layout/drawer_item.xml +++ b/mainActivity/src/main/res/layout/drawer_item.xml @@ -4,5 +4,6 @@ android:layout_width="match_parent" android:layout_height="match_parent" android:textColor="@android:color/white" + android:background="@drawable/listitem_selector" android:padding="@dimen/abc_button_padding_horizontal_material" android:textSize="@dimen/abc_text_size_large_material" /> \ No newline at end of file diff --git a/mainActivity/src/main/res/layout/fragment_run.xml b/mainActivity/src/main/res/layout/fragment_run.xml index 62358f5..d50d2fa 100644 --- a/mainActivity/src/main/res/layout/fragment_run.xml +++ b/mainActivity/src/main/res/layout/fragment_run.xml @@ -68,7 +68,7 @@ android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_weight="1" - android:orientation="vertical" > + android:orientation="vertical"> - + android:baselineAligned="false" + android:text="Send" + android:textAlignment="center" /> From ff84f0679b66bc03ac55ba108ed08d7b66aa345d Mon Sep 17 00:00:00 2001 From: Jean-bernard Damiano Date: Wed, 24 Jan 2018 16:18:04 +0100 Subject: [PATCH 02/60] Add a Serialized List of object prepare the object Add on Step 1 --- .../sierrawireless/avphone/MainActivity.java | 89 +++++++++-- .../sierrawireless/avphone/RunFragment.java | 13 ++ .../avphone/model/AvPhoneModel.java | 36 +++++ .../avphone/model/AvPhoneModelData.java | 90 ++++++++++++ .../avphone/tools/MyPreference.java | 139 ++++++++++++++++++ 5 files changed, 356 insertions(+), 11 deletions(-) create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/tools/MyPreference.java diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java index d8d6221..3ff0709 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java @@ -22,6 +22,7 @@ import android.support.v4.app.FragmentActivity; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; +import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; @@ -33,23 +34,32 @@ import com.crashlytics.android.Crashlytics; import com.crashlytics.android.ndk.CrashlyticsNdk; +import com.google.gson.Gson; import com.sierrawireless.avphone.auth.Authentication; import com.sierrawireless.avphone.auth.AuthenticationManager; +import com.sierrawireless.avphone.model.AvPhoneModel; +import com.sierrawireless.avphone.model.AvPhoneModelData; 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 com.sierrawireless.avphone.tools.MyPreference; +import com.sierrawireless.avphone.tools.ObjectSerializer; import net.airvantage.model.AvSystem; import net.airvantage.model.User; import net.airvantage.utils.AvPhonePrefs; import net.airvantage.utils.PreferenceUtils; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Map; import io.fabric.sdk.android.Fabric; @@ -85,7 +95,7 @@ public class MainActivity extends FragmentActivity 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_CONFIGURE = "Objects"; private final static String FRAGMENT_SETTINGS = "Settings"; private final static String FRAGMENT_FAQ = "FAQ"; @@ -93,24 +103,77 @@ public class MainActivity extends FragmentActivity private HomeFragment homeFragment; private RunFragment runFragment; + public static String SHARED_PREFS_FILE = "SavedModels"; + public static String MODELS = "models"; + public static String ACTIVE = "active"; + public static int current; + public static String currentName; + + private ArrayList models; + private int lastPosition = 0; private Boolean serviceSendData = false; - private final static String[] FRAGMENT_LIST = new String[]{ - FRAGMENT_HOME, - FRAGMENT_RUN, - FRAGMENT_CONFIGURE, - FRAGMENT_SETTINGS, - FRAGMENT_FAQ, - }; + SharedPreferences preferences; + + private static String[] FRAGMENT_LIST; + + public String[] buildFragmentList() { + ArrayList tmp = new ArrayList<>(); + tmp.add(FRAGMENT_HOME); + tmp.add(currentName); + tmp.add(FRAGMENT_CONFIGURE); + tmp.add(FRAGMENT_SETTINGS); + tmp.add(FRAGMENT_FAQ); + String[] array = new String[tmp.size()]; + return tmp.toArray(array); + } public void setCustomLabelsListener(CustomLabelsListener customLabelsListener) { this.customLabelsListener = customLabelsListener; } + @Override protected void onCreate(Bundle savedInstanceState) { + if (null == models) { + models = new ArrayList<>(); + } + + MyPreference pref = new MyPreference(getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)); + + + models = pref.getListObject(MODELS, AvPhoneModel.class); + current = pref.getInt(ACTIVE); + + Log.d(TAG, "onCreate: models " + models); + if (models.isEmpty()) { + // Create the default model here + AvPhoneModel model = new AvPhoneModel(); + model.name = "Printer"; + AvPhoneModelData data = new AvPhoneModelData("A6 Page Count", "page(s)", "0", AvPhoneModelData.Mode.UP, "1"); + model.add(data); + data = new AvPhoneModelData("Black Cartridge S/N", "", "NTOQN-7HUL9-NEPFL-13IOA", AvPhoneModelData.Mode.None, "2"); + model.add(data); + data = new AvPhoneModelData("Black lnk Level", "%", "100", AvPhoneModelData.Mode.DOWN, "3"); + model.add(data); + data = new AvPhoneModelData("A4 Page Count", "page(s)", "0", AvPhoneModelData.Mode.UP, "4"); + model.add(data); + data = new AvPhoneModelData("Color Cartridge S/N", "", "629U7-XLT5H-6SCGJ-@CENZ", AvPhoneModelData.Mode.None, "5"); + model.add(data); + data = new AvPhoneModelData("Color lnk Level", "%", "100", AvPhoneModelData.Mode.DOWN, "6"); + model.add(data); + models.add(model); + current = 0; + + } + + currentName = models.get(current).name; + + pref.putListObject(MODELS, models); + pref.putInt(ACTIVE, current); + super.onCreate(savedInstanceState); Fabric.with(this, new Crashlytics(), new CrashlyticsNdk()); @@ -123,9 +186,10 @@ protected void onCreate(Bundle savedInstanceState) { taskFactory = new AsyncTaskFactory(MainActivity.this); + FRAGMENT_LIST = buildFragmentList(); 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)); + drawerListView.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_item, buildFragmentList())); drawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); // Set the list's click listener @@ -146,7 +210,7 @@ public void onItemClick(AdapterView parent, View view, int position, long id) { final Fragment currentFragment; if (isLogged()) { - currentFragment = fragments.get(FRAGMENT_RUN); + currentFragment = fragments.get(currentName); unlockDrawer(); if (isServiceRunning()) { connectToService(); @@ -552,15 +616,18 @@ private Map initFragments() { homeFragment.setTaskFactory(taskFactory); } + if (runFragment == null) { runFragment = new RunFragment(); + runFragment.setTaskFactory(taskFactory); + runFragment.setModel(models.get(current)); } 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); + fragmentsMapping.put(currentName, runFragment); return fragmentsMapping; } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java index 0a98f8a..bbf6c0c 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java @@ -19,10 +19,12 @@ import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; +import com.sierrawireless.avphone.model.AvPhoneModel; import com.sierrawireless.avphone.model.CustomDataLabels; import com.sierrawireless.avphone.service.LogMessage; import com.sierrawireless.avphone.service.MonitoringService; import com.sierrawireless.avphone.service.NewData; +import com.sierrawireless.avphone.task.IAsyncTaskFactory; public class RunFragment extends AvPhoneFragment implements MonitorServiceListener, CustomLabelsListener { @@ -38,6 +40,17 @@ public class RunFragment extends AvPhoneFragment implements MonitorServiceListen private String systemUid; private String systemName; + private IAsyncTaskFactory taskFactory; + private AvPhoneModel model; + + public void setTaskFactory(IAsyncTaskFactory taskFactory) { + this.taskFactory = taskFactory; + } + + public void setModel(AvPhoneModel model) { + this.model = model; + } + @Override public void onAttach(Activity activity) { super.onAttach(activity); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java new file mode 100644 index 0000000..a63507e --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java @@ -0,0 +1,36 @@ +package com.sierrawireless.avphone.model; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created by JDamiano on 24/01/2018. + */ + +public class AvPhoneModel { + public String name; + ArrayList datas; + private static AvPhoneModel instance = null; + + public AvPhoneModel() { + datas = new ArrayList<>(); + } + + public void add(AvPhoneModelData data ) { + datas.add(data); + } + + public String toString() { + String returned = "{"; + returned = returned + "\"name\" : \"" + name + "\","; + returned = returned + "\"datas\":["; + for (AvPhoneModelData data: datas) { + returned = returned + data.toString()+","; + } + returned = returned + "]}"; + return returned; + } + + + +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java new file mode 100644 index 0000000..0e74ef0 --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java @@ -0,0 +1,90 @@ +package com.sierrawireless.avphone.model; + +import android.text.TextUtils; + + +public class AvPhoneModelData { + public enum Mode { + None, + UP, + DOWN + } + private static final String TAG = "AvPhoneModelData"; + + public String name; + public String unit; + public String defaults; + public Mode mode; + private Integer current=null; + private String label; + + public AvPhoneModelData(String name, String unit, String defaults, Mode mode, String label) { + this.name = name; + this.unit = unit; + this.defaults = defaults; + if (isInteger()) { + this.mode = mode; + current = Integer.parseInt(defaults); + }else{ + this.mode = Mode.None; + } + this.label = label; + } + + public String toString() { + String returned = "{"; + returned = returned + "\"name\": \"" + name + "\","; + returned = returned + "\"unit\": \"" + unit + "\","; + returned = returned + "\"defaults\": \"" + defaults + "\","; + returned = returned + "\"mode\": \"" + modeToString(mode) + "\","; + returned = returned + "\"label\": \"" + label + "\"}"; + return returned; + } + + + + public Boolean isInteger() { + return TextUtils.isDigitsOnly(defaults); + } + + public String execMode() { + if (this.mode == Mode.UP) { + return increment(); + }else if (this.mode == Mode.DOWN){ + return decrement(); + } + return defaults; + } + + public String modeToString(Mode mode){ + switch (mode) { + case UP: + return "Increase indefinitely"; + case DOWN: + return "Decrease to zero"; + case None: + return "None"; + } + return "None"; + } + + private String increment(){ + if (current == null) { + current = Integer.parseInt(defaults); + } + current ++; + return current.toString(); + } + + private String decrement() { + if (current == null) { + current = Integer.parseInt(defaults); + } + if (current > 0 ) + current --; + return current.toString(); + } + + + +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/tools/MyPreference.java b/mainActivity/src/main/java/com/sierrawireless/avphone/tools/MyPreference.java new file mode 100644 index 0000000..b4cc4d5 --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/tools/MyPreference.java @@ -0,0 +1,139 @@ +package com.sierrawireless.avphone.tools; + +import android.content.SharedPreferences; +import android.text.TextUtils; + +import com.google.gson.Gson; +import com.sierrawireless.avphone.model.AvPhoneModel; + +import java.util.ArrayList; +import java.util.Arrays; + +public class MyPreference { + SharedPreferences preferences; + + public MyPreference(SharedPreferences prefences) { + this.preferences = prefences; + } + + /** + * Get String value from SharedPreferences at 'key'. If key not found, return "" + * @param key SharedPreferences key + * @return String value at 'key' or "" (empty String) if key not found + */ + public String getString(String key) { + return preferences.getString(key, ""); + } + + /** + * Get parsed ArrayList of String from SharedPreferences at 'key' + * @param key SharedPreferences key + * @return ArrayList of String + */ + public ArrayList getListString(String key) { + return new ArrayList(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚"))); + } + + public ArrayList getListObject(String key, Class mClass){ + Gson gson = new Gson(); + + ArrayList objStrings = getListString(key); + ArrayList objects = new ArrayList(); + + for(String jObjString : objStrings){ + AvPhoneModel value = gson.fromJson(jObjString, mClass); + objects.add(value); + } + return objects; + } + + + + public T getObject(String key, Class classOfT){ + + String json = getString(key); + Object value = new Gson().fromJson(json, classOfT); + if (value == null) + throw new NullPointerException(); + return (T)value; + } + + /** + * Get int value from SharedPreferences at 'key'. If key not found, return 'defaultValue' + * @param key SharedPreferences key + * @param defaultValue int value returned if key was not found + * @return int value at 'key' or 'defaultValue' if key not found + */ + public int getInt(String key) { + return preferences.getInt(key, 0); + } + + /** + * Put int value into SharedPreferences with 'key' and save + * @param key SharedPreferences key + * @param value int value to be added + */ + public void putInt(String key, int value) { + checkForNullKey(key); + preferences.edit().putInt(key, value).apply(); + } + /** + * null keys would corrupt the shared pref file and make them unreadable this is a preventive measure + * @param the pref key + */ + public void checkForNullKey(String key){ + if (key == null){ + throw new NullPointerException(); + } + } + /** + * null keys would corrupt the shared pref file and make them unreadable this is a preventive measure + * @param the pref key + */ + public void checkForNullValue(String value){ + if (value == null){ + throw new NullPointerException(); + } + } + + /** + * Put String value into SharedPreferences with 'key' and save + * @param key SharedPreferences key + * @param value String value to be added + */ + public void putString(String key, String value) { + checkForNullKey(key); checkForNullValue(value); + preferences.edit().putString(key, value).apply(); + } + + /** + * Put ArrayList of String into SharedPreferences with 'key' and save + * @param key SharedPreferences key + * @param stringList ArrayList of String to be added + */ + public void putListString(String key, ArrayList stringList) { + checkForNullKey(key); + String[] myStringList = stringList.toArray(new String[stringList.size()]); + preferences.edit().putString(key, TextUtils.join("‚‗‚", myStringList)).apply(); + } + /** + * Put ObJect any type into SharedPrefrences with 'key' and save + * @param key SharedPreferences key + * @param obj is the Object you want to put + */ + public void putObject(String key, Object obj){ + checkForNullKey(key); + Gson gson = new Gson(); + putString(key, gson.toJson(obj)); + } + + public void putListObject(String key, ArrayList objArray){ + checkForNullKey(key); + Gson gson = new Gson(); + ArrayList objStrings = new ArrayList(); + for(Object obj : objArray){ + objStrings.add(gson.toJson(obj)); + } + putListString(key, objStrings); + } +} From cb551914582a090b7850f8ea9657451652387b98 Mon Sep 17 00:00:00 2001 From: Jean-bernard Damiano Date: Thu, 25 Jan 2018 08:44:37 +0100 Subject: [PATCH 03/60] Add ObjectsManager Class to manage All Object --- .../avphone/DataViewUpdater.java | 70 ++++++----- .../sierrawireless/avphone/HomeFragment.java | 2 + .../sierrawireless/avphone/MainActivity.java | 66 ++-------- .../avphone/ObjectsManager.java | 114 ++++++++++++++++++ .../sierrawireless/avphone/RunFragment.java | 55 +++++---- .../avphone/model/AvPhoneApplication.java | 18 +-- .../avphone/model/AvPhoneData.java | 1 + .../{AvPhoneModel.java => AvPhoneObject.java} | 22 ++-- ...eModelData.java => AvPhoneObjectData.java} | 8 +- .../avphone/service/MonitoringService.java | 30 +++-- .../avphone/service/MqttPushClient.java | 37 ++---- .../avphone/service/NewData.java | 74 +++--------- .../avphone/task/ApplicationClient.java | 3 +- .../avphone/task/IApplicationClient.java | 5 +- .../avphone/task/SyncWithAvParams.java | 2 + .../avphone/task/SyncWithAvTask.java | 14 ++- .../avphone/tools/MyPreference.java | 10 +- 17 files changed, 291 insertions(+), 240 deletions(-) create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java rename mainActivity/src/main/java/com/sierrawireless/avphone/model/{AvPhoneModel.java => AvPhoneObject.java} (60%) rename mainActivity/src/main/java/com/sierrawireless/avphone/model/{AvPhoneModelData.java => AvPhoneObjectData.java} (91%) diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java index 45c8b88..f100d88 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java @@ -2,6 +2,7 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Date; import java.util.Locale; @@ -11,8 +12,11 @@ import android.view.View; import android.widget.TextView; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; import com.sierrawireless.avphone.service.LogMessage; import com.sierrawireless.avphone.service.NewData; +import com.sierrawireless.avphone.tools.MyPreference; /** * A component in charge of listening for service events (new data, logs) and updating the view accordingly. @@ -22,9 +26,13 @@ public class DataViewUpdater extends BroadcastReceiver { private DateFormat hourFormat = new SimpleDateFormat("HH:mm:ss", Locale.FRENCH); private final View view; + private MainActivity activity; + private ObjectsManager objectsManager; - public DataViewUpdater(View view) { + public DataViewUpdater(View view, MainActivity activity) { this.view = view; + this.activity = activity; + objectsManager = ObjectsManager.getInstance(); } @Override @@ -133,34 +141,38 @@ private void setNewData(NewData 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())); + AvPhoneObject model = objectsManager.getCurrentObject(); + for (AvPhoneObjectData ldata:model.datas){ + TextView valueView = null; + String text; + if (ldata.isInteger()){ + text = ldata.current.toString(); + }else{ + text = ldata.defaults; + } + switch (ldata.label) { + case "1": + valueView = (TextView) view.findViewById(R.id.run_custom1_value); + break; + case "2": + valueView = (TextView) view.findViewById(R.id.run_custom2_value); + break; + case "3": + valueView = (TextView) view.findViewById(R.id.run_custom3_value); + break; + case "4": + valueView = (TextView) view.findViewById(R.id.run_custom4_value); + break; + case "5": + valueView = (TextView) view.findViewById(R.id.run_custom5_value); + break; + case "6": + valueView = (TextView) view.findViewById(R.id.run_custom6_value); + break; + } + if (valueView != null) { + valueView.setText(text); + } } } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java index 35cca94..fa4a6e0 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/HomeFragment.java @@ -186,6 +186,8 @@ public void onSynced(SyncWithAvResult result) { params.iccid = DeviceInfo.getICCID(getActivity()); params.mqttPassword = avPhonePrefs.password; params.customData = PreferenceUtils.getCustomDataLabels(getActivity()); + // params.current = ((MainActivity)getActivity()).current; + params.activity = ((MainActivity)getActivity()); syncAvTask.execute(params); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java index 3ff0709..78e6c94 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java @@ -22,7 +22,6 @@ import android.support.v4.app.FragmentActivity; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; -import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.MenuItem; @@ -34,32 +33,24 @@ import com.crashlytics.android.Crashlytics; import com.crashlytics.android.ndk.CrashlyticsNdk; -import com.google.gson.Gson; import com.sierrawireless.avphone.auth.Authentication; import com.sierrawireless.avphone.auth.AuthenticationManager; -import com.sierrawireless.avphone.model.AvPhoneModel; -import com.sierrawireless.avphone.model.AvPhoneModelData; 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 com.sierrawireless.avphone.tools.MyPreference; -import com.sierrawireless.avphone.tools.ObjectSerializer; import net.airvantage.model.AvSystem; import net.airvantage.model.User; import net.airvantage.utils.AvPhonePrefs; import net.airvantage.utils.PreferenceUtils; -import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; import io.fabric.sdk.android.Fabric; @@ -103,17 +94,10 @@ public class MainActivity extends FragmentActivity private HomeFragment homeFragment; private RunFragment runFragment; - public static String SHARED_PREFS_FILE = "SavedModels"; - public static String MODELS = "models"; - public static String ACTIVE = "active"; - public static int current; - public static String currentName; - - private ArrayList models; - private int lastPosition = 0; private Boolean serviceSendData = false; + ObjectsManager objectsManager; SharedPreferences preferences; @@ -122,7 +106,7 @@ public class MainActivity extends FragmentActivity public String[] buildFragmentList() { ArrayList tmp = new ArrayList<>(); tmp.add(FRAGMENT_HOME); - tmp.add(currentName); + tmp.add(objectsManager.getCurrentObjectName()); tmp.add(FRAGMENT_CONFIGURE); tmp.add(FRAGMENT_SETTINGS); tmp.add(FRAGMENT_FAQ); @@ -137,43 +121,9 @@ public void setCustomLabelsListener(CustomLabelsListener customLabelsListener) { @Override protected void onCreate(Bundle savedInstanceState) { - if (null == models) { - models = new ArrayList<>(); - } - - MyPreference pref = new MyPreference(getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)); - - - models = pref.getListObject(MODELS, AvPhoneModel.class); - current = pref.getInt(ACTIVE); - - Log.d(TAG, "onCreate: models " + models); - if (models.isEmpty()) { - // Create the default model here - AvPhoneModel model = new AvPhoneModel(); - model.name = "Printer"; - AvPhoneModelData data = new AvPhoneModelData("A6 Page Count", "page(s)", "0", AvPhoneModelData.Mode.UP, "1"); - model.add(data); - data = new AvPhoneModelData("Black Cartridge S/N", "", "NTOQN-7HUL9-NEPFL-13IOA", AvPhoneModelData.Mode.None, "2"); - model.add(data); - data = new AvPhoneModelData("Black lnk Level", "%", "100", AvPhoneModelData.Mode.DOWN, "3"); - model.add(data); - data = new AvPhoneModelData("A4 Page Count", "page(s)", "0", AvPhoneModelData.Mode.UP, "4"); - model.add(data); - data = new AvPhoneModelData("Color Cartridge S/N", "", "629U7-XLT5H-6SCGJ-@CENZ", AvPhoneModelData.Mode.None, "5"); - model.add(data); - data = new AvPhoneModelData("Color lnk Level", "%", "100", AvPhoneModelData.Mode.DOWN, "6"); - model.add(data); - models.add(model); - current = 0; - - } - - currentName = models.get(current).name; - - pref.putListObject(MODELS, models); - pref.putInt(ACTIVE, current); - + // Initialization og Object Manager + objectsManager = ObjectsManager.getInstance(); + objectsManager.init(this); super.onCreate(savedInstanceState); Fabric.with(this, new Crashlytics(), new CrashlyticsNdk()); @@ -210,7 +160,7 @@ public void onItemClick(AdapterView parent, View view, int position, long id) { final Fragment currentFragment; if (isLogged()) { - currentFragment = fragments.get(currentName); + currentFragment = fragments.get(objectsManager.getCurrentObjectName()); unlockDrawer(); if (isServiceRunning()) { connectToService(); @@ -620,14 +570,14 @@ private Map initFragments() { if (runFragment == null) { runFragment = new RunFragment(); runFragment.setTaskFactory(taskFactory); - runFragment.setModel(models.get(current)); + runFragment.setObjectName(objectsManager.getCurrentObjectName()); } final HashMap fragmentsMapping = new HashMap<>(); fragmentsMapping.put(FRAGMENT_CONFIGURE, configureFragment); fragmentsMapping.put(FRAGMENT_HOME, homeFragment); fragmentsMapping.put(FRAGMENT_SETTINGS, new SettingsActivity.SettingsFragment()); - fragmentsMapping.put(currentName, runFragment); + fragmentsMapping.put(objectsManager.getCurrentObjectName(), runFragment); return fragmentsMapping; } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java new file mode 100644 index 0000000..f5eb33a --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java @@ -0,0 +1,114 @@ +package com.sierrawireless.avphone; + + +import android.content.Context; + +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; +import com.sierrawireless.avphone.tools.MyPreference; + +import java.util.ArrayList; + +public class ObjectsManager { + private static final String TAG = "ObjectsManager"; + static ObjectsManager instance = null; + MainActivity mainActivyty = null; + public static String SHARED_PREFS_FILE = "SavedModels"; + public static String MODELS = "models"; + public static String ACTIVE = "active"; + public int current; + public String currentName; + + private ArrayList objects; + + + public static ObjectsManager getInstance(){ + if (instance == null) { + instance = new ObjectsManager(); + } + return instance; + } + + private ObjectsManager(){ + objects = new ArrayList<>(); + } + + public void init(MainActivity activity){ + this.mainActivyty = activity; + MyPreference pref = new MyPreference(activity.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)); + + + objects = pref.getListObject(MODELS, AvPhoneObject.class); + current = pref.getInt(ACTIVE); + + if (objects.isEmpty()) { + // Create the default model here + AvPhoneObject model = new AvPhoneObject(); + model.name = "Printer"; + AvPhoneObjectData data = new AvPhoneObjectData("A6 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "1"); + model.add(data); + data = new AvPhoneObjectData("Black Cartridge S/N", "", "NTOQN-7HUL9-NEPFL-13IOA", AvPhoneObjectData.Mode.None, "2"); + model.add(data); + data = new AvPhoneObjectData("Black lnk Level", "%", "100", AvPhoneObjectData.Mode.DOWN, "3"); + model.add(data); + data = new AvPhoneObjectData("A4 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "4"); + model.add(data); + data = new AvPhoneObjectData("Color Cartridge S/N", "", "629U7-XLT5H-6SCGJ-@CENZ", AvPhoneObjectData.Mode.None, "5"); + model.add(data); + data = new AvPhoneObjectData("Color lnk Level", "%", "100", AvPhoneObjectData.Mode.DOWN, "6"); + model.add(data); + objects.add(model); + current = 0; + saveOnPref(); + } + currentName = objects.get(current).name; + } + + private void saveOnPref() { + MyPreference pref = new MyPreference(mainActivyty.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)); + // Save the list for later + pref.putListObject(MODELS, objects); + pref.putInt(ACTIVE, current); + } + + public void execOnCurrent() { + AvPhoneObject object; + object = objects.get(current); + object.exec(); + // Save the list for later + saveOnPref(); + } + + public void changeCurrent(String name) { + Integer indice = 0; + for (AvPhoneObject object: objects) { + if (object.name == name) { + current = indice; + saveOnPref(); + return; + } + indice++; + } + } + + public AvPhoneObject getCurrentObject() { + return objects.get(current); + } + + public AvPhoneObject getObjectByName(String name) { + for (AvPhoneObject object: objects) { + if (object.name == name) { + return object; + } + } + return null; + } + + public String getCurrentObjectName() { + return objects.get(current).name; + } + + + + +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java index bbf6c0c..d5a85d9 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java @@ -19,7 +19,8 @@ import android.widget.CompoundButton.OnCheckedChangeListener; import android.widget.TextView; -import com.sierrawireless.avphone.model.AvPhoneModel; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; import com.sierrawireless.avphone.model.CustomDataLabels; import com.sierrawireless.avphone.service.LogMessage; import com.sierrawireless.avphone.service.MonitoringService; @@ -41,14 +42,15 @@ public class RunFragment extends AvPhoneFragment implements MonitorServiceListen private String systemName; private IAsyncTaskFactory taskFactory; - private AvPhoneModel model; + private String objectName; + private ObjectsManager objectsManager; public void setTaskFactory(IAsyncTaskFactory taskFactory) { this.taskFactory = taskFactory; } - public void setModel(AvPhoneModel model) { - this.model = model; + public void setObjectName(String name) { + this.objectName = name; } @Override @@ -78,7 +80,7 @@ protected void setCustomLabelsManager(CustomLabelsManager manager) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_run, container, false); - viewUpdater = new DataViewUpdater(view); + viewUpdater = new DataViewUpdater(view, (MainActivity)getActivity()); CustomDataLabels customLabels = PreferenceUtils.getCustomDataLabels(getActivity()); setCustomDataLabels(customLabels); @@ -198,23 +200,32 @@ private void 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); + TextView valueView = null; + objectsManager = ObjectsManager.getInstance(); + AvPhoneObject object = objectsManager.getObjectByName(objectName); + for (AvPhoneObjectData data : object.datas) { + switch (data.label) { + case "1": + valueView = (TextView) view.findViewById(R.id.run_custom1_label); + break; + case "2": + valueView = (TextView) view.findViewById(R.id.run_custom2_label); + break; + case "3": + valueView = (TextView) view.findViewById(R.id.run_custom3_label); + break; + case "4": + valueView = (TextView) view.findViewById(R.id.run_custom4_label); + break; + case "5": + valueView = (TextView) view.findViewById(R.id.run_custom5_label); + break; + case "6": + valueView = (TextView) view.findViewById(R.id.run_custom6_label); + break; + } + valueView.setText(data.name); + } } // Alarm button diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java index f63c2af..a549418 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java @@ -34,7 +34,7 @@ public static List createProtocols() { return Arrays.asList(mqtt); } - public static List createApplicationData(CustomDataLabels customData) { + public static List createApplicationData(ArrayList customData) { // // @@ -68,12 +68,16 @@ public static List createApplicationData(CustomDataLabels custo 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")); + for (AvPhoneObjectData data:customData) { + String type; + + if (data.isInteger()) { + type = "int"; + } else { + type = "string"; + } + asset.data.add(new Variable(AvPhoneData.CUSTOM + data.label, data.name, type)); + } Command c = new Command(AvPhoneData.NOTIFY, "Notify"); Parameter p = new Parameter("message", "string"); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java index ece7ab9..c525f9a 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneData.java @@ -16,6 +16,7 @@ public class AvPhoneData { 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 = "phone.custom."; 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"; diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObject.java similarity index 60% rename from mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java rename to mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObject.java index a63507e..f5b65bc 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModel.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObject.java @@ -1,22 +1,16 @@ package com.sierrawireless.avphone.model; import java.util.ArrayList; -import java.util.List; -/** - * Created by JDamiano on 24/01/2018. - */ - -public class AvPhoneModel { +public class AvPhoneObject { public String name; - ArrayList datas; - private static AvPhoneModel instance = null; + public ArrayList datas; - public AvPhoneModel() { + public AvPhoneObject() { datas = new ArrayList<>(); } - public void add(AvPhoneModelData data ) { + public void add(AvPhoneObjectData data ) { datas.add(data); } @@ -24,13 +18,17 @@ public String toString() { String returned = "{"; returned = returned + "\"name\" : \"" + name + "\","; returned = returned + "\"datas\":["; - for (AvPhoneModelData data: datas) { + for (AvPhoneObjectData data: datas) { returned = returned + data.toString()+","; } returned = returned + "]}"; return returned; } - + public void exec() { + for (AvPhoneObjectData data: datas) { + data.execMode(); + } + } } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObjectData.java similarity index 91% rename from mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java rename to mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObjectData.java index 0e74ef0..56ad9cf 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneModelData.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneObjectData.java @@ -3,7 +3,7 @@ import android.text.TextUtils; -public class AvPhoneModelData { +public class AvPhoneObjectData { public enum Mode { None, UP, @@ -15,10 +15,10 @@ public enum Mode { public String unit; public String defaults; public Mode mode; - private Integer current=null; - private String label; + public Integer current=null; + public String label; - public AvPhoneModelData(String name, String unit, String defaults, Mode mode, String label) { + public AvPhoneObjectData(String name, String unit, String defaults, Mode mode, String label) { this.name = name; this.unit = unit; this.defaults = defaults; diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java index 4755d23..a580f20 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java @@ -10,6 +10,7 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.content.SharedPreferences; import android.location.Criteria; import android.location.Location; import android.location.LocationListener; @@ -25,7 +26,6 @@ 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 android.widget.Toast; @@ -33,8 +33,11 @@ import com.crashlytics.android.Crashlytics; import com.google.gson.Gson; import com.sierrawireless.avphone.MainActivity; +import com.sierrawireless.avphone.ObjectsManager; import com.sierrawireless.avphone.R; import com.sierrawireless.avphone.auth.Authentication; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.tools.MyPreference; import net.airvantage.utils.PreferenceUtils; @@ -43,6 +46,7 @@ import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttMessage; +import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.List; @@ -80,12 +84,14 @@ public class MonitoringService extends Service { private Location networkLocation = null; private Location gpsLocation = null; private LocationListener networkLocationListener; - private LocationListener gpsLocationListener; + private LocationListener gpsLocationListener;; + private ObjectsManager objectsManager; @Override public void onCreate() { // Unique Identification Number for the Notification. int NOTIFICATION = R.string.notif_title; + objectsManager = ObjectsManager.getInstance(); // Display a notification icon @@ -121,18 +127,15 @@ public int onStartCommand(Intent intent, int flags, int startId) { lastRun = System.currentTimeMillis(); + AvPhoneObject object = objectsManager.getCurrentObject(); + try { final Boolean mustConnect = intent.getBooleanExtra(CONNECT, true); - Log.e(TAG, "onStartCommand: mustConnect here " + mustConnect ); /* First we have to create the system if it doesn't exist */ - Authentication auth = PreferenceUtils.readAuthentication(getApplicationContext()); - - if (this.client == null) { - Log.e(TAG, "onStartCommand: Start connect" ); // // Ensure intent is valid @@ -152,12 +155,10 @@ public int onStartCommand(Intent intent, int flags, int startId) { client = new MqttPushClient(deviceId, password, serverHost, mqttCallback); } if (!client.isConnected()) { - Log.e(TAG, "onStartCommand: client connect called"); client.connect(); } if (mustConnect) { - Log.e(TAG, "onStartCommand: Send Data Called"); Location location = getLastKnownLocation(); // retrieve data @@ -239,13 +240,11 @@ public int onStartCommand(Intent intent, int flags, int startId) { data.setBytesReceived(TrafficStats.getMobileRxBytes()); data.setBytesSent(TrafficStats.getMobileTxBytes()); + //execute action on current object datas + objectsManager.execOnCurrent(); // 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()); + data.setCustom(); + customDataSource.next(new Date()); @@ -393,7 +392,6 @@ public void sendAlarmEvent(boolean activated) { } } - NewData data = new NewData(); data.setAlarmActivated(activated); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java index ad3db83..3e73129 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MqttPushClient.java @@ -19,7 +19,10 @@ import com.google.gson.Gson; import com.sierrawireless.avphone.DeviceInfo; +import com.sierrawireless.avphone.ObjectsManager; import com.sierrawireless.avphone.model.AvPhoneData; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; public class MqttPushClient { private static final String TAG = "MqttPushClient"; @@ -29,6 +32,8 @@ public class MqttPushClient { private Gson gson = new Gson(); + private ObjectsManager objectsManager; + @SuppressLint("DefaultLocale") public MqttPushClient(String clientId, String password, String serverHost, MqttCallback callback) throws MqttException { @@ -44,6 +49,7 @@ public MqttPushClient(String clientId, String password, String serverHost, MqttC opt.setUserName(clientId.toUpperCase()); opt.setPassword(password.toCharArray()); opt.setKeepAliveInterval(30); + objectsManager = ObjectsManager.getInstance(); } public boolean isConnected() { @@ -66,10 +72,6 @@ public void push(NewData data) throws MqttException { Log.i(TAG, "Pushing data to the server : " + data); String message = this.convertToJson(data); - Log.d(TAG, "push: json data" + message); - - Log.d(TAG, "Rest content : " + message); - MqttMessage msg = null; try { msg = new MqttMessage(message.getBytes("UTF-8")); @@ -165,26 +167,13 @@ private String convertToJson(NewData data) { 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()))); + AvPhoneObject object = objectsManager.getCurrentObject(); + for (AvPhoneObjectData ldata:object.datas) { + if (ldata.isInteger()) { + values.put(AvPhoneData.CUSTOM + ldata.label, Collections.singletonList(new DataValue(timestamp, ldata.current))); + }else{ + values.put(AvPhoneData.CUSTOM + ldata.label, Collections.singletonList(new DataValue(timestamp, ldata.defaults))); + } } return gson.toJson(Collections.singletonList(values)); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/NewData.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/NewData.java index 8b51b67..8992548 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/NewData.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/NewData.java @@ -3,6 +3,12 @@ import android.content.Intent; import android.os.Bundle; +import com.sierrawireless.avphone.ObjectsManager; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; + +import java.util.ArrayList; + public class NewData extends Intent { public static final String NEW_DATA = "com.sierrawireless.avphone.newdata"; @@ -26,12 +32,14 @@ public class NewData extends Intent { private static final String ALARM_KEY = NEW_DATA_PREFIX + "alarm"; + private static final String CUSTOM = NEW_DATA_PREFIX + "custom."; private static final String CUSTOM_1 = NEW_DATA_PREFIX + "custom.1"; private static final String CUSTOM_2 = NEW_DATA_PREFIX + "custom.2"; private static final String CUSTOM_3 = NEW_DATA_PREFIX + "custom.3"; private static final String CUSTOM_4 = NEW_DATA_PREFIX + "custom.4"; private static final String CUSTOM_5 = NEW_DATA_PREFIX + "custom.5"; private static final String CUSTOM_6 = NEW_DATA_PREFIX + "custom.6"; + private ObjectsManager objectsManager; public NewData() { super(NEW_DATA); @@ -193,63 +201,15 @@ public int size() { return this.getExtras().size(); } - public Integer getCustomIntUp1() { - return (Integer) this.getExtras().get(CUSTOM_1); - } - - public void setCustomIntUp1(Integer custom1) { - if (custom1 != null) { - this.putExtra(CUSTOM_1, custom1); - } - } - - public Integer getCustomIntUp2() { - return (Integer) this.getExtras().get(CUSTOM_2); - } - - public void setCustomIntUp2(Integer custom2) { - if (custom2 != null) { - this.putExtra(CUSTOM_2, custom2); - } - } - - public Integer getCustomIntDown2() { - return (Integer) this.getExtras().get(CUSTOM_4); - } - - public void setCustomIntDown2(Integer custom2) { - if (custom2 != null) { - this.putExtra(CUSTOM_4, custom2); - } - } - - public Integer getCustomIntDown1() { - return (Integer) this.getExtras().get(CUSTOM_3); - } - - public void setCustomIntDown1(Integer custom1) { - if (custom1 != null) { - this.putExtra(CUSTOM_3, custom1); - } - } - - public String getCustomStr1() { - return (String) this.getExtras().get(CUSTOM_5); - } - - public String getCustomStr2() { - return (String) this.getExtras().get(CUSTOM_6); - } - - public void setCustomStr1(String customStr1) { - if (customStr1 != null) { - this.putExtra(CUSTOM_5, customStr1); - } - } - - public void setCustomStr2(String customStr2) { - if (customStr2 != null) { - this.putExtra(CUSTOM_6, customStr2); + public void setCustom() { + objectsManager = ObjectsManager.getInstance(); + AvPhoneObject object = objectsManager.getCurrentObject(); + for (AvPhoneObjectData data:object.datas) { + if (data.isInteger()){ + this.putExtra(CUSTOM+data.label, Integer.parseInt(data.execMode())); + }else{ + this.putExtra(CUSTOM + data.label, data.defaults); + } } } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/ApplicationClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/ApplicationClient.java index fa6d441..2df2fed 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/ApplicationClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/ApplicationClient.java @@ -14,6 +14,7 @@ import net.airvantage.utils.Utils; import com.sierrawireless.avphone.model.AvPhoneApplication; +import com.sierrawireless.avphone.model.AvPhoneObjectData; import com.sierrawireless.avphone.model.CustomDataLabels; public class ApplicationClient implements IApplicationClient { @@ -36,7 +37,7 @@ public Application ensureApplicationExists() throws IOException, AirVantageExcep } @Override - public void setApplicationData(String applicationUid, CustomDataLabels customData) + public void setApplicationData(String applicationUid, ArrayList customData) throws IOException, AirVantageException { List data = AvPhoneApplication.createApplicationData(customData); client.setApplicationData(applicationUid, data); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/IApplicationClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/IApplicationClient.java index 25877f9..9f24b22 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/IApplicationClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/IApplicationClient.java @@ -1,18 +1,19 @@ package com.sierrawireless.avphone.task; import java.io.IOException; +import java.util.ArrayList; import net.airvantage.model.AirVantageException; import net.airvantage.model.Application; import net.airvantage.model.AvSystem; -import com.sierrawireless.avphone.model.CustomDataLabels; +import com.sierrawireless.avphone.model.AvPhoneObjectData; public interface IApplicationClient { Application ensureApplicationExists() throws IOException, AirVantageException; - void setApplicationData(String applicationUid, CustomDataLabels customData) throws IOException, AirVantageException; + void setApplicationData(String applicationUid, ArrayList customData) throws IOException, AirVantageException; Application createApplication() throws IOException, AirVantageException; diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java index a7ad6c9..9fcfa35 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvParams.java @@ -1,5 +1,6 @@ package com.sierrawireless.avphone.task; +import com.sierrawireless.avphone.MainActivity; import com.sierrawireless.avphone.model.CustomDataLabels; public class SyncWithAvParams { @@ -9,4 +10,5 @@ public class SyncWithAvParams { public String iccid; public String deviceName; public CustomDataLabels customData; + public MainActivity activity; } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java index 21ff76f..f9abcfe 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java @@ -7,10 +7,13 @@ import com.crashlytics.android.Crashlytics; import com.sierrawireless.avphone.DeviceInfo; import com.sierrawireless.avphone.MainActivity; +import com.sierrawireless.avphone.ObjectsManager; import com.sierrawireless.avphone.R; import com.sierrawireless.avphone.message.IMessageDisplayer; import com.sierrawireless.avphone.model.AvPhoneApplication; +import com.sierrawireless.avphone.model.AvPhoneObject; import com.sierrawireless.avphone.model.CustomDataLabels; +import com.sierrawireless.avphone.tools.MyPreference; import android.annotation.SuppressLint; import android.app.Activity; @@ -40,6 +43,7 @@ public class SyncWithAvTask extends AsyncTask getListString(String key) { return new ArrayList(Arrays.asList(TextUtils.split(preferences.getString(key, ""), "‚‗‚"))); } - public ArrayList getListObject(String key, Class mClass){ + public ArrayList getListObject(String key, Class mClass){ Gson gson = new Gson(); ArrayList objStrings = getListString(key); - ArrayList objects = new ArrayList(); + ArrayList objects = new ArrayList(); for(String jObjString : objStrings){ - AvPhoneModel value = gson.fromJson(jObjString, mClass); + AvPhoneObject value = gson.fromJson(jObjString, mClass); objects.add(value); } return objects; @@ -127,7 +127,7 @@ public void putObject(String key, Object obj){ putString(key, gson.toJson(obj)); } - public void putListObject(String key, ArrayList objArray){ + public void putListObject(String key, ArrayList objArray){ checkForNullKey(key); Gson gson = new Gson(); ArrayList objStrings = new ArrayList(); From f0313a41d67c7027ba3e6510a0d8d7d76d75e0a5 Mon Sep 17 00:00:00 2001 From: Jean-bernard Damiano Date: Thu, 25 Jan 2018 14:06:33 +0100 Subject: [PATCH 04/60] Rework RunFragment --- mainActivity/build.gradle | 1 + .../avphone/DataViewUpdater.java | 171 +++--- .../sierrawireless/avphone/DeviceInfo.java | 1 - .../sierrawireless/avphone/MainActivity.java | 2 - .../avphone/ObjectsManager.java | 9 +- .../sierrawireless/avphone/RunFragment.java | 151 ++++- .../avphone/adapter/RunListViewAdapter.java | 74 +++ .../avphone/auth/Authentication.java | 2 - .../avphone/auth/AuthenticationManager.java | 8 +- .../avphone/service/MonitoringService.java | 30 +- .../avphone/task/ISystemClient.java | 2 +- .../avphone/task/SyncWithAvTask.java | 2 +- .../avphone/task/SystemClient.java | 27 +- .../avphone/tools/Constant.java | 14 + .../airvantage/utils/AirVantageClient.java | 19 +- .../src/main/res/layout/fragment_run.xml | 527 ++---------------- .../src/main/res/layout/run_column_row.xml | 18 + 17 files changed, 452 insertions(+), 606 deletions(-) create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.java create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/tools/Constant.java create mode 100644 mainActivity/src/main/res/layout/run_column_row.xml diff --git a/mainActivity/build.gradle b/mainActivity/build.gradle index ee5cb5e..ddb83c9 100644 --- a/mainActivity/build.gradle +++ b/mainActivity/build.gradle @@ -52,6 +52,7 @@ dependencies { compile('com.crashlytics.sdk.android:crashlytics-ndk:2.0.1@aar') { transitive = true; } + implementation 'com.android.support.constraint:constraint-layout:1.0.2' } crashlytics { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java index f100d88..8141e9e 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/DataViewUpdater.java @@ -4,18 +4,22 @@ import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; +import java.util.HashMap; import java.util.Locale; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.view.View; +import android.widget.ListView; import android.widget.TextView; +import com.sierrawireless.avphone.adapter.RunListViewAdapter; import com.sierrawireless.avphone.model.AvPhoneObject; import com.sierrawireless.avphone.model.AvPhoneObjectData; import com.sierrawireless.avphone.service.LogMessage; import com.sierrawireless.avphone.service.NewData; +import com.sierrawireless.avphone.tools.Constant; import com.sierrawireless.avphone.tools.MyPreference; /** @@ -28,6 +32,8 @@ public class DataViewUpdater extends BroadcastReceiver { private final View view; private MainActivity activity; private ObjectsManager objectsManager; + private ArrayList> listPhone; + private ArrayList> listObject; public DataViewUpdater(View view, MainActivity activity) { this.view = view; @@ -83,57 +89,82 @@ private void setStartedSince(Long startedSince) { } 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"); - } + ListView phoneListView = (ListView)view.findViewById(R.id.phoneListView); + listPhone = new ArrayList<>(); - if (data.getMemoryUsage() != null) { - findView(R.id.memory_usage_value).setText((int) (data.getMemoryUsage() * 100) + "%"); - } + String Rssi ; - 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"); - } + HashMap temp; - if (data.getAndroidVersion() != null) { - findView(R.id.android_version_value).setText(data.getAndroidVersion()); - } + if (data.getRssi() != null) { + Rssi = data.getRssi() + " dBm (RSSI)"; + } else if (data.getRsrp() != null) { + Rssi = data.getRsrp() + " dBm (RSRP)"; + }else{ + Rssi = "Unknown"; + } + temp = new HashMap<>(); + temp.put(Constant.NAME, "RSSI"); + temp.put(Constant.VALUE, Rssi); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Operator"); + if (data.getOperator() == null) { + temp.put(Constant.VALUE, ""); + }else{ + temp.put(Constant.VALUE, data.getOperator()); + } + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Bytes Sent"); + if (data.getBytesSent() == null) { + temp.put(Constant.VALUE, "0 Mo"); + }else{ + temp.put(Constant.VALUE, ((data.getBytesSent()) / (1024F * 1024F)) + " Mo"); + } + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Bytes Received"); + if (data.getBytesReceived() == null) { + temp.put(Constant.VALUE, "0 Mo"); + }else{ + temp.put(Constant.VALUE, ((data.getBytesReceived()) / (1024F * 1024F)) + " Mo"); + } + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Network Type"); + if (data.getNetworkType() == null) { + temp.put(Constant.VALUE, ""); + }else{ + temp.put(Constant.VALUE, data.getNetworkType()); + } + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Latitude"); + if (data.getLatitude() == null) { + temp.put(Constant.VALUE, ""); + }else{ + temp.put(Constant.VALUE, data.getLatitude().toString()); + } + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Longitude"); + if (data.getLongitude() == null) { + temp.put(Constant.VALUE, ""); + }else{ + temp.put(Constant.VALUE, data.getLongitude().toString()); + } + listPhone.add(temp); + RunListViewAdapter adapter = new RunListViewAdapter(activity, listPhone); + phoneListView.setAdapter(adapter); + phoneListView.invalidateViews(); setCustomDataValues(data); @@ -141,39 +172,25 @@ private void setNewData(NewData data) { } private void setCustomDataValues(NewData data) { - AvPhoneObject model = objectsManager.getCurrentObject(); - for (AvPhoneObjectData ldata:model.datas){ - TextView valueView = null; - String text; - if (ldata.isInteger()){ - text = ldata.current.toString(); + + ListView objectListView = (ListView)view.findViewById(R.id.objectLstView); + objectsManager = ObjectsManager.getInstance(); + AvPhoneObject object = objectsManager.getCurrentObject(); + HashMap temp; + listObject = new ArrayList<>(); + for (AvPhoneObjectData ldata : object.datas) { + temp = new HashMap(); + temp.put(Constant.NAME, ldata.name); + if (ldata.isInteger()) { + temp.put(Constant.VALUE, ldata.current.toString()); }else{ - text = ldata.defaults; - } - switch (ldata.label) { - case "1": - valueView = (TextView) view.findViewById(R.id.run_custom1_value); - break; - case "2": - valueView = (TextView) view.findViewById(R.id.run_custom2_value); - break; - case "3": - valueView = (TextView) view.findViewById(R.id.run_custom3_value); - break; - case "4": - valueView = (TextView) view.findViewById(R.id.run_custom4_value); - break; - case "5": - valueView = (TextView) view.findViewById(R.id.run_custom5_value); - break; - case "6": - valueView = (TextView) view.findViewById(R.id.run_custom6_value); - break; - } - if (valueView != null) { - valueView.setText(text); + temp.put(Constant.VALUE, ldata.defaults); } + listObject.add(temp); } + RunListViewAdapter adapter = new RunListViewAdapter(activity, listObject); + objectListView.setAdapter(adapter); + objectListView.invalidateViews(); } private TextView findView(int id) { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java b/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java index 727bf39..fdfb36b 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/DeviceInfo.java @@ -57,7 +57,6 @@ private static String capitalize(String str) { */ @SuppressLint("DefaultLocale") public static String generateSerial(final String userUid, final String systemType) { - Log.d(TAG, "generateSerial*****************: system_id is " + getDeviceName()); return (userUid); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java index 78e6c94..c310aa9 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java @@ -184,11 +184,9 @@ public void onItemClick(AdapterView parent, View view, int position, long id) { @Override protected void onResume() { super.onResume(); - Toast.makeText(getApplicationContext(), "On resume "+ lastPosition, Toast.LENGTH_SHORT).show(); drawerListView.requestFocusFromTouch(); drawerListView.setItemChecked(lastPosition, true); drawerListView.setSelection(lastPosition); - Toast.makeText(getApplicationContext(), "On resume "+ lastPosition + " " + drawerListView.getCheckedItemPosition(), Toast.LENGTH_SHORT).show(); drawerListView.refreshDrawableState(); //drawerListView.setSelection(); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java index f5eb33a..26a5379 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java @@ -47,11 +47,11 @@ public void init(MainActivity activity){ model.name = "Printer"; AvPhoneObjectData data = new AvPhoneObjectData("A6 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "1"); model.add(data); - data = new AvPhoneObjectData("Black Cartridge S/N", "", "NTOQN-7HUL9-NEPFL-13IOA", AvPhoneObjectData.Mode.None, "2"); + data = new AvPhoneObjectData("A4 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "2"); model.add(data); - data = new AvPhoneObjectData("Black lnk Level", "%", "100", AvPhoneObjectData.Mode.DOWN, "3"); + data = new AvPhoneObjectData("Black Cartridge S/N", "", "NTOQN-7HUL9-NEPFL-13IOA", AvPhoneObjectData.Mode.None, "3"); model.add(data); - data = new AvPhoneObjectData("A4 Page Count", "page(s)", "0", AvPhoneObjectData.Mode.UP, "4"); + data = new AvPhoneObjectData("Black lnk Level", "%", "100", AvPhoneObjectData.Mode.DOWN, "4"); model.add(data); data = new AvPhoneObjectData("Color Cartridge S/N", "", "629U7-XLT5H-6SCGJ-@CENZ", AvPhoneObjectData.Mode.None, "5"); model.add(data); @@ -92,6 +92,9 @@ public void changeCurrent(String name) { } public AvPhoneObject getCurrentObject() { + if (objects.isEmpty()) { + return null; + } return objects.get(current); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java index d5a85d9..12d1b6b 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java @@ -5,7 +5,9 @@ import android.app.Activity; import android.content.IntentFilter; +import android.graphics.Color; import android.os.Bundle; +import android.support.v4.content.ContextCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.SwitchCompat; import android.text.Html; @@ -17,8 +19,10 @@ import android.widget.Button; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.ListView; import android.widget.TextView; +import com.sierrawireless.avphone.adapter.RunListViewAdapter; import com.sierrawireless.avphone.model.AvPhoneObject; import com.sierrawireless.avphone.model.AvPhoneObjectData; import com.sierrawireless.avphone.model.CustomDataLabels; @@ -26,6 +30,11 @@ import com.sierrawireless.avphone.service.MonitoringService; import com.sierrawireless.avphone.service.NewData; import com.sierrawireless.avphone.task.IAsyncTaskFactory; +import com.sierrawireless.avphone.tools.Constant; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; public class RunFragment extends AvPhoneFragment implements MonitorServiceListener, CustomLabelsListener { @@ -44,6 +53,15 @@ public class RunFragment extends AvPhoneFragment implements MonitorServiceListen private IAsyncTaskFactory taskFactory; private String objectName; private ObjectsManager objectsManager; + Button phoneBtn; + Button objectBtn; + ListView phoneListView; + ListView objectListView; + + private ArrayList> listPhone; + private ArrayList> listObject; + + public void setTaskFactory(IAsyncTaskFactory taskFactory) { this.taskFactory = taskFactory; @@ -83,7 +101,7 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa viewUpdater = new DataViewUpdater(view, (MainActivity)getActivity()); CustomDataLabels customLabels = PreferenceUtils.getCustomDataLabels(getActivity()); - setCustomDataLabels(customLabels); + // register service listener LocalBroadcastManager.getInstance(getActivity()).registerReceiver(viewUpdater, @@ -133,6 +151,51 @@ public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { setLinkToSystem(systemUid, systemName); } + phoneBtn = (Button)view.findViewById(R.id.phone); + objectBtn = (Button)view.findViewById(R.id.object); + phoneListView = (ListView)view.findViewById(R.id.phoneListView); + objectListView = (ListView)view.findViewById(R.id.objectLstView); + objectBtn.setText(objectName); + phoneBtn.setBackgroundColor(getResources().getColor(R.color.grey_1)); + phoneListView.setVisibility(View.VISIBLE); + objectListView.setVisibility(View.GONE); + + phoneBtn.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + phoneListView.setVisibility(View.VISIBLE); + objectListView.setVisibility(View.GONE); + phoneBtn.setSelected(true); + phoneBtn.setPressed(true); + phoneBtn.setBackgroundColor(getResources().getColor(R.color.grey_1)); + objectBtn.setSelected(false); + objectBtn.setPressed(false); + objectBtn.setBackgroundColor(getResources().getColor(R.color.grey_4)); + } + } + ); + + objectBtn.setOnClickListener( + new View.OnClickListener() { + @Override + public void onClick(View view) { + phoneListView.setVisibility(View.GONE); + objectListView.setVisibility(View.VISIBLE); + phoneBtn.setSelected(false); + phoneBtn.setPressed(false); + phoneBtn.setBackgroundColor(getResources().getColor(R.color.grey_4)); + objectBtn.setSelected(true); + objectBtn.setPressed(true); + objectBtn.setBackgroundColor(getResources().getColor(R.color.grey_1)); + } + } + ); + + setCustomDataLabels(customLabels); + setPhoneDataLabels(); + + return view; } @@ -192,40 +255,84 @@ private void startMonitoringService() { } else { this.monitorServiceManager.startSendData(); } + this.monitorServiceManager.getMonitoringService().startSendData(); } private void stopMonitoringService() { this.monitorServiceManager.stopSendData(); + this.monitorServiceManager.getMonitoringService().stopSendData(); + } + + + private void setPhoneDataLabels(){ + listPhone = new ArrayList<>(); + + String Rssi ; + + HashMap temp; + + + temp = new HashMap<>(); + temp.put(Constant.NAME, "RSSI"); + temp.put(Constant.VALUE, ""); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Operator"); + temp.put(Constant.VALUE, ""); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Bytes Sent"); + temp.put(Constant.VALUE, "0 Mo"); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Bytes Received"); + temp.put(Constant.VALUE, "0 Mo"); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Network Type"); + temp.put(Constant.VALUE, ""); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Latitude"); + temp.put(Constant.VALUE, ""); + listPhone.add(temp); + + temp = new HashMap<>(); + temp.put(Constant.NAME, "Longitude"); + temp.put(Constant.VALUE, ""); + listPhone.add(temp); + RunListViewAdapter adapter = new RunListViewAdapter(getActivity(), listPhone); + phoneListView.setAdapter(adapter); + phoneListView.invalidateViews(); + } protected void setCustomDataLabels(CustomDataLabels customDataLabels) { - TextView valueView = null; + listObject=new ArrayList>(); + + objectsManager = ObjectsManager.getInstance(); AvPhoneObject object = objectsManager.getObjectByName(objectName); + HashMap temp; for (AvPhoneObjectData data : object.datas) { - switch (data.label) { - case "1": - valueView = (TextView) view.findViewById(R.id.run_custom1_label); - break; - case "2": - valueView = (TextView) view.findViewById(R.id.run_custom2_label); - break; - case "3": - valueView = (TextView) view.findViewById(R.id.run_custom3_label); - break; - case "4": - valueView = (TextView) view.findViewById(R.id.run_custom4_label); - break; - case "5": - valueView = (TextView) view.findViewById(R.id.run_custom5_label); - break; - case "6": - valueView = (TextView) view.findViewById(R.id.run_custom6_label); - break; + temp = new HashMap(); + temp.put(Constant.NAME, data.name); + if (data.isInteger()) { + temp.put(Constant.VALUE, data.current.toString()); + }else{ + temp.put(Constant.VALUE, data.defaults); } - valueView.setText(data.name); + listObject.add(temp); } + RunListViewAdapter adapter = new RunListViewAdapter(getActivity(), listObject); + objectListView.setAdapter(adapter); + objectListView.invalidateViews(); } // Alarm button diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.java b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.java new file mode 100644 index 0000000..6c0e243 --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/RunListViewAdapter.java @@ -0,0 +1,74 @@ +package com.sierrawireless.avphone.adapter; + +import android.app.Activity; +import android.view.LayoutInflater; +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.Constant; + +import java.util.ArrayList; +import java.util.HashMap; + +/** + * Created by JDamiano on 25/01/2018. + */ + +public class RunListViewAdapter extends BaseAdapter{ + public ArrayList> list; + Activity activity; + TextView name; + TextView value; + + public RunListViewAdapter(Activity activity, ArrayList> list){ + super(); + this.activity=activity; + this.list=list; + } + + @Override + public int getCount() { + // TODO Auto-generated method stub + return list.size(); + } + + @Override + public Object getItem(int position) { + // TODO Auto-generated method stub + return list.get(position); + } + + @Override + public long getItemId(int position) { + // TODO Auto-generated method stub + return 0; + } + + + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // TODO Auto-generated method stub + + + + LayoutInflater inflater=activity.getLayoutInflater(); + + if(convertView == null){ + + convertView=inflater.inflate(R.layout.run_column_row, null); + + name=(TextView) convertView.findViewById(R.id.name); + value =(TextView) convertView.findViewById(R.id.value); + } + + HashMap map=list.get(position); + name.setText(map.get(Constant.NAME)); + value.setText(map.get(Constant.VALUE)); + + return convertView; + } +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java index 81b3a00..2016056 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/Authentication.java @@ -3,9 +3,7 @@ import java.util.Date; public class Authentication { - public String code; private String accessToken; - public String refreshToken; private Date expirationDate; public String getAccessToken() { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java index ed6167b..dd71e64 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/auth/AuthenticationManager.java @@ -1,8 +1,8 @@ package com.sierrawireless.avphone.auth; public interface AuthenticationManager { - public void onAuthentication(Authentication auth); - public void forgetAuthentication(); - public boolean isLogged(); - public Authentication getAuthentication(); + void onAuthentication(Authentication auth); + void forgetAuthentication(); + boolean isLogged(); + Authentication getAuthentication(); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java index a580f20..8045740 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/service/MonitoringService.java @@ -90,18 +90,33 @@ public class MonitoringService extends Service { @Override public void onCreate() { // Unique Identification Number for the Notification. - int NOTIFICATION = R.string.notif_title; + objectsManager = ObjectsManager.getInstance(); // Display a notification icon + + + + + 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(); + + } + + public void startSendData(){ + int NOTIFICATION = R.string.notif_title; // 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)) // @@ -112,14 +127,12 @@ public void onCreate() { 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(); + public void stopSendData() { + // Cancel the persistent notification. + stopForeground(true); } @Override @@ -127,7 +140,6 @@ public int onStartCommand(Intent intent, int flags, int startId) { lastRun = System.currentTimeMillis(); - AvPhoneObject object = objectsManager.getCurrentObject(); try { final Boolean mustConnect = intent.getBooleanExtra(CONNECT, true); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java index d8b2508..4d2f896 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/ISystemClient.java @@ -7,7 +7,7 @@ public interface ISystemClient { - AvSystem getSystem(String serialNumber) throws IOException, AirVantageException; + AvSystem getSystem(String serialNumber, String type) throws IOException, AirVantageException; AvSystem createSystem(String serialNumber, String iccid, String type, String mqttPassword, String applicationUid, String deviceName, String userName, String imei) throws IOException, AirVantageException; diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java index f9abcfe..f1afa3d 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SyncWithAvTask.java @@ -99,7 +99,7 @@ protected SyncWithAvResult doInBackground(SyncWithAvParams... params) { publishProgress(SyncProgress.CHECKING_SYSTEM); - net.airvantage.model.AvSystem system = this.systemClient.getSystem(serialNumber); + net.airvantage.model.AvSystem system = this.systemClient.getSystem(serialNumber, systemType); if (system == null) { publishProgress(SyncProgress.CREATING_SYSTEM); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java index 63a4867..0947ff4 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/task/SystemClient.java @@ -1,5 +1,9 @@ package com.sierrawireless.avphone.task; +import android.util.Log; + +import com.sierrawireless.avphone.tools.Constant; + import java.io.IOException; import java.util.Arrays; import java.util.HashMap; @@ -13,6 +17,7 @@ import net.airvantage.utils.Utils; public class SystemClient implements ISystemClient { + private static final String TAG = "SystemClient"; private AirVantageClient client; @@ -21,10 +26,10 @@ public SystemClient(AirVantageClient client) { } @Override - public net.airvantage.model.AvSystem getSystem(final String serialNumber) throws IOException, AirVantageException { - List systems = client.getSystemsBySerialNumber(serialNumber); + public net.airvantage.model.AvSystem getSystem(final String serialNumber, String type) throws IOException, AirVantageException { + List systems = client.getSystemsBySerialNumber(Constant.buildSerialNumber(serialNumber, type)); - return Utils.firstWhere(systems, AvSystem.hasSerialNumber(serialNumber)); + return Utils.firstWhere(systems, AvSystem.hasSerialNumber(Constant.buildSerialNumber(serialNumber, type))); } @Override @@ -32,12 +37,18 @@ public net.airvantage.model.AvSystem createSystem(String serialNumber, String ic String applicationUid, String deviceName, String userName, String imei) throws IOException, AirVantageException { net.airvantage.model.AvSystem system = new net.airvantage.model.AvSystem(); - client.getGateway(serialNumber + "-" + type); - + Boolean exist = client.getGateway((serialNumber + "-ANDROID-" + type).toUpperCase()); net.airvantage.model.AvSystem.Gateway gateway = new net.airvantage.model.AvSystem.Gateway(); - gateway.serialNumber = serialNumber + "-ANDROID-" + type; - gateway.imei = imei; - gateway.type = type; + + if (!exist) { + gateway.serialNumber = (serialNumber + "-ANDROID-" + type).toUpperCase(); + gateway.imei = imei; + gateway.type = type; + }else{ + gateway.serialNumber = (serialNumber + "-ANDROID-" + type).toUpperCase(); + } + Log.d(TAG, "createSystem: Gateway exit " + exist); + Log.d(TAG, "gateway is " + (serialNumber + "-ANDROID-" + type).toUpperCase() ); system.name = deviceName + " de " + userName + "(" + type + ")"; system.gateway = gateway; diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/tools/Constant.java b/mainActivity/src/main/java/com/sierrawireless/avphone/tools/Constant.java new file mode 100644 index 0000000..30dae40 --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/tools/Constant.java @@ -0,0 +1,14 @@ +package com.sierrawireless.avphone.tools; + +/** + * Created by JDamiano on 25/01/2018. + */ + +public class Constant { + public static final String NAME="name"; + public static final String VALUE="value"; + + public static String buildSerialNumber(String serial, String type) { + return (serial + "-ANDROID-" + type).toUpperCase(); + } +} diff --git a/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java b/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java index 03598a7..ad5e674 100644 --- a/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java +++ b/mainActivity/src/main/java/net/airvantage/utils/AirVantageClient.java @@ -234,11 +234,12 @@ public List getSystemsBySerialNumber(String seria urlString += "&gateway=serialNumber:" + serialNumber; } URL url = new URL(urlString); + Log.d(TAG, "getSystemsBySerialNumber: url " + url); InputStream in = this.get(url); return gson.fromJson(new InputStreamReader(in), SystemsList.class).items; } - public void getGateway(String serialNumber) throws IOException, AirVantageException { + public Boolean getGateway(String serialNumber) throws IOException, AirVantageException { String urlString = buildEndpoint("/gateways"); Log.d(TAG, "getGateway: urlString " + urlString); URL url = new URL(urlString); @@ -250,10 +251,22 @@ public void getGateway(String serialNumber) throws IOException, AirVantageExcept while ((line = reader.readLine()) != null) { sb.append(line); } - in.close(); - Log.d(TAG, "getGateway: answer " + sb.toString()); + try { + JSONObject json = new JSONObject(sb.toString()); + JSONArray jsonValues = json.getJSONArray("items"); + for (int i = 0; i < jsonValues.length(); i++) { + JSONObject entry = jsonValues.getJSONObject(i); + String name = entry.getString("serialNumber"); + if (name.equals(serialNumber)) { + return true; + } + } + } catch (JSONException e) { + return false; + } + return false; } public net.airvantage.model.AvSystem createSystem(net.airvantage.model.AvSystem system) diff --git a/mainActivity/src/main/res/layout/fragment_run.xml b/mainActivity/src/main/res/layout/fragment_run.xml index d50d2fa..dbd8471 100644 --- a/mainActivity/src/main/res/layout/fragment_run.xml +++ b/mainActivity/src/main/res/layout/fragment_run.xml @@ -1,4 +1,5 @@ + android:orientation="vertical"> + android:textColor="@android:color/white" + android:visibility="gone" /> + android:orientation="horizontal"> + android:orientation="vertical"> + android:textOn="ON" + android:theme="@style/Switch" /> @@ -96,493 +98,72 @@ android:gravity="center" android:text="@string/toggle_to_start" android:textSize="12sp" /> - + + android:textSize="12sp" + android:visibility="gone" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + android:textSize="12sp" + android:visibility="gone" /> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + - + - - - - + android:background="@color/grey_4" + android:text="Phone" + app:layout_constraintBaseline_toBaselineOf="@+id/object" + app:layout_constraintEnd_toStartOf="@+id/object" + app:layout_constraintStart_toStartOf="parent" /> - - - + android:background="@color/grey_4" + android:text="Object" + 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/run_column_row.xml b/mainActivity/src/main/res/layout/run_column_row.xml new file mode 100644 index 0000000..a71a1c6 --- /dev/null +++ b/mainActivity/src/main/res/layout/run_column_row.xml @@ -0,0 +1,18 @@ + + + + + + + From d204261bcf6d6b427fe1f589d77d8c7fdcb98cac Mon Sep 17 00:00:00 2001 From: Jean-bernard Damiano Date: Fri, 26 Jan 2018 14:20:19 +0100 Subject: [PATCH 05/60] Allow the creation and destruction of object --- mainActivity/build.gradle | 1 + .../avphone/AuthorizationActivity.java | 3 + .../avphone/AvPhoneFragment.java | 1 + .../avphone/ConfigureFragment.java | 242 ++++++++++++------ .../sierrawireless/avphone/MainActivity.java | 111 ++++++-- .../avphone/MonitorServiceManager.java | 5 +- .../avphone/ObjectConfigure.java | 199 ++++++++++++++ .../avphone/ObjectDataActivity.java | 124 +++++++++ .../avphone/ObjectsManager.java | 49 +++- .../sierrawireless/avphone/RunFragment.java | 95 ++++++- .../adapter/AvPhoneObjectDataAdapter.java | 91 +++++++ .../avphone/adapter/ObjectAdapter.java | 101 ++++++++ .../avphone/model/AvPhoneApplication.java | 19 +- .../avphone/model/AvPhoneObjectData.java | 27 +- .../avphone/service/MonitoringService.java | 8 +- .../avphone/service/MqttPushClient.java | 7 +- .../avphone/service/NewData.java | 6 +- .../avphone/task/ApplicationClient.java | 6 + .../avphone/task/ISystemClient.java | 2 + .../avphone/task/SyncProgress.java | 3 +- .../avphone/task/SyncWithAvParams.java | 1 + .../avphone/task/SyncWithAvTask.java | 15 +- .../avphone/task/SystemClient.java | 7 +- .../avphone/tools/Constant.java | 6 + .../airvantage/utils/AirVantageClient.java | 21 +- .../res/layout/activity_object_configure.xml | 76 ++++++ .../main/res/layout/activity_object_data.xml | 136 ++++++++++ .../main/res/layout/fragment_configure.xml | 221 +++------------- 28 files changed, 1286 insertions(+), 297 deletions(-) create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/ObjectConfigure.java create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/ObjectDataActivity.java create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/adapter/AvPhoneObjectDataAdapter.java create mode 100644 mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.java create mode 100644 mainActivity/src/main/res/layout/activity_object_configure.xml create mode 100644 mainActivity/src/main/res/layout/activity_object_data.xml diff --git a/mainActivity/build.gradle b/mainActivity/build.gradle index ddb83c9..6562563 100644 --- a/mainActivity/build.gradle +++ b/mainActivity/build.gradle @@ -44,6 +44,7 @@ dependencies { compile 'com.android.support:appcompat-v7:22.2.1' compile 'com.google.code.gson:gson:2.8.0' compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.0.2' + compile 'com.baoyz.swipemenulistview:library:1.3.0' //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') { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java index 93ece8d..685e838 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/AuthorizationActivity.java @@ -85,6 +85,9 @@ protected void onCreate(Bundle savedInstanceState) { } else { btnCustom.setVisibility(Button.GONE); } + AvPhonePrefs avPhonePrefs = PreferenceUtils.getAvPhonePrefs(this); + final String serverHost = avPhonePrefs.serverHost; + openAuthorizationPage(); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java index 1a6e950..dd6155f 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/AvPhoneFragment.java @@ -80,6 +80,7 @@ private void toast(String message) { } protected void requestAuthentication() { + Intent intent = new Intent(this.getActivity(), AuthorizationActivity.class); this.startActivityForResult(intent, AuthorizationActivity.REQUEST_AUTHORIZATION); } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java index 9be3362..20994c6 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ConfigureFragment.java @@ -3,42 +3,63 @@ import net.airvantage.utils.AvPhonePrefs; import net.airvantage.utils.PreferenceUtils; +import android.app.Activity; +import android.app.FragmentManager; import android.content.Intent; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; +import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; +import android.widget.ListView; import android.widget.TextView; +import com.baoyz.swipemenulistview.SwipeMenu; +import com.baoyz.swipemenulistview.SwipeMenuCreator; +import com.baoyz.swipemenulistview.SwipeMenuItem; +import com.baoyz.swipemenulistview.SwipeMenuListView; +import com.sierrawireless.avphone.adapter.AvPhoneObjectDataAdapter; +import com.sierrawireless.avphone.adapter.ObjectAdapter; import com.sierrawireless.avphone.auth.AuthUtils; import com.sierrawireless.avphone.auth.Authentication; import com.sierrawireless.avphone.message.IMessageDisplayer; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; 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; +import com.sierrawireless.avphone.tools.Constant; + +import java.util.ArrayList; public class ConfigureFragment extends AvPhoneFragment { + private static final String TAG = "ConfigureFragment"; + + private Button addBtn; + private Button doneBtn; - private Button saveBt; + private SwipeMenuListView listView; - private EditText customData1EditText; - private EditText customData2EditText; - private EditText customData3EditText; - private EditText customData4EditText; - private EditText customData5EditText; - private EditText customData6EditText; + private ObjectsManager objectsManager; + ArrayList menu; + public static String INDEX = "index"; + public static int CONFIGURE = 0; + public static String POS = "position"; + private boolean delete; private View view; - private String deviceId; - private String imei; private IAsyncTaskFactory taskFactory; @@ -50,67 +71,116 @@ 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); + objectsManager = ObjectsManager.getInstance(); + - // try to get the IMEI for GSM phones - imei = DeviceInfo.getIMEI(this.getActivity()); + menu = new ArrayList<>(); + + for (AvPhoneObject object: objectsManager.objects) { + menu.add(object.name); + } + + listView = (SwipeMenuListView) view.findViewById(R.id.objectConfigure); + + SwipeMenuCreator creator = new SwipeMenuCreator() { - // Register button - saveBt = (Button) view.findViewById(R.id.save_bt); - saveBt.setOnClickListener(new View.OnClickListener() { @Override - public void onClick(View view) { - onRegisterClicked(); + public void create(SwipeMenu menu) { + + switch (menu.getViewType()) { + case 0: + // create "delete" item + SwipeMenuItem deleteItem = new SwipeMenuItem( + getActivity().getBaseContext()); + // set item background + deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, + 0x3F, 0x25))); + // set item width + deleteItem.setWidth((int) Constant.dp2px(90, + getActivity().getBaseContext())); + // set a icon + deleteItem.setIcon(android.R.drawable.ic_menu_delete); + // add to menu + menu.addMenuItem(deleteItem); + break; + } } - }); - // 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)); + listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() { + @Override + public boolean onMenuItemClick(int position, SwipeMenu lmenu, int index) { + switch (index) { + case 0: + //delete + objectsManager.setSavedPosition(position); + delete(); + delete = true; + break; + + } + return false; + } + }); + + listView.setMenuCreator(creator); - res.addTextChangedListener(new TextWatcher() { + ObjectAdapter adapter = new ObjectAdapter(getActivity(), android.R.layout.simple_list_item_1, menu); + listView.setAdapter(adapter); + + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override - public void onTextChanged(CharSequence s, int start, int before, int count) { + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + //Open a new intent with the selected Object + Log.d(TAG, "onItemClick: " + i + " " +menu.get(i)); + Intent intent = new Intent(view.getContext(), ObjectConfigure.class); + intent.putExtra(INDEX, i); + + startActivityForResult(intent, CONFIGURE); + } + }); + + + doneBtn = (Button) view.findViewById(R.id.doneConfigureBtn); + addBtn = (Button)view.findViewById(R.id.addConfigureBtn); + doneBtn.setOnClickListener(new View.OnClickListener() { @Override - public void beforeTextChanged(CharSequence s, int start, int count, int after) { + public void onClick(View view) { + ((MainActivity)getActivity()).goHomeFragment(); } + }); + addBtn.setOnClickListener(new View.OnClickListener() { @Override - public void afterTextChanged(Editable s) { - PreferenceUtils.setPreference(getActivity(), getActivity().getString(prefKeyId), s.toString()); + public void onClick(View view) { + Intent intent = new Intent(view.getContext(), ObjectConfigure.class); + intent.putExtra(INDEX, -1); + + startActivityForResult(intent, CONFIGURE); } }); - return res; + + + return view; } + + + private boolean checkCredentials() { AvPhonePrefs prefs = PreferenceUtils.getAvPhonePrefs(getActivity()); @@ -124,28 +194,53 @@ private boolean checkCredentials() { } - protected void onRegisterClicked() { + @Override + public void onActivityResult(int requestCode, int resultCode, Intent data) { + super.onActivityResult(requestCode, resultCode, data); + + if (requestCode == AuthorizationActivity.REQUEST_AUTHORIZATION) { + Authentication auth = AuthUtils.activityResultAsAuthentication(requestCode, resultCode, data); + if (auth != null) { + authManager.onAuthentication(auth); + syncWithAv(auth.getAccessToken(), this.delete); + } + }else if (requestCode == CONFIGURE) { + if (resultCode == Activity.RESULT_OK) { + this.delete = false; + int position = data.getIntExtra(POS, -1); + //set current and start synchronization + + objectsManager.setSavedPosition(position); + + if (checkCredentials()) { + Authentication auth = authManager.getAuthentication(); + if (auth != null && !auth.isExpired()) { + syncWithAv(auth.getAccessToken(), false); + } else { + this.delete = false; + requestAuthentication(); + } + } + } + MainActivity.instance.loadMenu(); + + + } + } + + protected void delete() { if (checkCredentials()) { Authentication auth = authManager.getAuthentication(); if (auth != null && !auth.isExpired()) { - syncWithAv(auth.getAccessToken()); + syncWithAv(auth.getAccessToken(), true); } else { + this.delete = true; 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) { + private void syncWithAv(String token, final boolean delete) { AvPhonePrefs prefs = PreferenceUtils.getAvPhonePrefs(getActivity()); @@ -154,17 +249,30 @@ private void syncWithAv(String token) { final SyncWithAvTask syncTask = taskFactory.syncAvTask(prefs.serverHost, token); SyncWithAvParams syncParams = new SyncWithAvParams(); - syncParams.deviceId = deviceId; - syncParams.imei = imei; + syncParams.deviceId = DeviceInfo.getUniqueId(getActivity()); + syncParams.imei = DeviceInfo.getIMEI(getActivity()); + syncParams.deviceName = DeviceInfo.getDeviceName(); + syncParams.iccid = DeviceInfo.getICCID(getActivity()); syncParams.mqttPassword = prefs.password; - syncParams.customData = getCustomDataLabels(); + syncParams.customData = PreferenceUtils.getCustomDataLabels(getActivity()); + // params.current = ((MainActivity)getActivity()).current; + // syncParams.activity = getActivity(); + if (delete) { + syncParams.delete = delete; + } syncTask.execute(syncParams); syncTask.addProgressListener(new SyncWithAvListener() { @Override public void onSynced(SyncWithAvResult result) { + Log.d(TAG, "onSynced: ICI"); + if (delete) { + objectsManager.removeSavedObject(); + } + syncTask.showResult(result, display, getActivity()); + MainActivity.instance.loadMenu(); if (!result.isError()) { syncListener.onSynced(result); @@ -175,19 +283,9 @@ public void onSynced(SyncWithAvResult 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); - } + return (TextView) view.findViewById(R.id.configure_error_message); + } } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java index c310aa9..87bbd17 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MainActivity.java @@ -35,6 +35,7 @@ import com.crashlytics.android.ndk.CrashlyticsNdk; import com.sierrawireless.avphone.auth.Authentication; import com.sierrawireless.avphone.auth.AuthenticationManager; +import com.sierrawireless.avphone.model.AvPhoneObject; import com.sierrawireless.avphone.service.MonitoringService; import com.sierrawireless.avphone.service.MonitoringService.ServiceBinder; import com.sierrawireless.avphone.task.AsyncTaskFactory; @@ -68,6 +69,7 @@ public class MainActivity extends FragmentActivity 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 String objectName; private ActionBar actionBar; private AlarmManager alarmManager; @@ -86,27 +88,29 @@ public class MainActivity extends FragmentActivity private final static String FRAGMENT_HOME = "Home"; private final static String FRAGMENT_RUN = "Run"; - private final static String FRAGMENT_CONFIGURE = "Objects"; + private final static String FRAGMENT_CONFIGURE = "Objects..."; private final static String FRAGMENT_SETTINGS = "Settings"; private final static String FRAGMENT_FAQ = "FAQ"; private ConfigureFragment configureFragment; private HomeFragment homeFragment; - private RunFragment runFragment; + private ArrayList runFragment; private int lastPosition = 0; private Boolean serviceSendData = false; ObjectsManager objectsManager; - SharedPreferences preferences; + static MainActivity instance; private static String[] FRAGMENT_LIST; public String[] buildFragmentList() { ArrayList tmp = new ArrayList<>(); tmp.add(FRAGMENT_HOME); - tmp.add(objectsManager.getCurrentObjectName()); + for (AvPhoneObject object: objectsManager.objects) { + tmp.add(object.name); + } tmp.add(FRAGMENT_CONFIGURE); tmp.add(FRAGMENT_SETTINGS); tmp.add(FRAGMENT_FAQ); @@ -118,9 +122,15 @@ public void setCustomLabelsListener(CustomLabelsListener customLabelsListener) { this.customLabelsListener = customLabelsListener; } + static MainActivity getInstance() { + return instance; + } + @Override protected void onCreate(Bundle savedInstanceState) { + + MainActivity.instance = this; // Initialization og Object Manager objectsManager = ObjectsManager.getInstance(); objectsManager.init(this); @@ -136,13 +146,9 @@ protected void onCreate(Bundle savedInstanceState) { taskFactory = new AsyncTaskFactory(MainActivity.this); - FRAGMENT_LIST = buildFragmentList(); drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout); - drawerListView = (ListView) findViewById(R.id.left_drawer); - drawerListView.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_item, buildFragmentList())); + loadMenu(); - drawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); - // Set the list's click listener drawerListView.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView parent, View view, int position, long id) { @@ -156,6 +162,18 @@ public void onItemClick(AdapterView parent, View view, int position, long id) { R.string.drawer_close); drawerLayout.setDrawerListener(drawerToggle); + + } + + public void loadMenu() { + FRAGMENT_LIST = buildFragmentList(); + drawerListView = (ListView) findViewById(R.id.left_drawer); + + drawerListView.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_item, buildFragmentList())); + + drawerListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); + // Set the list's click listener + drawerListView.invalidateViews(); final Map fragments = initFragments(); final Fragment currentFragment; if (isLogged()) { @@ -179,8 +197,8 @@ public void onItemClick(AdapterView parent, View view, int position, long id) { } selectItem(currentFragment); - } + } @Override protected void onResume() { super.onResume(); @@ -189,6 +207,7 @@ protected void onResume() { drawerListView.setSelection(lastPosition); drawerListView.refreshDrawableState(); //drawerListView.setSelection(); + } @Override @@ -327,7 +346,28 @@ public boolean isServiceRunning() { } - public boolean isServiceStarted() { + public boolean isServiceStarted(String name) { + if (this.objectName != name) { + return false; + } + //return serviceSendData; + + ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); + if (manager == null) { + Log.e(TAG, "isServiceRunning: can't get activity service"); + Toast.makeText(getApplicationContext(), "can't get activity service" ,Toast.LENGTH_SHORT).show(); + return false; + } + for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) { + if (MonitoringService.class.getName().equals(service.service.getClassName())) { + return true; + } + } + return false; + + } + + public boolean oneServiceStarted() { //return serviceSendData; ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); @@ -388,7 +428,8 @@ public void sendAlarmEvent(boolean activated) { } @Override - public void startMonitoringService() { + public void startMonitoringService(String name) { + this.objectName = name; AvPhonePrefs avPrefs = PreferenceUtils.getAvPhonePrefs(this); Intent intent = new Intent(this, MonitoringService.class); @@ -396,6 +437,7 @@ public void startMonitoringService() { intent.putExtra(MonitoringService.SERVER_HOST, avPrefs.serverHost); intent.putExtra(MonitoringService.PASSWORD, avPrefs.password); intent.putExtra(MonitoringService.CONNECT, false); + intent.putExtra(MonitoringService.OBJECT_NAME, name); PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, @@ -449,7 +491,7 @@ public void stopMonitoringService() { private void restartMonitoringService() { stopMonitoringService(); - startMonitoringService(); + startMonitoringService(objectName); } @Override @@ -472,6 +514,9 @@ public void setMonitoringServiceListener(MonitorServiceListener listener) { public void onSynced(SyncWithAvResult result) { final AvSystem system = result.getSystem(); + if (system == null){ + return; + } prefs.edit().putString("systemUid", system.uid).apply(); prefs.edit().putString(PREFERENCE_SYSTEM_NAME, system.name).apply(); @@ -485,7 +530,9 @@ public void onSynced(SyncWithAvResult result) { if (runFragment != null) { String systemUid = this.getSystemUid(); String systemName = this.getSystemName(); - runFragment.setLinkToSystem(systemUid, systemName); + for (RunFragment tmp:runFragment) { + tmp.setLinkToSystem(systemUid, systemName); + } } else { Log.w(TAG, "RunFragment reference is null when onSynced is called"); } @@ -530,6 +577,7 @@ private void selectItem(final int position) { getFragmentManager() .beginTransaction() .replace(R.id.content_frame, fragment) + .addToBackStack(null) .commit(); // Highlight the selected item, update the title, and close the drawer @@ -540,6 +588,23 @@ private void selectItem(final int position) { lastPosition = position; } + public void goHomeFragment() { + final Fragment fragment = getFragment(0); + // Insert the fragment by replacing any existing fragment + getFragmentManager() + .beginTransaction() + .replace(R.id.content_frame, fragment) + .addToBackStack(null) + .commit(); + + // Highlight the selected item, update the title, and close the drawer + drawerListView.setItemChecked(0, true); + setTitle(FRAGMENT_LIST[0]); + drawerListView.setSelection(0); + drawerLayout.closeDrawer(drawerListView); + lastPosition = 0; + + } private void selectItem(final Fragment fragment) { final Iterator fragmentsIterator = initFragments().values().iterator(); for (int position = 0; fragmentsIterator.hasNext(); position++) { @@ -564,18 +629,26 @@ private Map initFragments() { homeFragment.setTaskFactory(taskFactory); } + runFragment = new ArrayList<>(); - if (runFragment == null) { - runFragment = new RunFragment(); - runFragment.setTaskFactory(taskFactory); - runFragment.setObjectName(objectsManager.getCurrentObjectName()); + RunFragment tmp; + for (AvPhoneObject object: objectsManager.objects) { + tmp = new RunFragment(); + tmp.setTaskFactory(taskFactory); + tmp.setObjectName(object.name); + runFragment.add(tmp); } + final HashMap fragmentsMapping = new HashMap<>(); fragmentsMapping.put(FRAGMENT_CONFIGURE, configureFragment); fragmentsMapping.put(FRAGMENT_HOME, homeFragment); fragmentsMapping.put(FRAGMENT_SETTINGS, new SettingsActivity.SettingsFragment()); - fragmentsMapping.put(objectsManager.getCurrentObjectName(), runFragment); + int pos = 0; + for (AvPhoneObject object: objectsManager.objects) { + fragmentsMapping.put(object.name, runFragment.get(pos)); + pos++; + } return fragmentsMapping; } diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java index e4ef5b5..1f4667f 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/MonitorServiceManager.java @@ -5,9 +5,10 @@ public interface MonitorServiceManager { boolean isServiceRunning(); - boolean isServiceStarted(); + boolean isServiceStarted(String name); + boolean oneServiceStarted(); void stopMonitoringService(); - void startMonitoringService(); + void startMonitoringService(String name); void startSendData(); void stopSendData(); void sendAlarmEvent(boolean activated); diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectConfigure.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectConfigure.java new file mode 100644 index 0000000..6852c5e --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectConfigure.java @@ -0,0 +1,199 @@ +package com.sierrawireless.avphone; + +import android.app.Activity; +import android.content.Context; +import android.content.Intent; +import android.graphics.Color; +import android.graphics.drawable.ColorDrawable; +import android.support.v7.app.AppCompatActivity; +import android.os.Bundle; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.ListView; +import android.widget.TextView; + +import com.baoyz.swipemenulistview.SwipeMenu; +import com.baoyz.swipemenulistview.SwipeMenuCreator; +import com.baoyz.swipemenulistview.SwipeMenuItem; +import com.baoyz.swipemenulistview.SwipeMenuListView; +import com.sierrawireless.avphone.adapter.AvPhoneObjectDataAdapter; +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; +import com.sierrawireless.avphone.tools.Constant; + +import org.w3c.dom.Text; + +import java.util.ArrayList; + +public class ObjectConfigure extends Activity { + + Button cancel; + Button save; + SwipeMenuListView listView; + ObjectsManager objectsManager; + ArrayList menu; + int position; + AvPhoneObject object; + AvPhoneObject tmpObject; + TextView title; + TextView name; + EditText nameEdit; + + public static String OBJECT_POSITION = "object_pos"; + public static String DATA_POSITION = "data_position"; + public static String ADD = "add"; + private Context context; + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_object_configure); + cancel = (Button)findViewById(R.id.cancel); + save = (Button)findViewById(R.id.save); + listView = (SwipeMenuListView)findViewById(R.id.listView); + objectsManager = ObjectsManager.getInstance(); + title = (TextView)findViewById(R.id.titleObject); + name = (TextView)findViewById(R.id.nameObject); + nameEdit = (EditText) findViewById(R.id.objectNameEdit); + + context = this; + SwipeMenuCreator creator = new SwipeMenuCreator() { + + @Override + public void create(SwipeMenu menu) { + + switch (menu.getViewType()) { + case 0: + // create "delete" item + SwipeMenuItem deleteItem = new SwipeMenuItem( + getApplicationContext()); + // set item background + deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9, + 0x3F, 0x25))); + // set item width + deleteItem.setWidth((int) Constant.dp2px(90, context)); + // set a icon + deleteItem.setIcon(android.R.drawable.ic_menu_delete); + // add to menu + menu.addMenuItem(deleteItem); + break; + } + } + }; + + listView.setMenuCreator(creator); + + + Intent intent = getIntent(); + position = intent.getIntExtra(ConfigureFragment.INDEX, -1); + + if (position == -1) { + object = new AvPhoneObject(); + title.setText("Add New Object"); + objectsManager.objects.add(object); + position = objectsManager.objects.size() -1; + }else { + object = objectsManager.getObjectByIndex(position); + name.setVisibility(View.GONE); + nameEdit.setVisibility(View.GONE); + title.setText(object.name); + } + menu = new ArrayList<>(); + for (AvPhoneObjectData data:object.datas) { + menu.add(data.name); + } + menu.add("Add new data...."); + AvPhoneObjectDataAdapter adapter = new AvPhoneObjectDataAdapter(this, android.R.layout.simple_list_item_1, menu); + + + + listView.setAdapter(adapter); + cancel.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + //reload object from list + objectsManager.reload(); + Intent i = new Intent(); + setResult(Activity.RESULT_CANCELED, i); + finish(); + } + }); + + save.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + if (nameEdit.getVisibility() != View.GONE) { + object.name = nameEdit.getText().toString(); + } + objectsManager.save(); + Intent i = new Intent(); + i.putExtra(ConfigureFragment.POS, position); + setResult(Activity.RESULT_OK, i); + finish(); + } + }); + + + listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() { + @Override + public boolean onMenuItemClick(int position, SwipeMenu lmenu, int index) { + switch (index) { + case 0: + //delete + object.datas.remove(position); + menu = new ArrayList<>(); + for (AvPhoneObjectData data:object.datas) { + menu.add(data.name); + } + menu.add("Add new data...."); + ArrayAdapter adapter = new ArrayAdapter(listView.getContext(), android.R.layout.simple_list_item_1, menu); + + + + listView.setAdapter(adapter); + listView.invalidateViews(); + break; + + } + return false; + } + }); + listView.setOnItemClickListener( + new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int i, long l) { + Intent intent = new Intent(view.getContext(), ObjectDataActivity.class); + intent.putExtra(OBJECT_POSITION, position); + intent.putExtra(DATA_POSITION, i); + if (i == menu.size()-1) { + intent.putExtra(ADD, true); + }else{ + intent.putExtra(ADD, false); + } + startActivity(intent); + } + } + ); + + } + + @Override + protected void onResume() { + super.onResume(); + menu = new ArrayList<>(); + for (AvPhoneObjectData data:object.datas) { + menu.add(data.name); + } + menu.add("Add new data...."); + AvPhoneObjectDataAdapter adapter = new AvPhoneObjectDataAdapter(this, android.R.layout.simple_list_item_1, menu); + + + + + listView.setAdapter(adapter); + listView.invalidateViews(); + } +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectDataActivity.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectDataActivity.java new file mode 100644 index 0000000..913955f --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectDataActivity.java @@ -0,0 +1,124 @@ +package com.sierrawireless.avphone; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.widget.AdapterView; +import android.widget.ArrayAdapter; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Spinner; +import android.widget.TextView; + +import com.sierrawireless.avphone.model.AvPhoneObject; +import com.sierrawireless.avphone.model.AvPhoneObjectData; + +public class ObjectDataActivity extends Activity implements AdapterView.OnItemSelectedListener { + TextView title; + TextView name; + EditText nameEdit; + EditText unitEdit; + EditText defaulEdit; + Spinner simulationSpin; + Button saveBtn; + Button cancelBtn; + ObjectsManager objectsManager; + AvPhoneObject object; + AvPhoneObjectData data; + int objectPosition; + int dataPosition; + boolean add; + + @Override + protected void onCreate(Bundle savedInstanceState) { + String[] menuList = {"None", "Increase indefinitely", "Decrease to zero"}; + + + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_object_data); + Intent intent = getIntent(); + objectPosition = intent.getIntExtra(ObjectConfigure.OBJECT_POSITION, -1); + dataPosition = intent.getIntExtra(ObjectConfigure.DATA_POSITION, -1); + add= intent.getBooleanExtra(ObjectConfigure.ADD, true); + + if (objectPosition == -1 || dataPosition == -1) { + return; + } + title = (TextView)findViewById(R.id.title); + name = (TextView)findViewById(R.id.name); + nameEdit = (EditText)findViewById(R.id.nameText); + unitEdit = (EditText)findViewById(R.id.unitText); + defaulEdit = (EditText)findViewById(R.id.defaultText); + simulationSpin = (Spinner)findViewById(R.id.spinner); + saveBtn = (Button)findViewById(R.id.saveData); + cancelBtn = (Button)findViewById(R.id.cancelData); + + objectsManager = ObjectsManager.getInstance(); + object = objectsManager.getObjectByIndex(objectPosition); + + // Create an ArrayAdapter using the string array and a default spinner layout + ArrayAdapter adapter = new 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 + + simulationSpin.setAdapter(adapter); + simulationSpin.setOnItemSelectedListener(this); + + if (add== false) { + name.setVisibility(View.INVISIBLE); + nameEdit.setVisibility(View.GONE); + data = object.datas.get(dataPosition); + title.setText(data.name); + unitEdit.setText(data.unit); + defaulEdit.setText(data.defaults); + simulationSpin.setSelection(data.modePosition(), false); + + }else{ + title.setText("Add new data"); + } + + cancelBtn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + Intent intent = new Intent(); + finish(); + } + }); + + saveBtn.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View view) { + AvPhoneObjectData.Mode mode = AvPhoneObjectData.modeFromPosition(simulationSpin.getSelectedItemPosition()); + if (add == true) { + data = new AvPhoneObjectData( + nameEdit.getText().toString(), + unitEdit.getText().toString(), + defaulEdit.getText().toString(), + mode, + String.valueOf(objectPosition) + ); + object.datas.add(data); + }else{ + data.unit =unitEdit.getText().toString(); + data.defaults = defaulEdit.getText().toString(); + data.mode = mode; + } + finish(); + } + }); + + } + public void onItemSelected(AdapterView parent, View view, + int pos, long id) { + // An item was selected. You can retrieve the selected item using + // parent.getItemAtPosition(pos) + } + + public void onNothingSelected(AdapterView parent) { + // Another interface callback + } + +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java index 26a5379..9e5b238 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/ObjectsManager.java @@ -2,6 +2,7 @@ import android.content.Context; +import android.util.Log; import com.sierrawireless.avphone.model.AvPhoneObject; import com.sierrawireless.avphone.model.AvPhoneObjectData; @@ -18,8 +19,9 @@ public class ObjectsManager { public static String ACTIVE = "active"; public int current; public String currentName; + public int savedPosition = -1; - private ArrayList objects; + public ArrayList objects; public static ObjectsManager getInstance(){ @@ -61,9 +63,18 @@ public void init(MainActivity activity){ current = 0; saveOnPref(); } + if (savedPosition == -1) { + savedPosition = current; + } currentName = objects.get(current).name; } + public void removeSavedObject() { + objects.remove(savedPosition); + savedPosition = current; + saveOnPref(); + } + private void saveOnPref() { MyPreference pref = new MyPreference(mainActivyty.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)); // Save the list for later @@ -71,6 +82,16 @@ private void saveOnPref() { pref.putInt(ACTIVE, current); } + public void reload() { + + MyPreference pref = new MyPreference(mainActivyty.getSharedPreferences(SHARED_PREFS_FILE, Context.MODE_PRIVATE)); + + + objects = pref.getListObject(MODELS, AvPhoneObject.class); + current = pref.getInt(ACTIVE); + + } + public void execOnCurrent() { AvPhoneObject object; object = objects.get(current); @@ -80,10 +101,12 @@ public void execOnCurrent() { } public void changeCurrent(String name) { + Log.d(TAG, "changeCurrent: change axctive to " + name + " current before " + current); Integer indice = 0; for (AvPhoneObject object: objects) { if (object.name == name) { current = indice; + Log.d(TAG, "changeCurrent: current after " + current); saveOnPref(); return; } @@ -91,6 +114,25 @@ public void changeCurrent(String name) { } } + public void setSavedPosition(int position) { + savedPosition = position; + } + + public AvPhoneObject getSavecObject() { + return objects.get(savedPosition); + } + + public String getSavedObjectName() { + return objects.get(savedPosition).name; + } + + public AvPhoneObject getObjectByIndex(int position) { + if (position > objects.size()) { + return null; + } + return objects.get(position); + } + public AvPhoneObject getCurrentObject() { if (objects.isEmpty()) { return null; @@ -111,6 +153,11 @@ public String getCurrentObjectName() { return objects.get(current).name; } + public void save() { + saveOnPref(); + + } + diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java index 12d1b6b..9c62744 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/RunFragment.java @@ -4,10 +4,9 @@ import net.airvantage.utils.PreferenceUtils; import android.app.Activity; +import android.content.Intent; import android.content.IntentFilter; -import android.graphics.Color; import android.os.Bundle; -import android.support.v4.content.ContextCompat; import android.support.v4.content.LocalBroadcastManager; import android.support.v7.widget.SwitchCompat; import android.text.Html; @@ -23,6 +22,9 @@ import android.widget.TextView; import com.sierrawireless.avphone.adapter.RunListViewAdapter; +import com.sierrawireless.avphone.auth.AuthUtils; +import com.sierrawireless.avphone.auth.Authentication; +import com.sierrawireless.avphone.message.IMessageDisplayer; import com.sierrawireless.avphone.model.AvPhoneObject; import com.sierrawireless.avphone.model.AvPhoneObjectData; import com.sierrawireless.avphone.model.CustomDataLabels; @@ -30,13 +32,17 @@ import com.sierrawireless.avphone.service.MonitoringService; import com.sierrawireless.avphone.service.NewData; 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; import com.sierrawireless.avphone.tools.Constant; import java.util.ArrayList; import java.util.HashMap; -import java.util.List; public class RunFragment extends AvPhoneFragment implements MonitorServiceListener, CustomLabelsListener { + private static final String TAG = "RunFragment"; private static final String LOGTAG = RunFragment.class.getName(); @@ -96,6 +102,9 @@ protected void setCustomLabelsManager(CustomLabelsManager manager) { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { + Log.d(TAG, "onCreateView: " + this); + objectsManager = ObjectsManager.getInstance(); + objectsManager.changeCurrent(objectName); view = inflater.inflate(R.layout.fragment_run, container, false); viewUpdater = new DataViewUpdater(view, (MainActivity)getActivity()); @@ -114,8 +123,13 @@ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle sa SwitchCompat serviceSwitch = (SwitchCompat) view.findViewById(R.id.service_switch); serviceSwitch.setChecked(isServiceRunning); - if (!this.monitorServiceManager.isServiceStarted()) { - this.monitorServiceManager.startMonitoringService(); + if (!this.monitorServiceManager.isServiceStarted(objectName)) { + if (this.monitorServiceManager.oneServiceStarted()) { + //stop the service + this.monitorServiceManager.stopMonitoringService(); + } + //registerNewDevice(); + this.monitorServiceManager.startMonitoringService(objectName); } serviceSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() { @@ -199,6 +213,77 @@ public void onClick(View view) { return view; } + private boolean checkCredentials() { + + AvPhonePrefs prefs = PreferenceUtils.getAvPhonePrefs(getActivity()); + + if (!prefs.checkCredentials()) { + PreferenceUtils.showMissingPrefsDialog(getActivity()); + return false; + } + + return true; + + } + + private void registerNewDevice() { + 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); + + if (requestCode == AuthorizationActivity.REQUEST_AUTHORIZATION) { + 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 syncAvTask = taskFactory.syncAvTask(prefs.serverHost, token); + + + final SyncWithAvParams params = new SyncWithAvParams(); + + params.deviceId = DeviceInfo.getUniqueId(getActivity()); + params.imei = DeviceInfo.getIMEI(getActivity()); + params.deviceName = DeviceInfo.getDeviceName(); + params.iccid = DeviceInfo.getICCID(getActivity()); + params.mqttPassword = prefs.password; + params.customData = PreferenceUtils.getCustomDataLabels(getActivity()); + // params.current = ((MainActivity)getActivity()).current; + params.activity = ((MainActivity)getActivity()); + + syncAvTask.execute(params); + syncAvTask.addProgressListener(new SyncWithAvListener() { + @Override + public void onSynced(SyncWithAvResult result) { + syncAvTask.showResult(result, display, getActivity()); + + if (!result.isError()) { + syncListener.onSynced(result); + } + + } + }); + + + } + public void setLinkToSystem(String systemUid, String systemName) { if (view == null || getActivity() == null) { diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/AvPhoneObjectDataAdapter.java b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/AvPhoneObjectDataAdapter.java new file mode 100644 index 0000000..19bf726 --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/AvPhoneObjectDataAdapter.java @@ -0,0 +1,91 @@ +package com.sierrawireless.avphone.adapter; + +import android.app.Activity; +import android.text.Layout; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.TextView; + +import com.sierrawireless.avphone.R; + +import java.util.ArrayList; + + +/** + * Created by JDamiano on 26/01/2018. + */ + +public class AvPhoneObjectDataAdapter extends BaseAdapter { + public ArrayList list; + Activity activity; + TextView name; + int resource; + private static final String TAG = "AvPhoneObjectDataAdapte"; + + public AvPhoneObjectDataAdapter(Activity activity, int resource, ArrayList list){ + super(); + this.activity=activity; + this.list=list; + this.resource = resource; + } + + @Override + public int getCount() { + // TODO Auto-generated method stub + return list.size(); + } + + @Override + public Object getItem(int position) { + // TODO Auto-generated method stub + return list.get(position); + } + + @Override + public long getItemId(int position) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getViewTypeCount() { + // menu type count + return 2; + } + + @Override + public int getItemViewType(int position) { + // current menu type + if (position == list.size()-1) { + Log.d(TAG, "getItemViewType: position " + position); + return 1; + }else{ + return 0; + } + } + + + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // TODO Auto-generated method stub + + + LayoutInflater inflater=activity.getLayoutInflater(); + + if(convertView == null){ + + convertView=inflater.inflate(resource, null); + + name=(TextView) convertView.findViewById(android.R.id.text1); + } + + name.setText(list.get(position)); + + return convertView; + } + +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.java b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.java new file mode 100644 index 0000000..9b7276a --- /dev/null +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/adapter/ObjectAdapter.java @@ -0,0 +1,101 @@ +package com.sierrawireless.avphone.adapter; + +import android.app.Activity; +import android.graphics.Typeface; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.TextView; + +import com.sierrawireless.avphone.ObjectsManager; + +import java.util.ArrayList; + +/** + * Created by JDamiano on 26/01/2018. + */ + +public class ObjectAdapter extends BaseAdapter { + public ArrayList list; + Activity activity; + TextView name; + int resource; + private static final String TAG = "ObjectAdapter"; + + ObjectsManager objectsManager; + + public ObjectAdapter(Activity activity, int resource, ArrayList list){ + super(); + this.activity=activity; + this.list=list; + this.resource = resource; + objectsManager =ObjectsManager.getInstance(); + } + + @Override + public int getCount() { + // TODO Auto-generated method stub + return list.size(); + } + + @Override + public Object getItem(int position) { + // TODO Auto-generated method stub + Log.d(TAG, "getItem: position"+ position); + if (position == objectsManager.current) { + return list.get(position); + } + return list.get(position); + } + + @Override + public long getItemId(int position) { + // TODO Auto-generated method stub + return 0; + } + + @Override + public int getViewTypeCount() { + // menu type count + return 2; + } + + @Override + public int getItemViewType(int position) { + // current menu type + if (position == objectsManager.current) { + Log.d(TAG, "getItemViewType: position " + position); + return 1; + }else{ + return 0; + } + } + + + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // TODO Auto-generated method stub + + + LayoutInflater inflater=activity.getLayoutInflater(); + + if(convertView == null){ + + convertView=inflater.inflate(resource, null); + + name=(TextView) convertView.findViewById(android.R.id.text1); + } + + if (position == objectsManager.current) { + name.setTypeface(null, Typeface.BOLD); + }else{ + name.setTypeface(null, Typeface.NORMAL); + } + name.setText(list.get(position)); + + return convertView; + } +} diff --git a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java index a549418..f3b1e14 100644 --- a/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java +++ b/mainActivity/src/main/java/com/sierrawireless/avphone/model/AvPhoneApplication.java @@ -1,5 +1,9 @@ package com.sierrawireless.avphone.model; +import android.util.Log; + +import com.sierrawireless.avphone.ObjectsManager; + import java.util.ArrayList; import java.util.Arrays; import java.util.List; @@ -16,8 +20,9 @@ public class AvPhoneApplication { + private static final String TAG = "AvPhoneApplication"; public static final String ALERT_RULE_NAME = "AV Phone raised an alert"; - private static String type = "Printer"; + static ObjectsManager objectsManager; public static Application createApplication(final String userName) { Application application = new Application(); @@ -36,6 +41,7 @@ public static List createProtocols() { public static List createApplicationData(ArrayList customData) { + Log.d(TAG, "createApplicationData: ************applicationData called"); // // // @@ -68,6 +74,7 @@ public static List createApplicationData(ArrayList createApplicationData(ArrayList createApplicationData(ArrayList getApplications(String type) throws IOException, AirVantageException { URL url = new URL(buildEndpoint("/applications") + "&type=" + type + "&fields=uid,name,revision,type,category"); InputStream in = this.get(url); 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..21f2eb4 --- /dev/null +++ b/mainActivity/src/main/res/layout/activity_object_configure.xml @@ -0,0 +1,76 @@ + + + +