├── AndroidManifest.xml
├── README
├── bin
├── SmartHome.apk
├── classes.dex
├── classes
│ └── upb
│ │ └── smarthome
│ │ ├── MyViewFlipper.class
│ │ ├── R$anim.class
│ │ ├── R$attr.class
│ │ ├── R$drawable.class
│ │ ├── R$id.class
│ │ ├── R$layout.class
│ │ ├── R$string.class
│ │ ├── R.class
│ │ ├── SensorDetails$1$1.class
│ │ ├── SensorDetails$1.class
│ │ ├── SensorDetails.class
│ │ ├── SmartHomeActivity$1.class
│ │ ├── SmartHomeActivity$2$1$1.class
│ │ ├── SmartHomeActivity$2$1.class
│ │ ├── SmartHomeActivity$2.class
│ │ ├── SmartHomeActivity$ListWithImageAdapter.class
│ │ ├── SmartHomeActivity$MyOnItemSelectedListener.class
│ │ ├── SmartHomeActivity$MyUiUpdate.class
│ │ ├── SmartHomeActivity$ToggleOnOff.class
│ │ ├── SmartHomeActivity.class
│ │ ├── ThermostatControl$1.class
│ │ ├── ThermostatControl$SaveThermostatValues.class
│ │ ├── ThermostatControl.class
│ │ ├── clusters
│ │ ├── BasicCluster.class
│ │ ├── BasicClusterStatus.class
│ │ ├── ClusterConstants.class
│ │ ├── FlowCluster.class
│ │ ├── FlowClusterStatus.class
│ │ ├── OnOffCluster.class
│ │ ├── OnOffClusterStatus.class
│ │ ├── PowerCluster.class
│ │ ├── PowerClusterStatus.class
│ │ ├── TemperatureCluster.class
│ │ ├── TemperatureClusterStatus.class
│ │ ├── ThermostatCluster.class
│ │ └── ThermostatClusterStatus.class
│ │ ├── data
│ │ ├── SmartHomeProvider$1.class
│ │ ├── SmartHomeProvider$DatabaseHelper.class
│ │ └── SmartHomeProvider.class
│ │ ├── devices
│ │ ├── DeviceConstants.class
│ │ ├── FlowSensor.class
│ │ ├── LogicalDevice.class
│ │ ├── OnOffActuator.class
│ │ ├── TemperatureSensor.class
│ │ └── ThermostatActuator.class
│ │ └── restcomm
│ │ ├── JSONParser.class
│ │ └── RestComm.class
├── res
│ ├── drawable-hdpi
│ │ ├── homelogo.png
│ │ ├── ic_launcher.png
│ │ ├── light_switch_off.png
│ │ ├── light_switch_on.png
│ │ ├── meter.png
│ │ └── temperature.png
│ ├── drawable-ldpi
│ │ └── ic_launcher.png
│ └── drawable-mdpi
│ │ └── ic_launcher.png
└── resources.ap_
├── gen
└── upb
│ └── smarthome
│ └── R.java
├── lib
└── Androidplot-core-0.4.4-release.jar
├── proguard.cfg
├── project.properties
├── res
├── anim
│ ├── slide_left_in.xml
│ ├── slide_left_out.xml
│ ├── slide_right_in.xml
│ └── slide_right_out.xml
├── drawable-hdpi
│ ├── homelogo.png
│ ├── ic_launcher.png
│ ├── light_switch_off.png
│ ├── light_switch_on.png
│ ├── meter.png
│ ├── temperature.png
│ └── thermostat.jpeg
├── drawable-ldpi
│ └── ic_launcher.png
├── drawable-mdpi
│ └── ic_launcher.png
├── layout
│ ├── actuators.xml
│ ├── list_item.xml
│ ├── sensor_details.xml
│ ├── sensors.xml
│ └── thermostat.xml
└── values
│ └── strings.xml
└── src
└── upb
└── smarthome
├── MyViewFlipper.java
├── SensorDetails.java
├── SmartHomeActivity.java
├── ThermostatControl.java
├── clusters
├── BasicCluster.java
├── BasicClusterStatus.java
├── ClusterConstants.java
├── FlowCluster.java
├── FlowClusterStatus.java
├── OnOffCluster.java
├── OnOffClusterStatus.java
├── PowerCluster.java
├── PowerClusterStatus.java
├── TemperatureCluster.java
├── TemperatureClusterStatus.java
├── ThermostatCluster.java
└── ThermostatClusterStatus.java
├── data
└── SmartHomeProvider.java
├── devices
├── DeviceConstants.java
├── FlowSensor.java
├── LogicalDevice.java
├── OnOffActuator.java
├── TemperatureSensor.java
└── ThermostatActuator.java
└── restcomm
├── JSONParser.java
└── RestComm.java
/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
9 |
10 |
13 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
26 |
27 |
28 |
29 |
30 |
31 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | Rizea Daniel-Octavian
2 | 341C1
3 |
4 |
5 |
6 | SmartHome SI Tema2
7 |
8 |
9 | Functionalitati:
10 | Am implementat tema conform cu cerintele enuntului.
11 |
12 | Pentru testarea aplicatiei este necesara o conexiune la internet.
13 | Cand este lansata aplicatia apare o lista default cu senzorii de temperatura.In partea superioara a ecranului este un buton din care se poate selecta tipul de senzor dorit.
14 | Functionalitati onClick pe elemente din lista :
15 | Daca elementul este:
16 | -un comutator (se face toggle se inchide sau deschide)
17 | -un senzor de temperatura sau debit se porneste o alta activitate in care se afiseaza informatii generale (momentan nu prea multe), iar daca se face stanga dreapta touche event se face fliping la ecranul urmator cu datele de istorie de pe ultimeel 5 inregistrari.
18 |
19 | -un senzor de thermostat duce la meniul de setare al thermostatului. Pentru setare MinHeat se fece flip vertical in partea stanga a ecranului, iar pentru MaxHeat flip vertical in partea dreapta a ecranului.
20 | La fina se apasa pe butonul save.
21 |
22 |
23 | La inceputul aplicatiei, se verifica starea senzorilor (cei cu baterii daca a scazut sub un anumit prag si se alerteaza utilizatorul)
24 |
25 | De precizat ca schimbarile nu se produc imediat ce s-a actionat comanda in view, ci o data la 5 secunde cand este programat un update automat declansat de provider,acesta anunta prin handler refresh-ul la UI. (Am lasat asa pentru a fi mai transparent faptul la testare si notare ca updateurile se produc).
26 |
27 | Structura proiectului:
28 | pachetul:
29 | upb.smarthome :
30 | MainScreenActivity : activitate ce afiseaza lsita de senzori
31 | SensorDetails : activitate ce afiseaza detaliile unui senzor selectat din lista de la MainScreeActivity (doar pentru FLow si Temperature)
32 | ThermostatControl : activitate ce trimite comanda la thermostat
33 | MyViewFlipper : activitate ce prinde gestul dual touch si face flipping de la un ecran la altul
34 | upb.smarthome.clusters
35 | pachet ce cuprinda constante si clase pentru a organzia cat mai bine datele din standardul ZigBee
36 | upb.smarthome.data
37 | contine smart home providerul de furnizeaza datele
38 | upb.smarthome.devices
39 | contine tipul de baza LogicalDevice si extinderi ale acestuia pentru senzorii de fata
40 | upb.smarthome.restcomm
41 | contine clase ce comunica prin rest cu serverul si parseaza datele primite
42 |
43 |
--------------------------------------------------------------------------------
/bin/SmartHome.apk:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/SmartHome.apk
--------------------------------------------------------------------------------
/bin/classes.dex:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes.dex
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/MyViewFlipper.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/MyViewFlipper.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R$anim.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R$anim.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R$attr.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R$attr.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R$drawable.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R$drawable.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R$id.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R$id.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R$layout.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R$layout.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R$string.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R$string.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/R.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/R.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SensorDetails$1$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SensorDetails$1$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SensorDetails$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SensorDetails$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SensorDetails.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SensorDetails.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$2$1$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$2$1$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$2$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$2$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$2.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$2.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$ListWithImageAdapter.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$ListWithImageAdapter.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$MyOnItemSelectedListener.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$MyOnItemSelectedListener.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$MyUiUpdate.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$MyUiUpdate.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity$ToggleOnOff.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity$ToggleOnOff.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/SmartHomeActivity.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/SmartHomeActivity.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/ThermostatControl$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/ThermostatControl$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/ThermostatControl$SaveThermostatValues.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/ThermostatControl$SaveThermostatValues.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/ThermostatControl.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/ThermostatControl.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/BasicCluster.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/BasicCluster.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/BasicClusterStatus.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/BasicClusterStatus.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/ClusterConstants.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/ClusterConstants.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/FlowCluster.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/FlowCluster.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/FlowClusterStatus.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/FlowClusterStatus.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/OnOffCluster.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/OnOffCluster.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/OnOffClusterStatus.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/OnOffClusterStatus.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/PowerCluster.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/PowerCluster.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/PowerClusterStatus.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/PowerClusterStatus.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/TemperatureCluster.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/TemperatureCluster.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/TemperatureClusterStatus.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/TemperatureClusterStatus.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/ThermostatCluster.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/ThermostatCluster.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/clusters/ThermostatClusterStatus.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/clusters/ThermostatClusterStatus.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/data/SmartHomeProvider$1.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/data/SmartHomeProvider$1.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/data/SmartHomeProvider$DatabaseHelper.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/data/SmartHomeProvider$DatabaseHelper.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/data/SmartHomeProvider.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/data/SmartHomeProvider.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/devices/DeviceConstants.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/devices/DeviceConstants.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/devices/FlowSensor.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/devices/FlowSensor.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/devices/LogicalDevice.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/devices/LogicalDevice.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/devices/OnOffActuator.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/devices/OnOffActuator.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/devices/TemperatureSensor.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/devices/TemperatureSensor.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/devices/ThermostatActuator.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/devices/ThermostatActuator.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/restcomm/JSONParser.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/restcomm/JSONParser.class
--------------------------------------------------------------------------------
/bin/classes/upb/smarthome/restcomm/RestComm.class:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/classes/upb/smarthome/restcomm/RestComm.class
--------------------------------------------------------------------------------
/bin/res/drawable-hdpi/homelogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-hdpi/homelogo.png
--------------------------------------------------------------------------------
/bin/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/bin/res/drawable-hdpi/light_switch_off.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-hdpi/light_switch_off.png
--------------------------------------------------------------------------------
/bin/res/drawable-hdpi/light_switch_on.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-hdpi/light_switch_on.png
--------------------------------------------------------------------------------
/bin/res/drawable-hdpi/meter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-hdpi/meter.png
--------------------------------------------------------------------------------
/bin/res/drawable-hdpi/temperature.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-hdpi/temperature.png
--------------------------------------------------------------------------------
/bin/res/drawable-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/bin/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/bin/resources.ap_:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/bin/resources.ap_
--------------------------------------------------------------------------------
/gen/upb/smarthome/R.java:
--------------------------------------------------------------------------------
1 | /* AUTO-GENERATED FILE. DO NOT MODIFY.
2 | *
3 | * This class was automatically generated by the
4 | * aapt tool from the resource data it found. It
5 | * should not be modified by hand.
6 | */
7 |
8 | package upb.smarthome;
9 |
10 | public final class R {
11 | public static final class anim {
12 | public static final int slide_left_in=0x7f040000;
13 | public static final int slide_left_out=0x7f040001;
14 | public static final int slide_right_in=0x7f040002;
15 | public static final int slide_right_out=0x7f040003;
16 | }
17 | public static final class attr {
18 | }
19 | public static final class drawable {
20 | public static final int homelogo=0x7f020000;
21 | public static final int ic_launcher=0x7f020001;
22 | public static final int light_switch_off=0x7f020002;
23 | public static final int light_switch_on=0x7f020003;
24 | public static final int meter=0x7f020004;
25 | public static final int temperature=0x7f020005;
26 | public static final int thermostat=0x7f020006;
27 | }
28 | public static final class id {
29 | public static final int chose_senzor_type=0x7f06000d;
30 | public static final int flipper=0x7f060005;
31 | public static final int img=0x7f060001;
32 | public static final int listView=0x7f060000;
33 | public static final int mySimpleXYPlot=0x7f06000c;
34 | public static final int sensor_Location=0x7f060008;
35 | public static final int sensor_image=0x7f060006;
36 | public static final int sensor_last_update=0x7f06000a;
37 | public static final int sensor_power_suply=0x7f060009;
38 | public static final int sensor_value=0x7f060007;
39 | public static final int senzor_other_data=0x7f06000b;
40 | public static final int thermostat_image=0x7f06000e;
41 | public static final int thermostat_position=0x7f060011;
42 | public static final int thermostat_save=0x7f060012;
43 | public static final int thermostat_value_max=0x7f060010;
44 | public static final int thermostat_value_min=0x7f06000f;
45 | public static final int txtLocation=0x7f060003;
46 | public static final int txtName=0x7f060002;
47 | public static final int txtValue=0x7f060004;
48 | }
49 | public static final class layout {
50 | public static final int actuators=0x7f030000;
51 | public static final int list_item=0x7f030001;
52 | public static final int sensor_details=0x7f030002;
53 | public static final int sensors=0x7f030003;
54 | public static final int thermostat=0x7f030004;
55 | }
56 | public static final class string {
57 | public static final int app_name=0x7f050001;
58 | public static final int chose_senzor_type=0x7f050002;
59 | public static final int hello=0x7f050000;
60 | public static final int thermostat_button_text=0x7f050003;
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/lib/Androidplot-core-0.4.4-release.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/lib/Androidplot-core-0.4.4-release.jar
--------------------------------------------------------------------------------
/proguard.cfg:
--------------------------------------------------------------------------------
1 | -optimizationpasses 5
2 | -dontusemixedcaseclassnames
3 | -dontskipnonpubliclibraryclasses
4 | -dontpreverify
5 | -verbose
6 | -optimizations !code/simplification/arithmetic,!field/*,!class/merging/*
7 |
8 | -keep public class * extends android.app.Activity
9 | -keep public class * extends android.app.Application
10 | -keep public class * extends android.app.Service
11 | -keep public class * extends android.content.BroadcastReceiver
12 | -keep public class * extends android.content.ContentProvider
13 | -keep public class * extends android.app.backup.BackupAgentHelper
14 | -keep public class * extends android.preference.Preference
15 | -keep public class com.android.vending.licensing.ILicensingService
16 |
17 | -keepclasseswithmembernames class * {
18 | native ;
19 | }
20 |
21 | -keepclasseswithmembers class * {
22 | public (android.content.Context, android.util.AttributeSet);
23 | }
24 |
25 | -keepclasseswithmembers class * {
26 | public (android.content.Context, android.util.AttributeSet, int);
27 | }
28 |
29 | -keepclassmembers class * extends android.app.Activity {
30 | public void *(android.view.View);
31 | }
32 |
33 | -keepclassmembers enum * {
34 | public static **[] values();
35 | public static ** valueOf(java.lang.String);
36 | }
37 |
38 | -keep class * implements android.os.Parcelable {
39 | public static final android.os.Parcelable$Creator *;
40 | }
41 |
--------------------------------------------------------------------------------
/project.properties:
--------------------------------------------------------------------------------
1 | # This file is automatically generated by Android Tools.
2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED!
3 | #
4 | # This file must be checked in Version Control Systems.
5 | #
6 | # To customize properties used by the Ant build system use,
7 | # "ant.properties", and override values to adapt the script to your
8 | # project structure.
9 |
10 | # Project target.
11 | target=android-9
12 |
--------------------------------------------------------------------------------
/res/anim/slide_left_in.xml:
--------------------------------------------------------------------------------
1 |
2 |
20 |
21 |
22 |
24 |
26 |
27 |
--------------------------------------------------------------------------------
/res/anim/slide_left_out.xml:
--------------------------------------------------------------------------------
1 |
2 |
20 |
21 |
22 |
24 |
26 |
--------------------------------------------------------------------------------
/res/anim/slide_right_in.xml:
--------------------------------------------------------------------------------
1 |
2 |
20 |
21 |
22 |
24 |
26 |
27 |
--------------------------------------------------------------------------------
/res/anim/slide_right_out.xml:
--------------------------------------------------------------------------------
1 |
2 |
20 |
21 |
22 |
24 |
26 |
--------------------------------------------------------------------------------
/res/drawable-hdpi/homelogo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/homelogo.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/light_switch_off.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/light_switch_off.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/light_switch_on.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/light_switch_on.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/meter.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/meter.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/temperature.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/temperature.png
--------------------------------------------------------------------------------
/res/drawable-hdpi/thermostat.jpeg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-hdpi/thermostat.jpeg
--------------------------------------------------------------------------------
/res/drawable-ldpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-ldpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/drawable-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/danielrizea/SmartHome-Android/e41251080974ea7c79aeb17be4e2642d5d59d032/res/drawable-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/res/layout/actuators.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/res/layout/list_item.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
12 |
13 |
20 |
21 |
28 |
34 |
35 |
36 |
43 |
--------------------------------------------------------------------------------
/res/layout/sensor_details.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
12 |
13 |
17 | >
18 |
22 |
30 |
31 |
32 |
38 |
44 |
50 |
56 |
57 |
58 |
63 |
--------------------------------------------------------------------------------
/res/layout/sensors.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
12 |
13 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/res/layout/thermostat.xml:
--------------------------------------------------------------------------------
1 |
2 |
6 |
7 |
11 | >
12 |
16 |
24 |
33 |
34 |
35 |
43 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Hello World, SmartHomeActivity!
5 | SmartHome
6 | Chose senzor type
7 | Save values
8 |
9 |
--------------------------------------------------------------------------------
/src/upb/smarthome/MyViewFlipper.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome;
8 |
9 | import android.content.Context;
10 | import android.util.AttributeSet;
11 | import android.util.Log;
12 | import android.view.MotionEvent;
13 | import android.view.animation.Animation;
14 | import android.view.animation.AnimationUtils;
15 | import android.widget.Toast;
16 | import android.widget.ViewFlipper;
17 |
18 | /**
19 | * The Class MyViewFlipper.
20 | * This Class is used to implement flip gesture
21 | */
22 | public class MyViewFlipper extends ViewFlipper {
23 |
24 | /** The Constant logTag. */
25 | static final String logTag = "ViewFlipper";
26 |
27 | /** The Constant MIN_DISTANCE. */
28 | static final int MIN_DISTANCE = 30;
29 |
30 | /** The up y. */
31 | private float downX, downY, upX, upY;
32 |
33 | /** The slide left in. */
34 | Animation slideLeftIn;
35 |
36 | /** The slide left out. */
37 | Animation slideLeftOut;
38 |
39 | /** The slide right in. */
40 | Animation slideRightIn;
41 |
42 | /** The slide right out. */
43 | Animation slideRightOut;
44 |
45 | /** The context. */
46 | Context context;
47 |
48 | /** The view flipper. */
49 | ViewFlipper viewFlipper;
50 |
51 | /**
52 | * Instantiates a new my view flipper.
53 | *
54 | * @param context the context
55 | */
56 | public MyViewFlipper(Context context) {
57 | super(context);
58 | viewFlipper=this;
59 | this.context=context;
60 | System.out.println("I am in MyFlipper() counstructor...");
61 | }
62 |
63 | /**
64 | * Instantiates a new my view flipper.
65 | *
66 | * @param context the context
67 | * @param attrs the attrs
68 | */
69 | public MyViewFlipper(Context context, AttributeSet attrs) {
70 | super(context, attrs);
71 | this.context=context;
72 | viewFlipper=this;
73 | System.out.println("I am in MyFlipper() counstructor...");
74 | slideLeftIn =
75 | AnimationUtils.loadAnimation(context, R.anim.slide_left_in);
76 | slideLeftOut =
77 | AnimationUtils.loadAnimation(context, R.anim.slide_left_out);
78 | slideRightIn =
79 | AnimationUtils.loadAnimation(context, R.anim.slide_right_in);
80 | slideRightOut =
81 | AnimationUtils.loadAnimation(context, R.anim.slide_right_out);
82 | }
83 |
84 | /* (non-Javadoc)
85 | * @see android.view.View#onTouchEvent(android.view.MotionEvent)
86 | */
87 | @Override
88 | public boolean onTouchEvent(MotionEvent event) {
89 | switch (event.getAction()) {
90 | case MotionEvent.ACTION_DOWN: {
91 | downX = event.getX();
92 | downY = event.getY();
93 | return true;
94 | }
95 | case MotionEvent.ACTION_UP: {
96 | upX = event.getX();
97 | upY = event.getY();
98 |
99 | float deltaX = downX - upX;
100 | float deltaY = downY - upY;
101 |
102 | // swipe horizontal?
103 | if (Math.abs(deltaX) > MIN_DISTANCE) {
104 | // left or right
105 | if (deltaX < 0) {
106 | this.onLeftToRightSwipe();
107 | return true;
108 | }
109 | if (deltaX > 0) {
110 | this.onRightToLeftSwipe();
111 | return true;
112 | }
113 | } else {
114 | if(Math.abs(deltaX)<15){
115 | onClickEvent();
116 | }
117 | Log.i("swipe", "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
118 | }
119 | // swipe vertical?
120 | if (Math.abs(deltaY) > MIN_DISTANCE) {
121 | // top or down
122 | if (deltaY < 0) {
123 | this.onTopToBottomSwipe();
124 | return true;
125 | }
126 | if (deltaY > 0) {
127 | this.onBottomToTopSwipe();
128 | return true;
129 | }
130 | } else {
131 | Log.i(logTag, "Swipe was only " + Math.abs(deltaX)
132 | + " long, need at least " + MIN_DISTANCE);
133 | }
134 |
135 | return true;
136 | }
137 | }
138 | return false;
139 |
140 | }
141 |
142 | /**
143 | * On right to left swipe.
144 | */
145 | public void onRightToLeftSwipe() {
146 |
147 | viewFlipper.setInAnimation(slideLeftIn);
148 | viewFlipper.setOutAnimation(slideLeftOut);
149 | viewFlipper.showNext();
150 | }
151 |
152 | /**
153 | * On left to right swipe.
154 | */
155 | public void onLeftToRightSwipe() {
156 |
157 | viewFlipper.setInAnimation(slideRightIn);
158 | viewFlipper.setOutAnimation(slideRightOut);
159 | viewFlipper.showPrevious();
160 | }
161 |
162 | /**
163 | * On top to bottom swipe.
164 | */
165 | public void onTopToBottomSwipe() {
166 | Log.i(logTag, "onTopToBottomSwipe!");
167 | // activity.doSomething();
168 | }
169 |
170 | /**
171 | * On bottom to top swipe.
172 | */
173 | public void onBottomToTopSwipe() {
174 | Log.i(logTag, "onBottomToTopSwipe!");
175 | // activity.doSomething();
176 | }
177 |
178 | /**
179 | * On click event.
180 | */
181 | public void onClickEvent(){
182 | Toast.makeText(context, "Click",Toast.LENGTH_SHORT);
183 | }
184 |
185 | /* (non-Javadoc)
186 | * @see android.view.ViewGroup#onInterceptTouchEvent(android.view.MotionEvent)
187 | */
188 | @Override
189 | public boolean onInterceptTouchEvent(MotionEvent ev) {
190 | return true; // Here if true then Flipping done.
191 | // And if false then click event done.
192 | }
193 |
194 | }
--------------------------------------------------------------------------------
/src/upb/smarthome/SensorDetails.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome;
8 |
9 | import java.text.SimpleDateFormat;
10 | import java.util.Arrays;
11 | import java.util.Date;
12 |
13 | import upb.smarthome.clusters.ClusterConstants;
14 | import upb.smarthome.clusters.FlowClusterStatus;
15 | import upb.smarthome.clusters.TemperatureClusterStatus;
16 | import upb.smarthome.data.SmartHomeProvider;
17 | import upb.smarthome.devices.DeviceConstants;
18 | import upb.smarthome.devices.FlowSensor;
19 | import upb.smarthome.devices.LogicalDevice;
20 | import upb.smarthome.devices.TemperatureSensor;
21 | import android.app.Activity;
22 | import android.app.ProgressDialog;
23 | import android.database.Cursor;
24 | import android.graphics.Color;
25 | import android.graphics.DashPathEffect;
26 | import android.graphics.LinearGradient;
27 | import android.graphics.Paint;
28 | import android.graphics.Shader;
29 | import android.net.Uri;
30 | import android.os.Bundle;
31 | import android.text.format.DateFormat;
32 | import android.util.Log;
33 | import android.widget.ImageView;
34 | import android.widget.TextView;
35 | import android.widget.ViewFlipper;
36 |
37 | import com.androidplot.Plot;
38 | import com.androidplot.series.XYSeries;
39 | import com.androidplot.xy.LineAndPointFormatter;
40 | import com.androidplot.xy.SimpleXYSeries;
41 | import com.androidplot.xy.XYPlot;
42 | import com.androidplot.xy.XYStepMode;
43 |
44 |
45 | /**
46 | * The Class SensorDetails.
47 | */
48 | public class SensorDetails extends Activity{
49 |
50 | // Local data
51 | /** The provider. */
52 | private String provider = "content://" + SmartHomeProvider.PROVIDER_NAME;
53 |
54 | /** The ext address. */
55 | private String extAddress;
56 |
57 | /** The endpoint. */
58 | private int endpoint;
59 |
60 | /** The type. */
61 | private int type;
62 |
63 | /** The my simple xy plot. */
64 | private XYPlot mySimpleXYPlot;
65 |
66 | /** The flipper. */
67 | private ViewFlipper flipper;
68 |
69 | /** The pd. */
70 | private ProgressDialog pd;
71 |
72 | /** The img. */
73 | private ImageView img;
74 |
75 | /** The location. */
76 | private TextView location;
77 |
78 | /** The sensor value. */
79 | private TextView sensorValue;
80 |
81 | /** The timestamp. */
82 | private TextView timestamp;
83 |
84 | /** The position val. */
85 | private String positionVal;
86 |
87 | /** The show value. */
88 | private String showValue;
89 |
90 | /** The timestamp val. */
91 | private int timestampVal;
92 |
93 | /* (non-Javadoc)
94 | * @see android.app.Activity#onCreate(android.os.Bundle)
95 | */
96 | @Override
97 | protected void onCreate(Bundle savedInstanceState) {
98 |
99 | super.onCreate(savedInstanceState);
100 |
101 | setContentView(R.layout.sensor_details);
102 |
103 | pd = ProgressDialog.show(SensorDetails.this, "Download date", "Se descarca datele necesare istoriei");
104 |
105 |
106 | Bundle bundle = getIntent().getExtras();
107 | mySimpleXYPlot = (XYPlot) findViewById(R.id.mySimpleXYPlot);
108 | flipper = (ViewFlipper) findViewById(R.id.flipper);
109 |
110 | //get sensor information
111 | extAddress = bundle.getString("extAddress");
112 | endpoint = bundle.getInt("endpoint");
113 | type = bundle.getInt("type");
114 |
115 | img = (ImageView)findViewById(R.id.sensor_image);
116 |
117 | location = (TextView)findViewById(R.id.sensor_Location);
118 | sensorValue = (TextView)findViewById(R.id.sensor_value);
119 | timestamp = (TextView)findViewById(R.id.sensor_last_update);
120 |
121 | //get sensor falues in new thread
122 | new Thread()
123 | {
124 | public void run()
125 | {
126 |
127 | try
128 | {
129 | LogicalDevice device = null;
130 | int clusterID =402;
131 |
132 | Log.d("details", ""+type+" "+extAddress + " " +endpoint);
133 | switch(type){
134 |
135 | case DeviceConstants.TYPE_TEMPERATURE_SENSOR : {
136 |
137 | clusterID = ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER;
138 | device = new TemperatureSensor(extAddress, endpoint, type);
139 |
140 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
141 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
142 | //add senzor special cluster value
143 | if(val.getCount()>0){
144 |
145 | val.moveToFirst();
146 | device.position = val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription));
147 | Log.d("senzor_info","Location : " + device.position);
148 | positionVal = device.position;
149 | }
150 |
151 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER+"/last");
152 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
153 | //add senzor special cluster value
154 | if(val.getCount()>0){
155 | val.moveToFirst();
156 | TemperatureClusterStatus status = new TemperatureClusterStatus(val.getFloat(val.getColumnIndex(SmartHomeProvider.MeasuredValue)),val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)));
157 | showValue = status.measuredValue + " " + status.unit;
158 | timestampVal = status.timestamp;
159 | }
160 | else
161 | Log.d("senzor_info","Temperature: nu e setata");
162 |
163 | }
164 | break;
165 | case DeviceConstants.TYPE_FLOW_METER : {
166 |
167 |
168 |
169 | clusterID = ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER;
170 | device = new FlowSensor(extAddress, endpoint, type);
171 |
172 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
173 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
174 | //add senzor special cluster value
175 | if(val.getCount()>0){
176 | val.moveToFirst();
177 | device.position = val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription));
178 | positionVal = device.position;
179 | }
180 |
181 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER+"/last");
182 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
183 | //add senzor special cluster value
184 | if(val.getCount()>0){
185 | val.moveToFirst();
186 | FlowClusterStatus status = new FlowClusterStatus(val.getFloat(val.getColumnIndex(SmartHomeProvider.MeasuredValue)),val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)));
187 | showValue = status.measuredValue + " " + status.unit;
188 | timestampVal = status.timestamp;
189 | }
190 |
191 |
192 | }
193 | break;
194 |
195 | }
196 |
197 | //get data for chart creation
198 |
199 |
200 | Number[] timestamps = new Number[5];
201 | Number[] values = new Number[5];
202 |
203 | Uri allValues = Uri.parse(provider+ "/device/"+device.extAddress+"/"+device.endPoint+"/cluster/"+clusterID+"/last_10_values");
204 | Cursor c = managedQuery(allValues, null, null, null, null);
205 |
206 | Log.d("chart","make chart");
207 | int i=0;
208 | if (c.moveToFirst()) {
209 | do{
210 | // Difference between SQL Timestamp and Java Timestamp, got to *1000
211 | timestamps[i] = new Long(c.getLong(c.getColumnIndex(SmartHomeProvider.Timestamp))*1000);
212 | values[i] = new Double(c.getFloat(c.getColumnIndex(SmartHomeProvider.MeasuredValue)));
213 | Log.d("values","Values" + values[i] + " " + timestamps[i] +" value:"+ c.getString(c.getColumnIndex(SmartHomeProvider.MeasuredValue)));
214 | } while (c.moveToNext() && ++i<5);
215 | }
216 | createChart(timestamps, values, device);
217 |
218 | }
219 | catch (Exception e)
220 | {
221 | Log.e("tag",e.getMessage());
222 | }
223 | // dismiss the progress dialog
224 |
225 | runOnUiThread(new Runnable() {
226 |
227 | @Override
228 | public void run() {
229 | // TODO Auto-generated method stub
230 | location.setText(positionVal);
231 | timestamp.setText(DateFormat.getDateFormat(SensorDetails.this).format(new Date(timestampVal * 1000)) + "");
232 | sensorValue.setText(showValue);
233 |
234 | pd.dismiss();
235 | }
236 | });
237 |
238 | }
239 | }.start();
240 |
241 |
242 | if(type == DeviceConstants.TYPE_FLOW_METER)
243 | img.setImageResource(R.drawable.meter);
244 | else
245 | img.setImageResource(R.drawable.temperature);
246 | }
247 |
248 | /**
249 | * Creates the chart.
250 | *
251 | * @param timestamps the timestamps
252 | * @param values the values
253 | * @param s the s
254 | */
255 | private void createChart(Number[] timestamps, Number[] values, LogicalDevice s){
256 | mySimpleXYPlot.clear();
257 |
258 | // create our series from our array of nums:
259 | XYSeries series = new SimpleXYSeries(
260 | Arrays.asList(timestamps),
261 | Arrays.asList(values),
262 | "Temperatura de la senzor");
263 |
264 | mySimpleXYPlot.getGraphWidget().getGridBackgroundPaint().setColor(Color.WHITE);
265 | mySimpleXYPlot.getGraphWidget().getGridLinePaint().setColor(Color.BLACK);
266 | mySimpleXYPlot.getGraphWidget().getGridLinePaint().setPathEffect(new DashPathEffect(new float[]{1,1}, 1));
267 | mySimpleXYPlot.getGraphWidget().getDomainOriginLinePaint().setColor(Color.BLACK);
268 | mySimpleXYPlot.getGraphWidget().getRangeOriginLinePaint().setColor(Color.BLACK);
269 | mySimpleXYPlot.getGraphWidget().getDomainLabelPaint().setTextSize(16);
270 | mySimpleXYPlot.getGraphWidget().getRangeLabelPaint().setTextSize(16);
271 | mySimpleXYPlot.getGraphWidget().getCursorLabelPaint().setTextSize(16);
272 |
273 | mySimpleXYPlot.setBorderStyle(Plot.BorderStyle.SQUARE, null, null);
274 | mySimpleXYPlot.getBorderPaint().setStrokeWidth(1);
275 | mySimpleXYPlot.getBorderPaint().setAntiAlias(false);
276 | mySimpleXYPlot.getBorderPaint().setColor(Color.WHITE);
277 |
278 | // setup our line fill paint to be a slightly transparent gradient:
279 | Paint lineFill = new Paint();
280 | lineFill.setAlpha(200);
281 | lineFill.setShader(new LinearGradient(0, 0, 0, 250, Color.WHITE, Color.GREEN, Shader.TileMode.MIRROR));
282 |
283 | LineAndPointFormatter formatter = new LineAndPointFormatter(Color.rgb(0, 0,0), Color.BLUE, Color.RED);
284 | formatter.setFillPaint(lineFill);
285 | mySimpleXYPlot.getGraphWidget().setPadding(2, 2, 15, 10);
286 | mySimpleXYPlot.addSeries(series, formatter);
287 |
288 |
289 | //mySimpleXYPlot.setRangeBoundaries(-10, 50, BoundaryMode.SHRINNK);
290 | // draw a domain tick for each entry:
291 | mySimpleXYPlot.setDomainStep(XYStepMode.SUBDIVIDE, timestamps.length);
292 |
293 | // customize our domain/range labels
294 | mySimpleXYPlot.setDomainLabel("Ora");
295 |
296 | if(s.type == DeviceConstants.TYPE_TEMPERATURE_SENSOR)
297 |
298 | mySimpleXYPlot.setRangeLabel("temperatura" +" ("+ TemperatureClusterStatus.unit+")");
299 |
300 | if(s.type == DeviceConstants.TYPE_FLOW_METER)
301 |
302 | mySimpleXYPlot.setRangeLabel("volumul"+" ("+FlowClusterStatus.unit+")");
303 |
304 |
305 | // get rid of decimal points in our range labels:
306 | // mySimpleXYPlot.setRangeValueFormat(new DecimalFormat("0"));
307 |
308 | mySimpleXYPlot.setDomainValueFormat(new SimpleDateFormat("k:mm"));
309 |
310 | // by default, AndroidPlot displays developer guides to aid in laying out your plot.
311 | // To get rid of them call disableAllMarkup():
312 | mySimpleXYPlot.disableAllMarkup();
313 | }
314 |
315 |
316 | }
317 |
--------------------------------------------------------------------------------
/src/upb/smarthome/SmartHomeActivity.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome;
8 |
9 | import java.util.ArrayList;
10 | import java.util.concurrent.ScheduledThreadPoolExecutor;
11 |
12 | import upb.smarthome.clusters.ClusterConstants;
13 | import upb.smarthome.clusters.FlowClusterStatus;
14 | import upb.smarthome.clusters.OnOffClusterStatus;
15 | import upb.smarthome.clusters.TemperatureClusterStatus;
16 | import upb.smarthome.clusters.ThermostatClusterStatus;
17 | import upb.smarthome.data.SmartHomeProvider;
18 | import upb.smarthome.devices.DeviceConstants;
19 | import upb.smarthome.devices.FlowSensor;
20 | import upb.smarthome.devices.LogicalDevice;
21 | import upb.smarthome.devices.OnOffActuator;
22 | import upb.smarthome.devices.TemperatureSensor;
23 | import upb.smarthome.devices.ThermostatActuator;
24 | import android.app.Activity;
25 | import android.app.AlertDialog;
26 | import android.content.ContentValues;
27 | import android.content.Context;
28 | import android.content.DialogInterface;
29 | import android.content.Intent;
30 | import android.database.Cursor;
31 | import android.net.Uri;
32 | import android.os.AsyncTask;
33 | import android.os.Bundle;
34 | import android.os.Handler;
35 | import android.util.Log;
36 | import android.view.LayoutInflater;
37 | import android.view.Menu;
38 | import android.view.MenuItem;
39 | import android.view.View;
40 | import android.view.ViewGroup;
41 | import android.widget.AdapterView;
42 | import android.widget.AdapterView.OnItemClickListener;
43 | import android.widget.AdapterView.OnItemSelectedListener;
44 | import android.widget.ArrayAdapter;
45 | import android.widget.ImageView;
46 | import android.widget.ListView;
47 | import android.widget.Spinner;
48 | import android.widget.TextView;
49 | import android.widget.Toast;
50 |
51 | /**
52 | * The Class SmartHomeActivity.
53 | */
54 | public class SmartHomeActivity extends Activity {
55 |
56 | // Local data
57 | /** The provider. */
58 | private String provider = "content://" + SmartHomeProvider.PROVIDER_NAME;
59 |
60 | /** The senzori. */
61 | public ArrayList senzori;
62 |
63 | /** The senzor types. */
64 | public ArrayList senzorTypes;
65 |
66 | //default value selected
67 | /** The selected spinner value. */
68 | public int selectedSpinnerValue = 0;
69 |
70 | /** The handler. */
71 | private Handler handler = new Handler();
72 |
73 | /** The spinner. */
74 | Spinner spinner;
75 |
76 | //by default show temperature senzors
77 | /** The senzor type listing. */
78 | private int senzorTypeListing = DeviceConstants.TYPE_TEMPERATURE_SENSOR;
79 |
80 | // UI elements
81 | /** The lv. */
82 | private ListView lv;
83 |
84 | // used to update UI from content provider
85 | /** The ui update. */
86 | private MyUiUpdate uiUpdate;
87 |
88 | /** The la. */
89 | ListWithImageAdapter la ;
90 |
91 | /** The content provider. */
92 | SmartHomeProvider contentProvider = new SmartHomeProvider();
93 |
94 | /** The verify battery life. */
95 | private Runnable verifyBatteryLife;
96 |
97 | //minimal battery voltage value 2000 mV
98 | /** The min battery voltage alert value. */
99 | private int minBatteryVoltageAlertValue = 2000;
100 |
101 |
102 | /**
103 | * The Class MyUiUpdate.
104 | */
105 | class MyUiUpdate implements Runnable{
106 |
107 | /* (non-Javadoc)
108 | * @see java.lang.Runnable#run()
109 | */
110 | @Override
111 | public void run() {
112 | //update UI when new data is available
113 |
114 | Log.d("senzori","Senzori" + senzori.size()+" "+ selectedSpinnerValue);
115 | setSenzorSelection(selectedSpinnerValue);
116 | Log.d("senzori","Senzori" + senzori.size());
117 |
118 | la.items.clear();
119 | Log.d("senzori","Aici adauga" + senzori.size());
120 | la.items.addAll(senzori);
121 |
122 | la.notifyDataSetChanged();
123 |
124 | Toast.makeText(getApplicationContext(), "New data update", Toast.LENGTH_LONG).show();
125 | }
126 | }
127 |
128 | /**
129 | * Called when the activity is first created.
130 | *
131 | * @param savedInstanceState the saved instance state
132 | */
133 | @Override
134 | public void onCreate(Bundle savedInstanceState) {
135 | super.onCreate(savedInstanceState);
136 |
137 | // UI initialisation
138 | setContentView(R.layout.sensors);
139 |
140 | String[] senzorTypesStrings = {"Temperature","Flow","Thermostat","Switch"};
141 |
142 | Spinner spinner = (Spinner) findViewById(R.id.chose_senzor_type);
143 |
144 | ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,senzorTypesStrings);
145 |
146 | adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
147 | spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
148 | spinner.setAdapter(adapter);
149 |
150 | //set regular updates from server
151 |
152 | if(contentProvider.isUpdatesEnabled() == false)
153 | contentProvider.updateRegularFromServer();
154 |
155 | uiUpdate = new MyUiUpdate();
156 | contentProvider.setUiUpdate(handler, uiUpdate);
157 |
158 | lv = (ListView) findViewById(R.id.listView);
159 |
160 | //default value of list is temperature
161 | setSenzorSelection(DeviceConstants.TYPE_TEMPERATURE_SENSOR);
162 |
163 | // Configure UI for the sensor list
164 | la = new ListWithImageAdapter(this,R.layout.list_item, senzori);
165 | lv.setAdapter(la);
166 | // What happens when you click a button in the Sensor list
167 | lv.setOnItemClickListener(new OnItemClickListener() {
168 | public void onItemClick(AdapterView> parent, View view, int position, long id) {
169 |
170 | LogicalDevice s = (LogicalDevice)senzori.get(position);
171 |
172 | //start new activity
173 | if(s.type == DeviceConstants.TYPE_ON_OFF){
174 | new ToggleOnOff().execute((OnOffActuator)s);
175 | }else
176 | if(s.type == DeviceConstants.TYPE_THERMOSTAT)
177 | {
178 |
179 | Intent intent = new Intent(getApplicationContext(), ThermostatControl.class);
180 | intent.putExtra("extAddress", s.extAddress);
181 | intent.putExtra("endpoint", s.endPoint);
182 | intent.putExtra("type", s.type);
183 |
184 | startActivity(intent);
185 | }
186 | else
187 | {
188 | Intent intent = new Intent(getApplicationContext(), SensorDetails.class);
189 | intent.putExtra("extAddress", s.extAddress);
190 | intent.putExtra("endpoint", s.endPoint);
191 | intent.putExtra("type", s.type);
192 |
193 | startActivity(intent);
194 | }
195 | }
196 | });
197 |
198 |
199 | verifyBatteryLife = new Runnable() {
200 |
201 | @Override
202 | public void run() {
203 |
204 |
205 |
206 |
207 | Uri getSensorPowerInfo= Uri.parse(provider+"/cluster/"+ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER);
208 | Cursor values = managedQuery(getSensorPowerInfo, null, null, null, null);
209 |
210 |
211 | if(values.moveToFirst()){
212 | do{
213 | int batteryVoltage = values.getInt(values.getColumnIndex(SmartHomeProvider.BatteryVoltage));
214 |
215 | Log.d("Battery","voltage : " + batteryVoltage);
216 |
217 | final String extAddressLowPower = values.getString(values.getColumnIndex(SmartHomeProvider.Device_extAddress));
218 |
219 | //if battery voltage under a value and positive (it has a battery)
220 | if( batteryVoltage < minBatteryVoltageAlertValue && batteryVoltage > 0)
221 | handler.post(new Runnable() {
222 |
223 | @Override
224 | public void run() {
225 | // TODO Auto-generated method stub
226 | //show an alert box
227 | new AlertDialog.Builder(SmartHomeActivity.this)
228 | .setMessage("It has been detected that sensor with id :" + extAddressLowPower + " has a low voltage and may malfanction.Please change batteries!")
229 | .setTitle("Low voltage ")
230 | .setCancelable(true)
231 | .setNeutralButton(android.R.string.cancel,
232 | new DialogInterface.OnClickListener() {
233 | public void onClick(DialogInterface dialog, int whichButton){}
234 | })
235 | .show();
236 | }
237 | });
238 |
239 |
240 |
241 |
242 | }while(values.moveToNext());
243 | }
244 |
245 | }
246 | };
247 |
248 |
249 | //check to see if all sensors are ok, they have energy over a value
250 | new Thread(verifyBatteryLife).start();
251 | }
252 |
253 | /**
254 | * Sets the senzor selection.
255 | *
256 | * @param senzorType the new senzor selection
257 | */
258 | public void setSenzorSelection(int senzorType){
259 |
260 | Uri allSenzors = Uri.parse(provider+"/devices/type/"+senzorType);
261 |
262 | senzori = new ArrayList();
263 |
264 | selectedSpinnerValue = senzorType;
265 |
266 | Log.d("senzori","Get senzori din baza de date ");
267 | Cursor c = managedQuery(allSenzors, null, null, null, null);
268 | if (c.moveToFirst()) {
269 | do{
270 | Log.d("senzori","Senzors");
271 | String extAddress = c.getString(c.getColumnIndex(SmartHomeProvider.ExtAddress));
272 | int endpoint = c.getInt(c.getColumnIndex(SmartHomeProvider.Endpoint));
273 | int type = c.getInt(c.getColumnIndex(SmartHomeProvider.TYPE));
274 | switch(senzorType){
275 |
276 | case DeviceConstants.TYPE_TEMPERATURE_SENSOR : {
277 |
278 | TemperatureSensor device = new TemperatureSensor(extAddress, endpoint, type);
279 |
280 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
281 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
282 | //add senzor special cluster value
283 | if(val.getCount()>0){
284 |
285 | val.moveToFirst();
286 | device.position = val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription));
287 | Log.d("senzor_info","Location : " + device.position);
288 | }
289 |
290 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER+"/last");
291 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
292 | //add senzor special cluster value
293 | if(val.getCount()>0){
294 | val.moveToFirst();
295 | device.tempCluster.currentStatus = new TemperatureClusterStatus(val.getFloat(val.getColumnIndex(SmartHomeProvider.MeasuredValue)),val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)));
296 | Log.d("senzor_info","Temeprature: " + device.tempCluster.currentStatus.measuredValue);
297 | }
298 | else
299 | Log.d("senzor_info","Temperature: nu e setata");
300 | senzori.add(device);
301 | }
302 | break;
303 | case DeviceConstants.TYPE_FLOW_METER : {
304 |
305 | FlowSensor device = new FlowSensor(extAddress, endpoint, type);
306 |
307 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
308 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
309 | //add senzor special cluster value
310 | if(val.getCount()>0){
311 | val.moveToFirst();
312 | device.position = val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription));
313 | }
314 |
315 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER+"/last");
316 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
317 | //add senzor special cluster value
318 | if(val.getCount()>0){
319 | val.moveToFirst();
320 | device.flowCluster.currentStatus = new FlowClusterStatus(val.getFloat(val.getColumnIndex(SmartHomeProvider.MeasuredValue)),val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)));
321 | }
322 | senzori.add(device);
323 | }
324 | break;
325 |
326 | case DeviceConstants.TYPE_ON_OFF : {
327 |
328 | OnOffActuator device = new OnOffActuator(extAddress, endpoint, type);
329 |
330 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
331 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
332 | //add senzor special cluster value
333 | if(val.getCount()>0){
334 |
335 | val.moveToFirst();
336 | device.position = val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription));
337 | }
338 |
339 |
340 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_ON_OFF_CLUSTER+"/last");
341 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
342 | //add senzor special cluster value
343 |
344 | Log.d("debug","Intrari " + val.getCount());
345 | if(val.getCount()>0){
346 | val.moveToFirst();
347 | device.onOffcluster.currentStatus = new OnOffClusterStatus(val.getInt(val.getColumnIndex(SmartHomeProvider.On_Off_Status)),val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)));
348 | do{
349 | Log.d("valori_on_off","Ext Timestamp status "+device.onOffcluster.currentStatus.status+" val" + val.getString(val.getColumnIndex("device_extAddress")) + " " + val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)) +" " + val.getInt(val.getColumnIndex(SmartHomeProvider.On_Off_Status)) + " " +val.getCount());
350 | }while(val.moveToNext());
351 | }
352 |
353 |
354 |
355 | Log.d("timestamp","On off switch" + device.onOffcluster.currentStatus.timestamp + " " + device.onOffcluster.currentStatus.status);
356 | senzori.add(device);
357 | }
358 | break;
359 |
360 | case DeviceConstants.TYPE_THERMOSTAT : {
361 |
362 | ThermostatActuator device = new ThermostatActuator(extAddress, endpoint, type);
363 |
364 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
365 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
366 | //add senzor special cluster value
367 | if(val.getCount()>0){
368 | val.moveToFirst();
369 | device.position = val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription));
370 | }
371 |
372 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endpoint+"/cluster/"+ClusterConstants.ID_THERMOSTAT_CLUSTER+"/last");
373 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
374 | //add senzor special cluster value
375 | if(val.getCount()>0){
376 | val.moveToFirst();
377 | device.thermostatCluster.currentStatus = new ThermostatClusterStatus(val.getFloat(val.getColumnIndex(SmartHomeProvider.LocalTemperature)),val.getFloat(val.getColumnIndex(SmartHomeProvider.MinHeat)),val.getFloat(val.getColumnIndex(SmartHomeProvider.MaxHeat)),val.getInt(val.getColumnIndex(SmartHomeProvider.Timestamp)));
378 | }
379 | senzori.add(device);
380 | }
381 | break;
382 | }
383 | }while (c.moveToNext());
384 | }
385 | }
386 |
387 |
388 | // What happens when you press the menu button on your phone
389 | /* (non-Javadoc)
390 | * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
391 | */
392 | @Override
393 | public boolean onCreateOptionsMenu(Menu menu) {
394 | //MenuInflater inflater = getMenuInflater();
395 | //inflater.inflate(R.menu, menu);
396 | return true;
397 | }
398 | // What happens when you press a button in the Options menu
399 | /* (non-Javadoc)
400 | * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
401 | */
402 | @Override
403 | public boolean onOptionsItemSelected(MenuItem item) {
404 |
405 | return true;
406 | }
407 |
408 | // Custom adapter to populate the sensors list
409 | /**
410 | * The Class ListWithImageAdapter.
411 | */
412 | private class ListWithImageAdapter extends ArrayAdapter {
413 |
414 | /** The items. */
415 | private ArrayList items;
416 |
417 | /**
418 | * Instantiates a new list with image adapter.
419 | *
420 | * @param context the context
421 | * @param textViewResourceId the text view resource id
422 | * @param items the items
423 | */
424 | public ListWithImageAdapter(Context context, int textViewResourceId, ArrayList items) {
425 | super(context, textViewResourceId, items);
426 | this.items = items;
427 | }
428 |
429 | /* (non-Javadoc)
430 | * @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
431 | */
432 | @Override
433 | public View getView(int position, View convertView, ViewGroup parent) {
434 | View v = convertView;
435 | if (v == null) {
436 | LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
437 | v = vi.inflate(R.layout.list_item, null);
438 | }
439 |
440 | LogicalDevice s = items.get(position);
441 | if (s != null) {
442 | TextView t = (TextView) v.findViewById(R.id.txtName);
443 | if (t != null) {
444 | t.setText(s.position);
445 | }
446 | t = (TextView) v.findViewById(R.id.txtLocation);
447 | if (t != null) {
448 |
449 | t.setText(""+s.extAddress);
450 |
451 | }
452 | t = (TextView) v.findViewById(R.id.txtValue);
453 | if (t != null) {
454 | //TODO
455 |
456 | switch(s.type){
457 |
458 | case DeviceConstants.TYPE_TEMPERATURE_SENSOR: {t.setText("" + ((TemperatureSensor)s).tempCluster.currentStatus.measuredValue );} break;
459 |
460 | case DeviceConstants.TYPE_FLOW_METER: {t.setText("" + ((FlowSensor)s).flowCluster.currentStatus.measuredValue);} break;
461 |
462 | case DeviceConstants.TYPE_ON_OFF: {
463 | if(((OnOffActuator)(s)).onOffcluster.currentStatus.status == 1)
464 | t.setText("On");
465 | else
466 | t.setText("Off");
467 | } break;
468 |
469 | case DeviceConstants.TYPE_THERMOSTAT: {t.setText("" + ((ThermostatActuator)s).thermostatCluster.currentStatus.MinHeatSetpointLimit + " :" +
470 | +((ThermostatActuator)s).thermostatCluster.currentStatus.MaxHeatSetpointLimit );} break;
471 |
472 |
473 | }
474 |
475 | }
476 | ImageView i = (ImageView) v.findViewById(R.id.img);
477 | if (i != null) {
478 | if (s.type==DeviceConstants.TYPE_TEMPERATURE_SENSOR) {
479 | i.setImageResource(R.drawable.temperature);
480 | }
481 | if (s.type==DeviceConstants.TYPE_FLOW_METER) {
482 | i.setImageResource(R.drawable.meter);
483 | }
484 | if(s.type==DeviceConstants.TYPE_ON_OFF){
485 | if(((OnOffActuator)(s)).onOffcluster.currentStatus.status == 1)
486 | i.setImageResource(R.drawable.light_switch_on);
487 | else
488 | i.setImageResource(R.drawable.light_switch_off);
489 | }
490 | if(s.type==DeviceConstants.TYPE_THERMOSTAT){
491 | i.setImageResource(R.drawable.thermostat);
492 | }
493 | }
494 | }
495 | return v;
496 | }
497 | }
498 |
499 | /**
500 | * The listener interface for receiving myOnItemSelected events.
501 | * The class that is interested in processing a myOnItemSelected
502 | * event implements this interface, and the object created
503 | * with that class is registered with a component using the
504 | * component's addMyOnItemSelectedListener method. When
505 | * the myOnItemSelected event occurs, that object's appropriate
506 | * method is invoked.
507 | *
508 | * @see MyOnItemSelectedEvent
509 | */
510 | class MyOnItemSelectedListener implements OnItemSelectedListener {
511 |
512 | /* (non-Javadoc)
513 | * @see android.widget.AdapterView.OnItemSelectedListener#onItemSelected(android.widget.AdapterView, android.view.View, int, long)
514 | */
515 | public void onItemSelected(AdapterView> parent,
516 | View view, int pos, long id) {
517 |
518 | Log.d("senzori","Selctat" + pos);
519 | switch(pos){
520 |
521 | case 0 : setSenzorSelection(DeviceConstants.TYPE_TEMPERATURE_SENSOR); break;
522 | case 1 : setSenzorSelection(DeviceConstants.TYPE_FLOW_METER);break;
523 | case 2 : setSenzorSelection(DeviceConstants.TYPE_THERMOSTAT);break;
524 | case 3 : setSenzorSelection(DeviceConstants.TYPE_ON_OFF);break;
525 | }
526 |
527 | la.items.clear();
528 | Log.d("senzori","Aici adauga" + senzori.size());
529 | la.items.addAll(senzori);
530 |
531 | la.notifyDataSetChanged();
532 |
533 | Toast.makeText(parent.getContext(), "The senzor displayed is " +
534 | parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show();
535 | }
536 |
537 | /* (non-Javadoc)
538 | * @see android.widget.AdapterView.OnItemSelectedListener#onNothingSelected(android.widget.AdapterView)
539 | */
540 | public void onNothingSelected(AdapterView parent) {
541 | // Do nothing.
542 | }
543 | }
544 |
545 |
546 |
547 |
548 | /* (non-Javadoc)
549 | * @see android.app.Activity#onResume()
550 | */
551 | @Override
552 | protected void onResume() {
553 | // TODO Auto-generated method stub
554 | super.onResume();
555 | if(contentProvider.isUpdatesEnabled() == false)
556 | contentProvider.updateRegularFromServer();
557 |
558 | contentProvider.setUiUpdate(handler, uiUpdate);
559 | }
560 |
561 |
562 | /* (non-Javadoc)
563 | * @see android.app.Activity#onStop()
564 | */
565 | @Override
566 | protected void onStop() {
567 | // TODO Auto-generated method stub
568 | super.onStop();
569 |
570 |
571 | //contentProvider.stopRegularUpdates();
572 |
573 | }
574 |
575 | /* (non-Javadoc)
576 | * @see android.app.Activity#onDestroy()
577 | */
578 | @Override
579 | protected void onDestroy() {
580 | // TODO Auto-generated method stub
581 | super.onDestroy();
582 | contentProvider.stopRegularUpdates();
583 |
584 | }
585 |
586 |
587 | // custom AsyncTask that is called when an actuator is tapped in order to toggle its setting
588 | /**
589 | * The Class ToggleOnOff.
590 | */
591 | private class ToggleOnOff extends AsyncTask {
592 |
593 | /** The o. */
594 | private OnOffActuator o;
595 |
596 | /* (non-Javadoc)
597 | * @see android.os.AsyncTask#doInBackground(Params[])
598 | */
599 | protected Boolean doInBackground(OnOffActuator... os) {
600 |
601 |
602 | ContentValues editedValues = new ContentValues();
603 | o = os[0];
604 |
605 | if(o.onOffcluster.currentStatus.status == 1)
606 | editedValues.put("status", 0);
607 | else
608 | editedValues.put("status", 1);
609 |
610 | Uri actuatorChange = Uri.parse(provider+"/device/"+o.extAddress+"/"+o.endPoint+"/switch/"+0);
611 |
612 |
613 | if (getContentResolver().update(actuatorChange,editedValues,null,null)!=0)
614 | return true;
615 | return false;
616 | }
617 |
618 | /* (non-Javadoc)
619 | * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
620 | */
621 | protected void onPostExecute(Boolean result) {
622 | if (result){
623 |
624 | //((ListWithImageAdapter) lv.getAdapter()).notifyDataSetChanged();
625 | } else {
626 | Toast.makeText(getApplicationContext(), "Actuator setting change failed", Toast.LENGTH_SHORT);
627 | }
628 | }
629 | }
630 |
631 | }
632 |
633 |
--------------------------------------------------------------------------------
/src/upb/smarthome/ThermostatControl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome;
8 |
9 | import upb.smarthome.clusters.ClusterConstants;
10 | import upb.smarthome.clusters.ThermostatClusterStatus;
11 | import upb.smarthome.data.SmartHomeProvider;
12 | import upb.smarthome.devices.OnOffActuator;
13 | import android.app.Activity;
14 | import android.app.ProgressDialog;
15 | import android.content.ContentValues;
16 | import android.database.Cursor;
17 | import android.net.Uri;
18 | import android.os.AsyncTask;
19 | import android.os.Bundle;
20 | import android.util.Log;
21 | import android.view.Display;
22 | import android.view.MotionEvent;
23 | import android.view.View;
24 | import android.view.View.OnClickListener;
25 | import android.widget.Button;
26 | import android.widget.ImageView;
27 | import android.widget.TextView;
28 | import android.widget.Toast;
29 |
30 | /**
31 | * The Class ThermostatControl.
32 | * You can modify the temperature using a flip gesture on the Oy Axis
33 | * If you make a flip from buttom to up on the right size of the thermostat, you will increase the high value, else
34 | * you will increase the minimum value.
35 | */
36 | public class ThermostatControl extends Activity{
37 |
38 | // Local data
39 | /** The provider. */
40 | private String provider = "content://" + SmartHomeProvider.PROVIDER_NAME;
41 |
42 |
43 | /** The thermostat min. */
44 | private TextView thermostatMin;
45 |
46 | /** The thermostat max. */
47 | private TextView thermostatMax;
48 |
49 | /** The position. */
50 | private TextView position;
51 |
52 | /** The progress dialog. */
53 | private ProgressDialog progressDialog;
54 |
55 | /** The save settings button. */
56 | private Button saveSettingsButton;
57 |
58 | /** The measured min. */
59 | private float measuredMin;
60 |
61 | /** The measured max. */
62 | private float measuredMax;
63 |
64 | /** The img. */
65 | private ImageView img;
66 |
67 | /** The Constant MIN_DISTANCE. */
68 | static final int MIN_DISTANCE = 30;
69 |
70 | /** The up y. */
71 | private float downX, downY, upX, upY;
72 |
73 | /** The display width. */
74 | private float displayWidth;
75 |
76 | //modified based on the touched event
77 | /** The STE p_ value. */
78 | private float STEP_VALUE = 0.01f;
79 |
80 | /** The ext address. */
81 | private String extAddress;
82 |
83 | /** The end point. */
84 | private int endPoint;
85 |
86 | /* (non-Javadoc)
87 | * @see android.app.Activity#onCreate(android.os.Bundle)
88 | */
89 | @Override
90 | protected void onCreate(Bundle savedInstanceState) {
91 | // TODO Auto-generated method stub
92 | super.onCreate(savedInstanceState);
93 |
94 | setContentView(R.layout.thermostat);
95 | Bundle bundle = getIntent().getExtras();
96 | thermostatMin = (TextView) findViewById(R.id.thermostat_value_min);
97 | thermostatMax = (TextView) findViewById(R.id.thermostat_value_max);
98 | position = (TextView) findViewById(R.id.thermostat_position);
99 | saveSettingsButton = (Button) findViewById(R.id.thermostat_save);
100 |
101 |
102 | img = (ImageView) findViewById(R.id.thermostat_image);
103 |
104 | img.setImageResource(R.drawable.thermostat);
105 |
106 | extAddress = bundle.getString("extAddress");
107 | endPoint = bundle.getInt("endpoint");
108 | int type = bundle.getInt("type");
109 | int clusterID = ClusterConstants.ID_THERMOSTAT_CLUSTER;
110 |
111 |
112 | Uri getSenzorPosition= Uri.parse(provider + "/device/"+extAddress+"/"+endPoint+"/cluster/"+ClusterConstants.ID_BASIC_CLUSTER+"/last");
113 | Cursor val = managedQuery(getSenzorPosition, null, null, null, null);
114 | //add senzor special cluster value
115 | if(val.getCount()>0){
116 | val.moveToFirst();
117 | position.setText(val.getString(val.getColumnIndex(SmartHomeProvider.LocationDescription)));
118 |
119 | }
120 |
121 | Uri getSenzorLastDataCluster = Uri.parse(provider + "/device/"+extAddress+"/"+endPoint+"/cluster/"+ClusterConstants.ID_THERMOSTAT_CLUSTER+"/last");
122 | val = managedQuery(getSenzorLastDataCluster, null, null, null, null);
123 | //add senzor special cluster value
124 | if(val.getCount()>0){
125 | val.moveToFirst();
126 | measuredMin = val.getFloat(val.getColumnIndex(SmartHomeProvider.MinHeat));
127 | measuredMax = val.getFloat(val.getColumnIndex(SmartHomeProvider.MaxHeat));
128 |
129 |
130 |
131 | }
132 | Log.d("thermostat",""+ measuredMin + " " + measuredMax);
133 |
134 | thermostatMin.setText(measuredMin + " ");
135 | thermostatMax.setText(": "+measuredMax + " °C" );
136 |
137 | saveSettingsButton.setOnClickListener(new OnClickListener() {
138 |
139 | @Override
140 | public void onClick(View v) {
141 | // TODO Auto-generated method stub
142 | new SaveThermostatValues().execute(new ThermostatClusterStatus(0,measuredMin,measuredMax,0));
143 | }
144 | });
145 |
146 | Display display = getWindowManager().getDefaultDisplay();
147 | displayWidth = display.getWidth();
148 |
149 |
150 | }
151 |
152 | /* (non-Javadoc)
153 | * @see android.app.Activity#onTouchEvent(android.view.MotionEvent)
154 | */
155 | @Override
156 | public boolean onTouchEvent(MotionEvent event) {
157 |
158 | String logTag = "command log";
159 |
160 |
161 | switch (event.getAction()) {
162 | case MotionEvent.ACTION_DOWN: {
163 | downX = event.getX();
164 | downY = event.getY();
165 | return true;
166 | }
167 | case MotionEvent.ACTION_UP: {
168 | upX = event.getX();
169 | upY = event.getY();
170 |
171 | float deltaX = downX - upX;
172 | float deltaY = downY - upY;
173 |
174 |
175 |
176 | // swipe vertical
177 | if (Math.abs(deltaY) > MIN_DISTANCE) {
178 |
179 | STEP_VALUE = (int)(Math.abs(deltaY)%(MIN_DISTANCE))/100f;
180 |
181 | Log.d("thermostat","Step " + STEP_VALUE);
182 | // up to down
183 | if (deltaY < 0) {
184 |
185 | Log.d(logTag,"up to down");
186 |
187 | Log.d(logTag,"Width x up " + displayWidth + ":" + upX );
188 |
189 | if(upX>displayWidth/2){
190 | // right value
191 | measuredMax -= STEP_VALUE;
192 | thermostatMax.setText(String.format("%.2g",measuredMax)+" °C");
193 |
194 | }
195 | else
196 | { // left value
197 | measuredMin -= STEP_VALUE;
198 | thermostatMin.setText(String.format("%.2g",measuredMin)+" ");
199 |
200 | }
201 | return true;
202 | }
203 | // down to up
204 | if (deltaY > 0) {
205 |
206 | if(upX>displayWidth/2){
207 | // right value
208 | measuredMax += STEP_VALUE;
209 | thermostatMax.setText(String.format("%.2g",measuredMax)+" °C");
210 | }
211 | else
212 | { // left value
213 | measuredMin += STEP_VALUE;
214 | thermostatMin.setText(String.format("%.2g",measuredMin)+" ");
215 |
216 | }
217 | Log.d(logTag,"down to up");
218 | return true;
219 | }
220 | } else {
221 | if(Math.abs(deltaX)<15){
222 | //onClickEvent();
223 | }
224 | Log.i("swipe", "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
225 | }
226 | // swipe vertical?
227 | if (Math.abs(deltaY) > MIN_DISTANCE) {
228 |
229 | } else {
230 | Log.i(logTag, "Swipe was only " + Math.abs(deltaX)
231 | + " long, need at least " + MIN_DISTANCE);
232 | }
233 |
234 | return true;
235 | }
236 | }
237 | return false;
238 |
239 | }
240 |
241 | // custom AsyncTask that is called when an actuator is tapped in order to toggle its setting
242 | /**
243 | * The Class SaveThermostatValues.
244 | */
245 | private class SaveThermostatValues extends AsyncTask {
246 |
247 | /** The o. */
248 | private OnOffActuator o;
249 |
250 | /* (non-Javadoc)
251 | * @see android.os.AsyncTask#doInBackground(Params[])
252 | */
253 | protected Boolean doInBackground(ThermostatClusterStatus... os) {
254 |
255 |
256 | ThermostatClusterStatus status;
257 | status = os[0];
258 |
259 | ContentValues editedValues = new ContentValues();
260 |
261 |
262 | editedValues.put("minValue", status.MinHeatSetpointLimit);
263 | editedValues.put("maxValue", status.MaxHeatSetpointLimit);
264 |
265 | Uri actuatorChange = Uri.parse(provider+"/device/"+extAddress+"/"+endPoint+"/thermostat/");
266 |
267 |
268 | if (getContentResolver().update(actuatorChange,editedValues,null,null)!=0)
269 | return true;
270 | return false;
271 | }
272 |
273 | /* (non-Javadoc)
274 | * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
275 | */
276 | protected void onPostExecute(Boolean result) {
277 | if (result){
278 |
279 | Toast.makeText(getApplicationContext(), "Thermostat temperature changed", Toast.LENGTH_SHORT);
280 |
281 | //((ListWithImageAdapter) lv.getAdapter()).notifyDataSetChanged();
282 | } else {
283 | Toast.makeText(getApplicationContext(), "Actuator setting change failed", Toast.LENGTH_SHORT);
284 | }
285 | }
286 | }
287 | }
288 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/BasicCluster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * The Class BasicCluster.
13 | * Class used in ZigBee standard
14 | */
15 | public class BasicCluster {
16 |
17 | /** The statuses. */
18 | private ArrayList statuses;
19 |
20 | //null constructor
21 | /**
22 | * Instantiates a new basic cluster.
23 | */
24 | public BasicCluster(){
25 |
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/BasicClusterStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | /**
10 | * The Class BasicClusterStatus.
11 | * Class used in ZigBee standard
12 | */
13 | public class BasicClusterStatus {
14 |
15 | /** The Power source value. */
16 | public int PowerSourceValue;
17 |
18 | /** The Location description. */
19 | public String LocationDescription;
20 |
21 | /** The Device enabled. */
22 | public Boolean DeviceEnabled;
23 |
24 | /** The ZCL version. */
25 | public int ZCLVersion;
26 |
27 | /** The timestamp. */
28 | public long timestamp;
29 |
30 | }
31 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/ClusterConstants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | /**
10 | * The Class ClusterConstants.
11 | */
12 | public class ClusterConstants {
13 |
14 | //Cluster ID's used to get data from clusters
15 | /** The Constant ID_BASIC_CLUSTER. */
16 | public static final int ID_BASIC_CLUSTER = 0;
17 |
18 | /** The Constant ID_POWER_CONFIGURATION_CLUSTER. */
19 | public static final int ID_POWER_CONFIGURATION_CLUSTER = 1;
20 |
21 | /** The Constant ID_TEMPERATURE_MEASUREMENT_CLUSTER. */
22 | public static final int ID_TEMPERATURE_MEASUREMENT_CLUSTER = 402;
23 |
24 | /** The Constant ID_ON_OFF_CLUSTER. */
25 | public static final int ID_ON_OFF_CLUSTER = 7;
26 |
27 | /** The Constant ID_FLOW_MESUREMENT_CLUSTER. */
28 | public static final int ID_FLOW_MESUREMENT_CLUSTER = 404;
29 |
30 | /** The Constant ID_THERMOSTAT_CLUSTER. */
31 | public static final int ID_THERMOSTAT_CLUSTER = 201;
32 |
33 |
34 | //Basic cluster ID attributes
35 | /** The Constant BASIC_ZCLVersion. */
36 | public static final String BASIC_ZCLVersion = "0000";
37 |
38 | /** The Constant BASIC_PowerSource. */
39 | public static final String BASIC_PowerSource = "0007";
40 |
41 | /** The Constant BASIC_LocationDescription. */
42 | public static final String BASIC_LocationDescription = "0010";
43 |
44 | /** The Constant BASIC_DeviceEnabled. */
45 | public static final String BASIC_DeviceEnabled = "0012";
46 |
47 | //Power Configuration Cluster
48 | /** The Constant POWER_MainsVoltage. */
49 | public static final String POWER_MainsVoltage = "0000";
50 |
51 | /** The Constant POWER_MainsFrequency. */
52 | public static final String POWER_MainsFrequency = "0001";
53 |
54 | /** The Constant POWER_BatteryVoltage. */
55 | public static final String POWER_BatteryVoltage = "0020";
56 |
57 | //Temperature measurement cluster
58 | /** The Constant TEMPERATURE_MeasuredValue. */
59 | public static final String TEMPERATURE_MeasuredValue = "0000";
60 |
61 | //On/Off cluster
62 | /** The Constant ON_OFF. */
63 | public static final String ON_OFF = "0000";
64 |
65 | //Flow measurement cluster
66 | /** The Constant FLOW_MeasuredValue. */
67 | public static final String FLOW_MeasuredValue = "0000";
68 |
69 | //Thermostat cluster
70 | /** The Constant THERMOSTAT_LocalTemperature. */
71 | public static final String THERMOSTAT_LocalTemperature = "0000";
72 |
73 | /** The Constant THERMOSTAT_MinHeatSetpointLimit. */
74 | public static final String THERMOSTAT_MinHeatSetpointLimit = "0015";
75 |
76 | /** The Constant THERMOSTAT_MaxHeatSetpointLimit. */
77 | public static final String THERMOSTAT_MaxHeatSetpointLimit = "0016";
78 |
79 | }
80 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/FlowCluster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * The Class FlowCluster.
13 | */
14 | public class FlowCluster {
15 |
16 | /** The statuses. */
17 | public ArrayList statuses;
18 |
19 | /** The current status. */
20 | public FlowClusterStatus currentStatus;
21 |
22 | /**
23 | * Instantiates a new flow cluster.
24 | */
25 | public FlowCluster(){
26 |
27 | statuses = new ArrayList();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/FlowClusterStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | /**
10 | * The Class FlowClusterStatus.
11 | */
12 | public class FlowClusterStatus {
13 |
14 | /** The unit. */
15 | public static String unit = "l";
16 |
17 | /** The measured value. */
18 | public float measuredValue;
19 |
20 | /** The timestamp. */
21 | public int timestamp;
22 |
23 | /**
24 | * Instantiates a new flow cluster status.
25 | *
26 | * @param measuredValue the measured value
27 | * @param timestamp the timestamp
28 | */
29 | public FlowClusterStatus(float measuredValue, int timestamp) {
30 | super();
31 | this.measuredValue = measuredValue;
32 | this.timestamp = timestamp;
33 | }
34 |
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/OnOffCluster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * The Class OnOffCluster.
13 | */
14 | public class OnOffCluster {
15 |
16 | /** The statuses. */
17 | public ArrayList statuses;
18 |
19 | /** The current status. */
20 | public OnOffClusterStatus currentStatus;
21 |
22 | /**
23 | * Instantiates a new on off cluster.
24 | */
25 | public OnOffCluster(){
26 |
27 | statuses = new ArrayList();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/OnOffClusterStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | /**
10 | * The Class OnOffClusterStatus.
11 | */
12 | public class OnOffClusterStatus {
13 |
14 | /** The status. */
15 | public int status;
16 |
17 | /** The timestamp. */
18 | public int timestamp;
19 |
20 | /**
21 | * Instantiates a new on off cluster status.
22 | *
23 | * @param status the status
24 | * @param timestamp the timestamp
25 | */
26 | public OnOffClusterStatus(int status,int timestamp){
27 |
28 | this.status = status;
29 | this.timestamp = timestamp;
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/PowerCluster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * The Class PowerCluster.
13 | */
14 | public class PowerCluster {
15 |
16 |
17 |
18 | /** The statuses. */
19 | public ArrayList statuses;
20 |
21 | }
22 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/PowerClusterStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | /**
10 | * The Class PowerClusterStatus.
11 | */
12 | public class PowerClusterStatus {
13 |
14 | /** The mains voltage. */
15 | public float mainsVoltage;
16 |
17 | /** The mains frequency. */
18 | public float mainsFrequency;
19 |
20 | /** The battery voltage. */
21 | public float batteryVoltage;
22 |
23 | }
24 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/TemperatureCluster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | import java.util.ArrayList;
10 |
11 | /**
12 | * The Class TemperatureCluster.
13 | */
14 | public class TemperatureCluster {
15 |
16 | /** The statuses. */
17 | public ArrayList statuses;
18 |
19 | /** The current status. */
20 | public TemperatureClusterStatus currentStatus;
21 |
22 | /**
23 | * Instantiates a new temperature cluster.
24 | */
25 | public TemperatureCluster(){
26 |
27 | statuses = new ArrayList();
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/TemperatureClusterStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | public class TemperatureClusterStatus {
10 |
11 | public static String unit = "°C";
12 |
13 | public float measuredValue;
14 | public int timestamp;
15 |
16 | /**
17 | * Instantiates a new temperature cluster status.
18 | *
19 | * @param measuredValue the measured value
20 | * @param timestamp the timestamp
21 | */
22 | public TemperatureClusterStatus(float measuredValue,int timestamp) {
23 | super();
24 | this.measuredValue = measuredValue;
25 | this.timestamp = timestamp;
26 | }
27 |
28 | }
29 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/ThermostatCluster.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | import java.util.ArrayList;
10 |
11 | public class ThermostatCluster {
12 |
13 | public ArrayList statuses ;
14 |
15 | public ThermostatClusterStatus currentStatus;
16 |
17 | /**
18 | * Instantiates a new thermostat cluster.
19 | */
20 | public ThermostatCluster(){
21 |
22 | statuses = new ArrayList();
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/upb/smarthome/clusters/ThermostatClusterStatus.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.clusters;
8 |
9 | /**
10 | * The Class ThermostatClusterStatus.
11 | */
12 | public class ThermostatClusterStatus {
13 |
14 | /** The unit. */
15 | public static String unit = "°C";
16 |
17 | /** The Local temperature. */
18 | public float LocalTemperature;
19 |
20 | /** The Min heat setpoint limit. */
21 | public float MinHeatSetpointLimit;
22 |
23 | /** The Max heat setpoint limit. */
24 | public float MaxHeatSetpointLimit;
25 |
26 | /** The timestamp. */
27 | public int timestamp;
28 |
29 | /**
30 | * Instantiates a new thermostat cluster status.
31 | *
32 | * @param localTemperature the local temperature
33 | * @param minHeatSetpointLimit the min heat setpoint limit
34 | * @param maxHeatSetpointLimit the max heat setpoint limit
35 | * @param timestamp the timestamp
36 | */
37 | public ThermostatClusterStatus(float localTemperature,
38 | float minHeatSetpointLimit, float maxHeatSetpointLimit,
39 | int timestamp) {
40 | super();
41 | LocalTemperature = localTemperature;
42 | MinHeatSetpointLimit = minHeatSetpointLimit;
43 | MaxHeatSetpointLimit = maxHeatSetpointLimit;
44 | this.timestamp = timestamp;
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/upb/smarthome/data/SmartHomeProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 |
8 | package upb.smarthome.data;
9 |
10 |
11 | import java.util.ArrayList;
12 | import java.util.HashMap;
13 | import java.util.StringTokenizer;
14 | import java.util.concurrent.ScheduledFuture;
15 | import java.util.concurrent.ScheduledThreadPoolExecutor;
16 | import java.util.concurrent.TimeUnit;
17 |
18 | import org.apache.http.NameValuePair;
19 | import org.apache.http.client.ClientProtocolException;
20 | import org.apache.http.conn.ConnectTimeoutException;
21 | import org.apache.http.message.BasicNameValuePair;
22 | import org.json.JSONArray;
23 | import org.json.JSONException;
24 | import org.json.JSONObject;
25 |
26 | import upb.smarthome.clusters.ClusterConstants;
27 | import upb.smarthome.restcomm.JSONParser;
28 | import upb.smarthome.restcomm.RestComm;
29 | import android.content.ContentProvider;
30 | import android.content.ContentResolver;
31 | import android.content.ContentValues;
32 | import android.content.Context;
33 | import android.content.UriMatcher;
34 | import android.database.Cursor;
35 | import android.database.SQLException;
36 | import android.database.sqlite.SQLiteDatabase;
37 | import android.database.sqlite.SQLiteOpenHelper;
38 | import android.database.sqlite.SQLiteQueryBuilder;
39 | import android.net.Uri;
40 | import android.os.Handler;
41 | import android.util.Log;
42 |
43 | /**
44 | * The Class SmartHomeProvider.
45 | * ContentProvider for resources on the smart home server. Also has an SQLite local cache.
46 | */
47 |
48 | public class SmartHomeProvider extends ContentProvider {
49 |
50 |
51 |
52 | /** The updates enabled. */
53 | private static boolean updatesEnabled = false;
54 |
55 | /** The ui handler. */
56 | private static Handler uiHandler = null;
57 |
58 | /** The ui runnable. */
59 | private static Runnable uiRunnable = null;
60 |
61 | /** The exec. */
62 | public static ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(2);
63 |
64 | /** The smart home provicer. */
65 | public static SmartHomeProvider smartHomeProvicer;
66 | // Remove server initialization
67 | /** The Constant protocol. */
68 | public static final String protocol = "http://";
69 |
70 | /** The Constant host. */
71 | public static final String host = "embedded.cs.pub.ro/";
72 |
73 | /** The Constant serverURL. */
74 | public static final String serverURL = "si/zigbee/";
75 |
76 | /** The Constant status. */
77 | public static final String status = "status/";
78 |
79 | /** The Constant cluster. */
80 | public static final String cluster = "cluster/";
81 |
82 | /** The content resolver. */
83 | public static ContentResolver contentResolver;
84 |
85 | /** The scheduled task. */
86 | public static ScheduledFuture scheduledTask = null;
87 | //5 seconds update latest data
88 | /** The Constant SCHEDULE_LATEST_DATA_REFRESH_RATE. */
89 | public static final int SCHEDULE_LATEST_DATA_REFRESH_RATE = 5;
90 |
91 | /** The Constant baseUri. */
92 | public static final String baseUri = "http://embedded.cs.pub.ro/si/zigbee/";
93 |
94 |
95 | /** The Constant PROVIDER_NAME. */
96 | public static final String PROVIDER_NAME = "upb.smarthome.data.SmartHomeProvider";
97 |
98 | /** The Constant CONTENT_URI_DEVICES. */
99 | public static final Uri CONTENT_URI_DEVICES = Uri.parse("content://"+ PROVIDER_NAME + "/devices");
100 |
101 | /** The Constant CONTENT_URI_DEVICE_CLUSTERS. */
102 | public static final Uri CONTENT_URI_DEVICE_CLUSTERS = Uri.parse("content://"+ PROVIDER_NAME + "/device");
103 |
104 | /** The Constant CONTENT_URI_DEVICE_CLUSTERS_LAST. */
105 | public static final Uri CONTENT_URI_DEVICE_CLUSTERS_LAST = Uri.parse("content://"+ PROVIDER_NAME + "/device");
106 |
107 | /** The Constant CONTENT_URI_ALL. */
108 | public static final Uri CONTENT_URI_ALL = Uri.parse("content://"+ PROVIDER_NAME );
109 |
110 | /** The Constant DEBUG. */
111 | public static final String DEBUG = "debug_database";
112 | // column names
113 | /** The Constant _ID1. */
114 | public static final String _ID1 = "_id";
115 |
116 | /** The Constant NAME. */
117 | public static final String NAME = "name";
118 |
119 | /** The Constant LOCATION. */
120 | public static final String LOCATION = "location";
121 |
122 | /** The Constant _ID2. */
123 | public static final String _ID2 = "_id";
124 |
125 | /** The Constant IDSENSOR. */
126 | public static final String IDSENSOR = "idSenzor";
127 |
128 | /** The Constant VALUE. */
129 | public static final String VALUE = "value";
130 |
131 | /** The Constant _ID3. */
132 | public static final String _ID3 = "_id";
133 |
134 | /** The Constant SETTING. */
135 | public static final String SETTING = "setting";
136 |
137 | /** The Constant BatteryVoltage. */
138 | public static final String BatteryVoltage = "BatteryVoltage";
139 |
140 | /** The Constant TYPE. */
141 | public static final String TYPE = "type";
142 |
143 | /** The Constant ZCLVersion. */
144 | public static final String ZCLVersion = "ZCLVersion";
145 |
146 | /** The Constant PowerSource. */
147 | public static final String PowerSource = "PowerSource";
148 |
149 | /** The Constant LocationDescription. */
150 | public static final String LocationDescription = "LocationDescription";
151 |
152 | /** The Constant DeviceEnabled. */
153 | public static final String DeviceEnabled = "DeviceEnabled";
154 |
155 | /** The Constant Timestamp. */
156 | public static final String Timestamp = "timestamp";
157 |
158 | /** The Constant ExtAddress. */
159 | public static final String ExtAddress = "extAddress";
160 |
161 | /** The Constant Device_extAddress. */
162 | public static final String Device_extAddress = "device_extAddress";
163 |
164 | /** The Constant Endpoint. */
165 | public static final String Endpoint = "endpoint";
166 |
167 | /** The Constant MeasuredValue. */
168 | public static final String MeasuredValue = "MeasuredValue";
169 |
170 | /** The Constant LocalTemperature. */
171 | public static final String LocalTemperature = "LocalTemperature";
172 |
173 | /** The Constant MinHeat. */
174 | public static final String MinHeat = "MinHeatSetpointLimit";
175 |
176 | /** The Constant MaxHeat. */
177 | public static final String MaxHeat = "MaxHeatSetpointLimit";
178 |
179 | /** The Constant On_Off_Status. */
180 | public static final String On_Off_Status = "status";
181 |
182 | /** The Constant CLUSTER_ID. */
183 | public static final String CLUSTER_ID="clusterID";
184 | // routes
185 |
186 |
187 |
188 | /** The Constant DEVICES. */
189 | private static final int DEVICES = 0;
190 |
191 | /** The Constant DEVICE_CLUSTER_VALUES. */
192 | private static final int DEVICE_CLUSTER_VALUES = 1;
193 |
194 | /** The Constant DEVICE_CLUSTER_LAST_VALUE. */
195 | private static final int DEVICE_CLUSTER_LAST_VALUE =2;
196 |
197 | /** The Constant UPDATE_ON_OFF_SWITCH. */
198 | private static final int UPDATE_ON_OFF_SWITCH = 3;
199 |
200 | /** The Constant UPDATE_DEVICE_CLUSTER. */
201 | private static final int UPDATE_DEVICE_CLUSTER = 4;
202 |
203 | /** The Constant UPDATE_THERMOSTAT. */
204 | private static final int UPDATE_THERMOSTAT = 5;
205 |
206 | /** The Constant DEVICE_TYPE_ALL. */
207 | private static final int DEVICE_TYPE_ALL = 6;
208 |
209 | /** The Constant DEVICE_GET_LAST_10_VALUES. */
210 | private static final int DEVICE_GET_LAST_10_VALUES = 7;
211 |
212 | /** The Constant DEVICES_GET_CLUSTER_LAST. */
213 | private static final int DEVICES_GET_CLUSTER_LAST = 8;
214 |
215 | // UriMatcher
216 | /** The Constant uriMatcher. */
217 | private static final UriMatcher uriMatcher;
218 | static{
219 | uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
220 |
221 | uriMatcher.addURI(PROVIDER_NAME, "devices", DEVICES);
222 | uriMatcher.addURI(PROVIDER_NAME, "device/*/#/cluster/#", DEVICE_CLUSTER_VALUES);
223 | uriMatcher.addURI(PROVIDER_NAME,"device/*/#/cluster/#/last",DEVICE_CLUSTER_LAST_VALUE);
224 | uriMatcher.addURI(PROVIDER_NAME, "devices/type/#", DEVICE_TYPE_ALL);
225 | uriMatcher.addURI(PROVIDER_NAME,"device/*/#/switch/#",UPDATE_ON_OFF_SWITCH);
226 | uriMatcher.addURI(PROVIDER_NAME,"device/*/#/cluster/#/last_10_values",DEVICE_GET_LAST_10_VALUES);
227 | uriMatcher.addURI(PROVIDER_NAME,"device/*/#/thermostat",UPDATE_THERMOSTAT);
228 | uriMatcher.addURI(PROVIDER_NAME,"cluster/#",DEVICES_GET_CLUSTER_LAST);
229 | }
230 |
231 | //---for database use---
232 | /** The smarthome db. */
233 | public static SQLiteDatabase smarthomeDB = null;
234 |
235 | /** The Constant DATABASE_NAME. */
236 | private static final String DATABASE_NAME = "SmartHomeZigBee";
237 |
238 | /** The Constant DATABASE_TABLE_DEVICES. */
239 | private static final String DATABASE_TABLE_DEVICES = "devices";
240 |
241 | /** The Constant DATABASE_TABLE_BASIC_CLUSTER_STATUSES. */
242 | private static final String DATABASE_TABLE_BASIC_CLUSTER_STATUSES = "basic_clusters";
243 |
244 | /** The Constant DATABASE_TABLE_POWER_CLUSTER_STATUSES. */
245 | private static final String DATABASE_TABLE_POWER_CLUSTER_STATUSES = "power_clusters";
246 |
247 | /** The Constant DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES. */
248 | private static final String DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES = "temperature_clusters";
249 |
250 | /** The Constant DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES. */
251 | private static final String DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES = "on_off_clusters";
252 |
253 | /** The Constant DATABASE_TABLE_FLOW_CLUSTERS_STATUSES. */
254 | private static final String DATABASE_TABLE_FLOW_CLUSTERS_STATUSES = "flow_clusters";
255 |
256 | /** The Constant DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES. */
257 | private static final String DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES = "thermostat_clusters";
258 |
259 |
260 | /** The Constant DATABASE_VERSION. */
261 | private static final int DATABASE_VERSION = 1;
262 |
263 | /**
264 | * The Class DatabaseHelper.
265 | */
266 | private static class DatabaseHelper extends SQLiteOpenHelper
267 | {
268 |
269 | /**
270 | * Instantiates a new database helper.
271 | *
272 | * @param context the context
273 | */
274 | DatabaseHelper(Context context) {
275 | super(context, DATABASE_NAME, null, DATABASE_VERSION);
276 | }
277 |
278 | /* (non-Javadoc)
279 | * @see android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite.SQLiteDatabase)
280 | */
281 | @Override
282 | public void onCreate(SQLiteDatabase db)
283 | {
284 | }
285 |
286 | /* (non-Javadoc)
287 | * @see android.database.sqlite.SQLiteOpenHelper#onOpen(android.database.sqlite.SQLiteDatabase)
288 | */
289 | @Override
290 | public void onOpen(SQLiteDatabase db)
291 | {
292 | // Hack-ish initialisation. In a real case a smarter initialization is needed.
293 |
294 |
295 | //create tables
296 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_DEVICES );
297 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_DEVICES + " (_id" +
298 | " INTEGER PRIMARY KEY AUTOINCREMENT," + "extAddress text, endpoint INTEGER, type INTEGER);");
299 |
300 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_BASIC_CLUSTER_STATUSES );
301 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_BASIC_CLUSTER_STATUSES + " (_id" +
302 | " INTEGER PRIMARY KEY AUTOINCREMENT," + " device_extAddress text,endpoint INTEGER,timestamp INTEGER, ZCLVersion text, LocationDescription text, PowerSource text, DeviceEnabled text);");
303 |
304 |
305 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_FLOW_CLUSTERS_STATUSES );
306 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_FLOW_CLUSTERS_STATUSES + " (_id" +
307 | " INTEGER PRIMARY KEY AUTOINCREMENT," + "device_extAddress text, endpoint INTEGER,timestamp INTEGER,MeasuredValue text );");
308 |
309 |
310 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_POWER_CLUSTER_STATUSES );
311 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_POWER_CLUSTER_STATUSES + " (_id" +
312 | " INTEGER PRIMARY KEY AUTOINCREMENT," + "device_extAddress text, endpoint INTEGER,timestamp INTEGER,MainsVoltage text, MainsFrequency text, BatteryVoltage text );");
313 |
314 |
315 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES );
316 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES + " (_id" +
317 | " INTEGER PRIMARY KEY AUTOINCREMENT," + "device_extAddress text, endpoint INTEGER,timestamp INTEGER,status text );");
318 |
319 |
320 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES );
321 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES + " (_id" +
322 | " INTEGER PRIMARY KEY AUTOINCREMENT," + "device_extAddress text, endpoint INTEGER,timestamp INTEGER ,MeasuredValue text );");
323 |
324 |
325 | db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES );
326 | db.execSQL("CREATE TABLE " + DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES + " (_id" +
327 | " INTEGER PRIMARY KEY AUTOINCREMENT," + "device_extAddress text, endpoint INTEGER, timestamp INTEGER, MinHeatSetpointLimit text, MaxHeatSetpointLimit text, LocalTemperature text);");
328 |
329 | Log.d(DEBUG,"Tables created");
330 |
331 | Log.d(DEBUG,"Start parsing for initial data ");
332 |
333 |
334 | HashMap info = null;
335 | try{
336 |
337 | info = JSONParser.getInformationForDatabaseInitialization();
338 | }catch(Exception e){
339 | Log.d("debug_database","Could not parse all info " + e.getMessage());
340 | }
341 |
342 | Log.d("database","initial data from server");
343 |
344 | try {
345 |
346 |
347 | db.execSQL("INSERT INTO "+DATABASE_TABLE_DEVICES+" "+info.get("devices"));
348 | db.execSQL("INSERT INTO "+DATABASE_TABLE_BASIC_CLUSTER_STATUSES+" "+info.get("basic_clusters"));
349 | db.execSQL("INSERT INTO "+DATABASE_TABLE_POWER_CLUSTER_STATUSES+" "+info.get("power_clusters"));
350 | db.execSQL("INSERT INTO "+DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES+" "+info.get("on_off_clusters"));
351 | db.execSQL("INSERT INTO "+DATABASE_TABLE_FLOW_CLUSTERS_STATUSES+" "+info.get("flow_clusters"));
352 | db.execSQL("INSERT INTO "+DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES+" "+info.get("temperature_clusters"));
353 | db.execSQL("INSERT INTO "+DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES+" "+info.get("thermostat_clusters"));
354 |
355 |
356 | } catch (Exception e) {
357 | Log.d("debug_database","Could not create database " + e.getMessage());
358 | e.printStackTrace();
359 | }
360 |
361 |
362 | }
363 |
364 | /* (non-Javadoc)
365 | * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite.SQLiteDatabase, int, int)
366 | */
367 | @Override
368 | public void onUpgrade(SQLiteDatabase db, int oldVersion,
369 | int newVersion) {
370 | Log.w("Content provider database",
371 | "Upgrading database from version " +
372 | oldVersion + " to " + newVersion +
373 | ", which will destroy all old data");
374 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_BASIC_CLUSTER_STATUSES);
375 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_DEVICES);
376 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_FLOW_CLUSTERS_STATUSES);
377 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES);
378 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_POWER_CLUSTER_STATUSES);
379 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES);
380 | db.execSQL("DROP TABLE IF EXISTS " +DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES);
381 | onCreate(db);
382 | }
383 | }
384 |
385 |
386 |
387 |
388 | /* (non-Javadoc)
389 | * @see android.content.ContentProvider#getType(android.net.Uri)
390 | */
391 | @Override
392 | public String getType(Uri uri) {
393 | switch (uriMatcher.match(uri)){
394 | //--get all devices --
395 | case DEVICES:
396 | return PROVIDER_NAME + "/devices";
397 | case DEVICE_CLUSTER_VALUES:
398 | return PROVIDER_NAME + "/device/*/#/cluster/#";
399 | case DEVICE_CLUSTER_LAST_VALUE:
400 | return PROVIDER_NAME + "/device/*/#/cluster/#/last";
401 | case DEVICE_TYPE_ALL:
402 | return PROVIDER_NAME + "/devices/type/#";
403 | case DEVICE_GET_LAST_10_VALUES :
404 | return PROVIDER_NAME + "/device/*/#/cluster/#/last_10_values";
405 | case UPDATE_ON_OFF_SWITCH :
406 | return PROVIDER_NAME + "/device/*/#/switch/#";
407 | case UPDATE_THERMOSTAT :
408 | return PROVIDER_NAME + "/device/*/#/thermostat";
409 | case DEVICES_GET_CLUSTER_LAST :
410 | return PROVIDER_NAME + "/cluster/#";
411 |
412 |
413 | default:
414 | throw new IllegalArgumentException("Unsupported URI: " + uri);
415 | }
416 | }
417 |
418 | /* (non-Javadoc)
419 | * @see android.content.ContentProvider#onCreate()
420 | */
421 | @Override
422 | public boolean onCreate() {
423 | Context context = getContext();
424 | DatabaseHelper dbHelper = new DatabaseHelper(context);
425 | smarthomeDB = dbHelper.getWritableDatabase();
426 | smartHomeProvicer = this;
427 | return (smarthomeDB == null)? false:true;
428 | }
429 |
430 | /* (non-Javadoc)
431 | * @see android.content.ContentProvider#query(android.net.Uri, java.lang.String[], java.lang.String, java.lang.String[], java.lang.String)
432 | */
433 | @Override
434 | public Cursor query(Uri uri, String[] projection, String selection,
435 | String[] selectionArgs, String sortOrder) {
436 |
437 | SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
438 |
439 | switch (uriMatcher.match(uri)){
440 | case DEVICES:
441 | sqlBuilder.setTables(DATABASE_TABLE_DEVICES);
442 | if (sortOrder==null || sortOrder=="") sortOrder = null;
443 | break;
444 | case DEVICE_CLUSTER_VALUES:
445 |
446 | switch(Integer.parseInt(uri.getPathSegments().get(4))){
447 |
448 | case ClusterConstants.ID_BASIC_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_BASIC_CLUSTER_STATUSES);} break;
449 |
450 | case ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_FLOW_CLUSTERS_STATUSES);} break;
451 |
452 | case ClusterConstants.ID_ON_OFF_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES);} break;
453 |
454 | case ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_POWER_CLUSTER_STATUSES);} break;
455 |
456 | case ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES);} break;
457 |
458 | case ClusterConstants.ID_THERMOSTAT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES);} break;
459 |
460 | }
461 |
462 | sqlBuilder.appendWhere(" device_extAddress" + " = '" + uri.getPathSegments().get(1)+"'");
463 | sqlBuilder.appendWhere(" AND endpoint" + " = " + uri.getPathSegments().get(2));
464 | if (sortOrder==null || sortOrder=="") sortOrder = "timestamp";
465 | break;
466 | case DEVICE_CLUSTER_LAST_VALUE: {
467 |
468 | String table = "";
469 |
470 | switch(Integer.parseInt(uri.getPathSegments().get(4))){
471 |
472 | case ClusterConstants.ID_BASIC_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_BASIC_CLUSTER_STATUSES);
473 | table = DATABASE_TABLE_BASIC_CLUSTER_STATUSES;
474 | } break;
475 |
476 | case ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_FLOW_CLUSTERS_STATUSES);
477 | table = DATABASE_TABLE_FLOW_CLUSTERS_STATUSES;
478 | } break;
479 |
480 | case ClusterConstants.ID_ON_OFF_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES);
481 | table = DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES;
482 | } break;
483 |
484 | case ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_POWER_CLUSTER_STATUSES);
485 | table = DATABASE_TABLE_POWER_CLUSTER_STATUSES;
486 | } break;
487 |
488 | case ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES);
489 | table = DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES;
490 | } break;
491 |
492 | case ClusterConstants.ID_THERMOSTAT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES);
493 | table = DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES;
494 | } break;
495 |
496 | }
497 |
498 | sqlBuilder.appendWhere("device_extAddress" + " = '" + uri.getPathSegments().get(1)+"'");
499 | sqlBuilder.appendWhere(" AND endpoint" + " = '" + uri.getPathSegments().get(2)+"'");
500 |
501 | Log.d("debug_databse","SQL " +uri.getPathSegments().get(1)+" "+ uri.getPathSegments().get(2) + " " + table) ;
502 |
503 | //sort and return latest limit
504 | Cursor c = sqlBuilder.query(smarthomeDB, projection, selection, selectionArgs, null,null, "timestamp DESC");
505 |
506 |
507 |
508 | //---register to watch a content URI for changes---
509 | c.setNotificationUri(getContext().getContentResolver(), uri);
510 | return c;
511 | }
512 | case DEVICE_GET_LAST_10_VALUES : {
513 |
514 | String table = "";
515 |
516 | String uriGet = baseUri + status + "device/" + uri.getPathSegments().get(1) + "/"
517 | + uri.getPathSegments().get(2)+"/cluster/"+uri.getPathSegments().get(4)+".json";
518 |
519 | //recuperare si inserare daca nu exista in baza de date a ultimelor valori de pe server
520 |
521 | try{
522 | processJSONSqliteResponse(uriGet);
523 | }
524 | catch(Exception e){
525 | Log.d("latest_values","Exception in retrieving latest values :" + e.getMessage() );
526 | }
527 | switch(Integer.parseInt(uri.getPathSegments().get(4))){
528 |
529 | case ClusterConstants.ID_BASIC_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_BASIC_CLUSTER_STATUSES);
530 | table = DATABASE_TABLE_BASIC_CLUSTER_STATUSES;
531 | } break;
532 | case ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_FLOW_CLUSTERS_STATUSES);
533 | table = DATABASE_TABLE_FLOW_CLUSTERS_STATUSES;
534 | } break;
535 | case ClusterConstants.ID_ON_OFF_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES);
536 | table = DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES;
537 | } break;
538 | case ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_POWER_CLUSTER_STATUSES);
539 | table = DATABASE_TABLE_POWER_CLUSTER_STATUSES;
540 | } break;
541 | case ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES);
542 | table = DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES;
543 | } break;
544 | case ClusterConstants.ID_THERMOSTAT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES);
545 | table = DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES;
546 | } break;
547 |
548 | }
549 |
550 | sqlBuilder.appendWhere("device_extAddress" + " = '" + uri.getPathSegments().get(1)+"'");
551 | sqlBuilder.appendWhere(" AND endpoint" + " = '" + uri.getPathSegments().get(2)+"'");
552 |
553 | Log.d("debug_databse","SQL " +uri.getPathSegments().get(1)+" "+ uri.getPathSegments().get(2) + " " + table) ;
554 |
555 | //sort and return latest limit
556 | Cursor c = sqlBuilder.query(smarthomeDB, projection, selection, selectionArgs, null,null, "timestamp","10");
557 |
558 | //---register to watch a content URI for changes---
559 | c.setNotificationUri(getContext().getContentResolver(), uri);
560 | return c;
561 | }
562 |
563 | case DEVICE_TYPE_ALL : {
564 | sqlBuilder.setTables(DATABASE_TABLE_DEVICES);
565 | sqlBuilder.appendWhere("type" +" = "+ uri.getPathSegments().get(2));
566 | }
567 | break;
568 | case DEVICES_GET_CLUSTER_LAST : {
569 |
570 | String table;
571 |
572 | switch(Integer.parseInt(uri.getPathSegments().get(1))){
573 |
574 | case ClusterConstants.ID_BASIC_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_BASIC_CLUSTER_STATUSES);
575 | table = DATABASE_TABLE_BASIC_CLUSTER_STATUSES;
576 | } break;
577 | case ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_FLOW_CLUSTERS_STATUSES);
578 | table = DATABASE_TABLE_FLOW_CLUSTERS_STATUSES;
579 | } break;
580 | case ClusterConstants.ID_ON_OFF_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES);
581 | table = DATABASE_TABLE_ON_OFF_CLUSTERS_STATUSES;
582 | } break;
583 | case ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_POWER_CLUSTER_STATUSES);
584 | table = DATABASE_TABLE_POWER_CLUSTER_STATUSES;
585 | } break;
586 | case ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES);
587 | table = DATABASE_TABLE_TEMPERATURE_CLUSTER_STATUSES;
588 | } break;
589 | case ClusterConstants.ID_THERMOSTAT_CLUSTER : {sqlBuilder.setTables(DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES);
590 | table = DATABASE_TABLE_THERMOSTAT_CLUSTER_STATUSES;
591 | } break;
592 |
593 | }
594 |
595 | }
596 | break;
597 |
598 | default: throw new SQLException("Failed to process " + uri);
599 | }
600 |
601 | Cursor c = sqlBuilder.query(smarthomeDB, projection, selection, selectionArgs, null, null, sortOrder);
602 |
603 | //---register to watch a content URI for changes---
604 | c.setNotificationUri(getContext().getContentResolver(), uri);
605 | return c;
606 | }
607 |
608 | /* (non-Javadoc)
609 | * @see android.content.ContentProvider#update(android.net.Uri, android.content.ContentValues, java.lang.String, java.lang.String[])
610 | */
611 | @Override
612 | public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
613 | {
614 | int changed = 0;
615 |
616 | switch (uriMatcher.match(uri)){
617 | case UPDATE_DEVICE_CLUSTER:{
618 | String newValue = values.getAsString(SETTING);
619 | String serverUri = baseUri + status + "device/" + uri.getPathSegments().get(1)+ "/" + uri.getPathSegments().get(2)+"/cluster/"+uri.getPathSegments().get(4);
620 |
621 | try {
622 | String response = JSONParser.confirmSetting(serverUri);
623 | if (response.equalsIgnoreCase(newValue)) {
624 | // setarea a fost schimbata pe server - o schimbam si local
625 | // changed = smarthomeDB.update(DATABASE_TABLE_ACTUATORS, values, "_id="+uri.getPathSegments().get(1), selectionArgs);
626 |
627 | }
628 | } catch (Exception e) {
629 | e.printStackTrace();
630 | }
631 | }
632 | break;
633 |
634 | case UPDATE_ON_OFF_SWITCH:
635 | {
636 | int value = values.getAsInteger("status");
637 | String serverUri = baseUri + "cmd.json";
638 | Log.d("data","Update switch " + value);
639 |
640 | ArrayList pairs = new ArrayList();
641 |
642 | pairs.add(new BasicNameValuePair("id", ""));
643 | pairs.add(new BasicNameValuePair("cmd[extAddress]", uri.getPathSegments().get(1) ));
644 | pairs.add(new BasicNameValuePair("cmd[endpoint]", uri.getPathSegments().get(2)));
645 | pairs.add(new BasicNameValuePair("cmd[clusterID]", ClusterConstants.ID_ON_OFF_CLUSTER + ""));
646 |
647 | if(value == 0){
648 | pairs.add(new BasicNameValuePair("cmd[attributes]", "{0000:00}"));
649 | Log.d("debug","OFF cmd");
650 | }else{
651 | Log.d("debug","ON cmd");
652 | pairs.add(new BasicNameValuePair("cmd[attributes]", "{0000:01}"));
653 |
654 | }
655 | pairs.add(new BasicNameValuePair("cmd[timestamp]", System.currentTimeMillis()/1000 +""));
656 |
657 | try {
658 |
659 | JSONObject resp = RestComm.restPost(serverUri, pairs);
660 |
661 | } catch (Exception e) {
662 | e.printStackTrace();
663 | }
664 | }
665 | break;
666 |
667 |
668 | case UPDATE_THERMOSTAT : {
669 | int min = (int)(values.getAsFloat("minValue") * 100f);
670 | int max = (int)(values.getAsFloat("maxValue") * 100f);
671 |
672 | String serverUri = baseUri + "cmd.json";
673 | Log.d("thermostat","Send data : " + min + " max :" + max );
674 |
675 | ArrayList pairs = new ArrayList();
676 |
677 | pairs.add(new BasicNameValuePair("id", ""));
678 | pairs.add(new BasicNameValuePair("cmd[extAddress]", uri.getPathSegments().get(1) ));
679 | pairs.add(new BasicNameValuePair("cmd[endpoint]", uri.getPathSegments().get(2)));
680 | pairs.add(new BasicNameValuePair("cmd[clusterID]", ClusterConstants.ID_THERMOSTAT_CLUSTER + ""));
681 |
682 |
683 |
684 | pairs.add(new BasicNameValuePair("cmd[attributes]", "[{0015:"+Integer.toHexString(min)+"},{0016:"+Integer.toHexString(max)+"}]"));
685 | Log.d("data","Update switch [{0015:0"+Integer.toHexString(min)+"},{0016:"+Integer.toHexString(max)+"}]");
686 |
687 |
688 | pairs.add(new BasicNameValuePair("cmd[timestamp]", System.currentTimeMillis()/1000 +""));
689 |
690 | try {
691 |
692 | JSONObject resp = RestComm.restPost(serverUri, pairs);
693 |
694 | } catch (Exception e) {
695 | e.printStackTrace();
696 | }
697 |
698 | }
699 | break;
700 |
701 | default: throw new SQLException("Failed to process " + uri);
702 | }
703 | return changed;
704 | }
705 |
706 | /* (non-Javadoc)
707 | * @see android.content.ContentProvider#insert(android.net.Uri, android.content.ContentValues)
708 | */
709 | @Override
710 | public Uri insert(Uri uri, ContentValues values) {
711 | // we will not insert new sensors or actuators
712 | return null;
713 | }
714 |
715 | /* (non-Javadoc)
716 | * @see android.content.ContentProvider#delete(android.net.Uri, java.lang.String, java.lang.String[])
717 | */
718 | @Override
719 | public int delete(Uri arg0, String arg1, String[] arg2) {
720 | // we will not delete sensors or actuators
721 | return 0;
722 | }
723 |
724 | /**
725 | * Update regular from server.
726 | *
727 | * @return true, if successful
728 | */
729 | public boolean updateRegularFromServer(){
730 |
731 |
732 | if(smarthomeDB == null){
733 | Log.d("database","database is null");
734 | }
735 |
736 | scheduledTask = exec.scheduleAtFixedRate(new Runnable() {
737 |
738 | @Override
739 | public void run() {
740 | // TODO Auto-generated method stub
741 | Log.d(DEBUG,"Start parsing");
742 | //fetch data for tables
743 |
744 |
745 | if(smarthomeDB == null)
746 | Log.d("debug","SmarthomeDB is null");
747 | boolean isUpdate = false;
748 |
749 | try{
750 | String uri = SmartHomeProvider.baseUri + "status/timestamp/latest.json";
751 | isUpdate = processJSONSqliteResponse(uri);
752 | }
753 | catch(Exception e){
754 | Log.d("debug","Exception in parsing data for update " + e.getMessage());
755 | }
756 |
757 | if(uiHandler != null && uiRunnable != null){
758 | if(isUpdate){
759 | uiHandler.post(uiRunnable);
760 | Log.d("database","Post refresh callback");
761 | }
762 | else
763 | Log.d("updater","Nothing to update");
764 | }
765 | else
766 | Log.d("database","Can't post refresh callbacks");
767 |
768 | }
769 | }, SCHEDULE_LATEST_DATA_REFRESH_RATE, SCHEDULE_LATEST_DATA_REFRESH_RATE, TimeUnit.SECONDS);
770 |
771 | //set updates enabled
772 | updatesEnabled = true;
773 |
774 |
775 | return true;
776 |
777 |
778 | }
779 |
780 | /**
781 | * Checks if is updates enabled.
782 | *
783 | * @return true, if is updates enabled
784 | */
785 | public boolean isUpdatesEnabled(){
786 |
787 | if(scheduledTask != null)
788 | return true;
789 |
790 | return false;
791 | }
792 |
793 |
794 | /**
795 | * Stop regular updates.
796 | */
797 | public void stopRegularUpdates(){
798 | if(!scheduledTask.isCancelled())
799 | scheduledTask.cancel(false);
800 |
801 | updatesEnabled = false;
802 | scheduledTask = null;
803 |
804 | }
805 |
806 | /**
807 | * Sets the ui update.
808 | *
809 | * @param handler the handler
810 | * @param run the run
811 | */
812 | public void setUiUpdate(Handler handler, Runnable run){
813 |
814 | this.uiHandler = handler;
815 | this.uiRunnable = run;
816 |
817 | }
818 |
819 | /**
820 | * Clear ui update.
821 | */
822 | public void clearUiUpdate(){
823 |
824 | this.uiHandler = null;
825 | this.uiRunnable = null;
826 | }
827 |
828 | /**
829 | * Checks if is ui update enabled.
830 | *
831 | * @return true, if is ui update enabled
832 | */
833 | public boolean isUiUpdateEnabled(){
834 |
835 | if(this.uiHandler == null || this.uiRunnable == null)
836 | return false;
837 |
838 | return true;
839 | }
840 |
841 | //for an update parse the answer and verify if it is in database, if not , add it to the database
842 | /**
843 | * Process json sqlite response.
844 | *
845 | * @param uri the uri
846 | * @return true, if successful
847 | * @throws JSONException the jSON exception
848 | * @throws ConnectTimeoutException the connect timeout exception
849 | * @throws ClientProtocolException the client protocol exception
850 | */
851 | private boolean processJSONSqliteResponse(String uri) throws JSONException, ConnectTimeoutException,ClientProtocolException{
852 |
853 | boolean isUpdate = false;
854 |
855 |
856 |
857 | JSONObject responseJson = RestComm.restGet(uri);
858 | JSONArray result = responseJson.getJSONArray("statusSet");
859 |
860 | for(int i=0;i Exception
917 |
918 | if(att.equals("1")){
919 | //server error , not complaint with ZigBee standard
920 | attributes.put(ClusterConstants.ON_OFF,"00" );
921 | Log.d("attribute_error","attibute 1");
922 | }else
923 | {
924 | Log.d("attribute_error","attibute 2");
925 | while(tock.hasMoreElements()){
926 |
927 | String key = tock.nextToken(":[]{}, ");
928 | String value = tock.nextToken(":[]{}, ");
929 | attributes.put(key, value);
930 | }
931 | }
932 | //Log.d("debug_parser","New Attributes" + attributes.toString());
933 | ContentValues a = new ContentValues();
934 | a.put(Device_extAddress, extAddress);
935 | a.put(Endpoint, endpoint);
936 | a.put("_id", id);
937 | a.put(Timestamp, timestamp);
938 |
939 | Log.d("database","UPDATE timestamp "+timestamp);
940 |
941 | switch(clusterID){
942 |
943 | case ClusterConstants.ID_BASIC_CLUSTER : {
944 |
945 |
946 | String location = attributes.getString(ClusterConstants.BASIC_LocationDescription);
947 | String zclVersion = attributes.getString(ClusterConstants.BASIC_ZCLVersion);
948 | String deviceEnabled = attributes.getString(ClusterConstants.BASIC_DeviceEnabled);
949 | String powerSource = attributes.getString(ClusterConstants.BASIC_PowerSource);
950 | a.put(LocationDescription,location);
951 | a.put(ZCLVersion, zclVersion);
952 | a.put(DeviceEnabled, deviceEnabled);
953 | a.put(PowerSource,powerSource);
954 |
955 |
956 | smarthomeDB.insert(table, null, a);
957 |
958 |
959 |
960 | }break;
961 |
962 | case ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER : {
963 |
964 |
965 | String mainsVoltageH;
966 | String mainsFrequencyH;
967 | String batteryVoltageH;
968 | Double mainsVoltage=0d;
969 | Double mainsFrequency=0d;
970 | Double batteryVoltage=0d;
971 |
972 | if(attributes.opt(ClusterConstants.POWER_MainsVoltage) != null){
973 | mainsVoltageH = attributes.getString(ClusterConstants.POWER_MainsVoltage);
974 | mainsVoltage = Long.parseLong(mainsVoltageH, 16) * 100d;
975 | }else
976 | mainsVoltageH = "";
977 |
978 | if(attributes.opt(ClusterConstants.POWER_MainsFrequency) != null){
979 | mainsFrequencyH = attributes.getString(ClusterConstants.POWER_MainsFrequency);
980 | mainsFrequency = Long.parseLong(mainsFrequencyH, 16) *1d;
981 | }else
982 | mainsFrequencyH = "";
983 |
984 | if(attributes.opt(ClusterConstants.POWER_BatteryVoltage) != null){
985 | batteryVoltageH = attributes.getString(ClusterConstants.POWER_BatteryVoltage);
986 | batteryVoltage = Long.parseLong(batteryVoltageH, 16) *100d;
987 | }else
988 | batteryVoltageH = "";
989 |
990 | a.put("mainsVoltage",mainsVoltage);
991 | a.put("mainsFrequency", mainsFrequency);
992 | a.put("batteryVoltage", batteryVoltage);
993 | smarthomeDB.insert(table, null, a);
994 |
995 | }break;
996 |
997 | case ClusterConstants.ID_ON_OFF_CLUSTER : {
998 |
999 |
1000 |
1001 | String st = attributes.getString(ClusterConstants.ON_OFF);
1002 |
1003 | String stat = Long.parseLong(st)+"";
1004 | a.put(On_Off_Status, stat);
1005 | long res = smarthomeDB.insertOrThrow(table, null, a);
1006 |
1007 | Log.d("insert","Inserted " + res);
1008 |
1009 | } break;
1010 |
1011 | case ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER : {
1012 |
1013 | String tempStringHex = attributes.getString(ClusterConstants.TEMPERATURE_MeasuredValue);
1014 | Double temp = Long.parseLong(tempStringHex, 16)/100d;
1015 |
1016 | a.put(MeasuredValue, temp);
1017 | Log.d("alues","Measured value " + temp);
1018 | smarthomeDB.insert(table, null, a);
1019 |
1020 |
1021 | } break;
1022 |
1023 | case ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER : {
1024 |
1025 |
1026 | String flowStringHex = attributes.getString(ClusterConstants.FLOW_MeasuredValue);
1027 | Double flow = Long.parseLong(flowStringHex, 16)/100d;
1028 | a.put(MeasuredValue, flow);
1029 | smarthomeDB.insert(table, null, a);
1030 |
1031 |
1032 |
1033 | } break;
1034 |
1035 | case ClusterConstants.ID_THERMOSTAT_CLUSTER : {
1036 |
1037 |
1038 | Double localTemp;
1039 | String localTempH;
1040 |
1041 | if(attributes.opt(ClusterConstants.THERMOSTAT_LocalTemperature) != null){
1042 | localTempH = attributes.getString(ClusterConstants.THERMOSTAT_LocalTemperature);
1043 |
1044 | localTemp = Long.parseLong(localTempH, 16) / 100d;
1045 |
1046 |
1047 | }
1048 | else
1049 | localTemp = -1D;
1050 |
1051 | String minH = attributes.getString(ClusterConstants.THERMOSTAT_MinHeatSetpointLimit);
1052 | String maxH = attributes.getString(ClusterConstants.THERMOSTAT_MaxHeatSetpointLimit);
1053 |
1054 |
1055 | Double min = Long.parseLong(minH, 16)/100d;
1056 | Double max = Long.parseLong(maxH, 16)/100d;
1057 | a.put(MinHeat, min);
1058 | a.put(MaxHeat, max);
1059 | a.put(LocalTemperature, localTemp);
1060 | smarthomeDB.insert(table, null, a);
1061 | Log.d("thermostat","Temperature " + minH +" "+ min + " " + maxH + " " + max );
1062 |
1063 |
1064 | } break;
1065 |
1066 | }
1067 | }
1068 | else
1069 | cur.close();
1070 | }
1071 |
1072 | return isUpdate;
1073 | }
1074 |
1075 |
1076 | }
1077 |
--------------------------------------------------------------------------------
/src/upb/smarthome/devices/DeviceConstants.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.devices;
8 |
9 | /**
10 | * The Class DeviceConstants.
11 | */
12 | public class DeviceConstants {
13 |
14 | /** The Constant TYPE_TEMPERATURE_SENSOR. */
15 | public static final int TYPE_TEMPERATURE_SENSOR = 1;
16 |
17 | /** The Constant TYPE_ON_OFF. */
18 | public static final int TYPE_ON_OFF = 2;
19 |
20 | /** The Constant TYPE_FLOW_METER. */
21 | public static final int TYPE_FLOW_METER = 3;
22 |
23 | /** The Constant TYPE_THERMOSTAT. */
24 | public static final int TYPE_THERMOSTAT = 4;
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/src/upb/smarthome/devices/FlowSensor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.devices;
8 |
9 | import upb.smarthome.clusters.FlowCluster;
10 |
11 | /**
12 | * The Class FlowSensor.
13 | */
14 | public class FlowSensor extends LogicalDevice{
15 |
16 |
17 | /** The flow cluster. */
18 | public FlowCluster flowCluster;
19 |
20 | /**
21 | * Instantiates a new flow sensor.
22 | *
23 | * @param extAddString the ext add string
24 | * @param endPoint the end point
25 | * @param type the type
26 | */
27 | public FlowSensor(String extAddString, int endPoint, int type) {
28 | super(extAddString, endPoint, type);
29 | // TODO Auto-generated constructor stub
30 |
31 | flowCluster = new FlowCluster();
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/upb/smarthome/devices/LogicalDevice.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.devices;
8 |
9 | import upb.smarthome.clusters.BasicCluster;
10 | import upb.smarthome.clusters.PowerCluster;
11 |
12 | /**
13 | * The Class LogicalDevice.
14 | */
15 | public class LogicalDevice {
16 |
17 | /** The ext address. */
18 | public String extAddress;
19 |
20 | /** The end point. */
21 | public int endPoint = -1;
22 |
23 | /** The type. */
24 | public int type;
25 |
26 | /** The unit. */
27 | public String unit;
28 |
29 | //basic clusters
30 | /** The basic cluster. */
31 | private BasicCluster basicCluster;
32 |
33 | /** The power cluster. */
34 | private PowerCluster powerCluster;
35 |
36 | /** The position. */
37 | public String position ;
38 |
39 | /**
40 | * Instantiates a new logical device.
41 | *
42 | * @param extAddress the ext address
43 | * @param endPoint the end point
44 | * @param type the type
45 | */
46 | public LogicalDevice(String extAddress, int endPoint, int type){
47 |
48 | this.extAddress = extAddress;
49 | this.endPoint = endPoint;
50 | this.type = type;
51 |
52 | basicCluster = new BasicCluster();
53 | powerCluster = new PowerCluster();
54 |
55 | }
56 |
57 | /**
58 | * Gets the unit.
59 | *
60 | * @return the unit
61 | */
62 | public String getUnit(){
63 | return unit;
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/upb/smarthome/devices/OnOffActuator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.devices;
8 |
9 | import upb.smarthome.clusters.OnOffCluster;
10 |
11 | public class OnOffActuator extends LogicalDevice{
12 |
13 | public OnOffCluster onOffcluster;
14 |
15 | /**
16 | * Instantiates a new on off actuator.
17 | *
18 | * @param extAddString the ext add string
19 | * @param endPoint the end point
20 | * @param type the type
21 | */
22 | public OnOffActuator(String extAddString, int endPoint, int type) {
23 | super(extAddString, endPoint, type);
24 | // TODO Auto-generated constructor stub
25 |
26 | onOffcluster = new OnOffCluster();
27 | }
28 |
29 | }
30 |
--------------------------------------------------------------------------------
/src/upb/smarthome/devices/TemperatureSensor.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.devices;
8 |
9 | import upb.smarthome.clusters.TemperatureCluster;
10 |
11 | /**
12 | * The Class TemperatureSensor.
13 | */
14 | public class TemperatureSensor extends LogicalDevice{
15 |
16 |
17 | /** The temp cluster. */
18 | public TemperatureCluster tempCluster;
19 |
20 | /**
21 | * Instantiates a new temperature sensor.
22 | *
23 | * @param extAddString the ext add string
24 | * @param endPoint the end point
25 | * @param type the type
26 | */
27 | public TemperatureSensor(String extAddString, int endPoint, int type) {
28 | super(extAddString, endPoint, type);
29 | // TODO Auto-generated constructor stub
30 |
31 | tempCluster = new TemperatureCluster();
32 | }
33 |
34 |
35 | }
36 |
--------------------------------------------------------------------------------
/src/upb/smarthome/devices/ThermostatActuator.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 | package upb.smarthome.devices;
8 |
9 | import upb.smarthome.clusters.ThermostatCluster;
10 |
11 | /**
12 | * The Class ThermostatActuator.
13 | */
14 | public class ThermostatActuator extends LogicalDevice{
15 |
16 |
17 | /** The thermostat cluster. */
18 | public ThermostatCluster thermostatCluster;
19 |
20 | /**
21 | * Instantiates a new thermostat actuator.
22 | *
23 | * @param extAddString the ext add string
24 | * @param endPoint the end point
25 | * @param type the type
26 | */
27 | public ThermostatActuator(String extAddString, int endPoint, int type) {
28 | super(extAddString, endPoint, type);
29 | // TODO Auto-generated constructor stub
30 |
31 | thermostatCluster = new ThermostatCluster();
32 | }
33 |
34 | }
35 |
--------------------------------------------------------------------------------
/src/upb/smarthome/restcomm/JSONParser.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 |
8 | package upb.smarthome.restcomm;
9 |
10 |
11 | import java.util.ArrayList;
12 | import java.util.Collection;
13 | import java.util.HashMap;
14 | import java.util.Iterator;
15 | import java.util.StringTokenizer;
16 |
17 | import org.apache.http.client.ClientProtocolException;
18 | import org.apache.http.conn.ConnectTimeoutException;
19 | import org.json.JSONArray;
20 | import org.json.JSONException;
21 | import org.json.JSONObject;
22 |
23 | import upb.smarthome.clusters.ClusterConstants;
24 | import upb.smarthome.data.SmartHomeProvider;
25 | import upb.smarthome.devices.DeviceConstants;
26 | import upb.smarthome.devices.LogicalDevice;
27 | import android.util.Log;
28 |
29 | /**
30 | * The Class JSONParser.
31 | * Used to parse JSON content
32 | */
33 | public class JSONParser {
34 |
35 |
36 | // extract a device ID from a JSON description
37 | /**
38 | * Extract id.
39 | *
40 | * @param json the json
41 | * @return the int
42 | * @throws JSONException the jSON exception
43 | */
44 | public static int extractId(JSONObject json) throws JSONException {
45 | return json.getInt("id");
46 | }
47 | // extract extAddress
48 | /**
49 | * Extract ext address.
50 | *
51 | * @param json the json
52 | * @return the string
53 | * @throws JSONException the jSON exception
54 | */
55 | public static String extractExtAddress(JSONObject json ) throws JSONException {
56 | return json.getString("extAddress");
57 | }
58 | //extract endPoint
59 | /**
60 | * Extract end point.
61 | *
62 | * @param json the json
63 | * @return the int
64 | * @throws JSONException the jSON exception
65 | */
66 | public static int extractEndPoint(JSONObject json ) throws JSONException {
67 | return json.getInt("endpoint");
68 | }
69 | //extract CLusterID
70 | /**
71 | * Extract cluster id.
72 | *
73 | * @param json the json
74 | * @return the int
75 | * @throws JSONException the jSON exception
76 | */
77 | public static int extractClusterID(JSONObject json ) throws JSONException {
78 | return json.getInt("clusterID");
79 | }
80 | //extract Time stamp
81 | /**
82 | * Extract timestamp.
83 | *
84 | * @param json the json
85 | * @return the long
86 | * @throws JSONException the jSON exception
87 | */
88 | public static long extractTimestamp(JSONObject json ) throws JSONException {
89 | return json.getLong("timestamp");
90 | }
91 |
92 | //get statusSet from a device
93 | /**
94 | * Extract status set.
95 | *
96 | * @param json the json
97 | * @return the jSON object
98 | * @throws JSONException the jSON exception
99 | */
100 | public static JSONObject extractStatusSet(JSONObject json ) throws JSONException {
101 | return json.getJSONObject("statusSet");
102 | }
103 |
104 | //extract a JSONArray attribute list
105 | /**
106 | * Extract attributes.
107 | *
108 | * @param json the json
109 | * @return the jSON array
110 | * @throws JSONException the jSON exception
111 | */
112 | public static JSONArray extractAttributes(JSONObject json) throws JSONException {
113 | return json.getJSONArray("attributes");
114 | }
115 |
116 |
117 | // change an actuator setting and confirm
118 | /**
119 | * Confirm setting.
120 | *
121 | * @param URI the uRI
122 | * @return the string
123 | * @throws JSONException the jSON exception
124 | * @throws ClientProtocolException the client protocol exception
125 | * @throws ConnectTimeoutException the connect timeout exception
126 | */
127 | public static String confirmSetting(String URI) throws JSONException, ClientProtocolException, ConnectTimeoutException {
128 | JSONObject response = RestComm.restPut(URI);
129 | if (response != null) {
130 | return response.getJSONObject("actuator").getString("setting");
131 | }
132 | return null;
133 | }
134 |
135 | //get string to insert into database
136 | /**
137 | * Gets the information for database initialization.
138 | *
139 | * @return the information for database initialization
140 | * @throws JSONException the jSON exception
141 | * @throws ClientProtocolException the client protocol exception
142 | * @throws ConnectTimeoutException the connect timeout exception
143 | */
144 | public static HashMap getInformationForDatabaseInitialization()throws JSONException, ClientProtocolException, ConnectTimeoutException {
145 |
146 | HashMap databaseInitialize = new HashMap();
147 |
148 | String devicesS = "";
149 | String basic_clusters = "";
150 | String power_clusters = "";
151 | String on_off_clusters = "";
152 | String temperature_clusters = "";
153 | String flow_clusters = "";
154 | String thermostat_clusters = "";
155 |
156 | //devices so we can determine very fast if we have a device based on its extAddress and endpoint (they will act as a key for the HashMap)
157 | HashMap devicesL = new HashMap();
158 |
159 |
160 | //this retrieves all statuses from all clusters on all servers, do it only once to initialize database
161 | //it is very expensive on CPU
162 |
163 | String uri = SmartHomeProvider.baseUri + "status/timestamp/latest.json";
164 |
165 | JSONObject responseJson = RestComm.restGet(uri);
166 | JSONArray result = responseJson.getJSONArray("statusSet");
167 |
168 | for(int i=0;i Exception so use a tockenizer
193 | //this is not JSON standard => speak with professor and assistants for bug fix on server
194 | while(tock.hasMoreElements()){
195 |
196 | String key = tock.nextToken(":[]{}, ");
197 | String value = tock.nextToken(":[]{}, ");
198 |
199 | attributes.put(key, value);
200 | }
201 | }
202 | //Log.d("debug_parser","New Attributes" + attributes.toString());
203 | switch(clusterID){
204 |
205 | case ClusterConstants.ID_BASIC_CLUSTER : {
206 |
207 |
208 | String location = attributes.getString(ClusterConstants.BASIC_LocationDescription);
209 | String zclVersion = attributes.getString(ClusterConstants.BASIC_ZCLVersion);
210 | String deviceEnabled = attributes.getString(ClusterConstants.BASIC_DeviceEnabled);
211 | String powerSource = attributes.getString(ClusterConstants.BASIC_PowerSource);
212 |
213 |
214 |
215 |
216 | if(basic_clusters == "")
217 | basic_clusters += "SELECT "+id+" AS '_id', '"
218 | +extAddress+ "' AS 'device_extAddress', "
219 | +endpoint + " AS 'endpoint' ,"
220 | +timestamp+ " AS 'timestamp', '"
221 | +zclVersion+ "' AS 'ZCLVersion', '"
222 | +location+ "' AS 'LocationDescription', '"
223 | +powerSource+ "' AS 'PowerSource', '"
224 | +deviceEnabled+ "' AS 'DeviceEnabled' ";
225 | else
226 | basic_clusters += "UNION SELECT "+id+" AS '_id', '"
227 | +extAddress+ "' , "
228 | +endpoint + " AS 'endpoint' ,"
229 | +timestamp+ " , '"
230 | +zclVersion+ "' , '"
231 | +location+ "' , '"
232 | +powerSource+ "' , '"
233 | +deviceEnabled+ "' ";
234 |
235 | }break;
236 |
237 | case ClusterConstants.ID_POWER_CONFIGURATION_CLUSTER : {
238 |
239 | String mainsVoltageH;
240 | String mainsFrequencyH;
241 | String batteryVoltageH;
242 | Double mainsVoltage=0d;
243 | Double mainsFrequency=0d;
244 | Double batteryVoltage=0d;
245 |
246 | if(attributes.opt(ClusterConstants.POWER_MainsVoltage) != null){
247 | mainsVoltageH = attributes.getString(ClusterConstants.POWER_MainsVoltage);
248 | mainsVoltage = Long.parseLong(mainsVoltageH, 16) * 100d;
249 | }else
250 | mainsVoltageH = "";
251 |
252 | if(attributes.opt(ClusterConstants.POWER_MainsFrequency) != null){
253 | mainsFrequencyH = attributes.getString(ClusterConstants.POWER_MainsFrequency);
254 | mainsFrequency = Long.parseLong(mainsFrequencyH, 16) *1d;
255 | }else
256 | mainsFrequencyH = "";
257 |
258 | if(attributes.opt(ClusterConstants.POWER_BatteryVoltage) != null){
259 | batteryVoltageH = attributes.getString(ClusterConstants.POWER_BatteryVoltage);
260 | batteryVoltage = Long.parseLong(batteryVoltageH, 16) *100d;
261 | }else
262 | batteryVoltageH = "";
263 |
264 |
265 |
266 | if(power_clusters == "")
267 | power_clusters += "SELECT "+id+" AS '_id', '"
268 | +extAddress+ "' AS 'device_extAddress', "
269 | +endpoint + " AS 'endpoint' ,"
270 | +timestamp+ " AS 'timestamp', '"
271 | +mainsVoltage+ "' AS 'MainsVoltage', '"
272 | +mainsFrequency+ "' AS 'MainsFrequency', '"
273 | +batteryVoltage+ "' AS 'BatteryVoltage' ";
274 | else
275 | power_clusters += "UNION SELECT "+id+" AS '_id', '"
276 | +extAddress+ "' , "
277 | +endpoint + " AS 'endpoint' ,"
278 | +timestamp+ " , '"
279 | +mainsVoltage+ "' , '"
280 | +mainsFrequency+ "' , '"
281 | +batteryVoltage+ " '";
282 |
283 |
284 | }break;
285 |
286 | case ClusterConstants.ID_ON_OFF_CLUSTER : {
287 |
288 | if(!devicesL.containsKey(deviceKey)){
289 | LogicalDevice dev = new LogicalDevice(extAddress,endpoint,DeviceConstants.TYPE_ON_OFF);
290 | devicesL.put(deviceKey, dev);
291 | }
292 |
293 |
294 | String st = attributes.getString(ClusterConstants.ON_OFF);
295 |
296 | String stat = Long.parseLong(st)+"";
297 | if(on_off_clusters == "")
298 | on_off_clusters += "SELECT "+id+" AS '_id', '"
299 | +extAddress+ "' AS 'device_extAddress', "
300 | +endpoint + " AS 'endpoint' ,"
301 | +timestamp+ " AS 'timestamp', '"
302 | +stat+ "' AS 'status' ";
303 | else
304 | on_off_clusters += "UNION SELECT "+id+" AS '_id', '"
305 | +extAddress+ "', "
306 | +endpoint + " AS 'endpoint' ,"
307 | +timestamp+ ", '"
308 | +stat+ "'";
309 |
310 | } break;
311 |
312 | case ClusterConstants.ID_TEMPERATURE_MEASUREMENT_CLUSTER : {
313 |
314 | if(!devicesL.containsKey(deviceKey)){
315 | LogicalDevice dev = new LogicalDevice(extAddress,endpoint,DeviceConstants.TYPE_TEMPERATURE_SENSOR);
316 | devicesL.put(deviceKey, dev);
317 | }
318 |
319 |
320 | String tempStringHex = attributes.getString(ClusterConstants.TEMPERATURE_MeasuredValue);
321 | Double temp = Long.parseLong(tempStringHex, 16)/100d;
322 |
323 | if(temperature_clusters == "")
324 | temperature_clusters += "SELECT "+id+" AS '_id', '"
325 | +extAddress+ "' AS 'device_extAddress', "
326 | +endpoint + " AS 'endpoint' ,"
327 | +timestamp+ " AS 'timestamp', '"
328 | +temp+ "' AS 'MeasuredValue' ";
329 | else
330 | temperature_clusters += "UNION SELECT "+id+" AS '_id', '"
331 | +extAddress+ "' , "
332 | +endpoint + " AS 'endpoint' ,"
333 | +timestamp+ " , '"
334 | +temp+ "'";
335 |
336 |
337 | } break;
338 |
339 | case ClusterConstants.ID_FLOW_MESUREMENT_CLUSTER : {
340 |
341 | if(!devicesL.containsKey(deviceKey)){
342 | LogicalDevice dev = new LogicalDevice(extAddress,endpoint,DeviceConstants.TYPE_FLOW_METER);
343 | devicesL.put(deviceKey, dev);
344 | }
345 |
346 | String flowStringHex = attributes.getString(ClusterConstants.FLOW_MeasuredValue);
347 | Double flow = Long.parseLong(flowStringHex, 16)/100d;
348 |
349 | if(flow_clusters == "")
350 | flow_clusters += "SELECT "+id+" AS '_id', '"
351 | +extAddress+ "' AS 'device_extAddress', "
352 | +endpoint + " AS 'endpoint' ,"
353 | +timestamp+ " AS 'timestamp', '"
354 | +flow+ "' AS 'MeasuredValue' ";
355 | else
356 | flow_clusters += "UNION SELECT "+id+" AS '_id', '"
357 | +extAddress+ "' , "
358 | +endpoint + " ,"
359 | +timestamp+ " , '"
360 | +flow+ "'";
361 |
362 | } break;
363 |
364 | case ClusterConstants.ID_THERMOSTAT_CLUSTER : {
365 | if(!devicesL.containsKey(deviceKey)){
366 | LogicalDevice dev = new LogicalDevice(extAddress,endpoint,DeviceConstants.TYPE_THERMOSTAT);
367 | devicesL.put(deviceKey, dev);
368 | }
369 |
370 | Double localTemp;
371 | String localTempH;
372 |
373 | if(attributes.opt(ClusterConstants.THERMOSTAT_LocalTemperature) != null){
374 | localTempH = attributes.getString(ClusterConstants.THERMOSTAT_LocalTemperature);
375 |
376 | localTemp = Long.parseLong(localTempH, 16) / 100d;
377 | }
378 | else
379 | localTemp = -1D;
380 |
381 | String minH = attributes.getString(ClusterConstants.THERMOSTAT_MinHeatSetpointLimit);
382 | String maxH = attributes.getString(ClusterConstants.THERMOSTAT_MaxHeatSetpointLimit);
383 |
384 |
385 | Double min = Long.parseLong(minH, 16)/100d;
386 | Double max = Long.parseLong(maxH, 16)/100d;
387 |
388 |
389 |
390 | if(thermostat_clusters == "")
391 | thermostat_clusters += "SELECT "+id+" AS '_id', '"
392 | +extAddress+ "' AS 'device_extAddress', "
393 | +endpoint + " AS 'endpoint' ,"
394 | +timestamp+ " AS 'timestamp', '"
395 | +min+ "' AS 'MinHeatSetpointLimit', '"
396 | +max+ "' AS 'MaxHeatSetpointLimit', '"
397 | +localTemp+ "' AS 'LocalTemperature' ";
398 | else
399 | thermostat_clusters += "UNION SELECT "+id+" AS '_id', '"
400 | +extAddress+ "', "
401 | +endpoint + " AS 'endpoint' ,"
402 | +timestamp+ " , '"
403 | +min+ "' , '"
404 | +max+ "' , '"
405 | +localTemp+ "' ";
406 |
407 | } break;
408 |
409 | }
410 | //determine witch cluster the status corresponds to
411 | }
412 | //initialize string on devices
413 | Collection col = devicesL.values();
414 | Iterator it = col.iterator();
415 | int id=0;
416 | while(it.hasNext()){
417 |
418 | LogicalDevice dev = it.next();
419 | Log.d("debug_database",dev.extAddress + " id"+ id + dev.endPoint + " type" + dev.type );
420 | if(devicesS == "")
421 | devicesS += "SELECT "+id+" AS '_id', '"
422 | +dev.extAddress+ "' AS 'extAddress', "
423 | +dev.endPoint+ " AS 'endpoint', "
424 | +dev.type+ " AS 'type' ";
425 | else
426 | devicesS += "UNION SELECT "+id+" AS '_id', '"
427 | +dev.extAddress+ "', "
428 | +dev.endPoint+ " , "
429 | +dev.type+ " ";
430 | id++;
431 | }
432 |
433 |
434 |
435 | databaseInitialize.put("devices", devicesS);
436 | databaseInitialize.put("basic_clusters", basic_clusters);
437 | databaseInitialize.put("power_clusters",power_clusters);
438 | databaseInitialize.put("on_off_clusters",on_off_clusters);
439 | databaseInitialize.put("temperature_clusters",temperature_clusters);
440 | databaseInitialize.put("flow_clusters",flow_clusters);
441 | databaseInitialize.put("thermostat_clusters",thermostat_clusters);
442 | return databaseInitialize;
443 |
444 | }
445 |
446 | }
447 |
--------------------------------------------------------------------------------
/src/upb/smarthome/restcomm/RestComm.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Smart Home Project
3 | * Copyright (c) 2011 All rights reserved.
4 | * Polytehnic University of Bucharest
5 | * Developed by Daniel-Octavian Rizea
6 | */
7 |
8 | package upb.smarthome.restcomm;
9 |
10 | import java.io.BufferedReader;
11 | import java.io.IOException;
12 | import java.io.InputStream;
13 | import java.io.InputStreamReader;
14 | import java.io.UnsupportedEncodingException;
15 | import java.util.List;
16 |
17 | import org.apache.http.HttpEntity;
18 | import org.apache.http.HttpResponse;
19 | import org.apache.http.NameValuePair;
20 | import org.apache.http.client.ClientProtocolException;
21 | import org.apache.http.client.HttpClient;
22 | import org.apache.http.client.entity.UrlEncodedFormEntity;
23 | import org.apache.http.client.methods.HttpGet;
24 | import org.apache.http.client.methods.HttpPost;
25 | import org.apache.http.client.methods.HttpPut;
26 | import org.apache.http.conn.ConnectTimeoutException;
27 | import org.apache.http.impl.client.DefaultHttpClient;
28 | import org.json.JSONException;
29 | import org.json.JSONObject;
30 |
31 | import android.util.Log;
32 |
33 | /**
34 | * The Class RestComm.
35 | * This class implements REST primitives
36 | */
37 | public class RestComm {
38 |
39 | /*
40 | * To convert the InputStream to String we use the BufferedReader.readLine()
41 | * method. We iterate until the BufferedReader return null which means
42 | * there's no more data to read. Each line will appended to a StringBuilder
43 | * and returned as String.
44 | */
45 | /**
46 | * Convert stream to string.
47 | *
48 | * @param is the is
49 | * @return the string
50 | */
51 | private static String convertStreamToString(InputStream is) {
52 |
53 | BufferedReader reader = new BufferedReader(new InputStreamReader(is));
54 | StringBuilder sb = new StringBuilder();
55 |
56 | String line = null;
57 | try {
58 | while ((line = reader.readLine()) != null) {
59 | sb.append(line + "\n");
60 | }
61 | } catch (IOException e) {
62 | e.printStackTrace();
63 | } finally {
64 | try {
65 | is.close();
66 | } catch (IOException e) {
67 | e.printStackTrace();
68 | }
69 | }
70 | return sb.toString();
71 | }
72 |
73 | // GET Method
74 | /**
75 | * Rest get.
76 | *
77 | * @param url the url
78 | * @return the jSON object
79 | * @throws JSONException the jSON exception
80 | * @throws ClientProtocolException the client protocol exception
81 | * @throws ConnectTimeoutException the connect timeout exception
82 | */
83 | public static JSONObject restGet(String url) throws JSONException, ClientProtocolException, ConnectTimeoutException
84 | {
85 | Log.i("Rest",url);
86 |
87 | HttpClient httpclient = new DefaultHttpClient();
88 |
89 | // Prepare a request object
90 | HttpGet httpget = new HttpGet(url);
91 | httpget.addHeader("Content-type", "text/json");
92 | // Execute the request
93 | HttpResponse response;
94 | try {
95 | response = httpclient.execute(httpget);
96 | // Examine the response status
97 | Log.i("Rest",response.getStatusLine().toString());
98 |
99 | // Get hold of the response entity
100 | HttpEntity entity = response.getEntity();
101 | // If the response does not enclose an entity, there is no need
102 | // to worry about connection release
103 |
104 | if (entity != null) {
105 |
106 | // A Simple JSON Response Read
107 | InputStream instream = entity.getContent();
108 | String result= convertStreamToString(instream);
109 | Log.i("Rest",result);
110 |
111 | JSONObject json=null;
112 |
113 | // A Simple JSONObject Creation
114 | json=new JSONObject(result);
115 |
116 | // Closing the input stream will trigger connection release
117 | instream.close();
118 |
119 | return json;
120 | }
121 | } catch (IOException e) {
122 | e.printStackTrace();
123 | }
124 |
125 | return null;
126 | }
127 |
128 | // PUT Method
129 | /**
130 | * Rest put.
131 | *
132 | * @param url the url
133 | * @return the jSON object
134 | * @throws JSONException the jSON exception
135 | * @throws ClientProtocolException the client protocol exception
136 | * @throws ConnectTimeoutException the connect timeout exception
137 | */
138 | public static JSONObject restPut(String url) throws JSONException, ClientProtocolException, ConnectTimeoutException
139 | {
140 | Log.i("Rest",url);
141 |
142 | HttpClient httpclient = new DefaultHttpClient();
143 |
144 | // Prepare a request object
145 | HttpPut httpput = new HttpPut(url);
146 |
147 |
148 |
149 | // Execute the request
150 | HttpResponse response;
151 | try {
152 | response = httpclient.execute(httpput);
153 | // Examine the response status
154 | Log.i("Rest",response.getStatusLine().toString());
155 |
156 | // Get hold of the response entity
157 | HttpEntity entity = response.getEntity();
158 | // If the response does not enclose an entity, there is no need
159 | // to worry about connection release
160 |
161 | if (entity != null) {
162 |
163 | // A Simple JSON Response Read
164 | InputStream instream = entity.getContent();
165 | String result= convertStreamToString(instream);
166 | Log.i("Rest",result);
167 |
168 | JSONObject json=null;
169 |
170 | // A Simple JSONObject Creation
171 | json=new JSONObject(result);
172 |
173 | // Closing the input stream will trigger connection release
174 | instream.close();
175 |
176 | return json;
177 | }
178 | } catch (IOException e) {
179 | e.printStackTrace();
180 | }
181 |
182 |
183 | return null;
184 | }
185 |
186 | // POST Method
187 | /**
188 | * Rest post.
189 | *
190 | * @param url the url
191 | * @param pairs the pairs
192 | * @return the jSON object
193 | * @throws JSONException the jSON exception
194 | * @throws ClientProtocolException the client protocol exception
195 | * @throws ConnectTimeoutException the connect timeout exception
196 | * @throws UnsupportedEncodingException the unsupported encoding exception
197 | */
198 | public static JSONObject restPost(String url,List pairs) throws JSONException, ClientProtocolException, ConnectTimeoutException, UnsupportedEncodingException
199 | {
200 | Log.i("Rest",url);
201 |
202 | HttpClient httpclient = new DefaultHttpClient();
203 |
204 | // Prepare a request object
205 | HttpPost httppost = new HttpPost(url);
206 | httppost.addHeader("Content-Type", "application/x-www-form-urlencoded");
207 |
208 | //add POST body
209 | httppost.setEntity(new UrlEncodedFormEntity(pairs));
210 |
211 | // Execute the request
212 | HttpResponse response;
213 | try {
214 | response = httpclient.execute(httppost);
215 | // Examine the response status
216 | Log.i("Rest",response.getStatusLine().toString());
217 |
218 | // Get hold of the response entity
219 | HttpEntity entity = response.getEntity();
220 | // If the response does not enclose an entity, there is no need
221 | // to worry about connection release
222 |
223 | if (entity != null) {
224 |
225 | // A Simple JSON Response Read
226 | InputStream instream = entity.getContent();
227 | String result= convertStreamToString(instream);
228 | Log.i("Rest",result);
229 |
230 | JSONObject json=null;
231 |
232 | // A Simple JSONObject Creation
233 | json=new JSONObject(result);
234 |
235 | // Closing the input stream will trigger connection release
236 | instream.close();
237 |
238 | return json;
239 | }
240 | } catch (IOException e) {
241 | e.printStackTrace();
242 | }
243 |
244 |
245 | return null;
246 | }
247 |
248 | }
--------------------------------------------------------------------------------