+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef HOSTINGCONFIG_H_
#define HOSTINGCONFIG_H_
enum class HostingMode
{
- None,
- ManualMode,
- AutomaticMode,
+ None,
+ ManualMode,
+ AutomaticMode,
};
enum class AutomaticMethod
{
- None,
- NetworkStatusChange,
- Timer,
- DeviceStatus
+ None,
+ NetworkStatusChange,
+ Timer,
+ DeviceStatus
};
enum class NotifyMethod
{
- Frequence,
- Equalization,
- Granularity,
- None
+ Frequence,
+ Equalization,
+ Granularity,
+ None
};
enum class NotifyFrequency
{
- OnTime,
- Periodically,
- None
+ OnTime,
+ Periodically,
+ None
};
struct HostingConfig
{
- HostingMode hostingMode;
- AutomaticMethod automaticMethod;
- NotifyMethod notifyMethod;
- NotifyFrequency frequency;
+ HostingMode hostingMode;
+ AutomaticMethod automaticMethod;
+ NotifyMethod notifyMethod;
+ NotifyFrequency frequency;
};
#endif /* HOSTINGCONFIG_H_ */
-/*
- * HostingHandler.h
- *
- * Created on: 2014. 10. 15.
- * Author: jyong2
- */
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef HOSTINGHANDLER_H_
#define HOSTINGHANDLER_H_
class HostingHandler
{
-public:
+ public:
- static void initialize();
- static void initialize(HostingConfig cfg);
- static HostingHandler *getInstance();
+ static void initialize();
+ static void initialize(HostingConfig cfg);
+ static HostingHandler *getInstance();
- void setHostingConfig(HostingConfig cfg);
+ void setHostingConfig(HostingConfig cfg);
- void changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod = AutomaticMethod::None);
- void changeAutomaticHostingMethod(AutomaticMethod autoMethod);
- void changeNotifiyMethod(NotifyMethod notifyMethod);
- void changeNotifyFrequencyType(NotifyFrequency notifyFrequency);
+ void changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod = AutomaticMethod::None);
+ void changeAutomaticHostingMethod(AutomaticMethod autoMethod);
+ void changeNotifiyMethod(NotifyMethod notifyMethod);
+ void changeNotifyFrequencyType(NotifyFrequency notifyFrequency);
-private:
+ private:
- HostingHandler();
- ~HostingHandler();
+ HostingHandler();
+ ~HostingHandler();
- static HostingHandler *s_instance;
- static mutex s_mutexForCreation;
+ static HostingHandler *s_instance;
+ static mutex s_mutexForCreation;
- HostingConfig hostingCfg;
+ HostingConfig hostingCfg;
- static std::function< void(bool isHosting) > s_findHostingCandidate;
- static std::function< void(std::string) > s_addExtraStr;
- static std::function< void(std::shared_ptr< OCResource > resource) > s_startHosting;
- static std::function< void(OCResourceHandle resourceHandle) > s_notify;
+ static std::function< void(bool isHosting) > s_findHostingCandidate;
+ static std::function< void(std::string) > s_addExtraStr;
+ static std::function< void(std::shared_ptr< OCResource > resource) > s_startHosting;
+ static std::function< void(OCResourceHandle resourceHandle) > s_notify;
- void startFindHost();
- void onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle);
- void onFoundCandidate(std::shared_ptr< OCResource > resource);
+ void startFindHost();
+ void onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle);
+ void onFoundCandidate(std::shared_ptr< OCResource > resource);
- void runAutomaticHosting(AutomaticMethod autoMethod);
- void stopAutomaticHosting();
+ void runAutomaticHosting(AutomaticMethod autoMethod);
+ void stopAutomaticHosting();
- void notifyFrequence(OCResourceHandle resourceHandle);
+ void notifyFrequence(OCResourceHandle resourceHandle);
};
-/*
- * HostingInterface.h
- *
- * Created on: 2014. 10. 15.
- * Author: jyong2
- */
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef HOSTINGINTERFACE_H_
#define HOSTINGINTERFACE_H_
class HostingInterface
{
-public:
- HostingInterface();
- ~HostingInterface();
+ public:
+ HostingInterface();
+ ~HostingInterface();
- int setOnFoundHostingCandidate(
- std::function< void(std::shared_ptr< OCResource > resource) > func);
- int setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func);
+ int setOnFoundHostingCandidate(
+ std::function< void(std::shared_ptr< OCResource > resource) > func);
+ int setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >
+ func);
- int setFindHosting(std::function< void(bool isHosting) > &func);
- int setStartHosting(std::function< void(std::shared_ptr< OCResource > resource) > &func);
- int setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func);
- int setAddExtraStr(std::function< void(std::string) > &func);
+ int setFindHosting(std::function< void(bool isHosting) > &func);
+ int setStartHosting(std::function< void(std::shared_ptr< OCResource > resource) > &func);
+ int setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func);
+ int setAddExtraStr(std::function< void(std::string) > &func);
};
class NotificationManager
{
-private:
+ private:
- NotificationManager();
- NotificationManager(HostingConfig cfg);
- ~NotificationManager();
+ NotificationManager();
+ NotificationManager(HostingConfig cfg);
+ ~NotificationManager();
- static NotificationManager *s_instance;
- static mutex s_mutexForCreation;
+ static NotificationManager *s_instance;
+ static mutex s_mutexForCreation;
- int getNetInfo(IN int& sck, IN struct ifreq* item, OUT std::string& ip_addres);
- bool scanAndGetNetworkInterface(OUT std::string& ip_addres);
+ int getNetInfo(IN int &sck, IN struct ifreq *item, OUT std::string &ip_addres);
+ bool scanAndGetNetworkInterface(OUT std::string &ip_addres);
-public:
+ public:
- static void initialize();
- static void initialize(HostingConfig cfg);
- static NotificationManager *getInstance();
+ static void initialize();
+ static void initialize(HostingConfig cfg);
+ static NotificationManager *getInstance();
- void registerHostingEventListener();
+ void registerHostingEventListener();
};
-/*
- * OICPlatformConfig.h
- *
- * Created on: 2014. 10. 15.
- * Author: jyong2
- */
-
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#ifndef OICPLATFORMCONFIG_H_
#define OICPLATFORMCONFIG_H_
class OICPlatformConfig
{
-private:
+ private:
- OICPlatformConfig();
- ~OICPlatformConfig();
+ OICPlatformConfig();
+ ~OICPlatformConfig();
- static OICPlatformConfig *s_instance;
- static mutex s_mutexForCreation;
- static PlatformConfig s_cfg;
+ static OICPlatformConfig *s_instance;
+ static mutex s_mutexForCreation;
+ static PlatformConfig s_cfg;
-public:
+ public:
- void initialize();
- static OICPlatformConfig *getInstance();
- void setIP(std::string ipaddress);
+ void initialize();
+ static OICPlatformConfig *getInstance();
+ void setIP(std::string ipaddress);
};
#endif /* OICPLATFORMCONFIG_H_ */
class RegistrationManager
{
-private:
- RegistrationManager();
- ~RegistrationManager();
+ private:
+ RegistrationManager();
+ ~RegistrationManager();
- static RegistrationManager *s_instance;
- static mutex s_mutexForCreation;
+ static RegistrationManager *s_instance;
+ static mutex s_mutexForCreation;
-public:
+ public:
- static RegistrationManager *getInstance();
+ static RegistrationManager *getInstance();
- bool registerNMResource(VirtualRepresentation &resourceObject ,
- std::shared_ptr< OCResource > resource);
+ bool registerNMResource(VirtualRepresentation &resourceObject ,
+ std::shared_ptr< OCResource > resource);
- int addResource();
- int removeResource();
- int updateResource();
- bool unregisterResource();
+ int addResource();
+ int removeResource();
+ int updateResource();
+ bool unregisterResource();
};
class ResourceManager
{
-private:
- ResourceManager();
- ~ResourceManager();
+ private:
+ ResourceManager();
+ ~ResourceManager();
- static ResourceManager *s_instance;
- static mutex s_mutexForCreation;
- static std::list< VirtualRepresentation > s_resourceList;
- static std::string s_extraStr;
+ static ResourceManager *s_instance;
+ static mutex s_mutexForCreation;
+ static std::list< VirtualRepresentation > s_resourceList;
+ static std::string s_extraStr;
- void foundResourceforhosting(std::shared_ptr< OCResource > resource);
+ void foundResourceforhosting(std::shared_ptr< OCResource > resource);
- void checkResourceDBPolicy();
- void saveResourceDB();
+ void checkResourceDBPolicy();
+ void saveResourceDB();
-public:
+ public:
- std::function< void(std::shared_ptr< OCResource > resource) > m_onFoundforHosting;
- std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > m_onObserve;
- std::function< void(OCResourceHandle resourceHandle) > m_notify;
+ std::function< void(std::shared_ptr< OCResource > resource) > m_onFoundforHosting;
+ std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > m_onObserve;
+ std::function< void(OCResourceHandle resourceHandle) > m_notify;
- static ResourceManager *getInstance();
+ static ResourceManager *getInstance();
- void findNMResource(bool isHosting);
+ void findNMResource(bool isHosting);
- void onFoundforHostingDefault(std::shared_ptr< OCResource > resource);
- void onObserveDefault(AttributeMap &inputAttMap, OCResourceHandle resourceHandle);
- void notifyObserversDefault(OCResourceHandle resourceHandle);
+ void onFoundforHostingDefault(std::shared_ptr< OCResource > resource);
+ void onObserveDefault(AttributeMap &inputAttMap, OCResourceHandle resourceHandle);
+ void notifyObserversDefault(OCResourceHandle resourceHandle);
- void startHosting(std::shared_ptr< OCResource > resource);
- void notifyObservers(OCResourceHandle resourceHandle);
+ void startHosting(std::shared_ptr< OCResource > resource);
+ void notifyObservers(OCResourceHandle resourceHandle);
- VirtualRepresentation findVirtualRepresentation(std::string uri);
- AttributeMap copyAttributeMap(AttributeMap &inputAttMap);
- bool isEmptyAttributeMap(AttributeMap &inputAttMap);
- void printAttributeMap(AttributeMap &inputAttMap);
+ VirtualRepresentation findVirtualRepresentation(std::string uri);
+ AttributeMap copyAttributeMap(AttributeMap &inputAttMap);
+ bool isEmptyAttributeMap(AttributeMap &inputAttMap);
+ void printAttributeMap(AttributeMap &inputAttMap);
- void addExtraStr(std::string str);
- std::string getExtraStr();
+ void addExtraStr(std::string str);
+ std::string getExtraStr();
};
#endif /* RESOURCEMANAGER_H_ */
class VirtualRepresentation
{
-private:
- std::string m_virtualUri;
- std::string m_originHostIP;
- std::string m_resourceTypeName;
- std::string m_resourceInterface;
- uint8_t m_resourceProperty;
-
- OCResourceHandle m_resourceHandle;
-
- static AttributeMap s_attributeMap;
- static std::mutex s_mutexAttributeMap;
- static std::condition_variable s_conditionAttributeMap;
- static bool m_isReadyAttributeMap;
-
- int getRepresentation(OCRepresentation& oc);
-
-public:
-
- std::string getUri();
- std::string getHostIP();
- std::string getResourceTypeName();
- std::string getResourceInterface();
- uint8_t getResourceProperty();
- OCResourceHandle getResourceHandle();
-
- int setUri(std::string uri);
- int setHostIP(std::string ip);
- int setResourceTypeName(std::string typeName);
- int setResourceInterface(std::string interface);
- int setResourceProperty(uint8_t property);
- int setResourceHandle(OCResourceHandle & handle);
-
-public:
- VirtualRepresentation();
- virtual ~VirtualRepresentation();
-
- std::string addVirtualTag(std::string uri);
-
- OCEntityHandlerResult entityHandler(const std::shared_ptr<OCResourceRequest> request ,
- const std::shared_ptr<OCResourceResponse> response);
- void onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep ,
- const int eCode , const int sequenceNumber);
+ private:
+ std::string m_virtualUri;
+ std::string m_originHostIP;
+ std::string m_resourceTypeName;
+ std::string m_resourceInterface;
+ uint8_t m_resourceProperty;
+
+ OCResourceHandle m_resourceHandle;
+
+ static AttributeMap s_attributeMap;
+ static std::mutex s_mutexAttributeMap;
+ static std::condition_variable s_conditionAttributeMap;
+ static bool m_isReadyAttributeMap;
+
+ int getRepresentation(OCRepresentation &oc);
+
+ public:
+
+ std::string getUri();
+ std::string getHostIP();
+ std::string getResourceTypeName();
+ std::string getResourceInterface();
+ uint8_t getResourceProperty();
+ OCResourceHandle getResourceHandle();
+
+ int setUri(std::string uri);
+ int setHostIP(std::string ip);
+ int setResourceTypeName(std::string typeName);
+ int setResourceInterface(std::string interface);
+ int setResourceProperty(uint8_t property);
+ int setResourceHandle(OCResourceHandle &handle);
+
+ public:
+ VirtualRepresentation();
+ virtual ~VirtualRepresentation();
+
+ std::string addVirtualTag(std::string uri);
+
+ OCEntityHandlerResult entityHandler(const std::shared_ptr<OCResourceRequest> request ,
+ const std::shared_ptr<OCResourceResponse> response);
+ void onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep ,
+ const int eCode , const int sequenceNumber);
};
-/*
- * HostingHandler.cpp
- *
- * Created on: 2014. 10. 15.
- * Author: jyong2
- */
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "HostingHandler.h"
HostingHandler *HostingHandler::getInstance()
{
- if(!s_instance)
- {
- s_mutexForCreation.lock();
- if(!s_instance)
- {
- s_instance = new HostingHandler();
- }
- s_mutexForCreation.unlock();
- }
+ if (!s_instance)
+ {
+ s_mutexForCreation.lock();
+ if (!s_instance)
+ {
+ s_instance = new HostingHandler();
+ }
+ s_mutexForCreation.unlock();
+ }
- return s_instance;
+ return s_instance;
}
void HostingHandler::initialize()
{
- // Create Hosting Handler instance
- HostingHandler *ptr = HostingHandler::getInstance();
+ // Create Hosting Handler instance
+ HostingHandler *ptr = HostingHandler::getInstance();
- // Registration interface about hosting
- HostingInterface hostingInterface;
+ // Registration interface about hosting
+ HostingInterface hostingInterface;
- hostingInterface.setFindHosting(ptr->s_findHostingCandidate);
- hostingInterface.setStartHosting(ptr->s_startHosting);
- hostingInterface.setNotifyObservers(ptr->s_notify);
- hostingInterface.setAddExtraStr(ptr->s_addExtraStr);
+ hostingInterface.setFindHosting(ptr->s_findHostingCandidate);
+ hostingInterface.setStartHosting(ptr->s_startHosting);
+ hostingInterface.setNotifyObservers(ptr->s_notify);
+ hostingInterface.setAddExtraStr(ptr->s_addExtraStr);
- hostingInterface.setOnFoundHostingCandidate(
- std::function< void(std::shared_ptr< OCResource > resource) >(
- std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , std::placeholders::_1)));
- hostingInterface.setOnObserve(
- std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
- std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, std::placeholders::_2)));
+ hostingInterface.setOnFoundHostingCandidate(
+ std::function< void(std::shared_ptr< OCResource > resource) >(
+ std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() ,
+ std::placeholders::_1)));
+ hostingInterface.setOnObserve(
+ std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
+ std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1,
+ std::placeholders::_2)));
- ptr->s_addExtraStr("virtual");
- ptr->startFindHost();
+ ptr->s_addExtraStr("virtual");
+ ptr->startFindHost();
}
void HostingHandler::initialize(HostingConfig cfg)
{
- // Create Hosting Handler instance
- HostingHandler *ptr = HostingHandler::getInstance();
+ // Create Hosting Handler instance
+ HostingHandler *ptr = HostingHandler::getInstance();
- // Registration interface about hosting
- HostingInterface hostingInterface;
+ // Registration interface about hosting
+ HostingInterface hostingInterface;
- hostingInterface.setFindHosting(ptr->s_findHostingCandidate);
- hostingInterface.setStartHosting(ptr->s_startHosting);
- hostingInterface.setNotifyObservers(ptr->s_notify);
- hostingInterface.setAddExtraStr(ptr->s_addExtraStr);
+ hostingInterface.setFindHosting(ptr->s_findHostingCandidate);
+ hostingInterface.setStartHosting(ptr->s_startHosting);
+ hostingInterface.setNotifyObservers(ptr->s_notify);
+ hostingInterface.setAddExtraStr(ptr->s_addExtraStr);
- hostingInterface.setOnFoundHostingCandidate(
- std::function< void(std::shared_ptr< OCResource > resource) >(
- std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() , std::placeholders::_1)));
- hostingInterface.setOnObserve(
- std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
- std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1, std::placeholders::_2)));
+ hostingInterface.setOnFoundHostingCandidate(
+ std::function< void(std::shared_ptr< OCResource > resource) >(
+ std::bind(&HostingHandler::onFoundCandidate , HostingHandler::getInstance() ,
+ std::placeholders::_1)));
+ hostingInterface.setOnObserve(
+ std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
+ std::bind(&HostingHandler::onObserve , HostingHandler::getInstance() , std::placeholders::_1,
+ std::placeholders::_2)));
- // Set Hosting Config
- ptr->setHostingConfig(cfg);
- ptr->changeHostingMode(ptr->hostingCfg.hostingMode);
+ // Set Hosting Config
+ ptr->setHostingConfig(cfg);
+ ptr->changeHostingMode(ptr->hostingCfg.hostingMode);
- ptr->s_addExtraStr("virtual");
- ptr->startFindHost();
+ ptr->s_addExtraStr("virtual");
+ ptr->startFindHost();
}
void HostingHandler::setHostingConfig(HostingConfig cfg)
{
- hostingCfg.automaticMethod = cfg.automaticMethod;
- hostingCfg.frequency = cfg.frequency;
- hostingCfg.hostingMode = cfg.hostingMode;
- hostingCfg.notifyMethod = cfg.notifyMethod;
+ hostingCfg.automaticMethod = cfg.automaticMethod;
+ hostingCfg.frequency = cfg.frequency;
+ hostingCfg.hostingMode = cfg.hostingMode;
+ hostingCfg.notifyMethod = cfg.notifyMethod;
}
void HostingHandler::changeHostingMode(HostingMode hostingMode, AutomaticMethod autoMethod)
{
- if(hostingCfg.hostingMode != hostingMode)
- {
- hostingCfg.hostingMode = hostingMode;
- if(hostingCfg.hostingMode == HostingMode::AutomaticMode)
- {
- runAutomaticHosting(autoMethod);
- }
- else
- {
- stopAutomaticHosting();
- }
- }
+ if (hostingCfg.hostingMode != hostingMode)
+ {
+ hostingCfg.hostingMode = hostingMode;
+ if (hostingCfg.hostingMode == HostingMode::AutomaticMode)
+ {
+ runAutomaticHosting(autoMethod);
+ }
+ else
+ {
+ stopAutomaticHosting();
+ }
+ }
}
void HostingHandler::runAutomaticHosting(AutomaticMethod autoMethod)
{
- // TODO Triggering from Event Listener.
- if(hostingCfg.automaticMethod != autoMethod)
- {
- hostingCfg.automaticMethod = autoMethod;
- switch(hostingCfg.automaticMethod)
- {
- case AutomaticMethod::None:
- break;
- case AutomaticMethod::Timer:
- case AutomaticMethod::DeviceStatus:
- case AutomaticMethod::NetworkStatusChange:
- default:
- break;
- }
- }
+ // TODO Triggering from Event Listener.
+ if (hostingCfg.automaticMethod != autoMethod)
+ {
+ hostingCfg.automaticMethod = autoMethod;
+ switch (hostingCfg.automaticMethod)
+ {
+ case AutomaticMethod::None:
+ break;
+ case AutomaticMethod::Timer:
+ case AutomaticMethod::DeviceStatus:
+ case AutomaticMethod::NetworkStatusChange:
+ default:
+ break;
+ }
+ }
}
void HostingHandler::stopAutomaticHosting()
{
- if(hostingCfg.automaticMethod != AutomaticMethod::None)
- {
+ if (hostingCfg.automaticMethod != AutomaticMethod::None)
+ {
// TODO
- }
+ }
}
void HostingHandler::changeAutomaticHostingMethod(AutomaticMethod autoMethod)
{
-// TODO
+// TODO
}
void HostingHandler::changeNotifiyMethod(NotifyMethod notifyMethod)
{
-// TODO
+// TODO
}
void HostingHandler::changeNotifyFrequencyType(NotifyFrequency notifyFrequency)
{
-// TODO
+// TODO
}
void HostingHandler::startFindHost()
{
- if(hostingCfg.hostingMode != HostingMode::None)
- {
- s_findHostingCandidate(true);
- }
+ if (hostingCfg.hostingMode != HostingMode::None)
+ {
+ s_findHostingCandidate(true);
+ }
}
void HostingHandler::onFoundCandidate(std::shared_ptr< OCResource > resource)
{
- // TODO
- // Condition of Hosting
- s_startHosting(resource);
+ // TODO
+ // Condition of Hosting
+ s_startHosting(resource);
}
void HostingHandler::onObserve(AttributeMap &AttMap, OCResourceHandle resourceHandle)
{
- switch(hostingCfg.notifyMethod)
- {
- case NotifyMethod::None:
- break;
- case NotifyMethod::Equalization:
- case NotifyMethod::Granularity:
- case NotifyMethod::Frequence:
- default:
- notifyFrequence(resourceHandle);
- break;
- }
+ switch (hostingCfg.notifyMethod)
+ {
+ case NotifyMethod::None:
+ break;
+ case NotifyMethod::Equalization:
+ case NotifyMethod::Granularity:
+ case NotifyMethod::Frequence:
+ default:
+ notifyFrequence(resourceHandle);
+ break;
+ }
}
void HostingHandler::notifyFrequence(OCResourceHandle resourceHandle)
{
- switch(hostingCfg.frequency)
- {
- case NotifyFrequency::None:
- break;
- case NotifyFrequency::Periodically:
- case NotifyFrequency::OnTime:
- default:
- s_notify(resourceHandle);
- break;
- }
+ switch (hostingCfg.frequency)
+ {
+ case NotifyFrequency::None:
+ break;
+ case NotifyFrequency::Periodically:
+ case NotifyFrequency::OnTime:
+ default:
+ s_notify(resourceHandle);
+ break;
+ }
}
-/*
- * HostingInterface.cpp
- *
- * Created on: 2014. 10. 15.
- * Author: jyong2
- */
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "HostingInterface.h"
HostingInterface::~HostingInterface()
{
- // TODO Auto-generated destructor stub
+ // TODO Auto-generated destructor stub
}
int HostingInterface::setOnFoundHostingCandidate(
- std::function< void(std::shared_ptr< OCResource > resource) > func)
+ std::function< void(std::shared_ptr< OCResource > resource) > func)
{
- if(func != NULL)
+ if (func != NULL)
{
try
{
- ResourceManager::getInstance()->m_onFoundforHosting = func;
+ ResourceManager::getInstance()->m_onFoundforHosting = func;
}
- catch(exception &e)
+ catch (exception &e)
{
return false;
}
}
else
{
- ResourceManager::getInstance()->m_onFoundforHosting = std::function<
- void(std::shared_ptr< OCResource > resource) >(
- std::bind(&ResourceManager::onFoundforHostingDefault , ResourceManager::getInstance() ,
- std::placeholders::_1));
+ ResourceManager::getInstance()->m_onFoundforHosting = std::function <
+ void(std::shared_ptr< OCResource > resource) > (
+ std::bind(&ResourceManager::onFoundforHostingDefault , ResourceManager::getInstance() ,
+ std::placeholders::_1));
}
return true;
}
-int HostingInterface::setOnObserve(std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func)
+int HostingInterface::setOnObserve(
+ std::function< void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) > func)
{
- if(func != NULL)
+ if (func != NULL)
{
try
{
- ResourceManager::getInstance()->m_onObserve = func;
+ ResourceManager::getInstance()->m_onObserve = func;
}
- catch(exception &e)
+ catch (exception &e)
{
return false;
}
}
else
{
- ResourceManager::getInstance()->m_onObserve = std::function<
- void(AttributeMap &inputAttMap, OCResourceHandle resourceHandle) >(
- std::bind(&ResourceManager::onObserveDefault , ResourceManager::getInstance() ,
- std::placeholders::_1, std::placeholders::_2));
+ ResourceManager::getInstance()->m_onObserve = std::function <
+ void(AttributeMap & inputAttMap, OCResourceHandle resourceHandle) > (
+ std::bind(&ResourceManager::onObserveDefault , ResourceManager::getInstance() ,
+ std::placeholders::_1, std::placeholders::_2));
}
return true;
}
-int HostingInterface::setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) > &func)
+int HostingInterface::setNotifyObservers(std::function< void(OCResourceHandle resourceHandle) >
+ &func)
{
- try
- {
- func = std::function< void(OCResourceHandle resourceHandle) >(
- std::bind(&ResourceManager::notifyObservers , ResourceManager::getInstance() ,
- std::placeholders::_1));
- }
- catch(exception &e)
- {
- return false;
- }
-
- return true;
+ try
+ {
+ func = std::function< void(OCResourceHandle resourceHandle) >(
+ std::bind(&ResourceManager::notifyObservers , ResourceManager::getInstance() ,
+ std::placeholders::_1));
+ }
+ catch (exception &e)
+ {
+ return false;
+ }
+
+ return true;
}
int HostingInterface::setStartHosting(
- std::function< void(std::shared_ptr< OCResource > resource) > &func)
+ std::function< void(std::shared_ptr< OCResource > resource) > &func)
{
try
{
func = std::function< void(std::shared_ptr< OCResource > resource) >(
- std::bind(&ResourceManager::startHosting , ResourceManager::getInstance() ,
- std::placeholders::_1));
+ std::bind(&ResourceManager::startHosting , ResourceManager::getInstance() ,
+ std::placeholders::_1));
}
- catch(exception &e)
+ catch (exception &e)
{
return false;
}
try
{
func = std::function< void(bool isHosting) >(
- std::bind(&ResourceManager::findNMResource ,
- ResourceManager::getInstance() ,
- std::placeholders::_1));
+ std::bind(&ResourceManager::findNMResource ,
+ ResourceManager::getInstance() ,
+ std::placeholders::_1));
}
- catch(exception &e)
+ catch (exception &e)
{
return false;
}
try
{
func = std::function< void(std::string str) >(
- std::bind(&ResourceManager::addExtraStr , ResourceManager::getInstance() ,
- std::placeholders::_1));
+ std::bind(&ResourceManager::addExtraStr , ResourceManager::getInstance() ,
+ std::placeholders::_1));
}
- catch(exception &e)
+ catch (exception &e)
{
return false;
}
void NotificationManager::initialize()
{
- // find local ip address
+ // find local ip address
std::string ipAddress;
NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress);
void NotificationManager::initialize(HostingConfig cfg)
{
- // find local ip address
+ // find local ip address
std::string ipAddress;
NotificationManager::getInstance()->scanAndGetNetworkInterface(ipAddress);
NotificationManager *NotificationManager::getInstance()
{
- if(!s_instance)
- {
- s_mutexForCreation.lock();
- if(!s_instance)
- {
- s_instance = new NotificationManager();
- }
- s_mutexForCreation.unlock();
- }
+ if (!s_instance)
+ {
+ s_mutexForCreation.lock();
+ if (!s_instance)
+ {
+ s_instance = new NotificationManager();
+ }
+ s_mutexForCreation.unlock();
+ }
return s_instance;
}
-int NotificationManager::getNetInfo(IN int& sck, IN struct ifreq* item, OUT std::string& ip_addres)
+int NotificationManager::getNetInfo(IN int &sck, IN struct ifreq *item, OUT std::string &ip_addres)
{
- struct ifreq temp_ifr;
- memset(&temp_ifr, 0, sizeof(temp_ifr));
- strcpy(temp_ifr.ifr_name, item->ifr_name);
-
- if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr))
- {
- return -1;
- }
-
- if (!((temp_ifr.ifr_flags & IFF_UP) && (temp_ifr.ifr_flags & IFF_RUNNING)))
- {
- return -1;
- }
-
- std::string ip(inet_ntoa(((struct sockaddr_in *) &item->ifr_addr)->sin_addr));
- if (ip.empty())
- {
- return -1;
- }
-
- if (ip.find("127.0.0") == 0)
- {
- return -1;
- }
-
- ip_addres = ip;
- return 0;
+ struct ifreq temp_ifr;
+ memset(&temp_ifr, 0, sizeof(temp_ifr));
+ strcpy(temp_ifr.ifr_name, item->ifr_name);
+
+ if (ioctl(sck, SIOCGIFFLAGS, &temp_ifr))
+ {
+ return -1;
+ }
+
+ if (!((temp_ifr.ifr_flags & IFF_UP) && (temp_ifr.ifr_flags & IFF_RUNNING)))
+ {
+ return -1;
+ }
+
+ std::string ip(inet_ntoa(((struct sockaddr_in *) &item->ifr_addr)->sin_addr));
+ if (ip.empty())
+ {
+ return -1;
+ }
+
+ if (ip.find("127.0.0") == 0)
+ {
+ return -1;
+ }
+
+ ip_addres = ip;
+ return 0;
}
-bool NotificationManager::scanAndGetNetworkInterface(OUT std::string& ip_addres)
+bool NotificationManager::scanAndGetNetworkInterface(OUT std::string &ip_addres)
{
- while(1)
- {
- char buf[1024] = { 0, };
- struct ifconf ifc;
- struct ifreq *ifr;
- int sck;
- int interfaces;
- int i;
-
- sck = socket(AF_INET, SOCK_DGRAM, 0);
- if (sck < 0)
- {
- usleep(10);
- continue;
- }
-
- ifc.ifc_len = sizeof(buf);
- ifc.ifc_buf = buf;
- if (ioctl(sck, SIOCGIFCONF, &ifc) < 0)
- {
- printf( "SIOCGIFCONF Failed ");
- close(sck);
- usleep(10);
- continue;
- }
-
- ifr = ifc.ifc_req;
- interfaces = ifc.ifc_len / sizeof(struct ifreq);
-
- for (i = 0; i < interfaces; i++)
- {
- if( getNetInfo(sck, &ifr[i], ip_addres) == 0 )
- {
- return 0;
- }
- continue;
- }
- close(sck);
- usleep(10);
- }
-
- return 0;
+ while (1)
+ {
+ char buf[1024] = { 0, };
+ struct ifconf ifc;
+ struct ifreq *ifr;
+ int sck;
+ int interfaces;
+ int i;
+
+ sck = socket(AF_INET, SOCK_DGRAM, 0);
+ if (sck < 0)
+ {
+ usleep(10);
+ continue;
+ }
+
+ ifc.ifc_len = sizeof(buf);
+ ifc.ifc_buf = buf;
+ if (ioctl(sck, SIOCGIFCONF, &ifc) < 0)
+ {
+ printf( "SIOCGIFCONF Failed ");
+ close(sck);
+ usleep(10);
+ continue;
+ }
+
+ ifr = ifc.ifc_req;
+ interfaces = ifc.ifc_len / sizeof(struct ifreq);
+
+ for (i = 0; i < interfaces; i++)
+ {
+ if ( getNetInfo(sck, &ifr[i], ip_addres) == 0 )
+ {
+ return 0;
+ }
+ continue;
+ }
+ close(sck);
+ usleep(10);
+ }
+
+ return 0;
}
-/*
- * OICPlatformConfig.cpp
- *
- * Created on: 2014. 10. 15.
- * Author: jyong2
- */
+//******************************************************************
+//
+// Copyright 2014 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
#include "OICPlatformConfig.h"
OICPlatformConfig::OICPlatformConfig()
{
- // TODO Auto-generated constructor stub
+ // TODO Auto-generated constructor stub
}
OICPlatformConfig::~OICPlatformConfig()
{
- // TODO Auto-generated destructor stub
+ // TODO Auto-generated destructor stub
}
OICPlatformConfig *OICPlatformConfig::getInstance()
{
- if(!s_instance)
- {
- s_mutexForCreation.lock();
- if(!s_instance)
- {
- s_instance = new OICPlatformConfig();
- Configure(s_cfg);
- }
- s_mutexForCreation.unlock();
- }
+ if (!s_instance)
+ {
+ s_mutexForCreation.lock();
+ if (!s_instance)
+ {
+ s_instance = new OICPlatformConfig();
+ Configure(s_cfg);
+ }
+ s_mutexForCreation.unlock();
+ }
- return s_instance;
+ return s_instance;
}
//void OICPlatformConfig::getOCPlatform()
//{
-//// if(!s_nmOCPlatform)
-//// {
-//// if(s_cfg.ipAddress.empty())
-//// {
-//// return NULL;
-//// }
-//// s_nmOCPlatform = new OCPlatform(s_cfg);
-//// Configure(s_cfg);
-//// }
-//// return s_nmOCPlatform;
+//// if(!s_nmOCPlatform)
+//// {
+//// if(s_cfg.ipAddress.empty())
+//// {
+//// return NULL;
+//// }
+//// s_nmOCPlatform = new OCPlatform(s_cfg);
+//// Configure(s_cfg);
+//// }
+//// return s_nmOCPlatform;
//}
void OICPlatformConfig::initialize()
void OICPlatformConfig::setIP(std::string ipaddress)
{
- s_cfg.ipAddress = ipaddress;
+ s_cfg.ipAddress = ipaddress;
}
RegistrationManager *RegistrationManager::getInstance()
{
- if(!s_instance)
- {
- s_mutexForCreation.lock();
- if(s_instance)
- {
- s_instance = new RegistrationManager();
- }
- s_mutexForCreation.unlock();
- }
-
- return s_instance;
+ if (!s_instance)
+ {
+ s_mutexForCreation.lock();
+ if (s_instance)
+ {
+ s_instance = new RegistrationManager();
+ }
+ s_mutexForCreation.unlock();
+ }
+
+ return s_instance;
}
int RegistrationManager::addResource()
OCStackResult result;
result = registerResource(resourceHandle , uri , type ,
- interface ,
- std::function<
- OCEntityHandlerResult(const std::shared_ptr< OCResourceRequest > request ,
- const std::shared_ptr< OCResourceResponse > response) >(
- std::bind(&VirtualRepresentation::entityHandler , resourceObject ,
- std::placeholders::_1 , std::placeholders::_2)) ,
- resourceObject.getResourceProperty());
+ interface ,
+ std::function <
+ OCEntityHandlerResult(const std::shared_ptr< OCResourceRequest > request ,
+ const std::shared_ptr< OCResourceResponse > response) > (
+ std::bind(&VirtualRepresentation::entityHandler , resourceObject ,
+ std::placeholders::_1 , std::placeholders::_2)) ,
+ resourceObject.getResourceProperty());
resourceObject.setResourceHandle(resourceHandle);
- if(OC_STACK_OK != result)
+ if (OC_STACK_OK != result)
{
return false;
}
{
QueryParamsMap queryParmaMap;
resource->observe(ObserveType::Observe , queryParmaMap ,
- std::function<
- void(const HeaderOptions headerOption,
- const OCRepresentation& rep , const int& eCode ,
- const int& sequenceNumber) >(
- std::bind(&VirtualRepresentation::onObserve , resourceObject ,
- std::placeholders::_1 , std::placeholders::_2 ,
- std::placeholders::_3 , std::placeholders::_4)));
+ std::function <
+ void(const HeaderOptions headerOption,
+ const OCRepresentation & rep , const int &eCode ,
+ const int &sequenceNumber) > (
+ std::bind(&VirtualRepresentation::onObserve , resourceObject ,
+ std::placeholders::_1 , std::placeholders::_2 ,
+ std::placeholders::_3 , std::placeholders::_4)));
}
return true;
ResourceManager::ResourceManager()
{
- m_onFoundforHosting = NULL;
- m_onObserve = NULL;
- m_notify = NULL;
+ m_onFoundforHosting = NULL;
+ m_onObserve = NULL;
+ m_notify = NULL;
}
ResourceManager::~ResourceManager()
ResourceManager *ResourceManager::getInstance()
{
- if(!s_instance)
+ if (!s_instance)
{
s_mutexForCreation.lock();
- if(!s_instance)
+ if (!s_instance)
{
- s_instance = new ResourceManager();
+ s_instance = new ResourceManager();
}
s_mutexForCreation.unlock();
}
VirtualRepresentation retObject;
- for(auto it = s_resourceList.begin() ; it != s_resourceList.end() ; it++)
+ for (auto it = s_resourceList.begin() ; it != s_resourceList.end() ; it++)
{
- if(it->getUri().compare(uri) == 0)
+ if (it->getUri().compare(uri) == 0)
{
retObject = *it;
return retObject;
void ResourceManager::findNMResource(bool isHosting)
{
- if(isHosting)
- {
- findResource("" , "coap://224.0.1.187/oc/core",
- std::function< void(std::shared_ptr< OCResource > resource) >(
- std::bind(&ResourceManager::foundResourceforhosting , ResourceManager::getInstance() ,
- std::placeholders::_1)));
- }
+ if (isHosting)
+ {
+ findResource("" , "coap://224.0.1.187/oc/core",
+ std::function< void(std::shared_ptr< OCResource > resource) >(
+ std::bind(&ResourceManager::foundResourceforhosting , ResourceManager::getInstance() ,
+ std::placeholders::_1)));
+ }
}
void ResourceManager::foundResourceforhosting(std::shared_ptr< OCResource > resource)
{
try
{
- if(resource)
+ if (resource)
{
- if(resource->uri().find("/a/NM") != std::string::npos)
+ if (resource->uri().find("/a/NM") != std::string::npos)
{
ResourceManager::getInstance()->m_onFoundforHosting(resource);
}
}
else
{
- // TODO
+ // TODO
}
}
- catch(std::exception &e)
+ catch (std::exception &e)
{
}
}
void ResourceManager::startHosting(std::shared_ptr< OCResource > resource)
{
- cout << "start hosting" << endl;
+ cout << "start hosting" << endl;
VirtualRepresentation tmp = findVirtualRepresentation( resource->uri() );
- if( !tmp.getUri().empty() )
+ if ( !tmp.getUri().empty() )
{
return;
}
void ResourceManager::notifyObservers(OCResourceHandle resourceHandle)
{
- OCStackResult result = OC_STACK_OK;
+ OCStackResult result = OC_STACK_OK;
- result = notifyAllObservers(resourceHandle);
+ result = notifyAllObservers(resourceHandle);
- if(OC_STACK_NO_OBSERVERS == result)
- {
- // No observers.
- // TODO
- }
+ if (OC_STACK_NO_OBSERVERS == result)
+ {
+ // No observers.
+ // TODO
+ }
}
AttributeMap ResourceManager::copyAttributeMap(AttributeMap &inputAttMap)
bool ResourceManager::isEmptyAttributeMap(AttributeMap &inputAttMap)
{
- for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
+ for (auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
{
- if(inputAttMap.find(it->first) == inputAttMap.end())
+ if (inputAttMap.find(it->first) == inputAttMap.end())
{
return true;
}
}
void ResourceManager::onObserveDefault(AttributeMap &inputAttMap , OCResourceHandle resourceHandle)
{
- ResourceManager::getInstance()->notifyObservers(resourceHandle);
+ ResourceManager::getInstance()->notifyObservers(resourceHandle);
}
void ResourceManager::printAttributeMap(AttributeMap &inputAttMap)
{
- for(auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
+ for (auto it = inputAttMap.begin() ; it != inputAttMap.end() ; ++it)
{
std::cout << "\tAttribute name: " << it->first << " value: ";
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
std::cout << "\t" << *valueItr << " ";
}
return true;
}
-int VirtualRepresentation::setResourceHandle(OCResourceHandle & handle)
+int VirtualRepresentation::setResourceHandle(OCResourceHandle &handle)
{
m_resourceHandle = handle;
return true;
}
-int VirtualRepresentation::getRepresentation(OCRepresentation& oc)
+int VirtualRepresentation::getRepresentation(OCRepresentation &oc)
{
oc.setAttributeMap(s_attributeMap);
oc.setUri(this->getUri().c_str());
return true;
}
-OCEntityHandlerResult VirtualRepresentation::entityHandler(const std::shared_ptr<OCResourceRequest> request ,
- const std::shared_ptr<OCResourceResponse> response)
+OCEntityHandlerResult VirtualRepresentation::entityHandler(const std::shared_ptr<OCResourceRequest>
+ request , const std::shared_ptr<OCResourceResponse> response)
{
- if(request)
+ if (request)
{
std::string requestType = request->getRequestType();
int requestFlag = request->getRequestHandlerFlag();
- if(requestFlag == RequestHandlerFlag::InitFlag)
- {
- }
+ if (requestFlag == RequestHandlerFlag::InitFlag)
+ {
+ }
- else if(requestFlag == RequestHandlerFlag::RequestFlag)
+ else if (requestFlag == RequestHandlerFlag::RequestFlag)
{
- if( (requestType == "GET") && response )
+ if ( (requestType == "GET") && response )
{
- std::unique_lock< std::mutex > lck(s_mutexAttributeMap);
- while(!m_isReadyAttributeMap)
- {
- s_conditionAttributeMap.wait(lck);
- }
- m_isReadyAttributeMap = false;
+ std::unique_lock< std::mutex > lck(s_mutexAttributeMap);
+ while (!m_isReadyAttributeMap)
+ {
+ s_conditionAttributeMap.wait(lck);
+ }
+ m_isReadyAttributeMap = false;
- OCRepresentation rep;
- getRepresentation(rep);
+ OCRepresentation rep;
+ getRepresentation(rep);
- response->setErrorCode(200);
- response->setResourceRepresentation(rep , DEFAULT_INTERFACE);
+ response->setErrorCode(200);
+ response->setResourceRepresentation(rep , DEFAULT_INTERFACE);
- m_isReadyAttributeMap = true;
- s_conditionAttributeMap.notify_all();
- }
- else if(requestType == "PUT")
+ m_isReadyAttributeMap = true;
+ s_conditionAttributeMap.notify_all();
+ }
+ else if (requestType == "PUT")
{
- // TODO
+ // TODO
}
- else if(requestType == "POST")
+ else if (requestType == "POST")
{
- // TODO
+ // TODO
}
- else if(requestType == "DELETE")
+ else if (requestType == "DELETE")
{
- // TODO
+ // TODO
}
else
{
- // TODO
+ // TODO
}
}
- else if(requestFlag == RequestHandlerFlag::InitFlag)
- {
- // TODO
- }
- else if(requestFlag == RequestHandlerFlag::ObserverFlag)
+ else if (requestFlag == RequestHandlerFlag::InitFlag)
+ {
+ // TODO
+ }
+ else if (requestFlag == RequestHandlerFlag::ObserverFlag)
{
- // TODO
- cout << "requestFlag == RequestHandlerFlag::ObserverFlag\n";
+ // TODO
+ cout << "requestFlag == RequestHandlerFlag::ObserverFlag\n";
}
else
{
- // requestFlag is not [Request, Init, Observer]
- // TODO
+ // requestFlag is not [Request, Init, Observer]
+ // TODO
}
}
else
{
- // Param(request) is empty.
- // TODO
+ // Param(request) is empty.
+ // TODO
}
return OC_EH_OK;
}
-void VirtualRepresentation::onObserve(const HeaderOptions &headerOption, const OCRepresentation &rep , const int eCode , const int sequenceNumber)
+void VirtualRepresentation::onObserve(const HeaderOptions &headerOption,
+ const OCRepresentation &rep , const int eCode , const int sequenceNumber)
{
- cout << "VirtualRepresentation::onObserve Enter\n";
- if(eCode == SUCCESS_RESPONSE)
+ if (eCode == SUCCESS_RESPONSE)
{
- cout << "1\n";
AttributeMap inputAttributeMap = rep.getAttributeMap();
-
- if(ResourceManager::getInstance()->isEmptyAttributeMap(inputAttributeMap))
+ if (ResourceManager::getInstance()->isEmptyAttributeMap(inputAttributeMap))
{
- cout << "2\n";
return;
}
- cout << "3\n";
VirtualRepresentation tmpObj = *this;
- if(!tmpObj.getUri().empty())
+ if (!tmpObj.getUri().empty())
{
- cout << "4\n";
AttributeMap tmpAttMap = ResourceManager::getInstance()->copyAttributeMap(inputAttributeMap);
- cout << "5\n";
{
- cout << "6\n";
std::unique_lock< std::mutex > lck(s_mutexAttributeMap);
- cout << "7\n";
- while(!m_isReadyAttributeMap)
+ while (!m_isReadyAttributeMap)
{
- cout << "8\n";
s_conditionAttributeMap.wait(lck);
}
- cout << "9\n";
m_isReadyAttributeMap = false;
- cout << "10\n";
s_attributeMap = tmpAttMap;
- cout << "11\n";
m_isReadyAttributeMap = true;
- cout << "12\n";
s_conditionAttributeMap.notify_all();
- cout << "13\n";
}
- if(ResourceManager::getInstance()->m_onObserve)
- {
- cout << "14\n";
- ResourceManager::getInstance()->m_onObserve(inputAttributeMap, tmpObj.getResourceHandle());
- cout << "15\n";
- }
+ if (ResourceManager::getInstance()->m_onObserve)
+ {
+ ResourceManager::getInstance()->m_onObserve(inputAttributeMap, tmpObj.getResourceHandle());
+ }
}
}
else
{
- // Check the error.
- // TODO
+ // Check the error.
+ // TODO
}
cout << "VirtualRepresentation::onObserve Out\n";
}
std::cout << "Start Notification Manager : Hosting v0.5\n";
- HostingConfig cfg;
- cfg.hostingMode = HostingMode::ManualMode;
- cfg.automaticMethod = AutomaticMethod::None;
- cfg.notifyMethod = NotifyMethod::Frequence;
- cfg.frequency = NotifyFrequency::OnTime;
+ HostingConfig cfg;
+ cfg.hostingMode = HostingMode::ManualMode;
+ cfg.automaticMethod = AutomaticMethod::None;
+ cfg.notifyMethod = NotifyMethod::Frequence;
+ cfg.frequency = NotifyFrequency::OnTime;
- NotificationManager::initialize(cfg);
+ NotificationManager::initialize(cfg);
- while(true)
+ while (true)
{
- char signal;
- cin >> signal;
+ char signal;
+ cin >> signal;
- switch(signal)
- {
- case 'q':
- case 'Q':
- std::cout << endl;
- std::cout << "========================================================" << endl;
- std::cout << "End Notification Manager : Hosting v0.5\n";
- return true;
- default:
- break;
- }
+ switch (signal)
+ {
+ case 'q':
+ case 'Q':
+ std::cout << endl;
+ std::cout << "========================================================" << endl;
+ std::cout << "End Notification Manager : Hosting v0.5\n";
+ return true;
+ default:
+ break;
+ }
}
+++ /dev/null
-##
-# NotificationManager build script
-##
-
-Import('env')
-
-notimgr_env = env.Clone()
-
-######################################################################
-# Build flags
-######################################################################
-resource_path = env.get('SRC_DIR') + '/resource'
-
-notimgr_env.AppendUnique(CPPPATH = [
- resource_path + '/oc_logger/include',
- resource_path + '/csdk/stack/include',
- resource_path + '/csdk/ocsocket/include',
- resource_path + '/csdk/logger/include'
- ])
-
-notimgr_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-notimgr_env.PrependUnique(LIBS = ['octbstack', 'coap'])
-
-######################################################################
-# Source files and Targets
-######################################################################
-thserver = notimgr_env.Program('thserver', 'thserver.cpp')
-notimgr_env.CreateBin('thserver')
-
-i_thserver = notimgr_env.Install(env.get('BUILD_DIR'), thserver)
-
-Alias('thserver_arduino', i_thserver)
-env.AppendTarget('thserver_arduino')
\ No newline at end of file
+++ /dev/null
-/* DateStrings.cpp
- * Definitions for date strings for use with the Time library
- *
- * No memory is consumed in the sketch if your code does not call any of the string methods
- * You can change the text of the strings, make sure the short strings are each exactly 3 characters
- * the long strings can be any length up to the constant dt_MAX_STRING_LEN defined in Time.h
- *
- */
-
-#if defined(__AVR__)
-#include <avr/pgmspace.h>
-#else
-// for compatiblity with Arduino Due and Teensy 3.0 and maybe others?
-#define PROGMEM
-#define PGM_P const char *
-#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
-#define pgm_read_word(addr) (*(const unsigned char **)(addr))
-#define strcpy_P(dest, src) strcpy((dest), (src))
-#endif
-#include <string.h> // for strcpy_P or strcpy
-#include "Time.h"
-
-// the short strings for each day or month must be exactly dt_SHORT_STR_LEN
-#define dt_SHORT_STR_LEN 3 // the length of short strings
-
-static char buffer[dt_MAX_STRING_LEN+1]; // must be big enough for longest string and the terminating null
-
-const char monthStr1[] PROGMEM = "January";
-const char monthStr2[] PROGMEM = "February";
-const char monthStr3[] PROGMEM = "March";
-const char monthStr4[] PROGMEM = "April";
-const char monthStr5[] PROGMEM = "May";
-const char monthStr6[] PROGMEM = "June";
-const char monthStr7[] PROGMEM = "July";
-const char monthStr8[] PROGMEM = "August";
-const char monthStr9[] PROGMEM = "September";
-const char monthStr10[] PROGMEM = "October";
-const char monthStr11[] PROGMEM = "November";
-const char monthStr12[] PROGMEM = "December";
-
-PGM_P monthNames_P[] PROGMEM =
-{
- "",monthStr1,monthStr2,monthStr3,monthStr4,monthStr5,monthStr6,
- monthStr7,monthStr8,monthStr9,monthStr10,monthStr11,monthStr12
-};
-
-const char monthShortNames_P[] PROGMEM = "ErrJanFebMarAprMayJunJulAugSepOctNovDec";
-
-const char dayStr0[] PROGMEM = "Err";
-const char dayStr1[] PROGMEM = "Sunday";
-const char dayStr2[] PROGMEM = "Monday";
-const char dayStr3[] PROGMEM = "Tuesday";
-const char dayStr4[] PROGMEM = "Wednesday";
-const char dayStr5[] PROGMEM = "Thursday";
-const char dayStr6[] PROGMEM = "Friday";
-const char dayStr7[] PROGMEM = "Saturday";
-
-PGM_P dayNames_P[] PROGMEM = { dayStr0,dayStr1,dayStr2,dayStr3,dayStr4,dayStr5,dayStr6,dayStr7};
-char dayShortNames_P[] PROGMEM = "ErrSunMonTueWedThrFriSat";
-
-/* functions to return date strings */
-
-char* monthStr(uint8_t month)
-{
- strcpy_P(buffer, (PGM_P)pgm_read_word(&(monthNames_P[month])));
- return buffer;
-}
-
-char* monthShortStr(uint8_t month)
-{
- for (int i=0; i < dt_SHORT_STR_LEN; i++)
- buffer[i] = pgm_read_byte(&(monthShortNames_P[i+ (month*dt_SHORT_STR_LEN)]));
- buffer[dt_SHORT_STR_LEN] = 0;
- return buffer;
-}
-
-char* dayStr(uint8_t day)
-{
- strcpy_P(buffer, (PGM_P)pgm_read_word(&(dayNames_P[day])));
- return buffer;
-}
-
-char* dayShortStr(uint8_t day)
-{
- uint8_t index = day*dt_SHORT_STR_LEN;
- for (int i=0; i < dt_SHORT_STR_LEN; i++)
- buffer[i] = pgm_read_byte(&(dayShortNames_P[index + i]));
- buffer[dt_SHORT_STR_LEN] = 0;
- return buffer;
-}
+++ /dev/null
-Readme file for Arduino Time Library
-
-Time is a library that provides timekeeping functionality for Arduino.
-
-The code is derived from the Playground DateTime library but is updated
-to provide an API that is more flexable and easier to use.
-
-A primary goal was to enable date and time functionality that can be used with
-a variety of external time sources with minimum differences required in sketch logic.
-
-Example sketches illustrate how similar sketch code can be used with: a Real Time Clock,
-internet NTP time service, GPS time data, and Serial time messages from a computer
-for time synchronization.
-
-The functions available in the library include:
-
-hour(); // the hour now (0-23)
-minute(); // the minute now (0-59)
-second(); // the second now (0-59)
-day(); // the day now (1-31)
-weekday(); // day of the week, Sunday is day 0
-month(); // the month now (1-12)
-year(); // the full four digit year: (2009, 2010 etc)
-
-there are also functions to return the hour in 12 hour format
-hourFormat12(); // the hour now in 12 hour format
-isAM(); // returns true if time now is AM
-isPM(); // returns true if time now is PM
-
-now(); // returns the current time as seconds since Jan 1 1970
-
-The time and date functions can take an optional parameter for the time. This prevents
-errors if the time rolls over between elements. For example, if a new minute begins
-between getting the minute and second, the values will be inconsistent. Using the
-following functions eliminates this probglem
- time_t t = now(); // store the current time in time variable t
- hour(t); // returns the hour for the given time t
- minute(t); // returns the minute for the given time t
- second(t); // returns the second for the given time t
- day(t); // the day for the given time t
- weekday(t); // day of the week for the given time t
- month(t); // the month for the given time t
- year(t); // the year for the given time t
-
-
-Functions for managing the timer services are:
-setTime(t); // set the system time to the give time t
-setTime(hr,min,sec,day,mnth,yr); // alternative to above, yr is 2 or 4 digit yr (2010 or 10 sets year to 2010)
-adjustTime(adjustment); // adjust system time by adding the adjustment value
-
-timeStatus(); // indicates if time has been set and recently synchronized
- // returns one of the following enumerations:
- timeNotSet // the time has never been set, the clock started at Jan 1 1970
- timeNeedsSync // the time had been set but a sync attempt did not succeed
- timeSet // the time is set and is synced
-Time and Date values are not valid if the status is timeNotSet. Otherwise values can be used but
-the returned time may have drifted if the status is timeNeedsSync.
-
-setSyncProvider(getTimeFunction); // set the external time provider
-setSyncInterval(interval); // set the number of seconds between re-sync
-
-
-There are many convenience macros in the time.h file for time constants and conversion of time units.
-
-To use the library, copy the download to the Library directory.
-
-The Time directory contains the Time library and some example sketches
-illustrating how the library can be used with various time sources:
-
-- TimeSerial.pde shows Arduino as a clock without external hardware.
- It is synchronized by time messages sent over the serial port.
- A companion Processing sketch will automatically provide these messages
- if it is running and connected to the Arduino serial port.
-
-- TimeSerialDateStrings.pde adds day and month name strings to the sketch above
- Short (3 character) and long strings are available to print the days of
- the week and names of the months.
-
-- TimeRTC uses a DS1307 real time clock to provide time synchronization.
- A basic RTC library named DS1307RTC is included in the download.
- To run this sketch the DS1307RTC library must be installed.
-
-- TimeRTCSet is similar to the above and adds the ability to set the Real Time Clock
-
-- TimeRTCLog demonstrates how to calculate the difference between times.
- It is a vary simple logger application that monitors events on digtial pins
- and prints (to the serial port) the time of an event and the time period since the previous event.
-
-- TimeNTP uses the Arduino Ethernet shield to access time using the internet NTP time service.
- The NTP protocol uses UDP and the UdpBytewise library is required, see:
- http://bitbucket.org/bjoern/arduino_osc/src/14667490521f/libraries/Ethernet/
-
-- TimeGPS gets time from a GPS
- This requires the TinyGPS library from Mikal Hart:
- http://arduiniana.org/libraries/TinyGPS
-
-Differences between this code and the playground DateTime library
-although the Time library is based on the DateTime codebase, the API has changed.
-Changes in the Time library API:
-- time elements are functions returning int (they are variables in DateTime)
-- Years start from 1970
-- days of the week and months start from 1 (they start from 0 in DateTime)
-- DateStrings do not require a seperate library
-- time elements can be accessed non-atomically (in DateTime they are always atomic)
-- function added to automatically sync time with extrnal source
-- localTime and maketime parameters changed, localTime renamed to breakTime
-
-Technical notes:
-
-Internal system time is based on the standard Unix time_t.
-The value is the number of seconds since Jan 1 1970.
-System time begins at zero when the sketch starts.
-
-The internal time can be automatically synchronized at regular intervals to an external time source.
-This is enabled by calling the setSyncProvider(provider) function - the provider argument is
-the address of a function that returns the current time as a time_t.
-See the sketches in the examples directory for usage.
-
-The default interval for re-syncing the time is 5 minutes but can be changed by calling the
-setSyncInterval( interval) method to set the number of seconds between re-sync attempts.
-
-The Time library defines a structure for holding time elements that is a compact version of the C tm structure.
-All the members of the Arduino tm structure are bytes and the year is offset from 1970.
-Convenience macros provide conversion to and from the Arduino format.
-
-Low level functions to convert between system time and individual time elements are provided:
- breakTime( time, &tm); // break time_t into elements stored in tm struct
- makeTime( &tm); // return time_t from elements stored in tm struct
-
-The DS1307RTC library included in the download provides an example of how a time provider
-can use the low level functions to interface with the Time library.
+++ /dev/null
-/*
- time.c - low level time and date functions
- Copyright (c) Michael Margolis 2009
-
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Lesser General Public
- License as published by the Free Software Foundation; either
- version 2.1 of the License, or (at your option) any later version.
-
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
- Lesser General Public License for more details.
-
- You should have received a copy of the GNU Lesser General Public
- License along with this library; if not, write to the Free Software
- Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
- 6 Jan 2010 - initial release
- 12 Feb 2010 - fixed leap year calculation error
- 1 Nov 2010 - fixed setTime bug (thanks to Korman for this)
- 24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update
- status, updated examples for Arduino 1.0, fixed ARM
- compatibility issues, added TimeArduinoDue and TimeTeensy3
- examples, add error checking and messages to RTC examples,
- add examples to DS1307RTC library.
-*/
-
-#if ARDUINO >= 100
-#include <Arduino.h>
-#else
-#include <WProgram.h>
-#endif
-
-#include "Time.h"
-
-static tmElements_t tm; // a cache of time elements
-static time_t cacheTime; // the time the cache was updated
-static uint32_t syncInterval = 300; // time sync will be attempted after this many seconds
-
-void refreshCache(time_t t) {
- if (t != cacheTime) {
- breakTime(t, tm);
- cacheTime = t;
- }
-}
-
-int hour() { // the hour now
- return hour(now());
-}
-
-int hour(time_t t) { // the hour for the given time
- refreshCache(t);
- return tm.Hour;
-}
-
-int hourFormat12() { // the hour now in 12 hour format
- return hourFormat12(now());
-}
-
-int hourFormat12(time_t t) { // the hour for the given time in 12 hour format
- refreshCache(t);
- if( tm.Hour == 0 )
- return 12; // 12 midnight
- else if( tm.Hour > 12)
- return tm.Hour - 12 ;
- else
- return tm.Hour ;
-}
-
-uint8_t isAM() { // returns true if time now is AM
- return !isPM(now());
-}
-
-uint8_t isAM(time_t t) { // returns true if given time is AM
- return !isPM(t);
-}
-
-uint8_t isPM() { // returns true if PM
- return isPM(now());
-}
-
-uint8_t isPM(time_t t) { // returns true if PM
- return (hour(t) >= 12);
-}
-
-int minute() {
- return minute(now());
-}
-
-int minute(time_t t) { // the minute for the given time
- refreshCache(t);
- return tm.Minute;
-}
-
-int second() {
- return second(now());
-}
-
-int second(time_t t) { // the second for the given time
- refreshCache(t);
- return tm.Second;
-}
-
-int day(){
- return(day(now()));
-}
-
-int day(time_t t) { // the day for the given time (0-6)
- refreshCache(t);
- return tm.Day;
-}
-
-int weekday() { // Sunday is day 1
- return weekday(now());
-}
-
-int weekday(time_t t) {
- refreshCache(t);
- return tm.Wday;
-}
-
-int month(){
- return month(now());
-}
-
-int month(time_t t) { // the month for the given time
- refreshCache(t);
- return tm.Month;
-}
-
-int year() { // as in Processing, the full four digit year: (2009, 2010 etc)
- return year(now());
-}
-
-int year(time_t t) { // the year for the given time
- refreshCache(t);
- return tmYearToCalendar(tm.Year);
-}
-
-/*============================================================================*/
-/* functions to convert to and from system time */
-/* These are for interfacing with time serivces and are not normally needed in a sketch */
-
-// leap year calulator expects year argument as years offset from 1970
-#define LEAP_YEAR(Y) ( ((1970+Y)>0) && !((1970+Y)%4) && ( ((1970+Y)%100) || !((1970+Y)%400) ) )
-
-static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
-
-void breakTime(time_t timeInput, tmElements_t &tm){
-// break the given time_t into time components
-// this is a more compact version of the C library localtime function
-// note that year is offset from 1970 !!!
-
- uint8_t year;
- uint8_t month, monthLength;
- uint32_t time;
- unsigned long days;
-
- time = (uint32_t)timeInput;
- tm.Second = time % 60;
- time /= 60; // now it is minutes
- tm.Minute = time % 60;
- time /= 60; // now it is hours
- tm.Hour = time % 24;
- time /= 24; // now it is days
- tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1
-
- year = 0;
- days = 0;
- while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
- year++;
- }
- tm.Year = year; // year is offset from 1970
-
- days -= LEAP_YEAR(year) ? 366 : 365;
- time -= days; // now it is days in this year, starting at 0
-
- days=0;
- month=0;
- monthLength=0;
- for (month=0; month<12; month++) {
- if (month==1) { // february
- if (LEAP_YEAR(year)) {
- monthLength=29;
- } else {
- monthLength=28;
- }
- } else {
- monthLength = monthDays[month];
- }
-
- if (time >= monthLength) {
- time -= monthLength;
- } else {
- break;
- }
- }
- tm.Month = month + 1; // jan is month 1
- tm.Day = time + 1; // day of month
-}
-
-time_t makeTime(tmElements_t &tm){
-// assemble time elements into time_t
-// note year argument is offset from 1970 (see macros in time.h to convert to other formats)
-// previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
-
- int i;
- uint32_t seconds;
-
- // seconds from 1970 till 1 jan 00:00:00 of the given year
- seconds= tm.Year*(SECS_PER_DAY * 365);
- for (i = 0; i < tm.Year; i++) {
- if (LEAP_YEAR(i)) {
- seconds += SECS_PER_DAY; // add extra days for leap years
- }
- }
-
- // add days for this year, months start from 1
- for (i = 1; i < tm.Month; i++) {
- if ( (i == 2) && LEAP_YEAR(tm.Year)) {
- seconds += SECS_PER_DAY * 29;
- } else {
- seconds += SECS_PER_DAY * monthDays[i-1]; //monthDay array starts from 0
- }
- }
- seconds+= (tm.Day-1) * SECS_PER_DAY;
- seconds+= tm.Hour * SECS_PER_HOUR;
- seconds+= tm.Minute * SECS_PER_MIN;
- seconds+= tm.Second;
- return (time_t)seconds;
-}
-/*=====================================================*/
-/* Low level system time functions */
-
-static uint32_t sysTime = 0;
-static uint32_t prevMillis = 0;
-static uint32_t nextSyncTime = 0;
-static timeStatus_t Status = timeNotSet;
-
-getExternalTime getTimePtr; // pointer to external sync function
-//setExternalTime setTimePtr; // not used in this version
-
-#ifdef TIME_DRIFT_INFO // define this to get drift data
-time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync
-#endif
-
-
-time_t now() {
- while (millis() - prevMillis >= 1000){
- sysTime++;
- prevMillis += 1000;
-#ifdef TIME_DRIFT_INFO
- sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift
-#endif
- }
- if (nextSyncTime <= sysTime) {
- if (getTimePtr != 0) {
- time_t t = getTimePtr();
- if (t != 0) {
- setTime(t);
- } else {
- nextSyncTime = sysTime + syncInterval;
- Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
- }
- }
- }
- return (time_t)sysTime;
-}
-
-void setTime(time_t t) {
-#ifdef TIME_DRIFT_INFO
- if(sysUnsyncedTime == 0)
- sysUnsyncedTime = t; // store the time of the first call to set a valid Time
-#endif
-
- sysTime = (uint32_t)t;
- nextSyncTime = (uint32_t)t + syncInterval;
- Status = timeSet;
- prevMillis = millis(); // restart counting from now (thanks to Korman for this fix)
-}
-
-void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
- // year can be given as full four digit year or two digts (2010 or 10 for 2010);
- //it is converted to years since 1970
- if( yr > 99)
- yr = yr - 1970;
- else
- yr += 30;
- tm.Year = yr;
- tm.Month = mnth;
- tm.Day = dy;
- tm.Hour = hr;
- tm.Minute = min;
- tm.Second = sec;
- setTime(makeTime(tm));
-}
-
-void adjustTime(long adjustment) {
- sysTime += adjustment;
-}
-
-// indicates if time has been set and recently synchronized
-timeStatus_t timeStatus() {
- now(); // required to actually update the status
- return Status;
-}
-
-void setSyncProvider( getExternalTime getTimeFunction){
- getTimePtr = getTimeFunction;
- nextSyncTime = sysTime;
- now(); // this will sync the clock
-}
-
-void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
- syncInterval = (uint32_t)interval;
- nextSyncTime = sysTime + syncInterval;
-}
+++ /dev/null
-/*
- time.h - low level time and date functions
-*/
-
-/*
- July 3 2011 - fixed elapsedSecsThisWeek macro (thanks Vincent Valdy for this)
- - fixed daysToTime_t macro (thanks maniacbug)
-*/
-
-#ifndef _Time_h
-#ifdef __cplusplus
-#define _Time_h
-
-#include <inttypes.h>
-#ifndef __AVR__
-#include <sys/types.h> // for __time_t_defined, but avr libc lacks sys/types.h
-#endif
-
-
-#if !defined(__time_t_defined) // avoid conflict with newlib or other posix libc
-typedef unsigned long time_t;
-#endif
-
-
-// This ugly hack allows us to define C++ overloaded functions, when included
-// from within an extern "C", as newlib's sys/stat.h does. Actually it is
-// intended to include "time.h" from the C library (on ARM, but AVR does not
-// have that file at all). On Mac and Windows, the compiler will find this
-// "Time.h" instead of the C library "time.h", so we may cause other weird
-// and unpredictable effects by conflicting with the C library header "time.h",
-// but at least this hack lets us define C++ functions as intended. Hopefully
-// nothing too terrible will result from overriding the C library header?!
-extern "C++" {
-typedef enum {timeNotSet, timeNeedsSync, timeSet
-} timeStatus_t ;
-
-typedef enum {
- dowInvalid, dowSunday, dowMonday, dowTuesday, dowWednesday, dowThursday, dowFriday, dowSaturday
-} timeDayOfWeek_t;
-
-typedef enum {
- tmSecond, tmMinute, tmHour, tmWday, tmDay,tmMonth, tmYear, tmNbrFields
-} tmByteFields;
-
-typedef struct {
- uint8_t Second;
- uint8_t Minute;
- uint8_t Hour;
- uint8_t Wday; // day of week, sunday is day 1
- uint8_t Day;
- uint8_t Month;
- uint8_t Year; // offset from 1970;
-} tmElements_t, TimeElements, *tmElementsPtr_t;
-
-//convenience macros to convert to and from tm years
-#define tmYearToCalendar(Y) ((Y) + 1970) // full four digit year
-#define CalendarYrToTm(Y) ((Y) - 1970)
-#define tmYearToY2k(Y) ((Y) - 30) // offset is from 2000
-#define y2kYearToTm(Y) ((Y) + 30)
-
-typedef time_t(*getExternalTime)();
-//typedef void (*setExternalTime)(const time_t); // not used in this version
-
-
-/*==============================================================================*/
-/* Useful Constants */
-#define SECS_PER_MIN (60UL)
-#define SECS_PER_HOUR (3600UL)
-#define SECS_PER_DAY (SECS_PER_HOUR * 24UL)
-#define DAYS_PER_WEEK (7UL)
-#define SECS_PER_WEEK (SECS_PER_DAY * DAYS_PER_WEEK)
-#define SECS_PER_YEAR (SECS_PER_WEEK * 52UL)
-#define SECS_YR_2000 (946684800UL) // the time at the start of y2k
-
-/* Useful Macros for getting elapsed time */
-#define numberOfSeconds(_time_) (_time_ % SECS_PER_MIN)
-#define numberOfMinutes(_time_) ((_time_ / SECS_PER_MIN) % SECS_PER_MIN)
-#define numberOfHours(_time_) (( _time_% SECS_PER_DAY) / SECS_PER_HOUR)
-#define dayOfWeek(_time_) ((( _time_ / SECS_PER_DAY + 4) % DAYS_PER_WEEK)+1) // 1 = Sunday
-#define elapsedDays(_time_) ( _time_ / SECS_PER_DAY) // this is number of days since Jan 1 1970
-#define elapsedSecsToday(_time_) (_time_ % SECS_PER_DAY) // the number of seconds since last midnight
-// The following macros are used in calculating alarms and assume the clock is set to a date later than Jan 1 1971
-// Always set the correct time before settting alarms
-#define previousMidnight(_time_) (( _time_ / SECS_PER_DAY) * SECS_PER_DAY) // time at the start of the given day
-#define nextMidnight(_time_) ( previousMidnight(_time_) + SECS_PER_DAY ) // time at the end of the given day
-#define elapsedSecsThisWeek(_time_) (elapsedSecsToday(_time_) + ((dayOfWeek(_time_)-1) * SECS_PER_DAY) ) // note that week starts on day 1
-#define previousSunday(_time_) (_time_ - elapsedSecsThisWeek(_time_)) // time at the start of the week for the given time
-#define nextSunday(_time_) ( previousSunday(_time_)+SECS_PER_WEEK) // time at the end of the week for the given time
-
-
-/* Useful Macros for converting elapsed time to a time_t */
-#define minutesToTime_t ((M)) ( (M) * SECS_PER_MIN)
-#define hoursToTime_t ((H)) ( (H) * SECS_PER_HOUR)
-#define daysToTime_t ((D)) ( (D) * SECS_PER_DAY) // fixed on Jul 22 2011
-#define weeksToTime_t ((W)) ( (W) * SECS_PER_WEEK)
-
-/*============================================================================*/
-/* time and date functions */
-int hour(); // the hour now
-int hour(time_t t); // the hour for the given time
-int hourFormat12(); // the hour now in 12 hour format
-int hourFormat12(time_t t); // the hour for the given time in 12 hour format
-uint8_t isAM(); // returns true if time now is AM
-uint8_t isAM(time_t t); // returns true the given time is AM
-uint8_t isPM(); // returns true if time now is PM
-uint8_t isPM(time_t t); // returns true the given time is PM
-int minute(); // the minute now
-int minute(time_t t); // the minute for the given time
-int second(); // the second now
-int second(time_t t); // the second for the given time
-int day(); // the day now
-int day(time_t t); // the day for the given time
-int weekday(); // the weekday now (Sunday is day 1)
-int weekday(time_t t); // the weekday for the given time
-int month(); // the month now (Jan is month 1)
-int month(time_t t); // the month for the given time
-int year(); // the full four digit year: (2009, 2010 etc)
-int year(time_t t); // the year for the given time
-
-time_t now(); // return the current time as seconds since Jan 1 1970
-void setTime(time_t t);
-void setTime(int hr,int min,int sec,int day, int month, int yr);
-void adjustTime(long adjustment);
-
-/* date strings */
-#define dt_MAX_STRING_LEN 9 // length of longest date string (excluding terminating null)
-char* monthStr(uint8_t month);
-char* dayStr(uint8_t day);
-char* monthShortStr(uint8_t month);
-char* dayShortStr(uint8_t day);
-
-/* time sync functions */
-timeStatus_t timeStatus(); // indicates if time has been set and recently synchronized
-void setSyncProvider( getExternalTime getTimeFunction); // identify the external time provider
-void setSyncInterval(time_t interval); // set the number of seconds between re-sync
-
-/* low level functions to convert to and from system time */
-void breakTime(time_t time, tmElements_t &tm); // break time_t into elements
-time_t makeTime(tmElements_t &tm); // convert time elements into time_t
-
-} // extern "C++"
-#endif // __cplusplus
-#endif /* _Time_h */
-
+++ /dev/null
-/**
- * SyncArduinoClock.
- *
- * portIndex must be set to the port connected to the Arduino
- *
- * The current time is sent in response to request message from Arduino
- * or by clicking the display window
- *
- * The time message is 11 ASCII text characters; a header (the letter 'T')
- * followed by the ten digit system time (unix time)
- */
-
-
-import processing.serial.*;
-import java.util.Date;
-import java.util.Calendar;
-import java.util.GregorianCalendar;
-
-public static final short portIndex = 0; // select the com port, 0 is the first port
-public static final String TIME_HEADER = "T"; //header for arduino serial time message
-public static final char TIME_REQUEST = 7; // ASCII bell character
-public static final char LF = 10; // ASCII linefeed
-public static final char CR = 13; // ASCII linefeed
-Serial myPort; // Create object from Serial class
-
-void setup() {
- size(200, 200);
- println(Serial.list());
- println(" Connecting to -> " + Serial.list()[portIndex]);
- myPort = new Serial(this,Serial.list()[portIndex], 9600);
- println(getTimeNow());
-}
-
-void draw()
-{
- textSize(20);
- textAlign(CENTER);
- fill(0);
- text("Click to send\nTime Sync", 0, 75, 200, 175);
- if ( myPort.available() > 0) { // If data is available,
- char val = char(myPort.read()); // read it and store it in val
- if(val == TIME_REQUEST){
- long t = getTimeNow();
- sendTimeMessage(TIME_HEADER, t);
- }
- else
- {
- if(val == LF)
- ; //igonore
- else if(val == CR)
- println();
- else
- print(val); // echo everying but time request
- }
- }
-}
-
-void mousePressed() {
- sendTimeMessage( TIME_HEADER, getTimeNow());
-}
-
-
-void sendTimeMessage(String header, long time) {
- String timeStr = String.valueOf(time);
- myPort.write(header); // send header and time to arduino
- myPort.write(timeStr);
- myPort.write('\n');
-}
-
-long getTimeNow(){
- // java time is in ms, we want secs
- Date d = new Date();
- Calendar cal = new GregorianCalendar();
- long current = d.getTime()/1000;
- long timezone = cal.get(cal.ZONE_OFFSET)/1000;
- long daylight = cal.get(cal.DST_OFFSET)/1000;
- return current + timezone + daylight;
-}
+++ /dev/null
-SyncArduinoClock is a Processing sketch that responds to Arduino requests for
-time synchronization messages.
-
-The portIndex must be set the Serial port connected to Arduino.
-
-Download TimeSerial.pde onto Arduino and you should see the time
-message displayed when you run SyncArduinoClock in Processing.
-The Arduino time is set from the time on your computer through the
-Processing sketch.
+++ /dev/null
-/*
- * TimeRTC.pde
- * example code illustrating Time library with Real Time Clock.
- *
- * This example requires Markus Lange's Arduino Due RTC Library
- * https://github.com/MarkusLange/Arduino-Due-RTC-Library
- */
-
-#include <Time.h>
-#include <rtc_clock.h>
-
-// Select the Slowclock source
-//RTC_clock rtc_clock(RC);
-RTC_clock rtc_clock(XTAL);
-
-void setup() {
- Serial.begin(9600);
- rtc_clock.init();
- if (rtc_clock.date_already_set() == 0) {
- // Unfortunately, the Arduino Due hardware does not seem to
- // be designed to maintain the RTC clock state when the
- // board resets. Markus described it thusly: "Uhh the Due
- // does reset with the NRSTB pin. This resets the full chip
- // with all backup regions including RTC, RTT and SC. Only
- // if the reset is done with the NRST pin will these regions
- // stay with their old values."
- rtc_clock.set_time(__TIME__);
- rtc_clock.set_date(__DATE__);
- }
- setSyncProvider(getArduinoDueTime);
- if(timeStatus()!= timeSet)
- Serial.println("Unable to sync with the RTC");
- else
- Serial.println("RTC has set the system time");
-}
-
-time_t getArduinoDueTime()
-{
- return rtc_clock.unixtime();
-}
-
-void loop()
-{
- digitalClockDisplay();
- delay(1000);
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
+++ /dev/null
-/*
- * TimeGPS.pde
- * example code illustrating time synced from a GPS
- *
- */
-
-#include <Time.h>
-#include <TinyGPS.h> // http://arduiniana.org/libraries/TinyGPS/
-#include <SoftwareSerial.h>
-// TinyGPS and SoftwareSerial libraries are the work of Mikal Hart
-
-SoftwareSerial SerialGPS = SoftwareSerial(10, 11); // receive on pin 10
-TinyGPS gps;
-
-// To use a hardware serial port, which is far more efficient than
-// SoftwareSerial, uncomment this line and remove SoftwareSerial
-//#define SerialGPS Serial1
-
-// Offset hours from gps time (UTC)
-const int offset = 1; // Central European Time
-//const int offset = -5; // Eastern Standard Time (USA)
-//const int offset = -4; // Eastern Daylight Time (USA)
-//const int offset = -8; // Pacific Standard Time (USA)
-//const int offset = -7; // Pacific Daylight Time (USA)
-
-// Ideally, it should be possible to learn the time zone
-// based on the GPS position data. However, that would
-// require a complex library, probably incorporating some
-// sort of database using Eric Muller's time zone shape
-// maps, at http://efele.net/maps/tz/
-
-time_t prevDisplay = 0; // when the digital clock was displayed
-
-void setup()
-{
- Serial.begin(9600);
- while (!Serial) ; // Needed for Leonardo only
- SerialGPS.begin(4800);
- Serial.println("Waiting for GPS time ... ");
-}
-
-void loop()
-{
- while (SerialGPS.available()) {
- if (gps.encode(SerialGPS.read())) { // process gps messages
- // when TinyGPS reports new data...
- unsigned long age;
- int Year;
- byte Month, Day, Hour, Minute, Second;
- gps.crack_datetime(&Year, &Month, &Day, &Hour, &Minute, &Second, NULL, &age);
- if (age < 500) {
- // set the Time to the latest GPS reading
- setTime(Hour, Minute, Second, Day, Month, Year);
- adjustTime(offset * SECS_PER_HOUR);
- }
- }
- }
- if (timeStatus()!= timeNotSet) {
- if (now() != prevDisplay) { //update the display only if the time has changed
- prevDisplay = now();
- digitalClockDisplay();
- }
- }
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits) {
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
+++ /dev/null
-/*
- * Time_NTP.pde
- * Example showing time sync to NTP time source
- *
- * This sketch uses the Ethernet library
- */
-
-#include <Time.h>
-#include <Ethernet.h>
-#include <EthernetUdp.h>
-#include <SPI.h>
-
-byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
-// NTP Servers:
-IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov
-// IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov
-// IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov
-
-
-const int timeZone = 1; // Central European Time
-//const int timeZone = -5; // Eastern Standard Time (USA)
-//const int timeZone = -4; // Eastern Daylight Time (USA)
-//const int timeZone = -8; // Pacific Standard Time (USA)
-//const int timeZone = -7; // Pacific Daylight Time (USA)
-
-
-EthernetUDP Udp;
-unsigned int localPort = 8888; // local port to listen for UDP packets
-
-void setup()
-{
- Serial.begin(9600);
- while (!Serial) ; // Needed for Leonardo only
- delay(250);
- Serial.println("TimeNTP Example");
- if (Ethernet.begin(mac) == 0) {
- // no point in carrying on, so do nothing forevermore:
- while (1) {
- Serial.println("Failed to configure Ethernet using DHCP");
- delay(10000);
- }
- }
- Serial.print("IP number assigned by DHCP is ");
- Serial.println(Ethernet.localIP());
- Udp.begin(localPort);
- Serial.println("waiting for sync");
- setSyncProvider(getNtpTime);
-}
-
-time_t prevDisplay = 0; // when the digital clock was displayed
-
-void loop()
-{
- if (timeStatus() != timeNotSet) {
- if (now() != prevDisplay) { //update the display only if time has changed
- prevDisplay = now();
- digitalClockDisplay();
- }
- }
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits){
- // utility for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
-/*-------- NTP code ----------*/
-
-const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
-byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
-
-time_t getNtpTime()
-{
- while (Udp.parsePacket() > 0) ; // discard any previously received packets
- Serial.println("Transmit NTP Request");
- sendNTPpacket(timeServer);
- uint32_t beginWait = millis();
- while (millis() - beginWait < 1500) {
- int size = Udp.parsePacket();
- if (size >= NTP_PACKET_SIZE) {
- Serial.println("Receive NTP Response");
- Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
- unsigned long secsSince1900;
- // convert four bytes starting at location 40 to a long integer
- secsSince1900 = (unsigned long)packetBuffer[40] << 24;
- secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
- secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
- secsSince1900 |= (unsigned long)packetBuffer[43];
- return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
- }
- }
- Serial.println("No NTP Response :-(");
- return 0; // return 0 if unable to get the time
-}
-
-// send an NTP request to the time server at the given address
-void sendNTPpacket(IPAddress &address)
-{
- // set all bytes in the buffer to 0
- memset(packetBuffer, 0, NTP_PACKET_SIZE);
- // Initialize values needed to form NTP request
- // (see URL above for details on the packets)
- packetBuffer[0] = 0b11100011; // LI, Version, Mode
- packetBuffer[1] = 0; // Stratum, or type of clock
- packetBuffer[2] = 6; // Polling Interval
- packetBuffer[3] = 0xEC; // Peer Clock Precision
- // 8 bytes of zero for Root Delay & Root Dispersion
- packetBuffer[12] = 49;
- packetBuffer[13] = 0x4E;
- packetBuffer[14] = 49;
- packetBuffer[15] = 52;
- // all NTP fields have been given values, now
- // you can send a packet requesting a timestamp:
- Udp.beginPacket(address, 123); //NTP requests are to port 123
- Udp.write(packetBuffer, NTP_PACKET_SIZE);
- Udp.endPacket();
-}
-
+++ /dev/null
-/*
- * TimeRTC.pde
- * example code illustrating Time library with Real Time Clock.
- *
- */
-
-#include <Time.h>
-#include <Wire.h>
-#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) ; // wait until Arduino Serial Monitor opens
- setSyncProvider(RTC.get); // the function to get the time from the RTC
- if(timeStatus()!= timeSet)
- Serial.println("Unable to sync with the RTC");
- else
- Serial.println("RTC has set the system time");
-}
-
-void loop()
-{
- if (timeStatus() == timeSet) {
- digitalClockDisplay();
- } else {
- Serial.println("The time has not been set. Please run the Time");
- Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
- Serial.println();
- delay(4000);
- }
- delay(1000);
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
+++ /dev/null
-/*
- * TimeRTCLogger.pde
- * example code illustrating adding and subtracting Time.
- *
- * this sketch logs pin state change events
- * the time of the event and time since the previous event is calculated and sent to the serial port.
- */
-
-#include <Time.h>
-#include <Wire.h>
-#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
-
-const int nbrInputPins = 6; // monitor 6 digital pins
-const int inputPins[nbrInputPins] = {2,3,4,5,6,7}; // pins to monitor
-boolean state[nbrInputPins] ; // the state of the monitored pins
-time_t prevEventTime[nbrInputPins] ; // the time of the previous event
-
-void setup() {
- Serial.begin(9600);
- setSyncProvider(RTC.get); // the function to sync the time from the RTC
- for(int i=0; i < nbrInputPins; i++){
- pinMode( inputPins[i], INPUT);
- // uncomment these lines if pull-up resistors are wanted
- // pinMode( inputPins[i], INPUT_PULLUP);
- // state[i] = HIGH;
- }
-}
-
-void loop()
-{
- for(int i=0; i < nbrInputPins; i++)
- {
- boolean val = digitalRead(inputPins[i]);
- if(val != state[i])
- {
- time_t duration = 0; // the time since the previous event
- state[i] = val;
- time_t timeNow = now();
- if(prevEventTime[i] > 0)
- // if this was not the first state change, calculate the time from the previous change
- duration = duration = timeNow - prevEventTime[i];
- logEvent(inputPins[i], val, timeNow, duration ); // log the event
- prevEventTime[i] = timeNow; // store the time for this event
- }
- }
-}
-
-void logEvent( int pin, boolean state, time_t timeNow, time_t duration)
-{
- Serial.print("Pin ");
- Serial.print(pin);
- if( state == HIGH)
- Serial.print(" went High at ");
- else
- Serial.print(" went Low at ");
- showTime(timeNow);
- if(duration > 0){
- // only display duration if greater than 0
- Serial.print(", Duration was ");
- showDuration(duration);
- }
- Serial.println();
-}
-
-
-void showTime(time_t t){
- // display the given time
- Serial.print(hour(t));
- printDigits(minute(t));
- printDigits(second(t));
- Serial.print(" ");
- Serial.print(day(t));
- Serial.print(" ");
- Serial.print(month(t));
- Serial.print(" ");
- Serial.print(year(t));
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
-void showDuration(time_t duration){
-// prints the duration in days, hours, minutes and seconds
- if(duration >= SECS_PER_DAY){
- Serial.print(duration / SECS_PER_DAY);
- Serial.print(" day(s) ");
- duration = duration % SECS_PER_DAY;
- }
- if(duration >= SECS_PER_HOUR){
- Serial.print(duration / SECS_PER_HOUR);
- Serial.print(" hour(s) ");
- duration = duration % SECS_PER_HOUR;
- }
- if(duration >= SECS_PER_MIN){
- Serial.print(duration / SECS_PER_MIN);
- Serial.print(" minute(s) ");
- duration = duration % SECS_PER_MIN;
- }
- Serial.print(duration);
- Serial.print(" second(s) ");
-}
-
+++ /dev/null
-/*
- * TimeRTCSet.pde
- * example code illustrating Time library with Real Time Clock.
- *
- * RTC clock is set in response to serial port time message
- * A Processing example sketch to set the time is included in the download
- * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
- */
-
-#include <Time.h>
-#include <Wire.h>
-#include <DS1307RTC.h> // a basic DS1307 library that returns time as a time_t
-
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) ; // Needed for Leonardo only
- setSyncProvider(RTC.get); // the function to get the time from the RTC
- if (timeStatus() != timeSet)
- Serial.println("Unable to sync with the RTC");
- else
- Serial.println("RTC has set the system time");
-}
-
-void loop()
-{
- if (Serial.available()) {
- time_t t = processSyncMessage();
- if (t != 0) {
- RTC.set(t); // set the RTC and the system time to the received value
- setTime(t);
- }
- }
- digitalClockDisplay();
- delay(1000);
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
-/* code to process time sync messages from the serial port */
-#define TIME_HEADER "T" // Header tag for serial time sync message
-
-unsigned long processSyncMessage() {
- unsigned long pctime = 0L;
- const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-
- if(Serial.find(TIME_HEADER)) {
- pctime = Serial.parseInt();
- return pctime;
- if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
- pctime = 0L; // return 0 to indicate that the time is not valid
- }
- }
- return pctime;
-}
-
-
-
-
-
+++ /dev/null
-/*
- * TimeSerial.pde
- * example code illustrating Time library set through serial port messages.
- *
- * Messages consist of the letter T followed by ten digit time (as seconds since Jan 1 1970)
- * you can send the text on the next line using Serial Monitor to set the clock to noon Jan 1 2013
- T1357041600
- *
- * A Processing example sketch to automatically send the messages is inclided in the download
- * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
- */
-
-#include <Time.h>
-
-#define TIME_HEADER "T" // Header tag for serial time sync message
-#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) ; // Needed for Leonardo only
- pinMode(13, OUTPUT);
- setSyncProvider( requestSync); //set function to call when sync required
- Serial.println("Waiting for sync message");
-}
-
-void loop(){
- if (Serial.available()) {
- processSyncMessage();
- }
- if (timeStatus()!= timeNotSet) {
- digitalClockDisplay();
- }
- if (timeStatus() == timeSet) {
- digitalWrite(13, HIGH); // LED on if synced
- } else {
- digitalWrite(13, LOW); // LED off if needs refresh
- }
- delay(1000);
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
-
-void processSyncMessage() {
- unsigned long pctime;
- const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-
- if(Serial.find(TIME_HEADER)) {
- pctime = Serial.parseInt();
- if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
- setTime(pctime); // Sync Arduino clock to the time received on the serial port
- }
- }
-}
-
-time_t requestSync()
-{
- Serial.write(TIME_REQUEST);
- return 0; // the time will be sent later in response to serial mesg
-}
-
+++ /dev/null
-/*
- * TimeSerialDateStrings.pde
- * example code illustrating Time library date strings
- *
- * This sketch adds date string functionality to TimeSerial sketch
- * Also shows how to handle different messages
- *
- * A message starting with a time header sets the time
- * A Processing example sketch to automatically send the messages is inclided in the download
- * On Linux, you can use "date +T%s > /dev/ttyACM0" (UTC time zone)
- *
- * A message starting with a format header sets the date format
- *
- * send: Fs\n for short date format
- * send: Fl\n for long date format
- */
-
-#include <Time.h>
-
-// single character message tags
-#define TIME_HEADER 'T' // Header tag for serial time sync message
-#define FORMAT_HEADER 'F' // Header tag indicating a date format message
-#define FORMAT_SHORT 's' // short month and day strings
-#define FORMAT_LONG 'l' // (lower case l) long month and day strings
-
-#define TIME_REQUEST 7 // ASCII bell character requests a time sync message
-
-static boolean isLongFormat = true;
-
-void setup() {
- Serial.begin(9600);
- while (!Serial) ; // Needed for Leonardo only
- setSyncProvider( requestSync); //set function to call when sync required
- Serial.println("Waiting for sync message");
-}
-
-void loop(){
- if (Serial.available()) {
- char c = Serial.read();
- if( c == TIME_HEADER) {
- processSyncMessage();
- }
- else if( c== FORMAT_HEADER) {
- processFormatMessage();
- }
- }
- if (timeStatus()!= timeNotSet) {
- digitalClockDisplay();
- }
- delay(1000);
-}
-
-void digitalClockDisplay(){
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- if(isLongFormat)
- Serial.print(dayStr(weekday()));
- else
- Serial.print(dayShortStr(weekday()));
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- if(isLongFormat)
- Serial.print(monthStr(month()));
- else
- Serial.print(monthShortStr(month()));
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
-void processFormatMessage() {
- char c = Serial.read();
- if( c == FORMAT_LONG){
- isLongFormat = true;
- Serial.println("Setting long format");
- }
- else if( c == FORMAT_SHORT){
- isLongFormat = false;
- Serial.println("Setting short format");
- }
-}
-
-void processSyncMessage() {
- unsigned long pctime;
- const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013 - paul, perhaps we define in time.h?
-
- pctime = Serial.parseInt();
- if( pctime >= DEFAULT_TIME) { // check the integer is a valid time (greater than Jan 1 2013)
- setTime(pctime); // Sync Arduino clock to the time received on the serial port
- }
-}
-
-time_t requestSync()
-{
- Serial.write(TIME_REQUEST);
- return 0; // the time will be sent later in response to serial mesg
-}
-
+++ /dev/null
-/*
- * TimeRTC.pde
- * example code illustrating Time library with Real Time Clock.
- *
- */
-
-#include <Time.h>
-
-void setup() {
- // set the Time library to use Teensy 3.0's RTC to keep time
- setSyncProvider(getTeensy3Time);
-
- Serial.begin(115200);
- while (!Serial); // Wait for Arduino Serial Monitor to open
- delay(100);
- if (timeStatus()!= timeSet) {
- Serial.println("Unable to sync with the RTC");
- } else {
- Serial.println("RTC has set the system time");
- }
-}
-
-void loop() {
- if (Serial.available()) {
- time_t t = processSyncMessage();
- if (t != 0) {
- Teensy3Clock.set(t); // set the RTC
- setTime(t);
- }
- }
- digitalClockDisplay();
- delay(1000);
-}
-
-void digitalClockDisplay() {
- // digital clock display of the time
- Serial.print(hour());
- printDigits(minute());
- printDigits(second());
- Serial.print(" ");
- Serial.print(day());
- Serial.print(" ");
- Serial.print(month());
- Serial.print(" ");
- Serial.print(year());
- Serial.println();
-}
-
-time_t getTeensy3Time()
-{
- return Teensy3Clock.get();
-}
-
-/* code to process time sync messages from the serial port */
-#define TIME_HEADER "T" // Header tag for serial time sync message
-
-unsigned long processSyncMessage() {
- unsigned long pctime = 0L;
- const unsigned long DEFAULT_TIME = 1357041600; // Jan 1 2013
-
- if(Serial.find(TIME_HEADER)) {
- pctime = Serial.parseInt();
- return pctime;
- if( pctime < DEFAULT_TIME) { // check the value is a valid time (greater than Jan 1 2013)
- pctime = 0L; // return 0 to indicate that the time is not valid
- }
- }
- return pctime;
-}
-
-void printDigits(int digits){
- // utility function for digital clock display: prints preceding colon and leading 0
- Serial.print(":");
- if(digits < 10)
- Serial.print('0');
- Serial.print(digits);
-}
-
+++ /dev/null
-#######################################
-# Syntax Coloring Map For Time
-#######################################
-
-#######################################
-# Datatypes (KEYWORD1)
-#######################################
-time_t KEYWORD1
-#######################################
-# Methods and Functions (KEYWORD2)
-#######################################
-now KEYWORD2
-second KEYWORD2
-minute KEYWORD2
-hour KEYWORD2
-day KEYWORD2
-month KEYWORD2
-year KEYWORD2
-isAM KEYWORD2
-isPM KEYWORD2
-weekday KEYWORD2
-setTime KEYWORD2
-adjustTime KEYWORD2
-setSyncProvider KEYWORD2
-setSyncInterval KEYWORD2
-timeStatus KEYWORD2
-#######################################
-# Instances (KEYWORD2)
-#######################################
-
-#######################################
-# Constants (LITERAL1)
-#######################################
+++ /dev/null
-#ARDUINO_DIR = /home/choi/devel/arduino-1.0.5
-ARDUINO_DIR = /usr/share/arduino
-#ARDUINO_TOOLS_DIR = $(ARDUINO_DIR)/hardware/tools/avr/bin
-CC=avr-g++
-CCPLUS=avr-g++
-AR=avr-ar
-RANLIB=avr-ranlib
\ No newline at end of file
+++ /dev/null
-CC=avr-gcc
-CCPLUS=avr-g++
-AR=avr-ar
-RANLIB=avr-ranlib
-
-APP_NAME := thserver
-#BUILD := release
-BUILD := debug
-ARDUINO_PORT := /dev/ttyACM0
-
-OBJ_DIR := ./bin
-
-TB_DIR = ../../../../oic-resource_a/csdk
-
-include $(TB_DIR)/local.properties
-CC=avr-gcc
-LOGGER_DIR = $(TB_DIR)/logger
-TBSTACK_DIR = $(TB_DIR)/stack
-TBSOCKET_DIR = $(TB_DIR)/ocsocket
-
-#Source directories
-SDIR_ARD_CORE = $(ARDUINO_DIR)/hardware/arduino/cores/arduino
-SDIR_ARD_SPI = $(ARDUINO_DIR)/libraries/SPI
-SDIR_ARD_ETH = $(ARDUINO_DIR)/libraries/Ethernet
-SDIR_ARD_ETH_UTIL = $(ARDUINO_DIR)/libraries/Ethernet/utility
-SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time
-
-VPATH := $(SDIR_ARD_CORE):$(SDIR_ARD_SPI):$(SDIR_ARD_ETH):$(SDIR_ARD_ETH_UTIL):$(OCSOCK_DIR)/src
-
-#include directories
-INCD_ARD_CORE = -I$(ARDUINO_DIR)/hardware/arduino/cores/arduino
-INCD_ARD_VARIANT = -I$(ARDUINO_DIR)/hardware/arduino/variants/mega
-INCD_ARD_SPI = -I$(ARDUINO_DIR)/libraries/SPI
-INCD_ARD_ETH = -I$(ARDUINO_DIR)/libraries/Ethernet
-INCD_ARD_ETH_UTIL = -I$(ARDUINO_DIR)/libraries/Ethernet/utility
-INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time
-INCD_TBLOGGER = -I$(LOGGER_DIR)/include
-INCD_TBSTACK = -I$(TBSTACK_DIR)/include
-INCD_TBSOCKET = -I$(TBSOCKET_DIR)/include
-
-CPPFLAGSZ := -mmcu=atmega2560 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_MEGA2560 -DARDUINO_ARCH_AVR -MMD
-
-CPPFLAGS := -Wall -Os -c
-CPPFLAGS += $(CPPFLAGSZ) $(INCD_ARD_CORE) $(INCD_ARD_VARIANT) $(INCD_ARD_SPI) $(INCD_ARD_ETH) $(INCD_ARD_ETH_UTIL) $(INCD_ARD_TIME) $(INCD_TBLOGGER) $(INCD_TBSTACK) $(INCD_TBSOCKET)
-CPPFLAGS += -Wno-write-strings -ffunction-sections -fdata-sections -fno-exceptions -felide-constructors -std=c++0x -DATMEGA2560 -DTB_LOG
-
-SERVER_CPP_SRC := $(APP_NAME).cpp
-
-CORE_COBJ = WInterrupts.o wiring.o wiring_digital.o
-CORE_CPPOBJ = main.o Stream.o WMath.o WString.o HardwareSerial.o Print.o SPI.o IPAddress.o
-ETH_CPPOBJ = Dhcp.o Dns.o Ethernet.o EthernetUdp.o
-ETH_UTIL_CPPOBJ = socket.o w5100.o
-OCDEPENDENT_CPPOBJ = wiring_analog.o
-
-SERVER_OBJ := $(SERVER_CPP_SRC:.cpp=.o)
-
-#all: prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-all: preclean prebuild precopy prep_dirs core.a $(APP_NAME).o $(APP_NAME).elf $(APP_NAME).hex
-
-precopy:
- @cd $(TB_DIR) && mkdir debug && cp release/liboctbstack.a debug
-
-preclean:
- @cd $(TB_DIR) && make deepclean
-
-prebuild:
- @cd $(TB_DIR) && make PLATFORM=arduino
-
-core.a: $(CORE_COBJ) $(CORE_CPPOBJ) $(ETH_CPPOBJ) $(ETH_UTIL_CPPOBJ)
- @cd $(OBJ_DIR) && $(AR) -x ../$(TB_DIR)/$(BUILD)/liboctbstack.a
- $(AR) rcs $@ $^ $(OBJ_DIR)/*.o
- $(RANLIB) $@
-
-prep_dirs:
- -mkdir -p $(OBJ_DIR)
-
-%.o: %.cpp
- $(CCPLUS) $(CPPFLAGS) $< -o $@
-
-$(APP_NAME).elf: $(APP_NAME).o core.a $(OCDEPENDENT_CPPOBJ)
- $(CCPLUS) -Os -Wl,--gc-sections,--relax $(CPPFLAGSZ) -nodefaultlibs $^ -lm -lgcc -lc -lgcc -o $@
-
-$(APP_NAME).hex: $(APP_NAME).elf
- avr-objcopy -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 $< $(APP_NAME).eep
- avr-objcopy -O ihex -R .eeprom $< $@
-
-install: all
- avrdude -C$(ARDUINO_DIR)/hardware/tools/avrdude.conf -v -v -v -v -patmega2560 -cstk500v2 -P$(ARDUINO_PORT) -b115200 -D -Uflash:w:$(APP_NAME).hex:i
-
-.PHONY: clean
-
-clean:
- @rm -f *.o *.d *.elf *.eep *.a *.hex *-
- @rm -rf $(OBJ_DIR)
+++ /dev/null
-
-Followings should be done befor building Arudno applications
-
-1. Applications on arduino conform the Iotivity Base released on 22-Aug-2014.
- (Ver. 22th Aug(oic-resource: commit: cdeeed62bd9b11beb2cdd340168e766088c18dac [cdeeed6]))
-
- For successful execution, you have to copy the file, local.properties, into the following pathes:
- - oic-resource/csdk/
- - oic-resource/csdk/libcoap-4.1.1
-
-
-2. Time.c, Time.h should be copied in your machine and they should be refered in the Makefile as followings
-
- Makefile path: / oic-resource / csdk / libcoap-4.1.1 / makefile
-
- path to be modified:
-
- - INCD_ARD_TIME = -I$(ARDUINO_DIR)/libraries/Time ---> for Time.h
- - SDIR_ARD_TIME = $(ARDUINO_DIR)/libraries/Time ---> for Time.c
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2014 Intel Corporation All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "Arduino.h"
-
-#include "logger.h"
-#include "ocstack.h"
-#include <string.h>
-
-#include <EthernetServer.h>
-#include <Ethernet.h>
-#include <Dns.h>
-#include <EthernetClient.h>
-#include <util.h>
-#include <EthernetUdp.h>
-#include <Dhcp.h>
-
-const char *getResult(OCStackResult result);
-
-#define PCF(str) ((const prog_char*)(F(str)))
-#define dht11_pin 7 //Temperature & Humidity pin
-
-const prog_char TAG[] PROGMEM = "THServer";
-
-int gQuitFlag = 0;
-int gTHUnderObservation = 0;
-
-void createTHResource();
-typedef struct THRESOURCE {
- OCResourceHandle handle;
- int temp;
- int humid;
-} THResource;
-
-static THResource TH;
-
-String responsePayloadPut = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"0\",\"humidity\":\"0\"}}]}";
-String responsePayloadGet = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"0\",\"humidity\":\"0\"}}]}";
-
-
-/* read pin data */
-byte read_dht11_dat()
-{
- byte i = 0;
- byte result=0;
- for(i=0; i< 8; i++)
- {
- while (!digitalRead(dht11_pin));
- delayMicroseconds(30);
- if (digitalRead(dht11_pin) != 0 )
- bitSet(result, 7-i);
- while (digitalRead(dht11_pin));
- }
- return result;
-}
-
-/* Json Generator */
-String JsonGenerator(THResource TH){
- String a = "{\"oc\":[{\"href\":\"\",\"rep\":{\"temperature\":\"";
- String b = "\",\"humidity\":\"";
- String c = "\"}}]}";
-
- String ss;
-
- ss = a + TH.temp + b + TH.humid + c;
- return ss;
-}
-
-static uint8_t modCounter = 0;
-void *ChangeTHRepresentation (void *param)
-{
- (void)param;
- OCStackResult result = OC_STACK_ERROR;
-
- modCounter += 1;
- if(modCounter % 10 == 0) // Matching the timing that the Linux Server App uses for the same functionality.
- {
- /* Temperature & Humidity value check */
- byte dht11_dat[5];
- byte i;// start condition
-
- digitalWrite(dht11_pin, LOW);
- delay(18);
- digitalWrite(dht11_pin, HIGH);
- delayMicroseconds(1);
-
- pinMode(dht11_pin, INPUT);
- delayMicroseconds(40);
-
- if (digitalRead(dht11_pin))
- {
- Serial.println("dht11 start condition 1 not met"); // wait for DHT response signal: LOW
- delay(1000);
- return NULL;
-
- }
- delayMicroseconds(80);
- if (!digitalRead(dht11_pin))
- {
- Serial.println("dht11 start condition 2 not met"); // wait for second response signal:HIGH
- return NULL;
- }
-
- delayMicroseconds(80); // now ready for data reception
- for (i=0; i<5; i++)
- { dht11_dat[i] = read_dht11_dat();} // recieved 40 bits data.
-
- pinMode(dht11_pin, OUTPUT);
- digitalWrite(dht11_pin, HIGH);
- byte dht11_check_sum = dht11_dat[0]+dht11_dat[2]; // check check_sum
- if(dht11_dat[4]!= dht11_check_sum)
- {
- Serial.println("DHT11 checksum error");
- }
-
- delay(2000); // fresh time
- TH.humid = dht11_dat[0];
- TH.temp = dht11_dat[2];
-
- responsePayloadGet = JsonGenerator(TH);
-
-/* observe */
- if (gTHUnderObservation)
- {
- OC_LOG_V(INFO, TAG, " =====> Notifying stack of new humid level %d\n", TH.humid);
- OC_LOG_V(INFO, TAG, " =====> Notifying stack of new temp level %d\n", TH.temp);
-
- result = OCNotifyObservers (TH.handle);
-
- if (OC_STACK_NO_OBSERVERS == result)
- {
- gTHUnderObservation = 0;
- }
- }
- }
- return NULL;
-}
-
-OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag, OCEntityHandlerRequest * entityHandlerRequest ) {
- const char* typeOfMessage;
-
- OCEntityHandlerResult ehRet = OC_EH_OK;
-
- switch (flag) {
- case OC_INIT_FLAG:
- typeOfMessage = "OC_INIT_FLAG";
- break;
- case OC_REQUEST_FLAG:
- typeOfMessage = "OC_REQUEST_FLAG";
- break;
- case OC_OBSERVE_FLAG:
- typeOfMessage = "OC_OBSERVE_FLAG";
- break;
- default:
- typeOfMessage = "UNKNOWN";
- }
- OC_LOG_V(INFO, TAG, "Receiving message type: %s", typeOfMessage);
- if(entityHandlerRequest && flag == OC_REQUEST_FLAG) {
- if(OC_REST_GET == entityHandlerRequest->method) {
-
- int str_len = responsePayloadGet.length() + 1;
- char charBuf[str_len+1];
-
- responsePayloadGet.toCharArray(charBuf, str_len);
-
- if(strlen(charBuf) < entityHandlerRequest->resJSONPayloadLen)
- {
- strncpy((char *)entityHandlerRequest->resJSONPayload, charBuf, entityHandlerRequest->resJSONPayloadLen);
- }
- else
- ehRet = OC_EH_ERROR;
- }
- if(OC_REST_PUT == entityHandlerRequest->method) {
-
- int str_len1 = responsePayloadPut.length() + 1;
- char charBuf1[str_len1];
-
- responsePayloadPut.toCharArray(charBuf1, str_len1);
-
- if(strlen(charBuf1) < entityHandlerRequest->resJSONPayloadLen)
- {
- strncpy((char *)entityHandlerRequest->resJSONPayload, charBuf1, entityHandlerRequest->resJSONPayloadLen);
- }
- else
- ehRet = OC_EH_ERROR;
- }
- } else if (entityHandlerRequest && flag == OC_OBSERVE_FLAG) {
- gTHUnderObservation = 1;
- }
-
- return ehRet;
-}
-
-/* The setup function is called once at startup of the sketch */
-void setup()
-{
- pinMode(dht11_pin, OUTPUT);
- digitalWrite(dht11_pin, HIGH);
-
- OC_LOG_INIT();
-
- OC_LOG(DEBUG, TAG, PCF("THServer is starting..."));
- uint16_t port = USE_RANDOM_PORT;
-
- /* Mac address of my ethernet shield */
- uint8_t ETHERNET_MAC[] = {0x90, 0xA2, 0xDA, 0x0E, 0xB8, 0xAB};
- uint8_t error = Ethernet.begin(ETHERNET_MAC);
- Serial.print(Ethernet.localIP());
- if (error == 0)
- {
- OC_LOG_V(ERROR, TAG, "error is: %d", error);
- return;
- }
-
- if (OCInit(NULL, port, OC_SERVER) != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("OCStack init error"));
- return;
- }
-
- /*
- * Declare and create the resource: TH
- */
-
- createTHResource();
-
-}
-
-/* The loop function is called in an endless loop */
-void loop()
-{
- delay(1000);
- if (OCProcess() != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, PCF("OCStack process error"));
- return;
- }
- ChangeTHRepresentation(NULL);
-}
-
-void createTHResource() {
- TH.humid = 0;
- TH.temp = 0;
-
- OCStackResult res = OCCreateResource(&TH.handle,
- "SoftSensorManager.Sensor",
- "oc.mi.def",
- "/Thing_TempHumSensor",
- OCEntityHandlerCb,
- OC_DISCOVERABLE|OC_OBSERVABLE);
- OC_LOG_V(INFO, TAG, "Created TH resource with result: %s", getResult(res));
-}
-
-const char *getResult(OCStackResult result) {
- switch (result) {
- case OC_STACK_OK:
- return "OC_STACK_OK";
- case OC_STACK_INVALID_URI:
- return "OC_STACK_INVALID_URI";
- case OC_STACK_INVALID_QUERY:
- return "OC_STACK_INVALID_QUERY";
- case OC_STACK_INVALID_IP:
- return "OC_STACK_INVALID_IP";
- case OC_STACK_INVALID_PORT:
- return "OC_STACK_INVALID_PORT";
- case OC_STACK_INVALID_CALLBACK:
- return "OC_STACK_INVALID_CALLBACK";
- case OC_STACK_INVALID_METHOD:
- return "OC_STACK_INVALID_METHOD";
- case OC_STACK_NO_MEMORY:
- return "OC_STACK_NO_MEMORY";
- case OC_STACK_COMM_ERROR:
- return "OC_STACK_COMM_ERROR";
- case OC_STACK_INVALID_PARAM:
- return "OC_STACK_INVALID_PARAM";
- case OC_STACK_NOTIMPL:
- return "OC_STACK_NOTIMPL";
- case OC_STACK_NO_RESOURCE:
- return "OC_STACK_NO_RESOURCE";
- case OC_STACK_RESOURCE_ERROR:
- return "OC_STACK_RESOURCE_ERROR";
- case OC_STACK_SLOW_RESOURCE:
- return "OC_STACK_SLOW_RESOURCE";
- case OC_STACK_NO_OBSERVERS:
- return "OC_STACK_NO_OBSERVERS";
- case OC_STACK_ERROR:
- return "OC_STACK_ERROR";
- default:
- return "UNKNOWN";
- }
-}
-
-
std::shared_ptr< OCResource > g_curResource;
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName);
-void onObserve(const HeaderOptions &headerOption , const OCRepresentation& rep , const int& eCode, const int& sequenceNumber);
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName);
+void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode,
+ const int &sequenceNumber);
void findResourceCandidate()
{
{
nmfindResource("" , "coap://224.0.1.187/oc/core?rt=NotificationManager.Hosting");
std::cout << "Finding Resource... " << std::endl;
- while(true)
+ while (true)
{
- char signal;
- cin >> signal;
-
- switch(signal)
- {
- case 'q':
- case 'Q':
- exit(-1);
- default:
- break;
- }
+ char signal;
+ cin >> signal;
+
+ switch (signal)
+ {
+ case 'q':
+ case 'Q':
+ exit(-1);
+ default:
+ break;
+ }
}
}
- catch(OCException& e)
+ catch (OCException &e)
{
}
}
return ++oc;
}
-void onObserve(const HeaderOptions &headerOption , const OCRepresentation& rep , const int& eCode, const int& sequenceNumber)
+void onObserve(const HeaderOptions &headerOption , const OCRepresentation &rep , const int &eCode,
+ const int &sequenceNumber)
{
- std::cout << "onObserve" << std::endl;
+ std::cout << "onObserve" << std::endl;
// if(eCode == SUCCESS_RESPONSE)
- if(eCode <= OC_STACK_RESOURCE_DELETED)
+ if (eCode <= OC_STACK_RESOURCE_DELETED)
{
AttributeMap attributeMap = rep.getAttributeMap();
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
- if(attributeMap.find(it->first) == attributeMap.end())
+ if (attributeMap.find(it->first) == attributeMap.end())
{
return;
}
}
- if(rep.getUri().empty())
+ if (rep.getUri().empty())
{
- cout << "uri is null\n";
+ cout << "uri is null\n";
return;
}
std::cout << "========================================================" << std::endl;
std::cout << "Receive OBSERVE RESULT:" << std::endl;
std::cout << "\tSequenceNumber: " << sequenceNumber << std::endl;
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
std::cout << "\tAttribute name: " << it->first << " value: ";
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
std::cout << "\t" << *valueItr << " ";
}
std::cout << std::endl;
}
- if(observe_count() > 30)
+ if (observe_count() > 30)
{
std::cout << "Cancelling Observe..." << std::endl;
OCStackResult result = g_curResource->cancelObserve();
std::string hostAddress;
try
{
- if(resource)
+ if (resource)
{
// if(resource->uri().find("/a/NM/TempHumSensor/virtual") != std::string::npos)
- if(resource->uri().find("/a/NM/TempHumSensor") != std::string::npos)
+ if (resource->uri().find("/a/NM/TempHumSensor") != std::string::npos)
{
std::cout << std::endl;
std::cout << "========================================================" << std::endl;
}
}
- catch(std::exception& e)
+ catch (std::exception &e)
{
}
}
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName)
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName)
{
return OCPlatform::findResource(host , resourceName , &foundResource);
}
void getRepresentation(std::shared_ptr< OCResource > resource)
{
- if(resource)
+ if (resource)
{
std::cout << "Getting Light Representation..." << std::endl;
}
}
-void onPut(const OCRepresentation& rep , const int eCode)
+void onPut(const OCRepresentation &rep , const int eCode)
{
- if(eCode == SUCCESS_RESPONSE)
+ if (eCode == SUCCESS_RESPONSE)
{
std::cout << "PUT request was successful" << std::endl;
AttributeMap attributeMap = rep.getAttributeMap();
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
std::cout << "\tAttribute name: " << it->first << " value: ";
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
std::cout << "\t" << *valueItr << " ";
}
std::vector< OCRepresentation > children = rep.getChildren();
- for(auto oit = children.begin() ; oit != children.end() ; ++oit)
+ for (auto oit = children.begin() ; oit != children.end() ; ++oit)
{
attributeMap = oit->getAttributeMap();
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
std::cout << "\tAttribute name: " << it->first << " value: ";
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
std::cout << "\t" << *valueItr << " ";
}
}
}
- if(OBSERVE_TYPE_TO_USE == ObserveType::Observe)
+ if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
std::cout << std::endl << "Observe is used." << std::endl << std::endl;
- else if(OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
+ else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
std::cout << std::endl << "ObserveAll is used." << std::endl << std::endl;
QueryParamsMap test;
}
// callback handler on GET request
-void onGet(const HeaderOptions &headerOption , const OCRepresentation& rep , const int eCode)
+void onGet(const HeaderOptions &headerOption , const OCRepresentation &rep , const int eCode)
{
- if(eCode == SUCCESS_RESPONSE)
+ if (eCode == SUCCESS_RESPONSE)
{
std::cout << "GET request was successful" << std::endl;
std::cout << "Resource URI: " << rep.getUri() << std::endl;
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
std::cout << "\tAttribute name: " << it->first << " value: ";
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
std::cout << "\t" << *valueItr << " ";
}
std::vector< OCRepresentation > children = rep.getChildren();
- for(auto oit = children.begin() ; oit != children.end() ; ++oit)
+ for (auto oit = children.begin() ; oit != children.end() ; ++oit)
{
std::cout << "Child Resource URI: " << oit->getUri() << std::endl;
attributeMap = oit->getAttributeMap();
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
std::cout << "\tAttribute name: " << it->first << " value: ";
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
std::cout << "\t" << *valueItr << " ";
}
void getLightRepresentation(std::shared_ptr< OCResource > resource)
{
- if(resource)
+ if (resource)
{
std::cout << "Getting Light Representation..." << std::endl;
std::cout << " ObserveType : 2 - ObserveAll" << std::endl;
}
-int main(int argc , char* argv[])
+int main(int argc , char *argv[])
{
- if(argc == 1)
+ if (argc == 1)
{
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
}
- else if(argc == 2)
+ else if (argc == 2)
{
int value = atoi(argv[1]);
- if(value == 1)
+ if (value == 1)
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
- else if(value == 2)
+ else if (value == 2)
OBSERVE_TYPE_TO_USE = ObserveType::ObserveAll;
else
OBSERVE_TYPE_TO_USE = ObserveType::Observe;
class TempHumidResource
{
-public:
+ public:
- int m_temp;
- int m_humid;
+ int m_temp;
+ int m_humid;
- std::string m_uri;
- OCResourceHandle m_resourceHandle;
+ std::string m_uri;
+ OCResourceHandle m_resourceHandle;
- OCRepresentation m_Rep;
+ OCRepresentation m_Rep;
-public:
- TempHumidResource() :
+ public:
+ TempHumidResource() :
m_temp(0), m_humid(0), m_uri("/a/TempHumSensor")
- {
- }
+ {
+ }
- void createResource()
- {
- std::string resourceURI = "/a/NM/TempHumSensor";
- std::string resourceTypeName = "NotificationManager.Hosting";
- std::string resourceInterface = DEFAULT_INTERFACE;
+ void createResource()
+ {
+ std::string resourceURI = "/a/NM/TempHumSensor";
+ std::string resourceTypeName = "NotificationManager.Hosting";
+ std::string resourceInterface = DEFAULT_INTERFACE;
- m_uri = resourceURI;
+ m_uri = resourceURI;
- uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+ uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
- OCStackResult result = OCPlatform::registerResource(m_resourceHandle , resourceURI ,
- resourceTypeName , resourceInterface , &entityHandler , resourceProperty);
+ OCStackResult result = OCPlatform::registerResource(m_resourceHandle , resourceURI ,
+ resourceTypeName , resourceInterface , &entityHandler , resourceProperty);
- if(OC_STACK_OK != result)
- {
- cout << "Resource creation was unsuccessful\n";
+ if (OC_STACK_OK != result)
+ {
+ cout << "Resource creation was unsuccessful\n";
+ }
}
- }
- OCStackResult createResource1()
- {
- std::string resourceURI = "/a/NM/TempHumSensor1"; // URI of the resource
- std::string resourceTypeName = "NotificationManager.Hosting"; // resource type name. In this case, it is light
- std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
-
- // OCResourceProperty is defined ocstack.h
- uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
+ OCStackResult createResource1()
+ {
+ std::string resourceURI = "/a/NM/TempHumSensor1"; // URI of the resource
+ std::string resourceTypeName =
+ "NotificationManager.Hosting"; // resource type name. In this case, it is light
+ std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
- OCResourceHandle resHandle;
+ // OCResourceProperty is defined ocstack.h
+ uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE;
- // This will internally create and register the resource.
- OCStackResult result = OCPlatform::registerResource(
- resHandle, resourceURI, resourceTypeName,
- resourceInterface, &entityHandler, resourceProperty);
+ OCResourceHandle resHandle;
- if (OC_STACK_OK != result)
- {
- cout << "Resource creation was unsuccessful\n";
- }
+ // This will internally create and register the resource.
+ OCStackResult result = OCPlatform::registerResource(
+ resHandle, resourceURI, resourceTypeName,
+ resourceInterface, &entityHandler, resourceProperty);
- return result;
- }
+ if (OC_STACK_OK != result)
+ {
+ cout << "Resource creation was unsuccessful\n";
+ }
- OCResourceHandle getHandle()
- {
- return m_resourceHandle;
- }
+ return result;
+ }
- OCRepresentation post(OCRepresentation& rep)
- {
- static int first = 1;
+ OCResourceHandle getHandle()
+ {
+ return m_resourceHandle;
+ }
- // for the first time it tries to create a resource
- if(first)
+ OCRepresentation post(OCRepresentation &rep)
{
- first = 0;
+ static int first = 1;
- if(OC_STACK_OK == createResource1())
+ // for the first time it tries to create a resource
+ if (first)
{
- OCRepresentation rep1;
- rep1.setValue("createduri", std::string("/a/light1"));
+ first = 0;
+
+ if (OC_STACK_OK == createResource1())
+ {
+ OCRepresentation rep1;
+ rep1.setValue("createduri", std::string("/a/light1"));
- return rep1;
+ return rep1;
+ }
}
+
+ // from second time onwards it just puts
+ put(rep);
+ return get();
}
- // from second time onwards it just puts
- put(rep);
- return get();
- }
+ void put(OCRepresentation &rep)
+ {
+ try
+ {
+ if (rep.getValue("temperature", m_temp))
+ {
+ cout << "\t\t\t\t" << "temperature: " << m_temp << endl;
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "temperature not found in the representation" << endl;
+ }
- void put(OCRepresentation& rep)
- {
- try {
- if (rep.getValue("temperature", m_temp))
- {
- cout << "\t\t\t\t" << "temperature: " << m_temp << endl;
- }
- else
- {
- cout << "\t\t\t\t" << "temperature not found in the representation" << endl;
- }
-
- if (rep.getValue("humidity", m_humid))
- {
- cout << "\t\t\t\t" << "humidity: " << m_humid << endl;
- }
- else
- {
- cout << "\t\t\t\t" << "humidity not found in the representation" << endl;
- }
- }
- catch (exception& e)
- {
- cout << e.what() << endl;
- }
-
- }
-
- OCRepresentation get()
- {
- cout << "resource get\n";
- m_Rep.setValue("temperature", m_temp);
- m_Rep.setValue("humidity", m_humid);
-
- cout << "resource get : done\n";
-
- return m_Rep;
- }
+ if (rep.getValue("humidity", m_humid))
+ {
+ cout << "\t\t\t\t" << "humidity: " << m_humid << endl;
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "humidity not found in the representation" << endl;
+ }
+ }
+ catch (exception &e)
+ {
+ cout << e.what() << endl;
+ }
+
+ }
+
+ OCRepresentation get()
+ {
+ cout << "resource get\n";
+ m_Rep.setValue("temperature", m_temp);
+ m_Rep.setValue("humidity", m_humid);
+
+ cout << "resource get : done\n";
+
+ return m_Rep;
+ }
};
void *ChangeLightRepresentation(void *param)
{
- cout << "ChangeLigthRepresentation Enter\n";
- while(1){
- cout << "pthread_cond_wait\n";
- pthread_cond_wait(&m_cond, &m_mutex);
- cout << "pthread_cond_start\n";
- if(g_Observation)
- {
-
- cout << endl;
- cout << "========================================================" << endl;
- cout << "HUMTepm updated to : " << myResource.m_temp << endl;
- cout << "Notifying observers with resource handle: " << myResource.getHandle() << endl;
-
- cout << endl;
- cout << "========================================================" << endl;
- cout << "Send data : \n";
- cout << "Attribute Name: Temp\tvalue: " << myResource.m_temp << endl;
- cout << "Attribute Name: Humid\tvalue: " << myResource.m_humid << endl;
-
- OCStackResult result = OCPlatform::notifyAllObservers(myResource.getHandle());
- cout << "Notify Success\n";
-
- if(OC_STACK_NO_OBSERVERS == result)
- {
- cout << "No More observers, stopping notifications" << endl;
- g_Observation = 0;
- }
- }
- cout << "ChangeLigthRepresentation Out\n";
-
- }
+ cout << "ChangeLigthRepresentation Enter\n";
+ while (1)
+ {
+ cout << "pthread_cond_wait\n";
+ pthread_cond_wait(&m_cond, &m_mutex);
+ cout << "pthread_cond_start\n";
+ if (g_Observation)
+ {
+
+ cout << endl;
+ cout << "========================================================" << endl;
+ cout << "HUMTepm updated to : " << myResource.m_temp << endl;
+ cout << "Notifying observers with resource handle: " << myResource.getHandle() << endl;
+
+ cout << endl;
+ cout << "========================================================" << endl;
+ cout << "Send data : \n";
+ cout << "Attribute Name: Temp\tvalue: " << myResource.m_temp << endl;
+ cout << "Attribute Name: Humid\tvalue: " << myResource.m_humid << endl;
+
+ OCStackResult result = OCPlatform::notifyAllObservers(myResource.getHandle());
+ cout << "Notify Success\n";
+
+ if (OC_STACK_NO_OBSERVERS == result)
+ {
+ cout << "No More observers, stopping notifications" << endl;
+ g_Observation = 0;
+ }
+ }
+ cout << "ChangeLigthRepresentation Out\n";
+
+ }
return NULL;
}
OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request ,
- std::shared_ptr< OCResourceResponse > response)
+ std::shared_ptr< OCResourceResponse > response)
{
- cout << "Sample Provider entityHandler\n";
- if(request)
+ cout << "Sample Provider entityHandler\n";
+ if (request)
{
- cout << "flag : request\n";
+ cout << "flag : request\n";
std::string requestType = request->getRequestType();
int requestFlag = request->getRequestHandlerFlag();
- if(requestFlag == RequestHandlerFlag::InitFlag)
+ if (requestFlag == RequestHandlerFlag::InitFlag)
{
- cout << "\t\trequestFlag : Init\n";
+ cout << "\t\trequestFlag : Init\n";
}
- if(requestFlag == RequestHandlerFlag::RequestFlag)
+ if (requestFlag == RequestHandlerFlag::RequestFlag)
{
- cout << "\t\trequestFlag : Request\n";
- if(requestType == "GET")
+ cout << "\t\trequestFlag : Request\n";
+ if (requestType == "GET")
{
- cout << "\t\trequestType : GET\n";
- try
- {
- if(response)
- {
- OCRepresentation rep = myResource.get();
- cout << rep.getJSONRepresentation() << endl;
- response->setErrorCode(200);
- response->setResourceRepresentation(rep, DEFAULT_INTERFACE);
- }
- else
- {
- cout << "response is null\n";
- }
- } catch(exception& e)
- {
- cout << e.what() << endl;
- }
+ cout << "\t\trequestType : GET\n";
+ try
+ {
+ if (response)
+ {
+ OCRepresentation rep = myResource.get();
+ cout << rep.getJSONRepresentation() << endl;
+ response->setErrorCode(200);
+ response->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+ }
+ else
+ {
+ cout << "response is null\n";
+ }
+ }
+ catch (exception &e)
+ {
+ cout << e.what() << endl;
+ }
}
- else if(requestType == "PUT")
+ else if (requestType == "PUT")
{
cout << "\t\t\trequestType : PUT\n";
OCRepresentation rep = request->getResourceRepresentation();
myResource.put(rep);
- if(response)
+ if (response)
{
response->setErrorCode(200);
response->setResourceRepresentation(myResource.get());
}
}
- else if(requestType == "POST")
+ else if (requestType == "POST")
{
}
- else if(requestType == "DELETE")
+ else if (requestType == "DELETE")
{
}
}
- else if(requestFlag & RequestHandlerFlag::ObserverFlag)
+ else if (requestFlag & RequestHandlerFlag::ObserverFlag)
{
- pthread_t threadId;
+ pthread_t threadId;
cout << request->getResourceUri() << endl;
cout << request->getResourceRepresentation().getUri() << endl;
cout << "\t\trequestFlag : Observer\n";
static int startedThread = 0;
- if(!startedThread)
+ if (!startedThread)
{
- cout << "\t\tpthrerad_create\n";
+ cout << "\t\tpthrerad_create\n";
pthread_create(&threadId , NULL , ChangeLightRepresentation , (void *) NULL);
startedThread = 1;
}
int main()
{
- PlatformConfig cfg {
- OC::ServiceType::InProc,
- OC::ModeType::Server,
- "0.0.0.0",
- 0,
- OC::QualityOfService::LowQos
- };
+ PlatformConfig cfg
+ {
+ OC::ServiceType::InProc,
+ OC::ModeType::Server,
+ "0.0.0.0",
+ 0,
+ OC::QualityOfService::LowQos
+ };
- OCPlatform::Configure(cfg);
+ OCPlatform::Configure(cfg);
int number = 0;
myResource.createResource();
- while(true)
+ while (true)
{
bool end = false;
cout << endl;
cout << "========================================================" << endl;
cin >> number;
- switch(number)
+ switch (number)
{
case 1:
- {
- cout << "Temp is up!" << endl;
- myResource.m_temp += 10;
- pthread_cond_signal(&m_cond);
- cout << "ChangeLightRepresentation Done!" << endl;
- break;
- }
+ {
+ cout << "Temp is up!" << endl;
+ myResource.m_temp += 10;
+ pthread_cond_signal(&m_cond);
+ cout << "ChangeLightRepresentation Done!" << endl;
+ break;
+ }
case 2:
- {
- cout << "Temp is down!" << endl;
- myResource.m_temp -= 10;
- pthread_cond_signal(&m_cond);
- cout << "ChangeLightRepresentation Done!" << endl;
- break;
- }
+ {
+ cout << "Temp is down!" << endl;
+ myResource.m_temp -= 10;
+ pthread_cond_signal(&m_cond);
+ cout << "ChangeLightRepresentation Done!" << endl;
+ break;
+ }
case 3:
- {
- cout << "Bye!" << endl;
- end = true;
- break;
- }
+ {
+ cout << "Bye!" << endl;
+ end = true;
+ break;
+ }
default:
- {
- cout << "You type wrong number. Try again!" << endl;
- break;
- }
+ {
+ cout << "You type wrong number. Try again!" << endl;
+ break;
+ }
}
- if(end == true)
+ if (end == true)
{
break;
}
}
}
- catch(exception& e)
+ catch (exception &e)
{
- cout << "main exception : " << e.what() << endl;
+ cout << "main exception : " << e.what() << endl;
}
}
const int SUCCESS_RESPONSE = 0;
static ObserveType OBSERVE_TYPE_TO_USE = ObserveType::Observe;
-const char* PREFIX_URI = "Uri : ";
-const char* PREFIX_HOST = "Host : ";
+const char *PREFIX_URI = "Uri : ";
+const char *PREFIX_HOST = "Host : ";
OCPlatform *g_platform = nullptr;
PlatformConfig g_cfg;
oicappData *g_oicFindAd;
oicappData *g_oicObserveAd;
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName);
-void onObserve(const OCRepresentation& rep , const int& eCode , const int& sequenceNumber);
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName);
+void onObserve(const OCRepresentation &rep , const int &eCode , const int &sequenceNumber);
void onfound();
void onobserve();
std::cout << "Finding Resource... " << std::endl;
}
- catch(OCException& e)
+ catch (OCException &e)
{
}
g_oicFindAd = ad;
void startObserve(oicappData *ad)
{
- if(g_curResource != nullptr)
+ if (g_curResource != nullptr)
{
g_oicObserveAd = ad;
QueryParamsMap test;
void printAttributeMap(const AttributeMap attributeMap)
{
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
DBG("\tAttribute name: %s" , it->first.c_str());
- for(auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
+ for (auto valueItr = it->second.begin() ; valueItr != it->second.end() ; ++valueItr)
{
DBG("\t\tAttribute value: %s" , (*valueItr).c_str());
}
OCStackResult result = OC_STACK_ERROR;
- if(g_curResource != nullptr)
+ if (g_curResource != nullptr)
{
result = g_curResource->cancelObserve();
}
DBG("Cancel result: %d" , result);
}
-void onObserve(const OCRepresentation& rep , const int& eCode , const int& sequenceNumber)
+void onObserve(const OCRepresentation &rep , const int &eCode , const int &sequenceNumber)
{
AttributeMap attributeMap = rep.getAttributeMap();
- if(eCode == SUCCESS_RESPONSE)
+ if (eCode == SUCCESS_RESPONSE)
{
DBG("OBSERVE RESULT:");
DBG("\tSequenceNumber: %d" , sequenceNumber);
printAttributeMap(attributeMap);
-// updateAttribute(attributeMap);
+// updateAttribute(attributeMap);
g_curAttributeMap = attributeMap;
onobserve();
}
}
// callback handler on PUT request
-void onPut(const OCRepresentation& rep , const int eCode)
+void onPut(const OCRepresentation &rep , const int eCode)
{
AttributeMap attributeMap = rep.getAttributeMap();
- if(eCode == SUCCESS_RESPONSE)
+ if (eCode == SUCCESS_RESPONSE)
{
DBG("PUT request was successful");
printAttributeMap(attributeMap);
- if(OBSERVE_TYPE_TO_USE == ObserveType::Observe)
+ if (OBSERVE_TYPE_TO_USE == ObserveType::Observe)
INFO("Observe is used.");
- else if(OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
+ else if (OBSERVE_TYPE_TO_USE == ObserveType::ObserveAll)
INFO("ObserveAll is used.");
- if(g_curResource != nullptr)
+ if (g_curResource != nullptr)
{
DBG("Observe Start");
QueryParamsMap test;
}
// callback handler on GET request
-void onGet(const OCRepresentation& rep , const int eCode)
+void onGet(const OCRepresentation &rep , const int eCode)
{
AttributeMap attributeMap = rep.getAttributeMap();
- if(eCode == SUCCESS_RESPONSE)
+ if (eCode == SUCCESS_RESPONSE)
{
DBG("GET Succeeded:");
// Local function to get representation of light resource
void getLightRepresentation(std::shared_ptr< OCResource > resource)
{
- if(resource)
+ if (resource)
{
DBG("Getting Light Representation...");
// Invoke resource's get API with the callback parameter
{
try
{
- if(resource)
+ if (resource)
{
DBG("DISCOVERED Resource:");
DBG("\tURI of the resource: %s" , resource->uri().c_str());
DBG("\tHost address of the resource: %s" , resource->host().c_str());
- if(resource->uri().find("/a/NM") != string::npos)
+ if (resource->uri().find("/a/NM") != string::npos)
{
g_curResource = resource;
}
}
- catch(std::exception& e)
+ catch (std::exception &e)
{
}
}
-OCStackResult nmfindResource(const std::string& host , const std::string& resourceName)
+OCStackResult nmfindResource(const std::string &host , const std::string &resourceName)
{
- if(g_platform != nullptr)
+ if (g_platform != nullptr)
{
return g_platform->findResource(host , resourceName , &foundResource);
}
void oicapp_client_stop()
{
- if(g_curResource != nullptr)
+ if (g_curResource != nullptr)
{
cancelObserve();
g_curResource = NULL;
}
- if(g_platform)
+ if (g_platform)
{
delete (g_platform);
g_platform = NULL;
void onfound()
{
- if(g_curResource->uri().find("/a/NM/TempHumSensor/virtual") != string::npos)
+ if (g_curResource->uri().find("/a/NM/TempHumSensor/virtual") != string::npos)
{
oicappData *ad = g_oicFindAd;
std::string tmpStr[2];
int index = 0;
- for(auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
+ for (auto it = attributeMap.begin() ; it != attributeMap.end() ; ++it)
{
tmpStr[index] = it->first;
tmpStr[index].append(" : ");
- for(auto value = it->second.begin() ; value != it->second.end() ; ++value)
+ for (auto value = it->second.begin() ; value != it->second.end() ; ++value)
{
tmpStr[index].append(*value);
}
#define LOG_TAG "OIC_TEST"
#include <dlog.h>
-#define LOG_COLOR_RED "\033[0;31m"
-#define LOG_COLOR_BROWN "\033[0;33m"
-#define LOG_COLOR_BLUE "\033[0;34m"
-#define LOG_COLOR_END "\033[0;m"
+#define LOG_COLOR_RED "\033[0;31m"
+#define LOG_COLOR_BROWN "\033[0;33m"
+#define LOG_COLOR_BLUE "\033[0;34m"
+#define LOG_COLOR_END "\033[0;m"
#if 1
#define _ERR(fmt, arg...) SLOGE(fmt, ##arg)
#else
#define _DBG(fmt, arg...) \
- printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+ printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
#define _INFO(fmt, arg...) \
- printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+ printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
#define _WARN(fmt, arg...) \
- printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+ printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
#define _ERR(fmt, arg...) \
- printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
+ printf("[OIC_TEST]%s(%d):" fmt "\n", __FUNCTION__, __LINE__, ##arg)
#endif
#define DBG(fmt, arg...) _DBG(fmt, ##arg)
#define INFO(fmt, arg...) _INFO(LOG_COLOR_BLUE fmt LOG_COLOR_END, ##arg)
#define ret_if(expr) \
- do { \
- if (expr) { \
- ERR("(%s)", #expr); \
- return; \
- }\
- } while(0)
+ do { \
+ if (expr) { \
+ ERR("(%s)", #expr); \
+ return; \
+ }\
+ } while(0)
#define retv_if(expr, val) \
- do {\
- if (expr) { \
- ERR("(%s)", #expr); \
- return (val); \
- } \
- } while(0)
+ do {\
+ if (expr) { \
+ ERR("(%s)", #expr); \
+ return (val); \
+ } \
+ } while(0)
#define retm_if(expr, fmt, arg...) \
- do {\
- if (expr) { \
- ERR(fmt, ##arg); \
- return; \
- }\
- } while(0)
+ do {\
+ if (expr) { \
+ ERR(fmt, ##arg); \
+ return; \
+ }\
+ } while(0)
#define retvm_if(expr, val, fmt, arg...) \
- do {\
- if (expr) { \
- ERR(fmt, ##arg); \
- return (val); \
- } \
- } while(0)
+ do {\
+ if (expr) { \
+ ERR(fmt, ##arg); \
+ return (val); \
+ } \
+ } while(0)
#define warn_if(expr) \
- do { \
- if (expr) { \
- WARN("(%s)", #expr); \
- } \
- } while (0)
+ do { \
+ if (expr) { \
+ WARN("(%s)", #expr); \
+ } \
+ } while (0)
#endif //__OICAPP_LOG_H__
#define GRP_MAIN "main"
- enum
- {
- OICAPP_GENLIST_GRP_NONE = 0,
- OICAPP_GENLIST_GRP_TOP,
- OICAPP_GENLIST_GRP_CENTER,
- OICAPP_GENLIST_GRP_BOTTOM
- };
-
- typedef struct
- {
- Evas_Object *win;
- Evas_Object *base;
- Evas_Object *bg;
- Evas_Object *navi;
- Evas_Object *genlist;
- Evas_Object *popup;
- Evas_Object *conform;
-
- Elm_Object_Item *itemConsumer;
- Elm_Object_Item *itemConsumerUri;
- Elm_Object_Item *itemConsumerHost;
- Elm_Object_Item *itemConsumerTemp;
- Elm_Object_Item *itemConsumerHumid;
- Elm_Object_Item *itemFindResource;
- Elm_Object_Item *itemObserve;
- Elm_Object_Item *itemServer;
- Elm_Object_Item *itemServerTemp;
- Elm_Object_Item *itemServerHumid;
-
- Elm_Genlist_Item_Class itcSeperator;
- Elm_Genlist_Item_Class itcTitle;
- Elm_Genlist_Item_Class itcText;
- Elm_Genlist_Item_Class itcBtnFindResoruce;
- Elm_Genlist_Item_Class itcBtnObserve;
-
- char *ipAddr;
- //oicapp_mode mode;
- int clientOn;
- int serverOn;
- int power;
- int level;
-
- int temp;
- int humid;
-
- char *uri;
- char *host;
-
- } oicappData;
-
- extern void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item);
-
- typedef struct
- {
- oicappData *ad;
- const char *title;
- int group_style;
-
- } oicappItemData;
+enum
+{
+ OICAPP_GENLIST_GRP_NONE = 0,
+ OICAPP_GENLIST_GRP_TOP,
+ OICAPP_GENLIST_GRP_CENTER,
+ OICAPP_GENLIST_GRP_BOTTOM
+};
+
+typedef struct
+{
+ Evas_Object *win;
+ Evas_Object *base;
+ Evas_Object *bg;
+ Evas_Object *navi;
+ Evas_Object *genlist;
+ Evas_Object *popup;
+ Evas_Object *conform;
+
+ Elm_Object_Item *itemConsumer;
+ Elm_Object_Item *itemConsumerUri;
+ Elm_Object_Item *itemConsumerHost;
+ Elm_Object_Item *itemConsumerTemp;
+ Elm_Object_Item *itemConsumerHumid;
+ Elm_Object_Item *itemFindResource;
+ Elm_Object_Item *itemObserve;
+ Elm_Object_Item *itemServer;
+ Elm_Object_Item *itemServerTemp;
+ Elm_Object_Item *itemServerHumid;
+
+ Elm_Genlist_Item_Class itcSeperator;
+ Elm_Genlist_Item_Class itcTitle;
+ Elm_Genlist_Item_Class itcText;
+ Elm_Genlist_Item_Class itcBtnFindResoruce;
+ Elm_Genlist_Item_Class itcBtnObserve;
+
+ char *ipAddr;
+ //oicapp_mode mode;
+ int clientOn;
+ int serverOn;
+ int power;
+ int level;
+
+ int temp;
+ int humid;
+
+ char *uri;
+ char *host;
+
+} oicappData;
+
+extern void _gl_update_item(oicappData *ad , const char *title , Elm_Object_Item *item);
+
+typedef struct
+{
+ oicappData *ad;
+ const char *title;
+ int group_style;
+
+} oicappItemData;
#ifdef __cplusplus
}
{
#endif
- void oicapp_fail_popup(oicappData *ad , char *title , char *text , int timeout);
- void oicapp_util_update(oicappData *ad);
- char* oicapp_util_wifi();
+void oicapp_fail_popup(oicappData *ad , char *title , char *text , int timeout);
+void oicapp_util_update(oicappData *ad);
+char *oicapp_util_wifi();
- int oicapp_client_start(oicappData *ad);
- void oicapp_client_stop();
- int oicapp_client_put(int power , int level);
+int oicapp_client_start(oicappData *ad);
+void oicapp_client_stop();
+int oicapp_client_put(int power , int level);
- int oicapp_server_start(oicappData *ad);
- void oicapp_server_stop();
- void oicapp_server_put(int power , int level);
+int oicapp_server_start(oicappData *ad);
+void oicapp_server_stop();
+void oicapp_server_put(int power , int level);
- extern void *ChangeLightRepresentation(void *param);
+extern void *ChangeLightRepresentation(void *param);
- void findResourceCandidate(oicappData *ad);
- void startObserve(oicappData *ad);
+void findResourceCandidate(oicappData *ad);
+void startObserve(oicappData *ad);
#ifdef __cplusplus
}