Skip to content

Instantly share code, notes, and snippets.

@badarshahzad
Last active April 17, 2018 05:25
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/1931e81de0c59c02a7edc9e00328b985 to your computer and use it in GitHub Desktop.
Save badarshahzad/1931e81de0c59c02a7edc9e00328b985 to your computer and use it in GitHub Desktop.
The static variable for Gpio pin work but withou static its not working.
/**
* 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 static 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("BCM2");
ledBulb.setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW);
ledBulb.setValue(true);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 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();
recyclerView = view.findViewById(R.id.recycler);
recyclerAdapter = new DeviceRecyclerAdapter(getContext(), appliancesList, this);
recyclerView.setAdapter(recyclerAdapter);
layoutManager = new GridLayoutManager(getContext(), 2);
recyclerView.setLayoutManager(layoutManager);
handler = new Handler();
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();
}
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() {
//Get and Set time from internet
}
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() {
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 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) {
}
@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);
} 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);
//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);
/**
* Here the ledBulb pin index will be communicate to turn on
*/
Log.i(TAG, "onStateChangeClick: OFF");
}
}
@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));
}
}
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();
}
/**
* 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
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment