Skip to content

Instantly share code, notes, and snippets.

@badarshahzad
Created April 19, 2018 04:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save badarshahzad/189ee7c33a9d5206fd0a5ac74a66eee1 to your computer and use it in GitHub Desktop.
Save badarshahzad/189ee7c33a9d5206fd0a5ac74a66eee1 to your computer and use it in GitHub Desktop.
The Gpio pin work as a static fine but to work as normal like creation of gpio pin as a private or public variable at class level or in life cycle of fragment didn't work.
package com.badarshahzad54.pcbs.presentation.fragments;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.badarshahzad54.pcbs.R;
import com.badarshahzad54.pcbs.adapters.DeviceRecyclerAdapter;
import com.badarshahzad54.pcbs.adapters.SelectIconAdapter;
import com.badarshahzad54.pcbs.adapters.SelectIconAdapter.SelectIconInterface;
import com.badarshahzad54.pcbs.data.model.Appliance;
import com.badarshahzad54.pcbs.modelThings.ApplianceDataSource;
import com.badarshahzad54.pcbs.presentation.utils.BoomMenuesUtils;
import com.badarshahzad54.pcbs.presentation.utils.DeserilizeData;
import com.badarshahzad54.pcbs.presentation.utils.UnitsToRupeesConverter;
import com.google.android.things.pio.Gpio;
import com.google.android.things.pio.PeripheralManager;
import com.google.firebase.firestore.DocumentListenOptions;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.gson.Gson;
import com.nightonke.boommenu.Animation.BoomEnum;
import com.nightonke.boommenu.BoomButtons.BoomButton;
import com.nightonke.boommenu.BoomButtons.ButtonPlaceEnum;
import com.nightonke.boommenu.BoomButtons.TextInsideCircleButton;
import com.nightonke.boommenu.BoomMenuButton;
import com.nightonke.boommenu.ButtonEnum;
import com.nightonke.boommenu.OnBoomListener;
import com.nightonke.boommenu.Piece.PiecePlaceEnum;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* A simple {@link Fragment} subclass.
*/
public class DashboardFragment extends Fragment implements DeviceRecyclerAdapter.ListItemClickListeners,
OnBoomListener, SelectIconInterface {
private static final String TAG = DashboardFragment.class.getSimpleName();
private static final String APPLIANCES_KEY = "appliances_key";
private static final String TOTAL_PRICE = "total_price";
private static final String TOTAL_UNITS = "total_units";
private static final String TOTAL_ON_DEVICES = "total_turnOnDevices";
public Gpio ledBulb;
private static int[] imageResources = new int[]{
R.drawable.ic_connect_24dp,
R.drawable.ic_close_24dp,
R.drawable.ic_bluetooth_connect_24dp
};
PeripheralManager service1 = PeripheralManager.getInstance();
private Toast toast;
private List<Appliance> appliancesList;
private RecyclerView recyclerView;
private DeviceRecyclerAdapter recyclerAdapter;
private RecyclerView.LayoutManager layoutManager;
private SharedPreferences sharedPreferences;
private SharedPreferences.OnSharedPreferenceChangeListener shPreflistener;
private ArrayList<VirtualDevice> listVirtualElectricity;
private TextView unitsTxtView;
private TextView priceTxtView;
private TextView totalConnectedDevicesTxtView;
private TextView totalTurnedOnDevices;
private TextView dateTime;
private TextView textViewIpWifi;
private BoomMenuButton bmb;
private FirebaseFirestore mFirestore;
private DocumentReference mDocRef = FirebaseFirestore.getInstance().document("appliances/appliance");
private Handler handler;
//TODO: in DPS 7 this class is depricated 01/03/2018 solve this one
private ApplianceDataSource dataSource;
private boolean ledState = false;
public DashboardFragment() {
// Required empty public constructor
}
private void initBoomMenu() {
//boommenu
bmb.setButtonEnum(ButtonEnum.TextInsideCircle);
bmb.setPiecePlaceEnum(PiecePlaceEnum.DOT_2_1);
bmb.setButtonPlaceEnum(ButtonPlaceEnum.SC_2_1);
bmb.setBoomEnum(BoomEnum.HORIZONTAL_THROW_2);
bmb.setDraggable(true);
bmb.setOnBoomListener(this);
//bmb.addBuilder();
for (int i = 0; i < bmb.getPiecePlaceEnum().pieceNumber(); i++) {
TextInsideCircleButton.Builder builder = new TextInsideCircleButton.Builder()
.normalImageRes(BoomMenuesUtils.remoteConnectMenuImages[i])
.normalText(BoomMenuesUtils.remoteConnectMenuStrings[i])
.imagePadding(new Rect(16, 16, 16, 24));
bmb.addBuilder(builder);
// bmb.addBuilder(getSimpleCircleButtonBuilder());
}
}
@Override
public void onStart() {
super.onStart();
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
ledBulb = service1.openGpio("BCM6");
ledBulb.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
ledBulb.setValue(false);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//realm database source
// dataSource = new ApplianceDataSource();
// dataSource.open();
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_dashboard, container, false);
//initilize the views and get the referances from the xml
initViews(view);
//initilize the boom menues
initBoomMenu();
//initilize the all ledBulb pins
// initGpioPins();
//init the firebase instance for appliances List data
initFirebase();
/**
* For the first time run to load dumi data if the data not exist
*/
//initlize time then commit to load the dumi data
loadAppliancesPref();
//get the dafult document of storage
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
//check: get loaded the data from the preferances
loadStoreDataInViews();
//trigger the listener when the data save in the default document
// shPreflistener = new SharedPreferences.OnSharedPreferenceChangeListener() {
// @Override
// public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//
// Log.i(TAG, "onSharedPreferenceChanged: ");
// appliancesList.clear();
// String appliancesJsonStr = sharedPreferences.getString(DashboardFragment.APPLIANCES_KEY, "0");
// appliancesList = DeserilizeData.parseJsonInToList(appliancesJsonStr);
//
// //updating the views
// devicesDataUpdate(appliancesList);
//
// //update data in recyclerview
// recyclerAdapter.notifyDataSetChanged();
//
// }
// };
//-------end Load Data-----------------------
recyclerView = view.findViewById(R.id.recycler);
recyclerAdapter = new DeviceRecyclerAdapter(getContext(), appliancesList, this);
recyclerView.setAdapter(recyclerAdapter);
// initVirtualElectricityDevices();
// layoutManager = new StaggeredGridLayoutManager(getContext());
// layoutManager = new LinearLayoutManager(getContext());
// layoutManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.HORIZONTAL);
// layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
//check if the appliance turned on stop or shutdown restart from this point
// restorePointDevices(appliancesList);
handler = new Handler();
//this timer is for updating the views after 3 seconds
// startTimer(3);
return view;
}
private void initFirebase() {
/**
* Going to switch the firebase with firestore.
* Why? As the firebase RDB don't have the array feature in json. I will be
* more comfortable if the have that feature.Recently
* they introduce the firestore the new features & including the array
* feature in the json file. The purpose is just not the array feature they are
* giving the query feature and many other.
*/
//listen the data is store the locally or on the server
final DocumentListenOptions documentListenOptions = new DocumentListenOptions();
documentListenOptions.includeMetadataChanges();
//the below is the firebase data retriving and updating the list
/* //get the path of child of the storage
dbRefSingleString = FirebaseDatabase.getInstance().getReference("appliancesListData");
//get the path of the trigger storage
dbRefApplianceTrigger = FirebaseDatabase.getInstance().getReference("applianceTrigger");
dbRefSingleString.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot!=null) {
//Appliance: index, isState,
//TODO: trigger devices index and trigger them
// appliancesList.clear();
appliancesList = DeserilizeData.parseJsonInToList(dataSnapshot.getValue().toString());
//update the recycler view
setAdapter(appliancesList);
//retore the point as virtual appliances will start
restorePointDevices(appliancesList);
Log.i(TAG, "onDataChange: without null " + dataSnapshot.getValue());
}
Log.i(TAG, "onDataChange: " + dataSnapshot.getValue());
}
@Override
public void onCancelled(DatabaseError databaseError) {
//error
}
});
*/
//the firestore testing
mFirestore = FirebaseFirestore.getInstance();
/**
* Test 1
*/
// pushData(getUpData(appliancesList));
/* mFirestore.collection("appliance").addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
if(e !=null){
Log.i(TAG, "onEvent: Exception occured");
}
//if change the value the whole document list will get
*//*for(DocumentSnapshot docSp: documentSnapshots){
String name = docSp.getString("name");
Log.i(TAG, "onEvent: "+name);
}*//*
for(DocumentChange docChange: documentSnapshots.getDocumentChanges()){
*//**
* There could be multiple ways to define key for document and get fields
* What I do is just simple make count variable that whenever listen call
* the count start from 0 and
*//*
int modifyOrChange = Integer.valueOf(docChange.getDocument().getId());
int index = 0;
switch (docChange.getType()){
case ADDED:
Appliance appliance = docChange.getDocument().toObject(Appliance.class);
index++;
Log.i(TAG, "onEvent: added id: "+appliance.getId());
//make an update object of Appliance
appliancesList.add(appliance);
recyclerAdapter.notifyDataSetChanged();
//check:save data into shared preferance as storage
sharedPreferences.edit().remove(DashboardFragment.APPLIANCES_KEY).putString(
DashboardFragment.APPLIANCES_KEY, new Gson().toJson(appliancesList).toString()).apply();
// Log.i(TAG, "onEvent: Id: "+docChange.getDocument().getId());
break;
case REMOVED:
//get the list first as whenever change occur first the existing list
//remove the item
// will be clear
appliancesList = getDeserializeList();
appliancesList.remove(modifyOrChange);
recyclerAdapter.notifyDataSetChanged();
// Log.i(TAG, "onEvent: Id: "+docChange.getDocument().getId());
break;
case MODIFIED:
//update the model object on specific change item
Log.i(TAG, "onEvent: mo id: "+docChange.getDocument().toObject(Appliance.class).getId());
// Log.i(TAG, "onEvent: modify: "+modifyOrChange);
//get the stored list first
appliancesList = getDeserializeList();
Log.i(TAG, "onEvent: modify: "+modifyOrChange);
appliancesList.set(modifyOrChange,docChange.getDocument().toObject(Appliance.class));
recyclerAdapter.notifyItemChanged(modifyOrChange);
// Log.i(TAG, "onEvent: Id: "+docChange.getDocument().getId());
break;
}
// Log.i(TAG, "DocumentChange: "+docChange.getDocument().getId());
// Log.i(TAG, "DocumentChange: "+docChange.getType().name());
// Log.i(TAG, "DocumentChange: "+docChange.getType());
}
for(DocumentSnapshot docChange: documentSnapshots.getDocuments()){
String name = docChange.getString("name");
// Log.i(TAG, "DocumentSnapShot "+name);
// Log.i(TAG, "DocumentSnapShot: "+docChange.getId());
// Log.i(TAG, "DocumentSnapShot: "+docChange.getData());
}
//loadStoreDataInViews();
}
});*/
/**
* Test 2
*/
/* DocumentReference mDocRef = FirebaseFirestore.getInstance().document("App/Model");
// mDocRef.
mDocRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
Log.i(TAG, "onEvent: lala O: "+ documentSnapshot.toObject(Appliance.class).getName());
}
});*/
/**
* Test 3
*/
/*.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot documentSnapshots, FirebaseFirestoreException e) {
//check: Check this feature pending writes
if(documentSnapshots.getMetadata().hasPendingWrites()){
Log.i(TAG, "onEvent: Data didn't send to server");
}else {
Log.i(TAG, "onEvent: send it to server");
}
if(e!=null) Log.i(TAG, "Error occured: ");
//this will get each time the whole document so we just need change
*//*
for(DocumentSnapshot documentChange: documentSnapshots){
String applianceName = documentChange.getString("name");
Log.i(TAG, "onEvent: "+applianceName);
}*//*
List<Appliance> fetchApplianceList = new ArrayList<>();
List<Appliance> testApplianceList = new ArrayList<>();
for(DocumentSnapshot documentSnapshot: documentSnapshots){
fetchApplianceList.add(documentSnapshot.toObject(Appliance.class));
Log.i(TAG, "onEvent: Yeah size of List => "+fetchApplianceList.size());
}
//just change data will be get
for(DocumentChange doc: documentSnapshots.getDocumentChanges()){
DocumentSnapshot documentSnapshot = doc.getDocument();
Appliance appliance = documentSnapshot.toObject(Appliance.class);
Log.i(TAG, "onEvent: Hunr maza ghin"+ appliance.getName());
Log.i(TAG, "ID "+doc.getDocument().getId());
String name ;
switch (doc.getType()){
case ADDED:
name = doc.getDocument().getString("name");
Log.i(TAG, "onEvent: Added "+ name);
Log.i(TAG, "onEvent: Id: "+doc.getDocument().getId());
break;
case REMOVED:
name = doc.getDocument().getString("name");
Log.i(TAG, "onEvent: Removed "+ name);
Log.i(TAG, "onEvent: Id: "+doc.getDocument().getId());
break;
case MODIFIED:
name = doc.getDocument().getString("name");
Log.i(TAG, "onEvent: Modify "+ name);
Log.i(TAG, "onEvent: Id: "+doc.getDocument().getId());
break;
}
}
}
});
*/
/**
* Test 4
*/
/* FirebaseFirestore mFirestore2 = FirebaseFirestore.getInstance();
mFirestore2.collection("AppTest").document("appliance1").addSnapshotListener(new EventListener<DocumentSnapshot>() {
@Override
public void onEvent(DocumentSnapshot documentSnapshot, FirebaseFirestoreException e) {
Appliance appliance = documentSnapshot.toObject(Appliance.class);
Log.i(TAG, "AppTest: ghin maza: "+appliance.getName());
}
});
*/
/**
* Fetching data
*/
//check: testing to upload data on the server
// pushData(getUpData(appliancesList));
}
private void initVirtualElectricityDevices() {
//Virtual devices
listVirtualElectricity = new ArrayList<>();
for (int a = 0; a < appliancesList.size(); a++) {
listVirtualElectricity.add(new VirtualDevice());
}
}
private void initGpioPins() {
/**
* Android thigns ledBulb pin testing
*/
//Gpio pins list
/**
* [BCM10, BCM11, BCM12, BCM13, BCM14, BCM15, BCM16, BCM17, BCM18, BCM19,
* BCM2, BCM20, BCM21, BCM22, BCM23, BCM24, BCM25, BCM26, BCM27, BCM3, BCM4,
* BCM5, BCM6, BCM7, BCM8, BCM9]
* Size is : 26
*/
try {
PeripheralManager peripheralManager = PeripheralManager.getInstance();
ledBulb = peripheralManager.openGpio("BCM2");
ledBulb.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
// for (int i = 0; i < peripheralManager.getGpioList().size(); i++) {
//
// total 26 ledBulb pins made added in a list
// Gpio ledBulb = peripheralManager.openGpio(peripheralManager.getGpioList().get(i).toString());
// gpioArrayList.add(ledBulb);
//
// }
} catch (IOException e) {
e.printStackTrace();
}
}
private void initViews(View view) {
unitsTxtView = view.findViewById(R.id.totalConsumeUnits);
priceTxtView = view.findViewById(R.id.totalPrice);
totalConnectedDevicesTxtView = view.findViewById(R.id.connectedDevices);
bmb = view.findViewById(R.id.bmb);
dateTime = view.findViewById(R.id.dateTime);
setDateTime();
setIPAddress();
}
private void setDateTime() {
/* TimeManager timeManager = TimeManager.getInstance();
//24 hour time
timeManager.setAutoTimeEnabled(true);
timeManager.setTimeFormat(TimeManager.FORMAT_24);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MILLISECOND, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR_OF_DAY, 12);
long timeStamp = calendar.getTimeInMillis();
timeManager.setTime(timeStamp);
Log.i(TAG, "setDateTime: Time: "+calendar.getTime());
*/
// Calendar calendar = Calendar.getInstance();
// java.util.TimeZone current = calendar.getTimeZone();
}
private void setIPAddress() {
//GET THE IP
}
private void restorePointDevices(List<Appliance> appliancesList) {
for (int i = 0; i < appliancesList.size(); i++) {
if(appliancesList.get(i).isState()){
listVirtualElectricity.get(i).deviceOn(getContext(), appliancesList, i);
}
}
}
public void startTimer(int seconds) {
Timer timer = new Timer();
TimerTask timerTask;
timerTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
//sending data to firebase
//pushData(appliancesList);
//TODO: uncomment the device Data update
//updating the views every few seconds later
// devicesDataUpdate(appliancesList);
//refreshing the list to look the refresh values
recyclerAdapter.notifyDataSetChanged();
}
});
}
};
timer.scheduleAtFixedRate(timerTask, 2000, seconds*1000);
}
private void loadStoreDataInViews() {
if (sharedPreferences.contains(DashboardFragment.APPLIANCES_KEY)) {
//converting the whole list as string to store in the default preferance file
String appliancesJsonStr = sharedPreferences.getString(DashboardFragment.APPLIANCES_KEY, "0");
appliancesList = DeserilizeData.parseJsonInToList(appliancesJsonStr);
} else {
/**
* For the first time run this if the the data fields or not created
* and the appliances is not existed
*/
//TODO: initlize all appliances from here time then commit to load the dumi data
appliancesList = getUpData(appliancesList);
sharedPreferences.edit().putString(DashboardFragment.APPLIANCES_KEY, new Gson().toJson(appliancesList).toString()).apply();
}
}
/**
* Dialog to select a suitable icon for your appliance
*/
public void showAlertDialog() {
SelectIconAdapter adapter = new SelectIconAdapter(this, getContext(), loadAppliancesIcons());
LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.select_icon, null, false);
// RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(), 2);
RecyclerView recyclerView = view.findViewById(R.id.recycler);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
AlertDialog.Builder addAlert = new AlertDialog.Builder(getContext());
addAlert.setTitle("Select Appliance Icon");
addAlert.setView(view);
addAlert.setCancelable(true);
addAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getContext(), "Cancel", Toast.LENGTH_SHORT).show();
}
});
addAlert.setPositiveButton("Select", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog dialog = addAlert.create();
dialog.show();
}
private Drawable[] loadAppliancesIcons() {
TypedArray ta = getResources().obtainTypedArray(R.array.appliancesScreenIcon);
Drawable[] icons = new Drawable[ta.length()];
for (int i = 0; i < ta.length(); i++) {
int id = ta.getResourceId(i, 0);
if (id != 0) {
icons[i] = ContextCompat.getDrawable(getContext(), id);
}
}
ta.recycle();
return icons;
}
//get the deserilizeList
public List<Appliance> getDeserializeList(){
String appliancesJsonStr = sharedPreferences.getString(DashboardFragment.APPLIANCES_KEY, "0");
appliancesList = DeserilizeData.parseJsonInToList(appliancesJsonStr);
return appliancesList;
}
@Override
public void onListItemClick(int clickItemIndex) {
// if (toast != null)
// toast.cancel();
//toast.makeText(getContext(), "Full View" + clickItemIndex, Toast.LENGTH_SHORT).show();
}
@Override
public void onStateChangeClick(int clickItemIndex, Switch deviceState) {
if (toast != null)
toast.cancel();
/**
* If device on then turn turn off if off then turn on
*/
//appliance status false howa or device state checked then turn on
if (!appliancesList.get(clickItemIndex).isState() && deviceState.isChecked()) {
try {
ledBulb.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH);
ledBulb.setValue(true);
} catch (IOException e) {
e.printStackTrace();
}
Log.i(TAG, "onStateChangeClick: ON");
//status update for device is turn on
appliancesList.get(clickItemIndex).setState(true);
//device virtual electric turn on
// listVirtualElectricity.get(clickItemIndex).deviceOn(getContext(), appliancesList, clickItemIndex);
//totaldevices turnded on update
// devicesDataUpdate(appliancesList);
//push data to firebase
// pushData(appliancesList);
/**
* Here the ledBulb pin index will be communicate to turn on
* true to turn on
* ledBulb is the input/output communication wia software/programming talk
* getting the list of ledBulb pins and set the name of pin
*/
// turnDevice1(true,ledBulb,peripheralManagerService.getGpioList().get(clickItemIndex));
} else {
try {
ledBulb.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
ledBulb.setValue(false);
} catch (IOException e) {
e.printStackTrace();
}
//status update for device is turn off
appliancesList.get(clickItemIndex).setState(false);
//device virtual electric turn off
// listVirtualElectricity.get(clickItemIndex).deviceOff(appliancesList, clickItemIndex);
//when stop the device update the data
sharedPreferences.edit().remove(DashboardFragment.APPLIANCES_KEY).putString(
DashboardFragment.APPLIANCES_KEY, new Gson().toJson(appliancesList).toString()).apply();
//when the devices turned off update the list
recyclerAdapter.notifyDataSetChanged();
//update the devices turned on/off
//In the mean while update the values circle time,unit and price.
devicesDataUpdate(appliancesList);
//push data to firebase
// pushData(appliancesList);
/**
* Here the ledBulb pin index will be communicate to turn on
*/
// turnDevice1(false,ledBulb, peripheralManagerService.getGpioList().get(clickItemIndex));
Log.i(TAG, "onStateChangeClick: OFF");
// TODO: Add constaint for networking if no internet then no action of remote control
// TODO: Add the feature when the device is turn of show the updated values
// TODO: send the request to cloud to turnded on this index device
}
}
@Override
public void onListItemClickMenus(BoomMenuButton bmb) {
}
/**
* Add appliance icon for your list item
*/
@Override
public void onAddApplianceIconClick(int position) {
showAlertDialog();
}
@Override
public void onStop() {
super.onStop();
if (ledBulb != null) {
try {
ledBulb.close();
} catch (IOException e) {
Log.e(TAG, "Error on PeripheralIO API", e);
}
}
}
//update price,unit and turn on devices
private void devicesDataUpdate(List<Appliance> appliancesList) {
int countTurnedOn = 0;
double sumPrice = 0;
double sumUnits = 0;
for (int i = 0; i < appliancesList.size(); i++) {
if (appliancesList.get(i).isState()) countTurnedOn++;
sumPrice = sumPrice + appliancesList.get(i).getTotalPrice();
sumUnits = sumUnits + appliancesList.get(i).getTotalConsumtion();
}
// if the data is not formated then again format
DecimalFormat decimalFormat = new DecimalFormat("#.00");
String price = String.valueOf(UnitsToRupeesConverter.getUnitsToPrice(sumUnits));
String untis = decimalFormat.format(sumUnits);
//concatenate the int as string
// totalTurnedOnDevices.setText(countTurnedOn + "");
priceTxtView.setText(price);
unitsTxtView.setText(untis);
//cloud updated and android things configured total devices
totalConnectedDevicesTxtView.setText(appliancesList.size() + "");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPreferences.edit().putString(DashboardFragment.TOTAL_PRICE, price).apply();
sharedPreferences.edit().putString(DashboardFragment.TOTAL_UNITS, untis).apply();
sharedPreferences.edit().putString(DashboardFragment.TOTAL_ON_DEVICES, countTurnedOn + "");
//store the data in local default document of shared preferances
sharedPreferences.edit().putString(DashboardFragment.APPLIANCES_KEY, new Gson().toJson(appliancesList).toString()).apply();
}
private List<Appliance> getUpData(List<Appliance> applianceList) {
//TODO: Get all Connected Devices from cloud storage
applianceList = new ArrayList<>();
applianceList.add(new Appliance("Bulb", false, 1, 0, 0, 0, 0, 0, 0));
applianceList.add(new Appliance("TV", false, 2, 0, 0, 0, 0, 0, 0));
applianceList.add(new Appliance("Light", false, 3, 0, 0, 0, 0, 0, 0));
applianceList.add(new Appliance("Switch", false, 4, 0, 0, 0, 0, 0, 0));
return applianceList;
}
private void setAdapter(List<Appliance> appliancesList) {
recyclerAdapter = new DeviceRecyclerAdapter(getContext(), appliancesList, this);
recyclerView.setAdapter(recyclerAdapter);
}
private void pushData(List<Appliance> upData) {
//Check:get the dumi data
upData.clear();
upData = getUpData(upData);
Map<String, Appliance> applianceMap = new HashMap<>();
int counter = 0;
for(Appliance appliance: upData){
// check: this is just for testing now hard coded find a way of key assign
applianceMap.put("appliance"+upData.get(counter).getId(),appliance);
counter++;
}
if(upData.size()>10){
Log.i(TAG, "pushData: Erroooor: You are exceeding the limit");
return;
}
for (int i = 0; i <upData.size(); i++) {
mFirestore.collection("appliance").document(i+"").set(upData.get(i));
}
/**
* Testing 1 to upload data on cloud
*/
/*mFirestore.collection("AppTest").document("appliance1").set(upData.get(0)).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
Log.i(TAG, "onComplete: Yes complete");
}else{
Log.i(TAG, "Error: No error");
}
}
});*/
///DatabaseReference databaseReference = firebaseDatabase.getReference().child("appliancesListData");
//databaseReference.setValue(new Gson().toJson(upData).toString());
//devicesDataUpdate(appliancesList);
}
public void loadAppliancesPref() {
List<Appliance> list = new ArrayList<>();
list = getUpData(list);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
sharedPreferences.edit().putString(DashboardFragment.APPLIANCES_KEY, new Gson().toJson(list).toString()).apply();
//TODO: solve the keys issue how we can add first just and never add again
// sharedPreferences.edit().putString(DashboardFragment.TOTAL_UNITS,"0");
// sharedPreferences.edit().putString(DashboardFragment.TOTAL_PRICE,"0");
}
/**
* Turn the gipo pin on and off, with index
*/
private void turnDevice1(boolean onOff, Gpio ledGpio) {
if (onOff) {
try {
ledGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_HIGH);
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
ledGpio.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* Put all working code above these below life cycles call these are just for
* teseting
*/
@Override
public void onDestroy() {
super.onDestroy();
// dataSource.close();
try {
if (ledBulb != null) ledBulb.close();
ledBulb = null;
} catch (IOException e) {
e.printStackTrace();
}
Log.i(TAG, "onDestroy: ");
}
@Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "onDetach: ");
}
/**
* Boomenu Callback Begin
*/
@Override
public void onClicked(int index, BoomButton boomButton) {
}
@Override
public void onBackgroundClick() {
}
@Override
public void onBoomWillHide() {
}
@Override
public void onBoomDidHide() {
}
@Override
public void onBoomWillShow() {
}
@Override
public void onBoomDidShow() {
}
@Override
public void selectIconForApplianceClick(int clickItemIndex) {
}
/**
* Boomenu Callback End
*/
/**
* The virtual devie electricity class
*/
public class VirtualDevice {
private static final String TAG = "VirtualDevice";
private Timer timer1;
private TimerTask task;
private Random RAND = new Random();
private int currentVoltage;
private double currentCurrent;
private double currentPower;
private Handler handler = new Handler();
private int secondsCount = 0;
private int unitsCount = 0;
private int deviceId = 0;
//totalPrice, totalTimeInSeconds and total units (units could be in 1.343434E very small
/**
* Remember Sudo you have added that the totalPrice calculate when the unit will be
* greater than at least 1 unit ok! :)
*/
private double totalPrice = 0;
private double totalUnitConsume = 0;
private int totalTimeInSeconds = 0;
private Context context;
private List<Appliance> applianceListUpdateContinue;
private int applianceIdUpdateContinue;
public void deviceOn(Context context, List<Appliance> applianceList, int itemId) {
//TODO: Add the device ID data here and start from that data onward
totalPrice = applianceList.get(itemId).getTotalPrice();
totalTimeInSeconds = applianceList.get(itemId).getTotalTime();
totalUnitConsume = applianceList.get(itemId).getTotalConsumtion();
//get the referances
this.applianceListUpdateContinue = applianceList;
//this context need as I want to write on the default document {may be there is other
// cool way but i know this one}
this.context = context;
applianceIdUpdateContinue = itemId;
//turn on electricity
startAction();
}
public void deviceOff(List<Appliance> applianceList, int itemId) {
// DecimalFormat decimalFormat = new DecimalFormat("#.00");
// totalUnitConsume = Double.valueOf(decimalFormat.format(totalUnitConsume));
//
// applianceList.get(itemId).setTotalPrice(totalPrice);
// applianceList.get(itemId).setTotalTime(totalTimeInSeconds);
// applianceList.get(itemId).setTotalConsumtion(totalUnitConsume);
//turn off electricity
stopAction();
}
/**
* This return the power of consume device
*/
private double electricityValues() {
// currentVoltage = RAND.nextInt(220);
/*
* for testing the voltage is not random 215 to 220 as something going wrong
* in android as its not work as that was working in eclipse I think this is
* (due to memory or heap size because may it could not mantain continous random
* generate value
*/
currentVoltage = 220;
currentCurrent = RAND.nextDouble();
currentPower = 0;
// if (212 <= currentVoltage && currentVoltage <= 220 && 0.43 <= currentCurrent && currentCurrent <= 0.45) {
currentPower = currentVoltage * currentCurrent * 1;
// } else {
// electricityValues();
// }
return currentPower;
}
public void setTimer() {
timer1 = new Timer();
task = new TimerTask() {
public void run() {
// totalTimeInSeconds are calculate
if (totalTimeInSeconds >= 0) {
secondsCount = totalTimeInSeconds++;
/*
* I can use the String.Value() method to convert the integer and float values
* to string but I find it convienent in it if its wrong then please tell me
* how?
*/
// random voltage genearate
double power = electricityValues();
totalUnitConsume = unitsCount;
/**
*That was the error I was adding the unit again and again
* unit = unit + (power * totalTimeInSeconds) / (1000 * 3600);
*/
totalUnitConsume = (power * totalTimeInSeconds) / (1000 * 3600);
Log.i(TAG, "Units: " + totalUnitConsume);
Log.i(TAG, "Seconds: " + totalTimeInSeconds);
if (totalUnitConsume == 1) {
System.exit(0);
}
if (totalUnitConsume > 1) {
// As units are in int and im unable to convert it into int as its huge number
// while
// but after the values added it will be measureable
totalPrice = UnitsToRupeesConverter.getUnitsToPrice(totalUnitConsume);
Log.i(TAG, "Price: " + totalPrice);
}
DecimalFormat decimalFormat = new DecimalFormat("#.00");
totalUnitConsume = Double.valueOf(decimalFormat.format(totalUnitConsume));
// setting the continous values
applianceListUpdateContinue
.get(applianceIdUpdateContinue)
.setTotalPrice(totalPrice);
applianceListUpdateContinue
.get(applianceIdUpdateContinue)
.setTotalTime(totalTimeInSeconds);
applianceListUpdateContinue
.get(applianceIdUpdateContinue)
.setTotalConsumtion(totalUnitConsume);
}
}
};
// thread schedule time in 1 sec = 1000 mili totalTimeInSeconds
timer1.scheduleAtFixedRate(task, 0, 10);
}
public void startAction() {
timer1 = null;
task = null;
setTimer();
}
public void stopAction() {
if (timer1 != null) {
timer1.cancel();
task.cancel();
}
}
}
}
Verbose:
04-19 04:13:57.406 660-660/com.badarshahzad54.pcbs W/System.err: at com.badarshahzad54.pcbs.presentation.fragments.DashboardFragment.onCreate(DashboardFragment.java:145)
04-19 04:16:17.856 660-660/com.badarshahzad54.pcbs I/DashboardFragment: onStateChangeClick: ON
04-19 04:18:13.929 660-660/com.badarshahzad54.pcbs I/DashboardFragment: onStateChangeClick: OFF
04-19 04:18:15.756 660-660/com.badarshahzad54.pcbs I/DashboardFragment: onStateChangeClick: ON
04-19 04:18:23.631 660-660/com.badarshahzad54.pcbs I/DashboardFragment: onStateChangeClick: OFF
04-19 04:18:24.992 660-660/com.badarshahzad54.pcbs I/DashboardFragment: onStateChangeClick: ON
04-19 04:18:26.634 660-660/com.badarshahzad54.pcbs I/DashboardFragment: onStateChangeClick: OFF
04-19 04:22:05.183 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onAttach:
04-19 04:22:05.183 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: setRetainInstance:
04-19 04:22:05.500 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onSharedPreferenceChanged: Yes in
04-19 04:22:05.509 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onViewCreated:
04-19 04:22:05.510 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onViewStateRestored:
04-19 04:22:05.510 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onStart:
04-19 04:22:05.510 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onResume:
04-19 04:22:07.939 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onPause:
04-19 04:22:08.021 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onSaveInstanceState:
04-19 04:22:08.028 2615-2615/com.badarshahzad54.pcbs I/DashboardFragment: onStop:
04-19 04:22:24.967 2920-2920/com.badarshahzad54.pcbs I/DashboardFragment: onAttach:
04-19 04:22:24.967 2920-2920/com.badarshahzad54.pcbs I/DashboardFragment: setRetainInstance:
04-19 04:22:25.243 2920-2920/com.badarshahzad54.pcbs I/DashboardFragment: onViewCreated:
04-19 04:22:25.243 2920-2920/com.badarshahzad54.pcbs I/DashboardFragment: onViewStateRestored:
04-19 04:22:25.244 2920-2920/com.badarshahzad54.pcbs I/DashboardFragment: onStart:
04-19 04:22:25.244 2920-2920/com.badarshahzad54.pcbs I/DashboardFragment: onResume:
04-19 04:24:15.443 3804-3804/com.badarshahzad54.pcbs W/System.err: at com.badarshahzad54.pcbs.presentation.fragments.DashboardFragment.onCreate(DashboardFragment.java:145)
04-19 04:24:23.098 3804-3804/com.badarshahzad54.pcbs E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.badarshahzad54.pcbs, PID: 3804
java.lang.NullPointerException: Attempt to invoke interface method 'void com.google.android.things.pio.Gpio.setDirection(int)' on a null object reference
at com.badarshahzad54.pcbs.presentation.fragments.DashboardFragment.onStateChangeClick(DashboardFragment.java:752)
at com.badarshahzad54.pcbs.adapters.DeviceRecyclerAdapter$DeviceViewHolder$3.onClick(DeviceRecyclerAdapter.java:186)
at android.view.View.performClick(View.java:6294)
at android.widget.CompoundButton.performClick(CompoundButton.java:134)
at android.view.View$PerformClick.run(View.java:24770)
at android.os.Handler.handleCallback(Handler.java:790)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment