[IOT-1538] Add support for Protocol-Independent ID
[platform/upstream/iotivity.git] / resource / examples / simpleserver.cpp
index 86b1546..6185e3d 100644 (file)
 /// This sample provides steps to define an interface for a resource
 /// (properties and methods) and host this resource on the server.
 ///
+#include "iotivity_config.h"
 
 #include <functional>
-
+#ifdef HAVE_UNISTD_H
+#include <unistd.h>
+#endif
+#ifdef HAVE_PTHREAD_H
 #include <pthread.h>
+#endif
 #include <mutex>
 #include <condition_variable>
 
 #include "OCPlatform.h"
 #include "OCApi.h"
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+#endif
+
+#include "ocpayload.h"
 
 using namespace OC;
 using namespace std;
 namespace PH = std::placeholders;
 
+static const char* SVR_DB_FILE_NAME = "./oic_svr_db_server.dat";
 int gObservation = 0;
 void * ChangeLightRepresentation (void *param);
 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest);
 
+// Set of strings for each of platform Info fields
+std::string  platformId = "0A3E0D6F-DBF5-404E-8719-D6880042463A";
+std::string  manufacturerName = "OCF";
+std::string  manufacturerLink = "https://www.iotivity.org";
+std::string  modelNumber = "myModelNumber";
+std::string  dateOfManufacture = "2016-01-15";
+std::string  platformVersion = "myPlatformVersion";
+std::string  operatingSystemVersion = "myOS";
+std::string  hardwareVersion = "myHardwareVersion";
+std::string  firmwareVersion = "1.0";
+std::string  supportLink = "https://www.iotivity.org";
+std::string  systemTime = "2016-01-15T11.01";
+
+// Set of strings for each of device info fields
+std::string  deviceName = "IoTivity Simple Server";
+std::string  deviceType = "oic.wk.tv";
+std::string  specVersion = "core.1.1.0";
+std::vector<std::string> dataModelVersions = {"res.1.1.0", "sh.1.1.0"};
+std::string  protocolIndependentID = "fa008167-3bbf-4c9d-8604-c9bcb96cb712";
+
+// OCPlatformInfo Contains all the platform info to be stored
+OCPlatformInfo platformInfo;
+
 // Specifies where to notify all observers or list of observers
 // false: notifies all observers
 // true: notifies list of observers
@@ -74,7 +108,8 @@ public:
 public:
     /// Constructor
     LightResource()
-        :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light") {
+        :m_name("John's light"), m_state(false), m_power(0), m_lightUri("/a/light"),
+                m_resourceHandle(nullptr) {
         // Initialize representation
         m_lightRep.setUri(m_lightUri);
 
@@ -89,9 +124,12 @@ public:
     /// This function internally calls registerResource API.
     void createResource()
     {
-        std::string resourceURI = m_lightUri; //URI of the resource
-        std::string resourceTypeName = "core.light"; //resource type name. In this case, it is light
-        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+        //URI of the resource
+        std::string resourceURI = m_lightUri;
+        //resource type name. In this case, it is light
+        std::string resourceTypeName = "core.light";
+        // resource interface.
+        std::string resourceInterface = DEFAULT_INTERFACE;
 
         // OCResourceProperty is defined ocstack.h
         uint8_t resourceProperty;
@@ -118,9 +156,12 @@ public:
 
     OCStackResult createResource1()
     {
-        std::string resourceURI = "/a/light1"; // URI of the resource
-        std::string resourceTypeName = "core.light"; // resource type name. In this case, it is light
-        std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
+        // URI of the resource
+        std::string resourceURI = "/a/light1";
+        // resource type name. In this case, it is light
+        std::string resourceTypeName = "core.light";
+        // resource interface.
+        std::string resourceInterface = DEFAULT_INTERFACE;
 
         // OCResourceProperty is defined ocstack.h
         uint8_t resourceProperty;
@@ -233,9 +274,9 @@ public:
         }
     }
 
-    void addInterface(const std::string& interface) const
+    void addInterface(const std::string& iface) const
     {
-        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+        OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, iface);
         if (OC_STACK_OK != result)
         {
             cout << "Binding TypeName to Resource was unsuccessful\n";
@@ -255,12 +296,6 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
         std::string requestType = request->getRequestType();
         int requestFlag = request->getRequestHandlerFlag();
 
-        if(requestFlag & RequestHandlerFlag::InitFlag)
-        {
-            cout << "\t\trequestFlag : Init\n";
-
-            // entity handler to perform resource initialization operations
-        }
         if(requestFlag & RequestHandlerFlag::RequestFlag)
         {
             cout << "\t\trequestFlag : Request\n";
@@ -268,6 +303,19 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             pResponse->setRequestHandle(request->getRequestHandle());
             pResponse->setResourceHandle(request->getResourceHandle());
 
+            // Check for query params (if any)
+            QueryParamsMap queries = request->getQueryParameters();
+
+            if (!queries.empty())
+            {
+                std::cout << "\nQuery processing upto entityHandler" << std::endl;
+            }
+            for (auto it : queries)
+            {
+                std::cout << "Query key: " << it.first << " value : " << it.second
+                        << std:: endl;
+            }
+
             // If the request type is GET
             if(requestType == "GET")
             {
@@ -285,7 +333,7 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                 }
                 else // normal response case.
                 {
-                    pResponse->setErrorCode(200);
+
                     pResponse->setResponseResult(OC_EH_OK);
                     pResponse->setResourceRepresentation(get());
                     if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
@@ -302,7 +350,7 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                 // Do related operations related to PUT request
                 // Update the lightResource
                 put(rep);
-                pResponse->setErrorCode(200);
+
                 pResponse->setResponseResult(OC_EH_OK);
                 pResponse->setResourceRepresentation(get());
                 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
@@ -319,12 +367,16 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                 // Do related operations related to POST request
                 OCRepresentation rep_post = post(rep);
                 pResponse->setResourceRepresentation(rep_post);
-                pResponse->setErrorCode(200);
+
                 if(rep_post.hasAttribute("createduri"))
                 {
                     pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
                     pResponse->setNewResourceUri(rep_post.getValue<std::string>("createduri"));
                 }
+                else
+                {
+                    pResponse->setResponseResult(OC_EH_OK);
+                }
 
                 if(OC_STACK_OK == OCPlatform::sendResponse(pResponse))
                 {
@@ -333,7 +385,7 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             }
             else if(requestType == "DELETE")
             {
-                // DELETE request operations
+                cout << "Delete request received" << endl;
             }
         }
 
@@ -353,7 +405,12 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
                                                             m_interestedObservers.end());
             }
 
+#if defined(_WIN32)
+            DWORD threadId = 0;
+            HANDLE threadHandle = INVALID_HANDLE_VALUE;
+#else
             pthread_t threadId;
+#endif
 
             cout << "\t\trequestFlag : Observer\n";
             gObservation = 1;
@@ -363,7 +420,11 @@ OCEntityHandlerResult entityHandler(std::shared_ptr<OCResourceRequest> request)
             // If we have not created the thread already, we will create one here.
             if(!startedThread)
             {
+#if defined(_WIN32)
+                threadHandle = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ChangeLightRepresentation, (void*)this, 0, &threadId);
+#else
                 pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)this);
+#endif
                 startedThread = 1;
             }
             ehResult = OC_EH_OK;
@@ -389,7 +450,7 @@ void * ChangeLightRepresentation (void *param)
     // This function continuously monitors for the changes
     while (1)
     {
-        sleep (5);
+        sleep (3);
 
         if (gObservation)
         {
@@ -406,9 +467,9 @@ void * ChangeLightRepresentation (void *param)
 
             if(isListOfObservers)
             {
-                std::shared_ptr<OCResourceResponse> resourceResponse(new OCResourceResponse());
+                std::shared_ptr<OCResourceResponse> resourceResponse =
+                            {std::make_shared<OCResourceResponse>()};
 
-                resourceResponse->setErrorCode(200);
                 resourceResponse->setResourceRepresentation(lightPtr->get(), DEFAULT_INTERFACE);
 
                 result = OCPlatform::notifyListOfObservers(  lightPtr->getHandle(),
@@ -431,6 +492,99 @@ void * ChangeLightRepresentation (void *param)
     return NULL;
 }
 
+void DeletePlatformInfo()
+{
+    delete[] platformInfo.platformID;
+    delete[] platformInfo.manufacturerName;
+    delete[] platformInfo.manufacturerUrl;
+    delete[] platformInfo.modelNumber;
+    delete[] platformInfo.dateOfManufacture;
+    delete[] platformInfo.platformVersion;
+    delete[] platformInfo.operatingSystemVersion;
+    delete[] platformInfo.hardwareVersion;
+    delete[] platformInfo.firmwareVersion;
+    delete[] platformInfo.supportUrl;
+    delete[] platformInfo.systemTime;
+}
+
+void DuplicateString(char ** targetString, std::string sourceString)
+{
+    *targetString = new char[sourceString.length() + 1];
+    strncpy(*targetString, sourceString.c_str(), (sourceString.length() + 1));
+}
+
+OCStackResult SetPlatformInfo(std::string platformID, std::string manufacturerName,
+        std::string manufacturerUrl, std::string modelNumber, std::string dateOfManufacture,
+        std::string platformVersion, std::string operatingSystemVersion,
+        std::string hardwareVersion, std::string firmwareVersion, std::string supportUrl,
+        std::string systemTime)
+{
+    DuplicateString(&platformInfo.platformID, platformID);
+    DuplicateString(&platformInfo.manufacturerName, manufacturerName);
+    DuplicateString(&platformInfo.manufacturerUrl, manufacturerUrl);
+    DuplicateString(&platformInfo.modelNumber, modelNumber);
+    DuplicateString(&platformInfo.dateOfManufacture, dateOfManufacture);
+    DuplicateString(&platformInfo.platformVersion, platformVersion);
+    DuplicateString(&platformInfo.operatingSystemVersion, operatingSystemVersion);
+    DuplicateString(&platformInfo.hardwareVersion, hardwareVersion);
+    DuplicateString(&platformInfo.firmwareVersion, firmwareVersion);
+    DuplicateString(&platformInfo.supportUrl, supportUrl);
+    DuplicateString(&platformInfo.systemTime, systemTime);
+
+    return OC_STACK_OK;
+}
+
+OCStackResult SetDeviceInfo()
+{
+    OCStackResult result = OC_STACK_ERROR;
+
+    OCResourceHandle handle = OCGetResourceHandleAtUri(OC_RSRVD_DEVICE_URI);
+    if (handle == NULL)
+    {
+        cout << "Failed to find resource " << OC_RSRVD_DEVICE_URI << endl;
+        return result;
+    }
+
+    result = OCBindResourceTypeToResource(handle, deviceType.c_str());
+    if (result != OC_STACK_OK)
+    {
+        cout << "Failed to add device type" << endl;
+        return result;
+    }
+
+    result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DEVICE_NAME, deviceName);
+    if (result != OC_STACK_OK)
+    {
+        cout << "Failed to set device name" << endl;
+        return result;
+    }
+
+    result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_DATA_MODEL_VERSION,
+                                          dataModelVersions);
+    if (result != OC_STACK_OK)
+    {
+        cout << "Failed to set data model versions" << endl;
+        return result;
+    }
+
+    result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_SPEC_VERSION, specVersion);
+    if (result != OC_STACK_OK)
+    {
+        cout << "Failed to set spec version" << endl;
+        return result;
+    }
+
+    result = OCPlatform::setPropertyValue(PAYLOAD_TYPE_DEVICE, OC_RSRVD_PROTOCOL_INDEPENDENT_ID,
+                                          protocolIndependentID);
+    if (result != OC_STACK_OK)
+    {
+        cout << "Failed to set piid" << endl;
+        return result;
+    }
+
+    return OC_STACK_OK;
+}
+
 void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequest)
 {
     // This function handles slow response case
@@ -443,7 +597,7 @@ void * handleSlowResponse (void *param, std::shared_ptr<OCResourceRequest> pRequ
     pResponse->setRequestHandle(pRequest->getRequestHandle());
     pResponse->setResourceHandle(pRequest->getResourceHandle());
     pResponse->setResourceRepresentation(lightPtr->get());
-    pResponse->setErrorCode(200);
+
     pResponse->setResponseResult(OC_EH_OK);
 
     // Set the slow response flag back to false
@@ -463,10 +617,15 @@ void PrintUsage()
     std::cout << "    4 - Non-secure resource, GET slow response, notify all observers\n";
 }
 
+static FILE* client_open(const char* /*path*/, const char *mode)
+{
+    return fopen(SVR_DB_FILE_NAME, mode);
+}
 
 int main(int argc, char* argv[])
 {
     PrintUsage();
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
 
     if (argc == 1)
     {
@@ -492,6 +651,7 @@ int main(int argc, char* argv[])
                 break;
             case 4:
                 isSlowResponse = true;
+                break;
             default:
                 break;
        }
@@ -507,10 +667,33 @@ int main(int argc, char* argv[])
         OC::ModeType::Server,
         "0.0.0.0", // By setting to "0.0.0.0", it binds to all available interfaces
         0,         // Uses randomly available port
-        OC::QualityOfService::LowQos
+        OC::QualityOfService::LowQos,
+        &ps
     };
 
     OCPlatform::Configure(cfg);
+    std::cout << "Starting server & setting platform info\n";
+
+    OCStackResult result = SetPlatformInfo(platformId, manufacturerName, manufacturerLink,
+            modelNumber, dateOfManufacture, platformVersion, operatingSystemVersion,
+            hardwareVersion, firmwareVersion, supportLink, systemTime);
+
+    result = OCPlatform::registerPlatformInfo(platformInfo);
+
+    if (result != OC_STACK_OK)
+    {
+        std::cout << "Platform Registration failed\n";
+        return -1;
+    }
+
+    result = SetDeviceInfo();
+
+    if (result != OC_STACK_OK)
+    {
+        std::cout << "Device Registration failed\n";
+        return -1;
+    }
+
     try
     {
         // Create the instance of the resource class
@@ -519,9 +702,13 @@ int main(int argc, char* argv[])
 
         // Invoke createResource function of class light.
         myLight.createResource();
+        std::cout << "Created resource." << std::endl;
 
         myLight.addType(std::string("core.brightlight"));
-        myLight.addInterface(std::string("oc.mi.ll"));
+        myLight.addInterface(std::string(LINK_INTERFACE));
+        std::cout << "Added Interface and Type" << std::endl;
+
+        DeletePlatformInfo();
 
         // A condition variable will free the mutex it is given, then do a non-
         // intensive block until 'notify' is called on it.  In this case, since we
@@ -530,11 +717,12 @@ int main(int argc, char* argv[])
         std::mutex blocker;
         std::condition_variable cv;
         std::unique_lock<std::mutex> lock(blocker);
-        cv.wait(lock);
+        std::cout <<"Waiting" << std::endl;
+        cv.wait(lock, []{return false;});
     }
-    catch(OCException e)
+    catch(OCException &e)
     {
-        //log(e.what());
+        std::cout << "OCException in main : " << e.what() << endl;
     }
 
     // No explicit call to stop the platform.