diff --git a/app/build.gradle b/app/build.gradle index ff8369c0a..f2557a19c 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -5,13 +5,45 @@ android { compileSdkVersion 23 buildToolsVersion "23.0.3" - //noinspection GroovyAssignabilityCheck - defaultConfig { - minSdkVersion 16 - targetSdkVersion 23 - versionCode 98 - versionName '0.1.252' - multiDexEnabled true + def versionPropsFile = file('version.properties') + + if (versionPropsFile.canRead()) { + def Properties versionProps = new Properties() + + versionProps.load(new FileInputStream(versionPropsFile)) + def value = 0 + def runTasks = gradle.startParameter.taskNames + println "****************************" + println "runTasks: ${gradle.startParameter.taskNames}" + + if ('assemble' in runTasks || 'assembleRelease' in runTasks || 'aR' in runTasks || ':app:compilePaidReleaseSources' in runTasks) { + value = 1; + + println "Build Version: +1" + } + println "****************************" + + def versionMajor = 0 + def versionMinor = 1 + def versionPatch = versionProps['VERSION_PATCH'].toInteger() + value + def versionBuild = versionProps['VERSION_BUILD'].toInteger() + 1 + def version_Code = versionProps['VERSION_CODE'].toInteger() + value + + versionProps['VERSION_PATCH'] = versionPatch.toString() + versionProps['VERSION_BUILD'] = versionBuild.toString() + versionProps['VERSION_CODE'] = version_Code.toString() + + versionProps.store(versionPropsFile.newWriter(), null) + + defaultConfig { + versionCode version_Code + versionName "${versionMajor}.${versionMinor}.${versionPatch} (${versionBuild})" + minSdkVersion 16 + targetSdkVersion 23 + multiDexEnabled true + } + } else { + throw new GradleException("Could not read version.properties!") } //noinspection GroovyAssignabilityCheck @@ -76,48 +108,69 @@ dependencies { compile fileTree(include: ['*.jar'], dir: 'libs') compile project(':libs:MemorizingTrustManager') - compile('com.github.afollestad.material-dialogs:core:0.8.5.7@aar') { + compile('com.github.afollestad.material-dialogs:core:0.8.5.8@aar') { transitive = true } - compile('com.github.afollestad.material-dialogs:commons:0.8.5.7@aar') { + compile('com.github.afollestad.material-dialogs:commons:0.8.5.8@aar') { transitive = true } paidWearApp project(path: ':wear', configuration: 'paidRelease') - compile 'com.android.support:support-v4:23.2.1' - compile 'com.android.support:appcompat-v7:23.2.1' - compile 'com.android.support:support-v13:23.2.1' - compile 'com.android.support:recyclerview-v7:23.2.1' - compile 'com.android.support:cardview-v7:23.2.1' + compile 'com.android.support:support-v4:23.4.0' + compile 'com.android.support:appcompat-v7:23.4.0' + compile 'com.android.support:support-v13:23.4.0' + compile 'com.android.support:recyclerview-v7:23.4.0' + compile 'com.android.support:cardview-v7:23.4.0' + compile 'com.android.support:design:23.4.0' + compile 'com.android.support:multidex:1.0.1' compile 'com.google.code.gson:gson:2.4' + compile 'com.google.android.gms:play-services-analytics:8.4.0' compile 'com.google.android.gms:play-services-wearable:8.4.0' compile 'com.google.android.gms:play-services-maps:8.4.0' compile 'com.google.android.gms:play-services-gcm:8.4.0' compile 'com.google.android.gms:play-services-location:8.4.0' + compile 'com.mcxiaoke.volley:library:1.0.15' - compile 'com.android.support:design:23.2.1' compile 'fr.avianey.com.viewpagerindicator:library:2.4.1@aar' compile 'com.marvinlabs:android-floatinglabel-widgets:1.6.1@aar' compile 'com.splunk.mint:mint:5.0.0' - compile 'com.larswerkman:lobsterpicker:1.0.0' + compile 'com.larswerkman:lobsterpicker:1.0.1' compile 'com.github.lecho:hellocharts-library:1.5.8@aar' - compile 'com.github.dexafree:MaterialList:v3.2.2' - compile 'com.github.hotchemi:android-rate:0.5.6' compile 'com.squareup.picasso:picasso:2.5.2' compile 'com.github.fenjuly:SpinnerLoader:fd5b8ab578' compile 'com.nhaarman.listviewanimations:lib-core:3.1.0@aar' compile 'eu.inloop:easygcm:1.6.1@aar' compile 'me.dm7.barcodescanner:zxing:1.8.4' - compile 'com.github.jd-alexander:LikeButton:0.1.8' - compile 'jp.wasabeef:recyclerview-animators:2.2.1' + compile 'com.github.jd-alexander:LikeButton:0.2.0' + compile 'jp.wasabeef:recyclerview-animators:2.2.3' + compile 'com.mikepenz:google-material-typeface:2.2.0.1.original@aar' + compile('com.mikepenz:materialdrawer:5.2.2@aar') { + transitive = true + } + + compile 'com.github.gabrielemariotti.changeloglib:changelog:2.1.0' + compile 'com.github.zagum:SpeechRecognitionView:1.0.2' compile project(path: ':SeekArc_library') compile project(path: ':materialIntro_library') } -apply plugin: 'com.google.gms.google-services' \ No newline at end of file +apply plugin: 'com.google.gms.google-services' + +buildscript { + repositories { + mavenCentral() + } + + dependencies { + classpath 'com.jakewharton.hugo:hugo-plugin:1.2.1' + } +} + +apply plugin: 'com.android.application' +apply plugin: 'com.jakewharton.hugo' \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 5746a2fb9..979eeb5c0 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -29,6 +29,7 @@ + + - - + + + - + + + + + + + @@ -86,15 +98,6 @@ android:name="android.appwidget.provider" android:resource="@xml/appwidgetprovider" /> - - - - - - - - + + + + + + + + + + - + @@ -207,6 +221,12 @@ + + data = null; public ArrayList filteredData = null; - + private boolean showAsList = false; + private Domoticz domoticz; + private Context context; private switchesClickListener listener; private int previousDimmerValue; private SharedPrefUtil mSharedPrefs; @@ -315,13 +312,8 @@ private void setSwitchRowData(DevicesInfo mDeviceInfo, setButtons(holder, Buttons.BLINDS); setBlindsRowData(mDeviceInfo, holder); } else { - if (mSharedPrefs.showSwitchesAsButtons()) { - setButtons(holder, Buttons.BUTTONS); - setOnOffButtonRowData(mDeviceInfo, holder); - } else { - setButtons(holder, Buttons.BUTTONS); - setOnOffSwitchRowData(mDeviceInfo, holder); - } + setButtons(holder, Buttons.BUTTONS); + setOnOffButtonRowData(mDeviceInfo, holder); } break; @@ -615,7 +607,7 @@ private void setOnOffSwitchRowData(final DevicesInfo mDeviceInfo, else holder.onOffSwitch.setId(mDeviceInfo.getIdx()); - holder.onOffSwitch.setOnCheckedChangeListener (null); + holder.onOffSwitch.setOnCheckedChangeListener(null); holder.onOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -1032,11 +1024,11 @@ private void setSelectorRowData(final DevicesInfo mDeviceInfo, holder.switch_battery_level.setText(text); } - int loadLevel = (mDeviceInfo.getLevel()-1) / 10; + int loadLevel = (mDeviceInfo.getLevel() - 1) / 10; final String[] levelNames = mDeviceInfo.getLevelNames(); String statusText = context.getString(R.string.unknown); - if (levelNames.length > loadLevel) + if (levelNames != null && levelNames.length > loadLevel) statusText = levelNames[loadLevel]; holder.switch_dimmer_level.setId(mDeviceInfo.getIdx() + ID_TEXTVIEW); @@ -1045,7 +1037,7 @@ private void setSelectorRowData(final DevicesInfo mDeviceInfo, if (holder.dimmerOnOffSwitch != null) { holder.dimmerOnOffSwitch.setId(mDeviceInfo.getIdx() + ID_SWITCH); - holder.dimmerOnOffSwitch.setOnCheckedChangeListener (null); + holder.dimmerOnOffSwitch.setOnCheckedChangeListener(null); holder.dimmerOnOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.dimmerOnOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -1106,7 +1098,9 @@ public void onClick(View v) { holder.dimmer.incrementProgressBy(1); holder.dimmer.setProgress(loadLevel); - holder.dimmer.setMax(levelNames.length - 1); + + if (levelNames != null && levelNames.length > 0) + holder.dimmer.setMax(levelNames.length - 1); holder.dimmer.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { @@ -1201,7 +1195,7 @@ private void setDimmerRowData(final DevicesInfo mDeviceInfo, holder.dimmerOnOffSwitch.setId(mDeviceInfo.getIdx() + ID_SWITCH); - holder.dimmerOnOffSwitch.setOnCheckedChangeListener (null); + holder.dimmerOnOffSwitch.setOnCheckedChangeListener(null); holder.dimmerOnOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.dimmerOnOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -1250,14 +1244,18 @@ public void onStartTrackingTouch(SeekBar seekBar) { @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress = seekBar.getProgress(); - Switch dimmerOnOffSwitch = (Switch) seekBar.getRootView() - .findViewById(mDeviceInfo.getIdx() + ID_SWITCH); - - if (progress == 0 && dimmerOnOffSwitch.isChecked()) { - dimmerOnOffSwitch.setChecked(false); - seekBar.setProgress(previousDimmerValue); - } else if (progress > 0 && !dimmerOnOffSwitch.isChecked()) - dimmerOnOffSwitch.setChecked(true); + Switch dimmerOnOffSwitch = null; + try { + dimmerOnOffSwitch = (Switch) seekBar.getRootView() + .findViewById(mDeviceInfo.getIdx() + ID_SWITCH); + if (progress == 0 && dimmerOnOffSwitch.isChecked()) { + dimmerOnOffSwitch.setChecked(false); + seekBar.setProgress(previousDimmerValue); + } else if (progress > 0 && !dimmerOnOffSwitch.isChecked()) { + dimmerOnOffSwitch.setChecked(true); + } + } catch (Exception ex) {/*else we don't use a switch, but buttons */} + handleDimmerChange(mDeviceInfo.getIdx(), progress + 1, false); mDeviceInfo.setLevel(progress); } diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/NavigationAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/NavigationAdapter.java deleted file mode 100644 index f40990ef6..000000000 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/NavigationAdapter.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * Copyright (C) 2015 Domoticz - * - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - * - */ - -package nl.hnogames.domoticz.Adapters; - -import android.content.Context; -import android.os.Build; -import android.support.v7.widget.RecyclerView; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.ImageView; -import android.widget.TextView; - -import nl.hnogames.domoticz.R; -import nl.hnogames.domoticz.Utils.SharedPrefUtil; - -public class NavigationAdapter extends RecyclerView.Adapter { - - private static final int TYPE_HEADER = 0; // Declaring Variable to Understand which View is being worked on - // IF the view under inflation and population is header or Item - private static final int TYPE_ITEM = 1; - private static ClickListener mClickListener; - private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java - private int mIcons[]; // Int Array to store the passed icons resource value from MainActivity.java - private String name; //String Resource for header View Name - private int profile; //int Resource for header view profile picture - private String email; //String Resource for header view email - private Context mContext; - private SharedPrefUtil mSharedPrefs; - - // Creating a ViewHolder which extends the RecyclerView View Holder - // ViewHolder are used to to store the inflated views in order to recycle them - - public NavigationAdapter(String Titles[], int Icons[], String Name, String Email, int Profile, Context context) { // MyAdapter Constructor with titles and icons parameter - // titles, icons, name, email, profile pic are passed from the main activity as we - mNavTitles = Titles; //have seen earlier - mIcons = Icons; - name = Name; - email = Email; - profile = Profile; //here we assign those passed values to the values we declared here - mContext = context; - mSharedPrefs = new SharedPrefUtil(context); - } - - public boolean updateData(String Titles[], int Icons[]) { - mNavTitles = Titles; - mIcons = Icons; - this.notifyDataSetChanged(); - return true; - } - - - @Override - public NavigationAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { - if (viewType == TYPE_ITEM) { - View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.nav_item_row, parent, false); //Inflating the layout - if (mSharedPrefs.darkThemeEnabled()) { - (v.findViewById(R.id.row_global_wrapper)).setBackgroundColor(mContext.getResources().getColor(R.color.background_dark)); - } - return new ViewHolder(v, viewType); // Returning the created object - } else if (viewType == TYPE_HEADER) { - View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.nav_item_header, parent, false); //Inflating the layout - return new ViewHolder(v, viewType); - } - return null; - - } - - - //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is - //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml - // if the viewType is TYPE_HEADER - // and pass it to the view holder - - //Next we override a method which is called when the item in a row is needed to be displayed, here the int position - // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us - // which view type is being created 1 for item row - @Override - public void onBindViewHolder(ViewHolder holder, int position) { - if (holder.Holderid == 1) { // as the list view is going to be called after the header view so we decrement the - // position by 1 and pass it to the holder while setting the text and image - holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles - holder.imageView.setImageResource(mIcons[position - 1]);// Settimg the image with array of our icons+ - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (mSharedPrefs.darkThemeEnabled()) - holder.imageView.setColorFilter(mContext.getColor(R.color.white)); - else - holder.imageView.setColorFilter(mContext.getColor(R.color.material_indigo_600)); - } - } else { - holder.profile.setImageResource(profile); // Similarly we set the resources for header view - holder.Name.setText(name); - holder.email.setText(email); - } - } - - // This method returns the number of items present in the list - @Override - public int getItemCount() { - if (mNavTitles != null) - return mNavTitles.length + 1; // the number of items in the list will be +1 the titles including the header view. - else - return 0; - } - - // Witht the following method we check what type of view is being passed - @Override - public int getItemViewType(int position) { - if (isPositionHeader(position)) - return TYPE_HEADER; - - return TYPE_ITEM; - } - - private boolean isPositionHeader(int position) { - return position == 0; - } - - public void onClickListener(ClickListener clickListener) { - mClickListener = clickListener; - } - - public interface ClickListener { - void onClick(View child, int position); - } - - public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { - int Holderid; - - TextView textView; - ImageView imageView; - ImageView profile; - TextView Name; - TextView email; - - public ViewHolder(View itemView, int ViewType) { // Creating ViewHolder Constructor with View and viewType As a parameter - super(itemView); - - if (ViewType == TYPE_ITEM) { - textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml - imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml - Holderid = 1; - itemView.setOnClickListener(this); - } else { - Name = (TextView) itemView.findViewById(R.id.name); // Creating Text View object from header.xml for name - email = (TextView) itemView.findViewById(R.id.email); // Creating Text View object from header.xml for email - profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic - Holderid = 0; // Setting holder id = 0 as the object being populated are of type header view - } - } - - @Override - public void onClick(View v) { - if (mClickListener != null) { - mClickListener.onClick(v, this.getLayoutPosition()); - } - } - } -} diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/SceneAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/SceneAdapter.java index ae0f4ff12..4e2d6c016 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/SceneAdapter.java +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/SceneAdapter.java @@ -302,44 +302,6 @@ public int getItemCount() { return filteredData.size(); } - public static class DataObjectHolder extends RecyclerView.ViewHolder { - TextView switch_name, signal_level, switch_battery_level; - Boolean isProtected; - ImageView iconRow; - LikeButton likeButton; - LinearLayout extraPanel; - Button buttonOn, buttonLog, buttonTimer, buttonNotifications, buttonOff; - - public DataObjectHolder(View itemView) { - super(itemView); - - buttonOn = (Button) itemView.findViewById(R.id.on_button); - signal_level = (TextView) itemView.findViewById(R.id.switch_signal_level); - iconRow = (ImageView) itemView.findViewById(R.id.rowIcon); - switch_name = (TextView) itemView.findViewById(R.id.switch_name); - switch_battery_level = (TextView) itemView.findViewById(R.id.switch_battery_level); - - buttonLog = (Button) itemView.findViewById(R.id.log_button); - buttonTimer = (Button) itemView.findViewById(R.id.timer_button); - buttonNotifications = (Button) itemView.findViewById(R.id.notifications_button); - likeButton = (LikeButton) itemView.findViewById(R.id.fav_button); - - if (buttonTimer != null) - buttonTimer.setVisibility(View.GONE); - if (buttonNotifications != null) - buttonNotifications.setVisibility(View.GONE); - - likeButton = (LikeButton) itemView.findViewById(R.id.fav_button); - iconRow = (ImageView) itemView.findViewById(R.id.rowIcon); - buttonLog = (Button) itemView.findViewById(R.id.log_button); - buttonOff = (Button) itemView.findViewById(R.id.off_button); - - extraPanel = (LinearLayout) itemView.findViewById(R.id.extra_panel); - if (extraPanel != null) - extraPanel.setVisibility(View.GONE); - } - } - public void setButtons(DataObjectHolder holder, int button) { if (holder.buttonLog != null) { holder.buttonLog.setVisibility(View.GONE); @@ -367,11 +329,6 @@ public void setButtons(DataObjectHolder holder, int button) { } } - interface Buttons { - int SCENE = 0; - int GROUP = 1; - } - private void handleLikeButtonClick(int idx, boolean checked) { listener.onLikeButtonClick(idx, checked); } @@ -384,6 +341,49 @@ public void handleClick(int idx, boolean action) { listener.onSceneClick(idx, action); } + interface Buttons { + int SCENE = 0; + int GROUP = 1; + } + + public static class DataObjectHolder extends RecyclerView.ViewHolder { + TextView switch_name, signal_level, switch_battery_level; + Boolean isProtected; + ImageView iconRow; + LikeButton likeButton; + LinearLayout extraPanel; + Button buttonOn, buttonLog, buttonTimer, buttonNotifications, buttonOff; + + public DataObjectHolder(View itemView) { + super(itemView); + + buttonOn = (Button) itemView.findViewById(R.id.on_button); + signal_level = (TextView) itemView.findViewById(R.id.switch_signal_level); + iconRow = (ImageView) itemView.findViewById(R.id.rowIcon); + switch_name = (TextView) itemView.findViewById(R.id.switch_name); + switch_battery_level = (TextView) itemView.findViewById(R.id.switch_battery_level); + + buttonLog = (Button) itemView.findViewById(R.id.log_button); + buttonTimer = (Button) itemView.findViewById(R.id.timer_button); + buttonNotifications = (Button) itemView.findViewById(R.id.notifications_button); + likeButton = (LikeButton) itemView.findViewById(R.id.fav_button); + + if (buttonTimer != null) + buttonTimer.setVisibility(View.GONE); + if (buttonNotifications != null) + buttonNotifications.setVisibility(View.GONE); + + likeButton = (LikeButton) itemView.findViewById(R.id.fav_button); + iconRow = (ImageView) itemView.findViewById(R.id.rowIcon); + buttonLog = (Button) itemView.findViewById(R.id.log_button); + buttonOff = (Button) itemView.findViewById(R.id.off_button); + + extraPanel = (LinearLayout) itemView.findViewById(R.id.extra_panel); + if (extraPanel != null) + extraPanel.setVisibility(View.GONE); + } + } + private class ItemFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/SpeechAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/SpeechAdapter.java new file mode 100644 index 000000000..75addb30c --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/SpeechAdapter.java @@ -0,0 +1,162 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Adapters; + +import android.annotation.SuppressLint; +import android.app.Activity; +import android.content.Context; +import android.support.v4.content.ContextCompat; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.TextView; + +import java.util.ArrayList; + +import nl.hnogames.domoticz.Containers.SpeechInfo; +import nl.hnogames.domoticz.Interfaces.SpeechClickListener; +import nl.hnogames.domoticz.R; +import nl.hnogames.domoticz.Utils.SharedPrefUtil; +import nl.hnogames.domoticz.Utils.UsefulBits; + +public class SpeechAdapter extends BaseAdapter { + + @SuppressWarnings("unused") + private static final String TAG = SpeechAdapter.class.getSimpleName(); + public ArrayList data = null; + private Context context; + private SpeechClickListener listener; + + private SharedPrefUtil mSharedPrefs; + + public SpeechAdapter(Context context, + ArrayList data, + SpeechClickListener l) { + super(); + + mSharedPrefs = new SharedPrefUtil(context); + this.context = context; + this.data = data; + this.listener = l; + } + + @Override + public int getCount() { + if (data == null) + return 0; + + return data.size(); + } + + @Override + public Object getItem(int i) { + return data.get(i); + } + + @Override + public long getItemId(int i) { + return 0; + } + + + @SuppressLint({"ViewHolder", "SetTextI18n"}) + @Override + public View getView(int position, View convertView, ViewGroup parent) { + final ViewHolder holder; + int layoutResourceId; + + final SpeechInfo mSpeechInfo = data.get(position); + holder = new ViewHolder(); + + layoutResourceId = R.layout.speech_row; + LayoutInflater inflater = ((Activity) context).getLayoutInflater(); + convertView = inflater.inflate(layoutResourceId, parent, false); + + if (mSharedPrefs.darkThemeEnabled()) { + (convertView.findViewById(R.id.row_wrapper)).setBackground(ContextCompat.getDrawable(context, R.drawable.bordershadowdark)); + (convertView.findViewById(R.id.row_global_wrapper)).setBackgroundColor(ContextCompat.getColor(context, R.color.background_dark)); + + if ((convertView.findViewById(R.id.remove_button)) != null) + (convertView.findViewById(R.id.remove_button)).setBackground(ContextCompat.getDrawable(context, R.drawable.button_status_dark)); + } + + holder.enable = (CheckBox) convertView.findViewById(R.id.enableSpeech); + holder.Speech_name = (TextView) convertView.findViewById(R.id.speech_name); + holder.Speech_tag_id = (TextView) convertView.findViewById(R.id.speech_tag_id); + holder.Speech_switch_idx = (TextView) convertView.findViewById(R.id.speech_switchidx); + holder.remove = (Button) convertView.findViewById(R.id.remove_button); + + holder.Speech_name.setText(mSpeechInfo.getName()); + if (!UsefulBits.isEmpty(mSpeechInfo.getSwitchName())) { + holder.Speech_tag_id.setText(context.getString(R.string.connectedSwitch) + ": " + mSpeechInfo.getSwitchName()); + } else if (mSpeechInfo.getSwitchIdx() > 0) { + holder.Speech_tag_id.setText(context.getString(R.string.connectedSwitch) + ": " + mSpeechInfo.getSwitchIdx()); + } else { + holder.Speech_tag_id.setText(context.getString(R.string.connectedSwitch) + + ": " + context.getString(R.string.not_available)); + } + + holder.Speech_switch_idx.setText("Commando's: \r\n" + "'" + mSpeechInfo.getName() + "' " + "\r\n'" + mSpeechInfo.getName() + " " + context.getString(R.string.button_state_on).toLowerCase() + "'\r\n" + + "'" + mSpeechInfo.getName() + " " + context.getString(R.string.button_state_off).toLowerCase() + "'"); + + holder.remove.setId(position); + holder.remove.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(final View v) { + handleRemoveButtonClick(data.get(v.getId())); + } + }); + + holder.enable.setId(position); + holder.enable.setChecked(mSpeechInfo.isEnabled()); + holder.enable.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + handleEnableChanged(data.get(buttonView.getId()), isChecked); + } + }); + + convertView.setTag(holder); + return convertView; + } + + private void handleRemoveButtonClick(SpeechInfo Speech) { + listener.onRemoveClick(Speech); + } + + private boolean handleEnableChanged(SpeechInfo Speech, boolean enabled) { + return listener.onEnableClick(Speech, enabled); + } + + static class ViewHolder { + TextView Speech_name; + TextView Speech_tag_id; + TextView Speech_switch_idx; + CheckBox enable; + Button remove; + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/SwitchesAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/SwitchesAdapter.java index 03ae6321d..3f6412e02 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/SwitchesAdapter.java +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/SwitchesAdapter.java @@ -70,11 +70,10 @@ public class SwitchesAdapter extends RecyclerView.Adapter data = null; public ArrayList filteredData = null; + private Domoticz domoticz; + private Context context; private switchesClickListener listener; private int layoutResourceId; private int previousDimmerValue; @@ -341,13 +340,8 @@ private void setSwitchRowData(DevicesInfo mDeviceInfo, setButtons(holder, Buttons.BLINDS); setBlindsRowData(mDeviceInfo, holder); } else { - if (mSharedPrefs.showSwitchesAsButtons()) { - setButtons(holder, Buttons.BUTTONS); - setOnOffButtonRowData(mDeviceInfo, holder); - } else { - setButtons(holder, Buttons.BUTTONS); - setOnOffSwitchRowData(mDeviceInfo, holder); - } + setButtons(holder, Buttons.BUTTONS); + setOnOffButtonRowData(mDeviceInfo, holder); } break; @@ -636,7 +630,7 @@ private void setOnOffSwitchRowData(final DevicesInfo mDeviceInfo, else holder.onOffSwitch.setId(mDeviceInfo.getIdx()); - holder.onOffSwitch.setOnCheckedChangeListener (null); + holder.onOffSwitch.setOnCheckedChangeListener(null); holder.onOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -1053,11 +1047,11 @@ private void setSelectorRowData(final DevicesInfo mDeviceInfo, holder.switch_battery_level.setText(text); } - int loadLevel = (mDeviceInfo.getLevel()-1) / 10; + int loadLevel = (mDeviceInfo.getLevel() - 1) / 10; final String[] levelNames = mDeviceInfo.getLevelNames(); String statusText = context.getString(R.string.unknown); - if (levelNames.length > loadLevel) + if (levelNames != null && levelNames.length > loadLevel) statusText = levelNames[loadLevel]; holder.switch_dimmer_level.setId(mDeviceInfo.getIdx() + ID_TEXTVIEW); @@ -1065,7 +1059,7 @@ private void setSelectorRowData(final DevicesInfo mDeviceInfo, if (holder.dimmerOnOffSwitch != null) { holder.dimmerOnOffSwitch.setId(mDeviceInfo.getIdx() + ID_SWITCH); - holder.dimmerOnOffSwitch.setOnCheckedChangeListener (null); + holder.dimmerOnOffSwitch.setOnCheckedChangeListener(null); holder.dimmerOnOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.dimmerOnOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -1127,7 +1121,8 @@ public void onClick(View v) { holder.dimmer.incrementProgressBy(1); holder.dimmer.setProgress(loadLevel); - holder.dimmer.setMax(levelNames.length - 1); + if (levelNames != null && levelNames.length > 0) + holder.dimmer.setMax(levelNames.length - 1); holder.dimmer.setOnClickListener(new View.OnClickListener() { @Override @@ -1223,7 +1218,7 @@ private void setDimmerRowData(final DevicesInfo mDeviceInfo, holder.dimmerOnOffSwitch.setId(mDeviceInfo.getIdx() + ID_SWITCH); - holder.dimmerOnOffSwitch.setOnCheckedChangeListener (null); + holder.dimmerOnOffSwitch.setOnCheckedChangeListener(null); holder.dimmerOnOffSwitch.setChecked(mDeviceInfo.getStatusBoolean()); holder.dimmerOnOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override @@ -1272,14 +1267,18 @@ public void onStartTrackingTouch(SeekBar seekBar) { @Override public void onStopTrackingTouch(SeekBar seekBar) { int progress = seekBar.getProgress(); - Switch dimmerOnOffSwitch = (Switch) seekBar.getRootView() - .findViewById(mDeviceInfo.getIdx() + ID_SWITCH); - - if (progress == 0 && dimmerOnOffSwitch.isChecked()) { - dimmerOnOffSwitch.setChecked(false); - seekBar.setProgress(previousDimmerValue); - } else if (progress > 0 && !dimmerOnOffSwitch.isChecked()) - dimmerOnOffSwitch.setChecked(true); + Switch dimmerOnOffSwitch = null; + try { + dimmerOnOffSwitch = (Switch) seekBar.getRootView() + .findViewById(mDeviceInfo.getIdx() + ID_SWITCH); + if (progress == 0 && dimmerOnOffSwitch.isChecked()) { + dimmerOnOffSwitch.setChecked(false); + seekBar.setProgress(previousDimmerValue); + } else if (progress > 0 && !dimmerOnOffSwitch.isChecked()) { + dimmerOnOffSwitch.setChecked(true); + } + } catch (Exception ex) {/*else we don't use a switch, but buttons */} + handleDimmerChange(mDeviceInfo.getIdx(), progress + 1, false); mDeviceInfo.setLevel(progress); } @@ -1813,6 +1812,19 @@ public void setButtons(DataObjectHolder holder, int button) { } } + @Override + public int getItemCount() { + return filteredData.size(); + } + + private void handleTimerButtonClick(int idx) { + listener.onTimerButtonClick(idx); + } + + private void handleNotificationButtonClick(int idx) { + listener.onNotificationButtonClick(idx); + } + interface Buttons { int NOTHING = 0; int SWITCH = 1; @@ -1830,11 +1842,6 @@ interface Buttons { int SELECTOR_BUTTONS = 13; } - @Override - public int getItemCount() { - return filteredData.size(); - } - public static class DataObjectHolder extends RecyclerView.ViewHolder { TextView switch_name, signal_level, switch_status, switch_battery_level, switch_dimmer_level; @@ -1881,14 +1888,6 @@ public DataObjectHolder(View itemView) { } } - private void handleTimerButtonClick(int idx) { - listener.onTimerButtonClick(idx); - } - - private void handleNotificationButtonClick(int idx) { - listener.onNotificationButtonClick(idx); - } - /** * Item filter */ diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/TemperatureAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/TemperatureAdapter.java index 255035fde..1547838dc 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/TemperatureAdapter.java +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/TemperatureAdapter.java @@ -274,6 +274,10 @@ public int getItemCount() { return filteredData.size(); } + private void handleLikeButtonClick(int idx, boolean checked) { + listener.onLikeButtonClick(idx, checked); + } + public static class DataObjectHolder extends RecyclerView.ViewHolder { TextView name; TextView data; @@ -311,10 +315,6 @@ public DataObjectHolder(View itemView) { } } - private void handleLikeButtonClick(int idx, boolean checked) { - listener.onLikeButtonClick(idx, checked); - } - private class ItemFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/UtilityAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/UtilityAdapter.java index ed6bce0da..e3548fdb3 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/UtilityAdapter.java +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/UtilityAdapter.java @@ -400,6 +400,10 @@ public void setButtons(DataObjectHolder holder, int button) { } } + private void handleLikeButtonClick(int idx, boolean checked) { + listener.onLikeButtonClick(idx, checked); + } + interface Buttons { int DEFAULT = 0; int TEXT = 1; @@ -445,10 +449,6 @@ public DataObjectHolder(View itemView) { } } - private void handleLikeButtonClick(int idx, boolean checked) { - listener.onLikeButtonClick(idx, checked); - } - private class ItemFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/WeatherAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/WeatherAdapter.java index 75c384137..baa316ba5 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/WeatherAdapter.java +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/WeatherAdapter.java @@ -259,6 +259,10 @@ public int getItemCount() { return filteredData.size(); } + private void handleLikeButtonClick(int idx, boolean checked) { + listener.onLikeButtonClick(idx, checked); + } + public static class DataObjectHolder extends RecyclerView.ViewHolder { TextView name; TextView data; @@ -291,10 +295,6 @@ public DataObjectHolder(View itemView) { } } - private void handleLikeButtonClick(int idx, boolean checked) { - listener.onLikeButtonClick(idx, checked); - } - private class ItemFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { diff --git a/app/src/main/java/nl/hnogames/domoticz/Adapters/WidgetsAdapter.java b/app/src/main/java/nl/hnogames/domoticz/Adapters/WidgetsAdapter.java index 5fe1a4942..f1c02ac49 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Adapters/WidgetsAdapter.java +++ b/app/src/main/java/nl/hnogames/domoticz/Adapters/WidgetsAdapter.java @@ -53,6 +53,9 @@ public class WidgetsAdapter extends BaseAdapter implements Filterable { private ItemFilter mFilter = new ItemFilter(); private SharedPrefUtil mSharedPrefs; + private final int iVoiceAction = -55; + private final int iQRCodeAction = -66; + public WidgetsAdapter(Context context, Domoticz mDomoticz, ArrayList data) { @@ -68,6 +71,7 @@ public int compare(DevicesInfo left, DevicesInfo right) { return left.getName().compareTo(right.getName()); } }); + this.filteredData = data; this.data = data; } @@ -101,7 +105,6 @@ public View getView(int position, View convertView, ViewGroup parent) { convertView.setTag(holder); if (mSharedPrefs.darkThemeEnabled()) { - //(convertView.findViewById(R.id.row_wrapper)).setBackground(ContextCompat.getDrawable(context, R.drawable.bordershadowdark)); (convertView.findViewById(R.id.row_global_wrapper)).setBackgroundColor(context.getResources().getColor(R.color.background_dark)); } @@ -129,30 +132,40 @@ private void setDefaultRowData(DevicesInfo mDeviceInfo, if (holder.switch_name != null) holder.switch_name.setText(mDeviceInfo.getName()); - String text = context.getString(R.string.last_update) + ": " + - String.valueOf(mDeviceInfo.getLastUpdate().substring(mDeviceInfo.getLastUpdate().indexOf(" ") + 1)); - if (holder.signal_level != null) - holder.signal_level.setText(text); - - text = context.getString(R.string.data) + ": " + - String.valueOf(mDeviceInfo.getData()); - if (holder.switch_battery_level != null) - holder.switch_battery_level.setText(text); - - if (mDeviceInfo.getUsage() != null && mDeviceInfo.getUsage().length() > 0) - holder.switch_battery_level.setText(context.getString(R.string.usage) + ": " + mDeviceInfo.getUsage()); - if (mDeviceInfo.getCounterToday() != null && mDeviceInfo.getCounterToday().length() > 0) - holder.switch_battery_level.append(" " + context.getString(R.string.today) + ": " + mDeviceInfo.getCounterToday()); - if (mDeviceInfo.getCounter() != null && mDeviceInfo.getCounter().length() > 0 && - !mDeviceInfo.getCounter().equals(mDeviceInfo.getData())) - holder.switch_battery_level.append(" " + context.getString(R.string.total) + ": " + mDeviceInfo.getCounter()); - - Picasso.with(context).load(domoticz.getDrawableIcon(mDeviceInfo.getTypeImg(), - mDeviceInfo.getType(), - mDeviceInfo.getSubType(), - mDeviceInfo.getStatusBoolean(), - mDeviceInfo.getUseCustomImage(), - mDeviceInfo.getImage())).into(holder.iconRow); + try { + String text = context.getString(R.string.last_update) + ": " + + String.valueOf(mDeviceInfo.getLastUpdate().substring(mDeviceInfo.getLastUpdate().indexOf(" ") + 1)); + if (holder.signal_level != null) + holder.signal_level.setText(text); + text = context.getString(R.string.data) + ": " + + String.valueOf(mDeviceInfo.getData()); + if (holder.switch_battery_level != null) + holder.switch_battery_level.setText(text); + if (mDeviceInfo.getUsage() != null && mDeviceInfo.getUsage().length() > 0) + holder.switch_battery_level.setText(context.getString(R.string.usage) + ": " + mDeviceInfo.getUsage()); + if (mDeviceInfo.getCounterToday() != null && mDeviceInfo.getCounterToday().length() > 0) + holder.switch_battery_level.append(" " + context.getString(R.string.today) + ": " + mDeviceInfo.getCounterToday()); + if (mDeviceInfo.getCounter() != null && mDeviceInfo.getCounter().length() > 0 && + !mDeviceInfo.getCounter().equals(mDeviceInfo.getData())) + holder.switch_battery_level.append(" " + context.getString(R.string.total) + ": " + mDeviceInfo.getCounter()); + } catch (Exception ex) { + holder.switch_battery_level.setText(""); + holder.switch_battery_level.setVisibility(View.GONE); + } + + if (mDeviceInfo.getIdx() == iVoiceAction) { + Picasso.with(context).load(R.drawable.mic).into(holder.iconRow); + } + else if (mDeviceInfo.getIdx() == iQRCodeAction) { + Picasso.with(context).load(R.drawable.qrcode).into(holder.iconRow); + } else { + Picasso.with(context).load(domoticz.getDrawableIcon(mDeviceInfo.getTypeImg(), + mDeviceInfo.getType(), + mDeviceInfo.getSubType(), + mDeviceInfo.getStatusBoolean(), + mDeviceInfo.getUseCustomImage(), + mDeviceInfo.getImage())).into(holder.iconRow); + } holder.iconRow.setAlpha(1f); if (!mDeviceInfo.getStatusBoolean()) diff --git a/app/src/main/java/nl/hnogames/domoticz/AnalyticsTrackers.java b/app/src/main/java/nl/hnogames/domoticz/AnalyticsTrackers.java index 29d08abdc..7ed48a64e 100644 --- a/app/src/main/java/nl/hnogames/domoticz/AnalyticsTrackers.java +++ b/app/src/main/java/nl/hnogames/domoticz/AnalyticsTrackers.java @@ -20,12 +20,16 @@ */ public final class AnalyticsTrackers { - public enum Target { - APP, - // Add more trackers here if you need, and update the code in #get(Target) below - } - private static AnalyticsTrackers sInstance; + private final Map mTrackers = new HashMap(); + private final Context mContext; + + /** + * Don't instantiate directly - use {@link #getInstance()} instead. + */ + private AnalyticsTrackers(Context context) { + mContext = context.getApplicationContext(); + } public static synchronized void initialize(Context context) { if (sInstance != null) { @@ -43,16 +47,6 @@ public static synchronized AnalyticsTrackers getInstance() { return sInstance; } - private final Map mTrackers = new HashMap(); - private final Context mContext; - - /** - * Don't instantiate directly - use {@link #getInstance()} instead. - */ - private AnalyticsTrackers(Context context) { - mContext = context.getApplicationContext(); - } - public synchronized Tracker get(Target target) { if (!mTrackers.containsKey(target)) { Tracker tracker; @@ -68,4 +62,9 @@ public synchronized Tracker get(Target target) { return mTrackers.get(target); } + + public enum Target { + APP, + // Add more trackers here if you need, and update the code in #get(Target) below + } } diff --git a/app/src/main/java/nl/hnogames/domoticz/CameraActivity.java b/app/src/main/java/nl/hnogames/domoticz/CameraActivity.java index 9d2d583d8..4b3d02cd5 100644 --- a/app/src/main/java/nl/hnogames/domoticz/CameraActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/CameraActivity.java @@ -35,6 +35,9 @@ public class CameraActivity extends AppCompatActivity { protected void onCreate(Bundle savedInstanceState) { if (new SharedPrefUtil(this).darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); + super.onCreate(savedInstanceState); Bundle bundle = getIntent().getExtras(); diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/AuthInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/AuthInfo.java new file mode 100644 index 000000000..76cec3325 --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/AuthInfo.java @@ -0,0 +1,69 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Containers; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.Serializable; + +public class AuthInfo implements Serializable { + + private String user; + private int rights; + + public AuthInfo(JSONObject row) throws JSONException { + mapFields(row); + } + + public AuthInfo(String json) { + try { + mapFields(new JSONObject(json)); + } catch (JSONException e) { + e.printStackTrace(); + } + } + + private void mapFields(JSONObject row) throws JSONException { + if (row.has("user")) + setUser(row.getString("user")); + if (row.has("rights")) + setRights(row.getInt("rights")); + } + + public String getUser() { + return user; + } + + public void setUser(String user) { + this.user = user; + } + + public int getRights() { + return rights; + } + + public void setRights(int rights) { + this.rights = rights; + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/ConfigInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/ConfigInfo.java index 66ccccdcb..9105ed395 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Containers/ConfigInfo.java +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/ConfigInfo.java @@ -26,6 +26,7 @@ import org.json.JSONObject; import java.io.Serializable; +import java.util.ArrayList; public class ConfigInfo implements Serializable { @@ -40,6 +41,7 @@ public class ConfigInfo implements Serializable { private long dateOfConfig; private String language; private String DashboardType; + private ArrayList mUsers; public ConfigInfo(JSONObject row) throws JSONException { mapFields(row); @@ -123,4 +125,12 @@ public String getLanguage() { public String getDashboardType() { return DashboardType; } + + public ArrayList getUsers() { + return mUsers; + } + + public void setUsers(ArrayList mUsers) { + this.mUsers = mUsers; + } } \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/DevicesInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/DevicesInfo.java index b705e9eab..76e9628b2 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Containers/DevicesInfo.java +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/DevicesInfo.java @@ -34,6 +34,7 @@ import java.util.regex.Pattern; import nl.hnogames.domoticz.Domoticz.Domoticz; +import nl.hnogames.domoticz.Utils.UsefulBits; public class DevicesInfo implements Comparable { @@ -246,6 +247,9 @@ public DevicesInfo(JSONObject row) throws JSONException { } } + public DevicesInfo() { + } + public boolean getFavoriteBoolean() { boolean favorite = false; if (this.Favorite == 1) favorite = true; @@ -299,6 +303,9 @@ public void setStatus(String status) { } public String[] getLevelNames() { + if (UsefulBits.isEmpty(LevelNames)) + return null; + String[] names = Pattern.compile("|", Pattern.LITERAL).split(LevelNames); String[] newNames = new String[names.length - 1]; for (int i = 1; i < names.length; i++) { diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/NFCInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/NFCInfo.java index d5cbd6f42..d5f02bbfc 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Containers/NFCInfo.java +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/NFCInfo.java @@ -67,6 +67,10 @@ public String getSwitchPassword() { return switchPassword; } + public void setSwitchPassword(String switchPassword) { + this.switchPassword = switchPassword; + } + public String getSwitchName() { return switchName; } @@ -75,8 +79,4 @@ public void setSwitchName(String switchName) { this.switchName = switchName; } - public void setSwitchPassword(String switchPassword) { - this.switchPassword = switchPassword; - } - } diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/ServerInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/ServerInfo.java index 7f5fd293f..64d08a0e0 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Containers/ServerInfo.java +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/ServerInfo.java @@ -93,8 +93,8 @@ public void setServerUniqueId(String SERVER_UNIQUE_ID) { */ public String createUniqueServerId() { return UsefulBits.getMd5String( - LOCAL_SERVER_URL + LOCAL_SERVER_PORT + LOCAL_SERVER_USERNAME + - REMOTE_SERVER_URL + REMOTE_SERVER_PORT + REMOTE_SERVER_USERNAME); + LOCAL_SERVER_URL + LOCAL_SERVER_PORT + + REMOTE_SERVER_URL + REMOTE_SERVER_PORT); } public String getRemoteServerUsername() { @@ -345,7 +345,8 @@ private ConfigInfo readConfigInfoFromFile(Context context) { * @return Configuration info of this server */ public ConfigInfo getConfigInfo(Context context) { - if (configInfo == null) configInfo = readConfigInfoFromFile(context); + if (configInfo == null) + configInfo = readConfigInfoFromFile(context); return configInfo; } diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/SpeechInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/SpeechInfo.java new file mode 100644 index 000000000..3d3d3cb65 --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/SpeechInfo.java @@ -0,0 +1,82 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Containers; + +public class SpeechInfo { + + private boolean enabled = false; + private String id; + private String name; + private int switchIdx; + private String switchName; + private String switchPassword = ""; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getSwitchIdx() { + return switchIdx; + } + + public void setSwitchIdx(int switchIdx) { + this.switchIdx = switchIdx; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + this.enabled = enabled; + } + + public String getSwitchPassword() { + return switchPassword; + } + + public void setSwitchPassword(String switchPassword) { + this.switchPassword = switchPassword; + } + + public String getSwitchName() { + return switchName; + } + + public void setSwitchName(String switchName) { + this.switchName = switchName; + } + +} diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/UserInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/UserInfo.java new file mode 100644 index 000000000..be90c1880 --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/UserInfo.java @@ -0,0 +1,125 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Containers; + +import android.content.Context; + +import org.json.JSONException; +import org.json.JSONObject; + +import java.io.Serializable; + +import nl.hnogames.domoticz.R; + +public class UserInfo implements Serializable { + // private JSONObject jsonObject; + private boolean Enabled = true; + private String Password; + private int Rights; + private String Username; + private int idx; + + public UserInfo(String username, String password, int rights) { + Password = password; + Username = username; + Rights = rights; + } + + public UserInfo(JSONObject row) throws JSONException { + // this.setJsonObject(row); + if (row.has("Password")) + setPassword(row.getString("Password")); + if (row.has("Username")) + setUsername(row.getString("Username")); + if (row.has("idx")) + setIdx(row.getInt("idx")); + if (row.has("Rights")) + setRights(row.getInt("Rights")); + if (row.has("Password")) + setPassword(row.getString("Password")); + if (row.has("Enabled")) + setEnabled(row.getBoolean("Enabled")); + } + + @Override + public String toString() { + return "UserInfo{" + + "idx=" + getIdx() + + ", Username='" + getUsername() + + ", Password='" + getPassword() + + ", Enabled=" + isEnabled() + + "'}"; + } + + public boolean isEnabled() { + return Enabled; + } + + public void setEnabled(boolean enabled) { + Enabled = enabled; + } + + public String getPassword() { + return Password; + } + + public void setPassword(String password) { + Password = password; + } + + public int getRights() { + return Rights; + } + + public void setRights(int rights) { + Rights = rights; + } + + public String getRightsValue(Context context) { + switch (Rights) { + case 0: + return context.getString(R.string.user_viewer); + case 1: + return context.getString(R.string.user_user); + case 2: + return context.getString(R.string.user_admin); + } + return ""; + } + + public String getUsername() { + return Username; + } + + public void setUsername(String username) { + Username = username; + } + + public int getIdx() { + return idx; + } + + public void setIdx(int idx) { + this.idx = idx; + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Containers/WeatherInfo.java b/app/src/main/java/nl/hnogames/domoticz/Containers/WeatherInfo.java index fe6ea58b8..bc4f7e99b 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Containers/WeatherInfo.java +++ b/app/src/main/java/nl/hnogames/domoticz/Containers/WeatherInfo.java @@ -71,9 +71,12 @@ public WeatherInfo(JSONObject row) throws JSONException { if (row.has("Rain")) Rain = row.getString("Rain"); if (row.has("RainRate")) RainRate = row.getString("RainRate"); - if (Type.equals("Rain")) Data = Data.substring(Data.indexOf(';') + 1, Data.length()); - if (Type.equals("Wind")) Data = Data.substring(0, Data.indexOf(';')); - + if (Type.equals("Rain") && Data.indexOf(';') >= 0) { + Data = Data.substring(Data.indexOf(';') + 1); + } + if (Type.equals("Wind") && Data.indexOf(';') >= 0) { + Data = Data.substring(0, Data.indexOf(';')); + } if (row.has("DewPoint")) DewPoint = row.getLong("DewPoint"); if (row.has("Temp")) Temp = row.getLong("Temp"); if (row.has("ForecastStr")) ForecastStr = row.getString("ForecastStr"); diff --git a/app/src/main/java/nl/hnogames/domoticz/Domoticz/AuthParser.java b/app/src/main/java/nl/hnogames/domoticz/Domoticz/AuthParser.java new file mode 100644 index 000000000..7f739440e --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Domoticz/AuthParser.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Domoticz; + +import android.util.Log; + +import org.json.JSONException; +import org.json.JSONObject; + +import nl.hnogames.domoticz.Containers.AuthInfo; +import nl.hnogames.domoticz.Interfaces.AuthReceiver; +import nl.hnogames.domoticz.Interfaces.JSONParserInterface; + +public class AuthParser implements JSONParserInterface { + + private static final String TAG = AuthParser.class.getSimpleName(); + private AuthReceiver receiver; + + public AuthParser(AuthReceiver receiver) { + this.receiver = receiver; + } + + @Override + public void parseResult(String result) { + try { + AuthInfo mAuthInfo = new AuthInfo(new JSONObject(result)); + receiver.onReceiveAuthentication(mAuthInfo); + } catch (JSONException e) { + Log.e(TAG, "AuthParser JSON exception"); + e.printStackTrace(); + receiver.onError(e); + } + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "AuthParser of JSONParserInterface exception"); + receiver.onError(error); + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Domoticz/Domoticz.java b/app/src/main/java/nl/hnogames/domoticz/Domoticz/Domoticz.java index 21566bc17..ff60c1789 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Domoticz/Domoticz.java +++ b/app/src/main/java/nl/hnogames/domoticz/Domoticz/Domoticz.java @@ -41,15 +41,16 @@ import java.util.Map; import java.util.Set; +import hugo.weaving.DebugLog; import nl.hnogames.domoticz.Containers.CameraInfo; import nl.hnogames.domoticz.Containers.DevicesInfo; import nl.hnogames.domoticz.Containers.SceneInfo; import nl.hnogames.domoticz.Containers.ServerInfo; +import nl.hnogames.domoticz.Interfaces.AuthReceiver; import nl.hnogames.domoticz.Interfaces.CameraReceiver; import nl.hnogames.domoticz.Interfaces.ConfigReceiver; import nl.hnogames.domoticz.Interfaces.DevicesReceiver; import nl.hnogames.domoticz.Interfaces.EventReceiver; -import nl.hnogames.domoticz.Interfaces.EventXmlReceiver; import nl.hnogames.domoticz.Interfaces.GraphDataReceiver; import nl.hnogames.domoticz.Interfaces.LanguageReceiver; import nl.hnogames.domoticz.Interfaces.LogsReceiver; @@ -67,6 +68,7 @@ import nl.hnogames.domoticz.Interfaces.UpdateDownloadReadyReceiver; import nl.hnogames.domoticz.Interfaces.UpdateVersionReceiver; import nl.hnogames.domoticz.Interfaces.UserVariablesReceiver; +import nl.hnogames.domoticz.Interfaces.UsersReceiver; import nl.hnogames.domoticz.Interfaces.UtilitiesReceiver; import nl.hnogames.domoticz.Interfaces.VersionReceiver; import nl.hnogames.domoticz.Interfaces.WeatherReceiver; @@ -109,6 +111,7 @@ public class Domoticz { private String snapshot_file_path = "/Domoticz/SnapShot"; + @DebugLog public Domoticz(Context mContext, ServerUtil serverUtil) { this.mContext = mContext; @@ -122,20 +125,24 @@ public Domoticz(Context mContext, ServerUtil serverUtil) { mSessionUtil = new SessionUtil(mContext); mPhoneConnectionUtil = new PhoneConnectionUtil(mContext, new WifiSSIDListener() { @Override + @DebugLog public void ReceiveSSIDs(CharSequence[] entries) { } }); debug = mSharedPrefUtil.isDebugEnabled(); } + @DebugLog public boolean isDebugEnabled() { return mSharedPrefUtil.isDebugEnabled(); } + @DebugLog public void logger(String text) { if (debug) Log.d(TAG, text); } + @DebugLog public boolean isUserOnLocalWifi() { boolean userIsLocal = false; if (mServerUtil.getActiveServer().getIsLocalServerAddressDifferent()) { @@ -156,6 +163,7 @@ public boolean isUserOnLocalWifi() { return userIsLocal; } + @DebugLog public boolean isConnectionDataComplete(ServerInfo server) { boolean result = true; HashMap stringHashMap = new HashMap<>(); @@ -177,6 +185,7 @@ public boolean isConnectionDataComplete(ServerInfo server) { return result; } + @DebugLog public String isConnectionDataComplete(ServerInfo server, boolean validatePorts) { HashMap stringHashMap = new HashMap<>(); stringHashMap.put("Domoticz local URL", server.getLocalServerUrl()); @@ -196,6 +205,7 @@ public String isConnectionDataComplete(ServerInfo server, boolean validatePorts) return null; } + @DebugLog public boolean isUrlValid(ServerInfo server) { boolean result = true; HashMap stringHashMap = new HashMap<>(); @@ -214,6 +224,7 @@ public boolean isUrlValid(ServerInfo server) { return result; } + @DebugLog public boolean isOnOffSwitch(DevicesInfo testSwitch) { if (testSwitch.getSwitchTypeVal() <= 0 && testSwitch.getSwitchType() == null) return false; @@ -239,6 +250,7 @@ public boolean isOnOffSwitch(DevicesInfo testSwitch) { return false; } + @DebugLog public boolean isOnOffScene(SceneInfo testSwitch) { switch (testSwitch.getType()) { case Domoticz.Scene.Type.GROUP: @@ -248,23 +260,20 @@ public boolean isOnOffScene(SceneInfo testSwitch) { return false; } + @DebugLog public String getErrorMessage(Exception error) { - - String errorMessage; - + String errorMessage = ""; if (error instanceof VolleyError) { - VolleyUtil mVolleyUtil = new VolleyUtil(mContext); VolleyError volleyError = (VolleyError) error; - errorMessage = mVolleyUtil.getVolleyErrorMessage(volleyError); - } else { - errorMessage = error.getMessage(); } - + if (UsefulBits.isEmpty(errorMessage)) + errorMessage = error.getMessage(); return errorMessage; } + @DebugLog public List getSupportedSwitchesValues() { List switchesSupported = new ArrayList<>(); switchesSupported.add(Device.Type.Value.ON_OFF); @@ -289,6 +298,7 @@ public List getSupportedSwitchesValues() { return switchesSupported; } + @DebugLog public List getSupportedSwitchesNames() { List switchesSupported = new ArrayList<>(); switchesSupported.add(Device.Type.Name.ON_OFF); @@ -314,6 +324,8 @@ public List getSupportedSwitchesNames() { return switchesSupported; } + /* + @DebugLog public List getWearSupportedSwitchesValues() { List switchesSupported = new ArrayList<>(); switchesSupported.add(Device.Type.Value.ON_OFF); @@ -328,6 +340,7 @@ public List getWearSupportedSwitchesValues() { return switchesSupported; } + @DebugLog public List getWearSupportedSwitchesNames() { List switchesSupported = new ArrayList<>(); switchesSupported.add(Device.Type.Name.ON_OFF); @@ -341,7 +354,9 @@ public List getWearSupportedSwitchesNames() { switchesSupported.add(Device.Type.Name.DOORBELL); return switchesSupported; } + */ + @DebugLog public void debugTextToClipboard(TextView debugText) { String message = debugText.getText().toString(); UsefulBits.copyToClipboard(mContext, "Domoticz debug data", message); @@ -444,6 +459,18 @@ private String getJsonGetUrl(int jsonGetUrl) { url = Url.System.EVENTS; break; + case Json.Url.Request.USERS: + url = Url.System.USERS; + break; + + case Json.Url.Request.AUTH: + url = Url.System.AUTH; + break; + + case Json.Url.Request.LOGOFF: + url = Url.System.LOGOFF; + break; + case Json.Url.Request.EVENTXML: url = Url.System.EVENTXML; break; @@ -517,6 +544,7 @@ private String constructGetUrl(int jsonGetUrl) { return fullString; } + @DebugLog public String constructSetUrl(int jsonSetUrl, int idx, int action, double value) { String protocol, baseUrl, url, port, directory, jsonUrl = null, actionUrl; StringBuilder buildUrl = new StringBuilder(); @@ -701,13 +729,12 @@ public String constructSetUrl(int jsonSetUrl, int idx, int action, double value) return fullString; } + @DebugLog public String getUserCredentials(String credential) { - if (credential.equals(Authentication.USERNAME) || credential.equals(Authentication.PASSWORD)) { String username, password; - if (isUserOnLocalWifi()) { logger("On local wifi"); username = mServerUtil.getActiveServer().getLocalServerUsername(); @@ -720,11 +747,41 @@ public String getUserCredentials(String credential) { HashMap credentials = new HashMap<>(); credentials.put(Authentication.USERNAME, username); credentials.put(Authentication.PASSWORD, password); - return credentials.get(credential); } else return ""; } + /** + * Get's the version of the update (if available) + * + * @param receiver to get the callback on + */ + @DebugLog + public void getUserAuthenticationRights(AuthReceiver receiver) { + AuthParser parser = new AuthParser(receiver); + String url = constructGetUrl(Json.Url.Request.AUTH); + RequestUtil.makeJsonGetRequest(parser, + getUserCredentials(Authentication.USERNAME), + getUserCredentials(Authentication.PASSWORD), + url, mSessionUtil, false, 1); + } + + @DebugLog + public void setUserCredentials(String username, String password) { + if (!UsefulBits.isEmpty(username) && !UsefulBits.isEmpty(password)) { + if (isUserOnLocalWifi()) { + logger("On local wifi"); + mServerUtil.getActiveServer().setLocalServerUsername(username); + mServerUtil.getActiveServer().setLocalServerPassword(password); + } else { + logger("Not on local wifi"); + mServerUtil.getActiveServer().setRemoteServerUsername(username); + mServerUtil.getActiveServer().setRemoteServerPassword(password); + } + mServerUtil.saveDomoticzServers(true); + } + } + /** * Register you device on Domoticz * @@ -732,6 +789,7 @@ public String getUserCredentials(String credential) { * @param SenderId sender id from the Google services * @param receiver to get the callback on */ + @DebugLog public void AddMobileDevice(String DeviceId, String SenderId, MobileDeviceReceiver receiver) { MobileDeviceParser parser = new MobileDeviceParser(receiver); String url = constructGetUrl(Json.Url.Request.ADD_MOBILE_DEVICE); @@ -751,6 +809,7 @@ public void AddMobileDevice(String DeviceId, String SenderId, MobileDeviceReceiv * @param DeviceId UUID of the device * @param receiver to get the callback on */ + @DebugLog public void CleanMobileDevice(String DeviceId, MobileDeviceReceiver receiver) { MobileDeviceParser parser = new MobileDeviceParser(receiver); String url = constructGetUrl(Json.Url.Request.CLEAN_MOBILE_DEVICE); @@ -767,6 +826,7 @@ public void CleanMobileDevice(String DeviceId, MobileDeviceReceiver receiver) { * * @param receiver to get the callback on */ + @DebugLog public void getServerVersion(VersionReceiver receiver) { VersionParser parser = new VersionParser(receiver); String url = constructGetUrl(Json.Url.Request.VERSION); @@ -781,6 +841,7 @@ public void getServerVersion(VersionReceiver receiver) { * * @param receiver to get the callback on */ + @DebugLog public void getUpdate(UpdateVersionReceiver receiver) { UpdateVersionParser parser = new UpdateVersionParser(receiver); String url = constructGetUrl(Json.Url.Request.UPDATE); @@ -795,6 +856,7 @@ public void getUpdate(UpdateVersionReceiver receiver) { * * @param receiver to get the callback on */ + @DebugLog public void getUpdateDownloadReady(UpdateDownloadReadyReceiver receiver) { UpdateDownloadReadyParser parser = new UpdateDownloadReadyParser(receiver); String url = constructGetUrl(Json.Url.Request.UPDATE_DOWNLOAD_READY); @@ -809,6 +871,7 @@ public void getUpdateDownloadReady(UpdateDownloadReadyReceiver receiver) { * * @param receiver to get the callback on */ + @DebugLog public void updateDomoticzServer(@Nullable UpdateDomoticzServerReceiver receiver) { UpdateDomoticzServerParser parser = new UpdateDomoticzServerParser(receiver); String url = constructGetUrl(Json.Url.Request.UPDATE_DOMOTICZ_SERVER); @@ -818,6 +881,7 @@ public void updateDomoticzServer(@Nullable UpdateDomoticzServerReceiver receiver url, mSessionUtil, true, 3); } + @DebugLog public void getScenes(ScenesReceiver receiver) { ScenesParser parser = new ScenesParser(receiver); String url = constructGetUrl(Json.Url.Request.SCENES); @@ -827,6 +891,7 @@ public void getScenes(ScenesReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getScene(ScenesReceiver receiver, int idx) { ScenesParser parser = new ScenesParser(receiver, idx); String url = constructGetUrl(Json.Url.Request.SCENES); @@ -836,6 +901,7 @@ public void getScene(ScenesReceiver receiver, int idx) { url, mSessionUtil, true, 3); } + @DebugLog public void getPlans(PlansReceiver receiver) { PlanParser parser = new PlanParser(receiver); String url = constructGetUrl(Json.Url.Request.PLANS); @@ -845,6 +911,7 @@ public void getPlans(PlansReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getCameras(CameraReceiver receiver) { CameraParser parser = new CameraParser(receiver, this); String url = constructGetUrl(Json.Url.Request.CAMERAS); @@ -855,10 +922,12 @@ public void getCameras(CameraReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public String getSnapshotUrl(CameraInfo camera) { return constructGetUrl(Json.Url.Request.CAMERA) + camera.getIdx(); } + @DebugLog public void getSwitches(SwitchesReceiver switchesReceiver) { SwitchesParser parser = new SwitchesParser(switchesReceiver); String url = constructGetUrl(Json.Url.Request.SWITCHES); @@ -868,6 +937,7 @@ public void getSwitches(SwitchesReceiver switchesReceiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getSwitchLogs(int idx, SwitchLogReceiver switchesReceiver) { SwitchLogParser parser = new SwitchLogParser(switchesReceiver); logger("for idx: " + String.valueOf(idx)); @@ -879,6 +949,7 @@ public void getSwitchLogs(int idx, SwitchLogReceiver switchesReceiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getTextLogs(int idx, SwitchLogReceiver switchesReceiver) { SwitchLogParser parser = new SwitchLogParser(switchesReceiver); logger("for idx: " + String.valueOf(idx)); @@ -890,6 +961,7 @@ public void getTextLogs(int idx, SwitchLogReceiver switchesReceiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getSceneLogs(int idx, SwitchLogReceiver switchesReceiver) { SwitchLogParser parser = new SwitchLogParser(switchesReceiver); logger("for idx: " + String.valueOf(idx)); @@ -901,6 +973,7 @@ public void getSceneLogs(int idx, SwitchLogReceiver switchesReceiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getSwitchTimers(int idx, SwitchTimerReceiver switchesReceiver) { SwitchTimerParser parser = new SwitchTimerParser(switchesReceiver); logger("for idx: " + String.valueOf(idx)); @@ -912,6 +985,7 @@ public void getSwitchTimers(int idx, SwitchTimerReceiver switchesReceiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getNotifications(int idx, NotificationReceiver notificationReceiver) { NotificationsParser parser = new NotificationsParser(notificationReceiver); logger("for idx: " + String.valueOf(idx)); @@ -924,6 +998,7 @@ public void getNotifications(int idx, NotificationReceiver notificationReceiver) } @SuppressWarnings("SpellCheckingInspection") + @DebugLog public void setSecurityPanelAction(int secStatus, String seccode, setCommandReceiver receiver) { @@ -941,6 +1016,7 @@ public void setSecurityPanelAction(int secStatus, } @SuppressWarnings("SpellCheckingInspection") + @DebugLog public void setAction(int idx, int jsonUrl, int jsonAction, @@ -962,6 +1038,7 @@ public void setAction(int idx, } @SuppressWarnings("SpellCheckingInspection") + @DebugLog public void setRGBColorAction(int idx, int jsonUrl, long hue, @@ -988,6 +1065,7 @@ public void setRGBColorAction(int idx, } @SuppressWarnings("SpellCheckingInspection") + @DebugLog public void setModalAction(int id, int status, // one of Domoticz.Device.ModalSwitch.Action int action, // behaves like this action == 1 ? 1 : 0 @@ -1008,7 +1086,8 @@ public void setModalAction(int id, } /* - public void setEventAction(int id, + @DebugLog + public void setEventAction(int id, String xmlStatement, int jsonUrl, int jsonAction, @@ -1024,6 +1103,7 @@ public void setEventAction(int id, url, mSessionUtil, true, 3); }*/ + @DebugLog public void setDeviceUsed(int id, String name, String description, @@ -1046,6 +1126,7 @@ public void setDeviceUsed(int id, url, mSessionUtil, true, 3); } + @DebugLog public void getStatus(int idx, StatusReceiver receiver) { StatusInfoParser parser = new StatusInfoParser(receiver); String url = constructGetUrl(Json.Get.STATUS) + String.valueOf(idx); @@ -1057,6 +1138,7 @@ public void getStatus(int idx, StatusReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getUtilities(UtilitiesReceiver receiver) { UtilitiesParser parser = new UtilitiesParser(receiver); String url = constructGetUrl(Json.Url.Request.UTILITIES); @@ -1066,6 +1148,7 @@ public void getUtilities(UtilitiesReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getSettings(SettingsReceiver receiver) { SettingsParser parser = new SettingsParser(receiver); String url = constructGetUrl(Json.Url.Request.SETTINGS); @@ -1075,6 +1158,7 @@ public void getSettings(SettingsReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getConfig(ConfigReceiver receiver) { ConfigParser parser = new ConfigParser(receiver); String url = constructGetUrl(Json.Url.Request.CONFIG); @@ -1084,6 +1168,7 @@ public void getConfig(ConfigReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getLanguageStringsFromServer(String language, LanguageReceiver receiver) { LanguageParser parser = new LanguageParser(receiver); String url = constructGetUrl(Json.Url.Request.LANGUAGE); @@ -1094,6 +1179,7 @@ public void getLanguageStringsFromServer(String language, LanguageReceiver recei url, mSessionUtil, true, 3); } + @DebugLog public void getTemperatures(TemperatureReceiver receiver) { TemperaturesParser parser = new TemperaturesParser(receiver); String url = constructGetUrl(Json.Url.Request.TEMPERATURE); @@ -1103,6 +1189,7 @@ public void getTemperatures(TemperatureReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getWeathers(WeatherReceiver receiver) { WeatherParser parser = new WeatherParser(receiver); String url = constructGetUrl(Json.Url.Request.WEATHER); @@ -1112,6 +1199,7 @@ public void getWeathers(WeatherReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getDevices(DevicesReceiver receiver, int plan, String filter) { DevicesParser parser = new DevicesParser(receiver); String url = constructGetUrl(Json.Url.Request.DEVICES); @@ -1128,6 +1216,7 @@ public void getDevices(DevicesReceiver receiver, int plan, String filter) { url, mSessionUtil, true, 3); } + @DebugLog public void getDevice(DevicesReceiver receiver, int idx, boolean scene_or_group) { DevicesParser parser = new DevicesParser(receiver, idx, scene_or_group); String url = constructGetUrl(Json.Url.Request.DEVICES); @@ -1138,6 +1227,7 @@ public void getDevice(DevicesReceiver receiver, int idx, boolean scene_or_group) url, mSessionUtil, true, 3); } + @DebugLog public void getLogs(LogsReceiver receiver) { LogsParser parser = new LogsParser(receiver); String url = constructGetUrl(Json.Url.Request.LOG); @@ -1147,6 +1237,7 @@ public void getLogs(LogsReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog public void getUserVariables(UserVariablesReceiver receiver) { UserVariablesParser parser = new UserVariablesParser(receiver); String url = constructGetUrl(Json.Url.Request.USERVARIABLES); @@ -1156,6 +1247,26 @@ public void getUserVariables(UserVariablesReceiver receiver) { url, mSessionUtil, true, 3); } + @DebugLog + public void getUsers(UsersReceiver receiver) { + UsersParser parser = new UsersParser(receiver); + String url = constructGetUrl(Json.Url.Request.USERS); + RequestUtil.makeJsonGetResultRequest(parser, + getUserCredentials(Authentication.USERNAME), + getUserCredentials(Authentication.PASSWORD), + url, mSessionUtil, true, 3); + } + + @DebugLog + public void LogOff() { + String url = constructGetUrl(Json.Url.Request.LOGOFF); + RequestUtil.makeJsonGetRequest(new LogOffParser(), + getUserCredentials(Authentication.USERNAME), + getUserCredentials(Authentication.PASSWORD), + url, mSessionUtil, true, 3); + } + + @DebugLog public void getEvents(EventReceiver receiver) { EventsParser parser = new EventsParser(receiver); String url = constructGetUrl(Json.Url.Request.EVENTS); @@ -1165,6 +1276,8 @@ public void getEvents(EventReceiver receiver) { url, mSessionUtil, true, 3); } + /* + @DebugLog public void getEventXml(int id, EventXmlReceiver receiver) { EventsXmlParser parser = new EventsXmlParser(receiver); String url = constructGetUrl(Json.Url.Request.EVENTXML); @@ -1174,8 +1287,9 @@ public void getEventXml(int id, EventXmlReceiver receiver) { getUserCredentials(Authentication.PASSWORD), url, mSessionUtil, true, 3); } + */ - + @DebugLog public void getGraphData(int idx, String range, String type, GraphDataReceiver receiver) { GraphDataParser parser = new GraphDataParser(receiver); String url = constructGetUrl(Json.Url.Request.GRAPH) + String.valueOf(idx); @@ -1189,6 +1303,7 @@ public void getGraphData(int idx, String range, String type, GraphDataReceiver r url, mSessionUtil, true, 3); } + @DebugLog public File saveSnapShot(Bitmap bitmap, String name) { String file_path = Environment.getExternalStorageDirectory().getAbsolutePath() + this.snapshot_file_path; @@ -1358,6 +1473,7 @@ private int getDrawableIcon(String imgType, String Type, String switchType, bool return test; } + @DebugLog public interface Authentication { String USERNAME = "username"; String PASSWORD = "password"; @@ -1368,16 +1484,19 @@ interface Method { } } + @DebugLog public interface Result { String ERROR = "ERR"; String OK = "OK"; } + @DebugLog public interface Protocol { String SECURE = "HTTPS"; String INSECURE = "HTTP"; } + @DebugLog public interface Device { interface Switch { interface Action { @@ -1502,6 +1621,7 @@ interface Favorite { } } + @DebugLog public interface Json { interface Field { String RESULT = "result"; @@ -1547,6 +1667,9 @@ interface Request { int NOTIFICATIONS = 31; int LANGUAGE = 32; int SCENELOG = 33; + int USERS = 34; + int LOGOFF = 35; + int AUTH = 36; } @SuppressWarnings("SpellCheckingInspection") @@ -1567,6 +1690,7 @@ interface Get { } } + @DebugLog public interface Scene { interface Type { String GROUP = "Group"; @@ -1579,6 +1703,7 @@ interface Action { } } + @DebugLog public interface Graph { interface Range { String DAY = "day"; @@ -1588,6 +1713,7 @@ interface Range { } } + @DebugLog public interface Temperature { @SuppressWarnings("unused") interface Sign { @@ -1596,6 +1722,7 @@ interface Sign { } } + @DebugLog public interface Event { @SuppressWarnings("unused") interface Type { @@ -1608,6 +1735,7 @@ interface Action { } } + @DebugLog public interface Security { @SuppressWarnings("SpellCheckingInspection") interface Status { @@ -1750,6 +1878,9 @@ interface System { String ADD_MOBILE_DEVICE = "/json.htm?type=command¶m=addmobiledevice"; String CLEAN_MOBILE_DEVICE = "/json.htm?type=command¶m=deletemobiledevice"; String LANGUAGE_TRANSLATIONS = "/i18n/domoticz-"; + String USERS = "/json.htm?type=users"; + String AUTH = "/json.htm?type=command¶m=getauth"; + String LOGOFF = "/json.htm?type=command¶m=dologout"; } } diff --git a/app/src/main/java/nl/hnogames/domoticz/Domoticz/LogOffParser.java b/app/src/main/java/nl/hnogames/domoticz/Domoticz/LogOffParser.java new file mode 100644 index 000000000..841fe7dc8 --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Domoticz/LogOffParser.java @@ -0,0 +1,42 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Domoticz; + +import nl.hnogames.domoticz.Interfaces.JSONParserInterface; + +public class LogOffParser implements JSONParserInterface { + + private static final String TAG = LogOffParser.class.getSimpleName(); + + public LogOffParser() { + //TODO: extend this parser with status info + } + + @Override + public void parseResult(String result) { + } + + @Override + public void onError(Exception error) { + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Domoticz/UsersParser.java b/app/src/main/java/nl/hnogames/domoticz/Domoticz/UsersParser.java new file mode 100644 index 000000000..5ee23e054 --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Domoticz/UsersParser.java @@ -0,0 +1,77 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Domoticz; + +import android.util.Log; + +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import java.util.ArrayList; + +import nl.hnogames.domoticz.Containers.UserInfo; +import nl.hnogames.domoticz.Interfaces.JSONParserInterface; +import nl.hnogames.domoticz.Interfaces.UsersReceiver; + +public class UsersParser implements JSONParserInterface { + + private static final String TAG = UsersParser.class.getSimpleName(); + private UsersReceiver usersReceiver; + + public UsersParser(UsersReceiver usersReceiver) { + this.usersReceiver = usersReceiver; + } + + @Override + public void parseResult(String result) { + try { + JSONArray jsonArray = new JSONArray(result); + ArrayList mUserInfo = new ArrayList<>(); + + if (jsonArray.length() > 0) { + for (int i = 0; i < jsonArray.length(); i++) { + JSONObject row = jsonArray.getJSONObject(i); + mUserInfo.add(new UserInfo(row)); + } + } + + if (mUserInfo == null || mUserInfo.size() <= 0) + onError(new NullPointerException( + "No Users found in Domoticz.")); + else + usersReceiver.onReceiveUsers(mUserInfo); + + } catch (JSONException e) { + Log.e(TAG, "UsersParser JSON exception"); + e.printStackTrace(); + usersReceiver.onError(e); + } + } + + @Override + public void onError(Exception error) { + Log.e(TAG, "UsersParser of JSONParserInterface exception"); + usersReceiver.onError(error); + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Cameras.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Cameras.java index 3425b6751..28be703e1 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Cameras.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Cameras.java @@ -146,7 +146,8 @@ public void onAttach(Context context) { super.onAttach(context); this.context = context; mSharedPrefs = new SharedPrefUtil(context); - getActionBar().setTitle(R.string.title_cameras); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_cameras); } @Override diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Changelog.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Changelog.java new file mode 100644 index 000000000..48f8fadaa --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Changelog.java @@ -0,0 +1,52 @@ +package nl.hnogames.domoticz.Fragments; + +import android.app.Dialog; +import android.content.Context; +import android.content.DialogInterface; +import android.os.Bundle; +import android.support.v4.app.DialogFragment; +import android.support.v7.app.AlertDialog; +import android.view.LayoutInflater; + +import it.gmariotti.changelibs.library.view.ChangeLogRecyclerView; +import nl.hnogames.domoticz.Interfaces.DomoticzFragmentListener; +import nl.hnogames.domoticz.R; +import nl.hnogames.domoticz.Utils.SharedPrefUtil; + +public class Changelog extends DialogFragment implements DomoticzFragmentListener { + + private SharedPrefUtil mSharedPrefUtil; + + public Changelog() { + } + + @Override + public Dialog onCreateDialog(Bundle savedInstanceState) { + if (mSharedPrefUtil == null) + mSharedPrefUtil = new SharedPrefUtil(getContext()); + + LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService( + Context.LAYOUT_INFLATER_SERVICE); + ChangeLogRecyclerView chgList = (ChangeLogRecyclerView) layoutInflater.inflate(R.layout.changelog_fragment, null); + int theme = R.style.MyDialogTheme; + if (mSharedPrefUtil.darkThemeEnabled()) + theme = R.style.MyDarkDialogTheme; + + return new AlertDialog.Builder(getActivity(), theme) + .setTitle(getContext().getString(R.string.changelog)) + .setView(chgList) + .setPositiveButton(R.string.ok, + new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog, int whichButton) { + dialog.dismiss(); + } + } + ) + .create(); + } + + @Override + public void onConnectionOk() { + + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Dashboard.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Dashboard.java index 9ddbf7e78..4cccf0198 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Dashboard.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Dashboard.java @@ -37,6 +37,7 @@ import java.util.ArrayList; import java.util.List; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.DashboardAdapter; import nl.hnogames.domoticz.Containers.DevicesInfo; @@ -55,6 +56,7 @@ import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.app.DomoticzDashboardFragment; +@DebugLog public class Dashboard extends DomoticzDashboardFragment implements DomoticzFragmentListener, switchesClickListener { @@ -72,24 +74,28 @@ public class Dashboard extends DomoticzDashboardFragment implements DomoticzFrag private String filter = ""; @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; } @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); processDashboard(); } + @DebugLog public void selectedPlan(int plan, String name) { planID = plan; planName = name; } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -104,12 +110,15 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { - getActionBar().setTitle(R.string.title_dashboard); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_dashboard); super.showSpinner(true); if (getView() != null) { if (planName != null && planName.length() > 0) - getActionBar().setTitle(planName + ""); + if (getActionBar() != null) + getActionBar().setTitle(planName + ""); processDashboard(); } } @@ -125,15 +134,18 @@ private void processDashboard() { mDomoticz.getDevices(new DevicesReceiver() { @Override + @DebugLog public void onReceiveDevices(ArrayList switches) { processDevices(switches); } @Override + @DebugLog public void onReceiveDevice(DevicesInfo mDevicesInfo) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -181,18 +193,20 @@ private void createListView(ArrayList switches) { if (UsefulBits.isEmpty(super.getSort()) || super.getSort().equals(mContext.getString(R.string.filterOn_all))) { supportedSwitches.add(mExtendedStatusInfo); } else { - Snackbar.make(coordinatorLayout, getString(R.string.filterOn_on) + ": " + super.getSort(), Snackbar.LENGTH_SHORT).show(); - if ((super.getSort().equals(mContext.getString(R.string.filterOn_on)) && mExtendedStatusInfo.getStatusBoolean()) && - mDomoticz.isOnOffSwitch(mExtendedStatusInfo)) { - supportedSwitches.add(mExtendedStatusInfo); - } - if ((super.getSort().equals(mContext.getString(R.string.filterOn_off)) && !mExtendedStatusInfo.getStatusBoolean()) && - mDomoticz.isOnOffSwitch(mExtendedStatusInfo)) { - supportedSwitches.add(mExtendedStatusInfo); - } - if (super.getSort().equals(mContext.getString(R.string.filterOn_static)) && - !mDomoticz.isOnOffSwitch(mExtendedStatusInfo)) { - supportedSwitches.add(mExtendedStatusInfo); + if (mContext != null) { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.filter_on) + ": " + super.getSort(), Snackbar.LENGTH_SHORT); + if ((super.getSort().equals(mContext.getString(R.string.filterOn_on)) && mExtendedStatusInfo.getStatusBoolean()) && + mDomoticz.isOnOffSwitch(mExtendedStatusInfo)) { + supportedSwitches.add(mExtendedStatusInfo); + } + if ((super.getSort().equals(mContext.getString(R.string.filterOn_off)) && !mExtendedStatusInfo.getStatusBoolean()) && + mDomoticz.isOnOffSwitch(mExtendedStatusInfo)) { + supportedSwitches.add(mExtendedStatusInfo); + } + if (super.getSort().equals(mContext.getString(R.string.filterOn_static)) && + !mDomoticz.isOnOffSwitch(mExtendedStatusInfo)) { + supportedSwitches.add(mExtendedStatusInfo); + } } } } @@ -217,6 +231,7 @@ private void createListView(ArrayList switches) { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processDashboard(); } @@ -247,6 +262,7 @@ private void showInfoDialog(final DevicesInfo mSwitch) { infoDialog.onDismissListener(new DeviceInfoDialog.DismissListener() { @Override + @DebugLog public void onDismiss(boolean isChanged, boolean isFavorite) { if (isChanged) { changeFavorite(mSwitch, isFavorite); @@ -261,9 +277,9 @@ private void changeFavorite(final DevicesInfo mSwitch, final boolean isFavorite) addDebugText("Set idx " + mSwitch.getIdx() + " favorite to " + isFavorite); if (isFavorite) - Snackbar.make(coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.FAVORITE; @@ -277,12 +293,14 @@ private void changeFavorite(final DevicesInfo mSwitch, final boolean isFavorite) mDomoticz.setAction(mSwitch.getIdx(), jsonUrl, jsonAction, 0, null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); processDashboard(); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -290,6 +308,7 @@ public void onError(Exception error) { } @Override + @DebugLog public void onSwitchClick(int idx, final boolean checked) { if (busy) return; @@ -302,6 +321,7 @@ public void onSwitchClick(int idx, final boolean checked) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { toggleSwitch(clickedSwitch, checked, password); } @@ -313,9 +333,10 @@ public void onDismiss(String password) { private void toggleSwitch(final DevicesInfo clickedSwitch, final boolean checked, final String password) { if (checked) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + int idx = clickedSwitch.getIdx(); if (clickedSwitch.getIdx() > 0) { @@ -338,6 +359,7 @@ private void toggleSwitch(final DevicesInfo clickedSwitch, final boolean checked mDomoticz.setAction(idx, jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); //processDashboard(); @@ -347,9 +369,10 @@ public void onReceiveResult(String result) { } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -377,6 +400,7 @@ private DevicesInfo getDevice(int idx) { } @Override + @DebugLog public void onButtonClick(int idx, final boolean checked) { if (busy) return; @@ -391,6 +415,7 @@ public void onButtonClick(int idx, final boolean checked) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { toggleButton(clickedSwitch, checked, password); } @@ -401,9 +426,9 @@ public void onDismiss(String password) { private void toggleButton(final DevicesInfo clickedSwitch, final boolean checked, final String password) { if (checked) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); int idx = clickedSwitch.getIdx(); int jsonAction; @@ -419,6 +444,7 @@ private void toggleButton(final DevicesInfo clickedSwitch, final boolean checked } mDomoticz.setAction(idx, jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); clickedSwitch.setStatusBoolean(checked); @@ -427,9 +453,10 @@ public void onReceiveResult(String result) { } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -437,21 +464,25 @@ public void onError(Exception error) { } @Override + @DebugLog public void onLogButtonClick(int idx) { } @Override + @DebugLog public void onLikeButtonClick(int idx, boolean checked) { changeFavorite(getSwitch(idx), checked); } @Override + @DebugLog public void onColorButtonClick(final int idx) { ColorPickerDialog colorDialog = new ColorPickerDialog( mContext, idx); colorDialog.show(); colorDialog.onDismissListener(new ColorPickerDialog.DismissListener() { @Override + @DebugLog public void onDismiss(final int selectedColor) { if (getDevice(idx).isProtected()) { PasswordDialog passwordDialog = new PasswordDialog( @@ -459,6 +490,7 @@ public void onDismiss(final int selectedColor) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setColor(selectedColor, idx, password); } @@ -468,6 +500,7 @@ public void onDismiss(String password) { } @Override + @DebugLog public void onChangeColor(final int selectedColor) { if (!getDevice(idx).isProtected()) { setColor(selectedColor, idx, null); @@ -497,30 +530,35 @@ private void setColor(int selectedColor, final int idx, final String password) { password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.color_set) + ": " + getDevice(idx).getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.color_set) + ": " + getDevice(idx).getName(), Snackbar.LENGTH_SHORT); //processDashboard(); } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_color), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_color, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onTimerButtonClick(int idx) { } @Override + @DebugLog public void onNotificationButtonClick(int idx) { } @Override + @DebugLog public void onThermostatClick(final int idx) { addDebugText("onThermostatClick"); final DevicesInfo tempUtil = getDevice(idx); @@ -532,6 +570,7 @@ public void onThermostatClick(final int idx) { tempDialog.onDismissListener(new TemperatureDialog.DialogActionListener() { @Override + @DebugLog public void onDialogAction(final double newSetPoint, DialogAction dialogAction) { addDebugText("Set idx " + idx + " to " + String.valueOf(newSetPoint)); if (dialogAction == DialogAction.POSITIVE) { @@ -541,6 +580,7 @@ public void onDialogAction(final double newSetPoint, DialogAction dialogAction) passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(final String password) { int jsonUrl = Domoticz.Json.Url.Set.TEMP; int action = Domoticz.Device.Thermostat.Action.PLUS; @@ -549,14 +589,16 @@ public void onDismiss(final String password) { mDomoticz.setAction(idx, jsonUrl, action, newSetPoint, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); processDashboard(); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); } }); } @@ -569,12 +611,14 @@ public void onError(Exception error) { mDomoticz.setAction(idx, jsonUrl, action, newSetPoint, null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); processDashboard(); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -588,18 +632,21 @@ public void onError(Exception error) { } @Override + @DebugLog public void onSetTemperatureClick(final int idx) { addDebugText("onSetTemperatureClick"); final DevicesInfo tempUtil = getDevice(idx); if (tempUtil != null) { final setCommandReceiver commandReceiver = new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); processDashboard(); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -621,6 +668,7 @@ public void onError(Exception error) { tempDialog.onDismissListener(new TemperatureDialog.DialogActionListener() { @Override + @DebugLog public void onDialogAction(double newSetPoint, DialogAction dialogAction) { if (dialogAction == DialogAction.POSITIVE) { addDebugText("Set idx " + idx + " to " + String.valueOf(newSetPoint)); @@ -649,6 +697,7 @@ public void onDialogAction(double newSetPoint, DialogAction dialogAction) { } @Override + @DebugLog public void onSecurityPanelButtonClick(int idx) { SecurityPanelDialog securityDialog = new SecurityPanelDialog( mContext, mDomoticz, @@ -657,6 +706,7 @@ public void onSecurityPanelButtonClick(int idx) { securityDialog.onDismissListener(new SecurityPanelDialog.DismissListener() { @Override + @DebugLog public void onDismiss() { processDashboard();//refresh } @@ -664,12 +714,14 @@ public void onDismiss() { } @Override + @DebugLog public void onStateButtonClick(final int idx, int itemsRes, final int[] stateIds) { new MaterialDialog.Builder(mContext) .title(R.string.choose_status) .items(itemsRes) .itemsCallback(new MaterialDialog.ListCallback() { @Override + @DebugLog public void onSelection(MaterialDialog dialog, View view, final int which, CharSequence text) { if (getDevice(idx).isProtected()) { PasswordDialog passwordDialog = new PasswordDialog( @@ -677,6 +729,7 @@ public void onSelection(MaterialDialog dialog, View view, final int which, CharS passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setState(idx, stateIds[which], password); } @@ -689,12 +742,14 @@ public void onDismiss(String password) { } @Override + @DebugLog public void onSelectorDimmerClick(final int idx, final String[] levelNames) { new MaterialDialog.Builder(mContext) .title(R.string.choose_status) .items(levelNames) .itemsCallback(new MaterialDialog.ListCallback() { @Override + @DebugLog public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { for (int i = 0; i < levelNames.length; i++) { if (levelNames[i].equals(text)) { @@ -707,11 +762,13 @@ public void onSelection(MaterialDialog dialog, View view, int which, CharSequenc } @Override + @DebugLog public void onItemClicked(View v, int position) { } @Override + @DebugLog public boolean onItemLongClicked(int position) { showInfoDialog(adapter.filteredData.get(position)); return true; @@ -724,15 +781,17 @@ private void setState(final int idx, int state, final String password) { password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.state_set) + ": " + getSwitch(idx).getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.state_set) + ": " + getSwitch(idx).getName(), Snackbar.LENGTH_SHORT); processDashboard(); } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -750,6 +809,7 @@ private DevicesInfo getSwitch(int idx) { } @Override + @DebugLog public void onBlindClick(final int idx, final int jsonAction) { if (busy) return; @@ -763,6 +823,7 @@ public void onBlindClick(final int idx, final int jsonAction) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setBlindState(clickedSwitch, jsonAction, password); } @@ -774,29 +835,26 @@ public void onDismiss(String password) { private void setBlindState(final DevicesInfo clickedSwitch, final int jsonAction, final String password) { if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); clickedSwitch.setStatus(Domoticz.Device.Blind.State.OPEN); - } - else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) { + } else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) { clickedSwitch.setStatus(Domoticz.Device.Blind.State.CLOSED); - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - } - else if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } else if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) { clickedSwitch.setStatus(Domoticz.Device.Blind.State.CLOSED); - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - } - else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) { clickedSwitch.setStatus(Domoticz.Device.Blind.State.OPEN); - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - } - else { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } else { clickedSwitch.setStatus(Domoticz.Device.Blind.State.STOPPED); - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_stop) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_stop) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); } int jsonUrl = Domoticz.Json.Url.Set.SWITCHES; mDomoticz.setAction(clickedSwitch.getIdx(), jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); //processDashboard(); @@ -804,9 +862,10 @@ public void onReceiveResult(String result) { } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -834,6 +893,7 @@ private void changeAdapterData(DevicesInfo clickedSwitch) { } @Override + @DebugLog public void onDimmerChange(int idx, final int value, final boolean selector) { if (busy) return; @@ -846,6 +906,7 @@ public void onDimmerChange(int idx, final int value, final boolean selector) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setDimmerState(clickedSwitch, value, selector, password); } @@ -860,13 +921,14 @@ private void setDimmerState(DevicesInfo clickedSwitch, int value, final boolean String text = String.format(mContext.getString(R.string.set_level_switch), clickedSwitch.getName(), !selector ? (value - 1) : ((value) / 10) + 1); - Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, text, Snackbar.LENGTH_SHORT); int jsonUrl = Domoticz.Json.Url.Set.SWITCHES; int jsonAction = Domoticz.Device.Dimmer.Action.DIM_LEVEL; mDomoticz.setAction(clickedSwitch.getIdx(), jsonUrl, jsonAction, !selector ? (value) : (value) + 10, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); if (selector) @@ -874,9 +936,10 @@ public void onReceiveResult(String result) { } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -884,13 +947,14 @@ public void onError(Exception error) { } } - @Override + @DebugLog public void onPause() { super.onPause(); } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Events.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Events.java index 2241cb43c..aecdba43e 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Events.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Events.java @@ -28,14 +28,15 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; -import nl.hnogames.domoticz.Adapters.DashboardAdapter; import nl.hnogames.domoticz.Adapters.EventsAdapter; import nl.hnogames.domoticz.Containers.EventInfo; import nl.hnogames.domoticz.Interfaces.DomoticzFragmentListener; import nl.hnogames.domoticz.Interfaces.EventReceiver; import nl.hnogames.domoticz.Interfaces.EventsClickListener; import nl.hnogames.domoticz.R; +import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.app.DomoticzRecyclerFragment; public class Events extends DomoticzRecyclerFragment implements DomoticzFragmentListener { @@ -45,6 +46,7 @@ public class Events extends DomoticzRecyclerFragment implements DomoticzFragment private String filter = ""; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -52,13 +54,16 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_events); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_events); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -71,6 +76,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processUserVariables(); @@ -81,13 +87,15 @@ private void processUserVariables() { mSwipeRefreshLayout.setRefreshing(true); mDomoticz.getEvents(new EventReceiver() { @Override + @DebugLog public void onReceiveEvents(final ArrayList mEventInfos) { successHandling(mEventInfos.toString(), false); adapter = new EventsAdapter(mContext, mDomoticz, mEventInfos, new EventsClickListener() { @Override + @DebugLog public void onEventClick(final int id, boolean action) { - Snackbar.make(coordinatorLayout, R.string.action_not_supported_yet, Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.action_not_supported_yet, Snackbar.LENGTH_SHORT); } }); @@ -95,6 +103,7 @@ public void onEventClick(final int id, boolean action) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -109,6 +118,7 @@ private void createListView() { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processUserVariables(); } @@ -119,6 +129,7 @@ public void onRefresh() { } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Graph.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Graph.java index abbff5fb9..8899e34ad 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Graph.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Graph.java @@ -45,6 +45,7 @@ import java.util.Calendar; import java.util.List; +import hugo.weaving.DebugLog; import lecho.lib.hellocharts.model.Axis; import lecho.lib.hellocharts.model.AxisValue; import lecho.lib.hellocharts.model.ComboLineColumnChartData; @@ -86,6 +87,7 @@ public class Graph extends Fragment implements DomoticzFragmentListener { @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); this.context = context; @@ -93,6 +95,7 @@ public void onAttach(Context context) { } @Override + @DebugLog public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); @@ -114,6 +117,7 @@ public void finish() { } @Override + @DebugLog public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -125,6 +129,7 @@ public View onCreateView(LayoutInflater inflater, } @Override + @DebugLog public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); } @@ -135,20 +140,27 @@ public void getGraphs() { mDomoticz.getGraphData(idx, range, type, new GraphDataReceiver() { @Override + @DebugLog public void onReceive(ArrayList grphPoints) { - mGraphList = grphPoints; - ComboLineColumnChartData columnData = generateData(root); - if (columnData == null) - finish(); - else { - chart.setComboLineColumnChartData(columnData); - setViewPort(chart); - getActivity().invalidateOptionsMenu(); + try { + mGraphList = grphPoints; + ComboLineColumnChartData columnData = generateData(root); + if (columnData == null) + finish(); + else { + chart.setComboLineColumnChartData(columnData); + setViewPort(chart); + + if (getActivity() != null) + getActivity().invalidateOptionsMenu(); + } + } catch (Exception ex) { } } @Override - public void onError(Exception error) { + @DebugLog + public void onError(Exception ex) { // Let's check if were still attached to an activity if (isAdded()) { ((GraphActivity) getActivity()).noGraphFound(); @@ -177,6 +189,7 @@ public ActionBar getActionBar() { } @Override + @DebugLog public void onConnectionOk() { if (getView() != null) { getGraphs(); @@ -538,6 +551,7 @@ private void addLabelFilters(String label) { } @Override + @DebugLog public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { if (lineLabels != null && lineLabels.size() > 1) { inflater.inflate(R.menu.menu_graph_sort, menu); @@ -546,6 +560,7 @@ public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { } @Override + @DebugLog public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_sort: @@ -557,6 +572,7 @@ public boolean onOptionsItemSelected(MenuItem item) { .items(items) .itemsCallbackMultiChoice(selectedFilters, new MaterialDialog.ListCallbackMultiChoice() { @Override + @DebugLog public boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text) { selectedFilters = which; enableFilters = true; diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Logs.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Logs.java index d345416aa..5450ffb62 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Logs.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Logs.java @@ -27,6 +27,7 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.LogAdapter; import nl.hnogames.domoticz.Containers.LogInfo; @@ -42,6 +43,7 @@ public class Logs extends DomoticzRecyclerFragment implements DomoticzFragmentLi private String filter = ""; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -49,13 +51,16 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_logs); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_logs); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -68,6 +73,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processLogs(); @@ -78,6 +84,7 @@ private void processLogs() { mSwipeRefreshLayout.setRefreshing(true); mDomoticz.getLogs(new LogsReceiver() { @Override + @DebugLog public void onReceiveLogs(ArrayList mLogInfos) { successHandling(mLogInfos.toString(), false); adapter = new LogAdapter(mContext, mDomoticz, mLogInfos); @@ -85,6 +92,7 @@ public void onReceiveLogs(ArrayList mLogInfos) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -98,6 +106,7 @@ private void createListView() { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processLogs(); } @@ -108,11 +117,13 @@ public void onRefresh() { } @Override + @DebugLog public void onPause() { super.onPause(); } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Plans.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Plans.java index 00f9c6969..5b195585d 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Plans.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Plans.java @@ -93,12 +93,12 @@ public int compare(PlanInfo left, PlanInfo right) { } }); - mAdapter = new PlansAdapter(plans, getActivity()); + mAdapter = new PlansAdapter(plans, mContext); mAdapter.setOnItemClickListener(new PlansAdapter.onClickListener() { @Override public void onItemClick(int position, View v) { //Toast.makeText(getActivity(), "Clicked " + mPlans.get(position).getName(), Toast.LENGTH_SHORT).show(); - Intent intent = new Intent(getActivity(), PlanActivity.class); + Intent intent = new Intent(mContext, PlanActivity.class); //noinspection SpellCheckingInspection intent.putExtra("PLANNAME", mPlans.get(position).getName()); //noinspection SpellCheckingInspection @@ -122,7 +122,8 @@ public void onAttach(Context context) { super.onAttach(context); mContext = context; mSharedPrefs = new SharedPrefUtil(mContext); - getActionBar().setTitle(R.string.title_plans); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_plans); } @Override @@ -136,16 +137,15 @@ public void errorHandling(Exception error) { } public ActionBar getActionBar() { - return ((AppCompatActivity) getActivity()).getSupportActionBar(); + return getActivity() != null ? ((AppCompatActivity) getActivity()).getSupportActionBar() : null; } @Override public void onConnectionOk() { mRecyclerView = (RecyclerView) getView().findViewById(R.id.my_recycler_view); mRecyclerView.setHasFixedSize(true); - GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2); + GridLayoutManager mLayoutManager = new GridLayoutManager(mContext, 2); mRecyclerView.setLayoutManager(mLayoutManager); - processPlans(); } } \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Scenes.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Scenes.java index 29bc87a99..6404df1f3 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Scenes.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Scenes.java @@ -34,6 +34,7 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.SceneAdapter; import nl.hnogames.domoticz.Containers.SceneInfo; @@ -48,6 +49,7 @@ import nl.hnogames.domoticz.UI.PasswordDialog; import nl.hnogames.domoticz.UI.SceneInfoDialog; import nl.hnogames.domoticz.UI.SwitchLogInfoDialog; +import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.Utils.WidgetUtils; import nl.hnogames.domoticz.app.DomoticzRecyclerFragment; @@ -65,14 +67,17 @@ public class Scenes extends DomoticzRecyclerFragment implements DomoticzFragment private Animation animShow, animHide; @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_scenes); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_scenes); initAnimation(); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -90,6 +95,7 @@ private void initAnimation() { } @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -97,6 +103,7 @@ public void refreshFragment() { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processScenes(); @@ -111,17 +118,20 @@ private void processScenes() { mDomoticz.getScenes(new ScenesReceiver() { @Override + @DebugLog public void onReceiveScenes(ArrayList scenes) { successHandling(scenes.toString(), false); createListView(scenes); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @Override + @DebugLog public void onReceiveScene(SceneInfo scene) { } }); @@ -138,13 +148,15 @@ public void createListView(final ArrayList scenes) { if (super.getSort().equals(null) || super.getSort().length() <= 0 || super.getSort().equals(getContext().getString(R.string.filterOn_all))) { supportedScenes.add(s); } else { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.filter_on) + ": " + super.getSort(), Snackbar.LENGTH_SHORT).show(); - if ((super.getSort().equals(getContext().getString(R.string.filterOn_on)) && s.getStatusInBoolean()) && mDomoticz.isOnOffScene(s)) - supportedScenes.add(s); - if ((super.getSort().equals(getContext().getString(R.string.filterOn_off)) && !s.getStatusInBoolean()) && mDomoticz.isOnOffScene(s)) - supportedScenes.add(s); - if ((super.getSort().equals(getContext().getString(R.string.filterOn_static))) && !mDomoticz.isOnOffScene(s)) - supportedScenes.add(s); + if (mContext != null) { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.filter_on) + ": " + super.getSort(), Snackbar.LENGTH_SHORT); + if ((super.getSort().equals(getContext().getString(R.string.filterOn_on)) && s.getStatusInBoolean()) && mDomoticz.isOnOffScene(s)) + supportedScenes.add(s); + if ((super.getSort().equals(getContext().getString(R.string.filterOn_off)) && !s.getStatusInBoolean()) && mDomoticz.isOnOffScene(s)) + supportedScenes.add(s); + if ((super.getSort().equals(getContext().getString(R.string.filterOn_static))) && !mDomoticz.isOnOffScene(s)) + supportedScenes.add(s); + } } } @@ -154,6 +166,7 @@ public void createListView(final ArrayList scenes) { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processScenes(); } @@ -191,6 +204,7 @@ private void showInfoDialog(final SceneInfo mSceneInfo) { infoDialog.onDismissListener(new SceneInfoDialog.DismissListener() { @Override + @DebugLog public void onDismiss(boolean isChanged, boolean isFavorite) { if (isChanged) changeFavorite(mSceneInfo, isFavorite); } @@ -202,9 +216,9 @@ private void changeFavorite(final SceneInfo mSceneInfo, final boolean isFavorite addDebugText("Set idx " + mSceneInfo.getIdx() + " favorite to " + isFavorite); if (isFavorite) - Snackbar.make(coordinatorLayout, mSceneInfo.getName() + " " + getActivity().getString(R.string.favorite_added), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mSceneInfo.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mSceneInfo.getName() + " " + getActivity().getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mSceneInfo.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.SCENEFAVORITE; @@ -214,12 +228,14 @@ private void changeFavorite(final SceneInfo mSceneInfo, final boolean isFavorite mDomoticz.setAction(mSceneInfo.getIdx(), jsonUrl, jsonAction, 0, null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); mSceneInfo.setFavoriteBoolean(isFavorite); } @Override + @DebugLog public void onError(Exception error) { // Domoticz always gives an error: ignore errorHandling(error); @@ -229,6 +245,7 @@ public void onError(Exception error) { @Override + @DebugLog public void onSceneClick(int idx, final boolean action) { addDebugText("onSceneClick"); addDebugText("Set " + idx + " to " + action); @@ -239,6 +256,7 @@ public void onSceneClick(int idx, final boolean action) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setScene(clickedScene, action, password); } @@ -249,26 +267,31 @@ public void onDismiss(String password) { } @Override + @DebugLog public void onLikeButtonClick(int idx, boolean checked) { changeFavorite(getScene(idx), checked); } @Override + @DebugLog public void onLogButtonClick(int idx) { mDomoticz.getSceneLogs(idx, new SwitchLogReceiver() { @Override + @DebugLog public void onReceiveSwitches(ArrayList switchesLogs) { showLogDialog(switchesLogs); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, getContext().getString(R.string.error_logs), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_logs, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onItemClicked(View v, int position) { LinearLayout extra_panel = (LinearLayout) v.findViewById(R.id.extra_panel); if (extra_panel != null) { @@ -294,6 +317,7 @@ public void onItemClicked(View v, int position) { } @Override + @DebugLog public boolean onItemLongClicked(int position) { showInfoDialog(adapter.filteredData.get(position)); return true; @@ -313,9 +337,9 @@ private void showLogDialog(ArrayList switchLogs) { public void setScene(SceneInfo clickedScene, boolean action, String password) { if (action) - Snackbar.make(coordinatorLayout, getActivity().getString(R.string.switch_on) + ": " + clickedScene.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedScene.getName(), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, getActivity().getString(R.string.switch_off) + ": " + clickedScene.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedScene.getName(), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.SCENES; @@ -325,11 +349,13 @@ public void setScene(SceneInfo clickedScene, boolean action, String password) { mDomoticz.setAction(clickedScene.getIdx(), jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { processScenes(); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -337,12 +363,14 @@ public void onError(Exception error) { } @Override + @DebugLog public void onPause() { super.onPause(); } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Switches.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Switches.java index b8e6d1242..3a359aafe 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Switches.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Switches.java @@ -39,6 +39,7 @@ import java.util.ArrayList; import java.util.List; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.SwitchesAdapter; import nl.hnogames.domoticz.Containers.DevicesInfo; @@ -80,6 +81,7 @@ public class Switches extends DomoticzRecyclerFragment implements DomoticzFragme private Animation animShow, animHide; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -87,14 +89,18 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_switches); + + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_switches); initAnimation(); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -107,6 +113,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); getSwitchesData(); @@ -129,6 +136,7 @@ private void getSwitchesData() { mDomoticz.getDevices(new DevicesReceiver() { @Override + @DebugLog public void onReceiveDevices(ArrayList mDevicesInfo) { extendedStatusSwitches = mDevicesInfo; successHandling(mDevicesInfo.toString(), false); @@ -136,10 +144,12 @@ public void onReceiveDevices(ArrayList mDevicesInfo) { } @Override + @DebugLog public void onReceiveDevice(DevicesInfo mDevicesInfo) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -167,15 +177,17 @@ private void createListView(ArrayList switches) { if (UsefulBits.isEmpty(super.getSort()) || super.getSort().equals(mContext.getString(R.string.filterOn_all))) { supportedSwitches.add(mDevicesInfo); } else { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.filter_on) + ": " + super.getSort(), Snackbar.LENGTH_SHORT).show(); - if ((super.getSort().equals(mContext.getString(R.string.filterOn_on)) && mDevicesInfo.getStatusBoolean()) && mDomoticz.isOnOffSwitch(mDevicesInfo)) { - supportedSwitches.add(mDevicesInfo); - } - if ((super.getSort().equals(mContext.getString(R.string.filterOn_off)) && !mDevicesInfo.getStatusBoolean()) && mDomoticz.isOnOffSwitch(mDevicesInfo)) { - supportedSwitches.add(mDevicesInfo); - } - if ((super.getSort().equals(mContext.getString(R.string.filterOn_static))) && !mDomoticz.isOnOffSwitch(mDevicesInfo)) { - supportedSwitches.add(mDevicesInfo); + if (mContext != null) { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.filter_on) + ": " + super.getSort(), Snackbar.LENGTH_SHORT); + if ((super.getSort().equals(mContext.getString(R.string.filterOn_on)) && mDevicesInfo.getStatusBoolean()) && mDomoticz.isOnOffSwitch(mDevicesInfo)) { + supportedSwitches.add(mDevicesInfo); + } + if ((super.getSort().equals(mContext.getString(R.string.filterOn_off)) && !mDevicesInfo.getStatusBoolean()) && mDomoticz.isOnOffSwitch(mDevicesInfo)) { + supportedSwitches.add(mDevicesInfo); + } + if ((super.getSort().equals(mContext.getString(R.string.filterOn_static))) && !mDomoticz.isOnOffSwitch(mDevicesInfo)) { + supportedSwitches.add(mDevicesInfo); + } } } } @@ -189,6 +201,7 @@ private void createListView(ArrayList switches) { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { getSwitchesData(); } @@ -220,6 +233,7 @@ private void showInfoDialog(final DevicesInfo mSwitch) { infoDialog.show(); infoDialog.onDismissListener(new SwitchInfoDialog.DismissListener() { @Override + @DebugLog public void onDismiss(boolean isChanged, boolean isFavorite) { if (isChanged) changeFavorite(mSwitch, isFavorite); } @@ -269,9 +283,9 @@ private void changeFavorite(final DevicesInfo mSwitch, final boolean isFavorite) addDebugText("Set idx " + mSwitch.getIdx() + " favorite to " + isFavorite); if (isFavorite) - Snackbar.make(coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mSwitch.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.FAVORITE; @@ -281,42 +295,47 @@ private void changeFavorite(final DevicesInfo mSwitch, final boolean isFavorite) mDomoticz.setAction(mSwitch.getIdx(), jsonUrl, jsonAction, 0, null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); mSwitch.setFavoriteBoolean(isFavorite); - //getSwitchesData(); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_favorite), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_favorite, Snackbar.LENGTH_SHORT); } }); - } @Override + @DebugLog public void onLogButtonClick(int idx) { mDomoticz.getSwitchLogs(idx, new SwitchLogReceiver() { @Override + @DebugLog public void onReceiveSwitches(ArrayList switchesLogs) { showLogDialog(switchesLogs); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_logs), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_logs, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onLikeButtonClick(int idx, boolean checked) { changeFavorite(getSwitch(idx), checked); } @Override + @DebugLog public void onColorButtonClick(final int idx) { ColorPickerDialog colorDialog = new ColorPickerDialog( getActivity(), idx); @@ -324,6 +343,7 @@ public void onColorButtonClick(final int idx) { colorDialog.onDismissListener(new ColorPickerDialog.DismissListener() { @Override + @DebugLog public void onDismiss(final int selectedColor) { if (getSwitch(idx).isProtected()) { PasswordDialog passwordDialog = new PasswordDialog( @@ -331,6 +351,7 @@ public void onDismiss(final int selectedColor) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setColor(selectedColor, idx, password); } @@ -340,6 +361,7 @@ public void onDismiss(String password) { } @Override + @DebugLog public void onChangeColor(final int selectedColor) { if (!getSwitch(idx).isProtected()) { setColor(selectedColor, idx, null); @@ -368,61 +390,72 @@ private void setColor(int selectedColor, final int idx, final String password) { password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.color_set) + ": " + getSwitch(idx).getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.color_set) + ": " + getSwitch(idx).getName(), Snackbar.LENGTH_SHORT); } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_color), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_color, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onTimerButtonClick(int idx) { mDomoticz.getSwitchTimers(idx, new SwitchTimerReceiver() { @Override + @DebugLog public void onReceiveSwitchTimers(ArrayList switchTimers) { if (switchTimers != null) showTimerDialog(switchTimers); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_timer), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_timer, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onNotificationButtonClick(int idx) { mDomoticz.getNotifications(idx, new NotificationReceiver() { @Override + @DebugLog public void onReceiveNotifications(ArrayList mNotificationInfos) { if (mNotificationInfos != null) showNotificationDialog(mNotificationInfos); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_timer), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_notifications, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onThermostatClick(int idx) { } @Override + @DebugLog public void onSetTemperatureClick(int idx) { } @Override + @DebugLog public void onSecurityPanelButtonClick(int idx) { SecurityPanelDialog securityDialog = new SecurityPanelDialog( getActivity(), mDomoticz, @@ -431,6 +464,7 @@ public void onSecurityPanelButtonClick(int idx) { securityDialog.onDismissListener(new SecurityPanelDialog.DismissListener() { @Override + @DebugLog public void onDismiss() { getSwitchesData();//refresh } @@ -438,12 +472,14 @@ public void onDismiss() { } @Override + @DebugLog public void onStateButtonClick(final int idx, int itemsRes, final int[] stateIds) { new MaterialDialog.Builder(getActivity()) .title(R.string.choose_status) .items(itemsRes) .itemsCallback(new MaterialDialog.ListCallback() { @Override + @DebugLog public void onSelection(MaterialDialog dialog, View view, final int which, CharSequence text) { if (getSwitch(idx).isProtected()) { PasswordDialog passwordDialog = new PasswordDialog( @@ -451,6 +487,7 @@ public void onSelection(MaterialDialog dialog, View view, final int which, CharS passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setState(idx, stateIds[which], password); } @@ -464,12 +501,14 @@ public void onDismiss(String password) { } @Override + @DebugLog public void onSelectorDimmerClick(final int idx, final String[] levelNames) { new MaterialDialog.Builder(getActivity()) .title(R.string.choose_status) .items(levelNames) .itemsCallback(new MaterialDialog.ListCallback() { @Override + @DebugLog public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) { for (int i = 0; i < levelNames.length; i++) { if (levelNames[i].equals(text)) { @@ -482,6 +521,7 @@ public void onSelection(MaterialDialog dialog, View view, int which, CharSequenc } @Override + @DebugLog public void onItemClicked(View v, int position) { LinearLayout extra_panel = (LinearLayout) v.findViewById(R.id.extra_panel); if (extra_panel != null) { @@ -507,6 +547,7 @@ public void onItemClicked(View v, int position) { } @Override + @DebugLog public boolean onItemLongClicked(int position) { showInfoDialog(adapter.filteredData.get(position)); return true; @@ -519,15 +560,17 @@ private void setState(final int idx, int state, final String password) { password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { - Snackbar.make(coordinatorLayout, mContext.getString(R.string.state_set) + ": " + getSwitch(idx).getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.state_set) + ": " + getSwitch(idx).getName(), Snackbar.LENGTH_SHORT); getSwitchesData(); } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -545,6 +588,7 @@ private DevicesInfo getSwitch(int idx) { } @Override + @DebugLog public void onSwitchClick(int idx, final boolean checked) { if (busy) return; @@ -558,6 +602,7 @@ public void onSwitchClick(int idx, final boolean checked) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { toggleSwitch(clickedSwitch, checked, password); } @@ -569,9 +614,9 @@ public void onDismiss(String password) { private void toggleSwitch(DevicesInfo clickedSwitch, boolean checked, final String password) { if (checked) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); int idx = clickedSwitch.getIdx(); if (clickedSwitch.getIdx() > 0) { @@ -588,15 +633,17 @@ private void toggleSwitch(DevicesInfo clickedSwitch, boolean checked, final Stri mDomoticz.setAction(idx, jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); getSwitchesData(); } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -605,6 +652,7 @@ public void onError(Exception error) { } @Override + @DebugLog public void onButtonClick(int idx, final boolean checked) { if (busy) return; @@ -618,6 +666,7 @@ public void onButtonClick(int idx, final boolean checked) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { toggleButton(clickedSwitch, checked, password); } @@ -628,9 +677,9 @@ public void onDismiss(String password) { private void toggleButton(DevicesInfo clickedSwitch, boolean checked, final String password) { if (checked) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_on) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.switch_off) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); int idx = clickedSwitch.getIdx(); int jsonAction; @@ -641,15 +690,17 @@ private void toggleButton(DevicesInfo clickedSwitch, boolean checked, final Stri mDomoticz.setAction(idx, jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); getSwitchesData(); } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -657,6 +708,7 @@ public void onError(Exception error) { } @Override + @DebugLog public void onBlindClick(final int idx, final int jsonAction) { if (busy) return; @@ -670,6 +722,7 @@ public void onBlindClick(final int idx, final int jsonAction) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setBlindState(clickedSwitch, jsonAction, password); } @@ -680,29 +733,38 @@ public void onDismiss(String password) { } private void setBlindState(DevicesInfo clickedSwitch, int jsonAction, final String password) { - if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - else if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); - else - Snackbar.make(coordinatorLayout, mContext.getString(R.string.blind_stop) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT).show(); + if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) { + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + clickedSwitch.setStatus(Domoticz.Device.Blind.State.OPEN); + } else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() != Domoticz.Device.Type.Value.BLINDINVERTED)) { + clickedSwitch.setStatus(Domoticz.Device.Blind.State.CLOSED); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } else if ((jsonAction == Domoticz.Device.Blind.Action.UP || jsonAction == Domoticz.Device.Blind.Action.OFF) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) { + clickedSwitch.setStatus(Domoticz.Device.Blind.State.CLOSED); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_down) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } else if ((jsonAction == Domoticz.Device.Blind.Action.DOWN || jsonAction == Domoticz.Device.Blind.Action.ON) && (clickedSwitch.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDINVERTED)) { + clickedSwitch.setStatus(Domoticz.Device.Blind.State.OPEN); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_up) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } else { + clickedSwitch.setStatus(Domoticz.Device.Blind.State.STOPPED); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mContext.getString(R.string.blind_stop) + ": " + clickedSwitch.getName(), Snackbar.LENGTH_SHORT); + } int jsonUrl = Domoticz.Json.Url.Set.SWITCHES; mDomoticz.setAction(clickedSwitch.getIdx(), jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); getSwitchesData(); } + @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -710,6 +772,7 @@ public void onError(Exception error) { } @Override + @DebugLog public void onDimmerChange(int idx, final int value, final boolean selector) { if (busy) return; @@ -722,6 +785,7 @@ public void onDimmerChange(int idx, final int value, final boolean selector) { passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setDimmerState(clickedSwitch, value, selector, password); } @@ -736,13 +800,14 @@ private void setDimmerState(DevicesInfo clickedSwitch, int value, final boolean String text = String.format(mContext.getString(R.string.set_level_switch), clickedSwitch.getName(), !selector ? (value - 1) : ((value) / 10) + 1); - Snackbar.make(coordinatorLayout, text, Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, text, Snackbar.LENGTH_SHORT); int jsonUrl = Domoticz.Json.Url.Set.SWITCHES; int jsonAction = Domoticz.Device.Dimmer.Action.DIM_LEVEL; mDomoticz.setAction(clickedSwitch.getIdx(), jsonUrl, jsonAction, !selector ? (value) : (value) + 10, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); if (selector) @@ -750,9 +815,10 @@ public void onReceiveResult(String result) { } @Override + @DebugLog public void onError(Exception error) { if (!UsefulBits.isEmpty(password)) - Snackbar.make(coordinatorLayout, mContext.getString(R.string.security_wrong_code), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.security_wrong_code, Snackbar.LENGTH_SHORT); else errorHandling(error); } @@ -761,11 +827,13 @@ public void onError(Exception error) { } @Override + @DebugLog public void onPause() { super.onPause(); } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Temperature.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Temperature.java index 36481a5e0..e252debfa 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Temperature.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Temperature.java @@ -35,6 +35,7 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.TemperatureAdapter; import nl.hnogames.domoticz.Containers.TemperatureInfo; @@ -48,6 +49,7 @@ import nl.hnogames.domoticz.UI.ScheduledTemperatureDialog; import nl.hnogames.domoticz.UI.TemperatureDialog; import nl.hnogames.domoticz.UI.TemperatureInfoDialog; +import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.app.DomoticzRecyclerFragment; public class Temperature extends DomoticzRecyclerFragment implements DomoticzFragmentListener, TemperatureClickListener { @@ -66,6 +68,7 @@ public class Temperature extends DomoticzRecyclerFragment implements DomoticzFra private ArrayList mTempInfos; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -74,14 +77,17 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_temperature); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_temperature); initAnimation(); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -94,6 +100,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processTemperature(); @@ -110,6 +117,7 @@ private void processTemperature() { mDomoticz.getTemperatures(new TemperatureReceiver() { @Override + @DebugLog public void onReceiveTemperatures(ArrayList mTemperatureInfos) { mTempInfos = mTemperatureInfos; successHandling(mTemperatureInfos.toString(), false); @@ -117,6 +125,7 @@ public void onReceiveTemperatures(ArrayList mTemperatureInfos) } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -131,6 +140,7 @@ private void createListView(ArrayList mTemperatureInfos) { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processTemperature(); } @@ -151,6 +161,7 @@ private void showInfoDialog(final TemperatureInfo mTemperatureInfo) { infoDialog.show(); infoDialog.onDismissListener(new TemperatureInfoDialog.DismissListener() { @Override + @DebugLog public void onDismiss(boolean isChanged, boolean isFavorite) { if (isChanged) changeFavorite(mTemperatureInfo, isFavorite); @@ -163,9 +174,9 @@ private void changeFavorite(final TemperatureInfo mTemperatureInfo, final boolea addDebugText("Set idx " + mTemperatureInfo.getIdx() + " favorite to " + isFavorite); if (isFavorite) - Snackbar.make(coordinatorLayout, mTemperatureInfo.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mTemperatureInfo.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, mTemperatureInfo.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mTemperatureInfo.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.FAVORITE; @@ -175,12 +186,14 @@ private void changeFavorite(final TemperatureInfo mTemperatureInfo, final boolea mDomoticz.setAction(mTemperatureInfo.getIdx(), jsonUrl, jsonAction, 0, null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); mTemperatureInfo.setFavoriteBoolean(isFavorite); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -188,6 +201,7 @@ public void onError(Exception error) { } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity @@ -198,11 +212,13 @@ public void errorHandling(Exception error) { } @Override + @DebugLog public void onPause() { super.onPause(); } @Override + @DebugLog public void onLogClick(final TemperatureInfo temp, final String range) { Intent intent = new Intent(mContext, GraphActivity.class); intent.putExtra("IDX", temp.getIdx()); @@ -211,22 +227,25 @@ public void onLogClick(final TemperatureInfo temp, final String range) { intent.putExtra("STEPS", 3); startActivity(intent); - // Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_log) + ": " + temp.getName(), Snackbar.LENGTH_SHORT).show(); + // Snackbar.mtake(coordinatorLayout, mContext.getString(R.string.error_log) + ": " + temp.getName(), Snackbar.LENGTH_SHORT).show(); } @Override + @DebugLog public void onSetClick(final TemperatureInfo t) { addDebugText("onSetClick"); final int idx = t.getIdx(); final setCommandReceiver commandReceiver = new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); processTemperature(); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -248,6 +267,7 @@ public void onError(Exception error) { tempDialog.onDismissListener(new TemperatureDialog.DialogActionListener() { @Override + @DebugLog public void onDialogAction(double newSetPoint, DialogAction dialogAction) { if (dialogAction == DialogAction.POSITIVE) { addDebugText("Set idx " + idx + " to " + String.valueOf(newSetPoint)); @@ -275,11 +295,13 @@ public void onDialogAction(double newSetPoint, DialogAction dialogAction) { } @Override + @DebugLog public void onLikeButtonClick(int idx, boolean checked) { changeFavorite(getTemperature(idx), checked); } @Override + @DebugLog public void onItemClicked(View v, int position) { LinearLayout extra_panel = (LinearLayout) v.findViewById(R.id.extra_panel); if (extra_panel != null) { @@ -305,6 +327,7 @@ public void onItemClicked(View v, int position) { } @Override + @DebugLog public boolean onItemLongClicked(int position) { showInfoDialog(adapter.filteredData.get(position)); return true; diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/UserVariables.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/UserVariables.java index 1ba90c903..f2e438bf2 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/UserVariables.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/UserVariables.java @@ -5,6 +5,7 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.UserVariablesAdapter; import nl.hnogames.domoticz.Containers.UserVariableInfo; @@ -21,6 +22,7 @@ public class UserVariables extends DomoticzRecyclerFragment implements DomoticzF private String filter = ""; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -28,13 +30,16 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_vars); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_vars); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -47,6 +52,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processUserVariables(); @@ -58,6 +64,7 @@ private void processUserVariables() { mDomoticz.getUserVariables(new UserVariablesReceiver() { @Override + @DebugLog public void onReceiveUserVariables(ArrayList mVarInfos) { UserVariables.this.mUserVariableInfos = mVarInfos; successHandling(mUserVariableInfos.toString(), false); @@ -66,6 +73,7 @@ public void onReceiveUserVariables(ArrayList mVarInfos) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -79,6 +87,7 @@ private void createListView() { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processUserVariables(); } @@ -89,6 +98,7 @@ public void onRefresh() { } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Utilities.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Utilities.java index 8275d4db6..5c9854a87 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Utilities.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Utilities.java @@ -36,6 +36,7 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.UtilityAdapter; import nl.hnogames.domoticz.Containers.SwitchLogInfo; @@ -52,6 +53,7 @@ import nl.hnogames.domoticz.UI.SwitchLogInfoDialog; import nl.hnogames.domoticz.UI.TemperatureDialog; import nl.hnogames.domoticz.UI.UtilitiesInfoDialog; +import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.app.DomoticzRecyclerFragment; public class Utilities extends DomoticzRecyclerFragment implements DomoticzFragmentListener, @@ -66,6 +68,7 @@ public class Utilities extends DomoticzRecyclerFragment implements DomoticzFragm private Animation animShow, animHide; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -73,14 +76,17 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_utilities); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_utilities); initAnimation(); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -93,6 +99,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processUtilities(); @@ -111,6 +118,7 @@ private void processUtilities() { mDomoticz.getUtilities(new UtilitiesReceiver() { @Override + @DebugLog public void onReceiveUtilities(ArrayList mUtilitiesInfos) { successHandling(mUtilitiesInfos.toString(), false); @@ -121,6 +129,7 @@ public void onReceiveUtilities(ArrayList mUtilitiesInfos) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -135,6 +144,7 @@ private void createListView() { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processUtilities(); } @@ -155,6 +165,7 @@ private void showInfoDialog(final UtilitiesInfo mUtilitiesInfo) { infoDialog.show(); infoDialog.onDismissListener(new UtilitiesInfoDialog.DismissListener() { @Override + @DebugLog public void onDismiss(boolean isChanged, boolean isFavorite) { if (isChanged) changeFavorite(mUtilitiesInfo, isFavorite); } @@ -166,13 +177,9 @@ private void changeFavorite(final UtilitiesInfo mUtilitiesInfo, final boolean is addDebugText("Set idx " + mUtilitiesInfo.getIdx() + " favorite to " + isFavorite); if (isFavorite) - Snackbar.make(coordinatorLayout, - mUtilitiesInfo.getName() + " " + mContext.getString(R.string.favorite_added), - Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mUtilitiesInfo.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, - mUtilitiesInfo.getName() + " " + mContext.getString(R.string.favorite_removed), - Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mUtilitiesInfo.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.FAVORITE; @@ -187,12 +194,14 @@ private void changeFavorite(final UtilitiesInfo mUtilitiesInfo, final boolean is null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); mUtilitiesInfo.setFavoriteBoolean(isFavorite); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -227,6 +236,7 @@ private void notifyDataSetChanged() { } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity @@ -237,6 +247,7 @@ public void errorHandling(Exception error) { } @Override + @DebugLog public void onPause() { super.onPause(); } @@ -251,10 +262,12 @@ private UtilitiesInfo getUtility(int idx) { } @Override + @DebugLog public void onClick(UtilitiesInfo utility) { } @Override + @DebugLog public void onLogClick(final UtilitiesInfo utility, final String range) { /* Replace so we get the right log @@ -273,11 +286,10 @@ public void onLogClick(final UtilitiesInfo utility, final String range) { intent.putExtra("TITLE", utility.getSubType().toUpperCase()); intent.putExtra("STEPS", 3); startActivity(intent); - - // Snackbar.make(coordinatorLayout, mContext.getString(R.string.error_log) + ": " + temp.getName(), Snackbar.LENGTH_SHORT).show(); } @Override + @DebugLog public void onThermostatClick(final int idx) { addDebugText("onThermostatClick"); final UtilitiesInfo tempUtil = getUtility(idx); @@ -288,6 +300,7 @@ public void onThermostatClick(final int idx) { tempDialog.onDismissListener(new TemperatureDialog.DialogActionListener() { @Override + @DebugLog public void onDialogAction(final double newSetPoint, DialogAction dialogAction) { if (dialogAction == DialogAction.POSITIVE) { addDebugText("Set idx " + idx + " to " + String.valueOf(newSetPoint)); @@ -298,6 +311,7 @@ public void onDialogAction(final double newSetPoint, DialogAction dialogAction) passwordDialog.show(); passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String password) { setThermostatAction(tempUtil, newSetPoint, password); } @@ -332,12 +346,14 @@ public void setThermostatAction(final UtilitiesInfo tempUtil, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { updateThermostatSetPointValue(tempUtil.getIdx(), thermostatSetPointValue); successHandling(result, false); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -346,28 +362,31 @@ public void onError(Exception error) { @Override + @DebugLog public void onLogButtonClick(int idx) { mDomoticz.getTextLogs(idx, new SwitchLogReceiver() { @Override + @DebugLog public void onReceiveSwitches(ArrayList switchesLogs) { showLogDialog(switchesLogs); } @Override + @DebugLog public void onError(Exception error) { - Snackbar.make(coordinatorLayout, - mContext.getString(R.string.error_logs), - Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, R.string.error_logs, Snackbar.LENGTH_SHORT); } }); } @Override + @DebugLog public void onLikeButtonClick(int idx, boolean checked) { changeFavorite(getUtility(idx), checked); } @Override + @DebugLog public void onItemClicked(View v, int position) { LinearLayout extra_panel = (LinearLayout) v.findViewById(R.id.extra_panel); if (extra_panel != null) { @@ -393,6 +412,7 @@ public void onItemClicked(View v, int position) { } @Override + @DebugLog public boolean onItemLongClicked(int position) { showInfoDialog(adapter.filteredData.get(position)); return true; diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Weather.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Weather.java index c72dabc36..4417a7d2c 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Weather.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Weather.java @@ -12,6 +12,7 @@ import java.util.ArrayList; +import hugo.weaving.DebugLog; import jp.wasabeef.recyclerview.adapters.SlideInBottomAnimationAdapter; import nl.hnogames.domoticz.Adapters.WeatherAdapter; import nl.hnogames.domoticz.Containers.Language; @@ -26,6 +27,7 @@ import nl.hnogames.domoticz.UI.WeatherInfoDialog; import nl.hnogames.domoticz.Utils.AnimationUtil; import nl.hnogames.domoticz.Utils.SharedPrefUtil; +import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.app.DomoticzRecyclerFragment; public class Weather extends DomoticzRecyclerFragment implements DomoticzFragmentListener, WeatherClickListener { @@ -40,6 +42,7 @@ public class Weather extends DomoticzRecyclerFragment implements DomoticzFragmen private ArrayList mWeatherInfoList; @Override + @DebugLog public void refreshFragment() { if (mSwipeRefreshLayout != null) mSwipeRefreshLayout.setRefreshing(true); @@ -47,14 +50,17 @@ public void refreshFragment() { } @Override + @DebugLog public void onAttach(Context context) { super.onAttach(context); mContext = context; - getActionBar().setTitle(R.string.title_weather); + if (getActionBar() != null) + getActionBar().setTitle(R.string.title_weather); initAnimation(); } @Override + @DebugLog public void Filter(String text) { filter = text; try { @@ -67,6 +73,7 @@ public void Filter(String text) { } @Override + @DebugLog public void onConnectionOk() { super.showSpinner(true); processWeather(); @@ -78,6 +85,7 @@ private void processWeather() { mDomoticz.getWeathers(new WeatherReceiver() { @Override + @DebugLog public void onReceiveWeather(ArrayList mWeatherInfos) { mWeatherInfoList = mWeatherInfos; if (getView() != null) { @@ -87,6 +95,7 @@ public void onReceiveWeather(ArrayList mWeatherInfos) { } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -106,6 +115,7 @@ private void createListView(ArrayList mWeatherInfos) { mSwipeRefreshLayout.setRefreshing(false); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override + @DebugLog public void onRefresh() { processWeather(); } @@ -123,6 +133,7 @@ private void showInfoDialog(final WeatherInfo mWeatherInfo) { infoDialog.show(); infoDialog.onDismissListener(new WeatherInfoDialog.DismissListener() { @Override + @DebugLog public void onDismiss(boolean isChanged, boolean isFavorite) { if (isChanged) changeFavorite(mWeatherInfo, isFavorite); @@ -135,17 +146,9 @@ private void changeFavorite(final WeatherInfo mWeatherInfo, final boolean isFavo addDebugText("Set idx " + mWeatherInfo.getIdx() + " favorite to " + isFavorite); if (isFavorite) - Snackbar.make(coordinatorLayout, - mWeatherInfo.getName() - + " " - + mContext.getString(R.string.favorite_added), - Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mWeatherInfo.getName() + " " + mContext.getString(R.string.favorite_added), Snackbar.LENGTH_SHORT); else - Snackbar.make(coordinatorLayout, - mWeatherInfo.getName() - + " " - + mContext.getString(R.string.favorite_removed), - Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(mContext, coordinatorLayout, mWeatherInfo.getName() + " " + mContext.getString(R.string.favorite_removed), Snackbar.LENGTH_SHORT); int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.FAVORITE; @@ -160,12 +163,14 @@ private void changeFavorite(final WeatherInfo mWeatherInfo, final boolean isFavo null, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { successHandling(result, false); mWeatherInfo.setFavoriteBoolean(isFavorite); } @Override + @DebugLog public void onError(Exception error) { errorHandling(error); } @@ -173,6 +178,7 @@ public void onError(Exception error) { } @Override + @DebugLog public void errorHandling(Exception error) { if (error != null) { // Let's check if were still attached to an activity @@ -183,11 +189,13 @@ public void errorHandling(Exception error) { } @Override + @DebugLog public void onPause() { super.onPause(); } @Override + @DebugLog public void onLogClick(final WeatherInfo weather, final String range) { final String graphType = weather.getTypeImg() .toLowerCase() @@ -214,11 +222,13 @@ public void onLogClick(final WeatherInfo weather, final String range) { } @Override + @DebugLog public void onLikeButtonClick(int idx, boolean checked) { changeFavorite(getWeather(idx), checked); } @Override + @DebugLog public void onItemClicked(View v, int position) { LinearLayout extra_panel = (LinearLayout) v.findViewById(R.id.extra_panel); if (extra_panel != null) { @@ -244,6 +254,7 @@ public void onItemClicked(View v, int position) { } @Override + @DebugLog public boolean onItemLongClicked(int position) { showInfoDialog(adapter.filteredData.get(position)); return true; diff --git a/app/src/main/java/nl/hnogames/domoticz/Fragments/Wizard.java b/app/src/main/java/nl/hnogames/domoticz/Fragments/Wizard.java index 971bf8c76..a7d832de3 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Fragments/Wizard.java +++ b/app/src/main/java/nl/hnogames/domoticz/Fragments/Wizard.java @@ -46,6 +46,7 @@ import java.util.ArrayList; import java.util.List; +import hugo.weaving.DebugLog; import nl.hnogames.domoticz.MainActivity; import nl.hnogames.domoticz.R; import nl.hnogames.domoticz.SettingsActivity; @@ -66,6 +67,7 @@ public class Wizard extends Fragment { private final String NFC = "NFC_CARD"; private final String QRCODE = "QRCODE_CARD"; private final String FINISH = "FINISH"; + private final String SPEECH = "SPEECH"; private final String TAG = Wizard.class.getSimpleName(); private final int iSettingsResultCode = 995; @@ -74,6 +76,7 @@ public class Wizard extends Fragment { private Context context; @Override + @DebugLog public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { @@ -81,6 +84,11 @@ public View onCreateView(LayoutInflater inflater, root = (ViewGroup) inflater.inflate(R.layout.fragment_wizard, null); ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.title_wizard); mSharedPrefs = new SharedPrefUtil(getActivity()); + + if (mSharedPrefs.darkThemeEnabled()) { + if ((root.findViewById(R.id.wizard_relativeLayout)) != null) + (root.findViewById(R.id.wizard_relativeLayout)).setBackgroundColor(getResources().getColor(R.color.background_dark)); + } createCards(); return root; } @@ -94,6 +102,7 @@ private void createCards() { mListView.setOnDismissCallback(new OnDismissCallback() { @Override + @DebugLog public void onDismiss(@NonNull Card card, int position) { String cardTag = "Unknown"; try { @@ -123,6 +132,7 @@ public void onDismiss(@NonNull Card card, int position) { if (!mSharedPrefs.isCardCompleted(MULTISERVER)) cardsToGenerate.add(MULTISERVER); if (!mSharedPrefs.isCardCompleted(QRCODE)) cardsToGenerate.add(QRCODE); if (!mSharedPrefs.isCardCompleted(NFC)) cardsToGenerate.add(NFC); + if (!mSharedPrefs.isCardCompleted(SPEECH)) cardsToGenerate.add(SPEECH); if (cardsToGenerate.size() <= 0) cardsToGenerate.add(FINISH); List cards = generateCards(cardsToGenerate); @@ -130,6 +140,15 @@ public void onDismiss(@NonNull Card card, int position) { } public List generateCards(List cardsToGenerate) { + int blueColor = ContextCompat.getColor(context, R.color.md_material_blue_600); + int otherColor = ContextCompat.getColor(context, R.color.md_white_1000); + int titleColorLight = Color.WHITE; + int titleColorOther = Color.GRAY; + + if (mSharedPrefs.darkThemeEnabled()) { + titleColorOther = Color.WHITE; + otherColor = Color.parseColor("#3F3F3F"); + } List cards = new ArrayList<>(); for (String card : cardsToGenerate) { @@ -140,34 +159,39 @@ public List generateCards(List cardsToGenerate) { .withProvider(new CardProvider()) .setLayout(R.layout.material_welcome_card_layout) .setTitle(context.getString(R.string.wizard_welcome)) - .setTitleColor(Color.WHITE) + .setTitleColor(titleColorLight) .setDescription(context.getString(R.string.wizard_welcome_description)) - .setDescriptionColor(Color.WHITE) - .setSubtitleColor(Color.WHITE) - .setBackgroundColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) + .setDescriptionColor(titleColorLight) + .setSubtitleColor(titleColorLight) + .setBackgroundColor(blueColor) .addAction(R.id.ok_button, new WelcomeButtonAction(context) .setText(context.getString(R.string.wizard_button_nice)) - .setTextColor(Color.WHITE) + .setTextColor(titleColorLight) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } }))).endConfig().build()); } + if (card.equalsIgnoreCase(FAVORITE)) { cards.add(new Card.Builder(context) .setTag(FAVORITE) .setDismissible() .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) + .setBackgroundColor(otherColor) .setTitle(context.getString(R.string.wizard_favorites)) + .setTitleColor(titleColorOther) .setDescription(context.getString(R.string.wizard_favorites_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_switches)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { ((MainActivity) getActivity()).changeFragment("nl.hnogames.domoticz.Fragments.Switches"); } @@ -177,6 +201,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -191,12 +216,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_startup)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_startup_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -206,6 +234,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -220,12 +249,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_geo)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_geo_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -235,6 +267,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -249,12 +282,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_nfc)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_nfc_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -264,6 +300,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -278,12 +315,46 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_qrcode)) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_qrcode_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog + public void onActionClicked(View view, Card card) { + startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); + } + })) + .addAction(R.id.right_text_button, new TextViewAction(context) + .setText(context.getString(R.string.wizard_button_done)) + .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) + .setListener(new OnActionClickListener() { + @Override + @DebugLog + public void onActionClicked(View view, Card card) { + card.dismiss(); + } + })) + .endConfig() + .build()); + } + if (card.equalsIgnoreCase(SPEECH)) { + cards.add(new Card.Builder(context) + .setTag(SPEECH) + .setDismissible() + .withProvider(new CardProvider()) + .setLayout(R.layout.material_basic_buttons_card) + .setTitle(context.getString(R.string.wizard_speech)) + .setBackgroundColor(otherColor) + .setDescription(context.getString(R.string.wizard_speech_description)) + .addAction(R.id.left_text_button, new TextViewAction(context) + .setText(context.getString(R.string.wizard_button_settings)) + .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) + .setListener(new OnActionClickListener() { + @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -293,6 +364,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -305,14 +377,18 @@ public void onActionClicked(View view, Card card) { .setTag(WEAR) .setDismissible() .withProvider(new CardProvider()) + .setTitleColor(titleColorOther) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_wear)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_wear_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -322,6 +398,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -336,12 +413,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_notifications)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_notifications_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -351,6 +431,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -365,12 +446,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_multiserver)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_multiserver_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_settings)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { startActivityForResult(new Intent(context, SettingsActivity.class), iSettingsResultCode); } @@ -380,6 +464,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -394,12 +479,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_graph)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_graph_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_utilities)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { ((MainActivity) getActivity()).changeFragment("nl.hnogames.domoticz.Fragments.Utilities"); } @@ -409,6 +497,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -423,12 +512,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_filter)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_filter_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_nice)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { ((MainActivity) getActivity()).changeFragment("nl.hnogames.domoticz.Fragments.Switches"); } @@ -438,6 +530,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -452,12 +545,15 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_widgets)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_widgets_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText("") .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); @@ -468,6 +564,7 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { card.dismiss(); } @@ -482,15 +579,18 @@ public void onActionClicked(View view, Card card) { .withProvider(new CardProvider()) .setLayout(R.layout.material_basic_buttons_card) .setTitle(context.getString(R.string.wizard_menuitem)) + .setTitleColor(titleColorOther) + .setBackgroundColor(otherColor) .setDescription(context.getString(R.string.wizard_menuitem_description)) .addAction(R.id.left_text_button, new TextViewAction(context) .setText(context.getString(R.string.wizard_button_wizard)) .setTextColor(ContextCompat.getColor(context, R.color.md_material_blue_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { mSharedPrefs.removeWizard(); - ((MainActivity) getActivity()).drawNavigationMenu(); + ((MainActivity) getActivity()).drawNavigationMenu(null); ((MainActivity) getActivity()).removeFragmentStack("nl.hnogames.domoticz.Fragments.Wizard"); ((MainActivity) getActivity()).changeFragment("nl.hnogames.domoticz.Fragments.Dashboard"); } @@ -500,9 +600,10 @@ public void onActionClicked(View view, Card card) { .setTextColor(ContextCompat.getColor(context, R.color.material_orange_600)) .setListener(new OnActionClickListener() { @Override + @DebugLog public void onActionClicked(View view, Card card) { mSharedPrefs.removeWizard(); - ((MainActivity) getActivity()).drawNavigationMenu(); + ((MainActivity) getActivity()).drawNavigationMenu(null); ((MainActivity) getActivity()).removeFragmentStack("nl.hnogames.domoticz.Fragments.Wizard"); ((MainActivity) getActivity()).changeFragment("nl.hnogames.domoticz.Fragments.Dashboard"); } diff --git a/app/src/main/java/nl/hnogames/domoticz/GeoSettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/GeoSettingsActivity.java index 5f8395476..1226d4599 100644 --- a/app/src/main/java/nl/hnogames/domoticz/GeoSettingsActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/GeoSettingsActivity.java @@ -109,7 +109,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { // The user picked a place. Place place = PlacePicker.getPlace(this, data); String text = String.format(getString(R.string.geofence_place), place.getName()); - showSimpleSnackbar(text); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, text, Snackbar.LENGTH_SHORT); } } } @@ -119,6 +119,8 @@ protected void onCreate(Bundle savedInstanceState) { mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); @@ -272,34 +274,25 @@ private void showRemoveUndoSnackbar(final LocationInfo locationInfo) { // Show snackbar with undo option String text = String.format(getString(R.string.something_deleted), getString(R.string.geofence)); - Snackbar.make(coordinatorLayout, - text, - Snackbar.LENGTH_LONG) - .setAction(R.string.undo, new View.OnClickListener() { - @Override - public void onClick(View v) { - // User clicked undo button - // Let's undo the action on the list view - addLocationToListView(locationInfo); - } - }) - .setCallback(new Snackbar.Callback() { - @Override - public void onDismissed(Snackbar snackbar, int event) { - super.onDismissed(snackbar, event); - - switch (event) { - case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: - case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: - case Snackbar.Callback.DISMISS_EVENT_MANUAL: - // Snackbar was timed out so let's remove the data from - // shared preferences - removeLocationFromPreferences(locationInfo); - break; - } - } - }) - .show(); + + UsefulBits.showSnackbar(this, coordinatorLayout, text, Snackbar.LENGTH_SHORT, new Snackbar.Callback() { + @Override + public void onDismissed(Snackbar snackbar, int event) { + super.onDismissed(snackbar, event); + switch (event) { + case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: + case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: + case Snackbar.Callback.DISMISS_EVENT_MANUAL: + removeLocationFromPreferences(locationInfo); + break; + } + } + }, new View.OnClickListener() { + @Override + public void onClick(View v) { + addLocationToListView(locationInfo); + } + }, this.getString(R.string.undo)); } private void removeLocationFromListView(LocationInfo locationInfo) { @@ -325,17 +318,13 @@ public void onReceiveSwitches(ArrayList switches) { @Override public void onError(Exception error) { - Snackbar.make(coordinatorLayout, - R.string.unable_to_get_switches, - Snackbar.LENGTH_SHORT) - .setAction(R.string.retry, new View.OnClickListener() { + UsefulBits.showSnackbar(GeoSettingsActivity.this, coordinatorLayout, GeoSettingsActivity.this.getString(R.string.unable_to_get_switches), Snackbar.LENGTH_SHORT, + null, new View.OnClickListener() { @Override public void onClick(View v) { - // User clicked retry button getSwitchesAndShowSwitchesDialog(locationInfo); } - }) - .show(); + }, GeoSettingsActivity.this.getString(R.string.retry)); } }); } @@ -406,10 +395,8 @@ public void onRequestPermissionsResult( private void checkForLocationPermission(final int actionToStart) { if (PermissionsUtil.canAccessLocation(this)) { - // We have permission already! Log.v(TAG, "We have permission, let's go!"); - switch (actionToStart) { case ACTION_GET_LOCATION: getLocationServices(); @@ -419,11 +406,8 @@ private void checkForLocationPermission(final int actionToStart) { startGeofenceService(); break; } - } else { - // No permission, check if the dialog has already been shown to user - if (ActivityCompat.shouldShowRequestPermissionRationale( this, Manifest.permission.ACCESS_FINE_LOCATION) || ActivityCompat.shouldShowRequestPermissionRationale( @@ -431,21 +415,17 @@ private void checkForLocationPermission(final int actionToStart) { // User has declined already somewhere, we should explain why we need this // permission and what's in it for the user - Log.v(TAG, "Should show request permission rationale"); - if (!requestInProgress) { // Request not yet in progress: let's start! requestInProgress = true; - String sb; sb = "Geofencing in Domoticz enables you to switch based on your location" + UsefulBits.newLine(); sb += "For Geofencing to work, Domoticz needs to know the location of your device" + UsefulBits.newLine(); sb += UsefulBits.newLine(); sb += "Enable location permission?"; - AlertDialog.Builder builder = new AlertDialog.Builder(GeoSettingsActivity.this); builder.setTitle("Domoticz requires your permission") .setMessage(sb) @@ -525,19 +505,19 @@ private void startLocationUpdates() { } private void getLocationServices() { - - //noinspection ResourceType - LocationServices.FusedLocationApi.requestLocationUpdates( - mApiClient, mLocationRequest, new LocationListener() { - @Override - public void onLocationChanged(Location location) { - //noinspection ResourceType - currentLocation - = LocationServices.FusedLocationApi.getLastLocation(mApiClient); - } - }); - isLocationUpdatesStarted = true; - + if (mApiClient.isConnected()) { + //noinspection ResourceType + LocationServices.FusedLocationApi.requestLocationUpdates( + mApiClient, mLocationRequest, new LocationListener() { + @Override + public void onLocationChanged(Location location) { + //noinspection ResourceType + currentLocation + = LocationServices.FusedLocationApi.getLastLocation(mApiClient); + } + }); + isLocationUpdatesStarted = true; + } } private void showAddLocationDialog() { @@ -594,10 +574,6 @@ public void onDismissEmpty() { locationDialog.show(); } - private void showSimpleSnackbar(String message) { - Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_SHORT).show(); - } - @Override public boolean onCreateOptionsMenu(Menu menu) { try { @@ -637,8 +613,7 @@ private void startGeofenceService() { if (mSharedPrefs.isGeofenceEnabled()) { mSharedPrefs.enableGeoFenceService(); if (domoticz.isDebugEnabled()) - Snackbar.make(coordinatorLayout, - R.string.starting_geofence_service, Snackbar.LENGTH_LONG).show(); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.starting_geofence_service, Snackbar.LENGTH_SHORT); isGeofenceServiceStarted = true; } } diff --git a/app/src/main/java/nl/hnogames/domoticz/GraphActivity.java b/app/src/main/java/nl/hnogames/domoticz/GraphActivity.java index 77f09c166..ca35d96d3 100644 --- a/app/src/main/java/nl/hnogames/domoticz/GraphActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/GraphActivity.java @@ -37,6 +37,8 @@ protected void onCreate(Bundle savedInstanceState) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); diff --git a/app/src/main/java/nl/hnogames/domoticz/Interfaces/AuthReceiver.java b/app/src/main/java/nl/hnogames/domoticz/Interfaces/AuthReceiver.java new file mode 100644 index 000000000..f6d49ed2a --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Interfaces/AuthReceiver.java @@ -0,0 +1,31 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Interfaces; + +import nl.hnogames.domoticz.Containers.AuthInfo; + +public interface AuthReceiver { + void onReceiveAuthentication(AuthInfo auth); + + void onError(Exception error); +} diff --git a/app/src/main/java/nl/hnogames/domoticz/Interfaces/SpeechClickListener.java b/app/src/main/java/nl/hnogames/domoticz/Interfaces/SpeechClickListener.java new file mode 100644 index 000000000..efbc9a253 --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Interfaces/SpeechClickListener.java @@ -0,0 +1,32 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Interfaces; + + +import nl.hnogames.domoticz.Containers.SpeechInfo; + +public interface SpeechClickListener { + boolean onEnableClick(SpeechInfo speech, boolean checked); + + void onRemoveClick(SpeechInfo speech); +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/Interfaces/UsersReceiver.java b/app/src/main/java/nl/hnogames/domoticz/Interfaces/UsersReceiver.java new file mode 100644 index 000000000..5e6ce483b --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/Interfaces/UsersReceiver.java @@ -0,0 +1,33 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz.Interfaces; + +import java.util.ArrayList; + +import nl.hnogames.domoticz.Containers.UserInfo; + +public interface UsersReceiver { + void onReceiveUsers(ArrayList mUserInfo); + + void onError(Exception error); +} diff --git a/app/src/main/java/nl/hnogames/domoticz/MainActivity.java b/app/src/main/java/nl/hnogames/domoticz/MainActivity.java index 135772f8b..ea7a7fb3d 100644 --- a/app/src/main/java/nl/hnogames/domoticz/MainActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/MainActivity.java @@ -23,58 +23,81 @@ package nl.hnogames.domoticz; import android.content.Intent; +import android.content.pm.PackageInfo; +import android.content.pm.PackageManager; import android.content.res.Configuration; +import android.graphics.Color; import android.os.Build; import android.os.Bundle; +import android.speech.RecognizerIntent; +import android.speech.SpeechRecognizer; import android.support.annotation.NonNull; +import android.support.design.widget.CoordinatorLayout; import android.support.design.widget.Snackbar; +import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; -import android.support.v4.view.GravityCompat; import android.support.v4.view.MenuItemCompat; -import android.support.v4.widget.DrawerLayout; -import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; -import android.support.v7.widget.LinearLayoutManager; -import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; +import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.WindowManager; -import android.widget.LinearLayout; +import android.widget.FrameLayout; import android.widget.TextView; import android.widget.Toast; import com.afollestad.materialdialogs.MaterialDialog; +import com.github.zagum.speechrecognitionview.RecognitionProgressView; +import com.github.zagum.speechrecognitionview.adapters.RecognitionListenerAdapter; import com.google.android.gms.analytics.HitBuilders; import com.google.android.gms.analytics.Tracker; +import com.mikepenz.google_material_typeface_library.GoogleMaterial; +import com.mikepenz.materialdrawer.AccountHeader; +import com.mikepenz.materialdrawer.AccountHeaderBuilder; +import com.mikepenz.materialdrawer.Drawer; +import com.mikepenz.materialdrawer.DrawerBuilder; +import com.mikepenz.materialdrawer.holder.BadgeStyle; +import com.mikepenz.materialdrawer.model.DividerDrawerItem; +import com.mikepenz.materialdrawer.model.PrimaryDrawerItem; +import com.mikepenz.materialdrawer.model.ProfileDrawerItem; +import com.mikepenz.materialdrawer.model.SecondaryDrawerItem; +import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem; +import com.mikepenz.materialdrawer.model.interfaces.IProfile; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Timer; import java.util.TimerTask; import hotchemi.android.rate.AppRate; -import nl.hnogames.domoticz.Adapters.NavigationAdapter; +import hugo.weaving.DebugLog; +import nl.hnogames.domoticz.Containers.ConfigInfo; import nl.hnogames.domoticz.Containers.ExtendedStatusInfo; import nl.hnogames.domoticz.Containers.QRCodeInfo; import nl.hnogames.domoticz.Containers.ServerInfo; import nl.hnogames.domoticz.Containers.ServerUpdateInfo; +import nl.hnogames.domoticz.Containers.SpeechInfo; import nl.hnogames.domoticz.Containers.SwitchInfo; +import nl.hnogames.domoticz.Containers.UserInfo; import nl.hnogames.domoticz.Domoticz.Domoticz; import nl.hnogames.domoticz.Fragments.Cameras; +import nl.hnogames.domoticz.Fragments.Changelog; import nl.hnogames.domoticz.Fragments.Dashboard; import nl.hnogames.domoticz.Fragments.Scenes; import nl.hnogames.domoticz.Fragments.Switches; +import nl.hnogames.domoticz.Interfaces.ConfigReceiver; import nl.hnogames.domoticz.Interfaces.StatusReceiver; import nl.hnogames.domoticz.Interfaces.SwitchesReceiver; import nl.hnogames.domoticz.Interfaces.UpdateVersionReceiver; import nl.hnogames.domoticz.Interfaces.VersionReceiver; import nl.hnogames.domoticz.Interfaces.setCommandReceiver; +import nl.hnogames.domoticz.UI.PasswordDialog; import nl.hnogames.domoticz.UI.SortDialog; import nl.hnogames.domoticz.Utils.PermissionsUtil; import nl.hnogames.domoticz.Utils.ServerUtil; @@ -87,26 +110,37 @@ import nl.hnogames.domoticz.app.DomoticzDashboardFragment; import nl.hnogames.domoticz.app.DomoticzRecyclerFragment; -public class MainActivity extends AppCompatActivity { + +@DebugLog +public class MainActivity extends AppCompatActivity { private final int iQRResultCode = 775; private final int iWelcomeResultCode = 885; private final int iSettingsResultCode = 995; - + public boolean onPhone; + private SharedPrefUtil mSharedPrefs; private String TAG = MainActivity.class.getSimpleName(); - private ActionBarDrawerToggle mDrawerToggle; - private DrawerLayout mDrawer; private String[] fragments; - private SharedPrefUtil mSharedPrefs; private ServerUtil mServerUtil; - private NavigationAdapter mAdapter; private SearchView searchViewAction; - + private Toolbar toolbar; private ArrayList stackFragments = new ArrayList<>(); private Domoticz domoticz; - private boolean onPhone; private Timer cameraRefreshTimer = null; + private Fragment latestFragment = null; + private Drawer drawer; + + private SpeechRecognizer speechRecognizer; + private RecognitionProgressView recognitionProgressView; + private RecognitionListenerAdapter recognitionListener; + private boolean listeningSpeechRecognition = false; + + private boolean fromVoiceWidget = false; + private boolean fromQRCodeWidget = false; + + + @DebugLog public ServerUtil getServerUtil() { if (mServerUtil == null) mServerUtil = new ServerUtil(this); @@ -117,10 +151,21 @@ public ServerUtil getServerUtil() { protected void onCreate(Bundle savedInstanceState) { mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) - setTheme(R.style.AppThemeDark); + setTheme(R.style.AppThemeDarkMain); super.onCreate(savedInstanceState); - setContentView(R.layout.activity_main); + setContentView(R.layout.activity_newmain); + + if (savedInstanceState == null) { + Bundle extras = getIntent().getExtras(); + if(extras != null) { + fromVoiceWidget = extras.getBoolean("VOICE", false); + fromQRCodeWidget = extras.getBoolean("QRCODE", false); + } + } + + toolbar = (Toolbar) findViewById(R.id.toolbar); + setSupportActionBar(toolbar); boolean resolvableError = UsefulBits.checkPlayServicesAvailable(this); if (!resolvableError) this.finish(); @@ -141,28 +186,49 @@ protected void onCreate(Bundle savedInstanceState) { } } + @DebugLog public void buildScreen() { if (mSharedPrefs.isWelcomeWizardSuccess()) { applyLanguage(); + TextView usingTabletLayout = (TextView) findViewById(R.id.tabletLayout); - //noinspection ConstantConditions - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setHomeButtonEnabled(true); + if (usingTabletLayout == null) + onPhone = true; + appRate(); mServerUtil = new ServerUtil(this); domoticz = new Domoticz(this, mServerUtil); - drawNavigationMenu(); - setupMobileDevice(); - checkDomoticzServerUpdate(); - setScheduledTasks(); - checkDownloadedLanguage(); - saveServerConfigToActiveServer(); + if(!fromVoiceWidget && !fromQRCodeWidget) { + setupMobileDevice(); + checkDomoticzServerUpdate(); + setScheduledTasks(); - appRate(); - WidgetUtils.RefreshWidgets(this); + WidgetUtils.RefreshWidgets(this); + UsefulBits.checkDownloadedLanguage(this, mServerUtil, false, false); + AppController.getInstance().resendRegistrationIdToBackend(); - AppController.getInstance().resendRegistrationIdToBackend(); + UsefulBits.getServerConfigForActiveServer(this, false, new ConfigReceiver() { + @Override + @DebugLog + public void onReceiveConfig(ConfigInfo settings) { + drawNavigationMenu(settings); + addFragment(); + openDialogFragment(new Changelog()); + } + + @Override + @DebugLog + public void onError(Exception error) { + drawNavigationMenu(null); + addFragment(); + openDialogFragment(new Changelog()); + } + }, mServerUtil.getActiveServer().getConfigInfo(this)); + } + else{ + addFragment(); + } } else { Intent welcomeWizard = new Intent(this, WelcomeViewActivity.class); startActivityForResult(welcomeWizard, iWelcomeResultCode); @@ -170,47 +236,6 @@ public void buildScreen() { } } - public void drawNavigationMenu() { - TextView usingTabletLayout = (TextView) findViewById(R.id.tabletLayout); - if (usingTabletLayout == null) - onPhone = true; - else { - if (mSharedPrefs.darkThemeEnabled()) { - int color = ContextCompat.getColor(MainActivity.this, R.color.background_dark); - LinearLayout tabletLayoutWrapper = (LinearLayout) findViewById(R.id.tabletLayoutWrapper); - if (color != 0 && tabletLayoutWrapper != null) - tabletLayoutWrapper.setBackgroundColor(color); - } - if (getSupportActionBar() != null) - getSupportActionBar().setDisplayHomeAsUpEnabled(false); - } - - addDrawerItems(); - addFragment(); - } - - private void setScreenAlwaysOn() { - if (mSharedPrefs.getAlwaysOn()) - getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - else - getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); - } - - private void applyLanguage() { - if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) { - // User has set a language in settings - UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); - } - } - - private void checkDownloadedLanguage() { - UsefulBits.checkDownloadedLanguage(this, mServerUtil, false, false); - } - - private void saveServerConfigToActiveServer() { - UsefulBits.saveServerConfigToActiveServer(this, false, false); - } - /* Called when the second activity's finishes */ protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (data != null && resultCode == RESULT_OK) { @@ -221,16 +246,14 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { this.finish(); else { if (mSharedPrefs.darkThemeEnabled()) - setTheme(R.style.AppThemeDark); - + setTheme(R.style.AppThemeDarkMain); buildScreen(); } break; case iSettingsResultCode: mServerUtil = new ServerUtil(this); if (mSharedPrefs.darkThemeEnabled()) - setTheme(R.style.AppThemeDark); - + setTheme(R.style.AppThemeDarkMain); this.recreate(); break; case iQRResultCode: @@ -246,7 +269,8 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } } if (foundQRCode != null && foundQRCode.isEnabled()) { - handleSwitch(foundQRCode.getSwitchIdx(), foundQRCode.getSwitchPassword()); + handleSwitch(foundQRCode.getSwitchIdx(), foundQRCode.getSwitchPassword(), -1); + Toast.makeText(MainActivity.this, getString(R.string.qrcode) + " " + foundQRCode.getName(), Toast.LENGTH_SHORT).show(); } else { if (foundQRCode == null) Toast.makeText(MainActivity.this, getString(R.string.qrcode_new_found), Toast.LENGTH_SHORT).show(); @@ -258,35 +282,55 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } } else if (resultCode == 789) { //reload settings - startActivityForResult(new Intent(this, SettingsActivity.class), this.iSettingsResultCode); + startActivityForResult(new Intent(this, SettingsActivity.class), iSettingsResultCode); } + + if(fromQRCodeWidget) + this.finish(); } - private void handleSwitch(final int idx, final String password) { + private void handleSwitch(final int idx, final String password, final int inputJSONAction) { domoticz = new Domoticz(this, null); domoticz.getSwitches(new SwitchesReceiver() { @Override + @DebugLog public void onReceiveSwitches(ArrayList switches) { for (SwitchInfo s : switches) { if (s.getIdx() == idx) { domoticz.getStatus(idx, new StatusReceiver() { @Override + @DebugLog public void onReceiveStatus(ExtendedStatusInfo extendedStatusInfo) { int jsonAction; int jsonUrl = Domoticz.Json.Url.Set.SWITCHES; - if (extendedStatusInfo.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDS || - extendedStatusInfo.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDPERCENTAGE) { - if (!extendedStatusInfo.getStatusBoolean()) - jsonAction = Domoticz.Device.Switch.Action.OFF; - else - jsonAction = Domoticz.Device.Switch.Action.ON; + + if (inputJSONAction < 0) { + if (extendedStatusInfo.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDS || + extendedStatusInfo.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDPERCENTAGE) { + if (!extendedStatusInfo.getStatusBoolean()) + jsonAction = Domoticz.Device.Switch.Action.OFF; + else + jsonAction = Domoticz.Device.Switch.Action.ON; + } else { + if (!extendedStatusInfo.getStatusBoolean()) + jsonAction = Domoticz.Device.Switch.Action.ON; + else + jsonAction = Domoticz.Device.Switch.Action.OFF; + } } else { - if (!extendedStatusInfo.getStatusBoolean()) - jsonAction = Domoticz.Device.Switch.Action.ON; - else - jsonAction = Domoticz.Device.Switch.Action.OFF; + if (extendedStatusInfo.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDS || + extendedStatusInfo.getSwitchTypeVal() == Domoticz.Device.Type.Value.BLINDPERCENTAGE) { + if (inputJSONAction == 1) + jsonAction = Domoticz.Device.Switch.Action.OFF; + else + jsonAction = Domoticz.Device.Switch.Action.ON; + } else { + if (inputJSONAction == 1) + jsonAction = Domoticz.Device.Switch.Action.ON; + else + jsonAction = Domoticz.Device.Switch.Action.OFF; + } } - switch (extendedStatusInfo.getSwitchTypeVal()) { case Domoticz.Device.Type.Value.PUSH_ON_BUTTON: jsonAction = Domoticz.Device.Switch.Action.ON; @@ -298,18 +342,27 @@ public void onReceiveStatus(ExtendedStatusInfo extendedStatusInfo) { domoticz.setAction(idx, jsonUrl, jsonAction, 0, password, new setCommandReceiver() { @Override + @DebugLog public void onReceiveResult(String result) { Log.d(TAG, result); + if(fromQRCodeWidget) + MainActivity.this.finish(); } @Override + @DebugLog public void onError(Exception error) { + if(fromQRCodeWidget) + MainActivity.this.finish(); } }); } @Override + @DebugLog public void onError(Exception error) { + if(fromQRCodeWidget) + MainActivity.this.finish(); } }); } @@ -317,14 +370,18 @@ public void onError(Exception error) { } @Override + @DebugLog public void onError(Exception error) { + if(fromQRCodeWidget) + MainActivity.this.finish(); } } ); } + @DebugLog public void refreshFragment() { - Fragment f = getVisibleFragment(); + Fragment f = latestFragment; if (f instanceof DomoticzRecyclerFragment) { ((DomoticzRecyclerFragment) f).refreshFragment(); } else if (f instanceof DomoticzCardFragment) @@ -333,6 +390,7 @@ else if (f instanceof DomoticzDashboardFragment) ((DomoticzDashboardFragment) f).refreshFragment(); } + @DebugLog public void removeFragmentStack(String fragment) { if (stackFragments != null) { if (stackFragments.contains(fragment)) @@ -340,6 +398,7 @@ public void removeFragmentStack(String fragment) { } } + @DebugLog public void addFragmentStack(String fragment) { int screenIndex = mSharedPrefs.getStartupScreenIndex(); if (fragment.equals(getResources().getStringArray(R.array.drawer_fragments)[screenIndex])) { @@ -357,10 +416,53 @@ public void addFragmentStack(String fragment) { } } + private void setScreenAlwaysOn() { + if (mSharedPrefs.getAlwaysOn()) + getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + else + getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); + } + + @Override + @DebugLog + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + switch (requestCode) { + case PermissionsUtil.INITIAL_DEVICE_REQUEST: + if (PermissionsUtil.canAccessDeviceState(this)) + AppController.getInstance().StartEasyGCM(); + break; + case PermissionsUtil.INITIAL_CAMERA_REQUEST: + if (PermissionsUtil.canAccessStorage(this)) { + Intent iQRCodeScannerActivity = new Intent(this, QRCodeCaptureActivity.class); + startActivityForResult(iQRCodeScannerActivity, iQRResultCode); + } + break; + case PermissionsUtil.INITIAL_AUDIO_REQUEST: + if (PermissionsUtil.canAccessAudioState(this)) { + startRecognition(); + } + break; + } + } + + @Override + @DebugLog + public void onConfigurationChanged(Configuration newConfig) { + super.onConfigurationChanged(newConfig); + Fragment f = latestFragment; + if ((f instanceof DomoticzDashboardFragment)) { + ((DomoticzDashboardFragment) f).setGridViewLayout(); + } else if (f instanceof DomoticzRecyclerFragment) { + ((DomoticzRecyclerFragment) f).setGridViewLayout(); + } + } + + @DebugLog public void changeFragment(String fragment) { FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); - // tx.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left); - tx.replace(R.id.main, Fragment.instantiate(MainActivity.this, fragment)); + latestFragment = Fragment.instantiate(MainActivity.this, fragment); + tx.replace(R.id.main, latestFragment); tx.commitAllowingStateLoss(); addFragmentStack(fragment); saveScreenToAnalytics(fragment); @@ -369,8 +471,8 @@ public void changeFragment(String fragment) { private void addFragment() { int screenIndex = mSharedPrefs.getStartupScreenIndex(); FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); - //tx.setCustomAnimations(R.anim.enter_from_left, R.anim.exit_to_right, R.anim.enter_from_right, R.anim.exit_to_left); - tx.replace(R.id.main, Fragment.instantiate(MainActivity.this, getResources().getStringArray(R.array.drawer_fragments)[screenIndex])); + latestFragment = Fragment.instantiate(MainActivity.this, getResources().getStringArray(R.array.drawer_fragments)[screenIndex]); + tx.replace(R.id.main, latestFragment); tx.commitAllowingStateLoss(); addFragmentStack(getResources().getStringArray(R.array.drawer_fragments)[screenIndex]); saveScreenToAnalytics(getResources().getStringArray(R.array.drawer_fragments)[screenIndex]); @@ -386,177 +488,225 @@ private void saveScreenToAnalytics(String screen) { } } - @SuppressWarnings("unused") - private void updateDrawerItems() { - String[] drawerActions = mSharedPrefs.getNavigationActions(); - fragments = mSharedPrefs.getNavigationFragments(); - int ICONS[] = mSharedPrefs.getNavigationIcons(); - mAdapter.updateData(drawerActions, ICONS); + private void applyLanguage() { + if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) { + // User has set a language in settings + UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); + } } - /** - * Adds the items to the drawer and registers a click listener on the items - */ - private void addDrawerItems() { - String[] drawerActions = mSharedPrefs.getNavigationActions(); - fragments = mSharedPrefs.getNavigationFragments(); - int ICONS[] = mSharedPrefs.getNavigationIcons(); - - String NAME = getString(R.string.app_name_domoticz); - String WEBSITE = getString(R.string.domoticz_url); - int PROFILE = R.drawable.ic_launcher; + private void setupMobileDevice() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (!PermissionsUtil.canAccessDeviceState(this)) { + requestPermissions(PermissionsUtil.INITIAL_DEVICE_PERMS, PermissionsUtil.INITIAL_DEVICE_REQUEST); + } else { + AppController.getInstance().StartEasyGCM(); + } + } else { + AppController.getInstance().StartEasyGCM(); + } + } - mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout); - RecyclerView mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); - if (mRecyclerView != null) - mRecyclerView.setHasFixedSize(true); // Letting the system know that the list objects are of fixed size + private void appRate() { + if (!BuildConfig.DEBUG) { + AppRate.with(this) + .setInstallDays(0) // default 10, 0 means install day. + .setLaunchTimes(3) // default 10 + .setRemindInterval(2) // default 1 + .monitor(); - mAdapter = new NavigationAdapter(drawerActions, ICONS, NAME, WEBSITE, PROFILE, this); - mAdapter.onClickListener(new NavigationAdapter.ClickListener() { - @Override - public void onClick(View child, int position) { - if (child != null) { - try { - searchViewAction.setQuery("", false); - searchViewAction.clearFocus(); - } catch (Exception e) { - e.printStackTrace(); - } + // Show a dialog if meets conditions + AppRate.showRateDialogIfMeetsConditions(this); + } + } - try { - FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); - tx.replace(R.id.main, - Fragment.instantiate(MainActivity.this, - fragments[position - 1])); - tx.commitAllowingStateLoss(); - addFragmentStack(fragments[position - 1]); - } catch (Exception e) { - e.printStackTrace(); - } + @DebugLog + public void drawNavigationMenu(final ConfigInfo mConfig) { + ConfigInfo config = mConfig; - invalidateOptionsMenu(); - if (onPhone) - mDrawer.closeDrawer(GravityCompat.START); - } - } - }); + if (config == null) + config = mServerUtil.getActiveServer().getConfigInfo(this); - if (mRecyclerView != null) - mRecyclerView.setAdapter(mAdapter); - RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(this); - if (mRecyclerView != null) - mRecyclerView.setLayoutManager(mLayoutManager); + ProfileDrawerItem loggedinAccount = new ProfileDrawerItem().withName("Logged in").withEmail(domoticz.getUserCredentials(Domoticz.Authentication.USERNAME)) + .withIcon(R.drawable.ic_launcher); + if (mSharedPrefs.darkThemeEnabled()) { + loggedinAccount.withSelectedColorRes(R.color.material_indigo_600); + } - setupDrawer(); - } + // Create the AccountHeader + final ConfigInfo finalConfig = config; + AccountHeader headerResult = new AccountHeaderBuilder() + .withActivity(this) + .withHeaderBackground(R.drawable.darkheader) + .addProfiles(loggedinAccount) + .withOnlyMainProfileImageVisible(true) + .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { + @Override + @DebugLog + public boolean onProfileChanged(View view, final IProfile profile, boolean current) { + if (!current) { + if (BuildConfig.LITE_VERSION) { + Toast.makeText(MainActivity.this, getString(R.string.category_account) + " " + getString(R.string.premium_feature), Toast.LENGTH_LONG).show(); + return false; + } else { + PasswordDialog passwordDialog = new PasswordDialog(MainActivity.this, null); + passwordDialog.show(); + passwordDialog.onDismissListener(new PasswordDialog.DismissListener() { + @Override + @DebugLog + public void onDismiss(String password) { + if (UsefulBits.isEmpty(password)) { + UsefulBits.showSimpleSnackbar(MainActivity.this, getFragmentCoordinatorLayout(), R.string.security_wrong_code, Snackbar.LENGTH_SHORT); + drawNavigationMenu(finalConfig); + } else { + for (UserInfo user : finalConfig.getUsers()) { + if (user.getUsername() == profile.getEmail().getText()) { + String md5Pass = UsefulBits.getMd5String(password); + if (md5Pass.equals(user.getPassword())) { + //if correct set credentials in activeserver and recreate drawer + domoticz.setUserCredentials(user.getUsername(), password); + domoticz.LogOff(); + UsefulBits.getServerConfigForActiveServer(MainActivity.this, true, new ConfigReceiver() { + @Override + @DebugLog + public void onReceiveConfig(ConfigInfo settings) { + UsefulBits.showSimpleSnackbar(MainActivity.this, getFragmentCoordinatorLayout(), R.string.user_switch, Snackbar.LENGTH_SHORT); + drawNavigationMenu(finalConfig); + } + + @Override + @DebugLog + public void onError(Exception error) { + } + }, finalConfig); + } else { + UsefulBits.showSimpleSnackbar(MainActivity.this, getFragmentCoordinatorLayout(), R.string.security_wrong_code, Snackbar.LENGTH_SHORT); + drawNavigationMenu(finalConfig); + } + } + } + } + } + }); + } - /** - * Sets the drawer with listeners for open and closed - */ - private void setupDrawer() { - if (onPhone) { - mDrawerToggle = new ActionBarDrawerToggle( - this, mDrawer, R.string.drawer_open, R.string.drawer_close) { - /** - * Called when a mDrawer has settled in a completely open state. - */ - public void onDrawerOpened(View drawerView) { - super.onDrawerOpened(drawerView); - - try { - if (searchViewAction != null) - searchViewAction.clearFocus(); - } catch (Exception e) { - e.printStackTrace(); + drawNavigationMenu(finalConfig); + } + return false; } + }) + .build(); - //getSupportActionBar().setTitle(R.string.drawer_navigation_title); - invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() - } + if (config != null && + config.getUsers() != null) { + for (UserInfo user : config.getUsers()) { + + ProfileDrawerItem profile = new ProfileDrawerItem().withName(user.getRightsValue(this) + ).withEmail(user.getUsername()) + .withIcon(R.drawable.users) + .withEnabled(user.isEnabled()); - /** - * Called when a mDrawer has settled in a completely closed state. - */ - public void onDrawerClosed(View view) { - super.onDrawerClosed(view); - //getSupportActionBar().setTitle(currentTitle); - invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu() + if (mSharedPrefs.darkThemeEnabled()) { + profile.withSelectedColorRes(R.color.material_indigo_600); } - }; - mDrawerToggle.setDrawerIndicatorEnabled(true); // hamburger menu icon - mDrawer.addDrawerListener(mDrawerToggle); // attach hamburger menu icon to drawer + headerResult.addProfiles(profile); + } } - } - @Override - protected void onPostCreate(Bundle savedInstanceState) { - super.onPostCreate(savedInstanceState); - // Sync the toggle state after onRestoreInstanceState has occurred. - if (mDrawerToggle != null) mDrawerToggle.syncState(); - } - - @Override - public void onConfigurationChanged(Configuration newConfig) { - super.onConfigurationChanged(newConfig); - if (mDrawerToggle != null) mDrawerToggle.onConfigurationChanged(newConfig); - } + drawer = new DrawerBuilder() + .withActivity(this) + .withTranslucentStatusBar(false) + .withActionBarDrawerToggle(true) + .withAccountHeader(headerResult) + .withToolbar(toolbar) + .withSelectedItem(-1) + .withDrawerItems(getDrawerItems()) + .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { + @Override + @DebugLog + public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { + if (drawerItem != null) { + if (searchViewAction != null) { + searchViewAction.setQuery("", false); + searchViewAction.clearFocus(); + } - public Fragment getVisibleFragment() { - try { - FragmentManager fragmentManager = MainActivity.this.getSupportFragmentManager(); - List fragments = fragmentManager.getFragments(); - for (Fragment fragment : fragments) { - if (fragment != null && fragment.isVisible()) - return fragment; - } + if (drawerItem.getTag() != null && String.valueOf(drawerItem.getTag()).equals("Settings")) { + stopCameraTimer(); + startActivityForResult(new Intent(MainActivity.this, SettingsActivity.class), iSettingsResultCode); + } else if (drawerItem.getTag() != null) { + try { + latestFragment = Fragment.instantiate(MainActivity.this, + String.valueOf(drawerItem.getTag())); + FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); + tx.replace(R.id.main, + latestFragment); + tx.commitAllowingStateLoss(); + addFragmentStack(String.valueOf(drawerItem.getTag())); + } catch (Exception e) { + e.printStackTrace(); + } + stopCameraTimer(); + + invalidateOptionsMenu(); + if (onPhone) + drawer.closeDrawer(); + } + } + return false; + } + }) + .build(); - return null; - } catch (Exception ex) { - return null; - } + drawer.addStickyFooterItem(createSecondaryDrawerItem(this.getString(R.string.action_settings), null, "gmd_settings", "Settings")); } - private void appRate() { - if (!BuildConfig.DEBUG) { - AppRate.with(this) - .setInstallDays(0) // default 10, 0 means install day. - .setLaunchTimes(3) // default 10 - .setRemindInterval(2) // default 1 - .monitor(); + private List getDrawerItems() { + List drawerItems = new ArrayList<>(); + String[] drawerActions = mSharedPrefs.getNavigationActions(); + fragments = mSharedPrefs.getNavigationFragments(); + String ICONS[] = mSharedPrefs.getNavigationIcons(); - // Show a dialog if meets conditions - AppRate.showRateDialogIfMeetsConditions(this); - } + for (int i = 0; i < drawerActions.length; i++) + if (fragments[i].indexOf("Wizard") >= 0 || fragments[i].indexOf("Dashboard") >= 0) + drawerItems.add(createPrimaryDrawerItem(drawerActions[i], null, ICONS[i], fragments[i])); + drawerItems.add(new DividerDrawerItem()); + for (int i = 0; i < drawerActions.length; i++) + if (fragments[i].indexOf("Wizard") < 0 && fragments[i].indexOf("Dashboard") < 0) + drawerItems.add(createSecondaryDrawerItem(drawerActions[i], null, ICONS[i], fragments[i])); + + return drawerItems; } - private void setupMobileDevice() { - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { - if (!PermissionsUtil.canAccessDeviceState(this)) { - requestPermissions(PermissionsUtil.INITIAL_DEVICE_PERMS, PermissionsUtil.INITIAL_DEVICE_REQUEST); - } else { - AppController.getInstance().StartEasyGCM(); - } - } else { - AppController.getInstance().StartEasyGCM(); + private SecondaryDrawerItem createSecondaryDrawerItem(String title, String badge, String icon, String fragmentID) { + SecondaryDrawerItem item = new SecondaryDrawerItem(); + item.withName(title) + .withBadge(badge) + .withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_red_700)) + .withIcon(GoogleMaterial.Icon.valueOf(icon)).withIconColorRes(R.color.material_indigo_600) + .withTag(fragmentID); + + if (mSharedPrefs.darkThemeEnabled()) { + item.withIconColorRes(R.color.white); + item.withSelectedColorRes(R.color.material_indigo_600); } + + return item; } - @Override - public void onRequestPermissionsResult( - int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { - switch (requestCode) { - case PermissionsUtil.INITIAL_DEVICE_REQUEST: - if (PermissionsUtil.canAccessDeviceState(this)) - AppController.getInstance().StartEasyGCM(); - break; - case PermissionsUtil.INITIAL_CAMERA_REQUEST: - if (PermissionsUtil.canAccessStorage(this)) { - Intent iQRCodeScannerActivity = new Intent(this, QRCodeCaptureActivity.class); - startActivityForResult(iQRCodeScannerActivity, iQRResultCode); - } - break; + private PrimaryDrawerItem createPrimaryDrawerItem(String title, String badge, String icon, String fragmentID) { + PrimaryDrawerItem item = new PrimaryDrawerItem(); + item.withName(title).withBadge(badge).withBadgeStyle(new BadgeStyle().withTextColor(Color.WHITE).withColorRes(R.color.md_red_700)) + .withIcon(GoogleMaterial.Icon.valueOf(icon)).withIconColorRes(R.color.material_indigo_600) + .withTag(fragmentID); + + if (mSharedPrefs.darkThemeEnabled()) { + item.withIconColorRes(R.color.white); + item.withSelectedColorRes(R.color.material_indigo_600); } + + return item; } private void checkDomoticzServerUpdate() { @@ -564,6 +714,7 @@ private void checkDomoticzServerUpdate() { // Get latest Domoticz version update domoticz.getUpdate(new UpdateVersionReceiver() { @Override + @DebugLog public void onReceiveUpdate(ServerUpdateInfo serverUpdateInfo) { boolean haveUpdate = serverUpdateInfo.isUpdateAvailable(); @@ -586,6 +737,7 @@ public void onReceiveUpdate(ServerUpdateInfo serverUpdateInfo) { } @Override + @DebugLog public void onError(Exception error) { String message = String.format( getString(R.string.error_couldNotCheckForUpdates), @@ -604,6 +756,7 @@ private void getCurrentServerVersion() { // Get current Domoticz server version domoticz.getServerVersion(new VersionReceiver() { @Override + @DebugLog public void onReceiveVersion(String serverVersion) { if (!UsefulBits.isEmpty(serverVersion)) { @@ -634,6 +787,7 @@ public void onReceiveVersion(String serverVersion) { } @Override + @DebugLog public void onError(Exception error) { String message = String.format( getString(R.string.error_couldNotCheckForUpdates), @@ -644,100 +798,114 @@ public void onError(Exception error) { } private void showSnackBarToUpdateServer(String message) { - View layout = getFragmentCoordinatorLayout(); + CoordinatorLayout layout = getFragmentCoordinatorLayout(); if (layout != null) { - Snackbar.make(layout, message, Snackbar.LENGTH_LONG) - .setAction(R.string.update_server, new View.OnClickListener() { - @Override - public void onClick(View v) { - startActivity(new Intent(MainActivity.this, UpdateActivity.class)); - } - }) - .show(); + UsefulBits.showSnackbar(this, layout, message, Snackbar.LENGTH_SHORT, null, new View.OnClickListener() { + @Override + @DebugLog + public void onClick(View v) { + startActivity(new Intent(MainActivity.this, UpdateActivity.class)); + } + }, this.getString(R.string.update_server)); } } - /** - * Starts the scheduled tasks service via GCM Network manager - * Automatically detects if this has been done before - */ - private void setScheduledTasks() { - UsefulBits.setScheduledTasks(this); - } - - private void showSimpleSnackbar(String message) { - View layout = getFragmentCoordinatorLayout(); - if (layout != null) Snackbar.make(layout, message, Snackbar.LENGTH_SHORT).show(); - else Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); - } - - public View getFragmentCoordinatorLayout() { - View layout = null; - try { - Fragment f = getVisibleFragment(); - if (f != null) { - View v = f.getView(); - if (v != null) - layout = v.findViewById(R.id.coordinatorLayout); - } - } catch (Exception ex) { - Log.e(TAG, "Unable to get the coordinator layout of visible fragment"); - ex.printStackTrace(); - } - return layout; - } + private MenuItem speechMenuItem; @Override + @DebugLog public boolean onCreateOptionsMenu(Menu menu) { - Fragment f = getVisibleFragment(); - - if ((f instanceof Cameras)) { - if (cameraRefreshTimer != null) - getMenuInflater().inflate(R.menu.menu_camera_pause, menu); - else - getMenuInflater().inflate(R.menu.menu_camera, menu); - } else if ((f instanceof DomoticzDashboardFragment) || (f instanceof DomoticzRecyclerFragment)) { - if ((f instanceof Dashboard) || (f instanceof Scenes) || (f instanceof Switches)) - getMenuInflater().inflate(R.menu.menu_main_sort, menu); - else - getMenuInflater().inflate(R.menu.menu_main, menu); - - MenuItem searchMenuItem = menu.findItem(R.id.search); - searchViewAction = (SearchView) MenuItemCompat - .getActionView(searchMenuItem); - searchViewAction.setOnQueryTextListener(new SearchView.OnQueryTextListener() { - @Override - public boolean onQueryTextSubmit(String query) { - return false; - } + Fragment f = latestFragment; + + if(!fromVoiceWidget && !fromQRCodeWidget) + { + if ((f instanceof Cameras)) { + if (cameraRefreshTimer != null) + getMenuInflater().inflate(R.menu.menu_camera_pause, menu); + else + getMenuInflater().inflate(R.menu.menu_camera, menu); + } else if ((f instanceof DomoticzDashboardFragment) || (f instanceof DomoticzRecyclerFragment)) { + if ((f instanceof Dashboard) || (f instanceof Scenes) || (f instanceof Switches)) + getMenuInflater().inflate(R.menu.menu_main_sort, menu); + else + getMenuInflater().inflate(R.menu.menu_main, menu); + + MenuItem searchMenuItem = menu.findItem(R.id.search); + searchViewAction = (SearchView) MenuItemCompat + .getActionView(searchMenuItem); + searchViewAction.setOnQueryTextListener(new SearchView.OnQueryTextListener() { + @Override + @DebugLog + public boolean onQueryTextSubmit(String query) { + return false; + } - @Override - public boolean onQueryTextChange(String newText) { - Fragment n = getVisibleFragment(); - if (n instanceof DomoticzDashboardFragment) { - ((DomoticzDashboardFragment) n).Filter(newText); + @Override + @DebugLog + public boolean onQueryTextChange(String newText) { + Fragment n = latestFragment; + if (n instanceof DomoticzDashboardFragment) { + ((DomoticzDashboardFragment) n).Filter(newText); + } else if (n instanceof DomoticzRecyclerFragment) { + ((DomoticzRecyclerFragment) n).Filter(newText); + } + return false; } - return false; - } - }); - } else - getMenuInflater().inflate(R.menu.menu_simple, menu); - - if (mSharedPrefs.isMultiServerEnabled()) { - //set multi server actionbar item - MenuItem searchMenuItem = menu.findItem(R.id.action_switch_server); - if (searchMenuItem != null && mServerUtil.getEnabledServerList() != null && mServerUtil.getEnabledServerList().size() > 1) { - searchMenuItem.setVisible(true); - } else if (searchMenuItem != null) - searchMenuItem.setVisible(false); - } + }); + } else { + getMenuInflater().inflate(R.menu.menu_simple, menu); + } - if (mSharedPrefs.isQRCodeEnabled()) { - MenuItem searchMenuItem = menu.findItem(R.id.action_scan_qrcode); - if (searchMenuItem != null && mSharedPrefs.getQRCodeList() != null && mSharedPrefs.getQRCodeList().size() > 0) { - searchMenuItem.setVisible(true); - } else if (searchMenuItem != null) - searchMenuItem.setVisible(false); + if (mSharedPrefs.isMultiServerEnabled()) { + //set multi server actionbar item + MenuItem searchMenuItem = menu.findItem(R.id.action_switch_server); + if (searchMenuItem != null && mServerUtil != null && mServerUtil.getEnabledServerList() != null && mServerUtil.getEnabledServerList().size() > 1) { + searchMenuItem.setVisible(true); + } else if (searchMenuItem != null) + searchMenuItem.setVisible(false); + } + + if (mSharedPrefs.isQRCodeEnabled()) { + MenuItem searchMenuItem = menu.findItem(R.id.action_scan_qrcode); + if (searchMenuItem != null && mSharedPrefs != null && mSharedPrefs.getQRCodeList() != null && mSharedPrefs.getQRCodeList().size() > 0) { + searchMenuItem.setVisible(true); + } else if (searchMenuItem != null) + searchMenuItem.setVisible(false); + } + + if (mSharedPrefs.isSpeechEnabled()) { + speechMenuItem = menu.findItem(R.id.action_speech); + if (speechMenuItem != null && mSharedPrefs != null && mSharedPrefs.getSpeechList() != null && mSharedPrefs.getSpeechList().size() > 0) { + speechMenuItem.setVisible(true); + } else if (speechMenuItem != null) + speechMenuItem.setVisible(false); + } + } + else + { + if(fromVoiceWidget) { + getMenuInflater().inflate(R.menu.menu_speech, menu); + if (mSharedPrefs.isSpeechEnabled()) { + speechMenuItem = menu.findItem(R.id.action_speech); + if (speechMenuItem != null && mSharedPrefs != null && mSharedPrefs.getSpeechList() != null && mSharedPrefs.getSpeechList().size() > 0) { + speechMenuItem.setVisible(true); + onOptionsItemSelected(speechMenuItem); + } else if (speechMenuItem != null) + speechMenuItem.setVisible(false); + } + } + else if(fromQRCodeWidget) + { + getMenuInflater().inflate(R.menu.menu_qrcode, menu); + if (mSharedPrefs.isQRCodeEnabled()) { + MenuItem qrcodeMenuItem = menu.findItem(R.id.action_scan_qrcode); + if (qrcodeMenuItem != null && mSharedPrefs != null && mSharedPrefs.getQRCodeList() != null && mSharedPrefs.getQRCodeList().size() > 0) { + qrcodeMenuItem.setVisible(true); + onOptionsItemSelected(qrcodeMenuItem); + } else if (qrcodeMenuItem != null) + qrcodeMenuItem.setVisible(false); + } + } } return super.onCreateOptionsMenu(menu); @@ -745,20 +913,60 @@ public boolean onQueryTextChange(String newText) { @SuppressWarnings("SimplifiableIfStatement") @Override + @DebugLog public boolean onOptionsItemSelected(MenuItem item) { try { switch (item.getItemId()) { + case R.id.action_speech: + if (speechRecognizer == null) + speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this); + if (recognitionProgressView == null) + recognitionProgressView = (RecognitionProgressView) findViewById(R.id.recognition_view); + if (recognitionListener == null) { + recognitionListener = new RecognitionListenerAdapter() { + @Override + public void onResults(Bundle results) { + showSpeechResults(results); + stopRecognition(); + } + }; + } + if (mSharedPrefs.darkThemeEnabled()) { + int color = ContextCompat.getColor(MainActivity.this, R.color.background_dark); + if (color != 0 && recognitionProgressView != null) + recognitionProgressView.setBackgroundColor(color); + } + int[] colors = { + ContextCompat.getColor(this, R.color.material_amber_600), + ContextCompat.getColor(this, R.color.material_blue_600), + ContextCompat.getColor(this, R.color.material_deep_purple_600), + ContextCompat.getColor(this, R.color.material_green_600), + ContextCompat.getColor(this, R.color.material_orange_600) + }; + recognitionProgressView.setColors(colors); + recognitionProgressView.setSpeechRecognizer(speechRecognizer); + recognitionProgressView.setRecognitionListener(recognitionListener); + recognitionProgressView.postDelayed(new Runnable() { + @Override + public void run() { + startRecognition(); + } + }, 50); + + return true; case R.id.action_camera_play: if (cameraRefreshTimer == null) { cameraRefreshTimer = new Timer("camera", true); cameraRefreshTimer.scheduleAtFixedRate(new TimerTask() { @Override + @DebugLog public void run() { runOnUiThread(new Runnable() { @Override + @DebugLog public void run() { //call refresh fragment - Fragment f = getVisibleFragment(); + Fragment f = latestFragment; if (f instanceof Cameras) { ((Cameras) f).refreshFragment(); } else { @@ -790,19 +998,16 @@ public void run() { stopCameraTimer(); invalidateOptionsMenu();//set pause button return true; - case R.id.action_settings: - stopCameraTimer(); - startActivityForResult(new Intent(this, SettingsActivity.class), this.iSettingsResultCode); - return true; case R.id.action_sort: SortDialog infoDialog = new SortDialog( this, R.layout.dialog_switch_logs); infoDialog.onDismissListener(new SortDialog.DismissListener() { @Override + @DebugLog public void onDismiss(String selectedSort) { Log.i(TAG, "Sorting: " + selectedSort); - Fragment f = getVisibleFragment(); + Fragment f = latestFragment; if (f instanceof DomoticzRecyclerFragment) { ((DomoticzRecyclerFragment) f).sortFragment(selectedSort); } else if (f instanceof DomoticzDashboardFragment) { @@ -816,17 +1021,112 @@ public void onDismiss(String selectedSort) { showServerDialog(); return true; } - - // Activate the navigation drawer toggle - if (mDrawerToggle.onOptionsItemSelected(item)) { - return true; - } } catch (Exception ex) { ex.printStackTrace(); } return super.onOptionsItemSelected(item); } + private void playRecognitionAnimation() { + ((FrameLayout) findViewById(R.id.main)).setVisibility(View.GONE); + recognitionProgressView.setVisibility(View.VISIBLE); + recognitionProgressView.play(); + } + + private void stopRecognitionAnimation() { + ((FrameLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE); + recognitionProgressView.setVisibility(View.GONE); + recognitionProgressView.stop(); + } + + @DebugLog + private void showSpeechResults(Bundle results) { + ArrayList matches = results + .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); + + int jsonAction = -1; + String actionFound = "Toggle"; + String SPEECH_ID = matches.get(0).toLowerCase().trim(); + if (mSharedPrefs.isSpeechEnabled()) { + ArrayList qrList = mSharedPrefs.getSpeechList(); + SpeechInfo foundSPEECH = null; + if (qrList != null && qrList.size() > 0) { + for (SpeechInfo n : qrList) { + if (n.getId().equals(SPEECH_ID)) + foundSPEECH = n; + } + } + if (foundSPEECH == null) { + if (SPEECH_ID.endsWith(getString(R.string.button_state_off).toLowerCase())) { + actionFound = getString(R.string.button_state_off); + SPEECH_ID = SPEECH_ID.replace(getString(R.string.button_state_off).toLowerCase(), "").trim(); + jsonAction = 0; + } else if (SPEECH_ID.endsWith(getString(R.string.button_state_on).toLowerCase())) { + actionFound = getString(R.string.button_state_on); + SPEECH_ID = SPEECH_ID.replace(getString(R.string.button_state_on).toLowerCase(), "").trim(); + jsonAction = 1; + } + + if (qrList != null && qrList.size() > 0) { + for (SpeechInfo n : qrList) { + if (n.getId().equals(SPEECH_ID)) + foundSPEECH = n; + } + } + } + + if (foundSPEECH != null && foundSPEECH.isEnabled()) { + handleSwitch(foundSPEECH.getSwitchIdx(), foundSPEECH.getSwitchPassword(), jsonAction); + Toast.makeText(MainActivity.this, getString(R.string.Speech) + ": " + SPEECH_ID + " - " + actionFound, Toast.LENGTH_SHORT).show(); + } else { + if (foundSPEECH == null) + Toast.makeText(MainActivity.this, getString(R.string.Speech_found) + ": " + SPEECH_ID, Toast.LENGTH_SHORT).show(); + else + Toast.makeText(MainActivity.this, getString(R.string.Speech_disabled) + ": " + SPEECH_ID, Toast.LENGTH_SHORT).show(); + } + } + } + + private void startRecognition() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (PermissionsUtil.canAccessAudioState(this)) { + Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); + + speechRecognizer.startListening(intent); + listeningSpeechRecognition = true; + playRecognitionAnimation(); + } else { + requestPermissions(PermissionsUtil.INITIAL_AUDIO_PERMS, PermissionsUtil.INITIAL_AUDIO_REQUEST); + } + } else { + Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); + speechRecognizer.startListening(intent); + + listeningSpeechRecognition = true; + playRecognitionAnimation(); + } + } + + private void stopRecognition() { + if (speechRecognizer != null) { + speechRecognizer.stopListening(); + speechRecognizer.cancel(); + speechRecognizer.destroy(); + } + stopRecognitionAnimation(); + listeningSpeechRecognition = false; + + if(fromVoiceWidget) + this.finish(); + } + + @DebugLog public void showServerDialog() { String[] serverNames = new String[mServerUtil.getServerList().size()]; int count = 0; @@ -834,11 +1134,9 @@ public void showServerDialog() { for (ServerInfo s : mServerUtil.getEnabledServerList()) { serverNames[count] = s.getServerName(); - if (mServerUtil.getActiveServer() != null && mServerUtil.getActiveServer().getServerName().equals(s.getServerName())) selectionId = count; - count++; } @@ -848,6 +1146,7 @@ public void showServerDialog() { .items(serverNames) .itemsCallbackSingleChoice(selectionId, new MaterialDialog.ListCallbackSingleChoice() { @Override + @DebugLog public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) { ServerInfo setNew = null; for (ServerInfo s : mServerUtil.getEnabledServerList()) { @@ -869,17 +1168,37 @@ public boolean onSelection(MaterialDialog dialog, View itemView, int which, Char .show(); } - @Override - public void onResume() { - super.onResume(); - setScreenAlwaysOn(); - refreshFragment(); + /** + * Starts the scheduled tasks service via GCM Network manager + * Automatically detects if this has been done before + */ + private void setScheduledTasks() { + UsefulBits.setScheduledTasks(this); } - @Override - public void onDestroy() { - super.onDestroy(); - stopCameraTimer(); + private void showSimpleSnackbar(String message) { + CoordinatorLayout layout = getFragmentCoordinatorLayout(); + if (layout != null) + UsefulBits.showSimpleSnackbar(this, layout, message, Snackbar.LENGTH_SHORT); + else + Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show(); + } + + @DebugLog + public CoordinatorLayout getFragmentCoordinatorLayout() { + CoordinatorLayout layout = null; + try { + Fragment f = latestFragment; + if (f != null) { + View v = f.getView(); + if (v != null) + layout = (CoordinatorLayout) v.findViewById(R.id.coordinatorLayout); + } + } catch (Exception ex) { + Log.e(TAG, "Unable to get the coordinator layout of visible fragment"); + ex.printStackTrace(); + } + return layout; } private void stopCameraTimer() { @@ -891,17 +1210,71 @@ private void stopCameraTimer() { } @Override + @DebugLog + public void onResume() { + super.onResume(); + setScreenAlwaysOn(); + } + + @Override + @DebugLog + public void onDestroy() { + super.onDestroy(); + stopCameraTimer(); + } + + @Override + @DebugLog public void onBackPressed() { - if (stackFragments == null || stackFragments.size() <= 1) { - MainActivity.super.onBackPressed(); + if (listeningSpeechRecognition) { + stopRecognition(); + + if(fromVoiceWidget) + this.finish(); } else { - String currentFragment = stackFragments.get(stackFragments.size() - 1); - String previousFragment = stackFragments.get(stackFragments.size() - 2); - changeFragment(previousFragment); - stackFragments.remove(currentFragment); + if(fromQRCodeWidget) + this.finish(); + + //handle the back press :D close the drawer first and if the drawer is closed close the activity + if (drawer != null && drawer.isDrawerOpen()) { + drawer.closeDrawer(); + } else { + if (stackFragments == null || stackFragments.size() <= 1) { + MainActivity.super.onBackPressed(); + } else { + String currentFragment = stackFragments.get(stackFragments.size() - 1); + String previousFragment = stackFragments.get(stackFragments.size() - 2); + changeFragment(previousFragment); + stackFragments.remove(currentFragment); + } + + stopCameraTimer(); + invalidateOptionsMenu(); + } } + } - stopCameraTimer(); - invalidateOptionsMenu(); + /** + * Opens the dialog + * + * @param dialogStandardFragment + */ + private void openDialogFragment(DialogFragment dialogStandardFragment) { + if (mSharedPrefs != null) { + PackageInfo pInfo = null; + try { + pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); + String version = pInfo.versionName; + String preVersion = mSharedPrefs.getPreviousVersionNumber(); + if (!version.equals(preVersion)) { + if (dialogStandardFragment != null) { + getSupportFragmentManager().beginTransaction().add(dialogStandardFragment, "changelog_dialog").commitAllowingStateLoss(); + } + mSharedPrefs.setVersionNumber(version); + } + } catch (PackageManager.NameNotFoundException e) { + e.printStackTrace(); + } + } } -} \ No newline at end of file +} diff --git a/app/src/main/java/nl/hnogames/domoticz/NFCSettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/NFCSettingsActivity.java index f2dbd071c..c44ecb260 100644 --- a/app/src/main/java/nl/hnogames/domoticz/NFCSettingsActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/NFCSettingsActivity.java @@ -53,7 +53,6 @@ import nl.hnogames.domoticz.Adapters.NFCAdapter; import nl.hnogames.domoticz.Containers.NFCInfo; -import nl.hnogames.domoticz.Containers.QRCodeInfo; import nl.hnogames.domoticz.Containers.SwitchInfo; import nl.hnogames.domoticz.Domoticz.Domoticz; import nl.hnogames.domoticz.Interfaces.NFCClickListener; @@ -92,6 +91,8 @@ protected void onCreate(Bundle savedInstanceState) { mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); @@ -108,9 +109,9 @@ protected void onCreate(Bundle savedInstanceState) { mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter != null) { - showSimpleSnackbar(getString(R.string.nfc_register)); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.nfc_register, Snackbar.LENGTH_SHORT); } else { - showSimpleSnackbar(getString(R.string.nfc_not_supported)); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.nfc_not_supported, Snackbar.LENGTH_SHORT); } domoticz = new Domoticz(this, null); @@ -138,14 +139,15 @@ protected void onResume() { mNfcAdapter = NfcAdapter.getDefaultAdapter(this); if (mNfcAdapter != null) { - showSimpleSnackbar(getString(R.string.nfc_register)); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.nfc_register, Snackbar.LENGTH_SHORT); } else { - showSimpleSnackbar(getString(R.string.nfc_not_supported)); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.nfc_not_supported, Snackbar.LENGTH_SHORT); } } if (mNfcAdapter != null) mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, new IntentFilter[]{filter}, this.techList); - }catch(Exception ex){} + } catch (Exception ex) { + } } @Override @@ -171,7 +173,7 @@ protected void onNewIntent(Intent intent) { } if (newTagFound) { - showSimpleSnackbar(getString(R.string.nfc_tag_found) + ": " + tagID); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, getString(R.string.nfc_tag_found) + ": " + tagID, Snackbar.LENGTH_SHORT); new MaterialDialog.Builder(this) .title(R.string.nfc_tag_found) .content(R.string.nfc_tag_name) @@ -180,7 +182,7 @@ protected void onNewIntent(Intent intent) { @Override public void onInput(@NonNull MaterialDialog dialog, CharSequence input) { if (!UsefulBits.isEmpty(String.valueOf(input))) { - showSimpleSnackbar(getString(R.string.nfc_saved) + ": " + input); + UsefulBits.showSimpleSnackbar(NFCSettingsActivity.this, coordinatorLayout, getString(R.string.nfc_saved) + ": " + input, Snackbar.LENGTH_SHORT); NFCInfo newNFC = new NFCInfo(); newNFC.setId(tagID); newNFC.setName(String.valueOf(input)); @@ -190,7 +192,7 @@ public void onInput(@NonNull MaterialDialog dialog, CharSequence input) { } }).show(); } else { - showSimpleSnackbar(getString(R.string.nfc_exists)); + UsefulBits.showSimpleSnackbar(NFCSettingsActivity.this, coordinatorLayout, R.string.nfc_exists, Snackbar.LENGTH_SHORT); busyWithTag = false; } } @@ -247,17 +249,13 @@ public void onReceiveSwitches(ArrayList switches) { @Override public void onError(Exception error) { - Snackbar.make(coordinatorLayout, - R.string.unable_to_get_switches, - Snackbar.LENGTH_SHORT) - .setAction(R.string.retry, new View.OnClickListener() { + UsefulBits.showSnackbar(NFCSettingsActivity.this, coordinatorLayout, NFCSettingsActivity.this.getString(R.string.unable_to_get_switches), Snackbar.LENGTH_SHORT, + null, new View.OnClickListener() { @Override public void onClick(View v) { - // User clicked retry button getSwitchesAndShowSwitchesDialog(nfcInfo); } - }) - .show(); + }, NFCSettingsActivity.this.getString(R.string.retry)); } }); } @@ -324,11 +322,6 @@ public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) return result; } - private void showSimpleSnackbar(String message) { - Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_SHORT).show(); - } - - @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { @@ -365,32 +358,26 @@ private void showRemoveUndoSnackbar(final NFCInfo nfcInfo) { // Show snackbar with undo option String text = String.format(getString(R.string.something_deleted), getString(R.string.nfc)); - Snackbar.make(coordinatorLayout, - text, - Snackbar.LENGTH_LONG) - .setAction(R.string.undo, new View.OnClickListener() { - @Override - public void onClick(View v) { - updateNFC(nfcInfo);//undo - } - }) - .setCallback(new Snackbar.Callback() { - @Override - public void onDismissed(Snackbar snackbar, int event) { - super.onDismissed(snackbar, event); - - switch (event) { - case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: - case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: - case Snackbar.Callback.DISMISS_EVENT_MANUAL: - // Snackbar was timed out so let's remove the data from - // shared preferences - removeNFCFromListView(nfcInfo); - break; - } - } - }) - .show(); + + UsefulBits.showSnackbar(this, coordinatorLayout, text, Snackbar.LENGTH_SHORT, new Snackbar.Callback() { + @Override + public void onDismissed(Snackbar snackbar, int event) { + super.onDismissed(snackbar, event); + + switch (event) { + case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: + case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: + case Snackbar.Callback.DISMISS_EVENT_MANUAL: + removeNFCFromListView(nfcInfo); + break; + } + } + }, new View.OnClickListener() { + @Override + public void onClick(View v) { + updateNFC(nfcInfo); + } + }, this.getString(R.string.undo)); } private void removeNFCFromListView(NFCInfo nfcInfo) { diff --git a/app/src/main/java/nl/hnogames/domoticz/PlanActivity.java b/app/src/main/java/nl/hnogames/domoticz/PlanActivity.java index ccc7dc846..98e05460c 100644 --- a/app/src/main/java/nl/hnogames/domoticz/PlanActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/PlanActivity.java @@ -41,6 +41,8 @@ protected void onCreate(Bundle savedInstanceState) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); diff --git a/app/src/main/java/nl/hnogames/domoticz/Preference/Preference.java b/app/src/main/java/nl/hnogames/domoticz/Preference/Preference.java index d03198775..9aee97e90 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Preference/Preference.java +++ b/app/src/main/java/nl/hnogames/domoticz/Preference/Preference.java @@ -47,6 +47,7 @@ import nl.hnogames.domoticz.BuildConfig; import nl.hnogames.domoticz.Domoticz.Domoticz; +import nl.hnogames.domoticz.Fragments.Changelog; import nl.hnogames.domoticz.GeoSettingsActivity; import nl.hnogames.domoticz.Interfaces.MobileDeviceReceiver; import nl.hnogames.domoticz.NFCSettingsActivity; @@ -55,6 +56,7 @@ import nl.hnogames.domoticz.ServerListSettingsActivity; import nl.hnogames.domoticz.ServerSettingsActivity; import nl.hnogames.domoticz.SettingsActivity; +import nl.hnogames.domoticz.SpeechSettingsActivity; import nl.hnogames.domoticz.UI.SimpleTextDialog; import nl.hnogames.domoticz.UpdateActivity; import nl.hnogames.domoticz.Utils.DeviceUtils; @@ -107,8 +109,10 @@ private void setPreferences() { android.preference.SwitchPreference WearPreference = (android.preference.SwitchPreference) findPreference("enableWearItems"); android.preference.Preference NFCPreference = findPreference("nfc_settings"); android.preference.Preference QRCodePreference = findPreference("qrcode_settings"); + android.preference.Preference SpeechPreference = findPreference("speech_settings"); android.preference.SwitchPreference EnableNFCPreference = (android.preference.SwitchPreference) findPreference("enableNFC"); android.preference.SwitchPreference EnableQRCodePreference = (android.preference.SwitchPreference) findPreference("enableQRCode"); + android.preference.SwitchPreference EnableSpeechPreference = (android.preference.SwitchPreference) findPreference("enableSpeech"); MultiSelectListPreference drawerItems = (MultiSelectListPreference) findPreference("enable_menu_items"); @SuppressWarnings("SpellCheckingInspection") android.preference.SwitchPreference AlwaysOnPreference = (android.preference.SwitchPreference) findPreference("alwayson"); @SuppressWarnings("SpellCheckingInspection") android.preference.PreferenceScreen preferenceScreen = (android.preference.PreferenceScreen) findPreference("settingsscreen"); @@ -183,7 +187,7 @@ public boolean onPreferenceClick(android.preference.Preference preference) { fetchServerConfig.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(android.preference.Preference preference) { - UsefulBits.saveServerConfigToActiveServer(mContext, true, true); + UsefulBits.getServerConfigForActiveServer(mContext, true, null, null); return true; } }); @@ -254,6 +258,17 @@ public boolean onPreferenceChange(android.preference.Preference preference, Obje } }); + EnableSpeechPreference.setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() { + @Override + public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) { + if (BuildConfig.LITE_VERSION) { + Toast.makeText(mContext, getString(R.string.category_Speech) + " " + getString(R.string.premium_feature), Toast.LENGTH_LONG).show(); + return false; + } + return true; + } + }); + NFCPreference.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() { @Override public boolean onPreferenceClick(android.preference.Preference preference) { @@ -282,6 +297,20 @@ public boolean onPreferenceClick(android.preference.Preference preference) { } }); + SpeechPreference.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(android.preference.Preference preference) { + if (BuildConfig.LITE_VERSION) { + Toast.makeText(mContext, getString(R.string.category_Speech) + " " + getString(R.string.premium_feature), Toast.LENGTH_LONG).show(); + return false; + } else { + Intent intent = new Intent(mContext, SpeechSettingsActivity.class); + startActivity(intent); + return true; + } + } + }); + WearPreference.setOnPreferenceChangeListener(new android.preference.Preference.OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(android.preference.Preference preference, Object newValue) { @@ -406,6 +435,14 @@ public boolean onPreferenceClick(android.preference.Preference preference) { return false; } }); + android.preference.Preference changelog = findPreference("info_changelog"); + changelog.setOnPreferenceClickListener(new android.preference.Preference.OnPreferenceClickListener() { + @Override + public boolean onPreferenceClick(android.preference.Preference preference) { + ((SettingsActivity) getActivity()).getSupportFragmentManager().beginTransaction().add(new Changelog(), "changelog_dialog").commitAllowingStateLoss(); + return true; + } + }); } private void handleImportExportButtons() { @@ -559,9 +596,10 @@ public boolean onPreferenceClick(android.preference.Preference preference) { } domoticzVersion.setSummary(message); } - } catch (Exception ex) { - Log.e(TAG, mDomoticz.getErrorMessage(ex)); + String ex_message = mDomoticz.getErrorMessage(ex); + if (!UsefulBits.isEmpty(ex_message)) + Log.e(TAG, mDomoticz.getErrorMessage(ex)); } } diff --git a/app/src/main/java/nl/hnogames/domoticz/QRCodeSettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/QRCodeSettingsActivity.java index 8257040cd..4906c4bac 100644 --- a/app/src/main/java/nl/hnogames/domoticz/QRCodeSettingsActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/QRCodeSettingsActivity.java @@ -38,19 +38,16 @@ import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; -import com.google.zxing.qrcode.encoder.QRCode; import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter; import java.util.ArrayList; import nl.hnogames.domoticz.Adapters.QRCodeAdapter; -import nl.hnogames.domoticz.Containers.LocationInfo; import nl.hnogames.domoticz.Containers.QRCodeInfo; import nl.hnogames.domoticz.Containers.SwitchInfo; import nl.hnogames.domoticz.Domoticz.Domoticz; import nl.hnogames.domoticz.Interfaces.QRCodeClickListener; import nl.hnogames.domoticz.Interfaces.SwitchesReceiver; -import nl.hnogames.domoticz.UI.LocationDialog; import nl.hnogames.domoticz.UI.SwitchDialog; import nl.hnogames.domoticz.Utils.PermissionsUtil; import nl.hnogames.domoticz.Utils.SharedPrefUtil; @@ -72,6 +69,8 @@ protected void onCreate(Bundle savedInstanceState) { mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); @@ -92,7 +91,7 @@ protected void onCreate(Bundle savedInstanceState) { createListView(); - showSimpleSnackbar(getString(R.string.qrcode_register)); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.qrcode_register, Snackbar.LENGTH_SHORT); } private void createListView() { @@ -147,17 +146,13 @@ public void onReceiveSwitches(ArrayList switches) { @Override public void onError(Exception error) { - Snackbar.make(coordinatorLayout, - R.string.unable_to_get_switches, - Snackbar.LENGTH_SHORT) - .setAction(R.string.retry, new View.OnClickListener() { + UsefulBits.showSnackbar(QRCodeSettingsActivity.this, coordinatorLayout, QRCodeSettingsActivity.this.getString(R.string.unable_to_get_switches), Snackbar.LENGTH_SHORT, + null, new View.OnClickListener() { @Override public void onClick(View v) { - // User clicked retry button getSwitchesAndShowSwitchesDialog(qrInfo); } - }) - .show(); + }, QRCodeSettingsActivity.this.getString(R.string.retry)); } }); } @@ -224,10 +219,6 @@ public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) return result; } - private void showSimpleSnackbar(String message) { - Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).show(); - } - @Override public boolean onEnableClick(QRCodeInfo qrcode, boolean checked) { if (qrcode.getSwitchIdx() <= 0 && checked) @@ -252,32 +243,26 @@ private void showRemoveUndoSnackbar(final QRCodeInfo qrcodeInfo) { // Show snackbar with undo option String text = String.format(getString(R.string.something_deleted), getString(R.string.qrcode)); - Snackbar.make(coordinatorLayout, - text, - Snackbar.LENGTH_LONG) - .setAction(R.string.undo, new View.OnClickListener() { - @Override - public void onClick(View v) { - updateQRCode(qrcodeInfo);//undo - } - }) - .setCallback(new Snackbar.Callback() { - @Override - public void onDismissed(Snackbar snackbar, int event) { - super.onDismissed(snackbar, event); - - switch (event) { - case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: - case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: - case Snackbar.Callback.DISMISS_EVENT_MANUAL: - // Snackbar was timed out so let's remove the data from - // shared preferences - removeQRCodeFromListView(qrcodeInfo); - break; - } - } - }) - .show(); + + UsefulBits.showSnackbar(this, coordinatorLayout, text, Snackbar.LENGTH_SHORT, new Snackbar.Callback() { + @Override + public void onDismissed(Snackbar snackbar, int event) { + super.onDismissed(snackbar, event); + + switch (event) { + case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: + case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: + case Snackbar.Callback.DISMISS_EVENT_MANUAL: + removeQRCodeFromListView(qrcodeInfo); + break; + } + } + }, new View.OnClickListener() { + @Override + public void onClick(View v) { + updateQRCode(qrcodeInfo);//undo + } + }, this.getString(R.string.undo)); } @Override @@ -351,7 +336,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } if (newTagFound) { - showSimpleSnackbar(getString(R.string.qrcode_found) + ": " + QR_Code_ID); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, getString(R.string.qrcode_found) + ": " + QR_Code_ID, Snackbar.LENGTH_SHORT); new MaterialDialog.Builder(this) .title(R.string.qrcode_found) .content(R.string.qrcode_name) @@ -360,7 +345,7 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { @Override public void onInput(@NonNull MaterialDialog dialog, CharSequence input) { if (!UsefulBits.isEmpty(String.valueOf(input))) { - showSimpleSnackbar(getString(R.string.nfc_saved) + ": " + input); + UsefulBits.showSimpleSnackbar(QRCodeSettingsActivity.this, coordinatorLayout, getString(R.string.qrcode_saved) + ": " + input, Snackbar.LENGTH_SHORT); QRCodeInfo qrCodeInfo = new QRCodeInfo(); qrCodeInfo.setId(QR_Code_ID); qrCodeInfo.setName(String.valueOf(input)); @@ -370,7 +355,7 @@ public void onInput(@NonNull MaterialDialog dialog, CharSequence input) { } }).show(); } else { - showSimpleSnackbar(getString(R.string.qrcode_exists)); + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.qrcode_exists, Snackbar.LENGTH_SHORT); busyWithQRCode = false; } } diff --git a/app/src/main/java/nl/hnogames/domoticz/ServerListSettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/ServerListSettingsActivity.java index 8a0c8935d..df202466e 100644 --- a/app/src/main/java/nl/hnogames/domoticz/ServerListSettingsActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/ServerListSettingsActivity.java @@ -62,6 +62,8 @@ protected void onCreate(Bundle savedInstanceState) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); @@ -88,7 +90,7 @@ private void createListView() { @Override public boolean onEnableClick(ServerInfo server, boolean checked) { if (server.getServerName().equals(Domoticz.DOMOTICZ_DEFAULT_SERVER)) { - showSimpleSnackbar(getString(R.string.cant_disable_default_server)); + UsefulBits.showSimpleSnackbar(ServerListSettingsActivity.this, coordinatorLayout, R.string.cant_disable_default_server, Snackbar.LENGTH_SHORT); server.setEnabled(!checked); createListView(); //reset values } else { @@ -101,7 +103,7 @@ public boolean onEnableClick(ServerInfo server, boolean checked) { @Override public void onRemoveClick(ServerInfo server) { if (server.getServerName().equals(Domoticz.DOMOTICZ_DEFAULT_SERVER)) { - showSimpleSnackbar(getString(R.string.cant_remove_default_server)); + UsefulBits.showSimpleSnackbar(ServerListSettingsActivity.this, coordinatorLayout, R.string.cant_remove_default_server, Snackbar.LENGTH_SHORT); } else showRemoveUndoSnackbar(server); } @@ -136,30 +138,26 @@ private void showRemoveUndoSnackbar(final ServerInfo serverInfo) { // Show snackbar with undo option String text = String.format(getString(R.string.something_deleted), getString(R.string.server)); - Snackbar.make(coordinatorLayout, - text, - Snackbar.LENGTH_LONG) - .setAction(R.string.undo, new View.OnClickListener() { - @Override - public void onClick(View v) { - addServerToListView(serverInfo); - } - }) - .setCallback(new Snackbar.Callback() { - @Override - public void onDismissed(Snackbar snackbar, int event) { - super.onDismissed(snackbar, event); - - switch (event) { - case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: - case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: - case Snackbar.Callback.DISMISS_EVENT_MANUAL: - removeServerFromSettings(serverInfo); - break; - } - } - }) - .show(); + + UsefulBits.showSnackbar(this, coordinatorLayout, text, Snackbar.LENGTH_SHORT, new Snackbar.Callback() { + @Override + public void onDismissed(Snackbar snackbar, int event) { + super.onDismissed(snackbar, event); + switch (event) { + case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: + case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: + case Snackbar.Callback.DISMISS_EVENT_MANUAL: + removeServerFromSettings(serverInfo); + break; + } + } + }, new View.OnClickListener() { + @Override + public void onClick(View v) { + addServerToListView(serverInfo); + } + }, this.getString(R.string.undo)); + } private void removeServerFromListView(ServerInfo serverInfo) { @@ -190,10 +188,6 @@ public void showEditServerActivity(String name) { startActivityForResult(i, REQUEST_ADD_SERVER); } - private void showSimpleSnackbar(String message) { - Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_SHORT).show(); - } - @Override public boolean onCreateOptionsMenu(Menu menu) { try { diff --git a/app/src/main/java/nl/hnogames/domoticz/ServerSettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/ServerSettingsActivity.java index 3f5d40098..78711ac50 100644 --- a/app/src/main/java/nl/hnogames/domoticz/ServerSettingsActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/ServerSettingsActivity.java @@ -52,6 +52,8 @@ protected void onCreate(Bundle savedInstanceState) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); diff --git a/app/src/main/java/nl/hnogames/domoticz/Service/TaskService.java b/app/src/main/java/nl/hnogames/domoticz/Service/TaskService.java index 3e8359f8d..813d6e098 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Service/TaskService.java +++ b/app/src/main/java/nl/hnogames/domoticz/Service/TaskService.java @@ -52,7 +52,7 @@ public int onRunTask(TaskParams taskParams) { if (tag.equals(UsefulBits.TASK_TAG_PERIODIC) || tag.equals("TEST")) { final boolean forceUpdate = true; // Force update //noinspection ConstantConditions - UsefulBits.saveServerConfigToActiveServer(this, forceUpdate, false); + UsefulBits.getServerConfigForActiveServer(this, forceUpdate, null, null); //noinspection ConstantConditions UsefulBits.checkDownloadedLanguage(this, null, forceUpdate, true); } diff --git a/app/src/main/java/nl/hnogames/domoticz/Service/WidgetIntentReceiver.java b/app/src/main/java/nl/hnogames/domoticz/Service/WidgetIntentReceiver.java index 45837335c..4cc652dde 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Service/WidgetIntentReceiver.java +++ b/app/src/main/java/nl/hnogames/domoticz/Service/WidgetIntentReceiver.java @@ -36,6 +36,7 @@ import nl.hnogames.domoticz.Interfaces.DevicesReceiver; import nl.hnogames.domoticz.Interfaces.ScenesReceiver; import nl.hnogames.domoticz.Interfaces.setCommandReceiver; +import nl.hnogames.domoticz.MainActivity; import nl.hnogames.domoticz.R; import nl.hnogames.domoticz.Utils.SharedPrefUtil; import nl.hnogames.domoticz.Utils.UsefulBits; @@ -46,16 +47,38 @@ public class WidgetIntentReceiver extends BroadcastReceiver { private boolean action = false; private boolean toggle = true; private String password = null; + private SharedPrefUtil mSharedPrefs; + + private final int iVoiceAction = -55; + private final int iQRCodeAction = -66; + @Override - public void onReceive(Context context, Intent intent) { + public void onReceive(final Context context, Intent intent) { widgetID = intent.getIntExtra("WIDGETID", 999999); int idx = intent.getIntExtra("IDX", 999999); action = intent.getBooleanExtra("WIDGETACTION", false); toggle = intent.getBooleanExtra("WIDGETTOGGLE", true); - - if (intent.getAction().equals("nl.hnogames.domoticz.Service.WIDGET_TOGGLE_ACTION")) { - processSwitch(context, idx); + mSharedPrefs = new SharedPrefUtil(context); + + if (idx == iVoiceAction)//voice + { + Intent iStart = new Intent(context, MainActivity.class); + iStart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + iStart.putExtra("VOICE", true); + context.startActivity(iStart); + } + else if (idx == iQRCodeAction)//qrcode + { + Intent iStart = new Intent(context, MainActivity.class); + iStart.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + iStart.putExtra("QRCODE", true); + context.startActivity(iStart); + } + else { + if (intent.getAction().equals("nl.hnogames.domoticz.Service.WIDGET_TOGGLE_ACTION")) { + processSwitch(context, idx); + } } } @@ -119,7 +142,6 @@ private boolean isPushOffSwitch(DevicesInfo mExtendedStatusInfo) { } private void processSwitch(final Context context, int idx) { - SharedPrefUtil mSharedPrefs = new SharedPrefUtil(context); password = mSharedPrefs.getWidgetPassword(widgetID); final Domoticz domoticz = new Domoticz(context, null); boolean isScene = mSharedPrefs.getWidgetisScene(widgetID); diff --git a/app/src/main/java/nl/hnogames/domoticz/Service/WidgetProviderLarge.java b/app/src/main/java/nl/hnogames/domoticz/Service/WidgetProviderLarge.java index 2adbc81ed..8e2a58a2c 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Service/WidgetProviderLarge.java +++ b/app/src/main/java/nl/hnogames/domoticz/Service/WidgetProviderLarge.java @@ -47,7 +47,10 @@ import static android.appwidget.AppWidgetManager.INVALID_APPWIDGET_ID; public class WidgetProviderLarge extends AppWidgetProvider { - Context context; + private Context context; + + private static final int iVoiceAction = -55; + private static final int iQRCodeAction = -66; @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, @@ -102,140 +105,186 @@ public void updateAppWidget(final AppWidgetManager appWidgetManager, final Domoticz domoticz = new Domoticz(getApplicationContext(), null); final int idx = mSharedPrefs.getWidgetIDX(appWidgetId); - final boolean isScene = mSharedPrefs.getWidgetisScene(appWidgetId); - if (!isScene) { - domoticz.getDevice(new DevicesReceiver() { - @Override - public void onReceiveDevices(ArrayList mDevicesInfo) { - } - - @Override - public void onReceiveDevice(DevicesInfo s) { - if (s != null) { - int withButtons = withButtons(s); - if (mSharedPrefs.darkThemeEnabled()) { - if (withButtons == 1) - views = new RemoteViews(packageName, R.layout.widget_layout_dark); - if (withButtons == 2) - views = new RemoteViews(packageName, R.layout.widget_layout_buttons_dark); - } else { - if (withButtons == 1) - views = new RemoteViews(packageName, R.layout.widget_layout); - if (withButtons == 2) - views = new RemoteViews(packageName, R.layout.widget_layout_buttons); - } - String text = s.getData(); - views.setTextViewText(R.id.title, s.getName()); - if (s.getUsage() != null && s.getUsage().length() > 0) - text = s.getUsage(); - if (s.getCounterToday() != null && s.getCounterToday().length() > 0) - text += " Today: " + s.getCounterToday(); - if (s.getCounter() != null && s.getCounter().length() > 0 && - !s.getCounter().equals(s.getData())) - text += " Total: " + s.getCounter(); - - views.setTextViewText(R.id.desc, text); - if (withButtons == 1 && s.getStatus() != null) { - if (s.getStatusBoolean()) - views.setTextViewText(R.id.on_button, "off"); - else - views.setTextViewText(R.id.on_button, "on"); - - views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( - UpdateWidgetService.this, - appWidgetId, - s.getIdx(), - !s.getStatusBoolean(), - true)); - views.setViewVisibility(R.id.on_button, View.VISIBLE); - - } else if (withButtons == 2 && s.getStatus() != null) { - views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( - UpdateWidgetService.this, - appWidgetId, - s.getIdx(), true, - false)); - views.setViewVisibility(R.id.on_button, View.VISIBLE); - - views.setOnClickPendingIntent(R.id.off_button, buildButtonPendingIntent( - UpdateWidgetService.this, - appWidgetId, - s.getIdx(), false, - false)); - views.setViewVisibility(R.id.off_button, View.VISIBLE); - } else { - views.setViewVisibility(R.id.on_button, View.GONE); - } - - views.setImageViewResource(R.id.rowIcon, domoticz.getDrawableIcon(s.getTypeImg(), s.getType(), s.getSwitchType(), true, s.getUseCustomImage(), s.getImage())); - appWidgetManager.updateAppWidget(appWidgetId, views); + if (idx == iVoiceAction) { + if (mSharedPrefs.darkThemeEnabled()) { + views = new RemoteViews(packageName, R.layout.widget_layout_dark); + } else { + views = new RemoteViews(packageName, R.layout.widget_layout); + } + views.setTextViewText(R.id.desc, getApplicationContext().getString(R.string.Speech_desc)); + views.setTextViewText(R.id.title, getApplicationContext().getString(R.string.action_speech)); + views.setImageViewResource(R.id.rowIcon, R.drawable.mic); + views.setTextViewText(R.id.on_button, "GO"); + views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( + UpdateWidgetService.this, + appWidgetId, + idx, + false, + true)); + views.setViewVisibility(R.id.on_button, View.VISIBLE); + appWidgetManager.updateAppWidget(appWidgetId, views); + } + else if (idx == iQRCodeAction) { + if (mSharedPrefs.darkThemeEnabled()) { + views = new RemoteViews(packageName, R.layout.widget_layout_dark); + } else { + views = new RemoteViews(packageName, R.layout.widget_layout); + } + views.setTextViewText(R.id.desc, getApplicationContext().getString(R.string.qrcode_desc)); + views.setTextViewText(R.id.title, getApplicationContext().getString(R.string.action_qrcode_scan)); + views.setImageViewResource(R.id.rowIcon, R.drawable.qrcode); + views.setTextViewText(R.id.on_button, "GO"); + views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( + UpdateWidgetService.this, + appWidgetId, + idx, + false, + true)); + views.setViewVisibility(R.id.on_button, View.VISIBLE); + appWidgetManager.updateAppWidget(appWidgetId, views); + }else { + final boolean isScene = mSharedPrefs.getWidgetisScene(appWidgetId); + if (!isScene) { + domoticz.getDevice(new DevicesReceiver() { + @Override + public void onReceiveDevices(ArrayList mDevicesInfo) { } - } - - @Override - public void onError(Exception error) { - } - }, idx, false); - } else { - domoticz.getScene(new ScenesReceiver() { - @Override - public void onReceiveScenes(ArrayList scenes) { - } - @Override - public void onError(Exception error) { - } - - @Override - public void onReceiveScene(SceneInfo s) { - if (s != null) { - if (s.getStatusInString() != null) { - if (s.getType().equals(Domoticz.Scene.Type.SCENE)) { - views = new RemoteViews(packageName, R.layout.widget_layout); - views.setTextViewText(R.id.title, s.getName()); - views.setTextViewText(R.id.desc, s.getStatusInString()); + @Override + public void onReceiveDevice(DevicesInfo s) { + if (s != null) { + int withButtons = withButtons(s); + if (mSharedPrefs.darkThemeEnabled()) { + if (withButtons == 1) + views = new RemoteViews(packageName, R.layout.widget_layout_dark); + if (withButtons == 2) + views = new RemoteViews(packageName, R.layout.widget_layout_buttons_dark); + } else { + if (withButtons == 1) + views = new RemoteViews(packageName, R.layout.widget_layout); + if (withButtons == 2) + views = new RemoteViews(packageName, R.layout.widget_layout_buttons); + } + String text = s.getData(); + views.setTextViewText(R.id.title, s.getName()); + if (s.getUsage() != null && s.getUsage().length() > 0) + text = s.getUsage(); + if (s.getCounterToday() != null && s.getCounterToday().length() > 0) + text += " Today: " + s.getCounterToday(); + if (s.getCounter() != null && s.getCounter().length() > 0 && + !s.getCounter().equals(s.getData())) + text += " Total: " + s.getCounter(); + + views.setTextViewText(R.id.desc, text); + if (withButtons == 1 && s.getStatus() != null) { + if (s.getStatusBoolean()) + views.setTextViewText(R.id.on_button, "off"); + else + views.setTextViewText(R.id.on_button, "on"); - views.setTextViewText(R.id.on_button, "on"); views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( UpdateWidgetService.this, appWidgetId, - idx, - !s.getStatusInBoolean(), + s.getIdx(), + !s.getStatusBoolean(), true)); views.setViewVisibility(R.id.on_button, View.VISIBLE); - } else { - views = new RemoteViews(packageName, R.layout.widget_layout_buttons); - views.setTextViewText(R.id.title, s.getName()); - views.setTextViewText(R.id.desc, s.getStatusInString()); - - views.setTextViewText(R.id.off_button, "off"); - views.setTextViewText(R.id.on_button, "on"); + } else if (withButtons == 2 && s.getStatus() != null) { views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( UpdateWidgetService.this, appWidgetId, - idx, - true, + s.getIdx(), true, false)); views.setViewVisibility(R.id.on_button, View.VISIBLE); + views.setOnClickPendingIntent(R.id.off_button, buildButtonPendingIntent( UpdateWidgetService.this, appWidgetId, - idx, - false, + s.getIdx(), false, false)); - views.setViewVisibility(R.id.off_button, View.VISIBLE); + } else { + views.setViewVisibility(R.id.on_button, View.GONE); } - } else { - views.setViewVisibility(R.id.on_button, View.GONE); + + views.setImageViewResource(R.id.rowIcon, domoticz.getDrawableIcon(s.getTypeImg(), s.getType(), s.getSwitchType(), true, s.getUseCustomImage(), s.getImage())); + appWidgetManager.updateAppWidget(appWidgetId, views); } + } - views.setImageViewResource(R.id.rowIcon, domoticz.getDrawableIcon(s.getType(), null, null, false, false, null)); - appWidgetManager.updateAppWidget(appWidgetId, views); + @Override + public void onError(Exception error) { } - } - }, idx); + }, idx, false); + } else { + domoticz.getScene(new ScenesReceiver() { + @Override + public void onReceiveScenes(ArrayList scenes) { + } + + @Override + public void onError(Exception error) { + } + + @Override + public void onReceiveScene(SceneInfo s) { + if (s != null) { + if (s.getStatusInString() != null) { + if (s.getType().equals(Domoticz.Scene.Type.SCENE)) { + if (mSharedPrefs.darkThemeEnabled()) + views = new RemoteViews(packageName, R.layout.widget_layout_dark); + else + views = new RemoteViews(packageName, R.layout.widget_layout); + + views.setTextViewText(R.id.title, s.getName()); + views.setTextViewText(R.id.desc, s.getStatusInString()); + + views.setTextViewText(R.id.on_button, "on"); + views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( + UpdateWidgetService.this, + appWidgetId, + idx, + !s.getStatusInBoolean(), + true)); + views.setViewVisibility(R.id.on_button, View.VISIBLE); + } else { + if (mSharedPrefs.darkThemeEnabled()) + views = new RemoteViews(packageName, R.layout.widget_layout_buttons_dark); + else + views = new RemoteViews(packageName, R.layout.widget_layout_buttons); + + views.setTextViewText(R.id.title, s.getName()); + views.setTextViewText(R.id.desc, s.getStatusInString()); + views.setTextViewText(R.id.off_button, "off"); + views.setTextViewText(R.id.on_button, "on"); + + views.setOnClickPendingIntent(R.id.on_button, buildButtonPendingIntent( + UpdateWidgetService.this, + appWidgetId, + idx, + true, + false)); + views.setViewVisibility(R.id.on_button, View.VISIBLE); + views.setOnClickPendingIntent(R.id.off_button, buildButtonPendingIntent( + UpdateWidgetService.this, + appWidgetId, + idx, + false, + false)); + + views.setViewVisibility(R.id.off_button, View.VISIBLE); + } + } else { + views.setViewVisibility(R.id.on_button, View.GONE); + } + + views.setImageViewResource(R.id.rowIcon, domoticz.getDrawableIcon(s.getType(), null, null, false, false, null)); + appWidgetManager.updateAppWidget(appWidgetId, views); + } + } + }, idx); + } } } diff --git a/app/src/main/java/nl/hnogames/domoticz/SettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/SettingsActivity.java index 412d5525e..9b6fead7b 100644 --- a/app/src/main/java/nl/hnogames/domoticz/SettingsActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/SettingsActivity.java @@ -38,6 +38,9 @@ protected void onCreate(Bundle savedInstanceState) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); + if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); diff --git a/app/src/main/java/nl/hnogames/domoticz/SpeechSettingsActivity.java b/app/src/main/java/nl/hnogames/domoticz/SpeechSettingsActivity.java new file mode 100644 index 000000000..b3df389ab --- /dev/null +++ b/app/src/main/java/nl/hnogames/domoticz/SpeechSettingsActivity.java @@ -0,0 +1,441 @@ +/* + * Copyright (C) 2015 Domoticz + * + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * + */ + +package nl.hnogames.domoticz; + +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.speech.RecognizerIntent; +import android.speech.SpeechRecognizer; +import android.support.annotation.NonNull; +import android.support.design.widget.CoordinatorLayout; +import android.support.design.widget.Snackbar; +import android.support.v4.content.ContextCompat; +import android.support.v7.app.AppCompatActivity; +import android.text.InputType; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.LinearLayout; +import android.widget.ListView; + +import com.afollestad.materialdialogs.DialogAction; +import com.afollestad.materialdialogs.MaterialDialog; +import com.github.zagum.speechrecognitionview.RecognitionProgressView; +import com.github.zagum.speechrecognitionview.adapters.RecognitionListenerAdapter; +import com.nhaarman.listviewanimations.appearance.simple.SwingBottomInAnimationAdapter; + +import java.util.ArrayList; +import java.util.Locale; + +import nl.hnogames.domoticz.Adapters.SpeechAdapter; +import nl.hnogames.domoticz.Containers.SpeechInfo; +import nl.hnogames.domoticz.Containers.SwitchInfo; +import nl.hnogames.domoticz.Domoticz.Domoticz; +import nl.hnogames.domoticz.Interfaces.SpeechClickListener; +import nl.hnogames.domoticz.Interfaces.SwitchesReceiver; +import nl.hnogames.domoticz.UI.SwitchDialog; +import nl.hnogames.domoticz.Utils.PermissionsUtil; +import nl.hnogames.domoticz.Utils.SharedPrefUtil; +import nl.hnogames.domoticz.Utils.UsefulBits; + + +public class SpeechSettingsActivity extends AppCompatActivity implements SpeechClickListener { + + boolean result = false; + private SharedPrefUtil mSharedPrefs; + private Domoticz domoticz; + private CoordinatorLayout coordinatorLayout; + private ArrayList SpeechList; + private SpeechAdapter adapter; + private boolean busyWithSpeech = false; + + private SpeechRecognizer speechRecognizer; + private RecognitionProgressView recognitionProgressView; + private RecognitionListenerAdapter recognitionListener; + private boolean listeningSpeechRecognition = false; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + mSharedPrefs = new SharedPrefUtil(this); + if (mSharedPrefs.darkThemeEnabled()) + setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); + if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) + UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); + + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_speech_settings); + coordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); + if (mSharedPrefs.darkThemeEnabled()) { + coordinatorLayout.setBackgroundColor(getResources().getColor(R.color.background_dark)); + } + + if (getSupportActionBar() != null) + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + this.setTitle(R.string.category_Speech); + + domoticz = new Domoticz(this, null); + SpeechList = mSharedPrefs.getSpeechList(); + adapter = new SpeechAdapter(this, SpeechList, this); + + createListView(); + + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.Speech_register, Snackbar.LENGTH_SHORT); + } + + private void createListView() { + ListView listView = (ListView) findViewById(R.id.listView); + if (mSharedPrefs.darkThemeEnabled()) { + listView.setBackgroundColor(getResources().getColor(R.color.background_dark)); + } + SwingBottomInAnimationAdapter animationAdapter = new SwingBottomInAnimationAdapter(adapter); + animationAdapter.setAbsListView(listView); + listView.setAdapter(animationAdapter); + listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { + @Override + public void onItemClick(AdapterView adapterView, View view, int item, long id) { + showEditDialog(SpeechList.get(item)); + } + }); + listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() { + @Override + public boolean onItemLongClick(AdapterView parent, View view, final int position, long id) { + getSwitchesAndShowSwitchesDialog(SpeechList.get(position)); + return true; + } + }); + } + + private void showEditDialog(final SpeechInfo mSpeechInfo) { + busyWithSpeech = true; + new MaterialDialog.Builder(this) + .title(R.string.Speech_edit) + .content(R.string.Speech_name) + .inputType(InputType.TYPE_CLASS_TEXT) + .negativeText(R.string.cancel) + .input(this.getString(R.string.category_Speech), mSpeechInfo.getName(), new MaterialDialog.InputCallback() { + @Override + public void onInput(@NonNull MaterialDialog dialog, CharSequence input) { + if (!UsefulBits.isEmpty(String.valueOf(input))) { + mSpeechInfo.setName(String.valueOf(input)); + updateSpeech(mSpeechInfo); + } + busyWithSpeech = false; + } + }).show(); + } + + private void getSwitchesAndShowSwitchesDialog(final SpeechInfo qrInfo) { + domoticz.getSwitches(new SwitchesReceiver() { + @Override + public void onReceiveSwitches(ArrayList switches) { + showSwitchesDialog(qrInfo, switches); + } + + @Override + public void onError(Exception error) { + UsefulBits.showSnackbar(SpeechSettingsActivity.this, coordinatorLayout, SpeechSettingsActivity.this.getString(R.string.unable_to_get_switches), Snackbar.LENGTH_SHORT, + null, new View.OnClickListener() { + @Override + public void onClick(View v) { + getSwitchesAndShowSwitchesDialog(qrInfo); + } + }, SpeechSettingsActivity.this.getString(R.string.retry)); + } + }); + } + + private void showSwitchesDialog( + final SpeechInfo SpeechInfo, + ArrayList switches) { + + SwitchDialog infoDialog = new SwitchDialog( + SpeechSettingsActivity.this, switches, + R.layout.dialog_switch_logs, + domoticz); + infoDialog.onDismissListener(new SwitchDialog.DismissListener() { + @Override + public void onDismiss(int selectedSwitchIDX, String selectedSwitchPassword, String selectedSwitchName) { + SpeechInfo.setSwitchIdx(selectedSwitchIDX); + SpeechInfo.setSwitchPassword(selectedSwitchPassword); + SpeechInfo.setSwitchName(selectedSwitchName); + updateSpeech(SpeechInfo); + } + }); + + infoDialog.show(); + } + + public void updateSpeech(SpeechInfo SpeechInfo) { + if (SpeechList == null) + SpeechList = new ArrayList<>(); + + boolean found = false; + int i = 0; + for (SpeechInfo l : SpeechList) { + if (l.getId().equals(SpeechInfo.getId())) { + SpeechList.set(i, SpeechInfo); + found = true; + } + i++; + } + if (!found)//add new + SpeechList.add(SpeechInfo); + + mSharedPrefs.saveSpeechList(SpeechList); + adapter.data = SpeechList; + adapter.notifyDataSetChanged(); + } + + private boolean showNoDeviceAttachedDialog(final SpeechInfo SpeechInfo) { + new MaterialDialog.Builder(this) + .title(R.string.noSwitchSelected_title) + .content(getString(R.string.noSwitchSelected_explanation_Speech) + + UsefulBits.newLine() + + UsefulBits.newLine() + + getString(R.string.noSwitchSelected_connectOneNow)) + .positiveText(R.string.yes) + .negativeText(R.string.no) + .onPositive(new MaterialDialog.SingleButtonCallback() { + @Override + public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { + getSwitchesAndShowSwitchesDialog(SpeechInfo); + result = true; + } + }) + .show(); + return result; + } + + @Override + public boolean onEnableClick(SpeechInfo Speech, boolean checked) { + if (Speech.getSwitchIdx() <= 0 && checked) + return showNoDeviceAttachedDialog(Speech); + else { + Speech.setEnabled(checked); + updateSpeech(Speech); + return checked; + } + } + + @Override + public void onRemoveClick(SpeechInfo Speech) { + showRemoveUndoSnackbar(Speech); + } + + private void showRemoveUndoSnackbar(final SpeechInfo SpeechInfo) { + // remove location from list view + removeSpeechFromListView(SpeechInfo); + + // Show snackbar with undo option + String text = String.format(getString(R.string.something_deleted), + getString(R.string.Speech)); + + UsefulBits.showSnackbar(this, coordinatorLayout, text, Snackbar.LENGTH_SHORT, new Snackbar.Callback() { + @Override + public void onDismissed(Snackbar snackbar, int event) { + super.onDismissed(snackbar, event); + + switch (event) { + case Snackbar.Callback.DISMISS_EVENT_TIMEOUT: + case Snackbar.Callback.DISMISS_EVENT_CONSECUTIVE: + case Snackbar.Callback.DISMISS_EVENT_MANUAL: + removeSpeechFromListView(SpeechInfo); + break; + } + } + }, new View.OnClickListener() { + @Override + public void onClick(View v) { + updateSpeech(SpeechInfo);//undo + } + }, this.getString(R.string.undo)); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + try { + if (mSharedPrefs.isSpeechEnabled()) + getMenuInflater().inflate(R.menu.menu_speech, menu); + } catch (Exception ex) { + ex.printStackTrace(); + } + return super.onCreateOptionsMenu(menu); + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + switch (item.getItemId()) { + case android.R.id.home: + finish(); + return true; + case R.id.action_speech: + if (speechRecognizer == null) + speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this); + if (recognitionProgressView == null) + recognitionProgressView = (RecognitionProgressView) findViewById(R.id.recognition_view); + if (recognitionListener == null) { + recognitionListener = new RecognitionListenerAdapter() { + @Override + public void onResults(Bundle results) { + showSpeechResults(results); + stopRecognition(); + } + }; + } + + int[] colors = { + ContextCompat.getColor(this, R.color.material_amber_600), + ContextCompat.getColor(this, R.color.material_blue_600), + ContextCompat.getColor(this, R.color.material_deep_purple_600), + ContextCompat.getColor(this, R.color.material_green_600), + ContextCompat.getColor(this, R.color.material_orange_600) + }; + recognitionProgressView.setColors(colors); + recognitionProgressView.setSpeechRecognizer(speechRecognizer); + recognitionProgressView.setRecognitionListener(recognitionListener); + recognitionProgressView.postDelayed(new Runnable() { + @Override + public void run() { + startRecognition(); + } + }, 50); + + return true; + } + + return super.onOptionsItemSelected(item); + } + + private void playRecognitionAnimation() { + ((LinearLayout) findViewById(R.id.main)).setVisibility(View.GONE); + recognitionProgressView.setVisibility(View.VISIBLE); + recognitionProgressView.play(); + } + + private void stopRecognitionAnimation() { + ((LinearLayout) findViewById(R.id.main)).setVisibility(View.VISIBLE); + recognitionProgressView.setVisibility(View.GONE); + recognitionProgressView.stop(); + } + + private void showSpeechResults(Bundle results) { + ArrayList matches = results + .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION); + //Toast.makeText(this, matches.get(0), Toast.LENGTH_LONG).show(); + processResult(matches.get(0).toLowerCase()); + } + + private void startRecognition() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { + if (PermissionsUtil.canAccessAudioState(this)) { + Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); + + speechRecognizer.startListening(intent); + listeningSpeechRecognition = true; + playRecognitionAnimation(); + } else { + requestPermissions(PermissionsUtil.INITIAL_AUDIO_PERMS, PermissionsUtil.INITIAL_AUDIO_REQUEST); + } + } else { + Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH); + intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getPackageName()); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM); + intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault()); + speechRecognizer.startListening(intent); + + listeningSpeechRecognition = true; + playRecognitionAnimation(); + } + } + + private void stopRecognition() { + if (speechRecognizer != null) { + speechRecognizer.stopListening(); + speechRecognizer.cancel(); + speechRecognizer.destroy(); + } + stopRecognitionAnimation(); + listeningSpeechRecognition = false; + } + + + @Override + public void onRequestPermissionsResult( + int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { + switch (requestCode) { + case PermissionsUtil.INITIAL_AUDIO_REQUEST: + if (PermissionsUtil.canAccessAudioState(this)) { + startRecognition(); + } + break; + } + } + + private void removeSpeechFromListView(SpeechInfo SpeechInfo) { + SpeechList.remove(SpeechInfo); + mSharedPrefs.saveSpeechList(SpeechList); + + adapter.data = SpeechList; + adapter.notifyDataSetChanged(); + } + + /* Called when the second activity's finishes */ + protected void processResult(final String speechText) { + boolean newTagFound = true; + busyWithSpeech = true; + if (SpeechList != null && SpeechList.size() > 0) { + for (SpeechInfo n : SpeechList) { + if (n.getId().equals(speechText)) + newTagFound = false; + } + } + + if (newTagFound) { + UsefulBits.showSimpleSnackbar(SpeechSettingsActivity.this, coordinatorLayout, getString(R.string.Speech_saved) + ": " + speechText, Snackbar.LENGTH_SHORT); + SpeechInfo SpeechInfo = new SpeechInfo(); + SpeechInfo.setId(speechText); + SpeechInfo.setName(speechText); + updateSpeech(SpeechInfo); + } else { + UsefulBits.showSimpleSnackbar(this, coordinatorLayout, R.string.Speech_exists, Snackbar.LENGTH_SHORT); + busyWithSpeech = false; + } + } + + @Override + public void onBackPressed() { + if (listeningSpeechRecognition) { + stopRecognition(); + } else { + super.onBackPressed(); + } + } +} \ No newline at end of file diff --git a/app/src/main/java/nl/hnogames/domoticz/UI/SwitchLogInfoDialog.java b/app/src/main/java/nl/hnogames/domoticz/UI/SwitchLogInfoDialog.java index 54cf53f13..3650ec3ca 100644 --- a/app/src/main/java/nl/hnogames/domoticz/UI/SwitchLogInfoDialog.java +++ b/app/src/main/java/nl/hnogames/domoticz/UI/SwitchLogInfoDialog.java @@ -46,7 +46,6 @@ public SwitchLogInfoDialog(Context c, int layout) { this.info = _info; this.mContext = c; - mdb = new MaterialDialog.Builder(mContext); mdb.customView(layout, true) .positiveText(android.R.string.ok); @@ -55,7 +54,6 @@ public SwitchLogInfoDialog(Context c, @Override public void onDismiss(DialogInterface dialog) { - } public void show() { diff --git a/app/src/main/java/nl/hnogames/domoticz/UI/TemperatureDialog.java b/app/src/main/java/nl/hnogames/domoticz/UI/TemperatureDialog.java index 237346425..0210fa0ce 100644 --- a/app/src/main/java/nl/hnogames/domoticz/UI/TemperatureDialog.java +++ b/app/src/main/java/nl/hnogames/domoticz/UI/TemperatureDialog.java @@ -75,7 +75,7 @@ public TemperatureDialog(Context mContext, double temp) { ConfigInfo configInfo = new ServerUtil(mContext).getActiveServer().getConfigInfo(mContext); if (configInfo != null) { tempSign = UsefulBits.getDegreeSymbol() + configInfo.getTempSign(); - if (!configInfo.getTempSign().equals(Domoticz.Temperature.Sign.CELSIUS)) { + if (!UsefulBits.isEmpty(configInfo.getTempSign()) && !configInfo.getTempSign().equals(Domoticz.Temperature.Sign.CELSIUS)) { isFahrenheit = true; } } else diff --git a/app/src/main/java/nl/hnogames/domoticz/UpdateActivity.java b/app/src/main/java/nl/hnogames/domoticz/UpdateActivity.java index 59fee22d2..61d311ad2 100644 --- a/app/src/main/java/nl/hnogames/domoticz/UpdateActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/UpdateActivity.java @@ -67,6 +67,8 @@ protected void onCreate(Bundle savedInstanceState) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); if (!UsefulBits.isEmpty(mSharedPrefs.getDisplayLanguage())) UsefulBits.setDisplayLanguage(this, mSharedPrefs.getDisplayLanguage()); @@ -338,7 +340,7 @@ private void showSimpleSnackbar(String message) { CoordinatorLayout fragmentCoordinatorLayout = (CoordinatorLayout) findViewById(R.id.coordinatorLayout); if (fragmentCoordinatorLayout != null) { - Snackbar.make(fragmentCoordinatorLayout, message, Snackbar.LENGTH_SHORT).show(); + UsefulBits.showSimpleSnackbar(this, fragmentCoordinatorLayout, message, Snackbar.LENGTH_SHORT); } } diff --git a/app/src/main/java/nl/hnogames/domoticz/Utils/PermissionsUtil.java b/app/src/main/java/nl/hnogames/domoticz/Utils/PermissionsUtil.java index 744dd0762..3a23b8b89 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Utils/PermissionsUtil.java +++ b/app/src/main/java/nl/hnogames/domoticz/Utils/PermissionsUtil.java @@ -47,6 +47,10 @@ public class PermissionsUtil { public static final String[] INITIAL_CAMERA_PERMS = { Manifest.permission.CAMERA }; + //these permissions are needed for recording audio + public static final String[] INITIAL_AUDIO_PERMS = { + Manifest.permission.RECORD_AUDIO + }; //This range is from 0 to 255!! public static final int INITIAL_LOCATION_REQUEST = 111; @@ -54,6 +58,7 @@ public class PermissionsUtil { public static final int INITIAL_EXPORT_SETTINGS_REQUEST = 133; public static final int INITIAL_CAMERA_REQUEST = 144; public static final int INITIAL_DEVICE_REQUEST = 155; + public static final int INITIAL_AUDIO_REQUEST = 166; @SuppressWarnings("unused") private static final String TAG = PermissionsUtil.class.getSimpleName(); @@ -74,6 +79,10 @@ public static boolean canAccessDeviceState(Context context) { return (hasPermission(Manifest.permission.READ_PHONE_STATE, context)); } + public static boolean canAccessAudioState(Context context) { + return (hasPermission(Manifest.permission.RECORD_AUDIO, context)); + } + private static boolean hasPermission(String permission, Context context) { // Using ContextCompat.checkSelfPermission will work on all API versions return (PackageManager.PERMISSION_GRANTED diff --git a/app/src/main/java/nl/hnogames/domoticz/Utils/SerializableManager.java b/app/src/main/java/nl/hnogames/domoticz/Utils/SerializableManager.java index 0629fcccc..d24a039a2 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Utils/SerializableManager.java +++ b/app/src/main/java/nl/hnogames/domoticz/Utils/SerializableManager.java @@ -1,15 +1,14 @@ package nl.hnogames.domoticz.Utils; import android.content.Context; +import android.os.Environment; +import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.io.Serializable; - -import nl.hnogames.domoticz.Containers.ServerInfo; /** * Copyright (C) 2015 Domoticz @@ -42,14 +41,20 @@ public class SerializableManager { * @param fileName The name of the file. */ public static void saveSerializable(Context context, Object objectToSave, String fileName) { - try { - FileOutputStream fileOutputStream = context.openFileOutput(fileName, Context.MODE_PRIVATE); - ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream); + File SettingsFile = new File(Environment.getExternalStorageDirectory(), + "/Domoticz/DomoticzSettings.txt"); + + final String sPath = SettingsFile.getPath(). + substring(0, SettingsFile.getPath().lastIndexOf("/")); - objectOutputStream.writeObject(objectToSave); + //noinspection unused + boolean mkdirsResultIsOk = new File(sPath + "/").mkdirs(); + String combinedFilename = sPath + "/" + fileName; - objectOutputStream.close(); - fileOutputStream.close(); + try { + ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(combinedFilename)); + output.writeObject(objectToSave); + output.close(); } catch (IOException e) { e.printStackTrace(); } @@ -65,13 +70,23 @@ public static void saveSerializable(Context context, Object objectToSave, String public static Object readSerializedObject(Context context, String fileName) { Object objectToReturn = null; - try { - FileInputStream fis = context.openFileInput(fileName); - ObjectInputStream ois = new ObjectInputStream(fis); - objectToReturn = ois.readObject(); + File SettingsFile = new File(Environment.getExternalStorageDirectory(), + "/Domoticz/DomoticzSettings.txt"); - ois.close(); - fis.close(); + final String sPath = SettingsFile.getPath(). + substring(0, SettingsFile.getPath().lastIndexOf("/")); + + //noinspection unused + boolean mkdirsResultIsOk = new File(sPath + "/").mkdirs(); + String combinedFilename = sPath + "/" + fileName; + + if (!new File(combinedFilename).exists()) + return null; + + try { + ObjectInputStream input = new ObjectInputStream(new FileInputStream(combinedFilename)); + objectToReturn = input.readObject(); + input.close(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } diff --git a/app/src/main/java/nl/hnogames/domoticz/Utils/ServerUtil.java b/app/src/main/java/nl/hnogames/domoticz/Utils/ServerUtil.java index 4417fc297..ea3a5dea2 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Utils/ServerUtil.java +++ b/app/src/main/java/nl/hnogames/domoticz/Utils/ServerUtil.java @@ -47,11 +47,6 @@ public class ServerUtil { private final String SERVER_PREFS = "remote_servers"; private final String SERVER_PREFS_ACTIVE = "active_server"; - private final String JSON_CONFIG_INFO = "configInfo"; - private final String JSON_VALUE_PAIRS = "nameValuePairs"; - private final String JSON_OBJECT = "jsonObject"; - private final String serverUpdateInfoJSON_SERVER_UPDATE_INFO = "serverUpdateInfo"; - private Context mContext; private ServerInfo mActiveServer; @@ -91,12 +86,18 @@ private void loadDomoticzServers() { if (!UsefulBits.isEmpty(serverSettings)) { mServerList = new ArrayList<>(); + String JSON_VALUE_PAIRS = "nameValuePairs"; + String JSON_CONFIG_INFO = "configInfo"; + String JSON_OBJECT = "jsonObject"; + String serverUpdateInfoJSON_SERVER_UPDATE_INFO = "serverUpdateInfo"; try { JSONArray jsonSettingsArray = new JSONArray(serverSettings); for (int i = 0; i < jsonSettingsArray.length(); i++) { JSONObject jsonServer = jsonSettingsArray.getJSONObject(i); ServerInfo oPrefServer = new ServerInfo(); oPrefServer.setServerName(jsonServer.getString("SERVER_NAME")); + if (jsonServer.has("SERVER_UNIQUE_ID")) + oPrefServer.setServerUniqueId(jsonServer.getString("SERVER_UNIQUE_ID")); oPrefServer.setRemoteServerUsername(jsonServer.getString("REMOTE_SERVER_USERNAME")); oPrefServer.setRemoteServerPassword(jsonServer.getString("REMOTE_SERVER_PASSWORD")); oPrefServer.setRemoteServerUrl(jsonServer.getString("REMOTE_SERVER_URL")); @@ -158,6 +159,8 @@ private void loadDomoticzServers() { jsonServer = new JSONObject(activeServerSettings); ServerInfo oPrefServer = new ServerInfo(); oPrefServer.setServerName(jsonServer.getString("SERVER_NAME")); + if (jsonServer.has("SERVER_UNIQUE_ID")) + oPrefServer.setServerUniqueId(jsonServer.getString("SERVER_UNIQUE_ID")); oPrefServer.setRemoteServerUsername(jsonServer.getString("REMOTE_SERVER_USERNAME")); oPrefServer.setRemoteServerPassword(jsonServer.getString("REMOTE_SERVER_PASSWORD")); oPrefServer.setRemoteServerUrl(jsonServer.getString("REMOTE_SERVER_URL")); diff --git a/app/src/main/java/nl/hnogames/domoticz/Utils/SharedPrefUtil.java b/app/src/main/java/nl/hnogames/domoticz/Utils/SharedPrefUtil.java index a69786350..700709aa8 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Utils/SharedPrefUtil.java +++ b/app/src/main/java/nl/hnogames/domoticz/Utils/SharedPrefUtil.java @@ -59,6 +59,7 @@ import nl.hnogames.domoticz.Containers.NFCInfo; import nl.hnogames.domoticz.Containers.QRCodeInfo; import nl.hnogames.domoticz.Containers.ServerUpdateInfo; +import nl.hnogames.domoticz.Containers.SpeechInfo; import nl.hnogames.domoticz.Domoticz.Domoticz; import nl.hnogames.domoticz.Interfaces.LanguageReceiver; import nl.hnogames.domoticz.R; @@ -85,8 +86,10 @@ public class SharedPrefUtil { private static final String PREF_NAVIGATION_ITEMS = "enable_menu_items"; private static final String PREF_NFC_TAGS = "nfc_tags"; private static final String PREF_QR_CODES = "qr_codes"; + private static final String PREF_SPEECH_COMMANDS = "speech_commands"; private static final String PREF_GEOFENCE_LOCATIONS = "geofence_locations"; private static final String PREF_GEOFENCE_ENABLED = "geofence_enabled"; + private static final String PREF_SPEECH_ENABLED = "enableSpeech"; private static final String PREF_QRCODE_ENABLED = "enableQRCode"; private static final String PREF_GEOFENCE_STARTED = "geofence_started"; private static final String PREF_ADVANCED_SETTINGS_ENABLED = "advanced_settings_enabled"; @@ -100,6 +103,8 @@ public class SharedPrefUtil { private static final String PREF_SUPPRESS_NOTIFICATIONS = "suppressNotifications"; private static final String PREF_RECEIVED_NOTIFICATIONS = "receivedNotifications"; private static final String PREF_CHECK_UPDATES = "checkForSystemUpdates"; + private static final String PREF_LAST_VERSION = "lastappversion"; + private final String TAG = "Shared Pref util"; @SuppressWarnings("FieldCanBeLocal") private final String PREF_SORT_LIKESERVER = "sort_dashboardLikeServer"; @@ -458,7 +463,7 @@ public void setNavigationDefaults() { editor.putStringSet(PREF_NAVIGATION_ITEMS, selections).apply(); } - public int[] getNavigationIcons() { + public String[] getNavigationIcons() { if (!prefs.contains(PREF_NAVIGATION_ITEMS)) setNavigationDefaults(); TypedArray icons = mContext.getResources().obtainTypedArray(R.array.drawer_icons); @@ -466,14 +471,13 @@ public int[] getNavigationIcons() { String[] allNames = mContext.getResources().getStringArray(R.array.drawer_actions); if (selections != null) { - - int[] selectedICONS = new int[selections.size()]; + String[] selectedICONS = new String[selections.size()]; int iconIndex = 0; int index = 0; for (String v : allNames) { for (String s : selections) { if (s.equals(v)) { - selectedICONS[iconIndex] = icons.getResourceId(index, 0); + selectedICONS[iconIndex] = icons.getString(index); iconIndex++; } } @@ -515,6 +519,15 @@ public boolean isServerUpdateAvailable() { return prefs.getBoolean(PREF_UPDATE_SERVER_AVAILABLE, false); } + public String getPreviousVersionNumber() { + return prefs.getString(PREF_LAST_VERSION, ""); + } + + public void setVersionNumber(String version) { + editor.putString(PREF_LAST_VERSION, version); + editor.commit(); + } + public String getLastUpdateShown() { return prefs.getString(PREF_UPDATE_SERVER_SHOWN, ""); } @@ -524,6 +537,7 @@ public void setLastUpdateShown(String revisionNb) { editor.commit(); } + public boolean isGeofenceEnabled() { return prefs.getBoolean(PREF_GEOFENCE_ENABLED, false); } @@ -536,6 +550,10 @@ public boolean isQRCodeEnabled() { return prefs.getBoolean(PREF_QRCODE_ENABLED, false); } + public boolean isSpeechEnabled() { + return prefs.getBoolean(PREF_SPEECH_ENABLED, false); + } + public void saveNFCList(List list) { Gson gson = new Gson(); editor.putString(PREF_NFC_TAGS, gson.toJson(list)); @@ -584,6 +602,30 @@ public ArrayList getQRCodeList() { return oReturnValue; } + public void saveSpeechList(List list) { + Gson gson = new Gson(); + editor.putString(PREF_SPEECH_COMMANDS, gson.toJson(list)); + editor.commit(); + } + + public ArrayList getSpeechList() { + ArrayList oReturnValue = new ArrayList<>(); + List qrs; + if (prefs.contains(PREF_SPEECH_COMMANDS)) { + String jsonNFCs = prefs.getString(PREF_SPEECH_COMMANDS, null); + Gson gson = new Gson(); + SpeechInfo[] item = gson.fromJson(jsonNFCs, + SpeechInfo[].class); + qrs = Arrays.asList(item); + for (SpeechInfo n : qrs) { + oReturnValue.add(n); + } + } else + return null; + + return oReturnValue; + } + public void saveLocations(List locations) { Gson gson = new Gson(); String jsonLocations = gson.toJson(locations); diff --git a/app/src/main/java/nl/hnogames/domoticz/Utils/UsefulBits.java b/app/src/main/java/nl/hnogames/domoticz/Utils/UsefulBits.java index 0cbcfadf2..11a3f7394 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Utils/UsefulBits.java +++ b/app/src/main/java/nl/hnogames/domoticz/Utils/UsefulBits.java @@ -29,9 +29,12 @@ import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; +import android.support.design.widget.CoordinatorLayout; +import android.support.design.widget.Snackbar; import android.text.format.DateUtils; import android.util.DisplayMetrics; import android.util.Log; +import android.view.View; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; @@ -42,21 +45,25 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; import java.util.Calendar; import java.util.Locale; import java.util.UUID; +import hugo.weaving.DebugLog; +import nl.hnogames.domoticz.Containers.AuthInfo; import nl.hnogames.domoticz.Containers.ConfigInfo; +import nl.hnogames.domoticz.Containers.UserInfo; import nl.hnogames.domoticz.Domoticz.Domoticz; +import nl.hnogames.domoticz.Interfaces.AuthReceiver; import nl.hnogames.domoticz.Interfaces.ConfigReceiver; +import nl.hnogames.domoticz.Interfaces.UsersReceiver; import nl.hnogames.domoticz.MainActivity; import nl.hnogames.domoticz.R; import nl.hnogames.domoticz.Service.TaskService; public class UsefulBits { - public static final String TASK_TAG_PERIODIC = "taskPeriodic"; - private static final int RC_PLAY_SERVICES = 123; @SuppressWarnings("FieldCanBeLocal") @@ -87,10 +94,12 @@ public static char getDegreeSymbol() { return '\u00B0'; } + @DebugLog public static String createUniqueId() { return UUID.randomUUID().toString(); } + @DebugLog public static double[] rgb2hsv(int red, int green, int blue) { double computedH, computedS, computedV; double r, g, b; @@ -122,6 +131,7 @@ public static double[] rgb2hsv(int red, int green, int blue) { return new double[]{computedH, computedS, computedV}; } + @DebugLog public static String getMd5String(String password) { StringBuilder hexString = new StringBuilder(); MessageDigest md; @@ -150,7 +160,11 @@ public static String getMd5String(String password) { * * @param in_array byte array to convert */ + @DebugLog public static String ByteArrayToHexString(byte[] in_array) { + if (in_array == null) + return null; + int i, j, in; String[] hex = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}; String out = ""; @@ -171,6 +185,7 @@ public static String ByteArrayToHexString(byte[] in_array) { * @param context Context * @param lang Language to display */ + @DebugLog public static void setDisplayLanguage(Context context, String lang) { Locale myLocale = new Locale(lang); Resources res = context.getResources(); @@ -185,6 +200,7 @@ public static void setDisplayLanguage(Context context, String lang) { * * @return Returns the phone display language */ + @DebugLog public static String getPhoneDisplayLocale() { if (!isEmpty(Locale.getDefault().getLanguage())) return Locale.getDefault().getLanguage(); @@ -200,6 +216,7 @@ public static String getPhoneDisplayLocale() { * @param context Context * @return Returns the active language */ + @DebugLog public static String getActiveLanguage(Context context) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(context); @@ -222,6 +239,7 @@ public static String getActiveLanguage(Context context) { * @param context Context * @param forceDownload Force downloading the language anyway */ + @DebugLog public static void checkDownloadedLanguage(Context context, ServerUtil serverUtil, boolean forceDownload, boolean fromService) { SharedPrefUtil mSharedPrefs = new SharedPrefUtil(context); @@ -237,9 +255,9 @@ public static void checkDownloadedLanguage(Context context, ServerUtil serverUti mSharedPrefs.getLanguageStringsFromServer(activeLanguage.toLowerCase(), serverUtil); if (mSharedPrefs.isDebugEnabled()) { if (forceDownload && !fromService) { - showSimpleToast(context, "Language files downloaded because it was forced"); + showSimpleToast(context, "Language files downloaded because it was forced", Toast.LENGTH_SHORT); } else if (!fromService) - showSimpleToast(context, "Language files downloaded because there were none"); + showSimpleToast(context, "Language files downloaded because there were none", Toast.LENGTH_SHORT); } } else { long dateMillis = mSharedPrefs.getSavedLanguageDate(); @@ -247,13 +265,13 @@ public static void checkDownloadedLanguage(Context context, ServerUtil serverUti Log.d(TAG, "Language files are dated: " + dateStr); if (mSharedPrefs.isDebugEnabled() && !fromService) - showSimpleToast(context, "Language files are dated: " + dateStr); + showSimpleToast(context, "Language files are dated: " + dateStr, Toast.LENGTH_SHORT); // check if downloaded files are the correct ones if (!downloadedLanguage.equalsIgnoreCase(activeLanguage)) { if (mSharedPrefs.isDebugEnabled() && !fromService) - showSimpleToast(context, "Downloaded language files did not match the preferred language"); + showSimpleToast(context, "Downloaded language files did not match the preferred language", Toast.LENGTH_SHORT); Log.d(TAG, "Downloaded language files did not match the preferred language:" + newLine() + "Current downloaded language: " + downloadedLanguage + newLine() @@ -269,6 +287,7 @@ public static void checkDownloadedLanguage(Context context, ServerUtil serverUti * * @param activity to restart */ + @DebugLog public static void restartApplication(Activity activity) { Intent refresh = new Intent(activity, MainActivity.class); activity.finish(); @@ -282,6 +301,7 @@ public static void restartApplication(Activity activity) { * @param label Label of the to copy text * @param text Text to copy */ + @DebugLog public static void copyToClipboard(Context mContext, String label, String text) { ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = ClipData.newPlainText(label, text); @@ -315,13 +335,15 @@ public static int differenceInDays(long day1, long day2) { * * @param context Context to use */ + @DebugLog public static void setScheduledTasks(Context context) { final SharedPrefUtil mSharedPrefUtil = new SharedPrefUtil(context); if (!mSharedPrefUtil.getTaskIsScheduled()) { // Only when not already scheduled - if (mSharedPrefUtil.isDebugEnabled()) showSimpleToast(context, "Scheduling new task"); + if (mSharedPrefUtil.isDebugEnabled()) + showSimpleToast(context, "Scheduling new task", Toast.LENGTH_SHORT); GcmNetworkManager mGcmNetworkManager = GcmNetworkManager.getInstance(context); @@ -339,7 +361,7 @@ public static void setScheduledTasks(Context context) { mGcmNetworkManager.schedule(task); mSharedPrefUtil.setTaskIsScheduled(true); } else if (mSharedPrefUtil.isDebugEnabled()) - showSimpleToast(context, "Tasks already scheduled"); + showSimpleToast(context, "Tasks already scheduled", Toast.LENGTH_SHORT); } /** @@ -348,14 +370,14 @@ public static void setScheduledTasks(Context context) { * @param context Context * @param forced Force update the config */ - public static void saveServerConfigToActiveServer(final Context context, boolean forced, final boolean showSuccessMessage) { + @DebugLog + public static void getServerConfigForActiveServer(final Context context, boolean forced, final ConfigReceiver receiver, final ConfigInfo currentConfig) { final ServerUtil mServerUtil = new ServerUtil(context); final Domoticz domoticz = new Domoticz(context, mServerUtil); - final ConfigInfo mConfigInfo = mServerUtil.getActiveServer().getConfigInfo(context); final long currentTime = Calendar.getInstance().getTimeInMillis(); - if (mConfigInfo != null && !forced) { - final long dateOfConfig = mConfigInfo.getDateOfConfig(); + if (currentConfig != null && !forced) { + final long dateOfConfig = currentConfig.getDateOfConfig(); int age = UsefulBits.differenceInDays(dateOfConfig, currentTime); if (age < DAYS_TO_CHECK_FOR_SERVER_CONFIG) { Log.i(TAG, "Skipping ConfigInfo fetch which is " + String.valueOf(age) + " days old"); @@ -365,7 +387,8 @@ public static void saveServerConfigToActiveServer(final Context context, boolean + String.valueOf(age) + " days old (max is: " + String.valueOf(DAYS_TO_CHECK_FOR_SERVER_CONFIG) - + " days old)"); + + " days old)", Toast.LENGTH_SHORT); + receiver.onReceiveConfig(currentConfig); return; } } @@ -373,26 +396,70 @@ public static void saveServerConfigToActiveServer(final Context context, boolean // Get Domoticz server configuration domoticz.getConfig(new ConfigReceiver() { @Override - public void onReceiveConfig(ConfigInfo configInfo) { + @DebugLog + public void onReceiveConfig(final ConfigInfo configInfo) { if (configInfo != null) { configInfo.setDateOfConfig(currentTime); - mServerUtil.getActiveServer().setConfigInfo(context, configInfo); - mServerUtil.saveDomoticzServers(true); - if (showSuccessMessage) - showSimpleToast(context, context.getString(R.string.fetched_server_config_success)); + domoticz.getUsers(new UsersReceiver() { + @Override + @DebugLog + public void onReceiveUsers(final ArrayList mUserInfo) { + if (mUserInfo != null) { + domoticz.getUserAuthenticationRights(new AuthReceiver() { + @Override + @DebugLog + public void onReceiveAuthentication(AuthInfo auth) { + ArrayList mDetailUserInfo = mUserInfo; + //also add current user + UserInfo currentUser = new UserInfo(domoticz.getUserCredentials(Domoticz.Authentication.USERNAME), + UsefulBits.getMd5String(domoticz.getUserCredentials(Domoticz.Authentication.PASSWORD)), + auth.getRights()); + + mDetailUserInfo.add(currentUser); + configInfo.setUsers(mDetailUserInfo); + mServerUtil.getActiveServer().setConfigInfo(context, configInfo); + mServerUtil.saveDomoticzServers(true); + + if (receiver != null) + receiver.onReceiveConfig(configInfo); + } + + @Override + @DebugLog + public void onError(Exception error) { + } + }); + } else { + mServerUtil.getActiveServer().setConfigInfo(context, configInfo); + mServerUtil.saveDomoticzServers(true); + } + } + + @Override + @DebugLog + public void onError(Exception error) { + if (currentConfig != null) { + configInfo.setUsers(currentConfig.getUsers()); + } + + if (receiver != null) + receiver.onReceiveConfig(configInfo); + } + }); } } @Override + @DebugLog public void onError(Exception error) { - String message = String.format( + showSimpleToast(context, String.format( context.getString(R.string.error_couldNotCheckForConfig), - domoticz.getErrorMessage(error)); - showSimpleToast(context, message); + domoticz.getErrorMessage(error)), Toast.LENGTH_SHORT); } }); } + @DebugLog public static boolean checkPlayServicesAvailable(final Activity activity) { GoogleApiAvailability availability = GoogleApiAvailability.getInstance(); int resultCode = availability.isGooglePlayServicesAvailable(activity); @@ -405,7 +472,7 @@ public static boolean checkPlayServicesAvailable(final Activity activity) { // Unresolvable error Log.e(TAG, "Google Play services is unavailable."); showSimpleToast(activity, - activity.getString(R.string.google_play_services_unavailable)); + activity.getString(R.string.google_play_services_unavailable), Toast.LENGTH_SHORT); return false; } } @@ -415,11 +482,62 @@ public static boolean checkPlayServicesAvailable(final Activity activity) { return true; } - public static void showSimpleToast(Context context, String message) { - //sometimes this method is called from a service, but then we don't have an activity to show the Toast. - //for now, we suppress that exception & toast + @DebugLog + public static void showSimpleToast(Context context, String message, int length) { + try { + Toast.makeText(context, message, length).show(); + } catch (Exception ex) { + } + } + + @DebugLog + public static void showSimpleSnackbar(Context context, CoordinatorLayout coordinatorLayout, int message_resource_id, int length) { + try { + if (context != null && coordinatorLayout != null) + showSimpleSnackbar(context, coordinatorLayout, context.getString(message_resource_id), length); + } catch (Exception ex) { + } + } + + @DebugLog + public static void showSimpleSnackbar(Context context, CoordinatorLayout coordinatorLayout, String message, int length) { try { - Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); + if (context != null && coordinatorLayout != null && !UsefulBits.isEmpty(message)) + Snackbar.make(coordinatorLayout, message, length).show(); + } catch (Exception ex) { + } + } + + @DebugLog + public static void showSnackbar(Context context, CoordinatorLayout coordinatorLayout, String message, int length, + Snackbar.Callback callback, + View.OnClickListener onclickListener, String actiontext) { + try { + if (context != null && + coordinatorLayout != null && + !UsefulBits.isEmpty(message)) { + if (onclickListener == null || UsefulBits.isEmpty(actiontext)) { + if (callback != null) { + Snackbar.make(coordinatorLayout, message, length) + .setCallback(callback) + .show(); + } else { + Snackbar.make(coordinatorLayout, message, length) + .show(); + } + } else { + if (callback != null) { + Snackbar.make(coordinatorLayout, message, length) + .setAction(actiontext, onclickListener) + .setCallback(callback) + .show(); + } else { + Snackbar.make(coordinatorLayout, message, length) + .setAction(actiontext, onclickListener) + .show(); + } + } + } } catch (Exception ex) { } } diff --git a/app/src/main/java/nl/hnogames/domoticz/Welcome/SetupServerSettings.java b/app/src/main/java/nl/hnogames/domoticz/Welcome/SetupServerSettings.java index 3aab3f05f..71b83317a 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Welcome/SetupServerSettings.java +++ b/app/src/main/java/nl/hnogames/domoticz/Welcome/SetupServerSettings.java @@ -29,6 +29,7 @@ import android.support.annotation.NonNull; import android.support.v4.app.Fragment; import android.support.v7.app.AlertDialog; +import android.text.InputType; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.LayoutInflater; @@ -43,9 +44,11 @@ import android.widget.Spinner; import android.widget.Switch; +import com.afollestad.materialdialogs.MaterialDialog; import com.marvinlabs.widget.floatinglabel.edittext.FloatingLabelEditText; import java.util.ArrayList; +import java.util.Set; import nl.hnogames.domoticz.Containers.ServerInfo; import nl.hnogames.domoticz.Domoticz.Domoticz; @@ -86,6 +89,7 @@ public class SetupServerSettings extends Fragment { private ServerInfo newServer; private boolean isUpdateRequest = false; private Context mContext; + private Button btnManualSSID; public static SetupServerSettings newInstance(int instance) { SetupServerSettings f = new SetupServerSettings(); @@ -159,6 +163,36 @@ private void getLayoutReferences() { cbShowPasswordLocal = (CheckBox) v.findViewById(R.id.showpasswordlocal); startScreen_spinner = (Spinner) v.findViewById(R.id.startScreen_spinner); + + btnManualSSID = (Button) v.findViewById(R.id.set_ssid); + btnManualSSID.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + new MaterialDialog.Builder(getContext()) + .title(R.string.welcome_ssid_button_prompt) + .content(R.string.welcome_msg_no_ssid_found) + .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) + .input(null, null, new MaterialDialog.InputCallback() { + @Override + public void onInput(MaterialDialog dialog, CharSequence input) { + Set ssidFromPrefs = mServerUtil.getActiveServer().getLocalServerSsid(); + final ArrayList ssidListFromPrefs = new ArrayList<>(); + if (ssidFromPrefs != null) { + if (ssidFromPrefs.size() > 0) { + for (String wifi : ssidFromPrefs) { + ssidListFromPrefs.add(wifi); + } + } + } + ssidListFromPrefs.add(String.valueOf(input)); + mServerUtil.getActiveServer().setLocalServerSsid(ssidListFromPrefs); + + setSsid_spinner(); + } + }).show(); + } + }); + startScreen_spinner.setVisibility(View.GONE); v.findViewById(R.id.startScreen_title).setVisibility(View.GONE); v.findViewById(R.id.server_settings_title).setVisibility(View.GONE); diff --git a/app/src/main/java/nl/hnogames/domoticz/Welcome/WelcomePage3.java b/app/src/main/java/nl/hnogames/domoticz/Welcome/WelcomePage3.java index 8079e4d45..c232ad06f 100644 --- a/app/src/main/java/nl/hnogames/domoticz/Welcome/WelcomePage3.java +++ b/app/src/main/java/nl/hnogames/domoticz/Welcome/WelcomePage3.java @@ -26,6 +26,7 @@ import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.Fragment; +import android.text.InputType; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.LayoutInflater; @@ -33,12 +34,14 @@ import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; +import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Switch; +import com.afollestad.materialdialogs.MaterialDialog; import com.marvinlabs.widget.floatinglabel.edittext.FloatingLabelEditText; import java.util.ArrayList; @@ -77,6 +80,7 @@ public class WelcomePage3 extends Fragment { private PhoneConnectionUtil mPhoneConnectionUtil; private Switch advancedSettings_switch; private CheckBox cbShowPassword, cbShowPasswordLocal; + private Button btnManualSSID; public static WelcomePage3 newInstance(int instance) { WelcomePage3 f = new WelcomePage3(); @@ -139,6 +143,34 @@ private void getLayoutReferences() { cbShowPasswordLocal = (CheckBox) v.findViewById(R.id.showpasswordlocal); startScreen_spinner = (Spinner) v.findViewById(R.id.startScreen_spinner); + btnManualSSID = (Button) v.findViewById(R.id.set_ssid); + btnManualSSID.setOnClickListener(new View.OnClickListener() { + @Override + public void onClick(View v) { + new MaterialDialog.Builder(getContext()) + .title(R.string.welcome_ssid_button_prompt) + .content(R.string.welcome_msg_no_ssid_found) + .inputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD) + .input(null, null, new MaterialDialog.InputCallback() { + @Override + public void onInput(MaterialDialog dialog, CharSequence input) { + Set ssidFromPrefs = mServerUtil.getActiveServer().getLocalServerSsid(); + final ArrayList ssidListFromPrefs = new ArrayList<>(); + if (ssidFromPrefs != null) { + if (ssidFromPrefs.size() > 0) { + for (String wifi : ssidFromPrefs) { + ssidListFromPrefs.add(wifi); + } + } + } + ssidListFromPrefs.add(String.valueOf(input)); + mServerUtil.getActiveServer().setLocalServerSsid(ssidListFromPrefs); + + setSsid_spinner(); + } + }).show(); + } + }); if (callingInstance == SETTINGS) { // Hide these settings if being called by settings (instead of welcome wizard) @@ -208,9 +240,7 @@ private void setPreferenceValues() { remote_server_input.setInputWidgetText(mServerUtil.getActiveServer().getRemoteServerUrl()); remote_port_input.setInputWidgetText(mServerUtil.getActiveServer().getRemoteServerPort()); remote_directory_input.setInputWidgetText(mServerUtil.getActiveServer().getRemoteServerDirectory()); - localServer_switch.setChecked(mServerUtil.getActiveServer().getIsLocalServerAddressDifferent()); - local_username_input.setInputWidgetText(mServerUtil.getActiveServer().getLocalServerUsername()); local_password_input.setInputWidgetText(mServerUtil.getActiveServer().getLocalServerPassword()); local_server_input.setInputWidgetText(mServerUtil.getActiveServer().getLocalServerUrl()); diff --git a/app/src/main/java/nl/hnogames/domoticz/WidgetConfigurationActivity.java b/app/src/main/java/nl/hnogames/domoticz/WidgetConfigurationActivity.java index b95d97471..d64c011ad 100644 --- a/app/src/main/java/nl/hnogames/domoticz/WidgetConfigurationActivity.java +++ b/app/src/main/java/nl/hnogames/domoticz/WidgetConfigurationActivity.java @@ -23,6 +23,7 @@ import nl.hnogames.domoticz.Service.WidgetProviderLarge; import nl.hnogames.domoticz.UI.PasswordDialog; import nl.hnogames.domoticz.Utils.SharedPrefUtil; +import nl.hnogames.domoticz.Utils.UsefulBits; import nl.hnogames.domoticz.Welcome.WelcomeViewActivity; import static android.appwidget.AppWidgetManager.EXTRA_APPWIDGET_ID; @@ -38,11 +39,17 @@ public class WidgetConfigurationActivity extends AppCompatActivity { private WidgetsAdapter adapter; private SearchView searchViewAction; + private final int iVoiceAction = -55; + private final int iQRCodeAction = -66; + @Override protected void onCreate(Bundle savedInstanceState) { mSharedPrefs = new SharedPrefUtil(this); if (mSharedPrefs.darkThemeEnabled()) setTheme(R.style.AppThemeDark); + else + setTheme(R.style.AppTheme); + super.onCreate(savedInstanceState); setContentView(R.layout.widget_configuration); setResult(RESULT_CANCELED); @@ -87,13 +94,25 @@ protected void onActivityResult(int requestCode, int resultCode, Intent data) { } } - public void initListViews() { if (mSharedPrefs.isWelcomeWizardSuccess()) { Log.i(TAG, "Showing switches for widget"); domoticz.getDevices(new DevicesReceiver() { @Override public void onReceiveDevices(final ArrayList mDevicesInfo) { + if (mSharedPrefs.isSpeechEnabled()) { + DevicesInfo oVoiceRow = new DevicesInfo(); + oVoiceRow.setIdx(iVoiceAction); + oVoiceRow.setName(WidgetConfigurationActivity.this.getString(R.string.action_speech)); + mDevicesInfo.add(0, oVoiceRow); + } + if (mSharedPrefs.isQRCodeEnabled()) { + DevicesInfo oQRCodeRow = new DevicesInfo(); + oQRCodeRow.setIdx(iQRCodeAction); + oQRCodeRow.setName(WidgetConfigurationActivity.this.getString(R.string.action_qrcode_scan)); + mDevicesInfo.add(0, oQRCodeRow); + } + ListView listView = (ListView) findViewById(R.id.list); adapter = new WidgetsAdapter(WidgetConfigurationActivity.this, domoticz, mDevicesInfo); @@ -147,11 +166,16 @@ private void showAppWidget(DevicesInfo mSelectedSwitch, String password) { mAppWidgetId = extras.getInt(EXTRA_APPWIDGET_ID, INVALID_APPWIDGET_ID); - if (mSelectedSwitch.getType().equals(Domoticz.Scene.Type.GROUP) || mSelectedSwitch.getType().equals(Domoticz.Scene.Type.SCENE)) { - mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, true, password); - } else { + if (UsefulBits.isEmpty(mSelectedSwitch.getType())) { mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, false, password); + } else { + if (mSelectedSwitch.getType().equals(Domoticz.Scene.Type.GROUP) || mSelectedSwitch.getType().equals(Domoticz.Scene.Type.SCENE)) { + mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, true, password); + } else { + mSharedPrefs.setWidgetIDX(mAppWidgetId, idx, false, password); + } } + Intent startService = new Intent(WidgetConfigurationActivity.this, WidgetProviderLarge.UpdateWidgetService.class); startService.putExtra(EXTRA_APPWIDGET_ID, mAppWidgetId); diff --git a/app/src/main/java/nl/hnogames/domoticz/app/AppController.java b/app/src/main/java/nl/hnogames/domoticz/app/AppController.java index f36c7f0a3..bc6505f9b 100644 --- a/app/src/main/java/nl/hnogames/domoticz/app/AppController.java +++ b/app/src/main/java/nl/hnogames/domoticz/app/AppController.java @@ -75,8 +75,9 @@ public static synchronized AppController getInstance() { public void onCreate() { super.onCreate(); - if (!BuildConfig.DEBUG && !UsefulBits.isEmpty(getString(R.string.mintapikey))) + if (!BuildConfig.DEBUG && !UsefulBits.isEmpty(getString(R.string.mintapikey))) { Mint.initAndStartSession(this, getString(R.string.mintapikey)); + } if (PermissionsUtil.canAccessDeviceState(this)) StartEasyGCM(); diff --git a/app/src/main/java/nl/hnogames/domoticz/app/DomoticzDashboardFragment.java b/app/src/main/java/nl/hnogames/domoticz/app/DomoticzDashboardFragment.java index e437cc668..280ef00a5 100644 --- a/app/src/main/java/nl/hnogames/domoticz/app/DomoticzDashboardFragment.java +++ b/app/src/main/java/nl/hnogames/domoticz/app/DomoticzDashboardFragment.java @@ -23,6 +23,7 @@ package nl.hnogames.domoticz.app; import android.app.Activity; +import android.content.res.Configuration; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v4.app.Fragment; @@ -124,27 +125,70 @@ public void sortFragment(String sort) { } public void initViews(View root) { + gridView = (RecyclerView) root.findViewById(R.id.my_recycler_view); + if (mSharedPrefs == null) + mSharedPrefs = new SharedPrefUtil(getContext()); + + setGridViewLayout(); + oSpinner = (SpinnerLoader) root.findViewById(R.id.spinner); + coordinatorLayout = (CoordinatorLayout) root.findViewById(R.id.coordinatorLayout); + mSwipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipe_refresh_layout); + } + + public void setGridViewLayout() { + try { - gridView = (RecyclerView) root.findViewById(R.id.my_recycler_view); - if (mSharedPrefs == null) - mSharedPrefs = new SharedPrefUtil(getContext()); + + boolean isTablet = false; + float screenWidth = 0; + boolean isPortrait = false; + + if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) + isPortrait = true; + + if (getActivity() instanceof MainActivity) { + isTablet = !((MainActivity) getActivity()).onPhone; + } + + gridView.setHasFixedSize(true); if (!mSharedPrefs.showDashboardAsList()) { - gridView.setHasFixedSize(true); - GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1); - gridView.setLayoutManager(mLayoutManager); + if (isTablet) { + if (isPortrait) { + GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1); + gridView.setLayoutManager(mLayoutManager); + } else { + GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2); + gridView.setLayoutManager(mLayoutManager); + } + } else { + GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1); + gridView.setLayoutManager(mLayoutManager); + } } else { - gridView.setHasFixedSize(false); - StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); - gridView.setLayoutManager(mLayoutManager); + if (isTablet) { + if (isPortrait) { + StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); + gridView.setLayoutManager(mLayoutManager); + } else { + StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(4, StaggeredGridLayoutManager.VERTICAL); + gridView.setLayoutManager(mLayoutManager); + } + } else { + if (isPortrait) { + StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); + gridView.setLayoutManager(mLayoutManager); + } else { + StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL); + gridView.setLayoutManager(mLayoutManager); + } + } } + gridView.setItemAnimator(new SlideInUpAnimator(new OvershootInterpolator(1f))); } catch (Exception ignored) { } - oSpinner = (SpinnerLoader) root.findViewById(R.id.spinner); - coordinatorLayout = (CoordinatorLayout) root.findViewById(R.id.coordinatorLayout); - mSwipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipe_refresh_layout); } @Override diff --git a/app/src/main/java/nl/hnogames/domoticz/app/DomoticzRecyclerFragment.java b/app/src/main/java/nl/hnogames/domoticz/app/DomoticzRecyclerFragment.java index 5b857e90d..a932de1f5 100644 --- a/app/src/main/java/nl/hnogames/domoticz/app/DomoticzRecyclerFragment.java +++ b/app/src/main/java/nl/hnogames/domoticz/app/DomoticzRecyclerFragment.java @@ -23,6 +23,7 @@ package nl.hnogames.domoticz.app; import android.app.Activity; +import android.content.res.Configuration; import android.os.Bundle; import android.support.design.widget.CoordinatorLayout; import android.support.v4.app.Fragment; @@ -36,6 +37,7 @@ import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; +import android.view.animation.OvershootInterpolator; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; @@ -48,6 +50,7 @@ import java.util.List; +import jp.wasabeef.recyclerview.animators.SlideInUpAnimator; import nl.hnogames.domoticz.Domoticz.Domoticz; import nl.hnogames.domoticz.Interfaces.DomoticzFragmentListener; import nl.hnogames.domoticz.Interfaces.WifiSSIDListener; @@ -120,21 +123,47 @@ public void sortFragment(String sort) { } public void initViews(View root) { + + gridView = (RecyclerView) root.findViewById(R.id.my_recycler_view); + if (mSharedPrefs == null) + mSharedPrefs = new SharedPrefUtil(getContext()); + + setGridViewLayout(); + oSpinner = (SpinnerLoader) root.findViewById(R.id.spinner); + coordinatorLayout = (CoordinatorLayout) root.findViewById(R.id.coordinatorLayout); + mSwipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipe_refresh_layout); + } + + public void setGridViewLayout() { try { - gridView = (RecyclerView) root.findViewById(R.id.my_recycler_view); - if (mSharedPrefs == null) - mSharedPrefs = new SharedPrefUtil(getContext()); + boolean isTablet = false; + float screenWidth = 0; + boolean isPortrait = false; + + if (getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) + isPortrait = true; + if (getActivity() instanceof MainActivity) { + isTablet = !((MainActivity) getActivity()).onPhone; + } gridView.setHasFixedSize(true); - GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1); - gridView.setLayoutManager(mLayoutManager); + if (isTablet) { + if (isPortrait) { + GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1); + gridView.setLayoutManager(mLayoutManager); + } else { + GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 2); + gridView.setLayoutManager(mLayoutManager); + } + } else { + GridLayoutManager mLayoutManager = new GridLayoutManager(getActivity(), 1); + gridView.setLayoutManager(mLayoutManager); + } + + gridView.setItemAnimator(new SlideInUpAnimator(new OvershootInterpolator(1f))); } catch (Exception ex) { } - - oSpinner = (SpinnerLoader) root.findViewById(R.id.spinner); - coordinatorLayout = (CoordinatorLayout) root.findViewById(R.id.coordinatorLayout); - mSwipeRefreshLayout = (SwipeRefreshLayout) root.findViewById(R.id.swipe_refresh_layout); } @Override diff --git a/app/src/main/res/drawable-hdpi/ic_microphone.png b/app/src/main/res/drawable-hdpi/ic_microphone.png new file mode 100644 index 000000000..7c74fcacd Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_microphone.png differ diff --git a/app/src/main/res/drawable-hdpi/mic.png b/app/src/main/res/drawable-hdpi/mic.png new file mode 100644 index 000000000..782d351b8 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/mic.png differ diff --git a/app/src/main/res/drawable-hdpi/qrcode.png b/app/src/main/res/drawable-hdpi/qrcode.png new file mode 100644 index 000000000..820a0fdaf Binary files /dev/null and b/app/src/main/res/drawable-hdpi/qrcode.png differ diff --git a/app/src/main/res/drawable-ldpi/ic_microphone.png b/app/src/main/res/drawable-ldpi/ic_microphone.png new file mode 100644 index 000000000..0e3cdb1d4 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/ic_microphone.png differ diff --git a/app/src/main/res/drawable-ldpi/mic.png b/app/src/main/res/drawable-ldpi/mic.png new file mode 100644 index 000000000..b04cb13f0 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/mic.png differ diff --git a/app/src/main/res/drawable-ldpi/qrcode.png b/app/src/main/res/drawable-ldpi/qrcode.png new file mode 100644 index 000000000..946060941 Binary files /dev/null and b/app/src/main/res/drawable-ldpi/qrcode.png differ diff --git a/app/src/main/res/drawable-mdpi/ic_microphone.png b/app/src/main/res/drawable-mdpi/ic_microphone.png new file mode 100644 index 000000000..afdf3c1ea Binary files /dev/null and b/app/src/main/res/drawable-mdpi/ic_microphone.png differ diff --git a/app/src/main/res/drawable-mdpi/mic.png b/app/src/main/res/drawable-mdpi/mic.png new file mode 100644 index 000000000..86dde81ae Binary files /dev/null and b/app/src/main/res/drawable-mdpi/mic.png differ diff --git a/app/src/main/res/drawable-mdpi/qrcode.png b/app/src/main/res/drawable-mdpi/qrcode.png new file mode 100644 index 000000000..4fac510cd Binary files /dev/null and b/app/src/main/res/drawable-mdpi/qrcode.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_microphone.png b/app/src/main/res/drawable-xhdpi/ic_microphone.png new file mode 100644 index 000000000..97e670fe3 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_microphone.png differ diff --git a/app/src/main/res/drawable-xhdpi/mic.png b/app/src/main/res/drawable-xhdpi/mic.png new file mode 100644 index 000000000..ef0966b93 Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/mic.png differ diff --git a/app/src/main/res/drawable-xhdpi/qrcode.png b/app/src/main/res/drawable-xhdpi/qrcode.png new file mode 100644 index 000000000..ac2dfdd6a Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/qrcode.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_microphone.png b/app/src/main/res/drawable-xxhdpi/ic_microphone.png new file mode 100644 index 000000000..564fa6254 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_microphone.png differ diff --git a/app/src/main/res/drawable-xxhdpi/mic.png b/app/src/main/res/drawable-xxhdpi/mic.png new file mode 100644 index 000000000..28a3cd1e5 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/mic.png differ diff --git a/app/src/main/res/drawable-xxhdpi/qrcode.png b/app/src/main/res/drawable-xxhdpi/qrcode.png new file mode 100644 index 000000000..b176d04e5 Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/qrcode.png differ diff --git a/app/src/main/res/drawable-xxhdpi/users.png b/app/src/main/res/drawable-xxhdpi/users.png new file mode 100644 index 000000000..6ee7e9abf Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/users.png differ diff --git a/app/src/main/res/layout-sw600dp/activity_main.xml b/app/src/main/res/layout-sw600dp/activity_main.xml deleted file mode 100644 index cd230afc0..000000000 --- a/app/src/main/res/layout-sw600dp/activity_main.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/app/src/main/res/layout-sw720dp/activity_newmain.xml b/app/src/main/res/layout-sw720dp/activity_newmain.xml new file mode 100644 index 000000000..56f0f0cea --- /dev/null +++ b/app/src/main/res/layout-sw720dp/activity_newmain.xml @@ -0,0 +1,40 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_geo_settings.xml b/app/src/main/res/layout/activity_geo_settings.xml index 1fb4537e9..412458f67 100644 --- a/app/src/main/res/layout/activity_geo_settings.xml +++ b/app/src/main/res/layout/activity_geo_settings.xml @@ -1,8 +1,8 @@ + android:layout_height="match_parent"> + + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/activity_nfc_settings.xml b/app/src/main/res/layout/activity_nfc_settings.xml index 81bfb1918..4d8f7fabf 100644 --- a/app/src/main/res/layout/activity_nfc_settings.xml +++ b/app/src/main/res/layout/activity_nfc_settings.xml @@ -1,8 +1,8 @@ + android:layout_height="match_parent"> + android:layout_height="match_parent"> + android:layout_height="match_parent"> + + + + + + + + + \ No newline at end of file diff --git a/app/src/main/res/layout/barcode_capture.xml b/app/src/main/res/layout/barcode_capture.xml index ae74cb37c..f415358da 100644 --- a/app/src/main/res/layout/barcode_capture.xml +++ b/app/src/main/res/layout/barcode_capture.xml @@ -1,10 +1,10 @@ + android:keepScreenOn="true" + android:orientation="vertical"> diff --git a/app/src/main/res/layout/camera_row.xml b/app/src/main/res/layout/camera_row.xml index cc1c4e4c6..afe357525 100644 --- a/app/src/main/res/layout/camera_row.xml +++ b/app/src/main/res/layout/camera_row.xml @@ -2,9 +2,9 @@ + \ No newline at end of file diff --git a/app/src/main/res/layout/dashboard_row.xml b/app/src/main/res/layout/dashboard_row.xml index d6679fbcf..1c9ded7f4 100644 --- a/app/src/main/res/layout/dashboard_row.xml +++ b/app/src/main/res/layout/dashboard_row.xml @@ -1,9 +1,10 @@ - + android:orientation="horizontal"> + android:paddingBottom="7dp" + android:text="Switch" /> + android:gravity="left" + android:paddingLeft="10dp" + android:text="@string/battery_level" /> + android:gravity="left" + android:paddingLeft="10dp" + android:text="@string/signal_level" /> + android:orientation="horizontal" + android:paddingBottom="10dp"> + android:orientation="vertical" + android:paddingBottom="10dp"> + android:text="@string/button_color" + android:textSize="10dp" /> + \ No newline at end of file diff --git a/app/src/main/res/layout/dashboard_row_default.xml b/app/src/main/res/layout/dashboard_row_default.xml index 6005a56be..8f6a05828 100644 --- a/app/src/main/res/layout/dashboard_row_default.xml +++ b/app/src/main/res/layout/dashboard_row_default.xml @@ -1,19 +1,19 @@ + android:layout_width="match_parent" + android:layout_height="wrap_content"> + android:orientation="horizontal" + android:padding="10dp"> + android:src="@drawable/clock48" /> + android:orientation="vertical"> + diff --git a/app/src/main/res/layout/default_layout.xml b/app/src/main/res/layout/default_layout.xml index 7b76e4003..745eb527e 100644 --- a/app/src/main/res/layout/default_layout.xml +++ b/app/src/main/res/layout/default_layout.xml @@ -3,9 +3,9 @@ xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/coordinatorLayout" + style="@style/background_recyclerview" android:layout_width="match_parent" android:layout_height="match_parent" - style="@style/background_recyclerview" tools:context=".MainActivity"> - - - - + android:background="@color/material_grey_300_"> - + android:background="@color/white" + android:minHeight="50dp" + android:orientation="horizontal" + android:padding="10dp"> - + - + + + + + + - - \ No newline at end of file + \ No newline at end of file diff --git a/app/src/main/res/layout/fragment_add_server.xml b/app/src/main/res/layout/fragment_add_server.xml index bd2d4471a..794c6f767 100644 --- a/app/src/main/res/layout/fragment_add_server.xml +++ b/app/src/main/res/layout/fragment_add_server.xml @@ -231,12 +231,27 @@ android:textColor="@color/default_text_color_light" android:textSize="@dimen/text_size_large" /> + +