1 //******************************************************************
3 // Copyright 2014 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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
11 // http://www.apache.org/licenses/LICENSE-2.0
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.
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
21 // Do not remove the include below
29 // Arduino WiFi Shield
34 // Arduino Ethernet Shield
35 #include <EthernetServer.h>
38 #include <EthernetClient.h>
40 #include <EthernetUdp.h>
44 const char *getResult(OCStackResult result);
46 PROGMEM const char TAG[] = "ArduinoServer";
48 int gLightUnderObservation = 0;
49 void createLightResource();
51 /* Structure to represent a Light resource */
52 typedef struct LIGHTRESOURCE{
53 OCResourceHandle handle;
58 static LightResource Light;
60 static char responsePayloadGet[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"on\",\"power\":10}}";
61 static char responsePayloadPut[] = "{\"href\":\"/a/light\",\"rep\":{\"state\":\"off\",\"power\":0}}";
63 /// This is the port which Arduino Server will use for all unicast communication with it's peers
64 static uint16_t OC_WELL_KNOWN_PORT = 5683;
67 // Arduino WiFi Shield
68 // Note : Arduino WiFi Shield currently does NOT support multicast and therefore
69 // this server will NOT be listening on 224.0.1.187 multicast address.
71 /// WiFi Shield firmware with Intel patches
72 static const char INTEL_WIFI_SHIELD_FW_VER[] = "1.2.0";
74 /// WiFi network info and credentials
75 char ssid[] = "mDNSAP";
76 char pass[] = "letmein9";
78 int ConnectToNetwork()
81 int status = WL_IDLE_STATUS;
82 // check for the presence of the shield:
83 if (WiFi.status() == WL_NO_SHIELD)
85 OC_LOG(ERROR, TAG, PCF("WiFi shield not present"));
89 // Verify that WiFi Shield is running the firmware with all UDP fixes
90 fwVersion = WiFi.firmwareVersion();
91 OC_LOG_V(INFO, TAG, "WiFi Shield Firmware version %s", fwVersion);
92 if ( strncmp(fwVersion, INTEL_WIFI_SHIELD_FW_VER, sizeof(INTEL_WIFI_SHIELD_FW_VER)) !=0 )
94 OC_LOG(DEBUG, TAG, PCF("!!!!! Upgrade WiFi Shield Firmware version !!!!!!"));
98 // attempt to connect to Wifi network:
99 while (status != WL_CONNECTED)
101 OC_LOG_V(INFO, TAG, "Attempting to connect to SSID: %s", ssid);
102 status = WiFi.begin(ssid,pass);
104 // wait 10 seconds for connection:
107 OC_LOG(DEBUG, TAG, PCF("Connected to wifi"));
109 IPAddress ip = WiFi.localIP();
110 OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
114 // Arduino Ethernet Shield
115 int ConnectToNetwork()
117 // Note: ****Update the MAC address here with your shield's MAC address****
118 uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xC4, 0x05};
119 uint8_t error = Ethernet.begin(ETHERNET_MAC);
122 OC_LOG_V(ERROR, TAG, "error is: %d", error);
126 IPAddress ip = Ethernet.localIP();
127 OC_LOG_V(INFO, TAG, "IP Address: %d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
132 // On Arduino Atmel boards with Harvard memory architecture, the stack grows
133 // downwards from the top and the heap grows upwards. This method will print
134 // the distance(in terms of bytes) between those two.
135 // See here for more details :
136 // http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
137 void PrintArduinoMemoryStats()
139 #ifdef ARDUINO_AVR_MEGA2560
140 //This var is declared in avr-libc/stdlib/malloc.c
141 //It keeps the largest address not allocated for heap
142 extern char *__brkval;
143 //address of tmp gives us the current stack boundry
145 OC_LOG_V(INFO, TAG, "Stack: %u Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
146 OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
147 ((unsigned int)&tmp - (unsigned int)__brkval));
151 // This is the entity handler for the registered resource.
152 // This is invoked by OCStack whenever it recevies a request for this resource.
153 OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest )
155 OCEntityHandlerResult ehRet = OC_EH_OK;
156 OCEntityHandlerResponse response = {0};
157 char payload[MAX_RESPONSE_LENGTH] = {0};
159 if(entityHandlerRequest && (flag & OC_REQUEST_FLAG))
161 OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
163 if(OC_REST_GET == entityHandlerRequest->method)
165 size_t responsePayloadGetLength = strlen(responsePayloadGet);
166 if (responsePayloadGetLength < (sizeof(payload) - 1))
168 strncpy(payload, responsePayloadGet, responsePayloadGetLength);
175 else if(OC_REST_PUT == entityHandlerRequest->method)
177 //Do something with the 'put' payload
178 size_t responsePayloadPutLength = strlen(responsePayloadPut);
179 if (responsePayloadPutLength < (sizeof(payload) - 1))
181 strncpy((char *)payload, responsePayloadPut, responsePayloadPutLength);
189 if (ehRet == OC_EH_OK)
191 // Format the response. Note this requires some info about the request
192 response.requestHandle = entityHandlerRequest->requestHandle;
193 response.resourceHandle = entityHandlerRequest->resource;
194 response.ehResult = ehRet;
195 response.payload = (unsigned char *)payload;
196 response.payloadSize = strlen(payload);
197 response.numSendVendorSpecificHeaderOptions = 0;
198 memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
199 memset(response.resourceUri, 0, sizeof response.resourceUri);
200 // Indicate that response is NOT in a persistent buffer
201 response.persistentBufferFlag = 0;
204 if (OCDoResponse(&response) != OC_STACK_OK)
206 OC_LOG(ERROR, TAG, "Error sending response");
211 if (entityHandlerRequest && (flag & OC_OBSERVE_FLAG))
213 if (OC_OBSERVE_REGISTER == entityHandlerRequest->obsInfo.action)
215 OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_REGISTER from client"));
216 gLightUnderObservation = 1;
218 else if (OC_OBSERVE_DEREGISTER == entityHandlerRequest->obsInfo.action)
220 OC_LOG (INFO, TAG, PCF("Received OC_OBSERVE_DEREGISTER from client"));
227 // This method is used to display 'Observe' functionality of OC Stack.
228 static uint8_t modCounter = 0;
229 void *ChangeLightRepresentation (void *param)
232 OCStackResult result = OC_STACK_ERROR;
234 if(modCounter % 10 == 0) // Matching the timing that the Linux Sample Server App uses for the same functionality.
237 if (gLightUnderObservation)
239 OC_LOG_V(INFO, TAG, " =====> Notifying stack of new power level %d\n", Light.power);
240 result = OCNotifyAllObservers (Light.handle, OC_NA_QOS);
241 if (OC_STACK_NO_OBSERVERS == result)
243 gLightUnderObservation = 0;
250 //The setup function is called once at startup of the sketch
253 // Add your initialization code here
254 // Note : This will initialize Serial port on Arduino at 115200 bauds
256 OC_LOG(DEBUG, TAG, PCF("OCServer is starting..."));
257 uint16_t port = OC_WELL_KNOWN_PORT;
259 // Connect to Ethernet or WiFi network
260 if (ConnectToNetwork() != 0)
262 OC_LOG(ERROR, TAG, PCF("Unable to connect to network"));
266 // Initialize the OC Stack in Server mode
267 if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
269 OC_LOG(ERROR, TAG, PCF("OCStack init error"));
273 // Declare and create the example resource: Light
274 createLightResource();
277 // The loop function is called in an endless loop
280 // This artificial delay is kept here to avoid endless spinning
281 // of Arduino microcontroller. Modify it as per specfic application needs.
284 // This call displays the amount of free SRAM available on Arduino
285 PrintArduinoMemoryStats();
287 // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
288 if (OCProcess() != OC_STACK_OK)
290 OC_LOG(ERROR, TAG, PCF("OCStack process error"));
293 ChangeLightRepresentation(NULL);
296 void createLightResource()
299 OCStackResult res = OCCreateResource(&Light.handle,
304 OC_DISCOVERABLE|OC_OBSERVABLE);
305 OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
308 const char *getResult(OCStackResult result) {
311 return "OC_STACK_OK";
312 case OC_STACK_INVALID_URI:
313 return "OC_STACK_INVALID_URI";
314 case OC_STACK_INVALID_QUERY:
315 return "OC_STACK_INVALID_QUERY";
316 case OC_STACK_INVALID_IP:
317 return "OC_STACK_INVALID_IP";
318 case OC_STACK_INVALID_PORT:
319 return "OC_STACK_INVALID_PORT";
320 case OC_STACK_INVALID_CALLBACK:
321 return "OC_STACK_INVALID_CALLBACK";
322 case OC_STACK_INVALID_METHOD:
323 return "OC_STACK_INVALID_METHOD";
324 case OC_STACK_NO_MEMORY:
325 return "OC_STACK_NO_MEMORY";
326 case OC_STACK_COMM_ERROR:
327 return "OC_STACK_COMM_ERROR";
328 case OC_STACK_INVALID_PARAM:
329 return "OC_STACK_INVALID_PARAM";
330 case OC_STACK_NOTIMPL:
331 return "OC_STACK_NOTIMPL";
332 case OC_STACK_NO_RESOURCE:
333 return "OC_STACK_NO_RESOURCE";
334 case OC_STACK_RESOURCE_ERROR:
335 return "OC_STACK_RESOURCE_ERROR";
336 case OC_STACK_SLOW_RESOURCE:
337 return "OC_STACK_SLOW_RESOURCE";
338 case OC_STACK_NO_OBSERVERS:
339 return "OC_STACK_NO_OBSERVERS";
341 return "OC_STACK_ERROR";