Completing firmware for the temperature/humidity, IR, and magnetic sensors for both...
[iotcloud.git] / version2 / src / others / ino / Temp-Sensor / Temp-Sensor_Fidelius-Cloud.ino
1 #include "Table.h"
2 #include "IoTString.h"
3 #include "TimingSingleton.h"
4 #include "TransactionStatus.h"
5 #include "DHT.h"
6
7 SYSTEM_MODE(SEMI_AUTOMATIC)
8 SYSTEM_THREAD(ENABLED)
9
10 // System defines
11 // Arduino
12 #define DHTPIN                          2               // Data pin
13 #define PWRPIN                          D5              // Power pin
14 #define ERRPIN                          D7              // Error pin
15 #define DHTTYPE                         DHT22   // DHT 22  (AM2302)
16 // IoTCloud
17 #define SLEEP_TIME                      15              // Sleep time in seconds
18 #define RETRY_SLEEP_TIME        5               // Sleep time in seconds
19 #define RETRY_TIME                      10000   // stop trying after 10 seconds
20 #define CONNECTION_DELAY        2100000 // Need to delay after connecting WiFi to wait for sensor
21
22 // Initialize DHT sensor for normal 16mhz Arduino
23 DHT dht(DHTPIN, DHTTYPE);
24
25 // Globals
26 // IoTCloud
27 bool foundError;
28 MyVector<TransactionStatus *> * transStatusList;
29 char keyBuffer[80];
30 char dataBuffer[80];
31 Table *t1;
32 int64_t machineId;
33
34 void setup() {
35         // TODO: 
36         // 1) Before running PHOTON's with this firmware,
37         //    please go to the master branch and run Init.C
38         //    in iotcloud/version2/src/C to initialize 
39         //    a table on the cloud side.
40         //    If you want to read the committed keys and values 
41         //    on the cloud, then you can use Read.java in
42         //    iotcloud/version2/src/java/simple_test.
43         // 2) If you want to use the Serial library, 
44         //    please install "screen" on your machine and run
45         //    it on the serial port right after flashing the
46         //    firmware onto the Particle board.
47         //    e.g. sudo screen /dev/ttyACM0
48
49         // We use one I/O pin to power the sensor so
50         // that we can make it go to sleep when we go into
51         // deep sleep.
52         
53         // TODO: Profiling!
54         //Serial.begin();
55         //Serial.print("Time begin setup: ");
56         //Serial.println(micros());
57         // Turn on sensor
58         pinMode(PWRPIN, OUTPUT);
59         digitalWrite(PWRPIN, HIGH);
60         // Arduino DHT
61         dht.begin();
62         // Connect to WiFi and Particle cloud
63         // Wait for a maximum amount of time - sleep if WiFi is not connected
64         // Wake up and try again afterwards
65         // TODO: either use this or just WiFi connection (below)
66         //Particle.connect();
67         //if (!waitFor(Particle.connected, RETRY_TIME))
68         //      System.sleep(SLEEP_MODE_DEEP, RETRY_SLEEP_TIME);
69
70         // Connect only to WiFi
71         WiFi.on();
72         WiFi.connect();
73         if (!waitFor(WiFi.ready, RETRY_TIME))
74                 System.sleep(SLEEP_MODE_DEEP, RETRY_SLEEP_TIME);
75         while(!WiFi.localIP()); // Wait for valid IP
76     // Add delay if needed (for the humidity sensor we need ~2s delay)
77     // Delays are in millis but micros() returns microsecond time
78         if (micros() < CONNECTION_DELAY)
79                 delay((CONNECTION_DELAY - micros())/1000);
80
81         // TODO: Profiling WiFi
82         //Serial.println(micros());
83         //while(true) { }
84
85         // Prepare device key from MAC (just last 2 of 6 digits)
86         byte mac[6];
87         WiFi.macAddress(mac);
88
89         // TODO: Uncomment the following block to print MAC
90         //for (int i=0; i<6; i++) {
91         //      Serial.printf("%02x%s", mac[i], i != 5 ? ":" : "");
92         //}
93         //Serial.println();
94         // Prepare machine ID
95         int64_t mac4 = (int64_t) mac[4];
96         int64_t mac5 = (int64_t) mac[5];
97         machineId = (mac4 * 256) +  mac5;
98         //machineId = (int64_t) mac[5];   // Shorter version of machine ID
99         
100         // IoTCloud library
101         //foundError = false;
102         //transStatusList = new MyVector<TransactionStatus *>();
103         IoTString *baseurl = new IoTString("http://dc-6.calit2.uci.edu/test.iotcloud/");
104         IoTString *password = new IoTString("reallysecret");
105     // TODO: Profiling
106         //Serial.print("Time begin rebuilding table: ");
107         //Serial.println(micros());     
108         
109         t1 = new Table(baseurl, password, machineId, -1);
110         t1->rebuild();
111
112         baseurl->releaseRef();
113         password->releaseRef();
114     // TODO: Profiling  
115         //Serial.print("Time end setup: ");
116         //Serial.println(micros());
117 }
118
119 void loop() {
120         // Wait until sensor is ready
121         //delay(2000);
122     // TODO: Profiling
123         //Serial.print("Time begin loop: ");
124         //Serial.println(micros());
125         // Read humidity
126         float humid = dht.readHumidity();
127         // Read temperature as Fahrenheit
128         float tempF = dht.readTemperature(true);
129         // Check if any reads failed and exit early (to try again).
130         if (isnan(humid) || isnan(tempF))
131                 return;
132         
133         // TODO: Update values separately to different keys
134         /*
135         // Humidity
136         // Key
137         sprintf(keyBuffer, "h%04x", machineId);
138         IoTString * iKeyHumid = new IoTString(keyBuffer);
139         // Do updates for the humidity
140         sprintf(dataBuffer, "%0.2f", humid);
141         IoTString * iValueHumid = new IoTString(dataBuffer);
142
143         // Check and create a new key if it isn't created yet
144         t1->createNewKey(iKeyHumid, machineId);
145         t1->startTransaction();
146         t1->put(iKeyHumid, iValueHumid);
147         transStatusList->add(t1->commitTransaction());
148
149         // Temperature
150         // Key
151         sprintf(keyBuffer, "t%04x", machineId);
152         IoTString * iKeyTempF = new IoTString(keyBuffer);
153         // Do updates for the temperature
154         sprintf(dataBuffer, "%0.2f", tempF);
155         IoTString * iValueTempF = new IoTString(dataBuffer);
156
157         // Check and create a new key if it isn't created yet
158         t1->createNewKey(iKeyTempF, machineId);
159         t1->startTransaction();
160         t1->put(iKeyTempF, iValueTempF);
161         transStatusList->add(t1->commitTransaction());
162         t1->update();
163
164         iKeyHumid->releaseRef();
165         iValueHumid->releaseRef();
166         iKeyTempF->releaseRef();
167         iValueTempF->releaseRef();
168         */
169         
170         // TODO: Collapse temperature and humidity into one key
171         sprintf(keyBuffer, "humtemp%04x", machineId);
172         IoTString * iKey = new IoTString(keyBuffer);
173         // Do updates for the temperature
174         sprintf(dataBuffer, "%0.2f-%0.2f", humid, tempF);
175         IoTString * iValue = new IoTString(dataBuffer);
176         
177         t1->createNewKey(iKey, machineId);
178         t1->startTransaction();
179         t1->put(iKey, iValue);
180         transStatusList->add(t1->commitTransaction());
181         
182         iKey->releaseRef();
183         iValue->releaseRef();
184         
185         /*for (uint i = 0; i < transStatusList->size(); i++) {
186                 TransactionStatus * status = transStatusList->get(i);
187                 if (status->getStatus() != TransactionStatus_StatusCommitted) {
188                         foundError = true;
189                         digitalWrite(ERRPIN, HIGH);     // Turn on LED upon error
190                 }
191                 delete status;
192         }*/
193         
194         // Turn off sensor
195         digitalWrite(PWRPIN, LOW);
196
197         // TODO: Profiling
198         //Serial.print("Elapsed time: ");
199         //Serial.println(micros());
200         //while(true);
201         
202         System.sleep(SLEEP_MODE_DEEP, SLEEP_TIME);
203 }
204