Imported Upstream version 0.9.1
[platform/upstream/iotivity.git] / service / soft-sensor-manager / SampleApp / arduino / Reference_Thing / src / reference.cpp
1 /******************************************************************
2 *
3 * Copyright 2014 Samsung Electronics All Rights Reserved.
4 *
5 *
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 *      http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 ******************************************************************/
20
21 // Do not remove the include below
22 #include "Arduino.h"
23 #include "bleLib.h"
24 #include <stdio.h>
25
26 #include "logger.h"
27 #include "ocstack.h"
28 #include <string.h>
29
30 #include "oic_lanLib.h"
31 //#define ARDUINOWIFI 1
32 #define ARDUINO_AVR_MEGA2560 1
33 /// This is the port which Arduino Server will use for all unicast communication with it's peers
34 #define OC_WELL_KNOWN_PORT 5683
35
36 #define JSON_BASE00 "{\"href\":\"\",\"rep\":{"
37 #define JSON_BASE01 "\"0\":\"MAC\",\"1\":\"string\",\"2\":\""
38 #define JSON_BASE02 "\",\"3\":\"SERVICETYPE\",\"4\":\"string\",\"5\":\""
39 #define JSON_BASE03 "\"}}"
40
41 typedef struct REFERRESOURCE
42 {
43     OCResourceHandle m_handle;
44     char *m_macaddress;
45     char *m_servicetype;
46 } REFERResource;
47
48 PROGMEM const char TAG[] = "ReferenceSensor";
49
50 REFERResource REFER;
51 Cble ble;
52
53 //char macaddress[13]={"9059AF1704D7"};
54 //char macaddress[13]={"9059AF1700EE"};  R1
55 char macaddress[13] = {"34B1F7D004D2"};
56 //char macaddress[13]={"9059AF170C1D"};
57 char servicetype[15] = {"BOOKLight"};
58
59 int g_REFERUnderObservation = 0;
60
61 const char *getResult(OCStackResult result);
62 void createREFERResource();
63
64 #define LENGTH_VAR      100
65 static int base_length = 0;
66 bool JsonGenerator( REFERResource &ref, char *jsonBuf, uint16_t buf_length )
67 {
68     if ( (buf_length - base_length) < LENGTH_VAR )
69     {
70         OC_LOG_V(ERROR, TAG, "Error : length is very long.");
71         return false;
72     }
73
74     sprintf(jsonBuf, JSON_BASE00 JSON_BASE01"%s", ref.m_macaddress);
75     sprintf(jsonBuf + strlen(jsonBuf), JSON_BASE02"%s"JSON_BASE03, ref.m_servicetype);
76
77     Serial.println(jsonBuf);
78
79     return true;
80 }
81
82 // On Arduino Atmel boards with Harvard memory architecture, the stack grows
83 // downwards from the top and the heap grows upwards. This method will print
84 // the distance(in terms of bytes) between those two.
85 // See here for more details :
86 // http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
87 void PrintArduinoMemoryStats()
88 {
89 #ifdef ARDUINO_AVR_MEGA2560
90     //This var is declared in avr-libc/stdlib/malloc.c
91     //It keeps the largest address not allocated for heap
92     extern char *__brkval;
93     //address of tmp gives us the current stack boundry
94     int tmp;
95     OC_LOG_V(INFO, TAG, "Stack: %u         Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
96     OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
97              ((unsigned int)&tmp - (unsigned int)__brkval));
98 #endif
99 }
100
101 // This is the entity handler for the registered resource.
102 // This is invoked by OCStack whenever it recevies a request for this resource.
103 OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
104                                         OCEntityHandlerRequest *entityHandlerRequest )
105 {
106     OCEntityHandlerResult ehRet = OC_EH_OK;
107
108     if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
109     {
110         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
111         if (OC_REST_GET == entityHandlerRequest->method)
112         {
113             if (JsonGenerator( REFER, (char *)entityHandlerRequest->resJSONPayload, \
114                                entityHandlerRequest->resJSONPayloadLen))
115             {
116             }
117             else
118             {
119                 ehRet = OC_EH_ERROR;
120             }
121         }
122         if (OC_REST_PUT == entityHandlerRequest->method)
123         {
124             //Do something with the 'put' payload
125             if (JsonGenerator( REFER, (char *)entityHandlerRequest->resJSONPayload, \
126                                entityHandlerRequest->resJSONPayloadLen))
127             {
128             }
129             else
130             {
131                 ehRet = OC_EH_ERROR;
132             }
133         }
134     }
135     if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
136     {
137         if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo->action)
138         {
139             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
140             g_REFERUnderObservation = 1;
141         }
142         else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo->action)
143         {
144             OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
145         }
146     }
147
148     return ehRet;
149 }
150
151
152 char tempdata[200];
153 void ChangeREFERRepresentation (void *param)
154 {
155     (void)param;
156     OCStackResult result = OC_STACK_ERROR;
157     result = OCNotifyAllObservers (REFER.m_handle, OC_NA_QOS);
158
159     OC_LOG_V(INFO, TAG, "%s", JsonGenerator( REFER, tempdata, 200));
160
161     if (OC_STACK_NO_OBSERVERS == result)
162     {
163         OC_LOG_V(INFO, TAG, "g_REFERUnderObservation is 0." );
164         g_REFERUnderObservation = 0;
165     }
166 }
167
168 //The setup function is called once at startup of the sketch
169 void setup()
170 {
171     Serial.begin(115200);
172
173     REFER.m_macaddress = macaddress;
174     REFER.m_servicetype = servicetype;
175
176     // Add your initialization code here
177     OC_LOG_INIT();
178
179     OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
180
181     // Connect to Ethernet or WiFi network
182     if (ConnectToNetwork() != 0)
183     {
184         OC_LOG(ERROR, TAG, "Unable to connect to network");
185         return;
186     }
187
188     // Initialize the OC Stack in Server mode
189     if (OCInit(NULL, OC_WELL_KNOWN_PORT, OC_SERVER) != OC_STACK_OK)
190     {
191         OC_LOG(ERROR, TAG, PCF("OCStack init error"));
192         return;
193     }
194
195     OCStartPresence(60);
196     // Declare and create the example resource: PROXI
197     createREFERResource();
198
199     ble.init( (long)115200, BLE_SLAVER,  REFER.m_macaddress);
200
201 //  ble.StatusRead();
202
203     char str0[] = JSON_BASE00;
204     char str1[] = JSON_BASE01;
205     char str2[] = JSON_BASE02;
206     char str3[] = JSON_BASE03;
207
208     base_length = strlen(str0) + strlen(str1) + strlen(str2) + strlen(str3);
209
210     OC_LOG_V(INFO, TAG, "Program Start-\r\n");
211 }
212
213 // The loop function is called in an endless loop
214 void loop()
215 {
216     // This artificial delay is kept here to avoid endless spinning
217     // of Arduino microcontroller. Modify it as per specfic application needs.
218
219     // This call displays the amount of free SRAM available on Arduino
220     PrintArduinoMemoryStats();
221     delay(5000);
222     if (OCProcess() != OC_STACK_OK)
223     {
224         OC_LOG(ERROR, TAG, PCF("OCStack process error"));
225         return;
226     }
227     ChangeREFERRepresentation(NULL);
228
229     char *user_msg = NULL;
230     user_msg = ble.Debug2BLE( true );
231     ble.BLE2Debug( true );
232
233     if ( user_msg )
234     {
235         free( user_msg );
236         user_msg = NULL;
237     }
238 }
239
240 void createREFERResource()
241 {
242
243     OCStackResult res = OCCreateResource(&REFER.m_handle,
244                                          "SSManager.Sensor",
245                                          OC_RSRVD_INTERFACE_DEFAULT,
246                                          "/Reference_Thing",
247                                          OCEntityHandlerCb,
248                                          OC_DISCOVERABLE | OC_OBSERVABLE);
249     OC_LOG_V(INFO, TAG, "Created REFER resource with result: %s", getResult(res));
250 }
251
252 const char *getResult(OCStackResult result)
253 {
254     switch (result)
255     {
256         case OC_STACK_OK:
257             return "OC_STACK_OK";
258         case OC_STACK_INVALID_URI:
259             return "OC_STACK_INVALID_URI";
260         case OC_STACK_INVALID_QUERY:
261             return "OC_STACK_INVALID_QUERY";
262         case OC_STACK_INVALID_IP:
263             return "OC_STACK_INVALID_IP";
264         case OC_STACK_INVALID_PORT:
265             return "OC_STACK_INVALID_PORT";
266         case OC_STACK_INVALID_CALLBACK:
267             return "OC_STACK_INVALID_CALLBACK";
268         case OC_STACK_INVALID_METHOD:
269             return "OC_STACK_INVALID_METHOD";
270         case OC_STACK_NO_MEMORY:
271             return "OC_STACK_NO_MEMORY";
272         case OC_STACK_COMM_ERROR:
273             return "OC_STACK_COMM_ERROR";
274         case OC_STACK_INVALID_PARAM:
275             return "OC_STACK_INVALID_PARAM";
276         case OC_STACK_NOTIMPL:
277             return "OC_STACK_NOTIMPL";
278         case OC_STACK_NO_RESOURCE:
279             return "OC_STACK_NO_RESOURCE";
280         case OC_STACK_RESOURCE_ERROR:
281             return "OC_STACK_RESOURCE_ERROR";
282         case OC_STACK_SLOW_RESOURCE:
283             return "OC_STACK_SLOW_RESOURCE";
284         case OC_STACK_NO_OBSERVERS:
285             return "OC_STACK_NO_OBSERVERS";
286         case OC_STACK_ERROR:
287             return "OC_STACK_ERROR";
288         default:
289             return "UNKNOWN";
290     }
291 }
292