def ensure_libs(target, source, env):
return target, [source, env.get('BUILD_DIR') + 'liboc.so', env.get('BUILD_DIR') + 'liboc_logger.so']
+# build android_api
jdk_env = Environment(ENV=os.environ)
-jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PSECURED=%s -PTARGET_ARCH=%s -PRELEASE=%s --stacktrace' %(ANDROID_SECURED, ANDROID_TARGET_ARCH, ANDROID_RELEASE), emitter = ensure_libs)
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + os.getcwd()+'/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED), emitter = ensure_libs)
jdk_env['BUILD_DIR'] = env.get('BUILD_DIR')
-jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")
+cmdBuildApi=jdk_env.Gradle(target="base/objs", source="base/src/main/java/org/iotivity/base/OcResource.java")
+
+jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') + ' build -b' + 'android/examples/build.gradle -PTARGET_ARCH=%s -PRELEASE=%s -PSECURED=%s --stacktrace' %(ANDROID_TARGET_ARCH, ANDROID_RELEASE, ANDROID_SECURED))
+cmdBuildExamples=jdk_env.Gradle(target="../examples/devicediscoveryclient/apk", source="../examples/devicediscoveryclient/src/main/java/org/iotivity/base/examples/DeviceDiscoveryClient.java")
+
+# android examples require android api to be built before being invoked
+Depends(cmdBuildExamples, cmdBuildApi)
+
<option name="BUILDABLE" value="false" />
</configuration>
</facet>
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ </configuration>
+ </facet>
</component>
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
android {\r
compileSdkVersion 21\r
buildToolsVersion "20.0.0"\r
- archivesBaseName = "iotivity"\r
+ archivesBaseName = "iotivity-base"\r
\r
libraryVariants.all { variant ->\r
variant.outputs.each { output ->\r
def outputFile = output.outputFile\r
if (outputFile != null && outputFile.name.endsWith('.aar')) {\r
- def fileName = "${archivesBaseName}-${TARGET_ARCH}-${outputFile.name}"\r
+ def fileName = "${archivesBaseName}-${TARGET_ARCH}-${RELEASE}.aar"\r
output.outputFile = new File(outputFile.parent, fileName)\r
}\r
}\r
minSdkVersion 21\r
targetSdkVersion 21\r
versionCode 1\r
- versionName "0.9"\r
+ versionName "1.0"\r
}\r
buildTypes {\r
release {\r
}\r
\r
lintOptions {\r
- abortOnError false\r
+ abortOnError false\r
}\r
\r
sourceSets {\r
//for windows use 'ndk-build.cmd'\r
//def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build.cmd')\r
def ndkBuild = new File(System.env.ANDROID_NDK_HOME, 'ndk-build')\r
- commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", "SECURE=$SECURED"
+ commandLine ndkBuild, "APP_ABI=$TARGET_ARCH", "APP_OPTIM=$RELEASE", "SECURE=$SECURED"\r
} else {\r
println '##################'\r
println 'Skipping NDK build'\r
println 'Reason: ANDROID_NDK_HOME not set.'\r
println '##################'\r
}\r
-}\r
-//\r
-//task (copyARR, type: Copy) {\r
-// copy {\r
-// from 'build/outputs/aar/'\r
-// into '../../../out/android/'\r
-// include '**/*.aar'\r
-// }\r
-//}\r
-//build.finalizedBy(copyARR)\r
-\r
-\r
+}
\ No newline at end of file
return OCEntityHandlerResult::OC_EH_SLOW;
case 5:
return OCEntityHandlerResult::OC_EH_FORBIDDEN;
+ case 6:
+ return OCEntityHandlerResult::OC_EH_RESOURCE_NOT_FOUND;
default:
ThrowOcException(OC_STACK_INVALID_PARAM, "Unexpected OCEntityHandlerResult");
return OCEntityHandlerResult::OC_EH_ERROR;
package org.iotivity.base;
+/**
+ * Possible returned values from entity handler.
+ */
public enum EntityHandlerResult {
OK(0),
ERROR(1),
RESOURCE_CREATED(2),
RESOURCE_DELETED(3),
SLOW(4),
- FORBIDDEN(5);
+ FORBIDDEN(5),
+ RESOURCE_NOT_FOUND(6);
private int value;
package org.iotivity.base;
+/**
+ * Host Mode of Operation.
+ */
public enum ModeType {
+ /**
+ * Server mode.
+ */
SERVER(0),
+ /**
+ * Client mode.
+ */
CLIENT(1),
+ /**
+ * Client/Server mode.
+ */
CLIENT_SERVER(2),
- GATEWAY(3),; /**< Client server mode along with Routing capabilities.*/
+ /**
+ * Client/Server mode along with Routing capabilities.
+ */
+ GATEWAY(3),;
private int value;
package org.iotivity.base;
+/**
+ * This class is expected as input for device properties. Device name is mandatory and expected
+ * from the application. Device id of type UUID will be generated by the stack.
+ */
public class OcDeviceInfo {
private String mDeviceName;
import java.util.List;
/**
- * Contains the main entrance/functionality of the product. To set a custom configuration, the
- * implementer must make a call to OcPlatform.Configure before the first usage of a function in this
- * class.
+ * This class contains the main entrance/functionality of the product. To set a custom
+ * configuration, the implementer must make a call to OcPlatform.Configure before the first usage
+ * of a method in this class.
*/
public final class OcPlatform {
/**
* API for setting the configuration of the OcPlatform.
+ * <p>
* Note: Any calls made to this AFTER the first call to OcPlatform.Configure will have no affect
+ * </p>
*
* @param platformConfig platform configuration
*/
/**
* API for notifying base that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
*
* @param ocResourceHandle resource handle of the resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void notifyAllObservers(
OcResourceHandle ocResourceHandle) throws OcException {
/**
* API for notifying base that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
*
* @param ocResourceHandle resource handle of the resource
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public static void notifyAllObservers(
OcResourceHandle ocResourceHandle,
/**
* API for notifying only specific clients that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
*
* @param ocResourceHandle resource handle of the resource
* @param ocObservationIdList These set of ids are ones which which will be notified upon
* resource change.
* @param ocResourceResponse OcResourceResponse object used by app to fill the response for
* this resource change
- * @throws OcException
+ * @throws OcException if failure
*/
public static void notifyListOfObservers(
OcResourceHandle ocResourceHandle,
/**
* API for notifying only specific clients that resource's attributes have changed.
+ * <p>
+ * Note: This API is for server side only.
+ * </p>
*
* @param ocResourceHandle resource handle of the resource
* @param ocObservationIdList These set of ids are ones which which will be notified upon
* @param ocResourceResponse OcResourceResponse object used by app to fill the response for
* this resource change
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public static void notifyListOfObservers(
OcResourceHandle ocResourceHandle,
int qualityOfService) throws OcException;
/**
- * API for Service and Resource Discovery. NOTE: This API applies to client side only
+ * API for Service and Resource Discovery
+ * <p>
+ * Note: This API is for client side only.
+ * </p>
*
- * @param host Host IP Address of a service to direct resource discovery query.
+ * @param host Host Address of a service to direct resource discovery query.
* If empty, performs multicast resource discovery query
* @param resourceUri name of the resource. If null or empty, performs search for all
* resource names
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
* @param onResourceFoundListener Handles events, success states and failure states.
- * @throws OcException
+ * @throws OcException if failure
*/
public static void findResource(
String host,
OnResourceFoundListener onResourceFoundListener) throws OcException;
/**
- * API for Service and Resource Discovery. NOTE: This API applies to client side only
+ * API for Service and Resource Discovery.
+ * <p>
+ * Note: This API is for client side only.
+ * </p>
*
* @param host Host IP Address of a service to direct resource discovery query.
* If empty, performs multicast resource discovery query
* @param resourceUri name of the resource. If null or empty, performs search for all
* resource names
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
* @param onResourceFoundListener Handles events, success states and failure states.
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public static void findResource(
String host,
*
* @param host Host IP Address. If null or empty, Multicast is performed.
* @param deviceUri Uri containing address to the virtual device
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
* @param onDeviceFoundListener Handles events, success states and failure states.
- * @throws OcException
+ * @throws OcException if failure
*/
public static void getDeviceInfo(
String host,
*
* @param host Host IP Address. If null or empty, Multicast is performed.
* @param deviceUri Uri containing address to the virtual device
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
* @param onDeviceFoundListener Handles events, success states and failure states.
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public static void getDeviceInfo(
String host,
*
* @param host Host IP Address. If null or empty, Multicast is performed.
* @param platformUri Uri containing address to the platform
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
* @param onPlatformFoundListener Handles events, success states and failure states.
- * @throws OcException
+ * @throws OcException if failure
*/
public static void getPlatformInfo(
*
* @param host Host IP Address. If null or empty, Multicast is performed.
* @param platformUri Uri containing address to the platform
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
* @param onPlatformFoundListener Handles events, success states and failure states.
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public static void getPlatformInfo(
int qualityOfService) throws OcException;
/**
- * This API registers a resource with the server NOTE: This API applies to server side only.
+ * This API registers a resource with the server
+ * <P>
+ * Note: This API applies to server & client side.
+ * </P>
*
* @param ocResource The instance of OcResource with all data filled
* @return resource handle
- * @throws OcException
+ * @throws OcException if failure
*/
public static OcResourceHandle registerResource(
OcResource ocResource) throws OcException {
/**
* This API registers a resource with the server NOTE: This API applies to server side only.
- *
+ * <P>
+ * Note: This API applies to server side only.
+ * </P>
* @param resourceUri The URI of the resource. Example: "a/light"
* @param resourceTypeName The resource type. Example: "light"
* @param resourceInterface The resource interface (whether it is collection etc).
* @param entityHandler entity handler.
* @param resourcePropertySet indicates the property of the resource
* @return resource handle
- * @throws OcException
+ * @throws OcException if failure
*/
public static OcResourceHandle registerResource(
String resourceUri,
* Register Device Info
*
* @param ocDeviceInfo object containing all the device specific information
- * @throws OcException
+ * @throws OcException if failure
*/
public static void registerDeviceInfo(
OcDeviceInfo ocDeviceInfo) throws OcException {
* Register Platform Info
*
* @param ocPlatformInfo object containing all the platform specific information
- * @throws OcException
+ * @throws OcException if failure
*/
public static void registerPlatformInfo(
OcPlatformInfo ocPlatformInfo) throws OcException {
*
* @param ocResourceHandle This is the resource handle which we which to unregister from the
* server
- * @throws OcException
+ * @throws OcException if failure
*/
public static void unregisterResource(
OcResourceHandle ocResourceHandle) throws OcException {
*
* @param ocResourceCollectionHandle handle to the collection resource
* @param ocResourceHandle handle to resource to be added to the collection resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void bindResource(
OcResourceHandle ocResourceCollectionHandle,
* @param ocResourceCollectionHandle handle to the collection resource
* @param ocResourceHandleList reference to list of resource handles to be added to the
* collection resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void bindResources(
OcResourceHandle ocResourceCollectionHandle,
*
* @param ocResourceCollectionHandle handle to the collection resource
* @param ocResourceHandle resource handle to be unbound from the collection resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void unbindResource(
OcResourceHandle ocResourceCollectionHandle,
* @param ocResourceCollectionHandle Handle to the collection resource
* @param ocResourceHandleList List of resource handles to be unbound from the collection
* resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void unbindResources(
OcResourceHandle ocResourceCollectionHandle,
*
* @param ocResourceHandle handle to the resource
* @param resourceTypeName new typename to bind to the resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void bindTypeToResource(
OcResourceHandle ocResourceHandle,
*
* @param ocResourceHandle handle to the resource
* @param resourceInterfaceName new interface to bind to the resource
- * @throws OcException
+ * @throws OcException if failure
*/
public static void bindInterfaceToResource(
OcResourceHandle ocResourceHandle,
* Start Presence announcements.
*
* @param ttl time to live in seconds
- * @throws OcException
+ * @throws OcException if failure
*/
public static void startPresence(int ttl) throws OcException {
OcPlatform.initCheck();
/**
* Stop Presence announcements.
*
- * @throws OcException
+ * @throws OcException if failure
*/
public static void stopPresence() throws OcException {
OcPlatform.initCheck();
* Subscribes to a server's presence change events. By making this subscription, every time a
* server adds/removes/alters a resource, starts or is intentionally stopped
*
- * @param host The IP address/addressable name of the server to subscribe to
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
- * @param onPresenceListener listener that will receive notifications/subscription events
+ * @param host The IP address/addressable name of the server to subscribe to
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onPresenceListener listener that will receive notifications/subscription events
* @return a handle object that can be used to identify this subscription request. It can be
* used to unsubscribe from these events in the future
- * @throws OcException
+ * @throws OcException if failure
*/
public static OcPresenceHandle subscribePresence(
String host,
* Subscribes to a server's presence change events. By making this subscription, every time a
* server adds/removes/alters a resource, starts or is intentionally stopped
*
- * @param host The IP address/addressable name of the server to subscribe to
- * @param resourceType a resource type specified as a filter for subscription events.
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
- * @param onPresenceListener listener that will receive notifications/subscription events
+ * @param host The IP address/addressable name of the server to subscribe to
+ * @param resourceType a resource type specified as a filter for subscription events.
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param onPresenceListener listener that will receive notifications/subscription events
* @return a handle object that can be used to identify this subscription request. It can be
* used to unsubscribe from these events in the future
- * @throws OcException
+ * @throws OcException if failure
*/
public static OcPresenceHandle subscribePresence(
String host,
*
* @param ocPresenceHandle the handle object provided by the subscribePresence call that
* identifies this subscription
- * @throws OcException
+ * @throws OcException if failure
*/
public static void unsubscribePresence(
OcPresenceHandle ocPresenceHandle) throws OcException {
* Additionally, you can only create this object if OcPlatform was initialized to be a Client
* or Client/Server.
*
- * @param host a string containing a resolvable host address of the server holding
- * the resource
- * @param uri the rest of the resource's URI that will permit messages to be
- * properly routed.
- * Example: /a/light
- * @param connectivityType a type of connectivity indicating the interface. Example: IPV4,
- * IPV6, ALL
- * @param isObservable a boolean containing whether the resource supports observation
- * @param resourceTypeList a collection of resource types implemented by the resource
- * @param interfaceList a collection of interfaces that the resource supports/implements
+ * @param host a string containing a resolvable host address of the server holding
+ * the resource
+ * @param uri the rest of the resource's URI that will permit messages to be
+ * properly routed.
+ * Example: /a/light
+ * @param connectivityTypeSet Set of types of connectivity. Example: IP
+ * @param isObservable a boolean containing whether the resource supports observation
+ * @param resourceTypeList a collection of resource types implemented by the resource
+ * @param interfaceList a collection of interfaces that the resource supports/implements
* @return new resource object
- * @throws OcException
+ * @throws OcException if failure
*/
public static OcResource constructResourceObject(
String host,
* Allows application entity handler to send response to an incoming request.
*
* @param ocResourceResponse resource response
- * @throws OcException
+ * @throws OcException if failure
*/
public static void sendResponse(OcResourceResponse ocResourceResponse)
throws OcException {
package org.iotivity.base;
-import java.security.InvalidParameterException;
-
+/**
+ * This class describes the platform properties. All non-Null properties will be
+ * included in a platform discovery request.
+ */
public class OcPlatformInfo {
private String mPlatformId;
private String mManufacturerName;
private String mSupportUrl;
private String mSystemTime;
- // construct OcPlatformInfo with mandatory fields which cannot be null
- // manufacturerName cannot be > 16 chars
- // manufacturerUrl cannot be > 32 chars
+ /**
+ * construct OcPlatformInfo with mandatory fields which cannot be null
+ * manufacturerName cannot be > 16 chars
+ * manufacturerUrl cannot be > 32 chars
+ */
public OcPlatformInfo(String platformId, String manufacturerName,
String manufacturerUrl) {
this.mPlatformId = platformId;
* @param onGetListener The event handler will be invoked with a map of attribute name and
* values. The event handler will also have the result from this Get
* operation This will have error codes
- * @throws OcException
+ * @throws OcException if failure
*/
public native void get(Map<String, String> queryParamsMap,
OnGetListener onGetListener) throws OcException;
* values. The event handler will also have the result from this Get
* operation This will have error codes
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public void get(Map<String, String> queryParamsMap,
OnGetListener onGetListener,
* @param onGetListener The event handler will be invoked with a map of attribute name and
* values. The event handler will also have the result from this Get
* operation This will have error codes
- * @throws OcException
+ * @throws OcException if failure
*/
public void get(String resourceType,
String resourceInterface,
* values. The event handler will also have the result from this Get
* operation This will have error codes
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public void get(String resourceType,
String resourceInterface,
* @param queryParamsMap Map which can have the query parameter name and value
* @param onPutListener event handler The event handler will be invoked with a map of attribute
* name and values.
- * @throws OcException
+ * @throws OcException if failure
*/
public native void put(OcRepresentation representation,
Map<String, String> queryParamsMap,
* @param onPutListener event handler The event handler will be invoked with a map of
* attribute name and values.
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public void put(OcRepresentation ocRepresentation,
Map<String, String> queryParamsMap,
* @param queryParamsMap Map which can have the query parameter name and value
* @param onPutListener event handler The event handler will be invoked with a map of
* attribute name and values.
- * @throws OcException
+ * @throws OcException if failure
*/
public void put(String resourceType,
String resourceInterface,
* @param onPutListener event handler The event handler will be invoked with a map of
* attribute name and values.
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public void put(String resourceType,
String resourceInterface,
* @param queryParamsMap Map which can have the query parameter name and value
* @param onPostListener event handler The event handler will be invoked with a map of
* attribute name and values.
- * @throws OcException
+ * @throws OcException if failure
*/
public native void post(OcRepresentation ocRepresentation,
Map<String, String> queryParamsMap,
* @param onPostListener event handler The event handler will be invoked with a map of
* attribute name and values.
* @param qualityOfService the quality of communication
- * @throws OcException
+ * @throws OcException if failure
*/
public void post(OcRepresentation ocRepresentation,
Map<String, String> queryParamsMap,
* @param queryParamsMap Map which can have the query parameter name and value
* @param onPostListener event handler The event handler will be invoked with a map of
* attribute name and values.
- * @throws OcException
+ * @throws OcException if failure
*/
public void post(String resourceType,
String resourceInterface,
/**
* Method to get a string representation of the resource's server ID.
- * * This is unique per- server independent on how it was discovered.
+ * <p>
+ * This is unique per- server independent on how it was discovered.
+ * </p>
*
* @return server ID
*/
package org.iotivity.base;
+/**
+ * OcResourceIdentifier represents the identity information for a server. This
+ * object combined with the OcResource's URI property uniquely identify an
+ * OcResource on or across networks.
+ */
public class OcResourceIdentifier {
private OcResourceIdentifier(long nativeHandle) {
this.mNativeHandle = nativeHandle;
package org.iotivity.base;
/**
+ * Quality of Service attempts to abstract the guarantees provided by the underlying transport
+ * protocol. The precise definitions of each quality of service level depend on the
+ * implementation. In descriptions below are for the current implementation and may changed
+ * over time.
*/
public enum QualityOfService {
+ /**
+ * Packet delivery is best effort.
+ */
LOW(0),
+ /**
+ * Packet delivery is best effort.
+ */
MEDIUM(1),
+ /**
+ * Acknowledgments are used to confirm delivery.
+ */
HIGH(2),
+ /**
+ * No Quality is defined, let the stack decide.
+ */
NA(3);
private int value;
package org.iotivity.base;
+/**
+ * Resource Properties.
+ */
public enum ResourceProperty {
+ /**
+ * When none of the bits are set, the resource is non-discoverable &
+ * non-observable by the client.
+ */
+ RES_PROP_NONE(0),
+ /**
+ * When this bit is set, the resource is allowed to be discovered by clients.
+ */
DISCOVERABLE(1 << 0),
+ /**
+ * When this bit is set, the resource is allowed to be observed by clients.
+ */
OBSERVABLE(1 << 1),
+ /**
+ * When this bit is set, the resource is initialized, otherwise the resource
+ * is 'inactive'. 'inactive' signifies that the resource has been marked for
+ * deletion or is already deleted.
+ */
ACTIVE(1 << 2),
+ /**
+ * When this bit is set, the resource has been marked as 'slow'.
+ * 'slow' signifies that responses from this resource can expect delays in
+ * processing its requests from clients.
+ */
SLOW(1 << 3),
- SECURE(1 << 4);
+ /**
+ * When this bit is set, the resource is a secure resource.
+ */
+ SECURE(1 << 4),
+ /**
+ * When this bit is set, the resource is allowed to be discovered only
+ * if discovery request contains an explicit querystring.
+ * Ex: GET /oic/res?rt=oic.sec.acl
+ */
+ EXPLICIT_DISCOVERABLE(1 << 5),;
private int value;
jcenter()\r
}\r
dependencies {\r
- classpath 'com.android.tools.build:gradle:1.0.0'\r
+ classpath 'com.android.tools.build:gradle:1.3.0'\r
\r
// NOTE: Do not place your application dependencies here; they belong\r
// in the individual module build.gradle files\r
jcenter()\r
}\r
dependencies {\r
- classpath 'com.android.tools.build:gradle:1.0.0'\r
+ classpath 'com.android.tools.build:gradle:1.3.0'\r
\r
// NOTE: Do not place your application dependencies here; they belong\r
// in the individual module build.gradle files\r
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.devicediscoveryclient"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.devicediscoveryserver"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
<option name="BUILDABLE" value="false" />\r
</configuration>\r
</facet>\r
+ <facet type="android-gradle" name="Android-Gradle">\r
+ <configuration>\r
+ <option name="GRADLE_PROJECT_PATH" value=":" />\r
+ </configuration>\r
+ </facet>\r
+ <facet type="android" name="Android">\r
+ <configuration>\r
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
+ </configuration>\r
+ </facet>\r
</component>\r
<component name="NewModuleRootManager" inherit-compiler-output="true">\r
<exclude-output />\r
-apply plugin: 'com.android.application'\r
-\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "21.1.2"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.base.examples.fridgeclient"\r
- minSdkVersion 19\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
-}\r
-\r
-dependencies {\r
- compile fileTree(dir: 'libs', include: ['*.jar'])\r
- compile 'com.android.support:appcompat-v7:21.0.3'\r
- compile project(':message')\r
-}\r
+apply plugin: 'com.android.application'
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.fridgeclient"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
+}
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
\ No newline at end of file
-<?xml version="1.0" encoding="UTF-8"?>\r
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
- <component name="FacetManager">\r
- <facet type="android-gradle" name="Android-Gradle">\r
- <configuration>\r
- <option name="GRADLE_PROJECT_PATH" value=":fridgeclient" />\r
- </configuration>\r
- </facet>\r
- <facet type="android" name="Android">\r
- <configuration>\r
- <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
- <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
- </configuration>\r
- </facet>\r
- </component>\r
- <component name="NewModuleRootManager" inherit-compiler-output="false">\r
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
- <exclude-output />\r
- <content url="file://$MODULE_DIR$">\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
- </content>\r
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
- <orderEntry type="sourceFolder" forTests="false" />\r
- <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
- <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
- <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
- <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
- <orderEntry type="module" module-name="message" exported="" />\r
- </component>\r
-</module>\r
-\r
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":fridgeclient" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":fridgeclient" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />
+ <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+ <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+ <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+ <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
+ <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+ <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+ <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/examples/iotivity-base-armeabi-release/unspecified/jars" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+ <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="module" module-name="iotivity-base-armeabi-release" exported="" />
+ <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-unspecified" level="project" />
+ </component>
+</module>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
- package="org.iotivity.base.examples.fridgeclient" >
- <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>
+ package="org.iotivity.base.examples" >
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
+ android:icon="@drawable/iotivityicon"
+ android:label= "@string/app_name"
android:theme="@style/AppTheme">
<activity
+ android:screenOrientation="portrait"
android:name=".FridgeClient"
android:label="@string/app_name" >
<intent-filter>
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * FridgeClient
+ * <p/>
+ * FridgeClient is a sample client app which should be started after the fridgeServer is started.
+ * It creates DeviceResource, DoorResources, LightResource and performs a GET operation on them.
+ */
+public class FridgeClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcResource.OnGetListener {
+ public static final String DEVICE_URI = "/device";
+ public static final String LIGHT = "/light";
+ public static final String LEFT_DOOR = "/door/left";
+ public static final String RIGHT_DOOR = "/door/right";
+ public static final String RANDOM_DOOR = "/door/random";
+ public static final String API_VERSION = "v.1.0";
+ public static final String CLIENT_TOKEN = "21ae43gf";
+ public static final int API_VERSION_KEY = 2048;
+ public static final int CLIENT_TOKEN_KEY = 3000;
+
+ private final List<OcResource> mResourceList = new LinkedList<OcResource>();
+ private OcResource mFridgeResource;
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void startFridgeClient() {
+ PlatformConfig cfg = new PlatformConfig(
+ this, // context
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+
+ logMessage("Configuring platform");
+ OcPlatform.Configure(cfg);
+ logMessage("Initiating fridge discovery");
+ try {
+ OcPlatform.findResource("",
+ OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ } catch (OcException e) {
+ logMessage(" Failed to discover resource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * An event handler to be executed whenever a "findResource" request completes successfully
+ *
+ * @param ocResource found resource
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource ocResource) {
+ if (null != mFridgeResource || !ocResource.getUri().equals(DEVICE_URI)) {
+ logMessage("Didn't find the correct fridge resource. Exiting");
+ return;
+ }
+ mFridgeResource = ocResource;
+ logMessage("Discovered a fridge with \nHost: " + mFridgeResource.getHost());
+
+ List<String> lightTypes = new LinkedList<>();
+ lightTypes.add("intel.fridge.light");
+ List<String> doorTypes = new LinkedList<>();
+ doorTypes.add("intel.fridge.door");
+ List<String> resourceInterfaces = new LinkedList<>();
+ resourceInterfaces.add(OcPlatform.DEFAULT_INTERFACE);
+ logMessage("Creating child resource proxies for the previously known fridge components");
+ OcResource light = null;
+ OcResource leftDoor = null;
+ OcResource rightDoor = null;
+ OcResource randomDoor = null;
+ try {
+ light = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ LIGHT,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ lightTypes,
+ resourceInterfaces);
+ mResourceList.add(light);
+
+ leftDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ LEFT_DOOR,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ doorTypes,
+ resourceInterfaces);
+ mResourceList.add(leftDoor);
+
+ rightDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ RIGHT_DOOR,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ doorTypes,
+ resourceInterfaces);
+ mResourceList.add(rightDoor);
+
+ randomDoor = OcPlatform.constructResourceObject(mFridgeResource.getHost(),
+ RANDOM_DOOR,
+ mFridgeResource.getConnectivityTypeSet(),
+ false, //isObservable
+ doorTypes,
+ resourceInterfaces);
+ mResourceList.add(randomDoor);
+ } catch (OcException e) {
+ logMessage("Error in constructResourceObject");
+ Log.e(TAG, e.getMessage());
+ }
+
+ List<OcHeaderOption> headerOptions = new LinkedList<>();
+ OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY, API_VERSION);
+ OcHeaderOption clientToken = new OcHeaderOption(CLIENT_TOKEN_KEY, CLIENT_TOKEN);
+ headerOptions.add(apiVersion);
+ headerOptions.add(clientToken);
+ mFridgeResource.setHeaderOptions(headerOptions);
+
+ logMessage("Calling GET api on mFridgeResource and other component resources");
+ try {
+ mFridgeResource.get(new HashMap<String, String>(), this);
+ if (null != light) light.get(new HashMap<String, String>(), this);
+ if (null != leftDoor) leftDoor.get(new HashMap<String, String>(), this);
+ if (null != rightDoor) rightDoor.get(new HashMap<String, String>(), this);
+ if (null != randomDoor) randomDoor.get(new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ logMessage("Error in GET calls");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request completes successfully
+ *
+ * @param headerOptionList list of the header options
+ * @param ocRepresentation representation of a resource
+ */
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> headerOptionList,
+ OcRepresentation ocRepresentation) {
+ logMessage("Got a response from " + ocRepresentation.getUri());
+ }
+
+ /**
+ * An event handler to be executed whenever a "get" request fails
+ *
+ * @param throwable exception
+ */
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ logMessage("GET request has failed");
+ Log.e(TAG, throwable.toString());
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeClient();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ private void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+
+ private static String TAG = "FridgeClient: ";
+ private TextView mConsoleTextView;
+}
\ No newline at end of file
+++ /dev/null
-/*
- * //******************************************************************
- * //
- * // Copyright 2015 Intel Corporation.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- * //
- * // 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.
- * //
- * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
- */
-
-package org.iotivity.base.examples.fridgeclient;
-
-import android.app.Activity;
-import android.content.BroadcastReceiver;
-import android.content.Context;
-import android.content.Intent;
-import android.content.IntentFilter;
-import android.os.Bundle;
-import android.os.Message;
-import android.support.v4.content.LocalBroadcastManager;
-import android.text.method.ScrollingMovementMethod;
-import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.widget.LinearLayout;
-import android.widget.TextView;
-
-import org.iotivity.base.ErrorCode;
-import org.iotivity.base.ModeType;
-import org.iotivity.base.OcConnectivityType;
-import org.iotivity.base.OcException;
-import org.iotivity.base.OcHeaderOption;
-import org.iotivity.base.OcPlatform;
-import org.iotivity.base.OcRepresentation;
-import org.iotivity.base.OcResource;
-import org.iotivity.base.PlatformConfig;
-import org.iotivity.base.QualityOfService;
-import org.iotivity.base.ServiceType;
-
-import java.util.EnumSet;
-import java.util.HashMap;
-import java.util.LinkedList;
-import java.util.List;
-
-import base.iotivity.org.examples.message.IMessageLogger;
-
-/**
- * FridgeClient
- * <p/>
- * FridgeClient is a sample client app which should be started after the fridgeServer is started.
- * It creates DeviceResource, DoorResource, LightResource and performs a get operation on them.
- * This implements IMessageLogger to display messages on the screen
- */
-public class FridgeClient extends Activity implements
- OcPlatform.OnResourceFoundListener, IMessageLogger {
- private static String TAG = "FridgeClient: ";
-
- private MessageReceiver mMessageReceiver = new MessageReceiver();
- private TextView mEventsTextView;
- private String mDeviceName;
- private int mDeviceCode;
- private List<String> ifaces;
- private final List<OcResource> resourceList = new LinkedList<OcResource>();
-
- /**
- * configure OIC platform and call findResource
- */
- private void initOICStack() {
- PlatformConfig cfg = new PlatformConfig(
- this,
- ServiceType.IN_PROC,
- ModeType.CLIENT,
- "0.0.0.0", // bind to all available interfaces
- 0,
- QualityOfService.LOW);
-
- OcPlatform.Configure(cfg);
- try {
- OcPlatform.findResource("", OcPlatform.WELL_KNOWN_QUERY + "?rt=" + "intel.fridge",
- EnumSet.of(OcConnectivityType.CT_DEFAULT), this);
- } catch (OcException e) {
- logMessage(TAG + " init Error. " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * prints out the appropriate messages depending on the device code
- *
- * @param representation representation of the OcResource
- * @param value clientDeviceCode
- */
- private void getResponse(OcRepresentation representation, int value) {
- switch (value) {
- case 0:
- // Get on device
- try {
- logMessage(TAG + "Name of device: " +
- representation.getValue(StringConstants.DEVICE_NAME));
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- break;
- case 1:
- // get on fridge light
- try {
- boolean lightOn = representation.getValue(StringConstants.ON);
- logMessage(TAG + "The fridge light is " +
- (lightOn ? "" : "not " + "on"));
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- break;
- case 2:
- case 3:
- // get on fridge door(s)
- try {
- boolean doorOpen = representation.getValue(StringConstants.OPEN);
- logMessage(TAG + "Door is " + (doorOpen ?
- "open" : "not open") + " and is on the " +
- representation.getValue(StringConstants.SIDE) + " side");
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- break;
- case 4:
- // get on fridge random door
- try {
- logMessage("Name of fridge: " +
- representation.getValue(StringConstants.DEVICE_NAME));
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- break;
- default:
- logMessage("Unexpected State");
- break;
- }
- }
-
- /**
- * this method is used to wait for 1 second between calls to different resources.
- * It is added for better readability
- */
- private void doWait() {
- try {
- Thread.sleep(StringConstants.WAIT_TIME);
- } catch (InterruptedException e) {
- logMessage(TAG + "doWait exception: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- @Override
- /**
- * callback when a resource is found. This method calls getResponse with the correct code
- */
- synchronized public void onResourceFound(OcResource ocResource) {
- // eventHandler for onGetListener
- resourceList.add(ocResource);
- OcResource.OnGetListener onGetListener = new OcResource.OnGetListener() {
- @Override
- public void onGetCompleted(List<OcHeaderOption> headerOptionList, OcRepresentation rep) {
- logMessage(TAG + " Got a response from " + getClientDeviceName());
- getResponse(rep, getClientDeviceCode());
- }
-
- @Override
- public void onGetFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
- };
-
- if (ocResource.getUri().equals(StringConstants.RESOURCE_URI)) {
- logMessage(TAG + "Discovered a device with \nHost: " + ocResource.getHost() +
- ", Uri: " + ocResource.getUri());
- }
- List<String> lightTypes = new LinkedList<>();
- lightTypes.add("intel.fridge.light");
- try {
- OcResource light = OcPlatform.constructResourceObject(ocResource.getHost(),
- StringConstants.LIGHT, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, lightTypes, ifaces);
-
- List<String> doorTypes = new LinkedList<>();
- doorTypes.add("intel.fridge.door");
- OcResource leftDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
- StringConstants.LEFT_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
-
- OcResource rightDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
- StringConstants.RIGHT_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
-
- OcResource randomDoor = OcPlatform.constructResourceObject(ocResource.getHost(),
- StringConstants.RANDOM_DOOR, EnumSet.of(OcConnectivityType.CT_DEFAULT), false, doorTypes, ifaces);
-
- List<OcHeaderOption> headerOptions = new LinkedList<>();
- OcHeaderOption apiVersion = new OcHeaderOption(StringConstants.API_VERSION_KEY,
- StringConstants.API_VERSION);
- OcHeaderOption clientToken = new OcHeaderOption(StringConstants.CLIENT_TOKEN_KEY,
- StringConstants.CLIENT_TOKEN);
- headerOptions.add(apiVersion);
- headerOptions.add(clientToken);
- ocResource.setHeaderOptions(headerOptions);
- /**
- * wait for 1 second before calling get on different resources.
- * It is done for better readability.
- * doWait() is called before each call to get
- */
- doWait();
-
- setupClientOptions("Device", 0);
- ocResource.get(new HashMap<String, String>(), onGetListener);
- doWait();
-
- setupClientOptions("Fridge Light", 1);
- light.get(new HashMap<String, String>(), onGetListener);
- doWait();
-
- setupClientOptions("Left Door", 2);
- leftDoor.get(new HashMap<String, String>(), onGetListener);
- doWait();
-
- setupClientOptions("Right Door", 3);
- rightDoor.get(new HashMap<String, String>(), onGetListener);
- doWait();
-
- setupClientOptions("Random Door", 4);
- randomDoor.get(new HashMap<String, String>(), onGetListener);
- doWait();
-
- resourceList.add(leftDoor);
- leftDoor.deleteResource(new OcResource.OnDeleteListener() {
- @Override
- public void onDeleteCompleted(List<OcHeaderOption> ocHeaderOptions) {
- logMessage(TAG + "Delete resource successful");
- }
-
- @Override
- public void onDeleteFailed(Throwable throwable) {
- if (throwable instanceof OcException) {
- OcException ocEx = (OcException) throwable;
- ErrorCode errCode = ocEx.getErrorCode();
- //do something based on errorCode
- }
- Log.e(TAG, throwable.toString());
- }
- });
- } catch (OcException e) {
- logMessage(TAG + "onResourceFound Error. " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_fridge_client);
- registerReceiver(mMessageReceiver, new IntentFilter(StringConstants.INTENT));
-
- mEventsTextView = new TextView(this);
- mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
- LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
- layout.addView(mEventsTextView, new LinearLayout.LayoutParams
- (LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
- ifaces = new LinkedList<>();
- ifaces.add(StringConstants.RESOURCE_INTERFACE);
- mDeviceCode = -1;
- mDeviceName = "";
-
- initOICStack();
- }
-
- public class MessageReceiver extends BroadcastReceiver {
- @Override
- public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(StringConstants.MESSAGE);
- logMessage(message);
- }
- }
-
- @Override
- public void logMessage(final String text) {
- if (StringConstants.ENABLE_PRINTING) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mEventsTextView.append("\n");
- mEventsTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
- }
-
-
- private void setupClientOptions(String name, int value) {
- mDeviceName = name;
- mDeviceCode = value;
- }
-
- private String getClientDeviceName() {
- return mDeviceName;
- }
-
- private int getClientDeviceCode() {
- return mDeviceCode;
- }
-
-
- //method to print the headerOptions received from the server
- void printHeaderOptions(List<OcHeaderOption> headerOptions) {
- for (OcHeaderOption headerOption : headerOptions) {
- if (StringConstants.API_VERSION_KEY == headerOption.getOptionId()) {
- logMessage(TAG + "Server API version in GET response: " +
- headerOption.getOptionData());
- }
- }
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.menu_fridge_client, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- int id = item.getItemId();
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- onStop();
- }
-
- @Override
- protected void onStop() {
- LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
- super.onStop();
- }
-}
+++ /dev/null
-package org.iotivity.base.examples.fridgeclient;
-
-import org.iotivity.base.OcPlatform;
-
-/**
- * StringConstant contains the fridgeclient specific constant values. To add another supported
- * Resource or Interface type to this app, begin by adding the new strings here, and then
- * find the places throughout the app where Resource-specific case switches occur, and add
- * the newly-supported type there.
- */
-public interface StringConstants {
- public static final String RESOURCE_URI = "/device";
- public static final String DEVICE_NAME = "device_name";
- public static final String LIGHT = "/light";
- public static final String LEFT_DOOR = "/door/left";
- public static final String RIGHT_DOOR = "/door/right";
- public static final String RANDOM_DOOR = "/door/random";
- public static final String MESSAGE = "message";
- public static final String API_VERSION = "v.1.2";
- public static final String CLIENT_TOKEN = "AaBbYyZz";
- public static final String ON = "on";
- public static final String OPEN = "open";
- public static final String SIDE = "side";
- public static final String INTENT = "org.iotivity.base.examples.fridgeclient";
- public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE;
-
- public static final int WAIT_TIME = 1000;
- public static final int API_VERSION_KEY = 2048;
- public static final int CLIENT_TOKEN_KEY = 3000;
-
- public static final boolean ENABLE_PRINTING = true; // change to false to disable printing
- // of messages on the console and the screen
-}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".FridgeClient">
-
- <TextView android:text="@string/app_name" android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
- <LinearLayout
+ tools:context=".FridgeClient">
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/button"
+ android:layout_centerHorizontal="true"
+ android:textOff="Start"
+ android:textOn="Stop"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:text="Start" />
+ <ScrollView
+ android:layout_below="@id/button"
+ android:layout_above="@+id/imageView"
android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- android:id="@+id/linearLayout" >
- </LinearLayout>
-
-</RelativeLayout>
+ android:layout_height="wrap_content"
+ android:fillViewport="true"
+ android:id="@+id/scrollView">
+ <TextView android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/consoleTextView" />
+ </ScrollView>
+ <ImageView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/imageView"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:src="@drawable/iotivitylogo" />
+</RelativeLayout>
\ No newline at end of file
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".FridgeClient">
<item android:id="@+id/action_settings" android:title="@string/action_settings"
- android:orderInCategory="100" app:showAsAction="never" />
+ android:orderInCategory="100" />
</menu>
<resources>
<!-- Base application theme. -->
- <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
+ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
--- /dev/null
+apply plugin: 'com.android.application'\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.fridgegroupclient"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../android_api/base/build/outputs/aar/"\r
+ }\r
+}\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}\r
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ package="org.iotivity.base.examples" >
+
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.BLUETOOTH"/>
+ <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
+ <uses-permission android:name="android.permission.INTERNET"/>
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE"/>
+ <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE"/>
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/iotivityicon"
+ android:label= "@string/app_name"
+ android:theme="@style/AppTheme">
+ <activity
+ android:screenOrientation="portrait"
+ android:name=".FridgeGroupClient"
+ android:label="@string/app_name" >
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+</manifest>
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcConnectivityType;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcHeaderOption;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResource;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.List;
+
+/**
+ * FridgeGroupClient
+ * <p/>
+ * FridgeGroupClient is a sample client app which should be started after the fridgeGroupServer is
+ * started. It discovers a fridge resource and then creates the proxy resources for each one of its
+ * children (light and door) and performs a GET on them.
+ */
+public class FridgeGroupClient extends Activity implements
+ OcPlatform.OnResourceFoundListener,
+ OcResource.OnGetListener {
+ private static String TAG = "FridgeGroupClient: ";
+
+ private final List<OcResource> childResourceList = new LinkedList<>();
+ private OcResource fridgeResource;
+
+ private void startFridgeClient() {
+ PlatformConfig cfg = new PlatformConfig(
+ this, // context
+ ServiceType.IN_PROC,
+ ModeType.CLIENT,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+
+ logMessage("Configuring platform");
+ OcPlatform.Configure(cfg);
+ String requestUri = OcPlatform.WELL_KNOWN_QUERY + "?rt=intel.fridge.group";
+ logMessage("Initiating fridge discovery");
+ try {
+ OcPlatform.findResource("",
+ requestUri,
+ EnumSet.of(OcConnectivityType.CT_DEFAULT),
+ this);
+ } catch (OcException e) {
+ logMessage("Failed to discover resource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * callback when a fridge resource is found.
+ */
+ @Override
+ public synchronized void onResourceFound(OcResource ocResource) {
+ if ((null != fridgeResource) && !fridgeResource.getUri().equals("/fridge/group")) {
+ logMessage("Didn't find the correct fridge resource. Exiting");
+ return;
+ }
+ fridgeResource = ocResource;
+ logMessage("Discovered a fridge with \nHost: " + fridgeResource.getHost());
+ logMessage("Trying to call GET api on fridgeResource");
+ try {
+ fridgeResource.get(new HashMap<String, String>(), this);
+ } catch (OcException e) {
+ logMessage("Failed to call GET api");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * once the fridge resource is discovered, create proxy child resources of the fridge
+ * and call GET on each of the child resource proxies.
+ *
+ * @param list
+ * @param ocRepresentation parent resource
+ */
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ logMessage("Got a response from " + ocRepresentation.getUri());
+ for (OcRepresentation child : ocRepresentation.getChildren()) {
+ try {
+ logMessage("Creating child resource proxy from fridgeResource with uri " +
+ child.getUri());
+ OcResource childResource = OcPlatform.constructResourceObject(
+ fridgeResource.getHost(),
+ child.getUri(),
+ fridgeResource.getConnectivityTypeSet(),
+ false, // isObservable set to false
+ child.getResourceTypes(),
+ child.getResourceInterfaces());
+ childResourceList.add(childResource);
+ } catch (OcException e) {
+ logMessage("Error in creating child resource proxy");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ OcResource.OnGetListener childOnGetListener = new OcResource.OnGetListener() {
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+ public static final String LIGHT_STATUS_KEY = "light";
+
+ @Override
+ public synchronized void onGetCompleted(List<OcHeaderOption> list,
+ OcRepresentation ocRepresentation) {
+ logMessage("Received a response from a child of the fridge with uri: " +
+ ocRepresentation.getUri());
+ for (String resType : ocRepresentation.getResourceTypes()) {
+ if (resType.equals("intel.fridge.door")) {
+ try {
+ logMessage(ocRepresentation.getValue(DOOR_SIDE_KEY) +
+ " door is " + ((ocRepresentation.getValue(DOOR_STATE_KEY)
+ ) ? "open" : "close"));
+ } catch (OcException e) {
+ logMessage("Failed to get the door resource representation");
+ Log.e(TAG, e.getMessage());
+ }
+ } else if (resType.equals("intel.fridge.light")) {
+ try {
+ logMessage("Fridge light is " +
+ ((ocRepresentation.getValue(LIGHT_STATUS_KEY)) ?
+ "on" : "off"));
+ } catch (OcException e) {
+ logMessage("Failed to get the light resource representation");
+ Log.e(TAG, e.getMessage());
+ }
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ logMessage("OnGet failed for child of fridge");
+ Log.e(TAG, throwable.getMessage());
+ }
+ };
+
+ for (OcResource child : childResourceList) {
+ try {
+ logMessage("Trying to get a representation of " + child.getUri() +
+ " resource from server");
+ child.get(new HashMap<String, String>(), childOnGetListener);
+ } catch (OcException e) {
+ logMessage(e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ }
+
+ @Override
+ public synchronized void onGetFailed(Throwable throwable) {
+ logMessage("Failed to get representation of the fridge");
+ Log.e(TAG, throwable.toString());
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private TextView mConsoleTextView;
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_client);
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeClient();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+
+ private void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+}
\ No newline at end of file
--- /dev/null
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context=".FridgeGroupClient">
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/button"
+ android:layout_centerHorizontal="true"
+ android:textOff="Start"
+ android:textOn="Stop"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:text="Start" />
+ <ScrollView
+ android:layout_below="@id/button"
+ android:layout_above="@+id/imageView"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:fillViewport="true"
+ android:id="@+id/scrollView">
+ <TextView android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/consoleTextView" />
+ </ScrollView>
+ <ImageView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/imageView"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:src="@drawable/iotivitylogo" />
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<resources>
+ <!-- Example customization of dimensions originally defined in res/values/dimens.xml
+ (such as screen margins) for screens with more than 820dp of available width. This
+ would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
+ <dimen name="activity_horizontal_margin">64dp</dimen>
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources></resources>
\ No newline at end of file
--- /dev/null
+<resources>
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">16dp</dimen>
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">FridgeGroupClient</string>
+</resources>
--- /dev/null
+<resources>
+
+ <!-- Base application theme. -->
+ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+ <!-- Customize your theme here. -->
+ </style>
+
+</resources>
--- /dev/null
+apply plugin: 'com.android.application'\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion "20.0.0"\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.base.examples.fridgegroupserver"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ versionCode 1\r
+ versionName "1.0"\r
+ }\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+ }\r
+ }\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../android_api/base/build/outputs/aar/"\r
+ }\r
+}\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ package="org.iotivity.base.examples">
+
+ <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
+ <uses-permission android:name="android.permission.BLUETOOTH" />
+ <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/iotivityicon"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme">
+ <activity
+ android:name=".FridgeGroupServer"
+ android:label="@string/app_name"
+ android:screenOrientation="portrait">
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+/**
+ * DoorResource
+ * <p/>
+ * DoorResource is a sample OIC server resource created by the refrigerator.
+ */
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ DoorResource(String side, Context context) {
+ mContext = context;
+ mSide = side;
+
+ registerDoorResource();
+ }
+
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
+ try {
+ mResourceHandle = OcPlatform.registerResource(
+ resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for doorResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case PUT:
+ response.setErrorCode(Resource.SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ break;
+ case DELETE:
+ response.setResponseResult(EntityHandlerResult.RESOURCE_DELETED);
+ response.setErrorCode(204);
+ OcPlatform.sendResponse(response);
+ break;
+ }
+ result = EntityHandlerResult.OK;
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity of DoorResource");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ // Note, we won't let the user change the door side!
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private String mSide;
+ private boolean mDoorState;
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ private static String TAG = "DoorResource: ";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.app.Activity;
+import android.content.BroadcastReceiver;
+import android.content.Context;
+import android.content.Intent;
+import android.content.IntentFilter;
+import android.os.Bundle;
+import android.os.Message;
+import android.text.method.ScrollingMovementMethod;
+import android.util.Log;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ScrollView;
+import android.widget.TextView;
+
+import org.iotivity.base.ModeType;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.PlatformConfig;
+import org.iotivity.base.QualityOfService;
+import org.iotivity.base.ServiceType;
+
+/**
+ * FridgeGroupServer
+ * <p/>
+ * This is the main fridgeGroupServer class. This instantiates Refrigerator object
+ * which has different resources such as LightResource, DoorResource, etc.
+ */
+public class FridgeGroupServer extends Activity {
+ private Refrigerator refrigerator;
+
+ /**
+ * configure OIC platform and call findResource
+ */
+ private void startFridgeServer() {
+ logMessage("Configuring platform config");
+ PlatformConfig cfg = new PlatformConfig(
+ this, // context
+ ServiceType.IN_PROC,
+ ModeType.SERVER,
+ "0.0.0.0", // bind to all available interfaces
+ 0,
+ QualityOfService.LOW);
+ OcPlatform.Configure(cfg);
+
+ logMessage("Creating refrigerator resources");
+ refrigerator = new Refrigerator(this);
+ logMessage("-----------------------------------------------------");
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private static String TAG = "FridgeServer: ";
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+ private BroadcastReceiver mMessageReceiver = new MessageReceiver();
+
+ @Override
+ protected void onCreate(Bundle savedInstanceState) {
+ super.onCreate(savedInstanceState);
+ setContentView(R.layout.activity_fridge_server);
+ registerReceiver(mMessageReceiver, new IntentFilter(Resource.INTENT));
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeServer();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+ }
+
+ @Override
+ protected void onSaveInstanceState(Bundle outState) {
+ super.onSaveInstanceState(outState);
+ outState.putString("consoleOutputString", mConsoleTextView.getText().toString());
+ }
+
+ @Override
+ protected void onRestoreInstanceState(Bundle savedInstanceState) {
+ super.onRestoreInstanceState(savedInstanceState);
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
+
+ public class MessageReceiver extends BroadcastReceiver {
+ @Override
+ public void onReceive(Context context, Intent intent) {
+ final String message = intent.getStringExtra(Resource.MESSAGE);
+ logMessage(message);
+ }
+ }
+
+ private void logMessage(final String text) {
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+
+/**
+ * FridgeResource
+ * <p/>
+ * FridgeResource is a sample OIC server resource created by the refrigerator.
+ */
+public class FridgeResource extends Resource {
+ FridgeResource(Context context) {
+ mContext = context;
+ registerFridgeResource();
+ }
+
+ private void registerFridgeResource() {
+ try {
+ logMessage(TAG + "RegisterFridgeResource " + FRIDGE_URI +
+ " : " + FRIDGE_TYPENAME);
+ mResourceHandle = OcPlatform.registerResource(
+ FRIDGE_URI,
+ FRIDGE_TYPENAME,
+ OcPlatform.GROUP_INTERFACE,
+ null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "FridgeResource register error: " + e.getMessage());
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ public static final String FRIDGE_URI = "/fridge/group";
+ public static final String FRIDGE_TYPENAME = "intel.fridge.group";
+ private static String TAG = "FridgeResource: ";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra("message", msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+import android.content.Intent;
+import android.util.Log;
+
+import org.iotivity.base.EntityHandlerResult;
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+import org.iotivity.base.OcResourceRequest;
+import org.iotivity.base.OcResourceResponse;
+import org.iotivity.base.RequestHandlerFlag;
+import org.iotivity.base.ResourceProperty;
+
+import java.util.EnumSet;
+
+
+/**
+ * LightResource
+ * <p/>
+ * LightResource is a sample OIC server resource created by the refrigerator.
+ */
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ LightResource(Context context) {
+ mContext = context;
+
+ registerLightResource();
+ }
+
+ private void registerLightResource() {
+ try {
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(
+ LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
+ } catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
+ Log.e(TAG, e.getMessage());
+ }
+ logMessage("-----------------------------------------------------");
+ }
+
+ /**
+ * sample implementation of eventHandler for lightResource - this can be implemented in many
+ * different ways
+ *
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
+ */
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
+ EntityHandlerResult result = EntityHandlerResult.ERROR;
+ if (null != ocResourceRequest) {
+ try {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(
+ RequestHandlerFlag.REQUEST)) {
+ OcResourceResponse response = new OcResourceResponse();
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
+ switch (ocResourceRequest.getRequestType()) {
+ case GET:
+ response.setErrorCode(Resource.SUCCESS);
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ case PUT:
+ response.setErrorCode(Resource.SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
+ updateRepresentationValues();
+ response.setResourceRepresentation(mRepresentation);
+ response.setResponseResult(EntityHandlerResult.OK);
+ OcPlatform.sendResponse(response);
+ result = EntityHandlerResult.OK;
+ break;
+ }
+ }
+ } catch (OcException e) {
+ logMessage("Error in handleEntity");
+ Log.e(TAG, e.getMessage());
+ return EntityHandlerResult.ERROR;
+ }
+ }
+ logMessage("-----------------------------------------------------");
+ return result;
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ /**
+ * update the value of light (ON/ OFF) from the representation
+ *
+ * @param representation new state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * helper function to update the current state of the light
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private boolean mIsLightOn = false;
+
+ private static String TAG = "LightResource: ";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ public static final String LIGHT_STATUS_KEY = "light";
+
+ private void logMessage(String msg) {
+ Intent intent = new Intent(Resource.INTENT);
+ intent.putExtra(Resource.MESSAGE, msg);
+ mContext.sendBroadcast(intent);
+ }
+}
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.content.Context;
+
+/**
+ * Refrigerator
+ * <p/>
+ * Refrigerator class has different objects (resources) which are instantiated when a
+ * Refrigerator object is created. Operations are performed on each of the individual resources.
+ */
+public class Refrigerator {
+ public static final String LEFT_SIDE = "left";
+ public static final String RIGHT_SIDE = "right";
+ public static final String RANDOM_SIDE = "random";
+
+ private FridgeResource mFridge;
+ private LightResource mLight;
+ private DoorResource mLeftDoor;
+ private DoorResource mRightDoor;
+ private DoorResource mRandomDoor;
+
+ /**
+ * constructor - creates resources of light and doors
+ *
+ * @param context needed by individual resources to be able to send broadcast
+ * messages to be displayed on the user screen
+ */
+ Refrigerator(Context context) {
+ mFridge = new FridgeResource(context);
+ mLight = new LightResource(context);
+ mLeftDoor = new DoorResource(LEFT_SIDE, context);
+ mRightDoor = new DoorResource(RIGHT_SIDE, context);
+ mRandomDoor = new DoorResource(RANDOM_SIDE, context);
+
+ mLight.bindTo(mFridge.getHandle());
+ mLeftDoor.bindTo(mFridge.getHandle());
+ mRightDoor.bindTo(mFridge.getHandle());
+ mRandomDoor.bindTo(mFridge.getHandle());
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * //******************************************************************
+ * //
+ * // Copyright 2015 Intel Corporation.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ * //
+ * // 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.
+ * //
+ * //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+ */
+
+package org.iotivity.base.examples;
+
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
+import org.iotivity.base.OcRepresentation;
+import org.iotivity.base.OcResourceHandle;
+
+/**
+ * Resource
+ * <p/>
+ * Each of the other resource classes (DeviceResource, DoorResource and LightResource extend Resource
+ */
+public abstract class Resource {
+ protected OcResourceHandle mResourceHandle;
+ protected OcRepresentation mRepresentation;
+
+ Resource() {
+ mResourceHandle = null;
+ mRepresentation = new OcRepresentation();
+ }
+
+ public void bindTo(OcResourceHandle collectionResourceHandle) {
+ try {
+ if (null != mResourceHandle && null != collectionResourceHandle) {
+ OcPlatform.bindResource(collectionResourceHandle, mResourceHandle);
+ }
+ } catch (OcException e) {
+ Log.e("Resource", e.getMessage());
+ }
+ }
+
+ public static final int SUCCESS = 200;
+ public static final String INTENT = "org.iotivity.base.examples.fridgegroupserver";
+ public static final String MESSAGE = "message";
+}
\ No newline at end of file
--- /dev/null
+<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context=".FridgeGroupServer">
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/button"
+ android:layout_centerHorizontal="true"
+ android:textOff="Start"
+ android:textOn="Stop"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:text="Start" />
+ <ScrollView
+ android:layout_below="@id/button"
+ android:layout_above="@+id/imageView"
+ android:layout_width="fill_parent"
+ android:layout_height="wrap_content"
+ android:fillViewport="true"
+ android:id="@+id/scrollView">
+ <TextView android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/consoleTextView" />
+ </ScrollView>
+ <ImageView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/imageView"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:src="@drawable/iotivitylogo" />
+</RelativeLayout>
\ No newline at end of file
--- /dev/null
+<resources>
+ <!-- Example customization of dimensions originally defined in res/values/dimens.xml
+ (such as screen margins) for screens with more than 820dp of available width. This
+ would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
+ <dimen name="activity_horizontal_margin">64dp</dimen>
+</resources>
--- /dev/null
+<resources>
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">16dp</dimen>
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">FridgeGroupServer</string>
+</resources>
--- /dev/null
+<resources>
+
+ <!-- Base application theme. -->
+ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
+ <!-- Customize your theme here. -->
+ </style>
+
+</resources>
-apply plugin: 'com.android.application'\r
-\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "21.1.2"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.base.examples.fridgeserver"\r
- minSdkVersion 19\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
-}\r
-\r
-dependencies {\r
- compile fileTree(dir: 'libs', include: ['*.jar'])\r
- compile 'com.android.support:appcompat-v7:21.0.3'\r
- compile project(':message')\r
-}\r
+apply plugin: 'com.android.application'
+android {
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
+
+ defaultConfig {
+ applicationId "org.iotivity.base.examples.fridgeserver"
+ minSdkVersion 21
+ targetSdkVersion 21
+ versionCode 1
+ versionName "1.0"
+ }
+ buildTypes {
+ release {
+ minifyEnabled false
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
+ }
+ }
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
+}
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
+}
\ No newline at end of file
-<?xml version="1.0" encoding="UTF-8"?>\r
-<module external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">\r
- <component name="FacetManager">\r
- <facet type="android-gradle" name="Android-Gradle">\r
- <configuration>\r
- <option name="GRADLE_PROJECT_PATH" value=":fridgeserver" />\r
- </configuration>\r
- </facet>\r
- <facet type="android" name="Android">\r
- <configuration>\r
- <option name="SELECTED_BUILD_VARIANT" value="debug" />\r
- <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />\r
- <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />\r
- <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />\r
- <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugTest" />\r
- <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />\r
- <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugTestSources" />\r
- <option name="ALLOW_USER_CONFIGURATION" value="false" />\r
- <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />\r
- <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />\r
- <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />\r
- <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />\r
- </configuration>\r
- </facet>\r
- </component>\r
- <component name="NewModuleRootManager" inherit-compiler-output="false">\r
- <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />\r
- <output-test url="file://$MODULE_DIR$/build/intermediates/classes/test/debug" />\r
- <exclude-output />\r
- <content url="file://$MODULE_DIR$">\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/test/debug" isTestSource="true" generated="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/test/debug" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/test/debug" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />\r
- <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/outputs" />\r
- <excludeFolder url="file://$MODULE_DIR$/build/tmp" />\r
- </content>\r
- <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />\r
- <orderEntry type="sourceFolder" forTests="false" />\r
- <orderEntry type="library" exported="" name="iotivity-x86-base-debug-unspecified" level="project" />\r
- <orderEntry type="library" exported="" name="appcompat-v7-21.0.3" level="project" />\r
- <orderEntry type="library" exported="" name="support-annotations-21.0.3" level="project" />\r
- <orderEntry type="library" exported="" name="support-v4-21.0.3" level="project" />\r
- <orderEntry type="module" module-name="message" exported="" />\r
- </component>\r
-</module>\r
-\r
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":fridgeserver" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="examples" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":fridgeserver" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />
+ <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+ <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+ <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+ <option name="SOURCE_GEN_TASK_NAME" value="generateDebugSources" />
+ <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+ <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+ <option name="TEST_SOURCE_GEN_TASK_NAME" value="generateDebugAndroidTestSources" />
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/resValues/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+ <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="module" module-name="iotivity-base-armeabi-release" exported="" />
+ <orderEntry type="library" exported="" name="iotivity-base-armeabi-release-unspecified" level="project" />
+ </component>
+</module>
\ No newline at end of file
xmlns:tools="http://schemas.android.com/tools"
package="org.iotivity.base.examples.fridgeserver">
- <uses-sdk tools:overrideLibrary="org.iotivity.base"></uses-sdk>
-
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<application
android:allowBackup="true"
- android:icon="@drawable/ic_launcher"
+ android:icon="@drawable/iotivityicon"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
+ android:screenOrientation="portrait"
android:name=".FridgeServer"
android:label="@string/app_name" >
<intent-filter>
import java.util.LinkedList;
import java.util.List;
-import base.iotivity.org.examples.message.IMessageLogger;
-
/**
* DeviceResource
* <p/>
* Creates a device resource and performs action based on client requests
*/
-public class DeviceResource extends Resource implements IMessageLogger {
- private Context mContext;
-
+public class DeviceResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DEVICE_URI = "/device";
+ public static final String RESOURCE_TYPENAME = "intel.fridge";
+ public static final String API_VERSION = "v.1.0";
+ public static final String CLIENT_TOKEN = "21ae43gf";
+ public static final String DEVICE_NAME = "device_name";
private static String TAG = "DeviceResource: ";
+ public static final int SUCCESS = 200;
+ public static final int API_VERSION_KEY = 2048;
+ public static final int CLIENT_VERSION_KEY = 3000;
+
+ private Context mContext;
/**
* constructor
*/
DeviceResource(Context context) {
mContext = context;
-
- // eventHandler for register deviceResource
- OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
- @Override
- public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- // this is where the main logic of DeviceResource is handled
- return entityHandler(ocResourceRequest);
- }
- };
-
- try {
- logMessage(TAG + "RegisterDeviceResource " + StringConstants.DEVICE_URI + " : " +
- StringConstants.RESOURCE_TYPENAME + " : " + StringConstants.RESOURCE_INTERFACE);
- mResourceHandle = OcPlatform.registerResource(StringConstants.DEVICE_URI,
- StringConstants.RESOURCE_TYPENAME, StringConstants.RESOURCE_INTERFACE,
- eh, EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "registerResource error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
+ registerDeviceResource();
}
- /**
- * update current state of device
- *
- * @return device representation
- */
- private void updateRepresentationValues() {
+ private void registerDeviceResource() {
try {
- mRepresentation.setValue(StringConstants.DEVICE_NAME,
- "Intel Powered 2 door, 1 light refrigerator");
+ logMessage("RegisterDeviceResource " + DEVICE_URI + " : " + RESOURCE_TYPENAME);
+ mResourceHandle = OcPlatform.registerResource(
+ DEVICE_URI,
+ RESOURCE_TYPENAME,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
} catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * unregister the resource
- */
- private void deleteDeviceResource() {
- try {
- OcPlatform.unregisterResource(mResourceHandle);
- logMessage(TAG + "Unregister DeviceResource successful");
- } catch (OcException e) {
- logMessage(TAG + e.getMessage());
+ logMessage(TAG + "Failed to register DeviceResource");
Log.e(TAG, e.getMessage());
}
}
/**
* this is the main method which handles different incoming requests appropriately.
*
- * @param request OcResourceRequest from the client
- * @return EntityHandlerResult depending on whether the request was handled successfully or not
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
*/
- private EntityHandlerResult entityHandler(OcResourceRequest request) {
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != request) {
- List<OcHeaderOption> headerOptions = request.getHeaderOptions();
+ if (null != ocResourceRequest) {
+ List<OcHeaderOption> headerOptions = ocResourceRequest.getHeaderOptions();
String clientAPIVersion = "";
String clientToken = "";
-
// search for header options map and look for API version and client token
for (OcHeaderOption headerOption : headerOptions) {
int optionId = headerOption.getOptionId();
- if (StringConstants.API_VERSION_KEY == optionId) {
+ if (API_VERSION_KEY == optionId) {
clientAPIVersion = headerOption.getOptionData();
logMessage(TAG + " Client API Version: " + clientAPIVersion);
- } else if (StringConstants.CLIENT_VERSION_KEY == optionId) {
+ } else if (CLIENT_VERSION_KEY == optionId) {
clientToken = headerOption.getOptionData();
logMessage(TAG + " Client Token: " + clientToken);
}
}
-
- if (clientAPIVersion.equals(StringConstants.API_VERSION) &&
- clientToken.equals(StringConstants.CLIENT_TOKEN)) {
+ if (clientAPIVersion.equals(API_VERSION) &&
+ clientToken.equals(CLIENT_TOKEN)) {
List<OcHeaderOption> serverHeaderOptions = new LinkedList<>();
- OcHeaderOption apiVersion = new OcHeaderOption(StringConstants.API_VERSION_KEY,
- StringConstants.API_VERSION);
+ OcHeaderOption apiVersion = new OcHeaderOption(API_VERSION_KEY,
+ API_VERSION);
serverHeaderOptions.add(apiVersion);
try {
- if (request.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(request.getRequestHandle());
- response.setResourceHandle(request.getResourceHandle());
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
response.setHeaderOptions(serverHeaderOptions);
- switch (request.getRequestType()) {
+ switch (ocResourceRequest.getRequestType()) {
case GET:
- response.setErrorCode(StringConstants.OK);
+ response.setErrorCode(SUCCESS);
response.setResponseResult(EntityHandlerResult.OK);
updateRepresentationValues();
response.setResourceRepresentation(mRepresentation);
OcPlatform.sendResponse(response);
break;
- case DELETE:
- deleteDeviceResource();
- response.setErrorCode(StringConstants.OK);
- response.setResponseResult(EntityHandlerResult.OK);
- break;
}
result = EntityHandlerResult.OK;
}
} catch (OcException e) {
- logMessage(TAG + e.getMessage());
+ logMessage("Error in handleEntity of DeviceResource");
Log.e(TAG, e.getMessage());
}
}
}
+ logMessage("-----------------------------------------------------");
return result;
}
- @Override
- public void logMessage(String msg) {
- logMsg(msg);
- if (StringConstants.ENABLE_PRINTING) {
- Log.i(TAG, msg);
+ /**
+ * update state of device
+ *
+ * @return device representation
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DEVICE_NAME,
+ "Intel Powered 3 door, 1 light refrigerator");
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
}
}
- public void logMsg(final String text) {
- Intent intent = new Intent(StringConstants.INTENT);
- intent.putExtra("message", text);
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra("message", msg);
mContext.sendBroadcast(intent);
}
}
import java.util.EnumSet;
-import base.iotivity.org.examples.message.IMessageLogger;
-
/**
* DoorResource
* <p/>
- * Creates a door resource and performs action based on client requests
+ * Creates a door resource and performs actions based on the client requests
*/
-public class DoorResource extends Resource implements IMessageLogger {
- private Context mContext;
-
- private static String TAG = "DoorResource: ";
- private String mSide = StringConstants.LEFT;
- private boolean mOpen;
- private String resourceURI;
+public class DoorResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String DOOR_URI = "/door/";
+ public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
+ public static final String DOOR_STATE_KEY = "state";
+ public static final String DOOR_SIDE_KEY = "side";
+ private boolean mDoorState;
+ private String mSide;
/**
* Constructor
*
- * @param side left or right side of the door
+ * @param side side of the door
* @param context to enable sending of broadcast messages to be displayed on the user screen
*/
DoorResource(String side, Context context) {
mContext = context;
mSide = side;
-
- resourceURI = StringConstants.DOOR_URI + mSide;
-
- // eventHandler for register doorResource
- OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
- @Override
- public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- // this is where the main logic of DoorResource is handled
- return entityHandler(ocResourceRequest);
- }
- };
- try {
- logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " +
- StringConstants.RESOURCE_TYPEDOOR + " : " + StringConstants.RESOURCE_INTERFACE);
- mResourceHandle = OcPlatform.registerResource(resourceURI,
- StringConstants.RESOURCE_TYPEDOOR, StringConstants.RESOURCE_INTERFACE,
- eh, EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "DoorResource registerResource error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * updates the current value of the door resource
- *
- * @return door representation
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(StringConstants.SIDE, mSide);
- mRepresentation.setValue(StringConstants.OPEN, mOpen);
- mRepresentation.setValue(StringConstants.DEVICE_NAME,
- "Intel Powered 2 door, 1 light refrigerator");
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
+ registerDoorResource();
}
- /**
- * update the OPEN value of doorResource (door is open/ closed)
- *
- * @param representation get current state of door
- */
- private void put(OcRepresentation representation) {
+ private void registerDoorResource() {
+ String resourceURI = DOOR_URI + mSide;
+ logMessage(TAG + "RegisterDoorResource " + resourceURI + " : " + RESOURCE_TYPEDOOR);
try {
- mOpen = representation.getValue(StringConstants.OPEN);
+ mResourceHandle = OcPlatform.registerResource(resourceURI,
+ RESOURCE_TYPEDOOR,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
} catch (OcException e) {
+ logMessage(TAG + "Failed to register DoorResource");
Log.e(TAG, e.getMessage());
}
- // Note, we won't let the user change the door side!
}
/**
* this is the main method which handles different incoming requests appropriately.
*
- * @param request OcResourceRequest from the client
- * @return EntityHandlerResult depending on whether the request was handled successfully or not
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
*/
- private EntityHandlerResult entityHandler(OcResourceRequest request) {
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != request) {
+ if (null != ocResourceRequest) {
try {
- if (request.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(request.getRequestHandle());
- response.setResourceHandle(request.getResourceHandle());
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
- switch (request.getRequestType()) {
+ switch (ocResourceRequest.getRequestType()) {
case GET:
- response.setErrorCode(StringConstants.OK);
+ response.setErrorCode(SUCCESS);
updateRepresentationValues();
response.setResourceRepresentation(mRepresentation);
response.setResponseResult(EntityHandlerResult.OK);
OcPlatform.sendResponse(response);
break;
case PUT:
- response.setErrorCode(StringConstants.OK);
- put(request.getResourceRepresentation());
+ response.setErrorCode(SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
updateRepresentationValues();
response.setResourceRepresentation(mRepresentation);
response.setResponseResult(EntityHandlerResult.OK);
result = EntityHandlerResult.OK;
}
} catch (OcException e) {
- logMessage(TAG + e.getMessage());
+ logMessage("Error in handleEntity of DoorResource");
Log.e(TAG, e.getMessage());
return EntityHandlerResult.ERROR;
}
}
+ logMessage("-----------------------------------------------------");
return result;
}
- @Override
- public void logMessage(String msg) {
- logMsg(msg);
- if (StringConstants.ENABLE_PRINTING) {
- Log.i(TAG, msg);
+ /**
+ * helper function to update the current value of the door resource
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(DOOR_STATE_KEY, mDoorState);
+ mRepresentation.setValue(DOOR_SIDE_KEY, mSide);
+ logMessage(TAG + "door state is " + ((mDoorState == true) ? "open" : "close") +
+ " and door side is " + mSide);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of doorResource, depending on if door is open/ closed
+ *
+ * @param representation new state of a door
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mDoorState = representation.getValue(DOOR_STATE_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
}
+ // Note, we won't let the user change the door side!
}
- public void logMsg(final String text) {
- Intent intent = new Intent(StringConstants.INTENT);
- intent.putExtra(StringConstants.MESSAGE, text);
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "DoorResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
mContext.sendBroadcast(intent);
}
-}
+}
\ No newline at end of file
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Message;
-import android.support.v4.content.LocalBroadcastManager;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
-import android.view.Menu;
-import android.view.MenuItem;
-import android.widget.LinearLayout;
+import android.view.View;
+import android.widget.Button;
+import android.widget.ScrollView;
import android.widget.TextView;
import org.iotivity.base.ModeType;
import org.iotivity.base.QualityOfService;
import org.iotivity.base.ServiceType;
-import base.iotivity.org.examples.message.IMessageLogger;
-
/**
* FridgeServer
* <p/>
* This is the main fridgeServer class. This instantiates Refrigerator object
- * which has different resources (DeviceResource, LightResource, DoorResource).
+ * which has different resources (DeviceResource, LightResource, DoorResources).
*/
-public class FridgeServer extends Activity implements IMessageLogger {
- private Context mContext;
- private static String TAG = "FridgeServer: ";
- private TextView mEventsTextView;
- private MessageReceiver mMessageReceiver = new MessageReceiver();
+public class FridgeServer extends Activity {
private Refrigerator refrigerator;
/**
* configure OIC platform and call findResource
*/
- private void initOICStack() {
+ private void startFridgeServer() {
//create platform config
PlatformConfig cfg = new PlatformConfig(
- this,
+ this, //context
ServiceType.IN_PROC,
ModeType.SERVER,
"0.0.0.0", // bind to all available interfaces
0,
QualityOfService.LOW);
+ logMessage("Configuring platform");
OcPlatform.Configure(cfg);
- logMessage(TAG + "Creating refrigerator resources");
-
- refrigerator = new Refrigerator(mContext);
+ logMessage("Creating refrigerator resources");
+ refrigerator = new Refrigerator(this);
+ logMessage("-----------------------------------------------------");
}
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private static String TAG = "FridgeServer: ";
+ public static final String MESSAGE = "message";
+ public static final String INTENT = "org.iotivity.base.examples.fridgeserver";
+ private TextView mConsoleTextView;
+ private ScrollView mScrollView;
+ private MessageReceiver mMessageReceiver = new MessageReceiver();
+
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fridge_server);
- registerReceiver(mMessageReceiver, new IntentFilter(StringConstants.INTENT));
-
- mEventsTextView = new TextView(this);
- mEventsTextView.setMovementMethod(new ScrollingMovementMethod());
- LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout);
- layout.addView(mEventsTextView, new LinearLayout.LayoutParams
- (LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
- mContext = this;
-
- initOICStack();
+ registerReceiver(mMessageReceiver, new IntentFilter(INTENT));
+
+ mConsoleTextView = (TextView) findViewById(R.id.consoleTextView);
+ mConsoleTextView.setMovementMethod(new ScrollingMovementMethod());
+ mScrollView = (ScrollView) findViewById(R.id.scrollView);
+ mScrollView.fullScroll(View.FOCUS_DOWN);
+ final Button button = (Button) findViewById(R.id.button);
+
+ if (null == savedInstanceState) {
+ button.setOnClickListener(new View.OnClickListener() {
+ @Override
+ public void onClick(View v) {
+ button.setEnabled(false);
+ new Thread(new Runnable() {
+ public void run() {
+ startFridgeServer();
+ }
+ }).start();
+ }
+ });
+ } else {
+ String consoleOutput = savedInstanceState.getString("consoleOutputString");
+ mConsoleTextView.setText(consoleOutput);
+ }
}
public class MessageReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
- final String message = intent.getStringExtra(StringConstants.MESSAGE);
+ final String message = intent.getStringExtra(MESSAGE);
logMessage(message);
}
}
- @Override
public void logMessage(final String text) {
- if (StringConstants.ENABLE_PRINTING) {
- runOnUiThread(new Runnable() {
- public void run() {
- final Message msg = new Message();
- msg.obj = text;
- mEventsTextView.append("\n");
- mEventsTextView.append(text);
- }
- });
- Log.i(TAG, text);
- }
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- // Inflate the menu; this adds items to the action bar if it is present.
- getMenuInflater().inflate(R.menu.menu_fridge_server, menu);
- return true;
- }
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- int id = item.getItemId();
- if (id == R.id.action_settings) {
- return true;
- }
- return super.onOptionsItemSelected(item);
- }
-
- @Override
- public void onDestroy() {
- super.onDestroy();
- onStop();
- }
-
- @Override
- protected void onStop() {
- LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
- super.onStop();
+ runOnUiThread(new Runnable() {
+ public void run() {
+ final Message msg = new Message();
+ msg.obj = text;
+ mConsoleTextView.append("\n");
+ mConsoleTextView.append(text);
+ }
+ });
+ Log.i(TAG, text);
}
}
import java.util.EnumSet;
-import base.iotivity.org.examples.message.IMessageLogger;
-
/**
* LightResource
* <p/>
- * Creates a light resource and performs action based on client requests
+ * Creates a light resource and performs actions based on the client requests
*/
-public class LightResource extends Resource implements IMessageLogger {
- private Context mContext;
-
- private static String TAG = "LightResource: ";
-
- private boolean mIsOn = false;
+public class LightResource extends Resource implements OcPlatform.EntityHandler {
+ public static final String LIGHT_STATUS_KEY = "light";
+ public static final String LIGHT_URI = "/light";
+ public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
+ private boolean mIsLightOn = false;
/**
* constructor
*/
LightResource(Context context) {
mContext = context;
- //eventHandler for register lightResource
- OcPlatform.EntityHandler eh = new OcPlatform.EntityHandler() {
- @Override
- public EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
- // this is where the main logic of LightResource is handled
- return entityHandler(ocResourceRequest);
- }
- };
- try {
- logMessage(TAG + "RegisterLightResource " + StringConstants.LIGHT_URI + " : " +
- StringConstants.RESOURCE_TYPELIGHT + " : " + StringConstants.RESOURCE_INTERFACE);
- mResourceHandle = OcPlatform.registerResource(StringConstants.LIGHT_URI,
- StringConstants.RESOURCE_TYPELIGHT, StringConstants.RESOURCE_INTERFACE,
- eh, EnumSet.of(ResourceProperty.DISCOVERABLE));
- } catch (OcException e) {
- logMessage(TAG + "LightResource registerResource error: " + e.getMessage());
- Log.e(TAG, e.getMessage());
- }
- }
-
- /**
- * updates the current state of the light (on/ off)
- *
- * @return light is on or off
- */
- private void updateRepresentationValues() {
- try {
- mRepresentation.setValue(StringConstants.ON, mIsOn);
- } catch (OcException e) {
- Log.e(TAG, e.getMessage());
- }
+ registerLightResource();
}
- /**
- * update the value of mIsOn from the representation
- *
- * @param representation get current state of light
- */
- private void put(OcRepresentation representation) {
+ private void registerLightResource() {
try {
- mIsOn = representation.getValue(StringConstants.ON);
+ logMessage(TAG + "RegisterLightResource " + LIGHT_URI + " : " + RESOURCE_TYPELIGHT);
+ mResourceHandle = OcPlatform.registerResource(LIGHT_URI,
+ RESOURCE_TYPELIGHT,
+ OcPlatform.DEFAULT_INTERFACE,
+ this,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
} catch (OcException e) {
+ logMessage(TAG + "Failed to register LightResource");
Log.e(TAG, e.getMessage());
}
+ logMessage("-----------------------------------------------------");
}
/**
* this is the main method which handles different incoming requests appropriately.
*
- * @param request OcResourceRequest from the client
- * @return EntityHandlerResult depending on whether the request was handled successfully or not
+ * @param ocResourceRequest OcResourceRequest from the client
+ * @return EntityHandlerResult indicates whether the request was handled successfully or not
*/
- private EntityHandlerResult entityHandler(OcResourceRequest request) {
+ @Override
+ public synchronized EntityHandlerResult handleEntity(OcResourceRequest ocResourceRequest) {
EntityHandlerResult result = EntityHandlerResult.ERROR;
- if (null != request) {
+ if (null != ocResourceRequest) {
try {
- if (request.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
+ if (ocResourceRequest.getRequestHandlerFlagSet().contains(RequestHandlerFlag.REQUEST)) {
OcResourceResponse response = new OcResourceResponse();
- response.setRequestHandle(request.getRequestHandle());
- response.setResourceHandle(request.getResourceHandle());
+ response.setRequestHandle(ocResourceRequest.getRequestHandle());
+ response.setResourceHandle(ocResourceRequest.getResourceHandle());
- switch (request.getRequestType()) {
+ switch (ocResourceRequest.getRequestType()) {
case GET:
- response.setErrorCode(StringConstants.OK);
+ response.setErrorCode(SUCCESS);
updateRepresentationValues();
response.setResourceRepresentation(mRepresentation);
response.setResponseResult(EntityHandlerResult.OK);
result = EntityHandlerResult.OK;
break;
case PUT:
- response.setErrorCode(StringConstants.OK);
- put(request.getResourceRepresentation());
+ response.setErrorCode(SUCCESS);
+ put(ocResourceRequest.getResourceRepresentation());
updateRepresentationValues();
response.setResourceRepresentation(mRepresentation);
response.setResponseResult(EntityHandlerResult.OK);
}
}
} catch (OcException e) {
- logMessage(TAG + e.getMessage());
+ logMessage("Error in handleEntity of LightResource");
Log.e(TAG, e.getMessage());
return EntityHandlerResult.ERROR;
}
}
+ logMessage("-----------------------------------------------------");
return result;
}
- @Override
- public void logMessage(String msg) {
- logMsg(msg);
- if (StringConstants.ENABLE_PRINTING) {
- Log.i(TAG, msg);
+ /**
+ * updates the current state of the light (on/ off)
+ *
+ * @return light is on or off
+ */
+ private void updateRepresentationValues() {
+ try {
+ mRepresentation.setValue(LIGHT_STATUS_KEY, mIsLightOn);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
+ }
+ }
+
+ /**
+ * update the value of mIsOn from the representation
+ *
+ * @param representation get current state of light
+ */
+ private void put(OcRepresentation representation) {
+ try {
+ mIsLightOn = representation.getValue(LIGHT_STATUS_KEY);
+ } catch (OcException e) {
+ Log.e(TAG, e.getMessage());
}
}
- public void logMsg(final String text) {
- Intent intent = new Intent(StringConstants.INTENT);
- intent.putExtra(StringConstants.MESSAGE, text);
+ //******************************************************************************
+ // End of the OIC specific code
+ //******************************************************************************
+ private Context mContext;
+ private static String TAG = "LightResource: ";
+
+ public void logMessage(String msg) {
+ Intent intent = new Intent(FridgeServer.INTENT);
+ intent.putExtra(FridgeServer.MESSAGE, msg);
mContext.sendBroadcast(intent);
}
}
* Refrigerator
* <p/>
* Refrigerator class has different objects (resources) which are instantiated when a
- * Refrigerator object is created. Operations are performed on each of the individual resources.
+ * Refrigerator object is created.
*/
public class Refrigerator {
- private Context mContext;
+ public static final String LEFT_SIDE = "left";
+ public static final String RIGHT_SIDE = "right";
+ public static final String RANDOM_SIDE = "random";
private LightResource mLight;
private DeviceResource mDevice;
* messages to be displayed on the user screen
*/
Refrigerator(Context context) {
- mContext = context;
mLight = new LightResource(context);
mDevice = new DeviceResource(context);
- mLeftDoor = new DoorResource(StringConstants.LEFT, context);
- mRightDoor = new DoorResource(StringConstants.RIGHT, context);
- mRandomDoor = new DoorResource(StringConstants.RANDOM, context);
- }
+ mLeftDoor = new DoorResource(LEFT_SIDE, context);
+ mRightDoor = new DoorResource(RIGHT_SIDE, context);
+ mRandomDoor = new DoorResource(RANDOM_SIDE, context);
+ mLight.bindTo(mDevice.getHandle());
+ mLeftDoor.bindTo(mDevice.getHandle());
+ mRightDoor.bindTo(mDevice.getHandle());
+ mRandomDoor.bindTo(mDevice.getHandle());
+ }
}
package org.iotivity.base.examples.fridgeserver;
+import android.util.Log;
+
+import org.iotivity.base.OcException;
+import org.iotivity.base.OcPlatform;
import org.iotivity.base.OcRepresentation;
import org.iotivity.base.OcResourceHandle;
mResourceHandle = null;
mRepresentation = new OcRepresentation();
}
+
+ public void bindTo(OcResourceHandle collectionResourceHandle) {
+ try {
+ if (null != mResourceHandle && null != collectionResourceHandle) {
+ OcPlatform.bindResource(collectionResourceHandle, mResourceHandle);
+ }
+ } catch (OcException e) {
+ Log.e("Resource", e.getMessage());
+ }
+ }
+
+ public OcResourceHandle getHandle() {
+ return mResourceHandle;
+ }
+
+ public static final int SUCCESS = 200;
}
\ No newline at end of file
+++ /dev/null
-package org.iotivity.base.examples.fridgeserver;
-
-import org.iotivity.base.OcPlatform;
-
-/**
- * StringConstant contains the fridgeserver specific constant values. To add another supported
- * Resource or Interface type to this app, begin by adding the new strings here, and then
- * find the places throughout the app where Resource-specific case switches occur, and add
- * the newly-supported type there.
- */
-public interface StringConstants {
- public static final String DEVICE_URI = "/device";
- public static final String LIGHT_URI = "/light";
- public static final String DOOR_URI = "/door/";
- public static final String DEVICE_NAME = "device_name";
- public static final String RESOURCE_TYPENAME = "intel.fridge";
- public static final String RESOURCE_TYPEDOOR = "intel.fridge.door";
- public static final String RESOURCE_TYPELIGHT = "intel.fridge.light";
- public static final String API_VERSION = "v.1.2";
- public static final String CLIENT_TOKEN = "AaBbYyZz";
- public static final String SIDE = "side";
- public static final String OPEN = "open";
- public static final String MESSAGE = "message";
- public static final String LEFT = "left";
- public static final String RIGHT = "right";
- public static final String RANDOM = "random";
- public static final String ON = "on";
- public static final String INTENT = "org.iotivity.base.examples.fridgeserver";
- public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE;
-
- public static final int API_VERSION_KEY = 2048;
- public static final int CLIENT_VERSION_KEY = 3000;
- public static final int OK = 200;
-
- public static final boolean ENABLE_PRINTING = true; // change to false to disable printing
- // of messages on the console and the screen
-}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
- android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
- android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".FridgeServer">
-
- <TextView android:text="@string/app_name" android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
-
- <LinearLayout
+ tools:context=".FridgeServer">
+ <Button
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/button"
+ android:layout_centerHorizontal="true"
+ android:textOff="Start"
+ android:textOn="Stop"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:text="Start" />
+ <ScrollView
+ android:layout_below="@id/button"
+ android:layout_above="@+id/imageView"
android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- android:orientation="vertical"
- android:id="@+id/linearLayout" >
- </LinearLayout>
-
-</RelativeLayout>
+ android:layout_height="wrap_content"
+ android:fillViewport="true"
+ android:id="@+id/scrollView">
+ <TextView android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/consoleTextView" />
+ </ScrollView>
+ <ImageView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:id="@+id/imageView"
+ android:layout_alignParentBottom="true"
+ android:layout_alignParentEnd="true"
+ android:layout_alignParentStart="true"
+ android:src="@drawable/iotivitylogo" />
+</RelativeLayout>
\ No newline at end of file
+++ /dev/null
-<menu xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools" tools:context=".FridgeServer">
- <item android:id="@+id/action_settings" android:title="@string/action_settings"
- android:orderInCategory="100" app:showAsAction="never" />
-</menu>
<resources>
<!-- Base application theme. -->
- <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
+ <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
--- /dev/null
+#
+# //******************************************************************
+# //
+# // Copyright 2015 Intel Corporation.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+# //
+# // 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.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+
+# Project-wide Gradle settings.
+
+# IDE (e.g. Android Studio) users:
+# Gradle settings configured through the IDE *will override*
+# any settings specified in this file.
+
+# For more details on how to configure your build environment visit
+# http://www.gradle.org/docs/current/userguide/build_environment.html
+
+# Specifies the JVM arguments used for the daemon process.
+# The setting is particularly useful for tweaking memory settings.
+# Default value: -Xmx10248m -XX:MaxPermSize=256m
+# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
+
+# When configured, Gradle will run in incubating parallel mode.
+# This option should only be used with decoupled projects. More details, visit
+# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
+# org.gradle.parallel=true
+TARGET_ARCH=armeabi
+RELEASE=release
+SECURED=1
+ERROR_MSG="if building examples from android-studio, you might need to modify the default TARGET_ARCH\
+ and RELEASE in <iotivity>/android/examples/gradle.properties,\
+ if your aar file has different values for TARGET_ARCH and RELEASE"
+
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.groupclient"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.groupserver"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
-apply plugin: 'com.android.application'\r
-\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "21.1.1"\r
-\r
- defaultConfig {\r
- applicationId "org.iotivity.guiclient"\r
- minSdkVersion 19\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
-}\r
-\r
-dependencies {\r
- compile fileTree(dir: 'libs', include: ['*.jar'])\r
- compile 'com.android.support:appcompat-v7:21.0.2'\r
-}\r
+//apply plugin: 'com.android.application'\r
+//\r
+//android {\r
+// compileSdkVersion 21\r
+// buildToolsVersion "21.1.1"\r
+//\r
+// defaultConfig {\r
+// applicationId "org.iotivity.guiclient"\r
+// minSdkVersion 19\r
+// targetSdkVersion 21\r
+// versionCode 1\r
+// versionName "1.0"\r
+// }\r
+// buildTypes {\r
+// release {\r
+// minifyEnabled false\r
+// proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+// }\r
+// }\r
+//}\r
+//\r
+//dependencies {\r
+// compile fileTree(dir: 'libs', include: ['*.jar'])\r
+// compile 'com.android.support:appcompat-v7:21.0.2'\r
+//}\r
-apply plugin: 'com.android.library'\r
-\r
-android {\r
- compileSdkVersion 21\r
- buildToolsVersion "21.1.2"\r
-\r
- defaultConfig {\r
- minSdkVersion 19\r
- targetSdkVersion 21\r
- versionCode 1\r
- versionName "1.0"\r
- }\r
- buildTypes {\r
- release {\r
- minifyEnabled false\r
- proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
- }\r
- }\r
-}\r
-\r
-dependencies {\r
- compile fileTree(dir: 'libs', include: ['*.jar'])\r
- compile 'com.android.support:appcompat-v7:21.0.3'\r
-}\r
+//apply plugin: 'com.android.library'\r
+//\r
+//android {\r
+// compileSdkVersion 21\r
+// buildToolsVersion "21.1.2"\r
+//\r
+// defaultConfig {\r
+// minSdkVersion 19\r
+// targetSdkVersion 21\r
+// versionCode 1\r
+// versionName "1.0"\r
+// }\r
+// buildTypes {\r
+// release {\r
+// minifyEnabled false\r
+// proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
+// }\r
+// }\r
+//}\r
+//\r
+//dependencies {\r
+// compile fileTree(dir: 'libs', include: ['*.jar'])\r
+// compile 'com.android.support:appcompat-v7:21.0.3'\r
+//}\r
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.presenceclient"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.presenceserver"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
\r
android {\r
compileSdkVersion 21\r
- buildToolsVersion "21.1.2"\r
+ buildToolsVersion "20.0.0"\r
\r
defaultConfig {\r
applicationId "org.iotivity.base.examples.provisioningclient"\r
- minSdkVersion 19\r
+ minSdkVersion 21\r
targetSdkVersion 21\r
versionCode 1\r
versionName "1.0"\r
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'\r
}\r
}\r
+ lintOptions {\r
+ abortOnError false\r
+ }\r
+}\r
+repositories {\r
+ flatDir {\r
+ dirs "../../android_api/base/build/outputs/aar/"\r
+ }\r
}\r
\r
-dependencies {\r
- compile 'com.android.support:appcompat-v7:21.0.3'\r
+try {\r
+ dependencies {\r
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"\r
+ }\r
+} catch (all) {\r
+ print "${ERROR_MSG}"\r
+ assert all\r
}\r
+\r
-include ':simpleserver', ':simpleclient', ':message', ':fridgeserver', ':fridgeclient', ':guiclient', ':provisioningclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':iotivity-armeabi-base-debug'
+include ':simpleserver', ':simpleclient', ':message', ':fridgeserver', ':fridgeclient', ':guiclient', ':provisioningclient', ':presenceserver', ':presenceclient', ':devicediscoveryclient', ':devicediscoveryserver', ':groupclient', ':groupserver', ':fridgegroupclient', ':fridgegroupserver'
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.simpleclient"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
apply plugin: 'com.android.application'
android {
- compileSdkVersion 22
- buildToolsVersion "22.0.1"
+ compileSdkVersion 21
+ buildToolsVersion "20.0.0"
defaultConfig {
applicationId "org.iotivity.base.examples.simpleserver"
minSdkVersion 21
- targetSdkVersion 22
+ targetSdkVersion 21
versionCode 1
versionName "1.0"
}
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
+ lintOptions {
+ abortOnError false
+ }
+}
+repositories {
+ flatDir {
+ dirs "../../android_api/base/build/outputs/aar/"
+ }
}
-dependencies {
- compile fileTree(dir: 'libs', include: ['*.jar'])
+try {
+ dependencies {
+ compile ":iotivity-base-${TARGET_ARCH}-${RELEASE}@aar"
+ }
+} catch (all) {
+ print "${ERROR_MSG}"
+ assert all
}
build_linux_secured $1 $2
build_linux_unsecured_with_ra $1 $2
build_linux_secured_with_ra $1 $2
+ build_linux_unsecured_with_rm $1 $2
+ build_linux_unsecured_with_rd $1 $2
+ build_linux_secured_with_rd $1 $2
fi
build_android $1 $2
scons RELEASE=$1 $2
}
+function build_linux_unsecured_with_rm()
+{
+ echo "*********** Build for linux with RoutingManager************"
+ scons ROUTING=GW RELEASE=$1 $2
+}
+
function build_linux_secured()
{
echo "*********** Build for linux with Security *************"
scons RELEASE=$1 WITH_RA=1 WITH_RA_IBB=1 SECURED=1 $2
}
+function build_linux_unsecured_with_rd()
+{
+ echo "*********** Build for linux With Resource Directory *************"
+ scons RELEASE=$1 WITH_RD=1 $2
+}
+
+function build_linux_secured_with_rd()
+{
+ echo "*********** Build for linux With Resource Directory & Security ************"
+ scons RELEASE=$1 WITH_RD=1 SECURED=1 $2
+}
+
function build_android()
{
# Note: for android, as oic-resource uses C++11 feature stoi and to_string,
# and windows android-ndk-r10(64bit target version) support these features.
build_android_x86 $1 $2
+ build_android_x86_with_rm $1 $2
build_android_armeabi $1 $2
+ build_android_armeabi_with_rm $1 $2
}
function build_android_x86()
scons TARGET_OS=android TARGET_ARCH=x86 RELEASE=$1 TARGET_TRANSPORT=BLE $2
}
+function build_android_x86_with_rm()
+{
+ echo "*********** Build for android x86 with Routing Manager *************"
+ scons TARGET_OS=android TARGET_ARCH=x86 ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=IP $2
+ scons TARGET_OS=android TARGET_ARCH=x86 ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BT $2
+ scons TARGET_OS=android TARGET_ARCH=x86 ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BLE $2
+}
+
function build_android_armeabi()
{
echo "*********** Build for android armeabi *************"
scons TARGET_OS=android TARGET_ARCH=armeabi RELEASE=$1 TARGET_TRANSPORT=BLE $2
}
+function build_android_armeabi_with_rm()
+{
+ echo "*********** Build for android armeabi with Routing Manager*************"
+ scons TARGET_OS=android TARGET_ARCH=armeabi ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=IP $2
+ scons TARGET_OS=android TARGET_ARCH=armeabi ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BT $2
+ scons TARGET_OS=android TARGET_ARCH=armeabi ROUTING=GW RELEASE=$1 TARGET_TRANSPORT=BLE $2
+}
+
function build_arduino()
{
echo "*********** Build for arduino avr *************"
echo "*********** Build for Tizen CA lib and sample with Security *************"
scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true SECURED=1 RELEASE=$1 $2
+
+ echo "*********** Build for Tizen octbstack lib and sample *************"
+ scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true RELEASE=$1 $2
+
+ echo "*********** Build for Tizen octbstack lib and sample with Routing Manager*************"
+ scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP LOGGING=true ROUTING=GW RELEASE=$1 $2
}
function build_darwin() # Mac OSx and iOS
echo "Usage:"
echo " build:"
echo " `basename $0` <target_build>"
- echo " Allowed values for <target_build>: all, linux_unsecured, linux_secured, linux_unsecured_with_ra, linux_secured_with_ra, android, arduino, tizen, darwin"
- echo " Note: \"linux\" will build \"linux_unsecured\", \"linux_secured\", \"linux_unsecured_with_ra\" & \"linux_secured_with_ra\"."
+ echo " Allowed values for <target_build>: all, linux_unsecured, linux_secured, linux_unsecured_with_ra, linux_secured_with_ra, linux_unsecured_with_rd, linux_secured_with_rd, android, arduino, tizen, darwin"
+ echo " Note: \"linux\" will build \"linux_unsecured\", \"linux_secured\", \"linux_unsecured_with_ra\", \"linux_secured_with_ra\", \"linux_secured_with_rd\" & \"linux_unsecured_with_rd\"."
echo " Any selection will build both debug and release versions of all available targets in the scope you've"
echo " selected. To choose any specific command, please use the SCons commandline directly. Please refer"
echo " to [IOTIVITY_REPO]/Readme.scons.txt."
then
build_linux_unsecured true
build_linux_unsecured false
+ build_linux_unsecured_with_rm true
+ build_linux_unsecured_with_rm false
elif [ $1 = 'linux_secured' ]
then
build_linux_secured true
then
build_linux_secured_with_ra true
build_linux_secured_with_ra false
+ elif [ $1 = 'linux_unsecured_with_rd' ]
+ then
+ build_linux_unsecured_with_rd true
+ build_linux_unsecured_with_rd false
+ elif [ $1 = 'linux_secured_with_rd' ]
+ then
+ build_linux_secured_with_rd true
+ build_linux_secured_with_rd false
elif [ $1 = 'android' ]
then
build_android true
then
build_android_x86 true
build_android_x86 false
+ build_android_x86_with_rm true
+ build_android_x86_with_rm false
elif [ $1 = 'android_armeabi' ]
then
build_android_armeabi true
build_android_armeabi false
+ build_android_armeabi_with_rm true
+ build_android_armeabi_with_rm false
elif [ $1 = 'arduino' ]
then
build_arduino true
help_vars.Add(BoolVariable('WITH_RA', 'Build with Remote Access module', False))
+help_vars.Add(EnumVariable('WITH_RD', 'Build including Resource Directory', '0', allowed_values=('0', '1')))
help_vars.Add(BoolVariable('SIMULATOR', 'Build with simulator module', False))
env.AppendUnique(TINYDTLS_SRC = tinydtls_src)
if not env.get('RELEASE'):
- if(target_os) not in ['android', 'arduino']:
+ if(target_os) not in ['arduino']:
env.AppendUnique(TINYDTLS_SRC = ['debug.c'])
else:
env.AppendUnique(CPPDEFINES = ['NDEBUG'])
DTLS_X509=1],
[])
+AC_ARG_WITH(hal,
+ [AS_HELP_STRING([--with-hal],[use a hardware abstraction layer for crypto functions])],
+ [AC_DEFINE(DTLS_CRYPTO_HAL, 1, [Define to 1 if building with Hardware Abstraction Layer])
+ DTLS_CRYPTO_HAL=1],
+ [])
+
CPPFLAGS="${CPPFLAGS} -DDTLSv12 -DWITH_SHA256"
OPT_OBJS="${OPT_OBJS} sha2/sha2.o"
/* rfc4492#section-5.4 */
void
dtls_ecdsa_create_sig_hash(const unsigned char *priv_key, size_t key_size,
- const unsigned char *sign_hash, size_t sign_hash_size,
- uint32_t point_r[9], uint32_t point_s[9]) {
- uint8_t privateKey[32];
- uint8_t hashValue[32];
- uint8_t sign[64];
+ const unsigned char *sign_hash, size_t sign_hash_size,
+ uint32_t point_r[9], uint32_t point_s[9])
+{
+ uint8_t sign[64];
+ // Check the buffers
+ if (priv_key == NULL || key_size < 32)
+ return 0;
+ if (sign_hash == NULL || sign_hash_size < 32)
+ return 0;
- uECC_sign(privateKey, hashValue, sign);
- memcpy(point_r, sign, 32);
- memcpy(point_s, sign + 32, 32);
+ uECC_sign(priv_key, sign_hash, sign);
+ memcpy(point_r, sign, 32);
+ memcpy(point_s, sign + 32, 32);
}
void
/* rfc4492#section-5.4 */
int
dtls_ecdsa_verify_sig_hash(const unsigned char *pub_key_x,
- const unsigned char *pub_key_y, size_t key_size,
- const unsigned char *sign_hash, size_t sign_hash_size,
- unsigned char *result_r, unsigned char *result_s) {
-
- uint8_t publicKey[64];
- uint8_t hashValue[32];
- uint8_t sign[64];
-
- memcpy(publicKey, pub_key_x, 32);
- memcpy(publicKey + 32, pub_key_y, 32);
- return uECC_verify(publicKey, hashValue, sign);
+ const unsigned char *pub_key_y, size_t key_size,
+ const unsigned char *sign_hash, size_t sign_hash_size,
+ unsigned char *result_r, unsigned char *result_s)
+{
+ uint8_t publicKey[64];
+ uint8_t sign[64];
+
+ // Check the buffers
+ if (pub_key_x == NULL || pub_key_y == NULL || key_size < 32)
+ return 0;
+ if (sign_hash == NULL || sign_hash_size < 32)
+ return 0;
+ if (result_r == NULL || result_s == NULL)
+ return 0;
+
+ // Copy the public key into a single buffer
+ memcpy(publicKey, pub_key_x, 32);
+ memcpy(publicKey + 32, pub_key_y, 32);
+
+ // Copy the signature into a single buffer
+ memcpy(sign, result_r, 32);
+ memcpy(sign + 32, result_s, 32);
+
+ return uECC_verify(publicKey, sign_hash, sign);
}
int
const unsigned char *keyx_params, size_t keyx_params_size,
unsigned char *result_r, unsigned char *result_s);
+int dtls_ecdhe_psk_pre_master_secret(unsigned char *psk, size_t psklen,
+ unsigned char *ecc_priv_key,
+ unsigned char *ecc_pub_key_x,
+ unsigned char *ecc_pub_key_y,
+ size_t ecc_key_size,
+ unsigned char *result,
+ size_t result_len);
+
int dtls_ec_key_from_uint32_asn1(const uint32_t *key, size_t key_size,
unsigned char *buf);
#include <time.h>
#endif
+#ifdef __ANDROID__
+#include <android/log.h>
+#endif
+
#include "global.h"
#include "debug.h"
}
/* this array has the same order as the type log_t */
+#ifdef __ANDROID__
+static android_LogPriority loglevels_android[] = {
+ ANDROID_LOG_FATAL,
+ ANDROID_LOG_ERROR,
+ ANDROID_LOG_ERROR,
+ ANDROID_LOG_WARN,
+ ANDROID_LOG_INFO,
+ ANDROID_LOG_INFO,
+ ANDROID_LOG_DEBUG
+};
+#else
static char *loglevels[] = {
"EMRG", "ALRT", "CRIT", "WARN", "NOTE", "INFO", "DEBG"
};
+#endif
#ifdef HAVE_TIME_H
dsrv_print_addr(const session_t *addr, char *buf, size_t len) {
#ifdef HAVE_ARPA_INET_H
const void *addrptr = NULL;
+#ifdef __ANDROID__
+ unsigned short int port;
+#else
in_port_t port;
+#endif
char *p = buf;
switch (addr->addr.sa.sa_family) {
#endif
}
-#ifndef WITH_CONTIKI
+#ifdef __ANDROID__
+void
+dsrv_log(log_t level, char *format, ...) {
+ va_list ap;
+
+ if (maxlog < level)
+ return;
+
+ va_start(ap, format);
+ __android_log_vprint(loglevels_android[level], PACKAGE_NAME, format, ap);
+ va_end(ap);
+}
+#elif !defined (WITH_CONTIKI)
void
dsrv_log(log_t level, char *format, ...) {
static char timebuf[32];
dsrv_log(level, "%s: %s\n", name, addrbuf);
}
-#ifndef WITH_CONTIKI
+#ifdef __ANDROID__
+void
+dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend) {
+ char *hex_dump_text;
+ char *p;
+ int ret;
+ int size;
+
+ if (maxlog < level)
+ return;
+
+ size = length * 3 + strlen(name) + 22;
+ hex_dump_text = malloc(size);
+ if (!hex_dump_text)
+ return;
+
+ p = hex_dump_text;
+
+ ret = snprintf(p, size, "%s: (%zu bytes): ", name, length);
+ if (ret >= size)
+ goto print;
+ p += ret;
+ size -= ret;
+ while (length--) {
+ ret = snprintf(p, size, "%02X ", *buf++);
+ if (ret >= size)
+ goto print;
+ p += ret;
+ size -= ret;
+ }
+print:
+ __android_log_print(loglevels_android[level], PACKAGE_NAME, "%s\n", hex_dump_text);
+ free(hex_dump_text);
+}
+#elif !defined (WITH_CONTIKI)
void
dtls_dsrv_hexdump_log(log_t level, const char *name, const unsigned char *buf, size_t length, int extend) {
static char timebuf[32];
dtls_hash_finalize(sha256hash, &hs_hash);
ret = dtls_ecdsa_verify_sig_hash(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
- sizeof(config->keyx.ecc.other_pub_x),
- sha256hash, sizeof(sha256hash),
- result_r, result_s);
+ sizeof(config->keyx.ecc.other_pub_x),
+ sha256hash, sizeof(sha256hash),
+ result_r, result_s);
- if (ret < 0) {
+ if (ret <= 0) {
dtls_alert("wrong signature err: %i\n", ret);
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
data_length -= ret;
ret = dtls_ecdsa_verify_sig(config->keyx.ecc.other_pub_x, config->keyx.ecc.other_pub_y,
- sizeof(config->keyx.ecc.other_pub_x),
- config->tmp.random.client, DTLS_RANDOM_LENGTH,
- config->tmp.random.server, DTLS_RANDOM_LENGTH,
- key_params,
- 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
- result_r, result_s);
-
- if (ret < 0) {
+ sizeof(config->keyx.ecc.other_pub_x),
+ config->tmp.random.client, DTLS_RANDOM_LENGTH,
+ config->tmp.random.server, DTLS_RANDOM_LENGTH,
+ key_params,
+ 1 + 2 + 1 + 1 + (2 * DTLS_EC_KEY_SIZE),
+ result_r, result_s);
+
+ if (ret <= 0) {
dtls_alert("wrong signature\n");
return dtls_alert_fatal_create(DTLS_ALERT_HANDSHAKE_FAILURE);
}
/**
* Called during handshake to check the peer's pubic key in this
* session. If the public key matches the session and should be
- * considerated valid the return value must be @c 0. If not valid,
+ * considered valid the return value must be @c 0. If not valid,
* the return value must be less than zero.
*
* If ECDSA should not be supported, set this pointer to NULL.
*/
int (*is_x509_active)(struct dtls_context_t *ctx);
#endif /* DTLS_X509 */
+
} dtls_handler_t;
/** Holds global information of the DTLS engine. */
--- /dev/null
+/*
+Copyright (c) 2015 Atmel Corporation. All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright notice,
+this list of conditions and the following disclaimer in the documentation
+and/or other materials provided with the distribution.
+
+3. Neither the name of Atmel nor the names of its contributors may be used to
+endorse or promote products derived from this software without specific
+prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
+IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+/**
+ * @file dtls_hal.h
+ * @brief DTLS Hardware Abstraction Layer API and visible structures.
+ */
+
+#ifndef _DTLS_DTLS_HAL_H_
+#define _DTLS_DTLS_HAL_H_
+
+#include <stdint.h>
+#include <stdbool.h>
+
+// Define return values for HAL
+#define HAL_SUCCESS (1)
+#define HAL_FAILURE (0)
+#define ENC_KEY_SIZE (32)
+
+/**
+ * This structure contains callback functions used by tinydtls to
+ * provide a hardware abstraction layer for secure storage .
+ */
+typedef struct {
+
+ /**
+ * Call this function during application initialization to create HAL related resources.
+ *
+ * @param[in] ctx The current DTLS context.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_init)(struct dtls_context_t *ctx);
+
+ /**
+ * Call this function during application shut down to clean up any HAL related resources.
+ *
+ * @param[in] ctx The current DTLS context.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_finish)(struct dtls_context_t *ctx);
+
+ /**
+ * Call this function to store unsecured data on hardware.
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_location_handle The handle to the hardware location to store p_data.
+ * @param[in] p_data The data to store.
+ * @param[in] data_size The size of the data to store.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_write_mem)(struct dtls_context_t *ctx,
+ const uint8_t* p_location,
+ const uint8_t* p_data,
+ size_t data_size);
+
+ /**
+ * Call this function to read data from unsecured storage from hardware.
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_location_handle The handle to the hardware location to read p_data.
+ * @param[in] p_data The data to read.
+ * @param[inout] data_size IN: The size of the buffer to receive data. OUT: The actual number of bytes read.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_read_mem)(struct dtls_context_t *ctx,
+ const uint8_t* p_location,
+ uint8_t* p_data,
+ size_t* dataSize);
+
+ /**
+ * Call this function to store sensitive data in secure hardware.
+ * Data will be securely stored and encrypted on the wire
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_location_handle The handle to the hardware location to store p_data.
+ * @param[in] p_data The data to store securely.
+ * @param[in] data_size The size of the data to store securely.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_write_mem_enc)(struct dtls_context_t *ctx,
+ const uint8_t* p_location,
+ const uint8_t* p_data,
+ size_t data_size);
+
+ /**
+ * Call this function to read sensitive data from secure hardware.
+ * Data will be read from secure storage and encrypted on the wire
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_location_handle The handle to the hardware location to read p_data.
+ * @param[in] p_data The data to read securely.
+ * @param[inout] data_size IN: The size of the buffer to receive data. OUT: The actual number of bytes read.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_read_mem_enc)(struct dtls_context_t *ctx,
+ const uint8_t* p_location,
+ uint8_t* p_data,
+ size_t* dataSize);
+
+ /**
+ * Call this function to generate a unique encryption key that will be used for secure storage.
+ * This encryption key should be stored as a platform resource
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[out] p_enc_key_out The internally generated unique encryption key that will be used for secure storage.
+ * This key needs to be stored on the platform.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_init_enckey)(struct dtls_context_t *ctx,
+ uint8_t p_enc_key_out[ENC_KEY_SIZE]);
+
+ /**
+ * Call this function to set a unique encryption key that will be used for secure storage.
+ * This encryption key should be stored as a platform resource
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_enc_key_in The encryption key that will be used for secure storage.
+ * This key needs to be stored on the platform.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_set_enckey)(struct dtls_context_t *ctx,
+ const uint8_t p_enc_key_in[ENC_KEY_SIZE]);
+
+ /**
+ * This function is called internally from HAL_read_mem_enc and HAL_write_mem_enc.
+ * The platform must implement this function to return the encryption key that was
+ * returned by HAL_init_enckey or HAL_set_enckey.
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[out] p_enc_key_out The encryption key that is used for secure storage.
+ * Retrieve from platform in this function.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_get_enckey)(struct dtls_context_t *ctx,
+ uint8_t p_enc_key_out[ENC_KEY_SIZE]);
+
+ /**
+ * Call this function to use the hardware to calculate a SHA256
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_msg The message to calculate the SHA256.
+ * @param[in] msg_size The size of the message to hash.
+ * @param[out] p_hash The hash of p_msg.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_sha2_calc)(struct dtls_context_t *ctx,
+ uint8_t *p_msg,
+ size_t msg_size,
+ uint8_t p_hash[SHA256_DIGEST_LENGTH]);
+
+ /**
+ * Call this function to use the hardware key derivation function (KDF)
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] p_seed The seed used to produce the key.
+ * @param[in] seed_size The size of the message to hash.
+ * @param[out] p_keyout The key produced by the KDF.
+ * @param[in] key_size The size of the key to be returned.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_kdf_calc)(struct dtls_context_t *ctx,
+ const uint8_t* p_seed,
+ const size_t seed_size,
+ uint8_t* p_keyout,
+ const size_t key_size);
+
+ /**
+ * Call this function to retrieve the specified certificate from hardware
+ *
+ * @param[in] ctx The current DTLS context.
+ * @param[in] cert_id An index into the certificate to returned.
+ * @param[inout] cert The certificate to be returned.
+ * @param[inout] cert_size The size of the certificate.
+ * @return HAL_SUCCESS or HAL_FAILURE
+ */
+ int (*HAL_get_x509_cert)(struct dtls_context_t *ctx,
+ uint32_t cert_ref,
+ uint8_t **cert,
+ size_t *cert_size);
+
+} dtls_hal_handler_t;
+
+
+#endif /* _DTLS_DTLS_HAL_H_ */
+
static void vli_square(uECC_word_t *p_result, uECC_word_t *p_left);
static void vli_modSquare_fast(uECC_word_t *p_result, uECC_word_t *p_left);
#endif
+// Function declarations to support the HAL shims
+int uECC_make_key_impl(uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_privateKey[uECC_BYTES]);
+int uECC_shared_secret_impl(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKey[uECC_BYTES], uint8_t p_secret[uECC_BYTES]);
+int uECC_sign_impl(const uint8_t p_privateKey[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2]);
+int uECC_verify_impl(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2]);
+int uECC_ecdhe_impl(const uint8_t p_public_key_in[uECC_BYTES*2], uint8_t p_public_key_out[uECC_BYTES*2], uint8_t p_secret[uECC_BYTES]);
+int uECC_get_pubkey_impl(const uint8_t p_key_handle[uECC_BYTES], uint8_t p_public_key[uECC_BYTES*2]);
#if (defined(_WIN32) || defined(_WIN64))
/* Windows */
#endif
+///////////////////////////////////////////////////////
+// Functions to set the callbacks for crypto operations
static uECC_RNG_Function g_rng = &default_RNG;
void uECC_set_rng(uECC_RNG_Function p_rng)
g_rng = p_rng;
}
+static uECC_make_key_Function g_make_key_cb = &uECC_make_key_impl;
+
+void uECC_set_make_key_cb(uECC_make_key_Function p_make_key_cb)
+{
+ g_make_key_cb = p_make_key_cb;
+}
+
+static uECC_shared_secret_Function g_shared_secret_cb = &uECC_shared_secret_impl;
+
+void uECC_set_shared_secret_cb(uECC_shared_secret_Function p_shared_secret_cb)
+{
+ g_shared_secret_cb = p_shared_secret_cb;
+}
+
+static uECC_sign_Function g_sign_cb = &uECC_sign_impl;
+
+void uECC_set_sign_cb(uECC_sign_Function p_sign_cb)
+{
+ g_sign_cb = p_sign_cb;
+}
+
+static uECC_verify_Function g_verify_cb = &uECC_verify_impl;
+
+void uECC_set_verify_cb(uECC_verify_Function p_verify_cb)
+{
+ g_verify_cb = p_verify_cb;
+}
+
+static uECC_ecdhe_Function g_ecdhe_cb = &uECC_ecdhe_impl;
+
+void uECC_set_ecdhe_cb(uECC_ecdhe_Function p_ecdhe_cb)
+{
+ g_ecdhe_cb = p_ecdhe_cb;
+}
+
+static uECC_get_pubkey_Function g_get_pubkey_cb = &uECC_get_pubkey_impl;
+
+void uECC_set_get_pubkey_cb(uECC_get_pubkey_Function p_get_pubkey_cb)
+{
+ g_get_pubkey_cb = p_get_pubkey_cb;
+}
+
+///////////////////////////////////////////////////////
+
+
#ifdef __GNUC__ /* Only support GCC inline asm for now */
#if (uECC_ASM && (uECC_PLATFORM == uECC_avr))
#include "asm_avr.inc"
#endif /* uECC_WORD_SIZE */
+// Safe calls to the callback functions
int uECC_make_key(uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_privateKey[uECC_BYTES])
{
+ // Check for a valid function pointer
+ if (g_make_key_cb != NULL)
+ {
+ return g_make_key_cb(p_publicKey, p_privateKey);
+ }
+ else
+ {
+ return uECC_make_key_impl(p_publicKey, p_privateKey);
+ }
+}
+
+int uECC_shared_secret(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKey[uECC_BYTES], uint8_t p_secret[uECC_BYTES])
+{
+ // Check for a valid function pointer
+ if (g_shared_secret_cb != NULL)
+ {
+ return g_shared_secret_cb(p_publicKey, p_privateKey, p_secret);
+ }
+ else
+ {
+ return uECC_shared_secret_impl(p_publicKey, p_privateKey, p_secret);
+ }
+}
+
+int uECC_sign(const uint8_t p_privateKey[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2])
+{
+ // Check for a valid function pointer
+ if (g_sign_cb != NULL)
+ {
+ return g_sign_cb(p_privateKey, p_hash, p_signature);
+ }
+ else
+ {
+ return uECC_sign_impl(p_privateKey, p_hash, p_signature);
+ }
+}
+
+int uECC_verify(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2])
+{
+ // Check for a valid function pointer
+ if (g_verify_cb != NULL)
+ {
+ return g_verify_cb(p_publicKey, p_hash, p_signature);
+ }
+ else
+ {
+ return uECC_verify_impl(p_publicKey, p_hash, p_signature);
+ }
+}
+
+int uECC_ecdhe(const uint8_t p_public_key_in[uECC_BYTES*2], uint8_t p_public_key_out[uECC_BYTES*2], uint8_t p_secret[uECC_BYTES])
+{
+ // Check for a valid function pointer
+ if (g_ecdhe_cb != NULL)
+ {
+ return g_ecdhe_cb(p_public_key_in, p_public_key_out, p_secret);
+ }
+ else
+ {
+ return uECC_ecdhe_impl(p_public_key_in, p_public_key_out, p_secret);
+ }
+}
+
+int uECC_get_pubkey(const uint8_t p_key_handle[uECC_BYTES], uint8_t p_public_key[uECC_BYTES*2])
+{
+ // Check for a valid function pointer
+ if (g_get_pubkey_cb != NULL)
+ {
+ return g_get_pubkey_cb(p_key_handle, p_public_key);
+ }
+ else
+ {
+ return uECC_get_pubkey_impl(p_key_handle, p_public_key);
+ }
+}
+
+int uECC_ecdhe_impl(const uint8_t p_public_key_in[uECC_BYTES*2], uint8_t p_public_key_out[uECC_BYTES*2], uint8_t p_secret[uECC_BYTES])
+{
+ return 0;
+}
+
+int uECC_get_pubkey_impl(const uint8_t p_key_handle[uECC_BYTES], uint8_t p_public_key[uECC_BYTES*2])
+{
+ return 0;
+}
+
+int uECC_make_key_impl(uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_privateKey[uECC_BYTES])
+{
EccPoint l_public;
uECC_word_t l_private[uECC_WORDS];
uECC_word_t l_tries = 0;
return 1;
}
-int uECC_shared_secret(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKey[uECC_BYTES], uint8_t p_secret[uECC_BYTES])
+int uECC_shared_secret_impl(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKey[uECC_BYTES], uint8_t p_secret[uECC_BYTES])
{
EccPoint l_public;
uECC_word_t l_private[uECC_WORDS];
}
#endif /* (uECC_CURVE != uECC_secp160r1) */
-int uECC_sign(const uint8_t p_privateKey[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2])
+int uECC_sign_impl(const uint8_t p_privateKey[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2])
{
uECC_word_t k[uECC_N_WORDS];
uECC_word_t l_tmp[uECC_N_WORDS];
return (a > b ? a : b);
}
-int uECC_verify(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2])
+int uECC_verify_impl(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2])
{
uECC_word_t u1[uECC_N_WORDS], u2[uECC_N_WORDS];
uECC_word_t z[uECC_N_WORDS];
*/
void uECC_set_rng(uECC_RNG_Function p_rng);
+//////////////////////////////////////////
+// DTLS_CRYPTO_HAL
+/**
+* Call this function to create a unique public-private key pair in secure hardware
+*
+* @param[out] p_publicKey The public key that is associated with the private key that was just created.
+* @param[out] p_privateKeyHandle A handle that is used to point to the private key stored in hardware.
+* @return 1 upon success, 0 if an error occurred.
+*/
+typedef int (*uECC_make_key_Function)(uint8_t p_publicKey[uECC_BYTES*2], uint8_t p_privateKeyHandle[uECC_BYTES]);
+
+/**
+* Set the callback function that will be used to generate a public-private key pair.
+* This function will replace uECC_make_key.
+*
+* @param[in] p_make_key_cb The function that will be used to generate a public-private key pair.
+*/
+void uECC_set_make_key_cb(uECC_make_key_Function p_make_key_cb);
+
+/**
+* Call this function to sign a hash using a hardware protected private key.
+*
+* @param[in] p_privateKeyHandle A handle that is used to point to the private key stored in hardware.
+* @param[in] p_hash The hash to sign.
+* @param[out] p_signature The signature that is produced in hardware by the private key..
+* @return 1 upon success, 0 if an error occurred.
+*/
+typedef int (*uECC_sign_Function)(uint8_t p_privateKeyHandle[uECC_BYTES], const uint8_t p_hash[uECC_BYTES], uint8_t p_signature[uECC_BYTES*2]);
+
+/**
+* Set the callback function that will be used to sign.
+* This function will replace uECC_sign.
+*
+* @param[in] p_sign_cb The function that will be used to sign.
+*/
+void uECC_set_sign_cb(uECC_sign_Function p_sign_cb);
+
+/**
+* Call this function to verify a signature using the public key and hash that was signed.
+*
+* @param[in] p_publicKey The public key that is associated with the private key that produced the signature.
+* @param[in] p_hash The hash that was signed.
+* @param[in] p_signature The signature that was produced the private key that is associated with p_public_key
+* @return 1 upon success, 0 if an error occurred.
+*/
+typedef int (*uECC_verify_Function)(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_hash[uECC_BYTES], const uint8_t p_signature[uECC_BYTES*2]);
+
+/**
+* Set the callback function that will be used to verify.
+* This function will replace uECC_verify.
+*
+* @param[in] p_verify_cb The function that will be used to verify.
+*/
+void uECC_set_verify_cb(uECC_verify_Function p_verify_cb);
+
+/**
+* Call this function to produce an ECDH shared key using the public key of the other node.
+* A hardware protected private key will be used for the point multiply
+*
+* @param[in] p_publicKey The public key from the other node used for communication.
+* @param[in] p_privateKeyHandle A handle that is used to point to the private key stored in hardware.
+* @param[out] p_secret The pre-master key that is produced by the point multiply with p_public_key and our private key
+* @return 1 upon success, 0 if an error occurred.
+*/
+typedef int (*uECC_shared_secret_Function)(const uint8_t p_publicKey[uECC_BYTES*2], const uint8_t p_privateKeyHandle[uECC_BYTES], uint8_t p_secret[uECC_BYTES]);
+
+/**
+* Set the callback function that will be used to produce a shared secret.
+* This function will replace uECC_shared_secret.
+*
+* @param[in] p_make_key_cb The function that will be used to generate the shared secret.
+*/
+void uECC_set_shared_secret_cb(uECC_shared_secret_Function p_shared_secret_cb);
+
+/**
+* Call this function to produce a shared key using the public key of the other node.
+* An ephemeral private key will be created in secure hardware that will be used for the point multiply
+*
+* @param[in] p_public_key The public key from the other node used for communication.
+* @param[out] p_public_key_out The ephemeral public key that will be used in the point multiply.
+* @param[out] p_secret The pre-master key that is produced by the point multiply with p_public_key and our private key
+* @return 1 upon success, 0 if an error occurred.
+*/
+typedef int (*uECC_ecdhe_Function)(const uint8_t p_public_key_in[uECC_BYTES*2],
+ uint8_t p_public_key_out[uECC_BYTES*2],
+ uint8_t p_secret[uECC_BYTES]);
+
+/**
+* Set the callback function that will be used to produce a ECDHE shared secret.
+*
+* @param[in] p_ecdhe_cb The function that will be used to generate the ECDHE shared secret.
+*/
+void uECC_set_ecdhe_cb(uECC_ecdhe_Function p_ecdhe_cb);
+
+/**
+* Call this function to return the public key for an existing private key.
+*
+* @param[out] p_key_handle A handle that is used to point to the private key stored in hardware.
+* The public key that is associated with this private key will be returned
+* @param[out] p_public_key The public key that is associated with the private key that was just created.
+* @return 1 upon success, 0 if an error occurred.
+*/
+typedef int (*uECC_get_pubkey_Function)(const uint8_t p_key_handle[uECC_BYTES],
+ uint8_t p_public_key[uECC_BYTES*2]);
+
+/**
+* Set the callback function that will be used to return the public key for an existing private key.
+*
+* @param[in] p_get_pubkey_cb The function that will be used to return the public key for an existing private key.
+*/
+void uECC_set_get_pubkey_cb(uECC_get_pubkey_Function p_get_pubkey_cb);
+
+
+/**
+* Call this function to produce a shared key using the public key of the other node.
+* An ephemeral private key will be created that will be used for the point multiply
+*
+* @param[in] p_public_key The public key from the other node used for communication.
+* @param[out] p_public_key_out The ephemeral public key that will be used in the point multiply.
+* @param[out] p_secret The pre-master key that is produced by the point multiply with p_public_key and our private key
+* @return 1 upon success, 0 if an error occurred.
+*/
+int uECC_ecdhe(const uint8_t p_public_key_in[uECC_BYTES*2],
+ uint8_t p_public_key_out[uECC_BYTES*2],
+ uint8_t p_secret[uECC_BYTES]);
+
+/**
+* Call this function to return the public key for an existing private key.
+*
+* @param[out] p_key_handle A handle that is used to point to the private key stored in hardware.
+* The public key that is associated with this private key will be returned
+* @param[out] p_public_key The public key that is associated with the private key that was just created.
+* @return 1 upon success, 0 if an error occurred.
+*/
+int uECC_get_pubkey(const uint8_t p_key_handle[uECC_BYTES],
+ uint8_t p_public_key[uECC_BYTES*2]);
+
+//////////////////////////////////////////
+
+
/* uECC_make_key() function.
Create a public/private key pair.
/** Define to 1 if building with X.509 support */
#define DTLS_X509 1
+/** Define to 1 if building with Hardware Abstraction Layer */
+#define DTLS_CRYPTO_HAL 0
+
#endif /* _DTLS_TINYDTLS_H_ */
/** Define to 1 if building with X.509 support */
#undef DTLS_X509
+/** Define to 1 if building with crypto hardware abstraction support */
+#undef DTLS_CRYPTO_HAL
+
#endif /* _DTLS_TINYDTLS_H_ */
echo `pwd`
+# Clean tmp directory.
+rm -rf ./tmp
+
+# Create directory structure for GBS Build
mkdir ./tmp
mkdir ./tmp/extlibs/
mkdir ./tmp/packaging
cp -R ./build_common $sourcedir/tmp
cp -R ./examples $sourcedir/tmp
-cp -R ./extlibs/tinycbor $sourcedir/tmp/extlibs
+
+# tinycbor is available as soft-link, so copying with 'dereference' option.
+cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs
+rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
+
cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
cp -R ./extlibs/sqlite3 $sourcedir/tmp/extlibs
cp ./tools/tizen/*.spec ./tmp/packaging
cp ./tools/tizen/*.manifest ./tmp/packaging
cp ./SConstruct ./tmp
+
+# copy dependency RPMs and conf files for tizen build
cp ./tools/tizen/*.rpm ./tmp
cp ./tools/tizen/.gbs.conf ./tmp
echo "Build is successful"
else
echo "Build failed!"
+ exit 1
fi
cd $sourcedir
rm -rf $sourcedir/tmp
+
+exit 0
OICStrcpy(hexOutVal, hexOutValSize, HexPrepend);
OICStrcat(hexOutVal, hexOutValSize, str);
- char *endPtr;
+ char *endPtr = NULL;
errno = 0;
double value = strtod(hexOutVal, &endPtr);
if (attributeList.list[i].oicType == OIC_ATTR_INT)
{
char *endPtr = NULL;
+ errno = 0;
// Third arg is 16 as outVal is a hex Number
uint64_t value = strtol (outVal, &endPtr, 16);
- if (*endPtr != 0)
+ if (*endPtr != 0 || errno != 0)
{
return OC_EH_ERROR;
}
OCTBSTACK_SRC + 'occollection.c',
OCTBSTACK_SRC + 'oicgroup.c',
'logger/src/logger.c',
- 'ocrandom/src/ocrandom.c'
+ 'ocrandom/src/ocrandom.c',
+ OCTBSTACK_SRC + "rdpayload.c"
]
liboctbstack_src.extend(env['cbor_files'])
* Connectivity Abstraction Interface APIs.
*/
#include "cacommon.h"
-
-#ifdef __WITH_DTLS__
-#include "ocsecurityconfig.h"
-#endif
-#ifdef __WITH_X509__
-#include "pki.h"
-#endif //__WITH_X509__
+#include "casecurityinterface.h"
#ifdef __cplusplus
extern "C"
#endif //RA_ADAPTER
-#ifdef __WITH_DTLS__
-
-/**
- * Binary blob containing device identity and the credentials for all devices
- * trusted by this device.
- */
-typedef struct
-{
- unsigned char identity[DTLS_PSK_ID_LEN]; /** identity of self. */
- uint32_t num; /** number of credentials in this blob. */
- OCDtlsPskCreds *creds; /** list of credentials. Size of this
- array is determined by 'num' variable. */
-} CADtlsPskCredsBlob_t;
-
-/**
- * Callback function type for getting DTLS credentials.
- * @param[out] credInfo DTLS credentials info. Handler has to allocate new memory for.
- * both credInfo and credInfo->creds which is then freed by CA.
- */
-typedef void (*CAGetDTLSCredentialsHandler)(CADtlsPskCredsBlob_t **credInfo);
-#endif //__WITH_DTLS__
-
-#ifdef __WITH_X509__
-/**
- * Binary structure containing certificate chain and certificate credentials
- * for this device.
- */
-typedef struct
-{
- // certificate message for DTLS
- unsigned char certificateChain[MAX_CERT_MESSAGE_LEN];
- // length of the certificate message
- uint32_t certificateChainLen;
- // number of certificates in certificate message
- uint8_t chainLen;
- // x component of EC public key
- uint8_t rootPublicKeyX[PUBLIC_KEY_SIZE / 2];
- // y component of EC public key
- uint8_t rootPublicKeyY[PUBLIC_KEY_SIZE / 2];
- // EC private key
- uint8_t devicePrivateKey[PRIVATE_KEY_SIZE];
-
-} CADtlsX509Creds_t;
-
-/**
- * @brief Callback function type for getting certificate credentials.
- * @param credInfo [OUT] Certificate credentials info. Handler has to allocate new memory for
- * credInfo which is then freed by CA
- * @return NONE
- */
-typedef int (*CAGetDTLSX509CredentialsHandler)(CADtlsX509Creds_t *credInfo);
-/**
- * @brief Callback function type for getting CRL.
- * @param crlInfo [OUT] Certificate credentials info. Handler has to allocate new memory for
- * credInfo which is then freed by CA
- * @return NONE
- */
-typedef void (*CAGetDTLSCrlHandler)(ByteArray crlInfo);
-#endif //__WITH_X509__
-
/**
* Initialize the connectivity abstraction module.
* It will initialize adapters, thread pool and other modules based on the platform
CAResult_t CAStartListeningServer();
/**
+ * Stops the server from receiving the multicast traffic. This is used by sleeping
+ * device to not receives the multicast traffic.
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED
+ */
+CAResult_t CAStopListeningServer();
+
+/**
* Starts discovery servers.
* This API is used by resource required clients for listening multicast requests.
* Based on the adapters configurations, different kinds of servers are started.
void CARegisterHandler(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
CAErrorCallback ErrorHandler);
-#ifdef __WITH_DTLS__
-/**
- * Register callback to get DTLS PSK credentials.
- * @param[in] GetDTLSCredentials GetDTLS Credetials callback.
- * @return ::CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSCredentialsHandler GetDTLSCredentials);
-#endif //__WITH_DTLS__
-
-#ifdef __WITH_X509__
-/**
- * @brief Register callback to get DTLS Cert credentials.
- * @param GetCertCredentials [IN] GetCert Credetials callback
- * @return #CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSX509CredentialsHandler(CAGetDTLSX509CredentialsHandler GetX509Credentials);
-/**
- * @brief Register callback to get CRL.
- * @param GetCrl [IN] GetCrl callback
- * @return #CA_STATUS_OK
- */
-CAResult_t CARegisterDTLSCrlHandler(CAGetDTLSCrlHandler GetCrl);
-#endif //__WITH_X509__
-
/**
* Create an endpoint description.
* @param[in] flags how the adapter should be used.
CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo);
/**
- * Send notification to the remote object.
- * @param[in] object Endpoint where the payload need to be sent.
- * This endpoint is delivered with Request or response callback.
- * @param[in] responseInfo Information for the response.
- * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED or ::CA_MEMORY_ALLOC_FAILED
- */
-CAResult_t CASendNotification(const CAEndpoint_t *object,
- const CAResponseInfo_t *responseInfo);
-
-/**
* Select network to use.
* @param[in] interestedNetwork Connectivity Type enum.
* @return ::CA_STATUS_OK or ::CA_NOT_SUPPORTED or
#endif
-#ifdef __WITH_DTLS__
-
-/**
- * Select the cipher suite for dtls handshake.
- *
- * @param[in] cipher cipher suite (Note : Make sure endianness).
- * 0xC018 : TLS_ECDH_anon_WITH_AES_128_CBC_SHA
- * 0xC0A8 : TLS_PSK_WITH_AES_128_CCM_8
- * 0xC0AE : TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
- *
- * @retval ::CA_STATUS_OK Successful.
- * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CASelectCipherSuite(const uint16_t cipher);
-
-/**
- * Enable TLS_ECDH_anon_WITH_AES_128_CBC_SHA cipher suite in dtls.
- *
- * @param[in] enable TRUE/FALSE enables/disables anonymous cipher suite.
- *
- * @retval ::CA_STATUS_OK Successful.
- * @retval ::CA_STATUS_FAILED Operation failed.
- *
- * @note anonymous cipher suite should only be enabled for 'JustWorks' provisioning.
- */
-CAResult_t CAEnableAnonECDHCipherSuite(const bool enable);
-
-
-/**
- * Generate ownerPSK using PRF.
- * OwnerPSK = TLS-PRF('master key' , 'oic.sec.doxm.jw',
- * 'ID of new device(Resource Server)',
- * 'ID of owner smart-phone(Provisioning Server)')
- *
- * @param[in] endpoint information of network address.
- * @param[in] label Ownership transfer method e.g)"oic.sec.doxm.jw".
- * @param[in] labelLen Byte length of label.
- * @param[in] rsrcServerDeviceID ID of new device(Resource Server).
- * @param[in] rsrcServerDeviceIDLen Byte length of rsrcServerDeviceID.
- * @param[in] provServerDeviceID label of previous owner.
- * @param[in] provServerDeviceIDLen byte length of provServerDeviceID.
- * @param[in,out] ownerPSK Output buffer for owner PSK.
- * @param[in] ownerPSKSize Byte length of the ownerPSK to be generated.
- *
- * @retval ::CA_STATUS_OK Successful.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t *endpoint,
- const uint8_t* label, const size_t labelLen,
- const uint8_t* rsrcServerDeviceID,
- const size_t rsrcServerDeviceIDLen,
- const uint8_t* provServerDeviceID,
- const size_t provServerDeviceIDLen,
- uint8_t* ownerPSK, const size_t ownerPSKSize);
-
-/**
- * Initiate DTLS handshake with selected cipher suite.
- *
- * @param[in] endpoint information of network address.
- *
- * @retval ::CA_STATUS_OK Successful.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint);
-
-/**
- * Close the DTLS session.
- *
- * @param[in] endpoint information of network address.
- *
- * @retval ::CA_STATUS_OK Successful.
- * @retval ::CA_STATUS_FAILED Operation failed.
- */
-CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint);
-
-#endif /* __WITH_DTLS__ */
#ifdef __cplusplus
} /* extern "C" */
--- /dev/null
+/* *****************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file
+ *
+ * This file contains the Security APIs for Resource Model to use.
+ */
+
+#ifndef CA_SECURITY_INTERFACE_H_
+#define CA_SECURITY_INTERFACE_H_
+
+#ifdef __WITH_X509__
+#include "pki.h"
+#endif //__WITH_X509__
+
+
+#ifdef __cplusplus
+extern "C"
+{
+#endif
+
+
+#ifdef __WITH_DTLS__
+/**
+ * @enum CADtlsPskCredType_t
+ * Type of PSK credential required during DTLS handshake
+ * It does not make much sense in bringing in all definitions from dtls.h into here.
+ * Therefore, redefining them here.
+ */
+typedef enum
+{
+ CA_DTLS_PSK_HINT,
+ CA_DTLS_PSK_IDENTITY,
+ CA_DTLS_PSK_KEY
+} CADtlsPskCredType_t;
+
+/**
+ * This internal callback is used by CA layer to
+ * retrieve PSK credentials from SRM.
+ *
+ * @param[in] type type of PSK data required by CA layer during DTLS handshake set.
+ * @param[in] desc Additional request information.
+ * @param[in] desc_len The actual length of desc.
+ * @param[out] result Must be filled with the requested information.
+ * @param[in] result_length Maximum size of @p result.
+ *
+ * @return The number of bytes written to @p result or a value
+ * less than zero on error.
+ */
+typedef int (*CAGetDTLSPskCredentialsHandler)( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length);
+
+/**
+ * Register callback to get DTLS PSK credentials.
+ * @param[in] GetDTLSCredentials GetDTLS Credetials callback.
+ * @return ::CA_STATUS_OK
+ */
+CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentials);
+
+#endif //__WITH_DTLS__
+
+#ifdef __WITH_X509__
+/**
+ * Binary structure containing certificate chain and certificate credentials
+ * for this device.
+ */
+typedef struct
+{
+ // certificate message for DTLS
+ unsigned char certificateChain[MAX_CERT_MESSAGE_LEN];
+ // length of the certificate message
+ uint32_t certificateChainLen;
+ // number of certificates in certificate message
+ uint8_t chainLen;
+ // x component of EC public key
+ uint8_t rootPublicKeyX[PUBLIC_KEY_SIZE / 2];
+ // y component of EC public key
+ uint8_t rootPublicKeyY[PUBLIC_KEY_SIZE / 2];
+ // EC private key
+ uint8_t devicePrivateKey[PRIVATE_KEY_SIZE];
+
+} CADtlsX509Creds_t;
+
+/**
+ * @brief Callback function type for getting certificate credentials.
+ * @param credInfo [OUT] Certificate credentials info. Handler has to allocate new memory for
+ * credInfo which is then freed by CA
+ * @return NONE
+ */
+typedef int (*CAGetDTLSX509CredentialsHandler)(CADtlsX509Creds_t *credInfo);
+/**
+ * @brief Callback function type for getting CRL.
+ * @param crlInfo [OUT] Certificate credentials info. Handler has to allocate new memory for
+ * credInfo which is then freed by CA
+ * @return NONE
+ */
+typedef void (*CAGetDTLSCrlHandler)(ByteArray crlInfo);
+
+/**
+ * @brief Register callback to get DTLS Cert credentials.
+ * @param GetCertCredentials [IN] GetCert Credetials callback
+ * @return #CA_STATUS_OK
+ */
+CAResult_t CARegisterDTLSX509CredentialsHandler(CAGetDTLSX509CredentialsHandler GetX509Credentials);
+/**
+ * @brief Register callback to get CRL.
+ * @param GetCrl [IN] GetCrl callback
+ * @return #CA_STATUS_OK
+ */
+CAResult_t CARegisterDTLSCrlHandler(CAGetDTLSCrlHandler GetCrl);
+#endif //__WITH_X509__
+
+
+#ifdef __WITH_DTLS__
+
+/**
+ * Select the cipher suite for dtls handshake.
+ *
+ * @param[in] cipher cipher suite (Note : Make sure endianness).
+ * 0xC018 : TLS_ECDH_anon_WITH_AES_128_CBC_SHA
+ * 0xC0A8 : TLS_PSK_WITH_AES_128_CCM_8
+ * 0xC0AE : TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8
+ *
+ * @retval ::CA_STATUS_OK Successful.
+ * @retval ::CA_STATUS_INVALID_PARAM Invalid input arguments.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CASelectCipherSuite(const uint16_t cipher);
+
+/**
+ * Enable TLS_ECDH_anon_WITH_AES_128_CBC_SHA cipher suite in dtls.
+ *
+ * @param[in] enable TRUE/FALSE enables/disables anonymous cipher suite.
+ *
+ * @retval ::CA_STATUS_OK Successful.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ *
+ * @note anonymous cipher suite should only be enabled for 'JustWorks' provisioning.
+ */
+CAResult_t CAEnableAnonECDHCipherSuite(const bool enable);
+
+
+/**
+ * Generate ownerPSK using PRF.
+ * OwnerPSK = TLS-PRF('master key' , 'oic.sec.doxm.jw',
+ * 'ID of new device(Resource Server)',
+ * 'ID of owner smart-phone(Provisioning Server)')
+ *
+ * @param[in] endpoint information of network address.
+ * @param[in] label Ownership transfer method e.g)"oic.sec.doxm.jw".
+ * @param[in] labelLen Byte length of label.
+ * @param[in] rsrcServerDeviceID ID of new device(Resource Server).
+ * @param[in] rsrcServerDeviceIDLen Byte length of rsrcServerDeviceID.
+ * @param[in] provServerDeviceID label of previous owner.
+ * @param[in] provServerDeviceIDLen byte length of provServerDeviceID.
+ * @param[in,out] ownerPSK Output buffer for owner PSK.
+ * @param[in] ownerPSKSize Byte length of the ownerPSK to be generated.
+ *
+ * @retval ::CA_STATUS_OK Successful.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAGenerateOwnerPSK(const CAEndpoint_t *endpoint,
+ const uint8_t* label, const size_t labelLen,
+ const uint8_t* rsrcServerDeviceID,
+ const size_t rsrcServerDeviceIDLen,
+ const uint8_t* provServerDeviceID,
+ const size_t provServerDeviceIDLen,
+ uint8_t* ownerPSK, const size_t ownerPSKSize);
+
+/**
+ * Initiate DTLS handshake with selected cipher suite.
+ *
+ * @param[in] endpoint information of network address.
+ *
+ * @retval ::CA_STATUS_OK Successful.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CAInitiateHandshake(const CAEndpoint_t *endpoint);
+
+/**
+ * Close the DTLS session.
+ *
+ * @param[in] endpoint information of network address.
+ *
+ * @retval ::CA_STATUS_OK Successful.
+ * @retval ::CA_STATUS_FAILED Operation failed.
+ */
+CAResult_t CACloseDtlsSession(const CAEndpoint_t *endpoint);
+
+#endif /* __WITH_DTLS__ */
+
+
+#ifdef __cplusplus
+} /* extern "C" */
+#endif
+
+
+#endif /* CA_SECURITY_INTERFACE_H_ */
+
cp -rf %{ROOTDIR}/con/inc/caedradapter.h* %{DEST_INC_DIR}/
cp -rf %{ROOTDIR}/con/inc/caleadapter.h* %{DEST_INC_DIR}/
cp -rf %{ROOTDIR}/con/api/cainterface.h* %{DEST_INC_DIR}/
+cp -rf %{ROOTDIR}/con/api/casecurityinterface.h* %{DEST_INC_DIR}/
cp -rf %{ROOTDIR}/com.oic.ca.pc %{DEST_LIB_DIR}/pkgconfig/
uint32_t u_linklist_length(const u_linklist_t *linklist)
{
- VERIFY_NON_NULL(linklist, TAG, "list is null");
-
+ if (NULL == linklist)
+ {
+ OIC_LOG(ERROR, TAG, "linklist is NULL");
+ return 0;
+ }
return linklist->size;
}
+++ /dev/null
- //*******************************************************************
- //
- // Copyright 2014 Intel Mobile Communications GmbH 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.
- //
- //
- //******************************************************************
-/**
- * @file
- *
- * This file contains all the constants which can be configured/modified as
- * per platform or security specific product usage scenarios.
- */
-
-
-#ifndef OC_SECURITY_CONFIG_H
-#define OC_SECURITY_CONFIG_H
-
-#include <stdint.h>
-
-#define DTLS_PSK_ID_LEN 16
-#define DTLS_PSK_PSK_LEN 16
-
-#define DtlsPskCredsBlobVer_1 1 /**< Credentials stored in plaintext */
-#define DtlsPskCredsBlobVer_CurrentVersion DtlsPskCredsBlobVer_1
-
-/**
- * Credentials for a device. Includes identity and the associated PSK.
- */
-typedef struct
-{
- unsigned char id[DTLS_PSK_ID_LEN];
- unsigned char psk[DTLS_PSK_PSK_LEN];
-} OCDtlsPskCreds;
-
-/**
- * Binary blob containing device identity and the credentials for all devices
- * trusted by this device.
- */
-typedef struct
-{
- unsigned char identity[DTLS_PSK_ID_LEN]; /** identity of self */
- uint32_t num; /** number of credentials in this blob */
- OCDtlsPskCreds creds[1]; /** list of credentials. Size of this
- array is determined by 'num' variable. */
-} OCDtlsPskCredsBlob;
-
-#endif //OC_SECURITY_CONFIG_H
-
-
-
typedef CAResult_t (*CAAdapterStartListeningServer)();
/**
+ * Stopping listening server to not receive multicast search requests
+ * Transport Specific Behavior:
+ * WIFI/ETH Stops multicast server on all available IPs. This is required for the
+ * thin device that call this function once all local resources are pushed to the
+ * resource directory.
+ * @return ::CA_STATUS_OK or ::CA_STATUS_FAILED
+ * ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+typedef CAResult_t (*CAAdapterStopListeningServer)();
+
+/**
* for starting discovery servers for receiving multicast advertisements
* Transport Specific Behavior:
* WIFI/ETH Starts multicast server on all available IPs and defined port
/** Listening Server function address. */
CAAdapterStartListeningServer startListenServer;
+ /** Stops receiving the multicast traffic. */
+ CAAdapterStopListeningServer stopListenServer;
+
/** Discovery Server function address. **/
CAAdapterStartDiscoveryServer startDiscoveryServer;
#include "uarraylist.h"
#include "camutex.h"
#include "caadapterutils.h"
-#include "ocsecurityconfig.h"
#include "cainterface.h"
#include "cacommon.h"
*/
#define MAX_SUPPORTED_ADAPTERS 2
-/**
- * The implementation will be provided by OIC RI layer.
- */
-extern void OCGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
-
typedef void (*CAPacketReceivedCallback)(const CASecureEndpoint_t *sep,
const void *data, uint32_t dataLength);
/**
* Register callback to get DTLS PSK credentials.
- * @param[in] credCallback callback to get DTLS credentials.
+ * @param[in] credCallback callback to get DTLS PSK credentials.
*/
-void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback);
+void CADTLSSetCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
/**
* Select the cipher suite for dtls handshake
* @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
- const CAEndpoint_t *endpoint);
+ const CAEndpoint_t *endpoint, coap_list_t **options);
/**
* Write the block option2 in pdu binary data.
* @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
- const CABlockDataID_t *blockID);
+ const CABlockDataID_t *blockID, coap_list_t **options);
/**
* Write the block option1 in pdu binary data.
* @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
- const CABlockDataID_t *blockID);
+ const CABlockDataID_t *blockID, coap_list_t **options);
/**
* Add the block option in pdu data.
* @param[in] blockType block option type.
* @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
-CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType);
+CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType,
+ coap_list_t **options);
/**
* Add the size option in pdu data.
* @param[in] dataLength the total payload length to be sent.
* @return ::CASTATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
-CAResult_t CAAddBlockSizeOption(coap_pdu_t *pdu, uint16_t sizeType, size_t dataLength);
+CAResult_t CAAddBlockSizeOption(coap_pdu_t *pdu, uint16_t sizeType, size_t dataLength,
+ coap_list_t **options);
/**
* Get the size option from pdu data.
CAResult_t CAStartEDRListeningServer();
/**
+ * Stop listening server for receiving multicast search requests.
+ * Stop RFCOMM Server with prefixed UUID as per OIC specification.
+ *
+ * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAStopEDRListeningServer();
+
+/**
* Starting discovery server for receiving multicast advertisements.
* Starts RFCOMM Server with prefixed UUID as per OIC specification.
*
CAResult_t CAStartEDRListeningServer();
/**
+ * @brief Stops listening server for receiving multicast search requests.
+ *
+ * @return #CA_STATUS_OK or Appropriate error code
+ */
+CAResult_t CAStopEDRListeningServer();
+
+/**
* @brief Starts discovery server for receiving multicast advertisements.
* Starts RFCOMM Server with prefixed UUID as per OIC specification.
* @return #CA_STATUS_OK or Appropriate error code
CAResult_t CAStartListeningServerAdapters();
/**
+ * Stop listening servers to receive search requests from clients.
+ * @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
+ */
+CAResult_t CAStopListeningServerAdapters();
+
+/**
* Start discovery servers to receive advertisements from server.
* @return ::CA_STATUS_OK or ERROR CODES (::CAResult_t error codes in cacommon.h).
*/
CAResult_t CAStartListeningServerAdapters();
/**
+ * @brief Stops listening servers to receive search requests from clients
+ * @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
+ */
+CAResult_t CAStopListeningServerAdapters();
+
+/**
* @brief Start discovery servers to receive advertisements from server
* @return CA_STATUS_OK or ERROR CODES ( CAResult_t error codes in cacommon.h)
*/
CAResult_t CAStartIPListeningServer();
/**
+ * Stop listening server from receiving multicast search requests.
+ * Transport Specific Behavior:
+ * IP closes open multicast socket for a particular interface.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAStopIPListeningServer();
+
+/**
* Start discovery servers for receiving multicast advertisements.
* Transport Specific Behavior:
* IP Starts multicast server on a particular interface and prefixed port
void CAIPStopServer();
/**
+ * Starts receiving the multicast traffic.
+ *
+ * This will be used in case sleepy device wants to start back receiving the multicast
+ * traffic.
+ */
+CAResult_t CAIPStartListenServer();
+
+/**
+ * Stops the multicast traffic.
+ *
+ * This is to be used by the sleeping device to stop receiving multicast traffic.
+ * Once this is set no multicast traffic will be received. Device can still receive
+ * the unicast traffic.
+ */
+CAResult_t CAIPStopListenServer();
+
+/**
* Set this callback for receiving data packets from peer devices.
*
* @param[in] callback Callback to be notified on reception of unicast/multicast data packets.
* @param[in] endpoint endpoint information.
* @return generated pdu.
*/
-coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint);
+coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint,
+ coap_list_t **optlist, coap_transport_type *transport);
/**
* extracts request information from received pdu.
* @return generated pdu.
*/
coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
- const CAEndpoint_t *endpoint, coap_list_t *options);
+ const CAEndpoint_t *endpoint, coap_list_t *options,
+ coap_transport_type *transport);
/**
* parse the URI and creates the options.
CAResult_t CAStartRAListeningServer();
/**
+ * Stops listening server from receiving search requests.
+ * @return ::CA_NOT_SUPPORTED.
+ */
+CAResult_t CAStopRAListeningServer();
+
+/**
* Start discovery servers for receiving advertisements.
* @return ::CA_NOT_SUPPORTED.
*/
CAResult_t CAStartTCPListeningServer();
/**
+ * Stops listening server from receiving connect requests.
+ * Transport Specific Behavior:
+ * TCP Stops Listening Server on a particular interface and prefixed port
+ * number and as per OIC Specification.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+CAResult_t CAStopTCPListeningServer();
+
+/**
* Start discovery servers for receiving advertisements.
* Transport Specific Behavior:
* TCP Starts Discovery server on a particular interface and prefixed port
unsigned int length_field_data = 0;
switch(transport)
{
+ case coap_tcp:
+ length = header[0] >> 4;
+ break;
case coap_tcp_8bit:
length = header[1] + COAP_TCP_LENGTH_FIELD_8_BIT;
break;
}
}
dependencies {
- classpath 'com.android.tools.build:gradle:1.1.0'
+ classpath 'com.android.tools.build:gradle:1.3.0'
}
}
DLog.v(TAG, "SendNotification click");
if ( selectedNetwork != -1) {
RM.RMSendNotification(mNotification_ed.getText().toString(),
- null, selectedNetwork, isSecured, msgType, responseValue);
+ null, selectedNetwork, isSecured, msgType);
}
else {
DLog.v(TAG, "Please Select Network Type");
public native void RMAdvertiseResource(String advertiseResource);
public native void RMSendNotification(String uri, String payload,
- int selectedNetwork, int isSecured, int msgType, int responseValue);
+ int selectedNetwork, int isSecured, int msgType);
public native void RMSelectNetwork(int interestedNetwork);
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LOG_TAG, __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
-/**
- * @def RS_IDENTITY
- * @brief
- */
-#define IDENTITY ("1111111111111111")
-/* @def RS_CLIENT_PSK
- * @brief
- */
-#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
+// Iotivity Device Identity.
+const unsigned char IDENTITY[] = ("1111111111111111");
+
+// PSK between this device and peer device.
+const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
#define PORT_LENGTH 5
#define SECURE_DEFAULT_PORT 5684
}
#ifdef __WITH_DTLS__
-static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
-
-void clearDtlsCredentialInfo()
-{
- LOGI("clearDtlsCredentialInfo IN");
- if (pskCredsBlob)
- {
- // Initialize sensitive data to zeroes before freeing.
- if (NULL != pskCredsBlob->creds)
- {
- memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds)*(pskCredsBlob->num));
- free(pskCredsBlob->creds);
- }
-
- memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
- free(pskCredsBlob);
- pskCredsBlob = NULL;
- }
- LOGI("clearDtlsCredentialInfo OUT");
-}
-
// Internal API. Invoked by OC stack to retrieve credentials from this module
-void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length)
{
LOGI("CAGetDtlsPskCredentials IN");
- *credInfo = (CADtlsPskCredsBlob_t *) malloc(sizeof(CADtlsPskCredsBlob_t));
- if (NULL == *credInfo)
+
+ int32_t ret = -1;
+
+ if (NULL == result)
{
- LOGE("Failed to allocate credential blob.");
- return;
+ return ret;
}
- int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
- (*credInfo)->creds = (OCDtlsPskCreds *) malloc(credLen);
- if (NULL == (*credInfo)->creds)
+ switch (type)
{
- LOGE("Failed to allocate crentials.");
- free(*credInfo);
- *credInfo = NULL;
- return;
- }
+ case CA_DTLS_PSK_HINT:
+ case CA_DTLS_PSK_IDENTITY:
- memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
- (*credInfo)->num = pskCredsBlob->num;
- memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
+ if (result_length < sizeof(IDENTITY))
+ {
+ LOGE("ERROR : Wrong value for result for storing IDENTITY");
+ return ret;
+ }
- LOGI("CAGetDtlsPskCredentials OUT");
-}
+ memcpy(result, IDENTITY, sizeof(IDENTITY));
+ ret = sizeof(IDENTITY);
+ break;
-CAResult_t SetCredentials()
-{
- LOGI("SetCredentials IN");
- pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
- if (NULL == pskCredsBlob)
- {
- LOGE("Memory allocation failed!");
- return CA_MEMORY_ALLOC_FAILED;
- }
- memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+ case CA_DTLS_PSK_KEY:
- pskCredsBlob->num = 1;
+ if ((desc_len == sizeof(IDENTITY)) &&
+ memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
+ {
+ if (result_length < sizeof(RS_CLIENT_PSK))
+ {
+ LOGE("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
+ return ret;
+ }
- pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) *(pskCredsBlob->num));
- if (NULL == pskCredsBlob->creds)
- {
- LOGE("Memory allocation failed!");
- return CA_MEMORY_ALLOC_FAILED;
+ memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
+ ret = sizeof(RS_CLIENT_PSK);
+ }
+ break;
+
+ default:
+
+ LOGE("Wrong value passed for PSK_CRED_TYPE.");
+ ret = -1;
}
- memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
- memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
- LOGI("SetCredentials OUT");
- return CA_STATUS_OK;
+ LOGI("CAGetDtlsPskCredentials OUT\n");
+ return ret;
}
+
#endif
JNIEXPORT jint JNI_OnLoad(JavaVM *jvm, void *reserved)
}
#ifdef __WITH_DTLS__
- if (CA_STATUS_OK != SetCredentials())
- {
- LOGE("SetCredentials failed");
- return;
- }
-
res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
if(CA_STATUS_OK != res)
{
JNIEXPORT void JNICALL
Java_org_iotivity_ca_service_RMInterface_RMSendNotification(JNIEnv *env, jobject obj, jstring uri,
jstring payload, jint selectedNetwork,
- jint isSecured, jint msgType,
- jint responseValue)
+ jint isSecured, jint msgType)
{
LOGI("selectedNetwork - %d", selectedNetwork);
if (!env || !obj)
return;
}
- CAInfo_t responseData = { 0 };
- responseData.token = token;
- responseData.tokenLength = tokenLength;
- responseData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
- if (NULL == responseData.resourceUri)
+ CAInfo_t requestData = { 0 };
+ requestData.token = token;
+ requestData.tokenLength = tokenLength;
+ requestData.resourceUri = (CAURI_t) malloc(sizeof(resourceURI));
+ if (NULL == requestData.resourceUri)
{
LOGE("Memory allocation failed!");
// destroy token
CADestroyEndpoint(endpoint);
return;
}
- memcpy(responseData.resourceUri, resourceURI, sizeof(resourceURI));
+ memcpy(requestData.resourceUri, resourceURI, sizeof(resourceURI));
if (1 == isSecured)
{
uint32_t length = sizeof(SECURE_INFO_DATA) + strlen(resourceURI);
- responseData.payload = (CAPayload_t) malloc(length);
- if (NULL == responseData.payload)
+ requestData.payload = (CAPayload_t) malloc(length);
+ if (NULL == requestData.payload)
{
LOGE("Memory allocation failed!");
// destroy token
// destroy remote endpoint
CADestroyEndpoint(endpoint);
- free(responseData.resourceUri);
+ free(requestData.resourceUri);
return;
}
- snprintf((char *) responseData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
- responseData.payloadSize = length;
+ snprintf((char *) requestData.payload, length, SECURE_INFO_DATA, resourceURI, g_localSecurePort);
+ requestData.payloadSize = length;
}
else
{
uint32_t length = sizeof(NORMAL_INFO_DATA) + strlen(resourceURI);
- responseData.payload = (CAPayload_t) malloc(length);
- if (NULL == responseData.payload)
+ requestData.payload = (CAPayload_t) malloc(length);
+ if (NULL == requestData.payload)
{
LOGE("Memory allocation failed!");
// destroy token
// destroy remote endpoint
CADestroyEndpoint(endpoint);
- free(responseData.resourceUri);
+ free(requestData.resourceUri);
return;
}
- snprintf((char *) responseData.payload, length, NORMAL_INFO_DATA, resourceURI);
- responseData.payloadSize = length;
+ snprintf((char *) requestData.payload, length, NORMAL_INFO_DATA, resourceURI);
+ requestData.payloadSize = length;
}
- responseData.type = messageType;
+ requestData.type = messageType;
- CAResponseInfo_t responseInfo = { 0 };
- responseInfo.result = responseValue;
- responseInfo.info = responseData;
+ CARequestInfo_t requestInfo = { 0 };
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
// send notification
- if (CA_STATUS_OK != CASendNotification(endpoint, &responseInfo))
+ if (CA_STATUS_OK != CASendRequest(endpoint, &requestInfo))
{
LOGE("Could not send notification");
}
// destroy remote endpoint
CADestroyEndpoint(endpoint);
- free(responseData.payload);
- free(responseData.resourceUri);
+ free(requestData.payload);
+ free(requestData.resourceUri);
}
JNIEXPORT void JNICALL
* Signature: (Ljava/lang/String;Ljava/lang/String;IIII)V
*/
JNIEXPORT void JNICALL Java_org_iotivity_ca_service_RMInterface_RMSendNotification
- (JNIEnv *, jobject, jstring, jstring, jint, jint, jint, jint);
+ (JNIEnv *, jobject, jstring, jstring, jint, jint, jint);
/*
* Class: org_iotivity_ca_service_RMInterface
if (res != CA_STATUS_OK || (!token))
{
Serial.println("token error");
+ CADestroyEndpoint(endpoint);
return;
}
if (res != CA_STATUS_OK || (!token))
{
Serial.println("token error");
+ CADestroyEndpoint(endpoint);
return;
}
if (res != CA_STATUS_OK || (!token))
{
Serial.println("token error");
+ CADestroyEndpoint(endpoint);
return;
}
- CAInfo_t respondData = {CA_MSG_NONCONFIRM};
- respondData.token = token;
- respondData.tokenLength = tokenLength;
- respondData.payload = (CAPayload_t)"Notification Data";
- respondData.payloadSize = strlen((const char *) respondData.payload);
- respondData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
- strcpy(respondData.resourceUri, resourceUri);
+ CAInfo_t requestData = {CA_MSG_NONCONFIRM};
+ requestData.token = token;
+ requestData.tokenLength = tokenLength;
+ requestData.payload = (CAPayload_t)"Notification Data";
+ requestData.payloadSize = strlen((const char *) requestData.payload);
+ requestData.resourceUri = (char *)OICMalloc(strlen(resourceUri) + 1);
+ strcpy(requestData.resourceUri, resourceUri);
- CAResponseInfo_t responseInfo = {CA_BAD_REQ, {CA_MSG_RESET}};
- responseInfo.result = CA_CONTENT;
- responseInfo.info = respondData;
+ CARequestInfo_t requestInfo = {CA_GET, {CA_MSG_RESET}};
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
// send request
- CASendNotification(endpoint, &responseInfo);
+ CASendRequest(endpoint, &requestInfo);
// destroy remote endpoint
if (NULL != endpoint)
{
#include "cacommon.h"
#include "cainterface.h"
#include "oic_string.h"
-#ifdef __WITH_DTLS__
-#include "ocsecurityconfig.h"
-#endif
#define MAX_BUF_LEN 1024
#define MAX_OPT_LEN 16
#define BLOCK_SIZE(arg) (1 << ((arg) + 4))
#endif
-/**
- * @def RS_IDENTITY
- * @brief
- */
-#define IDENTITY ("1111111111111111")
-/* @def RS_CLIENT_PSK
- * @brief
- */
-#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
+// Iotivity Device Identity.
+const unsigned char IDENTITY[] = ("1111111111111111");
+
+// PSK between this device and peer device.
+const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
int g_received;
uint16_t g_local_secure_port = SECURE_DEFAULT_PORT;
"\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
#ifdef __WITH_DTLS__
-static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
-
-void clearDtlsCredentialInfo()
-{
- printf("clearDtlsCredentialInfo IN\n");
- if (pskCredsBlob)
- {
- // Initialize sensitive data to zeroes before freeing.
- if (pskCredsBlob->creds)
- {
- memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
- free(pskCredsBlob->creds);
- }
-
- memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
- free(pskCredsBlob);
- pskCredsBlob = NULL;
- }
- printf("clearDtlsCredentialInfo OUT\n");
-}
-
#ifdef __WITH_X509__
int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
{
{
return (int*) NULL;
}
-#endif
+#endif //__WITH_X509__
// Internal API. Invoked by CA stack to retrieve credentials from this module
-void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length)
{
printf("CAGetDtlsPskCredentials IN\n");
- if(!credInfo)
- {
- printf("Invalid credential container");
- return;
- }
- *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
- if (NULL == *credInfo)
+ int32_t ret = -1;
+
+ if (NULL == result)
{
- printf("Failed to allocate credential blob.");
- return;
+ return ret;
}
- size_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
- (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
- if (NULL == (*credInfo)->creds)
+ switch (type)
{
- printf("Failed to allocate credentials.");
- free(*credInfo);
- *credInfo = NULL;
- return;
- }
+ case CA_DTLS_PSK_HINT:
+ case CA_DTLS_PSK_IDENTITY:
- memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
- (*credInfo)->num = pskCredsBlob->num;
- memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
+ if (result_length < sizeof(IDENTITY))
+ {
+ printf("ERROR : Wrong value for result for storing IDENTITY");
+ return ret;
+ }
- printf("CAGetDtlsPskCredentials OUT\n");
-}
+ memcpy(result, IDENTITY, sizeof(IDENTITY));
+ ret = sizeof(IDENTITY);
+ break;
+ case CA_DTLS_PSK_KEY:
-CAResult_t SetCredentials()
-{
- printf("SetCredentials IN\n");
- pskCredsBlob = (CADtlsPskCredsBlob_t *)calloc(1, sizeof(CADtlsPskCredsBlob_t));
- if (NULL == pskCredsBlob)
- {
- printf("Memory allocation failed!\n");
- return CA_MEMORY_ALLOC_FAILED;
- }
- memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+ if ((desc_len == sizeof(IDENTITY)) &&
+ memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
+ {
+ if (result_length < sizeof(RS_CLIENT_PSK))
+ {
+ printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
+ return ret;
+ }
+ memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
+ ret = sizeof(RS_CLIENT_PSK);
+ }
+ break;
- pskCredsBlob->num = 1;
+ default:
- pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
- if (NULL == pskCredsBlob->creds)
- {
- printf("Memory allocation failed!\n");
- free(pskCredsBlob);
- return CA_MEMORY_ALLOC_FAILED;
+ printf("Wrong value passed for PSK_CRED_TYPE.");
+ ret = -1;
}
- memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
- memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
-
- printf("SetCredentials OUT\n");
- return CA_STATUS_OK;
+ printf("CAGetDtlsPskCredentials OUT\n");
+ return ret;
}
-#endif
+
+#endif //__WITH_DTLS__
int main()
{
return -1;
}
- /*
- * Read DTLS PSK credentials from persistent storage and
- * set in the OC stack.
- */
+ // Set the PSK Credentials callback handler.
#ifdef __WITH_DTLS__
- res = SetCredentials();
- if (CA_STATUS_OK != res)
- {
- printf("SetCredentials failed\n");
- return -1;
- }
-
res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
if (CA_STATUS_OK != res)
{
- printf("Set credential handler fail\n");
+ printf("Register credential handler fail\n");
return -1;
}
#endif
g_last_request_token = NULL;
CATerminate();
-#ifdef __WITH_DTLS__
- clearDtlsCredentialInfo();
-#endif
return 0;
}
CAPayload_t payload = (CAPayload_t) "TempNotificationData";
size_t payloadSize = strlen((const char *) payload);
- CAInfo_t respondData = { .type = messageType,
+ CAInfo_t requestData = { .type = messageType,
.messageId = 0,
.token = token,
.tokenLength = tokenLength,
.numOptions = 0,
.payload = payload,
.payloadSize = payloadSize,
- .resourceUri = (CAURI_t)uri };
+ .resourceUri = (CAURI_t) uri };
- CAResponseInfo_t responseInfo = { .result = CA_CONTENT,
- .info = respondData };
+ CARequestInfo_t requestInfo = { .method = CA_GET,
+ .info = requestData };
// send request
- res = CASendNotification(endpoint, &responseInfo);
+ res = CASendRequest(endpoint, &requestInfo);
if (CA_STATUS_OK != res)
{
printf("Send notification error, error code: %d\n", res);
#include "cacommon.h"
#include "cainterface.h"
-#ifdef __WITH_DTLS__
-#include "ocsecurityconfig.h"
-#endif
/**
* @def MAX_BUF_LEN
* @brief maximum buffer length
#define COAPS_PREFIX "coaps://"
#define COAPS_PREFIX_LEN 8
-/**
- * @def RS_IDENTITY
- * @brief
- */
-#define IDENTITY ("1111111111111111")
-/* @def RS_CLIENT_PSK
- * @brief
- */
-#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
+// Iotivity Device Identity.
+const unsigned char IDENTITY[] = ("1111111111111111");
+
+// PSK between this device and peer device.
+const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
/**
* Max size for big payload.
"\"if\":[\"oic.if.baseline\"],\"obs\":1}}]}";
#ifdef __WITH_DTLS__
-static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
-
-void clearDtlsCredentialInfo()
-{
- printf("clearDtlsCredentialInfo IN\n");
- if (pskCredsBlob)
- {
- // Initialize sensitive data to zeroes before freeing.
- if (pskCredsBlob->creds)
- {
- memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
- free(pskCredsBlob->creds);
- }
-
- memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
- free(pskCredsBlob);
- pskCredsBlob = NULL;
- }
- printf("clearDtlsCredentialInfo OUT\n");
-}
-
// Internal API. Invoked by CA stack to retrieve credentials from this module.
-void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length)
{
printf("CAGetDtlsPskCredentials IN\n");
- if(NULL == credInfo)
- {
- printf("Invalid credential container");
- return;
- }
+ int32_t ret = -1;
- *credInfo = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
- if (NULL == *credInfo)
+ if (NULL == result)
{
- printf("Failed to allocate credential blob.");
- return;
+ return ret;
}
- int16_t credLen = sizeof(OCDtlsPskCreds) * (pskCredsBlob->num);
- (*credInfo)->creds = (OCDtlsPskCreds *)malloc(credLen);
- if (NULL == (*credInfo)->creds)
+ switch (type)
{
- printf("Failed to allocate credentials.");
- free(*credInfo);
- *credInfo = NULL;
- return;
- }
+ case CA_DTLS_PSK_HINT:
+ case CA_DTLS_PSK_IDENTITY:
- memcpy((*credInfo)->identity, pskCredsBlob->identity, DTLS_PSK_ID_LEN);
- (*credInfo)->num = pskCredsBlob->num;
- memcpy((*credInfo)->creds, pskCredsBlob->creds, credLen);
+ if (result_length < sizeof(IDENTITY))
+ {
+ printf("ERROR : Wrong value for result for storing IDENTITY");
+ return ret;
+ }
- printf("CAGetDtlsPskCredentials OUT\n");
-}
+ memcpy(result, IDENTITY, sizeof(IDENTITY));
+ ret = sizeof(IDENTITY);
+ break;
-CAResult_t SetCredentials()
-{
- printf("SetCredentials IN\n");
- pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
- if (NULL == pskCredsBlob)
- {
- printf("Memory allocation failed!\n");
- return CA_MEMORY_ALLOC_FAILED;
- }
- memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
+ case CA_DTLS_PSK_KEY:
- pskCredsBlob->num = 1;
+ if ((desc_len == sizeof(IDENTITY)) &&
+ memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
+ {
+ if (result_length < sizeof(RS_CLIENT_PSK))
+ {
+ printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
+ return ret;
+ }
- pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
- if (NULL == pskCredsBlob->creds)
- {
- printf("Memory allocation failed!\n");
- free(pskCredsBlob);
- return CA_MEMORY_ALLOC_FAILED;
- }
+ memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
+ ret = sizeof(RS_CLIENT_PSK);
+ }
+ break;
- memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
- memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
+ default:
- printf("SetCredentials OUT\n");
- return CA_STATUS_OK;
+ printf("Wrong value passed for PSK_CRED_TYPE.");
+ ret = -1;
+ }
+
+ printf("CAGetDtlsPskCredentials OUT\n");
+ return ret;
}
#endif
return -1;
}
- /*
- * Read DTLS PSK credentials from persistent storage and
- * set in the OC stack.
- */
+ // Set the PSK Credentials callback handler.
#ifdef __WITH_DTLS__
- res = SetCredentials();
- if (CA_STATUS_OK != res)
- {
- printf("SetCredentials failed\n");
- return -1;
- }
-
res = CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials);
if (CA_STATUS_OK != res)
{
CADestroyToken(g_last_request_token);
CATerminate();
-#ifdef __WITH_DTLS__
- clearDtlsCredentialInfo();
-#endif
return 0;
}
if (CA_STATUS_OK != res)
{
printf("Could not send request to all\n");
- CADestroyEndpoint(endpoint);
}
else
{
printf("Generated token %s\n", token);
- CAInfo_t respondData = { 0 };
- respondData.token = token;
- respondData.tokenLength = tokenLength;
- respondData.payload = (CAPayload_t) "TempNotificationData";
- respondData.payloadSize = strlen((const char *) respondData.payload);
- respondData.type = messageType;
- respondData.resourceUri = (CAURI_t)uri;
+ CAInfo_t requestData = { 0 };
+ requestData.token = token;
+ requestData.tokenLength = tokenLength;
+ requestData.payload = (CAPayload_t) "TempNotificationData";
+ requestData.payloadSize = strlen((const char *) requestData.payload);
+ requestData.type = messageType;
+ requestData.resourceUri = (CAURI_t)uri;
- CAResponseInfo_t responseInfo = { 0 };
- responseInfo.result = CA_CONTENT;
- responseInfo.info = respondData;
+ CARequestInfo_t requestInfo = { 0 };
+ requestInfo.method = CA_GET;
+ requestInfo.info = requestData;
// send notification
- res = CASendNotification(endpoint, &responseInfo);
+ res = CASendRequest(endpoint, &requestInfo);
if (CA_STATUS_OK != res)
{
printf("Send notification error, error code: %d\n", res);
* @var g_getCredentialsCallback
* @brief callback to get DTLS credentials
*/
-static CAGetDTLSCredentialsHandler g_getCredentialsCallback = NULL;
+static CAGetDTLSPskCredentialsHandler g_getCredentialsCallback = NULL;
#ifdef __WITH_X509__
/**
}
VERIFY_NON_NULL_RET(g_getCredentialsCallback, NET_DTLS_TAG, "GetCredential callback", -1);
- VERIFY_NON_NULL_RET(result, NET_DTLS_TAG, "result", -1);
-
- CADtlsPskCredsBlob_t *credInfo = NULL;
// Retrieve the credentials blob from security module
- g_getCredentialsCallback(&credInfo);
-
- VERIFY_NON_NULL_RET(credInfo, NET_DTLS_TAG, "credInfo is NULL", -1);
- if(NULL == credInfo->creds)
- {
- OIC_LOG(DEBUG, NET_DTLS_TAG, "credentials are NULL");
- memset(credInfo, 0, sizeof(CADtlsPskCredsBlob_t));
- OICFree(credInfo);
- return -1;
- }
+ ret = g_getCredentialsCallback(type, desc, descLen, result, resultLen);
- if ((type == DTLS_PSK_HINT) || (type == DTLS_PSK_IDENTITY))
+ if (ret > 0)
{
- if (DTLS_PSK_ID_LEN <= resultLen)
- {
- memcpy(result, credInfo->identity, DTLS_PSK_ID_LEN);
- ret = DTLS_PSK_ID_LEN;
- }
- }
+ // TODO SRM needs identity of the remote end-point with every data packet to
+ // perform access control management. tinyDTLS 'frees' the handshake parameters
+ // data structure when handshake completes. Therefore, currently this is a
+ // workaround to cache remote end-point identity when tinyDTLS asks for PSK.
+ stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
+ char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
+ uint16_t port = 0;
+ CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
- if ((type == DTLS_PSK_KEY) && (desc) && (descLen == DTLS_PSK_PSK_LEN))
- {
- // Check if we have the credentials for the device with which we
- // are trying to perform a handshake
- for (uint32_t index = 0; index < credInfo->num; index++)
+ if(CA_STATUS_OK != CAAddIdToPeerInfoList(peerAddr, port, desc, descLen) )
{
- if (memcmp(desc, credInfo->creds[index].id, DTLS_PSK_ID_LEN) == 0)
- {
- // TODO SRM needs identity of the remote end-point with every data packet to
- // perform access control management. tinyDTLS 'frees' the handshake parameters
- // data structure when handshake completes. Therefore, currently this is a
- // workaround to cache remote end-point identity when tinyDTLS asks for PSK.
- stCADtlsAddrInfo_t *addrInfo = (stCADtlsAddrInfo_t *)session;
- char peerAddr[MAX_ADDR_STR_SIZE_CA] = { 0 };
- uint16_t port = 0;
- CAConvertAddrToName(&(addrInfo->addr.st), peerAddr, &port);
-
- if(CA_STATUS_OK != CAAddIdToPeerInfoList(peerAddr, port, desc, descLen) )
- {
- OIC_LOG(ERROR, NET_DTLS_TAG, "Fail to add peer id to gDtlsPeerInfoList");
- }
- memcpy(result, credInfo->creds[index].psk, DTLS_PSK_PSK_LEN);
- ret = DTLS_PSK_PSK_LEN;
- }
+ OIC_LOG(ERROR, NET_DTLS_TAG, "Fail to add peer id to gDtlsPeerInfoList");
}
}
- // Erase sensitive data before freeing.
- memset(credInfo->creds, 0, sizeof(OCDtlsPskCreds) * (credInfo->num));
- OICFree(credInfo->creds);
-
- memset(credInfo, 0, sizeof(CADtlsPskCredsBlob_t));
- OICFree(credInfo);
- credInfo = NULL;
-
return ret;
}
OIC_LOG(DEBUG, NET_DTLS_TAG, "OUT");
}
-void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback)
+void CADTLSSetCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback)
{
// TODO Does this method needs protection of DtlsContextMutex ?
OIC_LOG(DEBUG, NET_DTLS_TAG, "IN");
CAConnectivityHandler_t handler;
handler.startAdapter = CAStartEDR;
handler.startListenServer = CAStartEDRListeningServer;
+ handler.stopListenServer = CAStopEDRListeningServer;
handler.startDiscoveryServer = CAStartEDRDiscoveryServer;
handler.sendData = CASendEDRUnicastData;
handler.sendDataToAll = CASendEDRMulticastData;
return CAStartServer();
}
+CAResult_t CAStopEDRListeningServer()
+{
+ OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
+
+ return CAEDRServerStop();
+}
+
CAResult_t CAStartEDRDiscoveryServer()
{
OIC_LOG(DEBUG, EDR_ADAPTER_TAG, "IN");
CAConnectivityHandler_t handler = {
.startAdapter = CAStartEDR,
.startListenServer = CAStartEDRListeningServer,
+ .stopListenServer = CAStopEDRListeningServer,
.startDiscoveryServer = CAStartEDRDiscoveryServer,
.sendData = CASendEDRUnicastData,
.sendDataToAll = CASendEDRMulticastData,
return CA_STATUS_OK;
}
+CAResult_t CAStopEDRListeningServer()
+{
+ OIC_LOG(DEBUG, TAG, "CAStopEDRListeningServer");
+
+ return CA_STATUS_OK;
+}
+
CAResult_t CAStartEDRDiscoveryServer()
{
OIC_LOG(DEBUG, TAG, "CAStartEDRDiscoveryServer");
static CAResult_t CAStartLEListeningServer();
/**
+ * Stops listening server from receiving multicast search requests.
+ *
+ * Transport Specific Behavior:
+ * LE Starts GATT Server with prefixed UUID and Characteristics
+ * per OIC Specification.
+ * @return ::CA_STATUS_OK or Appropriate error code.
+ */
+static CAResult_t CAStopLEListeningServer();
+
+/**
* Sarting discovery of servers for receiving multicast
* advertisements.
*
.startAdapter = CAStartLE,
.stopAdapter = CAStopLE,
.startListenServer = CAStartLEListeningServer,
+ .stopListenServer = CAStopLEListeningServer,
.startDiscoveryServer = CAStartLEDiscoveryServer,
.sendData = CASendLEUnicastData,
.sendDataToAll = CASendLEMulticastData,
#endif
}
+static CAResult_t CAStopLEListeningServer()
+{
+ OIC_LOG(ERROR, CALEADAPTER_TAG, "Listen server stop not supported.");
+ return CA_NOT_SUPPORTED;
+}
+
static CAResult_t CAStartLEDiscoveryServer()
{
OIC_LOG(DEBUG, CALEADAPTER_TAG, "IN");
CAResult_t CAInitBlockWiseMutexVariables()
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (!g_context.blockDataListMutex)
{
g_context.blockDataListMutex = ca_mutex_new();
void CATerminateBlockWiseMutexVariables()
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (g_context.blockDataListMutex)
{
ca_mutex_free(g_context.blockDataListMutex);
}
CAResult_t CAAddBlockOption(coap_pdu_t **pdu, const CAInfo_t *info,
- const CAEndpoint_t *endpoint)
+ const CAEndpoint_t *endpoint, coap_list_t **options)
{
OIC_LOG(DEBUG, TAG, "IN-AddBlockOption");
VERIFY_NON_NULL(pdu, TAG, "pdu");
VERIFY_NON_NULL((*pdu)->hdr, TAG, "(*pdu)->hdr");
VERIFY_NON_NULL(info, TAG, "info");
VERIFY_NON_NULL(endpoint, TAG, "endpoint");
+ VERIFY_NON_NULL(options, TAG, "options");
size_t dataLength = 0;
if (info->payload)
uint8_t blockType = CAGetBlockOptionType(blockDataID);
if (COAP_OPTION_BLOCK2 == blockType)
{
- res = CAAddBlockOption2(pdu, info, dataLength, blockDataID);
+ res = CAAddBlockOption2(pdu, info, dataLength, blockDataID, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
}
else if (COAP_OPTION_BLOCK1 == blockType)
{
- res = CAAddBlockOption1(pdu, info, dataLength, blockDataID);
+ res = CAAddBlockOption1(pdu, info, dataLength, blockDataID, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
else
{
OIC_LOG(DEBUG, TAG, "no BLOCK option");
+
+ // in case it is not large data, add option list to pdu.
+ if (*options)
+ {
+ for (coap_list_t *opt = *options; opt; opt = opt->next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+ COAP_OPTION_DATA(*(coap_option *) opt->data));
+
+ OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", (*pdu)->length);
+ coap_add_option(*pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+ COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+ COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+ }
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", (*pdu)->length);
+
// if response data is so large. it have to send as block transfer
if (!coap_add_data(*pdu, dataLength, (const unsigned char *) info->payload))
{
}
exit:
- if (0 == endpoint->port)
+ if (CA_ADAPTER_IP == endpoint->adapter && 0 == endpoint->port)
{
CARemoveBlockDataFromList(blockDataID);
}
}
CAResult_t CAAddBlockOption2(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
- const CABlockDataID_t *blockID)
+ const CABlockDataID_t *blockID, coap_list_t **options)
{
OIC_LOG(DEBUG, TAG, "IN-AddBlockOption2");
VERIFY_NON_NULL(pdu, TAG, "pdu");
VERIFY_NON_NULL((*pdu)->hdr, TAG, "(*pdu)->hdr");
VERIFY_NON_NULL(info, TAG, "info");
VERIFY_NON_NULL(blockID, TAG, "blockID");
+ VERIFY_NON_NULL(options, TAG, "options");
// get set block data from CABlock list-set.
coap_block_t *block1 = CAGetBlockOption(blockID,
}
CALogBlockInfo(block2);
- if (block1->num)
+ // if block number is 0, add size2 option
+ if (0 == block2->num)
{
- OIC_LOG(DEBUG, TAG, "combining block1 and block2");
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1);
+ res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
CARemoveBlockDataFromList(blockID);
return res;
}
- // initialize block number
- block1->num = 0;
}
- // if block number is 0, add size2 option
- if (0 == block2->num)
+ if (block1->num)
{
- res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE2, dataLength);
+ OIC_LOG(DEBUG, TAG, "combining block1 and block2");
+ CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
CARemoveBlockDataFromList(blockID);
return res;
}
+ // initialize block number
+ block1->num = 0;
}
if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
else
{
OIC_LOG(DEBUG, TAG, "option2, not ACK msg");
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block2, COAP_OPTION_BLOCK2);
+ CAResult_t res = CAAddBlockOptionImpl(*pdu, block2, COAP_OPTION_BLOCK2, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
}
CAResult_t CAAddBlockOption1(coap_pdu_t **pdu, const CAInfo_t *info, size_t dataLength,
- const CABlockDataID_t *blockID)
+ const CABlockDataID_t *blockID, coap_list_t **options)
{
OIC_LOG(DEBUG, TAG, "IN-AddBlockOption1");
VERIFY_NON_NULL(pdu, TAG, "pdu");
VERIFY_NON_NULL((*pdu)->hdr, TAG, "(*pdu)->hdr");
VERIFY_NON_NULL(info, TAG, "info");
VERIFY_NON_NULL(blockID, TAG, "blockID");
+ VERIFY_NON_NULL(options, TAG, "options");
// get set block data from CABlock list-set.
coap_block_t *block1 = CAGetBlockOption(blockID, COAP_OPTION_BLOCK1);
if (CA_MSG_ACKNOWLEDGE == (*pdu)->hdr->coap_hdr_udp_t.type)
{
OIC_LOG(DEBUG, TAG, "option1 and ACK msg..");
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1);
+ CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
else
{
CAGetMoreBitFromBlock(dataLength, block1);
- CAResult_t res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1);
- if (CA_STATUS_OK != res)
- {
- OIC_LOG(ERROR, TAG, "add has failed");
- CARemoveBlockDataFromList(blockID);
- return res;
- }
- CALogBlockInfo(block1);
+ CAResult_t res = CA_STATUS_OK;
// if block number is 0, add size1 option
if (0 == block1->num)
{
- res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE1, dataLength);
+ res = CAAddBlockSizeOption(*pdu, COAP_OPTION_SIZE1, dataLength, options);
if (CA_STATUS_OK != res)
{
OIC_LOG(ERROR, TAG, "add has failed");
}
}
+ res = CAAddBlockOptionImpl(*pdu, block1, COAP_OPTION_BLOCK1, options);
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG(ERROR, TAG, "add has failed");
+ CARemoveBlockDataFromList(blockID);
+ return res;
+ }
+ CALogBlockInfo(block1);
+
if (!coap_add_block(*pdu, dataLength, (const unsigned char *) info->payload,
block1->num, block1->szx))
{
return CA_STATUS_OK;
}
-CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType)
+CAResult_t CAAddBlockOptionImpl(coap_pdu_t *pdu, coap_block_t *block, uint8_t blockType,
+ coap_list_t **options)
{
OIC_LOG(DEBUG, TAG, "IN-AddBlockOptionImpl");
VERIFY_NON_NULL(pdu, TAG, "pdu");
VERIFY_NON_NULL(block, TAG, "block");
+ VERIFY_NON_NULL(options, TAG, "options");
+
+ unsigned char buf[BLOCKWISE_OPTION_BUFFER] = { 0 };
+ unsigned int optionLength = coap_encode_var_bytes(buf,
+ ((block->num << BLOCK_NUMBER_IDX)
+ | (block->m << BLOCK_M_BIT_IDX)
+ | block->szx));
- coap_option *option = (coap_option *) OICMalloc(sizeof(coap_option));
- if (!option)
+ int ret = coap_insert(options,
+ CACreateNewOptionNode(blockType, optionLength, (char *) buf),
+ CAOrderOpts);
+ if (ret <= 0)
{
- OIC_LOG(ERROR, TAG, "out of memory");
- return CA_MEMORY_ALLOC_FAILED;
+ return CA_STATUS_INVALID_PARAM;
}
- unsigned char buf[BLOCKWISE_OPTION_BUFFER] = { 0 };
- option->key = blockType;
- option->length = coap_encode_var_bytes(buf,
- ((block->num << BLOCK_NUMBER_IDX)
- | (block->m << BLOCK_M_BIT_IDX) | block->szx));
- if (!coap_add_option(pdu, option->key, option->length, buf, coap_udp))
- {
- OIC_LOG(ERROR, TAG, "coap_add_option has failed");
- OICFree(option);
- return CA_STATUS_FAILED;
+ // after adding the block option to option list, add option list to pdu.
+ if (*options)
+ {
+ for (coap_list_t *opt = *options; opt; opt = opt->next)
+ {
+ OIC_LOG_V(DEBUG, TAG, "[%s] opt will be added.",
+ COAP_OPTION_DATA(*(coap_option *) opt->data));
+
+ OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
+ coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
+ COAP_OPTION_LENGTH(*(coap_option *) opt->data),
+ COAP_OPTION_DATA(*(coap_option *) opt->data), coap_udp);
+ }
}
- OICFree(option);
+ OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
OIC_LOG(DEBUG, TAG, "OUT-AddBlockOptionImpl");
return CA_STATUS_OK;
}
-CAResult_t CAAddBlockSizeOption(coap_pdu_t *pdu, uint16_t sizeType, size_t dataLength)
+CAResult_t CAAddBlockSizeOption(coap_pdu_t *pdu, uint16_t sizeType, size_t dataLength,
+ coap_list_t **options)
{
OIC_LOG(DEBUG, TAG, "IN-CAAddBlockSizeOption");
VERIFY_NON_NULL(pdu, TAG, "pdu");
+ VERIFY_NON_NULL(options, TAG, "options");
if (sizeType != COAP_OPTION_SIZE1 && sizeType != COAP_OPTION_SIZE2)
{
unsigned char value[BLOCKWISE_OPTION_BUFFER] = { 0 };
unsigned int optionLength = coap_encode_var_bytes(value, dataLength);
- if (!coap_add_option(pdu, sizeType, optionLength, value, coap_udp))
+ int ret = coap_insert(options,
+ CACreateNewOptionNode(sizeType, optionLength, (char *) value),
+ CAOrderOpts);
+ if (ret <= 0)
{
- OIC_LOG(ERROR, TAG, "failed to add size option");
- return CA_STATUS_FAILED;
+ return CA_STATUS_INVALID_PARAM;
}
OIC_LOG(DEBUG, TAG, "OUT-CAAddBlockSizeOption");
#ifdef __WITH_DTLS__
// CAAdapterNetDTLS will register the callback.
// Taking callback all the way through adapters not the right approach, hence calling here.
-extern void CADTLSSetCredentialsCallback(CAGetDTLSCredentialsHandler credCallback);
+extern void CADTLSSetCredentialsCallback(CAGetDTLSPskCredentialsHandler credCallback);
#endif
#ifdef __WITH_X509__
return CAStartListeningServerAdapters();
}
+CAResult_t CAStopListeningServer()
+{
+ OIC_LOG(DEBUG, TAG, "CAStopListeningServer");
+
+ if(!g_isInitialized)
+ {
+ return CA_STATUS_NOT_INITIALIZED;
+ }
+
+ return CAStopListeningServerAdapters();
+}
+
CAResult_t CAStartDiscoveryServer()
{
OIC_LOG(DEBUG, TAG, "CAStartDiscoveryServer");
}
#ifdef __WITH_DTLS__
-CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSCredentialsHandler GetDTLSCredentialsHandler)
+CAResult_t CARegisterDTLSCredentialsHandler(CAGetDTLSPskCredentialsHandler GetDTLSCredentialsHandler)
{
OIC_LOG(DEBUG, TAG, "CARegisterDTLSCredentialsHandler");
return CADetachRequestMessage(object, requestInfo);
}
-CAResult_t CASendNotification(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
-{
- OIC_LOG(DEBUG, TAG, "CASendNotification");
-
- if(!g_isInitialized)
- {
- return CA_STATUS_NOT_INITIALIZED;
- }
-
- return CADetachResponseMessage(object, responseInfo);
-}
-
CAResult_t CASendResponse(const CAEndpoint_t *object, const CAResponseInfo_t *responseInfo)
{
OIC_LOG(DEBUG, TAG, "CASendResponse");
if(handler.startAdapter == NULL ||
handler.startListenServer == NULL ||
+ handler.stopListenServer == NULL ||
handler.startDiscoveryServer == NULL ||
handler.sendData == NULL ||
handler.sendDataToAll == NULL ||
return CA_STATUS_OK;
}
+CAResult_t CAStopListeningServerAdapters()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ u_arraylist_t *list = CAGetSelectedNetworkList();
+ if (!list)
+ {
+ OIC_LOG(ERROR, TAG, "No selected network");
+ return CA_STATUS_FAILED;
+ }
+
+ for (uint32_t i = 0; i < u_arraylist_length(list); i++)
+ {
+ void* ptrType = u_arraylist_get(list, i);
+ if(ptrType == NULL)
+ {
+ continue;
+ }
+
+ CATransportAdapter_t connType = *(CATransportAdapter_t *)ptrType;
+
+ int index = CAGetAdapterIndex(connType);
+ if (index == -1)
+ {
+ OIC_LOG(ERROR, TAG, "unknown connectivity type!");
+ continue;
+ }
+
+ if (g_adapterHandler[index].stopListenServer != NULL)
+ {
+ g_adapterHandler[index].stopListenServer();
+ }
+ }
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
CAResult_t CAStartDiscoveryServerAdapters()
{
OIC_LOG(DEBUG, TAG, "IN");
#ifdef WITH_BWT
void CAAddDataToSendThread(CAData_t *data)
{
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(data, TAG, "data");
// add thread
CAQueueingThreadAddData(&g_sendThread, data, sizeof(CAData_t));
-
- OIC_LOG(DEBUG, TAG, "OUT");
}
void CAAddDataToReceiveThread(CAData_t *data)
{
- OIC_LOG(DEBUG, TAG, "IN - CAAddDataToReceiveThread");
VERIFY_NON_NULL_VOID(data, TAG, "data");
// add thread
CAQueueingThreadAddData(&g_receiveThread, data, sizeof(CAData_t));
-
- OIC_LOG(DEBUG, TAG, "OUT - CAAddDataToReceiveThread");
}
#endif
static void CATimeoutCallback(const CAEndpoint_t *endpoint, const void *pdu, uint32_t size)
{
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(endpoint, TAG, "endpoint");
VERIFY_NON_NULL_VOID(pdu, TAG, "pdu");
#else
CAQueueingThreadAddData(&g_receiveThread, cadata, sizeof(CAData_t));
#endif
-
- OIC_LOG(DEBUG, TAG, "OUT");
}
static void CADestroyData(void *data, uint32_t size)
static void CAReceiveThreadProcess(void *threadData)
{
- OIC_LOG(DEBUG, TAG, "IN");
#ifndef SINGLE_HANDLE
CAData_t *data = (CAData_t *) threadData;
CAProcessReceivedData(data);
#else
(void)threadData;
#endif
- OIC_LOG(DEBUG, TAG, "OUT");
}
#endif
static CAResult_t CAProcessSendData(const CAData_t *data)
{
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(data, TAG, "data");
VERIFY_NON_NULL(data->remoteEndpoint, TAG, "remoteEndpoint");
coap_pdu_t *pdu = NULL;
CAInfo_t *info = NULL;
+ coap_list_t *options = NULL;
+ coap_transport_type transport;
if (SEND_TYPE_UNICAST == type)
{
#ifdef ROUTING_GATEWAY
skipRetransmission = data->requestInfo->info.skipRetransmission;
#endif
- pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint);
+ pdu = CAGeneratePDU(data->requestInfo->method, info, data->remoteEndpoint,
+ &options, &transport);
}
else if (NULL != data->responseInfo)
{
#ifdef ROUTING_GATEWAY
skipRetransmission = data->responseInfo->info.skipRetransmission;
#endif
- pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint);
+ pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
+ &options, &transport);
}
else
{
if (NULL != info)
{
CAResult_t res = CAAddBlockOption(&pdu, info,
- data->remoteEndpoint);
+ data->remoteEndpoint,
+ &options);
if (CA_STATUS_OK != res)
{
OIC_LOG(INFO, TAG, "to write block option has failed");
CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+ coap_delete_list(options);
coap_delete_pdu(pdu);
return res;
}
{
OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+ coap_delete_list(options);
coap_delete_pdu(pdu);
return res;
}
{
//when retransmission not supported this will return CA_NOT_SUPPORTED, ignore
OIC_LOG_V(INFO, TAG, "retransmission is not enabled due to error, res : %d", res);
+ coap_delete_list(options);
coap_delete_pdu(pdu);
return res;
}
}
+ coap_delete_list(options);
coap_delete_pdu(pdu);
}
else
OIC_LOG(DEBUG, TAG, "requestInfo is available..");
info = &data->requestInfo->info;
- pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint);
+ pdu = CAGeneratePDU(CA_GET, info, data->remoteEndpoint, &options, &transport);
+
if (NULL != pdu)
{
#ifdef WITH_BWT
{
// Blockwise transfer
CAResult_t res = CAAddBlockOption(&pdu, &data->requestInfo->info,
- data->remoteEndpoint);
+ data->remoteEndpoint,
+ &options);
if (CA_STATUS_OK != res)
{
OIC_LOG(DEBUG, TAG, "CAAddBlockOption has failed");
CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+ coap_delete_list(options);
coap_delete_pdu(pdu);
return res;
}
OIC_LOG(DEBUG, TAG, "responseInfo is available..");
info = &data->responseInfo->info;
- pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint);
+ pdu = CAGeneratePDU(data->responseInfo->result, info, data->remoteEndpoint,
+ &options, &transport);
if (NULL != pdu)
{
if (NULL != info)
{
CAResult_t res = CAAddBlockOption(&pdu, info,
- data->remoteEndpoint);
+ data->remoteEndpoint,
+ &options);
if (CA_STATUS_OK != res)
{
OIC_LOG(INFO, TAG, "to write block option has failed");
CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+ coap_delete_list(options);
coap_delete_pdu(pdu);
return res;
}
{
OIC_LOG_V(ERROR, TAG, "send failed:%d", res);
CAErrorHandler(data->remoteEndpoint, pdu->hdr, pdu->length, res);
+ coap_delete_list(options);
coap_delete_pdu(pdu);
return res;
}
+ coap_delete_list(options);
coap_delete_pdu(pdu);
}
static void CAReceivedPacketCallback(const CASecureEndpoint_t *sep,
const void *data, uint32_t dataLen)
{
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_VOID(sep, TAG, "remoteEndpoint");
VERIFY_NON_NULL_VOID(data, TAG, "data");
#endif
coap_delete_pdu(pdu);
-
- OIC_LOG(DEBUG, TAG, "OUT");
}
static void CANetworkChangedCallback(const CAEndpoint_t *info, CANetworkStatus_t status)
CAResult_t CADetachRequestMessage(const CAEndpoint_t *object, const CARequestInfo_t *request)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
VERIFY_NON_NULL(object, TAG, "object");
VERIFY_NON_NULL(request, TAG, "request");
}
#endif
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CADetachResponseMessage(const CAEndpoint_t *object,
const CAResponseInfo_t *response)
{
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL(object, TAG, "object");
VERIFY_NON_NULL(response, TAG, "response");
}
#endif
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CASetInterfaceCallbacks(CARequestCallback ReqHandler, CAResponseCallback RespHandler,
CAErrorCallback errorHandler)
{
- OIC_LOG(DEBUG, TAG, "IN");
g_requestHandler = ReqHandler;
g_responseHandler = RespHandler;
g_errorHandler = errorHandler;
- OIC_LOG(DEBUG, TAG, "OUT");
}
CAResult_t CAInitializeMessageHandler()
{
- OIC_LOG(DEBUG, TAG, "IN");
CASetPacketReceivedCallback(CAReceivedPacketCallback);
CASetNetworkChangeCallback(CANetworkChangedCallback);
CAInitializeAdapters();
#endif
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CATerminateMessageHandler()
{
- OIC_LOG(DEBUG, TAG, "IN");
#ifndef SINGLE_THREAD
CATransportAdapter_t connType;
u_arraylist_t *list = CAGetSelectedNetworkList();
CARetransmissionStop(&g_retransmissionContext);
CARetransmissionDestroy(&g_retransmissionContext);
#endif
-
- OIC_LOG(DEBUG, TAG, "OUT");
}
void CALogPDUInfo(coap_pdu_t *pdu, const CAEndpoint_t *endpoint)
if (CA_STATUS_OK != res)
{
OICFree(cadata);
+ OICFree(errorInfo);
CAFreeEndpoint(ep);
return;
}
CAResult_t CAGetRequestInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
CARequestInfo_t *outReqInfo)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (NULL == pdu || NULL == outReqInfo)
{
OIC_LOG(ERROR, TAG, "parameter is null");
CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outReqInfo->info));
outReqInfo->method = code;
- OIC_LOG(DEBUG, TAG, "OUT");
return ret;
}
CAResult_t CAGetResponseInfoFromPDU(const coap_pdu_t *pdu, CAResponseInfo_t *outResInfo,
const CAEndpoint_t *endpoint)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (NULL == pdu || NULL == outResInfo)
{
OIC_LOG(ERROR, TAG, "parameter is null");
CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &(outResInfo->info));
outResInfo->result = code;
- OIC_LOG(DEBUG, TAG, "OUT");
return ret;
}
CAResult_t CAGetErrorInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
CAErrorInfo_t *errorInfo)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (!pdu)
{
OIC_LOG(ERROR, TAG, "parameter is null");
uint32_t code = 0;
CAResult_t ret = CAGetInfoFromPDU(pdu, endpoint, &code, &errorInfo->info);
- OIC_LOG(DEBUG, TAG, "OUT");
+
return ret;
}
-coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint)
+coap_pdu_t *CAGeneratePDU(uint32_t code, const CAInfo_t *info, const CAEndpoint_t *endpoint,
+ coap_list_t **optlist, coap_transport_type *transport)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
+ VERIFY_NON_NULL_RET(optlist, TAG, "optlist", NULL);
coap_pdu_t *pdu = NULL;
if (CA_MSG_RESET == info->type || (CA_EMPTY == code && CA_MSG_ACKNOWLEDGE == info->type))
{
OIC_LOG(DEBUG, TAG, "code is empty");
- if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL)))
+ if (!(pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, NULL, transport)))
{
OIC_LOG(ERROR, TAG, "pdu NULL");
return NULL;
}
else
{
- coap_list_t *optlist = NULL;
-
if (CA_MSG_ACKNOWLEDGE != info->type && info->resourceUri)
{
uint32_t length = strlen(info->resourceUri);
OICStrcat(coapUri, uriLength, info->resourceUri);
// parsing options in URI
- CAResult_t res = CAParseURI(coapUri, &optlist);
+ CAResult_t res = CAParseURI(coapUri, optlist);
if (CA_STATUS_OK != res)
{
- if (optlist)
- {
- coap_delete_list(optlist);
- }
OICFree(coapUri);
return NULL;
}
OICFree(coapUri);
}
// parsing options in HeadOption
- CAResult_t ret = CAParseHeadOption(code, info, &optlist);
+ CAResult_t ret = CAParseHeadOption(code, info, optlist);
if (CA_STATUS_OK != ret)
{
- coap_delete_list(optlist);
return NULL;
}
- pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, optlist);
+ pdu = CAGeneratePDUImpl((code_t) code, info, endpoint, *optlist, transport);
if (NULL == pdu)
{
OIC_LOG(ERROR, TAG, "pdu NULL");
- coap_delete_list(optlist);
return NULL;
}
-
- // free option list
- coap_delete_list(optlist);
}
// pdu print method : coap_show_pdu(pdu);
- OIC_LOG(DEBUG, TAG, "OUT");
return pdu;
}
coap_pdu_t *CAParsePDU(const char *data, uint32_t length, uint32_t *outCode,
const CAEndpoint_t *endpoint)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (NULL == data)
{
OIC_LOG(ERROR, TAG, "data is null");
(*outCode) = (uint32_t) CA_RESPONSE_CODE(coap_get_code(outpdu, transport));
}
- OIC_LOG(DEBUG, TAG, "OUT");
return outpdu;
}
coap_pdu_t *CAGeneratePDUImpl(code_t code, const CAInfo_t *info,
- const CAEndpoint_t *endpoint, coap_list_t *options)
+ const CAEndpoint_t *endpoint, coap_list_t *options,
+ coap_transport_type *transport)
{
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_RET(info, TAG, "info", NULL);
VERIFY_NON_NULL_RET(endpoint, TAG, "endpoint", NULL);
+ VERIFY_NON_NULL_RET(transport, TAG, "transport", NULL);
- coap_transport_type transport;
unsigned int length = COAP_MAX_PDU_SIZE;
#ifdef TCP_ADAPTER
unsigned int msgLength = 0;
{
msgLength = msgLength + info->payloadSize + PAYLOAD_MARKER;
}
- transport = coap_get_tcp_header_type_from_size(msgLength);
- length = msgLength + coap_get_tcp_header_length_for_transport(transport)
+ *transport = coap_get_tcp_header_type_from_size(msgLength);
+ length = msgLength + coap_get_tcp_header_length_for_transport(*transport)
+ info->tokenLength;
}
else
#endif
{
- transport = coap_udp;
+ *transport = coap_udp;
}
- coap_pdu_t *pdu = coap_new_pdu(transport, length);
+ coap_pdu_t *pdu = coap_new_pdu(*transport, length);
if (NULL == pdu)
{
}
OIC_LOG_V(DEBUG, TAG, "transport type: %d, payload size: %d",
- transport, info->payloadSize);
+ *transport, info->payloadSize);
#ifdef TCP_ADAPTER
if (CA_ADAPTER_TCP == endpoint->adapter)
{
- coap_add_length(pdu, transport, msgLength);
+ coap_add_length(pdu, *transport, msgLength);
}
else
#endif
pdu->hdr->coap_hdr_udp_t.type = info->type;
}
- coap_add_code(pdu, transport, code);
+ coap_add_code(pdu, *transport, code);
if (info->token && CA_EMPTY != code)
{
OIC_LOG_V(DEBUG, TAG, "token info token length: %d, token :", tokenLength);
OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)info->token, tokenLength);
- int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token, transport);
+ int32_t ret = coap_add_token(pdu, tokenLength, (unsigned char *)info->token, *transport);
if (0 == ret)
{
OIC_LOG(ERROR, TAG, "can't add token");
}
}
+#ifdef WITH_BWT
+ if (CA_ADAPTER_GATT_BTLE != endpoint->adapter
+#ifdef TCP_ADAPTER
+ && CA_ADAPTER_TCP != endpoint->adapter
+#endif
+ )
+ {
+ // option list will be added in blockwise-transfer
+ return pdu;
+ }
+#endif
+
if (options)
{
for (coap_list_t *opt = options; opt; opt = opt->next)
OIC_LOG_V(DEBUG, TAG, "[%d] pdu length", pdu->length);
coap_add_option(pdu, COAP_OPTION_KEY(*(coap_option *) opt->data),
COAP_OPTION_LENGTH(*(coap_option *) opt->data),
- COAP_OPTION_DATA(*(coap_option *) opt->data), transport);
+ COAP_OPTION_DATA(*(coap_option *) opt->data), *transport);
}
}
OIC_LOG_V(DEBUG, TAG, "[%d] pdu length after option", pdu->length);
- bool enabledPayload = false;
-#ifndef WITH_BWT
- enabledPayload = true;
-#endif
-
- if (enabledPayload || CA_ADAPTER_GATT_BTLE == endpoint->adapter
-#ifdef TCP_ADAPTER
- || CA_ADAPTER_TCP == endpoint->adapter
-#endif
- )
+ if (NULL != info->payload && 0 < info->payloadSize)
{
- if (NULL != info->payload && 0 < info->payloadSize)
- {
- OIC_LOG(DEBUG, TAG, "payload is added");
- coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
- }
+ OIC_LOG(DEBUG, TAG, "payload is added");
+ coap_add_data(pdu, info->payloadSize, (const unsigned char *) info->payload);
}
- OIC_LOG(DEBUG, TAG, "OUT");
return pdu;
}
CAResult_t CAParseURI(const char *uriInfo, coap_list_t **optlist)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (NULL == uriInfo)
{
OIC_LOG(ERROR, TAG, "uriInfo is null");
}
}
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
CAResult_t CAParseHeadOption(uint32_t code, const CAInfo_t *info, coap_list_t **optlist)
{
(void)code;
- OIC_LOG(DEBUG, TAG, "IN");
VERIFY_NON_NULL_RET(info, TAG, "info is NULL", CA_STATUS_INVALID_PARAM);
OIC_LOG_V(DEBUG, TAG, "parse Head Opt: %d", info->numOptions);
}
}
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
coap_list_t *CACreateNewOptionNode(uint16_t key, uint32_t length, const char *data)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (!data)
{
OIC_LOG(ERROR, TAG, "invalid pointer parameter");
return NULL;
}
- OIC_LOG(DEBUG, TAG, "OUT");
return node;
}
int CAOrderOpts(void *a, void *b)
{
- OIC_LOG(DEBUG, TAG, "IN");
if (!a || !b)
{
return a < b ? -1 : 1;
return -1;
}
- OIC_LOG(DEBUG, TAG, "OUT");
return COAP_OPTION_KEY(*(coap_option *) a) == COAP_OPTION_KEY(*(coap_option * ) b);
}
uint32_t CAGetOptionCount(coap_opt_iterator_t opt_iter)
{
- OIC_LOG(DEBUG, TAG, "IN");
uint32_t count = 0;
coap_opt_t *option;
}
}
- OIC_LOG(DEBUG, TAG, "OUT");
return count;
}
CAResult_t CAGetInfoFromPDU(const coap_pdu_t *pdu, const CAEndpoint_t *endpoint,
uint32_t *outCode, CAInfo_t *outInfo)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (!pdu || !outCode || !outInfo)
{
OIC_LOG(ERROR, TAG, "NULL pointer param");
}
}
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
exit:
CAResult_t CAGetTokenFromPDU(const coap_hdr_t *pdu_hdr, CAInfo_t *outInfo,
const CAEndpoint_t *endpoint)
{
- OIC_LOG(DEBUG, TAG, "IN");
if (NULL == pdu_hdr)
{
OIC_LOG(ERROR, TAG, "pdu_hdr is null");
outInfo->tokenLength = token_length;
- OIC_LOG(DEBUG, TAG, "OUT");
-
return CA_STATUS_OK;
}
CAResult_t CAGenerateTokenInternal(CAToken_t *token, uint8_t tokenLength)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (!token)
{
OIC_LOG(ERROR, TAG, "invalid token pointer");
OIC_LOG_V(DEBUG, TAG, "token len:%d, token:", tokenLength);
OIC_LOG_BUFFER(DEBUG, TAG, (const uint8_t *)(*token), tokenLength);
- OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
void CADestroyTokenInternal(CAToken_t token)
{
- OIC_LOG(DEBUG, TAG, "IN");
OICFree(token);
- OIC_LOG(DEBUG, TAG, "OUT");
}
void CADestroyInfo(CAInfo_t *info)
{
- OIC_LOG(DEBUG, TAG, "IN");
-
if (NULL != info)
{
OIC_LOG(DEBUG, TAG, "free options");
OIC_LOG(DEBUG, TAG, "free payload");
OICFree(info->payload);
}
-
- OIC_LOG(DEBUG, TAG, "OUT");
}
uint32_t CAGetOptionData(uint16_t key, const uint8_t *data, uint32_t len,
// Length of the IP address decimal notation string
#define IPNAMESIZE (16)
+/** Multicast IP address.*/
+#define IPv4_MULTICAST "224.0.1.187"
+
+/** Multicast Port.*/
+#define IPv4_MULTICAST_PORT 5683
+
CAResult_t CAIPStartUnicastServer(const char *localAddress, uint16_t *port,
const bool forceStart, int32_t *serverFD);
static CAResult_t CAArduinoRecvData(int32_t sockFd);
OIC_LOG_V(ERROR, TAG, "Start unicast server failed[%d]", ret);
return ret;
}
- ret = CAIPStartMulticastServer("0.0.0.0", "224.0.1.187", 5683);
+ ret = CAIPStartMulticastServer("0.0.0.0", IPv4_MULTICAST, IPv4_MULTICAST_PORT);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TAG, "Start multicast failed[%d]", ret);
return CA_STATUS_OK;
}
+CAResult_t CAIPStartListenServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ CAResult_t ret = CAIPStartMulticastServer("0.0.0.0", IPv4_MULTICAST, IPv4_MULTICAST_PORT);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "Start multicast failed[%d]", ret);
+ }
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopListenServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ CAResult_t ret = CAIPStopMulticastServer();
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "Stop multicast failed[%d]", ret);
+ }
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
void CAIPStopServer()
{
OIC_LOG(DEBUG, TAG, "IN");
for (uint32_t i = 0, j = 0; i < len; i++)
{
CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
-
+ if(!ifitem)
+ {
+ continue;
+ }
unsigned char *addr= (unsigned char *) &(ifitem->ipv4addr);
snprintf(eps[j].addr, MAX_ADDR_STR_SIZE_CA, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
// Length of the IP address decimal notation string
#define IPNAMESIZE (16)
+/** Multicast IP address.*/
+#define IPv4_MULTICAST "224.0.1.187"
+
+/** Multicast Port.*/
+#define IPv4_MULTICAST_PORT 5683
+
// Start offsets based on end of received data buffer
#define IP_RECBUF_IPADDR_OFFSET (6)
#define IP_RECBUF_PORT_OFFSET (2)
OIC_LOG_V(ERROR, TAG, "Start unicast server failed[%d]", ret);
return ret;
}
- ret = CAIPStartMulticastServer("0.0.0.0", "224.0.1.187", 5683);
+ ret = CAIPStartMulticastServer("0.0.0.0", IPv4_MULTICAST, IPv4_MULTICAST_PORT);
if (CA_STATUS_OK != ret)
{
OIC_LOG_V(ERROR, TAG, "Start multicast failed[%d]", ret);
return CAIPStopUnicastServer();
}
+CAResult_t CAIPStartListenServer()
+{
+ CAResult_t ret = CAIPStartMulticastServer("0.0.0.0", IPv4_MULTICAST, IPv4_MULTICAST_PORT);
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "Start multicast failed[%d]", ret);
+ }
+ return ret;
+}
+
+CAResult_t CAIPStopListenServer()
+{
+ return CAIPStopMulticastServer();
+}
+
void CAIPStopServer()
{
OIC_LOG(DEBUG, TAG, "IN");
for (uint32_t i = 0, j = 0; i < len; i++)
{
CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
-
+ if(!ifitem)
+ {
+ continue;
+ }
unsigned char *addr= (unsigned char *) &(ifitem->ipv4addr);
snprintf(eps[j].addr, MAX_ADDR_STR_SIZE_CA, "%d.%d.%d.%d", addr[0], addr[1], addr[2], addr[3]);
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-
CAConnectivityHandler_t ipHandler;
ipHandler.startAdapter = CAStartIP;
ipHandler.startListenServer = CAStartIPListeningServer;
+ ipHandler.stopListenServer = CAStopIPListeningServer;
ipHandler.startDiscoveryServer = CAStartIPDiscoveryServer;
ipHandler.sendData = CASendIPUnicastData;
ipHandler.sendDataToAll = CASendIPMulticastData;
CAResult_t CAStartIPListeningServer()
{
OIC_LOG(DEBUG, TAG, "IN");
+ CAResult_t ret = CAIPStartListenServer();
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", ret);
+ return ret;
+ }
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+CAResult_t CAStopIPListeningServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+ CAResult_t ret = CAIPStopListenServer();
+ if (CA_STATUS_OK != ret)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to stop listening server![%d]", ret);
+ return ret;
+ }
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
*
******************************************************************/
-#include "caipinterface.h"
+#define __APPLE_USE_RFC_3542 // for PKTINFO
+#define _GNU_SOURCE // for in6_pktinfo
#include <sys/types.h>
#include <sys/socket.h>
#endif
#include "pdu.h"
+#include "caipinterface.h"
#include "caadapterutils.h"
#ifdef __WITH_DTLS__
#include "caadapternetdtls.h"
static CAIPPacketReceivedCallback g_packetReceivedCallback;
static void CAHandleNetlink();
-static void CAApplyInterfaces();
static void CAFindReadyMessage();
static void CASelectReturned(fd_set *readFds, int ret);
static void CAProcessNewInterface(CAInterface_t *ifchanged);
{
char recvBuffer[COAP_MAX_PDU_SIZE];
+ size_t len;
+ int level, type;
struct sockaddr_storage srcAddr;
- socklen_t srcAddrLen = sizeof (srcAddr);
-
- ssize_t recvLen = recvfrom(fd,
- recvBuffer,
- sizeof (recvBuffer),
- 0,
- (struct sockaddr *)&srcAddr,
- &srcAddrLen);
+ unsigned char *pktinfo = NULL;
+ struct msghdr msg = { 0 };
+ struct cmsghdr *cmp;
+ struct iovec iov = { recvBuffer, sizeof (recvBuffer) };
+ union control
+ {
+ struct cmsghdr cmsg;
+ unsigned char data[CMSG_SPACE(sizeof (struct in6_pktinfo))];
+ } cmsg;
+
+ if (flags & CA_IPV6)
+ {
+ msg.msg_namelen = sizeof (struct sockaddr_in6);
+ level = IPPROTO_IPV6;
+ type = IPV6_PKTINFO;
+ len = sizeof (struct in6_pktinfo);
+ }
+ else
+ {
+ msg.msg_namelen = sizeof (struct sockaddr_in);
+ level = IPPROTO_IP;
+ type = IP_PKTINFO;
+ len = sizeof (struct in6_pktinfo);
+ }
+
+ msg.msg_name = &srcAddr;
+ msg.msg_iov = &iov;
+ msg.msg_iovlen = 1;
+ msg.msg_control = &cmsg;
+ msg.msg_controllen = CMSG_SPACE(len);
+
+ ssize_t recvLen = recvmsg(fd, &msg, flags);
if (-1 == recvLen)
{
OIC_LOG_V(ERROR, TAG, "Recvfrom failed %s", strerror(errno));
return CA_STATUS_FAILED;
}
- CASecureEndpoint_t sep =
- {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
+ if (flags & CA_MULTICAST)
+ {
+ for (cmp = CMSG_FIRSTHDR(&msg); cmp != NULL; cmp = CMSG_NXTHDR(&msg, cmp))
+ {
+ if (cmp->cmsg_level == level && cmp->cmsg_type == type)
+ {
+ pktinfo = CMSG_DATA(cmp);
+ }
+ }
+ }
+
+ CASecureEndpoint_t sep = {.endpoint = {.adapter = CA_ADAPTER_IP, .flags = flags}};
if (flags & CA_IPV6)
{
sep.endpoint.interface = ((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id;
((struct sockaddr_in6 *)&srcAddr)->sin6_scope_id = 0;
+
+ if ((flags & CA_MULTICAST) && pktinfo)
+ {
+ struct in6_addr *addr = &(((struct in6_pktinfo *)pktinfo)->ipi6_addr);
+ unsigned char topbits = ((unsigned char *)addr)[0];
+ if (topbits != 0xff)
+ {
+ sep.endpoint.flags &= ~CA_MULTICAST;
+ }
+ }
}
+ else
+ {
+ if ((flags & CA_MULTICAST) && pktinfo)
+ {
+ struct in_addr *addr = &((struct in_pktinfo *)pktinfo)->ipi_addr;
+ uint32_t host = ntohl(addr->s_addr);
+ unsigned char topbits = ((unsigned char *)&host)[3];
+ if (topbits < 224 || topbits > 239)
+ {
+ sep.endpoint.flags &= ~CA_MULTICAST;
+ }
+ }
+ }
+
CAConvertAddrToName(&srcAddr, sep.endpoint.addr, &sep.endpoint.port);
if (flags & CA_SECURE)
if (family == AF_INET6)
{
int on = 1;
+
if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof (on)))
{
OIC_LOG_V(ERROR, TAG, "IPV6_V6ONLY failed: %s", strerror(errno));
}
+
+ if (*port) // only do this for multicast ports
+ {
+ if (-1 == setsockopt(fd, IPPROTO_IPV6, IPV6_RECVPKTINFO, &on, sizeof (on)))
+ {
+ OIC_LOG_V(ERROR, TAG, "IPV6_RECVPKTINFO failed: %s", strerror(errno));
+ }
+ }
+
((struct sockaddr_in6 *)&sa)->sin6_port = htons(*port);
socklen = sizeof (struct sockaddr_in6);
}
else
{
+ if (*port) // only do this for multicast ports
+ {
+ int on = 1;
+ if (-1 == setsockopt(fd, IPPROTO_IP, IP_PKTINFO, &on, sizeof (on)))
+ {
+ OIC_LOG_V(ERROR, TAG, "IP_PKTINFO failed: %s", strerror(errno));
+ }
+ }
+
((struct sockaddr_in *)&sa)->sin_port = htons(*port);
socklen = sizeof (struct sockaddr_in);
}
caglobals.ip.selectTimeout = CAGetPollingInterval(caglobals.ip.selectTimeout);
- CAApplyInterfaces();
+ res = CAIPStartListenServer();
+ if (CA_STATUS_OK != res)
+ {
+ OIC_LOG_V(ERROR, TAG, "Failed to start listening server![%d]", res);
+ return res;
+ }
caglobals.ip.terminate = false;
res = ca_thread_pool_add_task(threadPool, CAReceiveHandler, NULL);
//applyMulticast6(caglobals.ip.m6s.fd, &IPv6MulticastAddressGlb, interface);
}
-static void CAApplyInterfaces()
+CAResult_t CAIPStartListenServer()
{
u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
if (!iflist)
{
OIC_LOG_V(ERROR, TAG, "get interface info failed: %s", strerror(errno));
- return;
+ return CA_STATUS_FAILED;
}
uint32_t len = u_arraylist_length(iflist);
}
u_arraylist_destroy(iflist);
+ return CA_STATUS_OK;
+}
+
+CAResult_t CAIPStopListenServer()
+{
+ u_arraylist_t *iflist = CAIPGetInterfaceInformation(0);
+ if (!iflist)
+ {
+ OIC_LOG_V(ERROR, TAG, "Get interface info failed: %s", strerror(errno));
+ return CA_STATUS_FAILED;
+ }
+
+ uint32_t len = u_arraylist_length(iflist);
+ OIC_LOG_V(DEBUG, TAG, "IP network interfaces found: %d", len);
+
+ for (uint32_t i = 0; i < len; i++)
+ {
+ CAInterface_t *ifitem = (CAInterface_t *)u_arraylist_get(iflist, i);
+
+ if (!ifitem)
+ {
+ continue;
+ }
+
+ if ((ifitem->flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
+ {
+ continue;
+ }
+ if (ifitem->family == AF_INET)
+ {
+ close(caglobals.ip.m4.fd);
+ close(caglobals.ip.m4s.fd);
+ caglobals.ip.m4.fd = -1;
+ caglobals.ip.m4s.fd = -1;
+ OIC_LOG_V(DEBUG, TAG, "IPv4 network interface: %s cloed", ifitem->name);
+ }
+ if (ifitem->family == AF_INET6)
+ {
+ close(caglobals.ip.m6.fd);
+ close(caglobals.ip.m6s.fd);
+ caglobals.ip.m6.fd = -1;
+ caglobals.ip.m6s.fd = -1;
+ OIC_LOG_V(DEBUG, TAG, "IPv6 network interface: %s", ifitem->name);
+ }
+ }
+ u_arraylist_destroy(iflist);
+ return CA_STATUS_OK;
}
static void CAProcessNewInterface(CAInterface_t *ifitem)
}
else
{
- OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %d bytes", secure, cast, fam, len);
+ OIC_LOG_V(INFO, TAG, "%s%s %s sendTo is successful: %ld bytes", secure, cast, fam, len);
}
}
OIC_LOG(DEBUG, TAG, "OUT");
return CA_STATUS_OK;
}
-
CAConnectivityHandler_t raHandler = {};
raHandler.startAdapter = CAStartRA;
raHandler.startListenServer = CAStartRAListeningServer;
+ raHandler.stopListenServer = CAStopRAListeningServer;
raHandler.startDiscoveryServer = CAStartRADiscoveryServer;
raHandler.sendData = CASendRAUnicastData;
raHandler.sendDataToAll = CASendRAMulticastData;
return CA_NOT_SUPPORTED;
}
+CAResult_t CAStopRAListeningServer()
+{
+ OIC_LOG(INFO, RA_ADAPTER_TAG, "RA adapter does not support listening for multicast data");
+ return CA_NOT_SUPPORTED;
+}
+
CAResult_t CAStartRADiscoveryServer()
{
OIC_LOG(INFO, RA_ADAPTER_TAG, "RA adapter does not support discovery of multicast servers");
#include <string.h>
#include <stdint.h>
+#define __STDC_FORMAT_MACROS
+#include <inttypes.h>
+
#include "catcpadapter.h"
#include "catcpinterface.h"
#include "caqueueingthread.h"
static CAErrorHandleCallback g_errorCallback = NULL;
static void CATCPPacketReceivedCB(const CAEndpoint_t *endpoint,
- const void *data, size_t dataLength);
+ const void *data, uint32_t dataLength);
static CAResult_t CATCPInitializeQueueHandles();
bool isMulticast);
void CAFreeTCPData(CATCPData *ipData);
-static void CADataDestroyer(void *data, size_t size);
+static void CADataDestroyer(void *data, uint32_t size);
CAResult_t CATCPInitializeQueueHandles()
{
}
void CATCPPacketReceivedCB(const CAEndpoint_t *endpoint, const void *data,
- size_t dataLength)
+ uint32_t dataLength)
{
OIC_LOG(DEBUG, TAG, "IN");
}
void CATCPErrorHandler(const CAEndpoint_t *endpoint, const void *data,
- size_t dataLength, CAResult_t result)
+ uint32_t dataLength, CAResult_t result)
{
OIC_LOG(DEBUG, TAG, "IN");
CAConnectivityHandler_t TCPHandler = {
.startAdapter = CAStartTCP,
.startListenServer = CAStartTCPListeningServer,
+ .stopListenServer = CAStopTCPListeningServer,
.startDiscoveryServer = CAStartTCPDiscoveryServer,
.sendData = CASendTCPUnicastData,
.sendDataToAll = CASendTCPMulticastData,
return CA_STATUS_OK;
}
+CAResult_t CAStopTCPListeningServer()
+{
+ OIC_LOG(DEBUG, TAG, "IN");
+
+ OIC_LOG(DEBUG, TAG, "OUT");
+ return CA_STATUS_OK;
+}
+
CAResult_t CAStartTCPDiscoveryServer()
{
OIC_LOG(DEBUG, TAG, "IN");
OICFree(TCPData);
}
-void CADataDestroyer(void *data, size_t size)
+void CADataDestroyer(void *data, uint32_t size)
{
if (size < sizeof(CATCPData))
{
- OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %d", data, size);
+ OIC_LOG_V(ERROR, TAG, "Destroy data too small %p %" PRIu32, data, size);
}
CATCPData *TCPData = (CATCPData *) data;
#ifdef __WITH_DTLS__
-/**
- * @def RS_IDENTITY
- * @brief
- */
-#define IDENTITY ("1111111111111111")
-/* @def RS_CLIENT_PSK
- * @brief
- */
-#define RS_CLIENT_PSK ("AAAAAAAAAAAAAAAA")
-
-static CADtlsPskCredsBlob_t *pskCredsBlob = NULL;
-
-void clearDtlsCredentialInfo()
-{
- printf("clearDtlsCredentialInfo IN\n");
- if (pskCredsBlob)
- {
- // Initialize sensitive data to zeroes before freeing.
- memset(pskCredsBlob->creds, 0, sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
- free(pskCredsBlob->creds);
+// Iotivity Device Identity.
+const unsigned char IDENTITY[] = ("1111111111111111");
- memset(pskCredsBlob, 0, sizeof(CADtlsPskCredsBlob_t));
- free(pskCredsBlob);
- pskCredsBlob = NULL;
- }
- printf("clearDtlsCredentialInfo OUT\n");
-}
+// PSK between this device and peer device.
+const unsigned char RS_CLIENT_PSK[] = ("AAAAAAAAAAAAAAAA");
-// Internal API. Invoked by OC stack to retrieve credentials from this module
-void CAGetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+// Internal API. Invoked by CA stack to retrieve credentials from this module
+int32_t CAGetDtlsPskCredentials( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length)
{
printf("CAGetDtlsPskCredentials IN\n");
- if (pskCredsBlob != NULL)
+ int32_t ret = -1;
+
+ if (NULL == result)
{
- *credInfo = pskCredsBlob;
+ return ret;
}
- printf("CAGetDtlsPskCredentials OUT\n");
-}
-
-int32_t SetCredentials()
-{
- printf("SetCredentials IN\n");
- pskCredsBlob = (CADtlsPskCredsBlob_t *)malloc(sizeof(CADtlsPskCredsBlob_t));
-
- memset(pskCredsBlob, 0x0, sizeof(CADtlsPskCredsBlob_t));
- memcpy(pskCredsBlob->identity, IDENTITY, DTLS_PSK_ID_LEN);
-
- pskCredsBlob->num = 1;
-
- pskCredsBlob->creds = (OCDtlsPskCreds *)malloc(sizeof(OCDtlsPskCreds) * (pskCredsBlob->num));
+ switch (type)
+ {
+ case CA_DTLS_PSK_HINT:
+ case CA_DTLS_PSK_IDENTITY:
+
+ if (result_length < sizeof(IDENTITY))
+ {
+ printf("ERROR : Wrong value for result for storing IDENTITY");
+ return ret;
+ }
+
+ memcpy(result, IDENTITY, sizeof(IDENTITY));
+ ret = sizeof(IDENTITY);
+ break;
+
+ case CA_DTLS_PSK_KEY:
+
+ if ((desc_len == sizeof(IDENTITY)) &&
+ memcmp(desc, IDENTITY, sizeof(IDENTITY)) == 0)
+ {
+ if (result_length < sizeof(RS_CLIENT_PSK))
+ {
+ printf("ERROR : Wrong value for result for storing RS_CLIENT_PSK");
+ return ret;
+ }
+
+ memcpy(result, RS_CLIENT_PSK, sizeof(RS_CLIENT_PSK));
+ ret = sizeof(RS_CLIENT_PSK);
+ }
+ break;
+
+ default:
+
+ printf("Wrong value passed for PSK_CRED_TYPE.");
+ ret = -1;
+ }
- memcpy(pskCredsBlob->creds[0].id, IDENTITY, DTLS_PSK_ID_LEN);
- memcpy(pskCredsBlob->creds[0].psk, RS_CLIENT_PSK, DTLS_PSK_PSK_LEN);
- printf("SetCredentials OUT\n");
- return 1;
+ printf("CAGetDtlsPskCredentials OUT\n");
+ return ret;
}
-#endif
+#endif //__WITH_DTLS__
int main(int argc, char **argv)
{
}
}
-// CASendNotification TC
-// check return value
-TEST(SendNotificationTest, DISABLED_TC_22_Positive_01)
-{
- addr = (char *) ADDRESS;
- CACreateEndpoint(CA_DEFAULT_FLAGS, CA_ADAPTER_IP, addr, PORT, &tempRep);
-
- memset(&responseData, 0, sizeof(CAInfo_t));
- responseData.type = CA_MSG_NONCONFIRM;
- responseData.payload = (CAPayload_t)malloc(sizeof("Temp Notification Data"));
-
- EXPECT_TRUE(responseData.payload != NULL);
- if(!responseData.payload)
- {
- CADestroyEndpoint(tempRep);
- return;
- }
-
- memcpy(responseData.payload, "Temp Notification Data", sizeof("Temp Notification Data"));
- responseData.payloadSize = sizeof("Temp Notification Data");
-
- CAGenerateToken(&tempToken, tokenLength);
- requestData.token = tempToken;
- requestData.tokenLength = tokenLength;
-
- memset(&responseInfo, 0, sizeof(CAResponseInfo_t));
- responseInfo.result = CA_CONTENT;
- responseInfo.info = responseData;
-
- EXPECT_EQ(CA_STATUS_OK, CASendNotification(tempRep, &responseInfo));
-
- CADestroyToken(tempToken);
- if (tempRep != NULL)
- {
- CADestroyEndpoint(tempRep);
- tempRep = NULL;
- }
- free(responseData.payload);
-}
-
// CASelectNewwork TC
// check return value
TEST_F(CATests, SelectNetworkTestGood)
TEST_F(CATests, RegisterDTLSCredentialsHandlerTest)
{
#ifdef __WITH_DTLS__
- if (SetCredentials() == 0)
- {
- printf("SetCredentials failed\n");
- }
-
EXPECT_EQ(CA_STATUS_OK, CARegisterDTLSCredentialsHandler(CAGetDtlsPskCredentials));
#endif
}
if (gatewayId == g_GatewayID)
{
OC_LOG(INFO, TAG, "-------------->Own entry, continue!!");
+ RTMFreeGatewayRouteTable(&gatewayTableList);
return OC_STACK_ERROR;
}
// Convert OCDevAddr to endpoint address
OC_LOG(ERROR, TAG, "Few packet drops are found, sequence number is not matching");
// Send a observe request to the gateway.
RMSendObserveRequest(devAddr, NULL);
+ RTMFreeGatewayRouteTable(&gatewayTableList);
return result;
}
else if (OC_STACK_DUPLICATE_REQUEST == result)
{
OC_LOG(ERROR, TAG, "Same sequence number is received");
+ RTMFreeGatewayRouteTable(&gatewayTableList);
return result;
}
}
// Create a list to add the updated entries and notify the observers
u_linklist_t *updatedTableList = u_linklist_create();
+ if(!updatedTableList)
+ {
+ OC_LOG(DEBUG, TAG, "Failed to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+
u_linklist_t *alternativeRouteList = u_linklist_create();
+ if(!alternativeRouteList)
+ {
+ OC_LOG(DEBUG, TAG, "Failed to allocate memory");
+ return OC_STACK_NO_MEMORY;
+ }
+
OCRepPayload *updatedPayload = NULL;
if (false == doRemoveEntry)
{
if (OC_STACK_OK != result)
{
OC_LOG_V(DEBUG, TAG, "Send response failed[%d]", result);
+ RMPFreePayload(payload);
return result;
}
for (uint32_t i = 0; i < u_arraylist_length(entry->destination->destIntfAddr); i++)
{
RTMDestIntfInfo_t *dest = u_arraylist_get(entry->destination->destIntfAddr, i);
+ if (!dest)
+ {
+ OC_LOG(ERROR, RM_TAG, "Failed to get dest address");
+ continue;
+ }
OCDevAddr devAddr = {.adapter = OC_DEFAULT_ADAPTER};
CopyEndpointToDevAddr(&(dest->destIntfAddr), &devAddr);
OC_LOG_V(DEBUG, TAG, "\nDestination interface addresses: %s[%d], OCDevAddr: %s[%d]",
RMSendDeleteRequest(&devAddr, payload);
}
}
- RMPFreePayload(payload);
+
u_linklist_get_next(&iterTable);
}
if (NULL == *gatewayTable)
{
*gatewayTable = u_linklist_create();
+ if (NULL == *gatewayTable)
+ {
+ OC_LOG(ERROR, TAG, "u_linklist_create failed");
+ return OC_STACK_NO_MEMORY;
+ }
}
if (1 == routeCost && 0 != nextHop)
if (NULL == *endpointTable)
{
*endpointTable = u_linklist_create();
+ if (NULL == *endpointTable)
+ {
+ OC_LOG(ERROR, TAG, "u_linklist_create failed");
+ return OC_STACK_NO_MEMORY;
+ }
}
u_linklist_iterator_t *iterTable = NULL;
if (NULL == *removedGatewayNodes)
{
*removedGatewayNodes = u_linklist_create();
+ if (NULL == *removedGatewayNodes)
+ {
+ OC_LOG(ERROR, TAG, "u_linklist_create failed");
+ return OC_STACK_NO_MEMORY;
+ }
}
OCStackResult ret = OC_STACK_OK;
u_linklist_init_iterator(*gatewayTable, &iterTable);
for (uint32_t i = 0; i < u_arraylist_length(entry->destination->destIntfAddr); i++)
{
RTMDestIntfInfo_t *destCheck = u_arraylist_get(entry->destination->destIntfAddr, i);
+ if(!destCheck)
+ {
+ continue;
+ }
if (0 == memcmp(destCheck->destIntfAddr.addr, destInfAdr->destIntfAddr.addr,
strlen(destInfAdr->destIntfAddr.addr))
&& destInfAdr->destIntfAddr.port == destCheck->destIntfAddr.port)
RM_NULL_CHECK_VOID(gatewayTable, TAG, "gatewayTable");
*neighbourNodes = u_linklist_create();
+ if (NULL == *neighbourNodes)
+ {
+ OC_LOG(ERROR, TAG, "u_linklist_create failed");
+ return;
+ }
u_linklist_iterator_t *iterTable = NULL;
u_linklist_init_iterator(gatewayTable, &iterTable);
while (NULL != iterTable)
{
RTMDestIntfInfo_t *removeAdr =
u_arraylist_get(entry->destination->destIntfAddr, i);
+ if (!removeAdr)
+ {
+ continue;
+ }
if (0 == memcmp(removeAdr->destIntfAddr.addr, destInterfaces.destIntfAddr.addr,
strlen(destInterfaces.destIntfAddr.addr))
&& destInterfaces.destIntfAddr.port == removeAdr->destIntfAddr.port)
RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
*invalidTable = u_linklist_create();
+ if (NULL == *invalidTable)
+ {
+ OC_LOG(ERROR, TAG, "u_linklist_create failed");
+ return OC_STACK_NO_MEMORY;
+ }
+
u_linklist_iterator_t *iterTable = NULL;
uint64_t presentTime = RTMGetCurrentTime();
for (uint32_t i = 0; i < u_arraylist_length(entry->destination->destIntfAddr); i++)
{
RTMDestIntfInfo_t *destCheck = u_arraylist_get(entry->destination->destIntfAddr, i);
+ if (!destCheck)
+ {
+ continue;
+ }
if (GATEWAY_ALIVE_TIMEOUT < (presentTime - destCheck->timeElapsed))
{
destCheck->isValid = false;
RM_NULL_CHECK_WITH_RET(*gatewayTable, TAG, "*gatewayTable");
*invalidTable = u_linklist_create();
+ if (NULL == *invalidTable)
+ {
+ OC_LOG(ERROR, TAG, "u_linklist_create failed");
+ return OC_STACK_NO_MEMORY;
+ }
u_linklist_iterator_t *iterTable = NULL;
u_linklist_init_iterator(*gatewayTable, &iterTable);
for (uint32_t i = 0; i < u_arraylist_length(entry->destination->destIntfAddr); i++)
{
RTMDestIntfInfo_t *destCheck = u_arraylist_get(entry->destination->destIntfAddr, i);
- if (!destCheck->isValid)
+ if (!destCheck && !destCheck->isValid)
{
void *data = u_arraylist_remove(entry->destination->destIntfAddr, i);
OICFree(data);
#ifndef IOTVT_SRM_CREDR_H
#define IOTVT_SRM_CREDR_H
-#include "ocsecurityconfig.h"
#include "cainterface.h"
#include "securevirtualresourcetypes.h"
#include "octypes.h"
* This internal callback is used by lower stack (i.e. CA layer) to
* retrieve PSK credentials from RI security layer.
*
- * Note: When finished, caller should initialize memory to zeroes and
- * invoke OCFree to delete @p credInfo.
+ * @param[in] type type of PSK data required by CA layer during DTLS handshake.
+ * @param[in] desc Additional request information.
+ * @param[in] desc_len The actual length of desc.
+ * @param[out] result Must be filled with the requested information.
+ * @param[in] result_length Maximum size of @p result.
*
- * @param credInfo
- * binary blob containing PSK credentials
- *
- * @retval none
+ * @return The number of bytes written to @p result or a value
+ * less than zero on error.
*/
-void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo);
+int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length);
/**
* Add temporal PSK to PIN based OxM
x509_env.AppendUnique(LIBS = ['asn1'])
x509_env.AppendUnique(LIBS = ['Base64'])
x509_env.AppendUnique(LIBS = ['Json'])
+
+SConscript('sample/SConscript')
+SConscript('unittest/SConscript')
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH 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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <pthread.h>
+#include <iostream>
+#include <sstream>
+#include "ocstack.h"
+#include "logger.h"
+#include "cJSON.h"
+#include "global.h"
+#include "cainterface.h"
+#include "cacommon.h"
+#include "payload_logging.h"
+#include "ocpayload.h"
+
+
+#define TAG "DEMO"
+#define DEFAULT_CONTEXT_VALUE 0x99
+#define STATE "state"
+#define OPEN_DURATION "openDuration"
+#define OPEN_ALARM "openAlarm"
+
+static const char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
+
+volatile sig_atomic_t gQuitFlag = 0;
+OCPersistentStorage ps = {0, 0, 0, 0, 0};
+static const char *gResourceUri = "/a/door";
+uint8_t lightIpAddr[4] = {};
+uint16_t lightPortNu;
+static bool isUpdated = false;
+static std::string coapServerIP;
+static std::string coapServerPort;
+static std::string coapServerResource;
+static OCConnectivityType ocConnType;
+
+static std::string address;
+
+static int coapSecureResource;
+
+static const char CRED_FILE[] = "oic_svr_db_door.json";
+
+CAEndpoint_t endpoint = {CA_DEFAULT_ADAPTER, CA_DEFAULT_FLAGS, 0, {0}, 0};
+
+// myDoorState_t variable to store resource's state .
+typedef enum
+{
+ STATE_OPEN, /**< State is opened */
+ STATE_CLOSED /**< State is closed*/
+} myDoorState_t;
+
+//Structure to represent a door resource and its attributes
+typedef struct DOORRESOURCE
+{
+ OCResourceHandle handle;
+ myDoorState_t state; //ReadOnly, The state of the door (open or closed)"
+ char *openDuration; //ReadOnly, The time duration the door has been open
+ bool openAlarm ; //The state of the door open alarm
+
+} DoorResource;
+
+static DoorResource Door;
+
+int parseClientResponse(OCClientResponse * clientResponse)
+{
+ if(!clientResponse)
+ {
+ return 0;
+ }
+
+ OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+
+ // Initialize all global variables
+ coapServerResource.clear();
+ coapSecureResource = 0;
+
+ while (res)
+ {
+ coapServerResource.assign(res->uri);
+ OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
+
+ if (res->secure)
+ {
+ endpoint.port = res->port;
+ coapSecureResource = 1;
+ }
+
+ OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
+
+ // If we discovered a secure resource, exit from here
+ if (coapSecureResource)
+ {
+ break;
+ }
+
+ res = res->next;
+ }
+
+ return 0;
+}
+
+OCRepPayload* getPayload(const char* uri, int64_t state, char* openDuration, bool openAlarm)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+ return nullptr;
+ }
+
+ OCRepPayloadSetUri(payload, uri);
+ OCRepPayloadSetPropInt(payload, STATE, state);
+ OCRepPayloadSetPropString(payload, OPEN_DURATION, openDuration);
+ OCRepPayloadSetPropBool(payload, OPEN_ALARM, openAlarm);
+
+ return payload;
+}
+
+//This function takes the request as an input and returns the response
+OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
+{
+ if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+ return nullptr;
+ }
+
+ DoorResource *currdoorResource = &Door;
+
+ return getPayload(gResourceUri, currdoorResource->state, currdoorResource->openDuration, currdoorResource->openAlarm);
+}
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload **payload)
+{
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+ OCRepPayload *getResp = constructResponse(ehRequest);
+
+ if(getResp)
+ {
+ *payload = getResp;
+ ehResult = OC_EH_OK;
+ }
+
+ return ehResult;
+}
+
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest *entityHandlerRequest,
+ void* /*callbackParam*/)
+{
+ OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ OCEntityHandlerResponse response;
+
+ // Validate pointer
+ if (!entityHandlerRequest)
+ {
+ OC_LOG (ERROR, TAG, "Invalid request pointer");
+ return OC_EH_ERROR;
+ }
+
+ OCRepPayload* payload = nullptr;
+
+ if (flag & OC_REQUEST_FLAG)
+ {
+ OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+
+ if (entityHandlerRequest)
+ {
+ switch(entityHandlerRequest->method)
+ {
+ case OC_REST_GET:
+ {
+ OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+ ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
+ }
+ break;
+ default:
+ {
+ OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+ entityHandlerRequest->method);
+ ehResult = OC_EH_ERROR;
+ }
+ break;
+ }
+
+ if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
+ {
+ // Format the response. Note this requires some info about the request
+ response.requestHandle = entityHandlerRequest->requestHandle;
+ response.resourceHandle = entityHandlerRequest->resource;
+ response.ehResult = ehResult;
+ response.payload = reinterpret_cast<OCPayload*>(payload);
+ response.numSendVendorSpecificHeaderOptions = 0;
+ memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+ memset(response.resourceUri, 0, sizeof(response.resourceUri));
+ // Indicate that response is NOT in a persistent buffer
+ response.persistentBufferFlag = 0;
+
+ // Send the response
+ if (OCDoResponse(&response) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Error sending response");
+ ehResult = OC_EH_ERROR;
+ }
+ }
+ }
+ }
+
+ OCPayloadDestroy(response.payload);
+ return ehResult;
+}
+
+
+/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
+void handleSigInt(int signum)
+{
+ if (signum == SIGINT)
+ {
+ gQuitFlag = 1;
+ }
+}
+
+FILE *server_fopen(const char * /*path*/, const char *mode)
+{
+ return fopen(CRED_FILE, mode);
+}
+
+void SetPersistentHandler(OCPersistentStorage *ps)
+{
+ if (ps)
+ {
+ ps->open = server_fopen;
+ ps->read = fread;
+ ps->write = fwrite;
+ ps->close = fclose;
+ ps->unlink = unlink;
+
+ OCRegisterPersistentStorageHandler(ps);
+ }
+}
+
+/**
+ * GetResult is returned result to string.
+ * @param result [IN] stack result
+ * @return converted OCStackResult as string for debugging
+ */
+static const char *getResult(OCStackResult result)
+{
+ switch (result)
+ {
+ case OC_STACK_OK:
+ return "OC_STACK_OK";
+ case OC_STACK_RESOURCE_CREATED:
+ return "OC_STACK_RESOURCE_CREATED";
+ case OC_STACK_RESOURCE_DELETED:
+ return "OC_STACK_RESOURCE_DELETED";
+ 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_UNAUTHORIZED_REQ:
+ return "OC_STACK_UNAUTHORIZED_REQ";
+ #ifdef WITH_PRESENCE
+ case OC_STACK_PRESENCE_STOPPED:
+ return "OC_STACK_PRESENCE_STOPPED";
+ #endif
+ case OC_STACK_ERROR:
+ return "OC_STACK_ERROR";
+ default:
+ return "UNKNOWN";
+ }
+}
+
+
+/**
+ * CreateDoorResource creates a new door resource by calling the OCCreateResource() method.
+ * @param uri [IN] uri
+ * @param doorResource [IN] info of resource
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+int createDoorResource (const char *uri, DoorResource *doorResource)
+{
+ if (!uri)
+ {
+ OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+
+ }
+
+ doorResource->state = STATE_CLOSED; //1:closed , 0: open
+ char str[] = "10min";
+ doorResource->openDuration = str;
+ doorResource->openAlarm = false;
+ OCStackResult res = OCCreateResource(&(doorResource->handle),
+ "core.door",
+ OC_RSRVD_INTERFACE_DEFAULT,
+ uri,
+ OCEntityHandlerCb,
+ NULL,
+ OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+
+ OC_LOG_V(INFO, TAG, "Created Door resource with result: %s", getResult(res));
+ return 0;
+}
+
+OCStackApplicationResult putReqCB(void * ctx, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
+{
+ if (ctx == (void *)DEFAULT_CONTEXT_VALUE)
+ {
+ OC_LOG(INFO, TAG, "Callback Context for PUT recvd successfully");
+ }
+
+ if (clientResponse)
+ {
+ OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+ OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+ OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+ if ((OCSecurityPayload*)clientResponse->payload)
+ {
+ OC_LOG_V(INFO, TAG, "=============> Put Response",
+ ((OCSecurityPayload*)clientResponse->payload)->securityData);
+ }
+ }
+ return OC_STACK_DELETE_TRANSACTION;
+}
+
+OCStackApplicationResult getReqCB(void * /*ctx*/, OCDoHandle /*handle*/, OCClientResponse *clientResponse)
+{
+ OC_LOG(INFO, TAG, "Callback Context for GET query recvd successfully");
+
+ if (clientResponse)
+ {
+ OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+ OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
+ OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+ if ((OCSecurityPayload*)clientResponse->payload)
+ {
+ OC_LOG(INFO, TAG, PCF("=============> Get Response"));
+ }
+ }
+ return OC_STACK_DELETE_TRANSACTION;
+}
+
+// This is a function called back when a device is discovered
+OCStackApplicationResult discoveryReqCB(void* /*ctx*/, OCDoHandle /*handle*/,
+ OCClientResponse * clientResponse)
+{
+ OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
+
+ if (clientResponse)
+ {
+ OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
+ OC_LOG_V(INFO, TAG,
+ "Device =============> Discovered @ %s:%d",
+ clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+
+ if (clientResponse->result == OC_STACK_OK)
+ {
+ OC_LOG_PAYLOAD(INFO, clientResponse->payload);
+ ocConnType = clientResponse->connType;
+ parseClientResponse(clientResponse);
+ }
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+
+
+void initAddress()
+{
+ static bool initFlag = false;
+ if (!initFlag)
+ {
+ OC_LOG(INFO, TAG, "Enter IP address (with optional port) of the Server hosting resource\n");
+ OC_LOG(INFO, TAG, "IPv4: 192.168.0.15:45454\n");
+ OC_LOG(INFO, TAG, "IPv6: [fe80::20c:29ff:fe1b:9c5]:45454\n");
+
+ std::cin >> address;
+ }
+ initFlag = true;
+}
+
+// Local function to send get request of light resource
+void SendGetRequest()
+{
+ OCStackResult ret;
+ OC_LOG(INFO, TAG, "Send Get REQ to Light server");
+
+ initAddress();
+
+ char szQueryUri[64] = { '\0'};
+ OCDoHandle handle;
+ OCCallbackData cbData;
+ cbData.cb = getReqCB;
+ cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+ cbData.cd = NULL;
+ OC_LOG_V(INFO, TAG, "Get payload from Door sample = /a/light ");
+ snprintf(szQueryUri, sizeof(szQueryUri), "coaps://%s/a/light", const_cast<char*> (address.c_str())); // lightPortNu);
+ ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, NULL, ocConnType, OC_LOW_QOS,
+ &cbData, NULL, 0);
+ if (ret != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack resource error");
+ }
+}
+
+
+void *input_function(void * /*data*/)
+{
+ char input;
+ char szQueryUri[64] = { 0 };
+ OCDoHandle handle;
+ OCCallbackData cbData;
+ cbData.cb = discoveryReqCB;
+ cbData.context = (void *)DEFAULT_CONTEXT_VALUE;
+ cbData.cd = NULL;
+
+ strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
+
+ while (1)
+ {
+ std::cin >> input;
+ switch (input)
+ {
+ case 'D':
+ case 'd':
+ if (isUpdated == false)
+ {
+ OC_LOG(INFO, TAG, "isUpdated is false...");
+ OCDoResource(&handle, OC_REST_DISCOVER, szQueryUri, 0, 0, CT_DEFAULT, OC_LOW_QOS, &cbData, NULL, 0);
+
+ }
+ break;
+ case 'G':
+ case 'g':
+ isUpdated = true;
+ if (isUpdated == true)
+ {
+ OC_LOG(INFO, TAG, "isUpdated is true...");
+ SendGetRequest();
+ }
+ break;
+ case 'Q':
+ case 'q':
+ gQuitFlag = 1;
+ return 0;
+ default: break;
+ }
+ }
+ return 0;
+}
+
+static void PrintUsage()
+{
+ OC_LOG(INFO, TAG, "*******************************************");
+ OC_LOG(INFO, TAG, "Input D or d to discover Resources");
+ OC_LOG(INFO, TAG, "Input G or g to initiate Get Request");
+ OC_LOG(INFO, TAG, "Input Q or q to exit");
+ OC_LOG(INFO, TAG, "*******************************************");
+}
+
+int main()
+{
+
+ OC_LOG(INFO, TAG, "OCServer is starting...");
+ SetPersistentHandler(&ps);
+ //PrintUsage();
+ if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack init error");
+ return 0;
+ }
+
+ /*
+ * Declare and create the example resource: Door
+ */
+ createDoorResource(gResourceUri, &Door);
+ PrintUsage();
+
+ //select ciphersuite for certificates
+ CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
+
+ struct timespec timeout;
+ timeout.tv_sec = 0;
+ timeout.tv_nsec = 100000000L;
+
+ // Break from loop with Ctrl-C
+ OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+ signal(SIGINT, handleSigInt);
+ int thr_id;
+ pthread_t p_thread;
+ thr_id = pthread_create(&p_thread, NULL, input_function, (void *)NULL);
+ if (thr_id < 0)
+ {
+ OC_LOG(ERROR, TAG, "create thread error");
+ return 0;
+ }
+
+ while (!gQuitFlag)
+ {
+
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ return 0;
+ }
+
+
+ nanosleep(&timeout, NULL);
+ }
+
+ pthread_join(p_thread, NULL);
+
+ OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+
+ if (OCStop() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ }
+
+ return 0;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 Intel Mobile Communications GmbH 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 <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <signal.h>
+#include <iostream>
+#include <pthread.h>
+#include "ocstack.h"
+#include "logger.h"
+#include "cJSON.h"
+#include "global.h"
+#include "cainterface.h"
+#include "cacommon.h"
+#include "ocpayload.h"
+
+#define TAG "DEMO"
+
+volatile sig_atomic_t gQuitFlag = 0;
+OCPersistentStorage ps = {0, 0, 0, 0, 0};
+const char *gResourceUri = (char *)"/a/light";
+
+//Secure Virtual Resource database for Iotivity Server
+//It contains Server's Identity and the PSK credentials
+//of other devices which the server trusts
+static char CRED_FILE[] = "oic_svr_db_light.json";
+
+
+//Structure to represent a light resource and its attributes
+typedef struct LIGHTRESOURCE
+{
+ OCResourceHandle handle;
+ //Attributes
+ int brightness; // 0-100
+} LightResource;
+
+// Structure to represent a light resource and its attributes
+static LightResource Light;
+
+OCRepPayload* getPayload(const char* uri, int64_t brightness)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if(!payload)
+ {
+ OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+ return nullptr;
+ }
+
+ OCRepPayloadSetUri(payload, uri);
+ OCRepPayloadSetPropInt(payload, "brightness", brightness);
+
+ return payload;
+}
+
+//This function takes the request as an input and returns the response
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
+{
+ if(!ehRequest)
+ {
+ return nullptr;
+ }
+
+ if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+ return nullptr;
+ }
+
+ return getPayload(gResourceUri, Light.brightness);
+}
+
+OCEntityHandlerResult ProcessGetRequest (OCEntityHandlerRequest *ehRequest,
+ OCRepPayload **payload)
+{
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+ OCRepPayload *getResp = constructResponse(ehRequest);
+
+ if(getResp && payload)
+ {
+ *payload = getResp;
+ ehResult = OC_EH_OK;
+ }
+
+ return ehResult;
+}
+
+
+OCEntityHandlerResult OCEntityHandlerCb (OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest *entityHandlerRequest,
+ void* /*callbackParam*/)
+{
+ OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ OCEntityHandlerResponse response;
+
+ // Validate pointer
+ if (!entityHandlerRequest)
+ {
+ OC_LOG (ERROR, TAG, "Invalid request pointer");
+ return OC_EH_ERROR;
+ }
+
+ OCRepPayload* payload = nullptr;
+
+ if (flag & OC_REQUEST_FLAG)
+ {
+ OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+ if (entityHandlerRequest)
+ {
+ switch(entityHandlerRequest->method)
+ {
+ case OC_REST_GET:
+ {
+ OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+ ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
+ }
+ break;
+ default:
+ {
+ OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+ entityHandlerRequest->method);
+ ehResult = OC_EH_ERROR;
+ }
+ break;
+ }
+
+ if (ehResult == OC_EH_OK && ehResult != OC_EH_FORBIDDEN)
+ {
+ // Format the response. Note this requires some info about the request
+ response.requestHandle = entityHandlerRequest->requestHandle;
+ response.resourceHandle = entityHandlerRequest->resource;
+ response.ehResult = ehResult;
+ response.payload = reinterpret_cast<OCPayload*>(payload);
+ response.numSendVendorSpecificHeaderOptions = 0;
+ memset(response.sendVendorSpecificHeaderOptions, 0, sizeof response.sendVendorSpecificHeaderOptions);
+ memset(response.resourceUri, 0, sizeof(response.resourceUri));
+ // Indicate that response is NOT in a persistent buffer
+ response.persistentBufferFlag = 0;
+
+ // Send the response
+ if (OCDoResponse(&response) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Error sending response");
+ ehResult = OC_EH_ERROR;
+ }
+ }
+ }
+ }
+
+ OCPayloadDestroy(response.payload);
+ return ehResult;
+}
+
+/* SIGINT handler: set gQuitFlag to 1 for graceful termination */
+void handleSigInt(int signum)
+{
+ if (signum == SIGINT)
+ {
+ gQuitFlag = 1;
+ }
+}
+
+FILE* server_fopen(const char * /*path*/, const char *mode)
+{
+ return fopen(CRED_FILE, mode);
+}
+
+void SetPersistentHandler(OCPersistentStorage *ps)
+
+{
+
+ if (ps)
+
+ {
+
+ ps->open = server_fopen;
+
+ ps->read = fread;
+
+ ps->write = fwrite;
+
+ ps->close = fclose;
+
+ ps->unlink = unlink;
+
+
+ OCRegisterPersistentStorageHandler(ps);
+
+ }
+
+}
+/**
+ * GetResult is returned result to string.
+ * @param result [IN] stack result
+ * @return converted OCStackResult as string for debugging
+ */
+static const char *getResult(OCStackResult result)
+{
+ switch (result)
+ {
+ case OC_STACK_OK:
+ return "OC_STACK_OK";
+ case OC_STACK_RESOURCE_CREATED:
+ return "OC_STACK_RESOURCE_CREATED";
+ case OC_STACK_RESOURCE_DELETED:
+ return "OC_STACK_RESOURCE_DELETED";
+ 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";
+ }
+}
+
+/**
+ * CreateLightResource creates a new light resource by calling the OCCreateResource() method.
+ * @param uri [IN] uri
+ * @param lightResource [IN] info of resource
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+int createLightResource (const char *uri, LightResource *lightResource)
+{
+ if (!uri)
+ {
+ OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+
+ }
+
+ lightResource->brightness = 0;
+ OCStackResult res = OCCreateResource(&(lightResource->handle),
+ "core.light",
+ OC_RSRVD_INTERFACE_DEFAULT,
+ uri,
+ OCEntityHandlerCb,
+ NULL,
+ OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
+
+ OC_LOG_V(INFO, TAG, "Created Light resource with result: %s", getResult(res));
+ return 0;
+}
+
+
+int main()
+{
+ OC_LOG(DEBUG, TAG, "OCServer is starting...");
+ SetPersistentHandler(&ps);
+ if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack init error");
+ return 0;
+ }
+
+ /*
+ * Declare and create the example resource: Light
+ */
+ createLightResource(gResourceUri, &Light);
+
+ CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
+
+ struct timespec timeout;
+ timeout.tv_sec = 0;
+ timeout.tv_nsec = 100000000L;
+
+ // Break from loop with Ctrl-C
+ OC_LOG(INFO, TAG, "Entering ocserver main loop...");
+ signal(SIGINT, handleSigInt);
+ while (!gQuitFlag)
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ return 0;
+ }
+
+ nanosleep(&timeout, NULL);
+ }
+
+ OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+
+ if (OCStop() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ }
+
+ return 0;
+}
--- /dev/null
+# Open three terminal windows in linux
+# The first one use for start Light server
+# Note: Here and below $PROJ_DIR is root directory of iotivity project (e.g /path/to/iotivity)
+$ cd $PROJ_DIR/out/linux/x86_64/release/resource/csdk/security/provisioning/ck_manager/sample/Light_Resource
+$ cp $PROJ_DIR/resource/csdk/security/provisioning/ck_manager/sample/Light_Resource/*.json ./
+$ ./Light_server
+
+# Second terminal window use for start Door server
+$ cp $PROJ_DIR/resource/csdk/security/provisioning/ck_manager/sample/Door_Resource/*.json ./
+$ ./Door_server
+
+# And third terminal window use for start provisioning_client
+# provisioning_client ask for input ACL data:
+# 1. Controller device. Enter ID of the doorDeviceUUID00
+# 2. Controlee device. Enter ID of the lightDeviceUUID0
+# 3. Subject : doorDeviceUUID00
+# 4. Num. of Resource : 1
+# 5. [1]Resource : /a/light
+# 6. permissions: CRUDN
+# 7. Num. of Rowner : 1
+# 8. [1]Rowner : lightDeviceUUID0
+#
+# After successfull sending acl provisioning_client will ask you for CRL data:
+# 1. Enter number of revoced certificates(1..9): 1
+# 2. Revoced certificate 0: Serial number (E. g.: 100): 3
+# And then you should see message about successfull sending CRL
+#
+# Note: provisioning_client send ACL and CRL only to Light sever
+
+$ cd $PROJ_DIR/out/linux/x86_64/release/resource/csdk/security/provisioning/ck_manager/sample
+$ rm ckminfo.dat
+$ cp $PROJ_DIR/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json ./
+$ ./provisioningclient
+Provisioning device ID : doorDeviceUUID00
+Provisioning Success~!!
+Provisioning device ID : lightDeviceUUID0
+Provisioning Success~!!
+Sending credential is succeed~!!
+******************************************************************************
+-Set ACL policy for target device
+******************************************************************************
+-URN identifying the subject
+ex) doorDeviceUUID00 (16 Numbers except to '-')
+Subject : doorDeviceUUID00
+Num. of Resource : 1
+-URI of resource
+ex) /a/light (Max_URI_Length: 64 Byte )
+[1]Resource : /a/light
+-Set the permission(C,R,U,D,N)
+ex) CRUDN, CRU_N,..(5 Charaters)
+Permission : CRUDN
+Num. of Rowner : 1
+-URN identifying the rowner
+ex) lightDeviceUUID0 (16 Numbers except to '-')
+[1]Rowner : lightDeviceUUID0
+Sending ACL is succeed~!!
+Enter number of revoced certificates (1..9)
+1
+Revoked certificate 0:
+Serial number (E. g.: 100):
+2
+Sending CRL is succeed~!!
+
+# Change window to terminal where Door server is running
+# Enter 'd' for discovery. You should see output like this:
+21:56.283 INFO: DEMO: isUpdated is false...
+21:56.495 INFO: DEMO: Callback Context for DISCOVER query recvd successfully
+21:56.495 INFO: DEMO: StackResult: OC_STACK_OK
+21:56.495 INFO: DEMO: Device =============> Discovered @ 10.0.2.15:37942
+21:56.495 INFO: DEMO: Payload Type: Discovery
+21:56.495 INFO: DEMO: Resource #1
+21:56.495 INFO: DEMO: URI:/a/light
+21:56.495 INFO: DEMO: SID:
+21:56.495 INFO: DEMO: F0 5A 6C 8B 59 66 48 89 BE 1E 4E EF FA 23 4E FD
+21:56.495 INFO: DEMO: Resource Types:
+21:56.495 INFO: DEMO: core.light
+21:56.495 INFO: DEMO: Interfaces:
+21:56.495 INFO: DEMO: oic.if.baseline
+21:56.495 INFO: DEMO: Bitmap: 3
+21:56.495 INFO: DEMO: Secure?: true
+21:56.495 INFO: DEMO: Port: 43910
+21:56.495 INFO: DEMO:
+21:56.495 INFO: DEMO: Uri -- /a/light
+21:56.495 INFO: DEMO: Secure -- YES
+21:56.591 INFO: DEMO: Callback Context for DISCOVER query recvd successfully
+21:56.591 INFO: DEMO: StackResult: OC_STACK_OK
+21:56.591 INFO: DEMO: Device =============> Discovered @ 10.0.2.15:55808
+21:56.591 INFO: DEMO: Payload Type: Discovery
+21:56.591 INFO: DEMO: Resource #1
+21:56.591 INFO: DEMO: URI:/a/door
+21:56.591 INFO: DEMO: SID:
+21:56.591 INFO: DEMO: E9 68 45 ED 5D E1 4A F3 86 31 FD 0E 5E 25 EB B3
+21:56.591 INFO: DEMO: Resource Types:
+21:56.591 INFO: DEMO: core.door
+21:56.591 INFO: DEMO: Interfaces:
+21:56.591 INFO: DEMO: oic.if.baseline
+21:56.591 INFO: DEMO: Bitmap: 3
+21:56.591 INFO: DEMO: Secure?: true
+21:56.591 INFO: DEMO: Port: 41403
+21:56.591 INFO: DEMO:
+21:56.591 INFO: DEMO: Uri -- /a/door
+21:56.591 INFO: DEMO: Secure -- YES
+
+# If you can see /a/light discowered then this is success.
+# Next you should enter g to start get request
+# Enter address : 10.0.2.15:43910
+# Port you can find here
+21:56.495 INFO: DEMO: URI:/a/light
+21:56.495 INFO: DEMO: SID:
+21:56.495 INFO: DEMO: F0 5A 6C 8B 59 66 48 89 BE 1E 4E EF FA 23 4E FD
+21:56.495 INFO: DEMO: Resource Types:
+21:56.495 INFO: DEMO: core.light
+21:56.495 INFO: DEMO: Interfaces:
+21:56.495 INFO: DEMO: oic.if.baseline
+21:56.495 INFO: DEMO: Bitmap: 3
+21:56.495 INFO: DEMO: Secure?: true
+21:56.495 INFO: DEMO: Port: 43910
+
+# If you see this lines in output:
+22:31.647 INFO: DEMO: Callback Context for GET query recvd successfully
+22:31.647 INFO: DEMO: StackResult: OC_STACK_OK
+22:31.647 INFO: DEMO: SEQUENCE NUMBER: 2
+22:31.647 INFO: DEMO: Payload Type: Representation
+22:31.647 INFO: DEMO: Resource #1
+22:31.647 INFO: DEMO: URI:/a/light
+22:31.647 INFO: DEMO: Resource Types:
+22:31.647 INFO: DEMO: Interfaces:
+22:31.647 INFO: DEMO: Values:
+22:31.647 INFO: DEMO: brightness(int):0
+22:31.647 INFO: DEMO: =============> Get Response
+# then certificate did not rejected with CRL
+# if not then it did.
--- /dev/null
+# //******************************************************************
+# //
+# // Copyright 2015 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.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+
+Import('env')
+
+provisioning_env = env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+provisioning_env.AppendUnique(CPPPATH = [
+ '../../../../stack/include',
+ '../../../../ocrandom/include',
+ '../../../../logger/include',
+ '../../../../security/include',
+ '../../../../../oc_logger/include',
+ '../../include',
+ '../../include/internal',
+ '../../../include',
+ '../../../include/internal',
+ '../../../../../../extlibs/tinydtls',
+ '../../../../../../extlibs/cjson',
+ '../../../../../../extlibs/asn1cert/',
+ '../../../../../../extlibs/tinydtls/ecc/',
+ '../../../../../../extlibs/tinydtls/sha2/',
+ '../../../../connectivity/inc',
+ '../../../../connectivity/inc/pkix/',
+ '../../../../connectivity/common/inc',
+ '../../../../connectivity/lib/libcoap-4.1.1',
+ '../../../../connectivity/api',
+ '../../../../../c_common/oic_malloc/include',
+ '../include',
+ '../../include/oxm'
+ ])
+
+provisioning_env.AppendUnique(CFLAGS = ['-D__WITH_DTLS__','-std=c99'])
+provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-fpermissive'])
+provisioning_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
+
+provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm','m', 'octbstack', 'connectivity_abstraction', 'coap'])
+provisioning_env.AppendUnique(LIBS = ['CKManager'])
+provisioning_env.AppendUnique(LIBS = ['asn1'])
+
+if env.get('SECURED') == '1':
+ provisioning_env.AppendUnique(LIBS = ['tinydtls'])
+
+provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+provisioning_client = provisioning_env.Program('provisioningclient', 'provisioningclient.c')
+light_server =provisioning_env.Program('light_server', 'Light_sample.cpp')
+door_server=provisioning_env.Program('door_server', 'Door_sample.cpp')
+
+Alias("samples", [provisioning_client, light_server, door_server])
+
+provisioning_env.AppendTarget('samples')
+
+src_dir = provisioning_env.get('SRC_DIR')
+sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/ck_manager/sample/'
+sec_provisioning_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/ck_manager/sample/'
+
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+ sec_provisioning_src_dir + 'oic_svr_db_pt.json'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+ sec_provisioning_src_dir + 'oic_svr_db_light.json'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+ sec_provisioning_src_dir + 'oic_svr_db_door.json'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+ sec_provisioning_src_dir + 'README.txt'))
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/res/d",
+ "/oic/res/types/d",
+ "/oic/presence"
+ ],
+ "perms": 2,
+ "ownrs" : [
+ "ZG9vckRldmljZVVVSUQwMA=="
+ ]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat",
+ "/oic/sec/acl",
+ "/oic/sec/crl",
+ "/oic/sec/cred"
+ ],
+ "perms": 6,
+ "ownrs" : [
+ "ZG9vckRldmljZVVVSUQwMA=="
+ ]
+ }
+ ],
+ "pstat": {
+ "isop": false,
+ "deviceid": "ZG9vckRldmljZVVVSUQwMA==",
+ "commithash": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": false,
+ "deviceid": "ZG9vckRldmljZVVVSUQwMA=="
+ }
+}
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/res/d",
+ "/oic/res/types/d",
+ "/oic/presence"
+ ],
+ "perms": 2,
+ "ownrs" : [
+ "bGlnaHREZXZpY2VVVUlEMA=="
+ ]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat",
+ "/oic/sec/acl",
+ "/oic/sec/crl",
+ "/oic/sec/cred"
+ ],
+ "perms": 6,
+ "ownrs" : [
+ "bGlnaHREZXZpY2VVVUlEMA=="
+ ]
+ }
+ ],
+ "pstat": {
+ "isop": false,
+ "deviceid": "bGlnaHREZXZpY2VVVUlEMA==",
+ "commithash": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": false,
+ "deviceid": "bGlnaHREZXZpY2VVVUlEMA=="
+ }
+}
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/d",
+ "/oic/p",
+ "/oic/res/types/d",
+ "/oic/ad"
+ ],
+ "perms": 2,
+ "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat",
+ "/oic/sec/acl",
+ "/oic/sec/cred"
+ ],
+ "perms": 7,
+ "ownrs" : ["YWRtaW5EZXZpY2VVVUlEMA=="]
+ }
+ ],
+ "pstat": {
+ "isop": true,
+ "deviceid": "YWRtaW5EZXZpY2VVVUlEMA==",
+ "ch": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "sct": 1,
+ "owned": true,
+ "deviceid": "YWRtaW5EZXZpY2VVVUlEMA==",
+ "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
+ }
+}
--- /dev/null
+/******************************************************************
+*
+* Copyright 2015 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 <stdio.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "logger.h"
+#include "oic_malloc.h"
+#include "utlist.h"
+#include "ocprovisioningmanager.h"
+#include "secureresourceprovider.h"
+#include "oxmjustworks.h"
+#include "oic_string.h"
+#include "securevirtualresourcetypes.h"
+#include "cacommon.h"
+#include "ck_manager.h"
+#include "ckm_info.h"
+#include "crlresource.h"
+
+#define MAX_URI_LENGTH (64)
+#define MAX_PERMISSION_LENGTH (5)
+#define CREATE (1)
+#define READ (2)
+#define UPDATE (4)
+#define DELETE (8)
+#define NOTIFY (16)
+#define DASH '-'
+#define PREDEFINED_TIMEOUT (10)
+#define MAX_OWNED_DEVICE (10)
+#define DATE_LENGTH (14)
+#define TAG "provisioningclient"
+
+static OicSecAcl_t *gAcl = NULL;
+static OicSecCrl_t *gCrl = NULL;
+static char PROV_TOOL_DB_FILE[] = "oic_svr_db_pt.json";
+static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
+static int gOwnershipState = 0;
+
+typedef enum
+{
+ ownershipDone = 1 << 1,
+ finalizeDone = 1 << 2,
+ provisionAclDone = 1 << 3,
+ provisionCert1Done = 1 << 4,
+ provisionCert2Done = 1 << 5,
+ provisionCrlDone = 1 << 6
+} StateManager;
+
+
+/**
+ * Perform cleanup for ACL
+ * @param[in] ACL
+ */
+static void deleteACL(OicSecAcl_t *acl)
+{
+ if (acl)
+ {
+ /* Clean Resources */
+ for (size_t i = 0; i < (acl)->resourcesLen; i++)
+ {
+ OICFree((acl)->resources[i]);
+ }
+ OICFree((acl)->resources);
+
+ /* Clean Owners */
+ OICFree((acl)->owners);
+
+ /* Clean ACL node itself */
+ OICFree((acl));
+
+ acl = NULL;
+ }
+}
+
+void deleteCrl(OicSecCrl_t *crl)
+{
+ if (crl)
+ {
+ //Clean ThisUpdate
+ OICFree(crl->ThisUpdate.data);
+
+ //clean CrlData
+ OICFree(crl->CrlData.data);
+
+ //Clean crl itself
+ OICFree(crl);
+ }
+}
+
+/**
+ * Calculate ACL permission from string to bit
+ *
+ * @param[in] temp_psm Input data of ACL permission string
+ * @param[in,out] pms The pointer of ACL permission value
+ * @return 0 on success otherwise -1.
+ */
+static int CalculateAclPermission(const char *temp_pms, uint16_t *pms)
+{
+ int i = 0;
+
+ if (NULL == temp_pms || NULL == pms)
+ {
+ return -1;
+ }
+ *pms = 0;
+ while (temp_pms[i] != '\0')
+ {
+ switch (temp_pms[i])
+ {
+ case 'C':
+ {
+ *pms += CREATE;
+ i++;
+ break;
+ }
+ case 'R':
+ {
+ *pms += READ;
+ i++;
+ break;
+ }
+ case 'U':
+ {
+ *pms += UPDATE;
+ i++;
+ break;
+ }
+ case 'D':
+ {
+ *pms += DELETE;
+ i++;
+ break;
+ }
+ case 'N':
+ {
+ *pms += NOTIFY;
+ i++;
+ break;
+ }
+ case '_':
+ {
+ i++;
+ break;
+ }
+ default:
+ {
+ return -1;
+ }
+ }
+ }
+ return 0;
+}
+
+/**
+ * Get the ACL property from user
+ *
+ * @param[in] ACL Datastructure to save user inputs
+ * @return 0 on success otherwise -1.
+ */
+static int InputACL(OicSecAcl_t *acl)
+{
+ int ret;
+ char temp_id [UUID_LENGTH + 4] = {0,};
+ char temp_rsc[MAX_URI_LENGTH + 1] = {0,};
+ char temp_pms[MAX_PERMISSION_LENGTH + 1] = {0,};
+ printf("******************************************************************************\n");
+ printf("-Set ACL policy for target device\n");
+ printf("******************************************************************************\n");
+ //Set Subject.
+ printf("-URN identifying the subject\n");
+ printf("ex) doorDeviceUUID00 (16 Numbers except to '-')\n");
+ printf("Subject : ");
+ char *ptr = NULL;
+ ret = scanf("%19ms", &ptr);
+ if(1==ret)
+ {
+ OICStrcpy(temp_id, sizeof(temp_id), ptr);
+ OICFree(ptr);
+ }
+ else
+ {
+ printf("Error while input\n");
+ return -1;
+ }
+ int j = 0;
+ for (int i = 0; temp_id[i] != '\0'; i++)
+ {
+ if (DASH != temp_id[i])
+ {
+ if(j>UUID_LENGTH)
+ {
+ printf("Invalid input\n");
+ return -1;
+ }
+ acl->subject.id[j++] = temp_id[i];
+ }
+ }
+
+ //Set Resource.
+ printf("Num. of Resource : \n");
+ ret = scanf("%zu", &acl->resourcesLen);
+ printf("-URI of resource\n");
+ printf("ex) /a/light (Max_URI_Length: 64 Byte )\n");
+ acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
+ if (NULL == acl->resources)
+ {
+ OC_LOG(ERROR, TAG, "Error while memory allocation");
+ return -1;
+ }
+ for (size_t i = 0; i < acl->resourcesLen; i++)
+ {
+ printf("[%zu]Resource : ", i + 1);
+ char *ptr_tempRsc = NULL;
+ ret = scanf("%64ms", &ptr_tempRsc);
+ if (1==ret)
+ {
+ OICStrcpy(temp_rsc, sizeof(temp_rsc), ptr_tempRsc);
+ OICFree(ptr_tempRsc);
+ }
+ else
+ {
+ printf("Error while input\n");
+ return -1;
+ }
+ acl->resources[i] = OICStrdup(temp_rsc);
+
+ if (NULL == acl->resources[i])
+ {
+ OC_LOG(ERROR, TAG, "Error while memory allocation");
+ return -1;
+ }
+ }
+ // Set Permission
+ do
+ {
+ printf("-Set the permission(C,R,U,D,N)\n");
+ printf("ex) CRUDN, CRU_N,..(5 Charaters)\n");
+ printf("Permission : ");
+ char *ptr_temp_pms = NULL;
+ ret = scanf("%5ms", &ptr_temp_pms);
+ if(1 == ret)
+ {
+ OICStrcpy(temp_pms, sizeof(temp_pms), ptr_temp_pms);
+ OICFree(ptr_temp_pms);
+
+ }
+ else
+ {
+ printf("Error while input\n");
+ return -1;
+ }
+ }
+ while (0 != CalculateAclPermission(temp_pms, &(acl->permission)) );
+ // Set Rowner
+ printf("Num. of Rowner : ");
+ ret = scanf("%zu", &acl->ownersLen);
+ printf("-URN identifying the rowner\n");
+ printf("ex) lightDeviceUUID0 (16 Numbers except to '-')\n");
+ acl->owners = (OicUuid_t *)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
+ if (NULL == acl->owners)
+ {
+ OC_LOG(ERROR, TAG, "Error while memory allocation");
+ return -1;
+ }
+ for (size_t i = 0; i < acl->ownersLen; i++)
+ {
+ printf("[%zu]Rowner : ", i + 1);
+ char *ptr_temp_id = NULL;
+ ret = scanf("%19ms", &ptr_temp_id);
+ if (1 == ret)
+ {
+ OICStrcpy(temp_id, sizeof(temp_id), ptr_temp_id);
+ OICFree(ptr_temp_id);
+ }
+ else
+ {
+ printf("Error while input\n");
+ return -1;
+ }
+ j = 0;
+ for (int k = 0; temp_id[k] != '\0'; k++)
+ {
+ if (DASH != temp_id[k])
+ {
+ acl->owners[i].id[j++] = temp_id[k];
+ }
+ }
+ }
+ return 0;
+}
+
+
+//FILE *client_fopen(const char *path, const char *mode)
+FILE *client_fopen(const char* UNUSED_PARAM , const char *mode)
+{
+ (void)UNUSED_PARAM;
+ return fopen(PROV_TOOL_DB_FILE, mode);
+}
+
+void PrintfResult(const char* procName, void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
+{
+ printf("-----------------------------------------------------------\n");
+ if(!hasError)
+ {
+ printf("%s was successfully done.\n", procName);
+ }
+ else
+ {
+ for(int i = 0; i < nOfRes; i++)
+ {
+ printf("UUID : ");
+ for(int j = 0; j < UUID_LENGTH; j++)
+ {
+ printf("%c", arr[i].deviceId.id[j]);
+ }
+ printf("\t");
+ printf("Result=%d\n", arr[i].res);
+ }
+ }
+
+ if(ctx)
+ {
+ printf("Context is %s\n", (char*)ctx);
+ }
+ printf("-----------------------------------------------------------\n");
+}
+
+void ProvisionCertCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
+{
+ if(!hasError)
+ {
+ gOwnershipState = 1;
+ PrintfResult("Provision Credential", ctx, nOfRes, arr, hasError);
+ }
+ else printf("Cert provisioning error\n-----------------------------------------");
+}
+
+void ProvisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
+{
+ if(!hasError)
+ {
+ gOwnershipState = 1;
+ PrintfResult("Provision ACL", ctx, nOfRes, arr, hasError);
+ }
+}
+
+void ProvisionCrlCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
+{
+ if(!hasError)
+ {
+ gOwnershipState = 1;
+ PrintfResult("Provision CRL", ctx, nOfRes, arr, hasError);
+ }
+}
+
+
+
+void OwnershipTransferCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
+{
+ if(!hasError)
+ {
+ gOwnershipState = 1;
+ PrintfResult("Ownership transfer", ctx, nOfRes, arr, hasError);
+ }
+}
+
+static short IsCKMInfoFileExists()
+{
+ FILE *ckmInf = fopen(CA_STORAGE_FILE, "r");
+ if (NULL != ckmInf)
+ {
+ fclose(ckmInf);
+ return 1;
+ }
+ return 0;
+}
+
+static PKIError InitCA()
+{
+ FUNCTION_INIT();
+
+ if (IsCKMInfoFileExists())
+ {
+ CHECK_CALL(InitCKMInfo);
+ }
+ else
+ {
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+ ByteArray CAPubKey = BYTE_ARRAY_INITIALIZER;
+ ByteArray CAPrivKey = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootCert = BYTE_ARRAY_INITIALIZER;
+
+
+ uint8_t rootCertData[ISSUER_MAX_CERT_SIZE];
+ uint8_t CAPubKeyData[PUBLIC_KEY_SIZE];
+ uint8_t CAPrivKeyData[PRIVATE_KEY_SIZE];
+ const char rootNameStr[] = "Sample_Root";
+
+ CAPubKey.data = CAPubKeyData;
+ CAPubKey.len = PUBLIC_KEY_SIZE;
+ CAPrivKey.data = CAPrivKeyData;
+ CAPrivKey.len = PRIVATE_KEY_SIZE;
+ rootCert.data = rootCertData;
+ rootCert.len = ISSUER_MAX_CERT_SIZE;
+ rootName.data = (uint8_t *)rootNameStr;
+ rootName.len = strlen(rootNameStr);
+
+ CHECK_CALL(SetRootName, rootName);
+ CHECK_CALL(GenerateCAKeyPair, &CAPrivKey, &CAPubKey);
+ CHECK_CALL(SetSerialNumber, 1);
+ CHECK_CALL(CKMIssueRootCertificate, NULL, NULL, &rootCert);
+ CHECK_CALL(SetCACertificate, &rootCert);
+ }
+
+ FUNCTION_CLEAR();
+}
+
+static int InputCRL(OicSecCrl_t *crlRes)
+{
+ FUNCTION_INIT(
+ ByteArray crl = BYTE_ARRAY_INITIALIZER;
+ );
+
+ const int MAX_Revoked_NUMBER = 9;
+ uint8_t uint8ThisUpdateTime[DATE_LENGTH] = "130101000005Z";
+ uint32_t revokedNumbers[MAX_Revoked_NUMBER];
+ const uint8_t* revocationDates[MAX_Revoked_NUMBER];
+ // const uint8_t revocationDatesContent[MAX_Revoked_NUMBER][DATE_LENGTH];
+ uint32_t nuberOfRevoked = 0;
+ printf("Enter number of Revoked certificates(1..%d)\n", MAX_Revoked_NUMBER);
+ scanf("%u", &nuberOfRevoked);
+
+ for (size_t i = 0; i < nuberOfRevoked; ++i)
+ {
+ printf("Revoked certificate %d:", i);
+ printf("Serial number (E. g.: 100):");
+ scanf("%u", &revokedNumbers[i]);
+ revocationDates[i] = (const uint8_t*)"130101000005Z";
+ }
+
+ crl.len = CRL_MIN_SIZE + nuberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)/* + 1000*/;
+ crl.data = (uint8_t *)OICCalloc(1, crl.len);
+
+ CHECK_CALL(CKMIssueCRL, uint8ThisUpdateTime, nuberOfRevoked, revokedNumbers,
+ revocationDates, &crl);
+ PRINT_BYTE_ARRAY("CRL:\n",crl);
+ CHECK_CALL(SetCertificateRevocationList, &crl);
+ crlRes->CrlData = crl;
+ crlRes->ThisUpdate.data = uint8ThisUpdateTime;
+ crlRes->ThisUpdate.len = DATE_LENGTH;
+ crlRes->CrlId = 1;
+
+
+ FUNCTION_CLEAR(
+ //OICFree(crl.data);
+ );
+}
+
+
+/**
+ * Provisioning client sample using ProvisioningAPI
+ */
+int main()
+{
+ OCStackResult res = OC_STACK_OK;
+
+ // Initialize Persistent Storage for SVR database
+ OCPersistentStorage ps = { .open = client_fopen,
+ .read = fread,
+ .write = fwrite,
+ .close = fclose,
+ .unlink = unlink};
+
+ OCRegisterPersistentStorageHandler(&ps);
+
+ if (OC_STACK_OK != OCInit(NULL, 0, OC_CLIENT_SERVER))
+ {
+ OC_LOG(ERROR, TAG, "OCStack init error");
+ goto error;
+ }
+ if(OC_STACK_OK != OCInitPM(PRVN_DB_FILE_NAME))
+ {
+ OC_LOG(ERROR, TAG, "OC_PM init error");
+ goto error;
+ }
+
+ OCProvisionDev_t* pDeviceList = NULL;
+ res = OCDiscoverUnownedDevices(PREDEFINED_TIMEOUT, &pDeviceList);
+ if(OC_STACK_OK != res)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed to PMDeviceDiscovery : %d", res);
+ goto error;
+ }
+
+ OCProvisionDev_t* pCurDev = pDeviceList;
+ int i;
+ while(pCurDev !=NULL)
+ {
+ for(i = 0; i < UUID_LENGTH; i++)
+ {
+ printf("%c", pCurDev->doxm->deviceID.id[i]);
+ }
+ printf("\n");
+ pCurDev = pCurDev->next;
+ }
+
+ //Register callback function to each OxM
+ OTMCallbackData_t justWorksCBData = {.loadSecretCB=NULL,
+ .createSecureSessionCB=NULL,
+ .createSelectOxmPayloadCB=NULL,
+ .createOwnerTransferPayloadCB=NULL};
+ justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback;
+ justWorksCBData.createSecureSessionCB = CreateSecureSessionJustWorksCallback;
+ justWorksCBData.createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload;
+ justWorksCBData.createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload;
+ OTMSetOwnershipTransferCallbackData(OIC_JUST_WORKS, &justWorksCBData);
+
+ char* myContext = "OTM Context";
+ //Perform ownership transfer
+ res = OCDoOwnershipTransfer((void*)myContext, pDeviceList, OwnershipTransferCB);
+ if(OC_STACK_OK == res)
+ {
+ OC_LOG(INFO, TAG, "Request for ownership transfer is sent successfully.");
+ }
+ else
+ {
+ OC_LOG_V(ERROR, TAG, "Failed to OCDoOwnershipTransfer : %d", res);
+ }
+
+ gOwnershipState = 0;
+ while (gOwnershipState == 0)
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ goto error;
+ }
+ sleep(1);
+ }
+
+// Credential & ACL provisioning between two devices.
+
+ OCProvisionDev_t *pOwnedList = NULL;
+ OCProvisionDev_t *pOwnedDevices [MAX_OWNED_DEVICE] = {0,};
+ int nOwnedDevice = 0;
+
+ res = OCDiscoverOwnedDevices(PREDEFINED_TIMEOUT, &pOwnedList);
+ if (OC_STACK_OK == res)
+ {
+ printf("################## Owned Device List #######################\n");
+ while (pOwnedList != NULL)
+ {
+ nOwnedDevice ++;
+ printf(" %d : ", nOwnedDevice);
+ for (int i = 0; i < UUID_LENGTH; i++)
+ {
+ printf("%c", pOwnedList->doxm->deviceID.id[i]);
+ }
+ printf("\n");
+ pOwnedDevices[nOwnedDevice] = pOwnedList;
+ pOwnedList = pOwnedList->next;
+ }
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, "Error while Owned Device Discovery");
+ }
+
+ int Device1 = 0;
+ int Device2 = 0;
+
+ printf("Select 2 devices for Credential & ACL provisioning\n");
+ printf("Device 1: ");
+ scanf("%d", &Device1);
+ printf("Device 2: ");
+ scanf("%d", &Device2);
+
+
+ gAcl = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
+ if (NULL == gAcl)
+ {
+ OC_LOG(ERROR, TAG, "Error while memory allocation");
+ goto error;
+ }
+
+ if (PKI_SUCCESS != InitCA())
+ {
+ OC_LOG(ERROR, TAG, "CA init error");
+ goto error;
+ }
+
+
+ char *ctx = "DUMMY";
+
+ res = OCProvisionCredentials(ctx, SIGNED_ASYMMETRIC_KEY, 0, pOwnedDevices[Device1],
+ NULL, ProvisionCertCB);
+ if (OC_STACK_OK != res) OC_LOG_V(ERROR, TAG, "Failed to provision Device 1 : %d", res);
+ gOwnershipState = 0;
+ while ( gOwnershipState == 0 )
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ goto error;
+ }
+ sleep(1);
+ }
+
+ res = OCProvisionCredentials(ctx, SIGNED_ASYMMETRIC_KEY, 0, pOwnedDevices[Device2],
+ NULL, ProvisionCertCB);
+ if (OC_STACK_OK != res)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed to provision Device 2 : %d", res);
+ }
+
+ gOwnershipState = 0;
+ while (gOwnershipState == 0)
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ goto error;
+ }
+ sleep(1);
+ }
+
+ printf("Input ACL for Device2\n");
+ if (0 == InputACL(gAcl))
+ {
+ printf("Success Input ACL\n");
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, "InputACL error");
+ goto error;
+ }
+ res = OCProvisionACL(ctx, pOwnedDevices[Device2], gAcl, &ProvisionAclCB);
+ if (OC_STACK_OK != res)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed to ACL provision Device 2 : %d", res);
+ }
+
+ gOwnershipState = 0;
+ while (gOwnershipState == 0)
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ goto error;
+ }
+ sleep(1);
+ }
+ gCrl = (OicSecCrl_t *)OICMalloc(sizeof(OicSecCrl_t));
+ if (PKI_SUCCESS != InputCRL(gCrl))
+ {
+ OC_LOG(ERROR, TAG, "CA init error");
+ goto error;
+ }
+
+ PRINT_BYTE_ARRAY("gCrl = \n", gCrl->CrlData);
+
+ res = OCProvisionCRL(ctx, pOwnedDevices[Device2], gCrl, &ProvisionCrlCB);
+ if (OC_STACK_OK != res) OC_LOG_V(ERROR, TAG, "Failed to CRL provision Device 2 : %d", res);
+
+ gOwnershipState = 0;
+ while (gOwnershipState == 0)
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ goto error;
+ }
+ sleep(1);
+ }
+
+ if (OCStop() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ goto error;
+ }
+
+error:
+ deleteACL(gAcl);
+ OCDeleteDiscoveredDevices(pDeviceList);
+ OCDeleteDiscoveredDevices(pOwnedList);
+
+ return 0;
+}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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
+ *
+ * LICENSE-2.0" target="_blank">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 <iostream>
+#include <string.h>
+#include <oic_malloc.h>
+#include <gtest/gtest.h>
+#include "ocstack.h"
+
+#include "cert_generator.h"
+#include "ck_manager.h"
+#include "pki.h"
+#include "sn_store.h"
+#include "der_dec.h"
+#include "crl.h"
+#include "crl_generator.h"
+#include "crlresource.h"
+#include "ckm_info.h"
+
+
+#define RUNS 1
+#define MAX_LEN 1000
+#define TEST_SN 50
+#define READ_WRITE_BLOCK_N 1ul
+#define N_LENGTH_BYTES 3
+
+const char *CKMI_JSON_FILE_NAME = "CKMInfo.json";
+
+#define CRL_DEFAULT_CRL_ID 1
+#define CRL_DEFAULT_THIS_UPDATE "150101000000Z"
+#define CRL_DEFAULT_CRL_DATA "-"
+
+#define NUMBER_OF_REVOKED 2
+
+OCPersistentStorage ps = { NULL, NULL, NULL, NULL, NULL};
+
+//#define NUM_ACE_FOR_WILDCARD_IN_CKM1_JSON (2)
+
+FILE* ckm_fopen(const char * /*path*/, const char *mode)
+{
+ return fopen(CKMI_JSON_FILE_NAME, mode);
+}
+
+void SetPersistentHandler(OCPersistentStorage *ps)
+{
+ if(ps)
+ {
+ ps->open = ckm_fopen;
+ ps->read = fread;
+ ps->write = fwrite;
+ ps->close = fclose;
+ ps->unlink = unlink;
+ }
+}
+
+// Length of test certificate
+#define SIMPLE_CRT_LEN 469
+
+class PKITest : public ::testing::Test
+{
+public:
+ static void SetUpTestCase()
+ {
+ SetPersistentHandler(&ps);
+ OCStackResult res = OCRegisterPersistentStorageHandler(&ps);
+ ASSERT_TRUE(res == OC_STACK_OK);
+ }
+
+ static void TearDownTestCase()
+ {
+ }
+
+ static CertificateX509 g_certificate;
+
+ static const ByteArray g_caPublicKey;
+
+ static const ByteArray g_derCode ;
+
+ static ByteArray g_serNum;
+};
+
+CertificateX509 PKITest::g_certificate;
+
+const ByteArray PKITest::g_derCode = {(uint8_t[])
+ {
+ 0x30, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00,
+ 0xd7, 0x56, 0x8c, 0xfc, 0x53, 0x18, 0xb0, 0xab, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce,
+ 0x3d, 0x04, 0x03, 0x02, 0x30, 0x45, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13,
+ 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f,
+ 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04,
+ 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67,
+ 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x30, 0x1e, 0x17, 0x0d, 0x31,
+ 0x35, 0x30, 0x33, 0x31, 0x32, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x17, 0x0d, 0x31, 0x37,
+ 0x30, 0x33, 0x31, 0x31, 0x31, 0x32, 0x32, 0x35, 0x31, 0x31, 0x5a, 0x30, 0x45, 0x31, 0x0b, 0x30,
+ 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x41, 0x55, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03,
+ 0x55, 0x04, 0x08, 0x0c, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, 0x31,
+ 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x0c, 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e,
+ 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c,
+ 0x74, 0x64, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06,
+ 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x8c, 0xc8, 0x92,
+ 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f, 0x1a, 0x09, 0xc5,
+ 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3, 0x75, 0x5c, 0xdd,
+ 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36, 0x8f, 0xc5, 0x7b,
+ 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1, 0xa3, 0x50, 0x30,
+ 0x4e, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x5c, 0x0e, 0x30, 0xa8,
+ 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a, 0x59,
+ 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, 0x5c, 0x0e, 0x30,
+ 0xa8, 0x8e, 0x7f, 0xc9, 0x02, 0xcd, 0xa8, 0xed, 0x0d, 0x1a, 0x1b, 0xd9, 0x7d, 0xe6, 0xce, 0x2a,
+ 0x59, 0x30, 0x0c, 0x06, 0x03, 0x55, 0x1d, 0x13, 0x04, 0x05, 0x30, 0x03, 0x01, 0x01, 0xff, 0x30,
+ 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, 0x03, 0x48, 0x00, 0x30, 0x45,
+ 0x02, 0x21, 0x00, 0xf6, 0x79, 0xed, 0x69, 0xd5, 0xe5, 0xba, 0x42, 0x14, 0xfc, 0xce, 0x47, 0xf1,
+ 0x61, 0x1c, 0x51, 0x11, 0x2b, 0xba, 0x04, 0x70, 0x56, 0x78, 0xaf, 0xa9, 0xa6, 0x98, 0x8f, 0x4b,
+ 0xa8, 0x11, 0x67, 0x02, 0x20, 0x3a, 0xdf, 0xf1, 0x74, 0xc9, 0x2f, 0xfb, 0x84, 0x46, 0xde, 0xbc,
+ 0x2d, 0xda, 0xe3, 0x05, 0xb4, 0x81, 0x31, 0x45, 0xf7, 0x3d, 0x71, 0x46, 0x07, 0xa7, 0xd8, 0xcb,
+ 0xae, 0x1e, 0x1b, 0x1c, 0x5a
+ }, SIMPLE_CRT_LEN };
+
+
+const ByteArray PKITest::g_caPublicKey = {(uint8_t[])
+{
+ 0x8c, 0xc8, 0x92, 0x1d, 0xaa, 0x7f, 0xf0, 0xe4, 0xb2, 0x75, 0xd6, 0x4a, 0xf1, 0xd5, 0x14, 0x3f,
+ 0x1a, 0x09, 0xc5, 0x3e, 0x52, 0xd6, 0xda, 0xa0, 0xbf, 0x90, 0x43, 0xd1, 0x6b, 0xfe, 0xd1, 0xb3,
+ 0x75, 0x5c, 0xdd, 0x69, 0xac, 0x42, 0xa1, 0xcb, 0x03, 0x16, 0xee, 0xa4, 0x30, 0xa5, 0x8d, 0x36,
+ 0x8f, 0xc5, 0x7b, 0xb4, 0xb5, 0x6a, 0x7d, 0x9b, 0x16, 0x04, 0x46, 0xab, 0xae, 0xbb, 0x56, 0xa1
+}, PUBLIC_KEY_SIZE };
+
+
+ByteArray PKITest::g_serNum = {(uint8_t[SERIAL_NUMBER_MAX_LEN]) {0}, SERIAL_NUMBER_MAX_LEN};
+
+//registering persistent storage test
+TEST(CKManager, RegisterPersistentStorage)
+{
+ SetPersistentHandler(&ps);
+ ASSERT_EQ(OC_STACK_OK, OCRegisterPersistentStorageHandler(&ps));
+}
+
+//check decoding predefined certificate
+TEST(X509Certificate, DecodeTest)
+{
+ ByteArray code = PKITest::g_derCode;
+
+ ASSERT_EQ(DecodeCertificate(code, &PKITest::g_certificate), PKI_SUCCESS);
+ code.data = NULL;
+ ASSERT_NE(DecodeCertificate(code, &PKITest::g_certificate), PKI_SUCCESS);
+}
+
+//check decoding of random symbols sequence
+TEST(X509Certificate, RandomDecode)
+{
+ srand((unsigned int)time(NULL));
+
+ ByteArray code;
+ INIT_BYTE_ARRAY(code);
+
+ for (unsigned int i = 0; i < RUNS; i++)
+ {
+ code.len = rand() % MAX_LEN;
+ code.data = (uint8_t *)malloc(code.len * sizeof(uint8_t));
+
+ EXPECT_NE(code.data, (uint8_t *)NULL);
+
+ for (unsigned int j = 0; j < code.len; j++)
+ {
+ code.data[j] = (uint8_t)(rand() % 128 + 1);
+ }
+
+ EXPECT_NE(PKI_SUCCESS, DecodeCertificate(code, &PKITest::g_certificate));
+
+ free(code.data);
+ }
+}
+//testing validity check of predefined certificate
+TEST(X509Certificate, testCheckValidity)
+{
+ CertificateX509 tempCrt;
+ ASSERT_EQ(PKI_SUCCESS, DecodeCertificate(PKITest::g_derCode, &tempCrt));
+ ASSERT_EQ(PKI_SUCCESS, CheckValidity(tempCrt.validFrom, tempCrt.validTo));
+ ByteArray temp = tempCrt.validTo;
+
+ tempCrt.validTo = tempCrt.validFrom;
+ tempCrt.validFrom = temp;
+ ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckValidity(tempCrt.validFrom, tempCrt.validTo));
+}
+
+//testing signature check of predefined certificate
+TEST(X509Certificate, CheckSignature)
+{
+ ByteArray code = PKITest::g_derCode;
+
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(code, PKITest::g_caPublicKey));
+ code.data = NULL;
+ ASSERT_NE(PKI_SUCCESS, CheckCertificate(code, PKITest::g_caPublicKey));
+}
+
+//test saving certificate into file
+TEST_F(PKITest, DERCertificateFile)
+{
+ uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ ByteArray certDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ certDer.data = derData;
+ certDer.len = ISSUER_MAX_CERT_SIZE;
+
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = sizeof(caPubKey);
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = sizeof(caPrivKey);
+ rootName.data = (uint8_t *)"ROOT1";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+
+ for (int i = 1; i <= RUNS; i++)
+ {
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss));
+ ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i));
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer));
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ ASSERT_EQ(PKI_SUCCESS, GenerateDERCertificateFile (&certDer, "der_cert"));
+ }
+ ASSERT_EQ(CloseCKMInfo(), PKI_SUCCESS);
+}
+
+//test checking time validity of generated certificate
+TEST_F(PKITest, TimeValidity)
+{
+ uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ ByteArray certDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKey = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKey = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ privKey.data = caPrivKey;
+ privKey.len = sizeof(caPrivKey);
+
+ certDer.data = derData;
+ certDer.len = sizeof(derData);
+
+ pubKey.data = caPubKey;
+ pubKey.len = sizeof(caPubKey);
+
+ rootName.data = (uint8_t *)"ROOT3";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+
+ for (int i = 1; i <= RUNS; i++)
+ {
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKey, &pubKey));
+ ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i));
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer));
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKey));
+
+ certDer.len = sizeof(derData);
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, (uint8_t *)"130101000000Z", &certDer));
+ ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckCertificate(certDer, pubKey));
+
+ certDer.len = sizeof(derData);
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate((uint8_t *)"160101000000Z", 0, &certDer));
+ ASSERT_EQ(PKI_CERT_DATE_INVALID, CheckCertificate(certDer, pubKey));
+ }
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//testing certificate generation by certificate signing request
+TEST_F(PKITest, CertificateSigningRequest)
+{
+ uint8_t certData[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t csrData[CSR_MAX_SIZE] = {0};
+ uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+ uint8_t *subjName = (uint8_t *)"Subject05";
+
+ ByteArray certDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray csrDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ certDer.data = certData;
+ certDer.len = sizeof(certData);
+ csrDer.data = csrData;
+ csrDer.len = CSR_MAX_SIZE;
+
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = sizeof(caPubKey);
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = sizeof(caPrivKey);
+ pubKeySubj.data = subjPubKey;
+ pubKeySubj.len = sizeof(subjPubKey);
+ privKeySubj.data = subjPrivKey;
+ privKeySubj.len = sizeof(subjPrivKey);
+ rootName.data = (uint8_t *)"ROOT2";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+
+ ASSERT_EQ(GenerateCAKeyPair(&privKeyIss, &pubKeyIss), PKI_SUCCESS);
+ ASSERT_EQ(SetSerialNumber(1), PKI_SUCCESS);
+ ASSERT_EQ(SetRootName(rootName), PKI_SUCCESS);
+
+ for (int i = 1; i <= RUNS; i++)
+ {
+ ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeySubj, &pubKeySubj));
+ ASSERT_EQ(PKI_SUCCESS, GenerateCSR(subjName, subjPubKey, subjPrivKey, &csrDer));
+ ASSERT_EQ(PKI_SUCCESS, GenerateCertificateByCSR(&csrDer, &certDer));
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ certDer.data[0]++;
+ ASSERT_NE(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ certDer.data[0]--;
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ }
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//test public key structure parsing
+TEST(X509Certificate, testParsePublicKey)
+{
+ ASSERT_EQ(PKI_SUCCESS, ParsePublicKey((ByteArray*)&PKITest::g_caPublicKey));
+
+ size_t length = 3;
+ uint8_t shortAr[length];
+ ByteArray shortArray = {shortAr, length};
+ ASSERT_EQ(PKI_WRONG_ARRAY_LEN, ParsePublicKey(&shortArray));
+
+ uint8_t uncompressed[PUBLIC_KEY_SIZE + 2];
+ uncompressed[0] = 0;
+ uncompressed[1] = ASN1_UNCOMPRESSED_KEY;
+ memcpy(&uncompressed[2], PKITest::g_caPublicKey.data, PUBLIC_KEY_SIZE);
+ ByteArray uncomprArr = {uncompressed, PUBLIC_KEY_SIZE+2};
+ ParsePublicKey(&uncomprArr);
+ ASSERT_EQ((size_t)PUBLIC_KEY_SIZE, uncomprArr.len);
+ ASSERT_EQ(0, memcmp(uncomprArr.data, PKITest::g_caPublicKey.data, PUBLIC_KEY_SIZE));
+}
+
+//test checking of certificate generated by OpenSSL
+TEST(OpenSSLCompatibility, verifyOpenSslCertSign)
+{
+ ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
+ CertificateX509 certificate;
+
+ FILE *fileCert = fopen("01.der", "rb");
+ ASSERT_TRUE(fileCert != NULL);
+
+ //get the length
+ fseek(fileCert, 0, SEEK_END);
+ crtDer.len = ftell(fileCert);
+ fseek(fileCert, 0, SEEK_SET);
+ //allocate memory
+ crtDer.data = (uint8_t*)malloc(crtDer.len+1);
+ //read the content
+ EXPECT_EQ(READ_WRITE_BLOCK_N, fread(crtDer.data, crtDer.len, READ_WRITE_BLOCK_N, fileCert));
+ fclose(fileCert);
+
+ ByteArray pubKey = BYTE_ARRAY_INITIALIZER;
+ FILE * fileKey = fopen("capub.der", "rb");
+ ASSERT_TRUE(fileKey != NULL);
+ fseek(fileKey, 0, SEEK_END);
+ pubKey.len = ftell(fileKey);
+ fseek(fileKey, 0, SEEK_SET);
+ //openssl generates a public key that is longer than 64 bytes
+ //with additional 27 bytes prepending the actual key
+ if(pubKey.len > PUBLIC_KEY_SIZE){
+ fseek(fileKey, (pubKey.len - PUBLIC_KEY_SIZE), SEEK_SET);
+ pubKey.len = PUBLIC_KEY_SIZE;
+ }
+ pubKey.data = (uint8_t*)malloc(pubKey.len+1);
+ //read the content
+ EXPECT_EQ(READ_WRITE_BLOCK_N, fread(pubKey.data, pubKey.len, READ_WRITE_BLOCK_N, fileKey));
+ fclose(fileKey);
+
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtDer, &certificate));
+ EXPECT_EQ(PKI_SUCCESS, CheckCertificate(crtDer, pubKey));
+
+ free(crtDer.data);
+ free(pubKey.data);
+}
+
+//test parsing of certificate chain generated by OpenSSL
+TEST(CertificateChain, LoadCertificateChain)
+{
+ ByteArray crtChainDer[MAX_CHAIN_LEN] = {{0,0},};
+ CertificateX509 crtChain[MAX_CHAIN_LEN] = {{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}},};
+ ByteArray msg = BYTE_ARRAY_INITIALIZER;
+ uint8_t chainLength;
+
+ FILE *file = fopen("cert_chain.dat", "rb");
+
+ ASSERT_TRUE(file != NULL);
+
+ while (!feof (file))
+ {
+ msg.data = (uint8_t *) realloc (msg.data, msg.len + 1);
+ msg.data[msg.len] = fgetc (file);
+ msg.len++;
+ }
+ msg.len--;
+ fclose (file);
+ INC_BYTE_ARRAY(msg, 3);
+ EXPECT_EQ(PKI_SUCCESS, LoadCertificateChain (msg, crtChainDer, &chainLength));
+#ifdef X509_DEBUG
+ printf("chain len: %d\n", chainLength);
+#endif
+ EXPECT_EQ(PKI_UNKNOWN_OID, ParseCertificateChain (crtChainDer, crtChain, chainLength));
+
+ free(msg.data - 3);
+}
+
+//test checking CA certificate generated by OpenSSL
+TEST(OpenSSLCompatibility, testOpenSSLCertificate)
+{
+ ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
+ FILE *fileCert = fopen("cacert.der", "rb");
+ ASSERT_TRUE(fileCert != NULL);
+
+ //get the length
+ fseek(fileCert, 0, SEEK_END);
+ crtDer.len = ftell(fileCert);
+ fseek(fileCert, 0, SEEK_SET);
+ //allocate memory
+ crtDer.data = (uint8_t*)malloc(crtDer.len+1);
+ //read the content
+ EXPECT_EQ(READ_WRITE_BLOCK_N, fread(crtDer.data, crtDer.len, READ_WRITE_BLOCK_N, fileCert));
+
+ fclose(fileCert);
+ #ifdef X509_DEBUG
+ printf("Length of cert: %lu\n", crtDer.len);
+ #endif
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtDer, &PKITest::g_certificate));
+ free(crtDer.data);
+}
+
+//test signatures checking of certificate chain generated by OpenSSL
+TEST(OpenSSLCompatibility, ParseAndCheckCertificateChain)
+{
+ ByteArray crtChainDer[MAX_CHAIN_LEN] = {{0,0},};
+ CertificateX509 crtChain[MAX_CHAIN_LEN] = {{{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0}},};
+ ByteArray msg = BYTE_ARRAY_INITIALIZER;
+ uint8_t chainLength;
+
+ const char* chainPath = {"chain.der"};
+ FILE *fileChain = fopen(chainPath, "rb");
+ ASSERT_TRUE(fileChain != NULL);
+
+ //get the length
+ fseek(fileChain, 0, SEEK_END);
+ msg.len = ftell(fileChain);
+ fseek(fileChain, 0, SEEK_SET);
+ //allocate memory
+ msg.data = (uint8_t*)malloc(msg.len+1);
+ //read the content
+ EXPECT_EQ(READ_WRITE_BLOCK_N, fread(msg.data, msg.len, READ_WRITE_BLOCK_N, fileChain));
+
+ fclose (fileChain);
+
+ INC_BYTE_ARRAY(msg, 3);
+ EXPECT_EQ(PKI_SUCCESS, LoadCertificateChain(msg, crtChainDer, &chainLength));
+ EXPECT_EQ(3, chainLength);
+ #ifdef X509_DEBUG
+ printf("Length of the chain: %d\n", chainLength);
+ #endif
+
+ EXPECT_EQ(PKI_SUCCESS, ParseCertificateChain(crtChainDer, crtChain, chainLength));
+
+ ByteArray caPubKey = BYTE_ARRAY_INITIALIZER;
+
+ const char* caPubKeyPath = {"capub.der"};
+ FILE *fileCaPubKey = fopen(caPubKeyPath, "rb");
+ ASSERT_TRUE(fileCaPubKey != NULL);
+
+ fseek(fileCaPubKey, 0, SEEK_END);
+ caPubKey.len = ftell(fileCaPubKey);
+ fseek(fileCaPubKey, 0, SEEK_SET);
+ if(caPubKey.len > PUBLIC_KEY_SIZE){
+ fseek(fileCaPubKey, (caPubKey.len - PUBLIC_KEY_SIZE), SEEK_SET);
+ caPubKey.len = PUBLIC_KEY_SIZE;
+ }
+ caPubKey.data = (uint8_t*)malloc(caPubKey.len+1);
+ //read the content
+ EXPECT_EQ(READ_WRITE_BLOCK_N, fread(caPubKey.data, caPubKey.len, READ_WRITE_BLOCK_N, fileCaPubKey));
+ fclose(fileCaPubKey);
+
+ EXPECT_EQ(PKI_SUCCESS, CheckCertificateChain(crtChain, chainLength, caPubKey));
+
+ free(msg.data - 3);
+ free(caPubKey.data);
+}
+
+//testing correctness of decoding certificate length from ASN.1 structure
+TEST(CRL, testDecodeLength)
+{
+ ByteArray cert = BYTE_ARRAY_INITIALIZER;
+ size_t length(0);
+ EXPECT_EQ(PKI_NULL_PASSED, DecodeLength(&cert, &length));
+
+ //a simple DER
+ size_t derLength = (size_t)rand() % LEN_LONG;
+ cert.len = derLength + 2;
+ uint8_t *certData = (uint8_t*)malloc(cert.len);
+ cert.data = certData;
+ cert.data[0] = (uint8_t)0x30; //mixed types
+ cert.data[1] = (uint8_t)(derLength & 0xff);
+ EXPECT_EQ(PKI_SUCCESS, DecodeLength(&cert, &length));
+ EXPECT_EQ(derLength, length);
+ free(certData);
+}
+
+//testing serial number storage
+TEST(CRL, StoreSerialNumber)
+{
+ uint8_t data[10] = {0x01, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03};
+ const ByteArray sn = { data, sizeof(data) / sizeof(uint8_t)};
+ int i;
+ for (i = 0; i < 400; i++)
+ {
+ sn.data[0] = i % 20;
+ ASSERT_EQ(PKI_SUCCESS, StoreSerialNumber(sn));
+ }
+ ASSERT_EQ(PKI_CERT_REVOKED, CheckSerialNumber(sn));
+
+ sn.data[1] = 0x01;
+ ASSERT_EQ(PKI_SUCCESS, CheckSerialNumber(sn));
+
+ FreeSNStore();
+}
+#ifdef ARDUINO_MEMORY_DEBUG
+//testing memory allocation fault handling at Arduino
+TEST(SNStore, MemoryOverflow)
+{
+ uint8_t data[10] = {0x01, 0x82, 0x01, 0xd1, 0x30, 0x82, 0x01, 0x77, 0xa0, 0x03};
+ const ByteArray sn = { data, sizeof(data) / sizeof(uint8_t)};
+ int i;
+ PKIError res;
+ do
+ {
+ res = StoreSerialNumber(sn);
+ }
+ while (res == PKI_SUCCESS);
+ ASSERT_EQ(PKI_MEMORY_ALLOC_FAILED, res);
+
+ FreeSNStore();
+}
+#endif /* ARDUINO_MEMORY_DEBUG */
+
+//testing next certificate serial number handling by "CKM info" unit
+TEST_F(PKITest, CAInitAndSerialNum)
+{
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ long serialNum = rand() % (MAX_LEN - 1) + 1;
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ //all the serials should start from
+ ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(serialNum));
+ long nextSerial;
+ ASSERT_EQ(PKI_SUCCESS, GetNextSerialNumber(&nextSerial));
+ ASSERT_EQ(nextSerial, serialNum);
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//testing CA name handling by "CKM info" unit
+TEST_F(PKITest, testCAName)
+{
+ ByteArray caName = BYTE_ARRAY_INITIALIZER;
+ caName.len = ((size_t)rand() % (ISSUER_MAX_NAME_SIZE - 1) + 1);
+ caName.data = (uint8_t*)malloc(caName.len);
+ size_t i;
+ for(i = 0; i < caName.len; i++){
+ caName.data[i] = (uint8_t)(rand() % 128);
+ }
+ EXPECT_EQ(PKI_SUCCESS, InitCKMInfo());
+ EXPECT_EQ(PKI_SUCCESS, SetRootName(caName));
+ ByteArray getName = BYTE_ARRAY_INITIALIZER;
+ uint8_t uint8CAName[ISSUER_MAX_NAME_SIZE] = {0};
+ getName.data = uint8CAName;
+ getName.len = ISSUER_MAX_NAME_SIZE;
+ EXPECT_EQ(PKI_SUCCESS, GetCAName(&getName));
+ EXPECT_EQ(0, memcmp(caName.data, getName.data, caName.len));
+ free(caName.data);
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//testing key pair generation and storing by "CKM info" unit
+TEST_F(PKITest, testKeyPair)
+{
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+ rootName.data = (uint8_t *)"ROOT";
+ rootName.len = strlen((char *)rootName.data);
+ SetRootName(rootName);
+
+ //first test the GenerateCAKeyPair - this writes to the CA storage
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ privKeyIss.len = PRIVATE_KEY_SIZE;
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+ privKeyIss.data = caPrivKey;
+
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ pubKeyIss.len = PUBLIC_KEY_SIZE;
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ pubKeyIss.data = caPubKey;
+
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss));
+
+ ByteArray keyCheck = BYTE_ARRAY_INITIALIZER;
+ keyCheck.len = PUBLIC_KEY_SIZE;
+ uint8_t keyCheckData[PUBLIC_KEY_SIZE] = {0};
+ keyCheck.data = keyCheckData;
+ ASSERT_EQ(PKI_SUCCESS, GetCAPrivateKey(&keyCheck));
+ ASSERT_EQ(0, memcmp(keyCheck.data, privKeyIss.data, PRIVATE_KEY_SIZE));
+
+ ASSERT_EQ(PKI_SUCCESS, GetCAPublicKey(&keyCheck));
+ ASSERT_EQ(0, memcmp(keyCheck.data, pubKeyIss.data, PUBLIC_KEY_SIZE));
+
+ //now test the GenerateKeyPair - does not write to the CA storage
+ ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeyIss, &pubKeyIss));
+
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ ASSERT_EQ(PKI_SUCCESS, GetCAPrivateKey(&keyCheck));
+ ASSERT_NE(0, memcmp(keyCheck.data, privKeyIss.data, PRIVATE_KEY_SIZE));
+
+ ASSERT_EQ(PKI_SUCCESS, GetCAPublicKey(&keyCheck));
+ ASSERT_NE(0, memcmp(keyCheck.data, pubKeyIss.data, PUBLIC_KEY_SIZE));
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//testing CRL encoding
+TEST_F(PKITest, testEncodeCRL)
+{
+ CertificateList crl;
+
+ uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z";
+ uint32_t numberOfRevoked = 0;
+ uint32_t revokedNumbers[2];
+ const uint8_t *revocationDates[2];
+
+ ByteArray code = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = PUBLIC_KEY_SIZE;
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = PRIVATE_KEY_SIZE;
+
+ numberOfRevoked = 2;
+
+ revokedNumbers[0] = 100; // serial number of first revoked certificate
+ revokedNumbers[1] = 200; // serial number of second revoked certificate
+ revocationDates[0] = (const uint8_t *)"130101000001Z";
+ revocationDates[1] = (const uint8_t *)"130101000002Z";
+
+ rootName.data = (uint8_t *)"ROOT2";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss));
+
+ code.data = (uint8_t *)calloc(1,
+ (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)));
+ code.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4));
+
+ EXPECT_EQ(PKI_SUCCESS,CKMIssueCRL(uint8ThisUpdateTime, numberOfRevoked, revokedNumbers,
+ revocationDates,&code));
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (code, &crl, pubKeyIss));
+#ifdef X509_DEBUG
+ PrintSNStore();
+ PrintCRL(&crl);
+#endif
+
+ FreeSNStore();
+ free(code.data);
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//check correctness of certificate revocation by CKMIssueCRL() and CKMRevocateCertificate()
+TEST_F(PKITest, testRevocateCertificate)
+{
+ CertificateList crl;
+
+ uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z";
+ uint32_t numberOfRevoked = 0;
+ uint32_t revokedNumbers[2];
+ const uint8_t *revocationDates[2];
+
+ ByteArray code = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = sizeof(caPubKey);
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = sizeof(caPrivKey);
+
+ numberOfRevoked = 2;
+
+ revokedNumbers[0] = 100; // serial number of first revoked certificate
+ revokedNumbers[1] = 200; // serial number of second revoked certificate
+ revocationDates[0] = (const uint8_t *)"130101000001Z";
+ revocationDates[1] = (const uint8_t *)"130101000002Z";
+
+ rootName.data = (uint8_t *)"ROOT2";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss));
+
+ code.len = CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4);
+ code.data = (uint8_t *)calloc(1, code.len);
+
+ EXPECT_EQ(PKI_SUCCESS, CKMIssueCRL (uint8ThisUpdateTime, numberOfRevoked, revokedNumbers,
+ revocationDates, &code));
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (code, &crl, pubKeyIss));
+ free(code.data);
+ numberOfRevoked++;
+ code.len = CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4);
+ code.data = (uint8_t *)calloc(1, code.len);
+ EXPECT_EQ(PKI_SUCCESS, CKMRevocateCertificate (uint8ThisUpdateTime, 50, &code));
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (code, &crl, pubKeyIss));
+#ifdef X509_DEBUG
+ PrintSNStore();
+ PrintCRL(&crl);
+#endif
+
+ FreeSNStore();
+ free(code.data);
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//checck correctness of saving root certificate to binary file
+TEST_F(PKITest, StoreCKMInfo)
+{
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+ uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+ const long serNum = 48598490;
+ CertificateList crl;
+ uint8_t *uint8ThisUpdateTime = (uint8_t *)"130101000000Z";
+ uint32_t numberOfRevoked = 0;
+ uint32_t revokedNumbers[2];
+ const uint8_t *revocationDates[2];
+
+ ByteArray certDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+ ByteArray code = BYTE_ARRAY_INITIALIZER;
+
+ certDer.data = derData;
+ certDer.len = ISSUER_MAX_CERT_SIZE;
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = PUBLIC_KEY_SIZE;
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = PRIVATE_KEY_SIZE;
+ rootName.data = (uint8_t *)"ROOT";
+ rootName.len = strlen((char *)rootName.data);
+
+ //generate CA Certificate
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss));
+ ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(serNum));
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer));
+
+ //generate CRL
+ numberOfRevoked = NUMBER_OF_REVOKED;
+
+ revokedNumbers[0] = 100; // serial number of first revoked certificate
+ revokedNumbers[1] = 200; // serial number of second revoked certificate
+ revocationDates[0] = (const uint8_t *)"130101000001Z";
+ revocationDates[1] = (const uint8_t *)"130101000002Z";
+
+ code.data = (uint8_t *)calloc(1,
+ (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4)));
+ code.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4));
+
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueCRL (uint8ThisUpdateTime, numberOfRevoked, revokedNumbers,
+ revocationDates, &code));
+
+ // Check Certificate file
+ CertificateX509 certificate;
+ ByteArray crtDer = BYTE_ARRAY_INITIALIZER;
+ FILE *filePtr = fopen(CA_STORAGE_CRT_FILE , "rb");
+ ASSERT_TRUE(filePtr != NULL);
+
+ //get the length
+ fseek(filePtr, 0, SEEK_END);
+ crtDer.len = ftell(filePtr);
+ fseek(filePtr, 0, SEEK_SET);
+ //allocate memory
+ crtDer.data = (uint8_t*)malloc(crtDer.len+1);
+ //read the content
+ EXPECT_EQ(READ_WRITE_BLOCK_N, fread(crtDer.data, crtDer.len, READ_WRITE_BLOCK_N, filePtr));
+ fclose(filePtr);
+ ByteArray crtCheck;
+ crtCheck.data = crtDer.data + 3; //now file contains length of certificate
+ crtCheck.len = crtDer.len - 3;
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificate(crtCheck, &certificate));
+#ifdef X509_DEBUG
+ PrintCertificate(&certificate);
+#endif
+
+ //check CRL
+ ByteArray crlDer = BYTE_ARRAY_INITIALIZER;
+ crlDer.len = (CRL_MIN_SIZE + numberOfRevoked * (sizeof(CertificateRevocationInfo_t) + 4));
+ crlDer.data = (uint8_t *)malloc(crlDer.len);
+
+ EXPECT_EQ(PKI_SUCCESS, GetCertificateRevocationList(&crlDer));
+
+ EXPECT_EQ(PKI_SUCCESS, DecodeCertificateList (crlDer, &crl, pubKeyIss));
+#ifdef X509_DEBUG
+ PrintCRL(&crl);
+#endif
+ EXPECT_EQ(PKI_SUCCESS, CloseCKMInfo());
+ free(crlDer.data);
+ free(code.data);
+ free(crtDer.data);
+}
+
+//check correctness of root certificate generation
+TEST_F(PKITest, GenerateRootCertificate)
+{
+ uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+
+ ByteArray certDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ certDer.data = derData;
+ certDer.len = sizeof(derData);
+
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = sizeof(caPubKey);
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = sizeof(caPrivKey);
+ rootName.data = (uint8_t *)"ROOT";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+
+ for (int i = 1; i <= RUNS; i++)
+ {
+ ASSERT_EQ(PKI_SUCCESS, GenerateCAKeyPair(&privKeyIss, &pubKeyIss));
+ ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i));
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueRootCertificate(0, 0, &certDer));
+
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ certDer.data[0]++;
+ ASSERT_NE(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ certDer.data[0]--;
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ }
+ ASSERT_EQ(PKI_SUCCESS, CloseCKMInfo());
+}
+
+//check correctness of ordinal device certificate generation
+TEST_F(PKITest, GenerateDeviceCertificate)
+{
+ uint8_t derData[ISSUER_MAX_CERT_SIZE] = {0};
+ uint8_t subjPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t subjPrivKey[PRIVATE_KEY_SIZE] = {0};
+ uint8_t caPubKey[PUBLIC_KEY_SIZE] = {0};
+ uint8_t caPrivKey[PRIVATE_KEY_SIZE] = {0};
+ uint8_t *subjName = (uint8_t *)"Subject Name";
+
+ ByteArray certDer = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeyIss = BYTE_ARRAY_INITIALIZER;
+ ByteArray pubKeySubj = BYTE_ARRAY_INITIALIZER;
+ ByteArray privKeySubj = BYTE_ARRAY_INITIALIZER;
+ ByteArray rootName = BYTE_ARRAY_INITIALIZER;
+
+ certDer.data = derData;
+ certDer.len = ISSUER_MAX_CERT_SIZE;
+
+ pubKeyIss.data = caPubKey;
+ pubKeyIss.len = sizeof(caPubKey);
+ privKeyIss.data = caPrivKey;
+ privKeyIss.len = sizeof(caPrivKey);
+ pubKeySubj.data = subjPubKey;
+ pubKeySubj.len = sizeof(subjPubKey);
+ privKeySubj.data = subjPrivKey;
+ privKeySubj.len = sizeof(subjPrivKey);
+ rootName.data = (uint8_t *)"ROOT2";
+ rootName.len = strlen((char *)rootName.data);
+ ASSERT_EQ(PKI_SUCCESS, InitCKMInfo());
+
+ ASSERT_EQ(GenerateCAKeyPair(&privKeyIss, &pubKeyIss), PKI_SUCCESS);
+ for (int i = 1; i <= RUNS; i++)
+ {
+ ASSERT_EQ(PKI_SUCCESS, GenerateKeyPair(&privKeySubj, &pubKeySubj));
+ ASSERT_EQ(PKI_SUCCESS, SetSerialNumber(i));
+ ASSERT_EQ(PKI_SUCCESS, SetRootName(rootName));
+ ASSERT_EQ(PKI_SUCCESS, CKMIssueDeviceCertificate(subjName, 0, 0, subjPubKey, &certDer));
+
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ certDer.data[0]++;
+ ASSERT_NE(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ certDer.data[0]--;
+ ASSERT_EQ(PKI_SUCCESS, CheckCertificate(certDer, pubKeyIss));
+ }
+ ASSERT_EQ(CloseCKMInfo(), PKI_SUCCESS);
+}
+
+//check correctness of saving CRL to storage and loading CRL from storage
+TEST_F(PKITest, CRLSetGet)
+{
+ OicSecCrl_t *defaultCrl = NULL;
+ defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
+ defaultCrl->CrlId = CRL_DEFAULT_CRL_ID;
+ defaultCrl->CrlData.data = (uint8_t *)CRL_DEFAULT_CRL_DATA;
+ defaultCrl->CrlData.len = strlen(CRL_DEFAULT_CRL_DATA);
+ defaultCrl->ThisUpdate.data = (uint8_t *)CRL_DEFAULT_THIS_UPDATE;
+ defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE);
+ EXPECT_EQ(OC_STACK_OK, UpdateCRLResource(defaultCrl));
+
+ EXPECT_NE((void *)NULL, GetBase64CRL());
+ OICFree(defaultCrl);
+
+
+}
+
+int main(int argc, char **argv)
+{
+ ::testing::InitGoogleTest(&argc, argv);
+ return RUN_ALL_TESTS();
+}
--- /dev/null
+{
+ "acl": [
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/res",
+ "/oic/d",
+ "/oic/p",
+ "/oic/res/types/d",
+ "/oic/ad"
+ ],
+ "perms": 2,
+ "ownrs" : ["YWRtaW5EZXZpY2VVVUlE"]
+ },
+ {
+ "sub": "Kg==",
+ "rsrc": [
+ "/oic/sec/doxm",
+ "/oic/sec/pstat",
+ "/oic/sec/acl",
+ "/oic/sec/cred"
+ ],
+ "perms": 7,
+ "ownrs" : ["YWRtaW5EZXZpY2VVVUlE"]
+ }
+ ],
+ "crl": {
+ "CRLId": 1,
+ "ThisUpdate": "MTUwMTAxMDAwMDAwWg==",
+ "CRLData": "LQ=="
+ },
+ "pstat": {
+ "isop": true,
+ "deviceid": "YWRtaW5EZXZpY2VVVUlE",
+ "ch": 0,
+ "cm": 0,
+ "tm": 0,
+ "om": 3,
+ "sm": [3]
+ },
+ "doxm": {
+ "oxm": [0],
+ "oxmsel": 0,
+ "owned": true,
+ "deviceid": "YWRtaW5EZXZpY2VVVUlE",
+ "ownr": "YWRtaW5EZXZpY2VVVUlE"
+ }
+}
#include "cainterface.h"
#include "base64.h"
#include "cJSON.h"
+#include "global.h"
#include "srmresourcestrings.h"
#include "doxmresource.h"
CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
endpoint->port = otmCtx->selectedDeviceInfo->securePort;
- CAResult_t closeRes = CACloseDtlsSession(endpoint);
- if(CA_STATUS_OK != closeRes)
+ CAResult_t caResult = CACloseDtlsSession(endpoint);
+ if(CA_STATUS_OK != caResult)
{
OC_LOG(ERROR, TAG, "Failed to close DTLS session");
- SetResult(otmCtx, closeRes);
+ SetResult(otmCtx, caResult);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ /**
+ * If we select NULL cipher,
+ * client will select appropriate cipher suite according to server's cipher-suite list.
+ */
+ caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL);
+ if(CA_STATUS_OK != caResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
+ SetResult(otmCtx, caResult);
return OC_STACK_DELETE_TRANSACTION;
}
}
OC_LOG(INFO, TAG, "Anonymous cipher suite Enabled.");
+ caresult = CASelectCipherSuite(TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256);
+ if (CA_STATUS_OK != caresult)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256");
+ caresult = CAEnableAnonECDHCipherSuite(false);
+ if (CA_STATUS_OK != caresult)
+ {
+ OC_LOG_V(ERROR, TAG, "Unable to enable anon cipher suite");
+ }
+ else
+ {
+ OC_LOG(INFO, TAG, "Anonymous cipher suite Disabled.");
+ }
+ return OC_STACK_ERROR;
+ }
+ OC_LOG(INFO, TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
+
OCProvisionDev_t* selDevInfo = otmCtx->selectedDeviceInfo;
CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
if(NULL == endpoint)
#include <memory.h>
#include "ocstack.h"
-#include "ocsecurityconfig.h"
#include "securevirtualresourcetypes.h"
#include "doxmresource.h"
#include "credresource.h"
return OC_STACK_INVALID_PARAM;
}
+ CAResult_t caresult = CAEnableAnonECDHCipherSuite(false);
+ if (CA_STATUS_OK != caresult)
+ {
+ OC_LOG_V(ERROR, TAG, "Unable to disable anon cipher suite");
+ return OC_STACK_ERROR;
+ }
+ OC_LOG(INFO, TAG, "Anonymous cipher suite disabled.");
+
+ caresult = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
+ if (CA_STATUS_OK != caresult)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed to select TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256");
+ return OC_STACK_ERROR;
+ }
+ OC_LOG(INFO, TAG, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
+
+
OCProvisionDev_t* selDevInfo = otmCtx->selectedDeviceInfo;
CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
if(NULL == endpoint)
}
memcpy(endpoint,&selDevInfo->endpoint,sizeof(CAEndpoint_t));
endpoint->port = selDevInfo->securePort;
- CAResult_t caresult = CAInitiateHandshake(endpoint);
+ caresult = CAInitiateHandshake(endpoint);
OICFree(endpoint);
if (CA_STATUS_OK != caresult)
{
#define PDM_SQLITE_LIST_ALL_UUID "SELECT UUID FROM T_DEVICE_LIST"
#define PDM_SQLITE_GET_UUID "SELECT UUID FROM T_DEVICE_LIST WHERE ID = ?"
#define PDM_SQLITE_GET_LINKED_DEVICES "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE ID = ? or ID2 = ?"
+#define PDM_SQLITE_GET_DEVICE_LINKS "SELECT ID,ID2 FROM T_DEVICE_LINK_STATE WHERE ID = ? and ID2 = ?"
#define ASCENDING_ORDER(id1, id2) do{if( (id1) > (id2) )\
{ int temp; temp = id1; id1 = id2; id2 = temp; }}while(0)
sqlite3_stmt *stmt = 0;
int res = 0;
- res = sqlite3_prepare_v2(g_db, PDM_SQLITE_GET_LINKED_DEVICES,
- strlen(PDM_SQLITE_GET_LINKED_DEVICES) + 1, &stmt, NULL);
+ res = sqlite3_prepare_v2(g_db, PDM_SQLITE_GET_DEVICE_LINKS,
+ strlen(PDM_SQLITE_GET_DEVICE_LINKS) + 1, &stmt, NULL);
PDM_VERIFY_SQLITE_OK(TAG, res, ERROR, OC_STACK_ERROR);
res = sqlite3_bind_int(stmt, PDM_BIND_INDEX_FIRST, id1);
OC_LOG(INFO, TAG, "In SRPProvisionCredentials");
- bool linkExisits = true;
- OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
- if (res != OC_STACK_OK)
- {
- OC_LOG(ERROR, TAG, "Internal error occured");
- return res;
- }
- if (linkExisits)
+ if (SYMMETRIC_PAIR_WISE_KEY == type)
{
- OC_LOG(ERROR, TAG, "Link already exists");
- return OC_STACK_INVALID_PARAM;
+ bool linkExisits = true;
+ OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
+
+ if (res != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Internal error occured");
+ return res;
+ }
+ if (linkExisits)
+ {
+ OC_LOG(ERROR, TAG, "Link already exists");
+ return OC_STACK_INVALID_PARAM;
+ }
}
OicUuid_t provTooldeviceID = {{0,}};
}
OICFree(ace->resources);
- //Clean Period & Recurrence
- for(i = 0; i < ace->prdRecrLen; i++)
+ //Clean Period
+ if(ace->periods)
{
- OICFree(ace->periods[i]);
- OICFree(ace->recurrences[i]);
+ for(i = 0; i < ace->prdRecrLen; i++)
+ {
+ OICFree(ace->periods[i]);
+ }
+ OICFree(ace->periods);
+ }
+
+ //Clean Recurrence
+ if(ace->recurrences)
+ {
+ for(i = 0; i < ace->prdRecrLen; i++)
+ {
+ OICFree(ace->recurrences[i]);
+ }
+ OICFree(ace->recurrences);
}
- OICFree(ace->periods);
- OICFree(ace->recurrences);
// Clean Owners
OICFree(ace->owners);
{
VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,
ERROR);
+
if(acl->prdRecrLen > 0)
{
acl->recurrences = (char**)OICCalloc(acl->prdRecrLen,
for(size_t i = 0; i < acl->prdRecrLen; i++)
{
jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
+ VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
jsonObjLen = strlen(jsonRecur->valuestring) + 1;
acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
OICStrcpy(acl->recurrences[i], jsonObjLen,
- jsonRecur->valuestring);
+ jsonRecur->valuestring);
}
}
}
#include "cainterface.h"
#include "pbkdf2.h"
#include <stdlib.h>
+#include "iotvticalendar.h"
#ifdef WITH_ARDUINO
#include <string.h>
#else
* This internal callback is used by lower stack (i.e. CA layer) to
* retrieve PSK credentials from RI security layer.
*
- * Note: When finished, caller should initialize memory to zeros and
- * invoke OICFree to delete @p credInfo.
+ * @param[in] type type of PSK data required by tinyDTLS layer during DTLS handshake.
+ * @param[in] desc Additional request information.
+ * @param[in] desc_len The actual length of desc.
+ * @param[out] result Must be filled with the requested information.
+ * @param[in] result_length Maximum size of @p result.
*
- * @param credInfo
- * binary blob containing PSK credentials
- *
- * @retval none
+ * @return The number of bytes written to @p result or a value
+ * less than zero on error.
*/
-void GetDtlsPskCredentials(CADtlsPskCredsBlob_t **credInfo)
+int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
+ const unsigned char *desc, size_t desc_len,
+ unsigned char *result, size_t result_length)
{
- CADtlsPskCredsBlob_t * caBlob = NULL;
- if(credInfo)
- {
- caBlob = (CADtlsPskCredsBlob_t *)OICCalloc(sizeof(CADtlsPskCredsBlob_t), 1);
- if (caBlob)
- {
- OicUuid_t deviceID = {.id={}};
+ int32_t ret = -1;
- // Retrieve Device ID from doxm resource and copy in PSK creds blob
- VERIFY_SUCCESS(TAG, GetDoxmDeviceID(&deviceID) == OC_STACK_OK, ERROR);
- memcpy(caBlob->identity, deviceID.id, sizeof(caBlob->identity));
+ if (NULL == result)
+ {
+ return ret;
+ }
- OicSecCred_t *cred = NULL;
- size_t count = 0;
- LL_FOREACH(gCred, cred)
+ switch (type)
+ {
+ case CA_DTLS_PSK_HINT:
+ case CA_DTLS_PSK_IDENTITY:
{
- // Currently, Iotivity supports only symmetric pair wise key credentials
- if (cred->credType == SYMMETRIC_PAIR_WISE_KEY)
+ OicUuid_t deviceID = {.id={}};
+ // Retrieve Device ID from doxm resource
+ if ( OC_STACK_OK != GetDoxmDeviceID(&deviceID) )
{
- ++count;
+ OC_LOG (ERROR, TAG, "Unable to retrieve doxm Device ID");
+ return ret;
}
+
+ if (result_length < sizeof(deviceID.id))
+ {
+ OC_LOG (ERROR, TAG, "Wrong value for result_length");
+ return ret;
+ }
+ memcpy(result, deviceID.id, sizeof(deviceID.id));
+ return (sizeof(deviceID.id));
}
- caBlob->num = count;
- if (caBlob->num)
- {
- caBlob->creds =
- (OCDtlsPskCreds*) OICMalloc(caBlob->num * sizeof(OCDtlsPskCreds));
- VERIFY_NON_NULL(TAG, caBlob->creds, ERROR);
+ break;
- unsigned int i = 0;
+ case CA_DTLS_PSK_KEY:
+ {
+ OicSecCred_t *cred = NULL;
LL_FOREACH(gCred, cred)
{
- if ((cred->credType == SYMMETRIC_PAIR_WISE_KEY) &&
- (i < count))
-
+ if (cred->credType != SYMMETRIC_PAIR_WISE_KEY)
{
- // Copy subject ID
- memcpy(caBlob->creds[i].id, cred->subject.id,
- sizeof(caBlob->creds[i].id));
+ continue;
+ }
- // Convert PSK from JSON to binary before copying
+ if ((desc_len == sizeof(cred->subject.id)) &&
+ (memcmp(desc, cred->subject.id, sizeof(cred->subject.id)) == 0))
+ {
+ /*
+ * If the credentials are valid for limited time,
+ * check their expiry.
+ */
+ if (cred->period)
+ {
+ if(IOTVTICAL_VALID_ACCESS != IsRequestWithinValidTime(cred->period, NULL))
+ {
+ OC_LOG (INFO, TAG, "Credentials are expired.");
+ ret = -1;
+ return ret;
+ }
+ }
+
+ // Convert PSK from Base64 encoding to binary before copying
uint32_t outLen = 0;
B64Result b64Ret = b64Decode(cred->privateData.data,
- strlen(cred->privateData.data), caBlob->creds[i].psk,
- sizeof(caBlob->creds[i].psk), &outLen);
- VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
- i++;
+ strlen(cred->privateData.data), result,
+ result_length, &outLen);
+ if (B64_OK != b64Ret)
+ {
+ OC_LOG (ERROR, TAG, "Base64 decoding failed.");
+ ret = -1;
+ return ret;
+ }
+ return outLen;
}
}
}
- }
- *credInfo = caBlob;
- // Return from here after making the credential list
- return;
- }
+ break;
-exit:
- if (caBlob)
- {
- memset(caBlob->creds, 0, caBlob->num * sizeof(OCDtlsPskCreds));
- OICFree(caBlob->creds);
+ default:
+ {
+ OC_LOG (ERROR, TAG, "Wrong value passed for CADtlsPskCredType_t.");
+ ret = -1;
+ }
+ break;
}
- OICFree(caBlob);
+
+ return ret;
}
/**
return true;
}
+ //periods & recurrences rules are paired.
+ if(NULL == acl->recurrences)
+ {
+ return false;
+ }
+
for(size_t i = 0; i < acl->prdRecrLen; i++)
{
if(IOTVTICAL_VALID_ACCESS == IsRequestWithinValidTime(acl->periods[i],
const OicUuid_t* OCGetServerInstanceID(void);
/**
- * Get a string representation the server instance ID.
- * The memory is managed internal to this function, so freeing externally will result
- * in a runtime error.
- * Note: This will NOT seed the RNG, so it must be called after the RNG is seeded.
- * This is done automatically during the OCInit process,
- * so ensure that this call is done after that.
- *
- * @return A string representation the server instance ID.
- */
-const char* OCGetServerInstanceIDString(void);
-
-/**
* Map OCQualityOfService to CAMessageType.
*
* @param qos Input qos.
#endif // __cplusplus
#endif /* OCSTACKINTERNAL_H_ */
-
OCPresenceTrigger trigger, const char* resourceType);
void OCPresencePayloadDestroy(OCPresencePayload* payload);
+// Helper API
+OCStringLL* CloneOCStringLL (OCStringLL* ll);
+void OCFreeOCStringLL(OCStringLL* ll);
+
#ifdef __cplusplus
}
#endif
#endif
-
OCStackResult OCStop();
/**
+ * This function starts receiving the multicast traffic. This can be only called
+ * when stack is in OC_STACK_INITIALIZED state but device is not receiving multicast
+ * traffic.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult OCStartMulticastServer();
+
+/**
+ * This function stops receiving the multicast traffic. The rest of the stack
+ * keeps working and no resource are deleted. Device can still receive the unicast
+ * traffic. Once this is set, no response to multicast /oic/res will be sent by the
+ * device. This is to be used for devices that uses other entity to push resources.
+ *
+ * @return ::OC_STACK_OK on success, some other value upon failure.
+ */
+OCStackResult OCStopMulticastServer();
+
+/**
* This function is Called in main loop of OC client or server.
* Allows low-level processing of stack services.
*
OCStackResult OCDeleteResource(OCResourceHandle handle);
/**
+ * Get a string representation the server instance ID.
+ * The memory is managed internal to this function, so freeing externally will result
+ * in a runtime error.
+ * Note: This will NOT seed the RNG, so it must be called after the RNG is seeded.
+ * This is done automatically during the OCInit process,
+ * so ensure that this call is done after that.
+ *
+ * @return A string representation the server instance ID.
+ */
+const char* OCGetServerInstanceIDString(void);
+
+/**
* This function gets the URI of the resource specified by handle.
*
* @param handle Handle of resource.
#define OC_RSRVD_DATA_MODEL_VERSION "dmv"
/** Device specification version.*/
-#define OC_SPEC_VERSION "0.9.0"
+#define OC_SPEC_VERSION "0.9.2"
/** Device Data Model version.*/
#define OC_DATA_MODEL_VERSION "sec.0.95"
/** Max identity size. */
#define MAX_IDENTITY_SIZE (32)
+/** Resource Directory */
+
+/** Resource Directory URI used to Discover RD and Publish resources.*/
+#define OC_RSRVD_RD_URI "/oic/rd"
+
+/** To represent resource type with rd.*/
+#define OC_RSRVD_RESOURCE_TYPE_RD "oic.wk.rd"
+
+/** RD Discovery bias factor type. */
+#define OC_RSRVD_RD_DISCOVERY_SEL "sel"
+
+/** Base URI. */
+#define OC_RSRVD_BASE_URI "baseURI"
+
+/** Unique value per collection/link. */
+#define OC_RSRVD_INS "ins"
+
+/** Allowable resource types in the links. */
+#define OC_RSRVD_RTS "rts"
+
+/** Default relationship. */
+#define OC_RSRVD_DREL "drel"
+
+/** Defines relationship between links. */
+#define OC_RSRVD_REL "rel"
+
+/** Defines title. */
+#define OC_RSRVD_TITLE "title"
+
+/** Defines URI. */
+#define OC_RSRVD_URI "uri"
+
+/** Defines media type. */
+#define OC_RSRVD_MEDIA_TYPE "mt"
+
+/** To represent resource type with Publish RD.*/
+#define OC_RSRVD_RESOURCE_TYPE_RDPUBLISH "oic.wk.rdPub"
+
/**
* These enums (OCTransportAdapter and OCTransportFlags) must
* be kept synchronized with OCConnectivityType (below) as well as
PAYLOAD_TYPE_PLATFORM,
PAYLOAD_TYPE_REPRESENTATION,
PAYLOAD_TYPE_SECURITY,
- PAYLOAD_TYPE_PRESENCE
+ PAYLOAD_TYPE_PRESENCE,
+ PAYLOAD_TYPE_RD
} OCPayloadType;
typedef struct
struct OCResourcePayload* next;
} OCResourcePayload;
+/**
+ * Structure holding Links Payload. It is a sub-structure used in
+ * OCResourceCollectionPayload.
+ */
+typedef struct OCLinksPayload
+{
+ /** This is the target relative URI. */
+ char *href;
+ /** Resource Type - A standard OIC specified or vendor defined resource
+ * type of the resource referenced by the target URI. */
+ OCStringLL *rt;
+ /** Interface - The interfaces supported by the resource referenced by the target URI. */
+ OCStringLL *itf;
+ /** The relation of the target URI referenced by the link to the context URI;
+ * The default value is null. */
+ char *rel;
+ /** Specifies if the resource referenced by the target URIis observable or not. */
+ bool obs;
+ /** A title for the link relation. Can be used by the UI to provide a context. */
+ char *title;
+ /** This is used to override the context URI e.g. override the URI of the containing collection. */
+ char *uri;
+ /** The instance identifier for this web link in an array of web links - used in links. */
+ union
+ {
+ /** An ordinal number that is not repeated - must be unique in the collection context. */
+ uint8_t ins;
+ /** Any unique string including a URI. */
+ char *uniqueStr;
+ /** Use UUID for universal uniqueness - used in /oic/res to identify the device. */
+ OCIdentity uniqueUUID;
+ };
+ /** A hint of the media type of the representation of the resource referenced by the target URI. */
+ OCStringLL *mt;
+ /** Holding address of the next resource. */
+ struct OCLinksPayload *next;
+} OCLinksPayload;
+
+/** Structure holding tags value of the links payload. */
+typedef struct
+{
+ /** Name of tags. */
+ OCDeviceInfo n;
+ /** Device identifier. */
+ OCIdentity di;
+ /** The base URI where the resources are hold. */
+ char *baseURI;
+ /** Bitmap holds observable, discoverable, secure option flag.*/
+ uint8_t bitmap;
+ /** Port set in case, the secure flag is set above. */
+ uint16_t port;
+ /** Id for each set of links i.e. tag. */
+ union
+ {
+ /** An ordinal number that is not repeated - must be unique in the collection context. */
+ uint8_t ins;
+ /** Any unique string including a URI. */
+ char *uniqueStr;
+ /** Use UUID for universal uniqueness - used in /oic/res to identify the device. */
+ OCIdentity uniqueUUID;
+ };
+ /** Defines the list of allowable resource types (for Target and anchors) in links included
+ * in the collection; new links being created can only be from this list. */
+ char *rts;
+ /** When specified this is the default relationship to use when an OIC Link does not specify
+ * an explicit relationship with *rel* parameter. */
+ char *drel;
+ /** Time to keep holding resource.*/
+ uint32_t ttl;
+} OCTagsPayload;
+
+/** Resource collection payload. */
+typedef struct OCResourceCollectionPayload
+{
+ /** Collection tags payload.*/
+ OCTagsPayload *tags;
+ /** Array of links payload. */
+ OCLinksPayload *setLinks;
+ /** Holding address of the next resource. */
+ struct OCResourceCollectionPayload *next;
+} OCResourceCollectionPayload;
+
typedef struct
{
OCPayload base;
- OCResourcePayload* resources;
+ /** This structure holds the old /oic/res response. */
+ OCResourcePayload *resources;
+ /** This structure holds the collection response for the /oic/res. */
+ OCResourceCollectionPayload *collectionResources;
} OCDiscoveryPayload;
+/**
+ * Structure holding discovery payload.
+ */
+typedef struct
+{
+ /** Device Name. */
+ OCDeviceInfo n;
+ /** Device Identity. */
+ OCIdentity di;
+ /** Value holding the bias factor of the RD. */
+ uint8_t sel;
+} OCRDDiscoveryPayload;
+
+/**
+ * RD Payload that will be transmitted over the wire.
+ */
+typedef struct
+{
+ OCPayload base;
+ /** Pointer to the discovery response payload.*/
+ OCRDDiscoveryPayload *rdDiscovery;
+ /** Pointer to the publish payload.*/
+ OCResourceCollectionPayload *rdPublish;
+} OCRDPayload;
+
typedef struct
{
OCPayload base;
#include <dlog.h>
#endif
+#include "rdpayload.h"
+
#ifdef __cplusplus
extern "C"
{
OC_LOG_V(level, PL_TAG, "\tSecurity Data: %s", payload->securityData);
}
+static inline void OCRDPayloadLog(const LogLevel level, const OCRDPayload *payload)
+{
+ if (!payload)
+ {
+ return;
+ }
+
+ if (payload->rdDiscovery)
+ {
+ OC_LOG(level, PL_TAG, "RD Discovery");
+ OC_LOG_V(level, PL_TAG, " Device Name : %s", payload->rdDiscovery->n.deviceName);
+ OC_LOG_V(level, PL_TAG, " Device Identity : %s", payload->rdDiscovery->di.id);
+ OC_LOG_V(level, PL_TAG, " Bias: %d", payload->rdDiscovery->sel);
+ }
+ if (payload->rdPublish)
+ {
+ OC_LOG(level, PL_TAG, "RD Publish");
+ OCResourceCollectionPayload *rdPublish = payload->rdPublish;
+ OCTagsLog(level, rdPublish->tags);
+ OCLinksLog(level, rdPublish->setLinks);
+ }
+}
+
static inline void OCPayloadLog(LogLevel level, OCPayload* payload)
{
if(!payload)
case PAYLOAD_TYPE_SECURITY:
OCPayloadLogSecurity(level, (OCSecurityPayload*)payload);
break;
+ case PAYLOAD_TYPE_RD:
+ OCRDPayloadLog(level, (OCRDPayload*)payload);
+ break;
default:
OC_LOG_V(level, PL_TAG, "Unknown Payload Type: %d", payload->type);
break;
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 _RDPAYLOAD_H_
+#define _RDPAYLOAD_H_
+
+#include <cbor.h>
+#include "octypes.h"
+#include "logger.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ * Converts RD payload from structure to CBOR format. It creates the outPayload
+ * which is then transmitted over the wire.
+ *
+ * @param rdPayload Contains structure holding values of OCRDPayload.
+ * @param outPayload The payload in the CBOR format converting OCRDPayload
+ * structure.
+ * @param size Length of the payload.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size);
+
+/**
+ * Converts tags structure to the tags cbor payload.
+ *
+ * @param tags Allocated Tag structure
+ * @param setMap The cbor map where result will be stored.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+OCStackResult OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap);
+
+/**
+ * Converts links structure to cbor map structure
+ *
+ * @param links Allocated links structure.
+ * @param setMap The cbor map where result will be stored.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+OCStackResult OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap);
+
+/**
+ * Converts CBOR to OCRDPayload.
+ *
+ * @param rdCBORPayload Payload received from other end in CBOR format.
+ * @param outPayload Parsing the values from CBOR into OCRDPayload structure.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in parsing CBOR.
+ */
+OCStackResult OCRDCborToPayload(const CborValue *cborPayload, OCPayload **outPayload);
+
+/**
+ * Converts cbor map payload to OCTags payload.
+ *
+ * @param tagstMap CborValue holding tags structure.
+ * @param tagsPayload Allocated tags payload.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+OCStackResult OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload);
+
+/**
+ * Converts cbor map payload to OCLinks payload.
+ *
+ * @param tagstMap CborValue holding links structure.
+ * @param tagsPayload Allocated links payload.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+OCStackResult OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload);
+
+/**
+ * Initializes RD payload structure.
+ *
+ * @param payloadType Defines whether payload is RD_PAYLOAD_TYPE_DISCOVERY or
+ * RD_PAYLOAD_TYPE_PUBLISH.
+ *
+ * @return Allocated memory for the OCRDPayload and NULL in case if failed to
+ * allocate memory
+ */
+OCRDPayload *OCRDPayloadCreate();
+
+/**
+ * Initializes RD Discovery payload structure and sets the bias factor.
+ *
+ * @param name Name of the discovery device payload.
+ * @param identity Device identity of the discovery device.
+ * @param biasFactor Value specifies the selection factor. It is weigthage of
+ * CPU, Memory, Network, Load and Power capability of the RD server.
+ *
+ * @return Allocated memory for the OCRDDiscoveryPayload and NULL in case if
+ * failed to allocate memory.
+ */
+OCRDDiscoveryPayload *OCRDDiscoveryPayloadCreate(const char *name, const char *identity, int biasFactor);
+
+/**
+ * Free memory allocation of the RDPayload and its internal structure.
+ *
+ * @param payload Pointer to already allocated memory for OCRDPayload.
+ */
+void OCRDPayloadDestroy(OCRDPayload *payload);
+
+/**
+ * Copies tag paramter to creates OCTagsPayload.
+ *
+ * @param deviceName The device name as set during enrollment.
+ * @param id The device UUID
+ * @param baseURI baseURI pointing to the resource directory location.
+ * @param bitmap The bitmap value include observe, discovery and secure bit set.
+ * @param port The secure port in case above bitmap is set to secure.
+ * @param ins Unique value per collection.
+ * @param rts Defines allowed resource types.
+ * @param drel Defines defaultr relationship.
+ * @param ttl Time to leave for the . Used only in resource directory.
+ *
+ * @retun Allocated memory for OCTagsPayload or else NULL in case of error.
+ */
+OCTagsPayload* OCCopyTagsResources(const char *deviceName, const unsigned char *id,
+ const char *baseURI, uint8_t bitmap, uint16_t port, uint8_t ins, const char *rts, const char *drel, uint32_t ttl);
+
+/**
+ * Copies link resource to create LinksPayload.
+ *
+ * @param href URI of the resource
+ * @param rt Array of String pointing to resource types.
+ * @param itf Array of String pointing to interface
+ * @param rel Relation
+ * @param obs Whether to observe or not.
+ * @param title Title
+ * @param uri URI
+ * @param ins Unique value per link.
+ * @param mt Media Type
+
+ * @retun Allocated memory for OCLinksPayload or else NULL in case of error.
+ */
+OCLinksPayload* OCCopyLinksResources(const char *href, OCStringLL *rt, OCStringLL *itf,
+ const char *rel, bool obs, const char *title, const char *uri, uint8_t ins, OCStringLL *mt);
+
+/**
+ * Creates a resource collection object.
+ *
+ * @param tags Pointer pointing to tags payload.
+ * @param links Pointer pointing to links payload.
+ *
+ * @return Memory allocation for OCResourceCollectionPayload, else NULL.
+ */
+OCResourceCollectionPayload* OCCopyCollectionResource(OCTagsPayload *tags, OCLinksPayload *links);
+
+/**
+ * Adds discocvery collection in discovery payload.
+ *
+ * @param payload Pointer to the discovery payload. It adds allocated collection resource.
+ * @param tags Pointer to the tags payload.
+ * @param links Pointer to the links payload.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+
+OCStackResult OCDiscoveryCollectionPayloadAddResource(OCDiscoveryPayload *payload, OCTagsPayload *tags,
+ OCLinksPayload *links);
+
+/**
+ * Destroys tags payload including internal structure allocated
+ *
+ * @param tags - Allocated memory of the tags payload.
+ */
+void OCFreeTagsResource(OCTagsPayload *tags);
+
+/**
+ * Destroys allocated links payload including internal structure allocated.
+ *
+ * @param links - Allocated memory to the links payload.
+ */
+void OCFreeLinksResource(OCLinksPayload *links);
+
+/**
+ * ResourceCollection payload destroy. Includes free up tags and links structure.
+ *
+ * @param payload Pointer pointing to allocated memroy of ResourceCollection.
+ */
+void OCFreeCollectionResource(OCResourceCollectionPayload *payload);
+
+/**
+ * Discovery collection payload destroy includes internal structure OCResourceCollectionPayload.
+ *
+ * @param payload Pointer pointing to allocated memory of OCDiscoveryPayload.
+ */
+void OCDiscoveryCollectionPayloadDestroy(OCDiscoveryPayload* payload);
+
+/**
+ * Prints tags payload.
+ *
+ * @param level LogLevel for the print.
+ * @param tags Structure of the tags payload.
+ */
+void OCTagsLog(const LogLevel level, const OCTagsPayload *tags);
+
+/**
+ * Prints links payload.
+ *
+ * @param level LogLevel for the print.
+ * @param tags Structure of the links payload.
+ */
+void OCLinksLog(const LogLevel level, const OCLinksPayload *links);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif /* OCTYPES_H_ */
Observers interestedObservers[SAMPLE_MAX_NUM_OBSERVATIONS];
+pthread_t threadId_observe;
+pthread_t threadId_presence;
+
+static bool observeThreadStarted = false;
+
#ifdef WITH_PRESENCE
-static int stopPresenceCount = 10;
#define numPresenceResources (2)
#endif
{
OC_LOG_V (INFO, TAG, "Received observation registration request with observation Id %d",
ehRequest->obsInfo.obsId);
+
+ if (!observeThreadStarted)
+ {
+ pthread_create (&threadId_observe, NULL, ChangeLightRepresentation, (void *)NULL);
+ observeThreadStarted = 1;
+ }
for (uint8_t i = 0; i < SAMPLE_MAX_NUM_OBSERVATIONS; i++)
{
if (interestedObservers[i].valid == false)
OC_LOG (ERROR, TAG, "Incorrect notification type selected");
}
}
-#ifdef WITH_PRESENCE
- if(stopPresenceCount > 0)
- {
- OC_LOG_V(INFO, TAG, "================ Counting down to stop presence %d", stopPresenceCount);
- }
- if(!stopPresenceCount--)
- {
- OC_LOG(INFO, TAG, "================ stopping presence");
- OCStopPresence();
- }
-#endif
}
return NULL;
}
#ifdef WITH_PRESENCE
void *presenceNotificationGenerator(void *param)
{
- sleep(10);
+ uint8_t secondsBeforePresence = 10;
+ OC_LOG_V(INFO, TAG, "Will send out presence in %u seconds", secondsBeforePresence);
+ sleep(secondsBeforePresence);
(void)param;
OCDoHandle presenceNotificationHandles[numPresenceResources];
OCStackResult res = OC_STACK_OK;
OC_LOG_V(INFO, TAG, PCF("Deleted %s for presence notification"),
presenceNotificationUris[i].c_str());
}
+
+ OC_LOG(INFO, TAG, "================ stopping presence");
+ OCStopPresence();
+
return NULL;
}
#endif
int main(int argc, char* argv[])
{
- pthread_t threadId;
- pthread_t threadId_presence;
#ifdef RA_ADAPTER
char host[] = "localhost";
interestedObservers[i].valid = false;
}
- /*
- * Create a thread for changing the representation of the Light
- */
- pthread_create (&threadId, NULL, ChangeLightRepresentation, (void *)NULL);
/*
* Create a thread for generating changes that cause presence notifications
OC_LOG(ERROR, TAG, "OCStack process error");
return 0;
}
-#ifndef ROUTING_GATEWAY
- sleep(2);
-#endif
}
- /*
- * Cancel the Light thread and wait for it to terminate
- */
- pthread_cancel(threadId);
- pthread_join(threadId, NULL);
+ if (observeThreadStarted)
+ {
+ pthread_cancel(threadId_observe);
+ pthread_join(threadId_observe, NULL);
+ }
+
pthread_cancel(threadId_presence);
pthread_join(threadId_presence, NULL);
"credid": 1,
"sub": "MTExMTExMTExMTExMTExMQ==",
"credtyp": 1,
+ "prd": "20150630T060000/20990920T220000",
"pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
"ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
}]
--- /dev/null
+Build Procedure
+===============
+
+1) If you are building first time, then delete GBS-ROOT-RI folder from home directory.
+ Note: Default build server URL for Tizen is set in gbs configuration file @ iotivity/tools/tizen/.gbs.conf.
+ If needed, same can be modified as per appropriate target.
+2) Go to "iotivity/" folder.
+3) Execute following command(s) to start build based on transport selection required :
+ -> Building for all transports :
+ $ scons -f resource/csdk/stack/samples/tizen/build/SConscript TARGET_OS=tizen TARGET_TRANSPORT=ALL
+
+ -> Building for a specific transport :
+ $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP
+
+ -> Building for multiple transports :
+ $ scons -f resource/csdk/connectivity/build/tizen/SConscript TARGET_OS=tizen TARGET_TRANSPORT=IP,BT,BLE
+
+4) By default, above command will build csdk samples also.
+
+Note :- Upon successful execution of above command(s) RI library and sample applications will be
+ generated at path "~/GBS-ROOT-RI/local/repos/<target>/armv7l/RPMS".
+
+Procedure to Execute Sample App:
+================================
+ 1) Copy the generated rpms(com-oic-ri-0.1-1.armv7l.rpm, com-oic-ri-sample-0.1-1.armv7l.rpm) to Tizen Device
+ (say /opt/usr/media/xxx/)
+ 2) sdb shell
+ 3) su
+ 4) cd /opt/usr/media/xxx/
+ 5) change-booting-mode.sh --update
+
+ 6) Install the rpms using the following commands:
+ a) rpm -Uvh com-oic-ri-0.1-1.armv7l.rpm --force --nodeps
+ b) rpm -Uvh com-oic-ri-sample-0.1-1.armv7l.rpm --force --nodeps
+ 7) For IP transport, apply net-config smack rules using below command:
+ a) chsmack -a "net-config" /usr/apps/com.oic.ri.sample/bin/*
+ b) chsmack -e "net-config" /usr/apps/com.oic.ri.sample/bin/*
+ 7) RPM will be installed in "/usr/apps/"
+ Execute the sample app by below commands
+ i) cd /usr/apps/com.oic.ri.sample/bin
+ a) ./ocserver -o0 [For Server sample]
+ b) ./occlient -t2 [For client sample]
+ c) ./ocrouting [For Gateway sample]
\ No newline at end of file
echo `pwd`
+rm -rf ./tmp
mkdir ./tmp
mkdir ./tmp/extlibs/
mkdir ./tmp/packaging
-cp -R ./extlibs/tinycbor $sourcedir/tmp/extlibs
+cp -LR ./extlibs/tinycbor $sourcedir/tmp/extlibs
+rm -rf $sourcedir/tmp/extlibs/tinycbor/tinycbor/.git
cp -R ./extlibs/cjson $sourcedir/tmp/extlibs
cp -R ./extlibs/tinydtls $sourcedir/tmp/extlibs
cp -R ./extlibs/timer $sourcedir/tmp/extlibs
cp -R ./resource $sourcedir/tmp/
cp -R ./build_common/external_libs.scons $sourcedir/tmp/
+# copy dependency RPMs and conf files for tizen build
+cp ./tools/tizen/*.rpm $sourcedir/tmp
+cp ./tools/tizen/*.rpm $sourcedir/tmp/resource/csdk/stack/samples/tizen/SimpleClientServer
+cp ./tools/tizen/.gbs.conf ./tmp
+cp ./tools/tizen/.gbs.conf ./tmp/resource/csdk/stack/samples/tizen/SimpleClientServer
+
cd $sourcedir
cd ./resource/csdk/stack/samples/tizen/build/
fi
echo "Calling core gbs build command"
-gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6' --repository ./"
+gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6'"
echo $gbscommand
if eval $gbscommand; then
echo "Core build is successful"
else
- echo "Core build failed. Try 'sudo find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+ echo "Core build failed. Try 'find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
cd $sourcedir
rm -rf $sourcedir/tmp
- exit
+ exit 1
fi
if echo $BUILD_SAMPLE|grep -qi '^ON$'; then
git commit -m "Initial commit"
fi
echo "Calling sample gbs build command"
- gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI --include-all --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6' --repository ./"
+ gbscommand="gbs build -A armv7l -B ~/GBS-ROOT-RI --include-all --repository ./ --define 'TARGET_TRANSPORT $1' --define 'SECURED $2' --define 'RELEASE $4' --define 'LOGGING $5' --define 'ROUTING $6'"
echo $gbscommand
if eval $gbscommand; then
echo "Sample build is successful"
else
- echo "Sample build is failed. Try 'sudo find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+ echo "Sample build is failed. Try 'find . -type f -exec dos2unix {} \;' in the 'connectivity/' folder"
+ exit 1
fi
else
echo "Sample build is not enabled"
fi
-
cd $sourcedir
rm -rf $sourcedir/tmp
+exit 0
cp resource/csdk/stack/include/ocpayload.h %{DEST_INC_DIR}
cp resource/c_common/platform_features.h %{DEST_INC_DIR}
cp resource/csdk/stack/include/payload_logging.h %{DEST_INC_DIR}
+cp resource/csdk/stack/include/rdpayload.h %{DEST_INC_DIR}
+cp extlibs/tinycbor/tinycbor/src/cbor.h %{DEST_INC_DIR}
cp extlibs/cjson/cJSON.h %{DEST_INC_DIR}
cp -rf %{ROOTDIR}/com.oic.ri.pc %{DEST_LIB_DIR}/pkgconfig/
#include "ocstackinternal.h"
#include "ocresource.h"
#include "logger.h"
+#include "rdpayload.h"
#define TAG "OCPayload"
static void OCFreeRepPayloadValueContents(OCRepPayloadValue* val);
case PAYLOAD_TYPE_SECURITY:
OCSecurityPayloadDestroy((OCSecurityPayload*)payload);
break;
+ case PAYLOAD_TYPE_RD:
+ OCRDPayloadDestroy((OCRDPayload*)payload);
+ break;
default:
OC_LOG_V(ERROR, TAG, "Unsupported payload type in destroy: %d", payload->type);
OICFree(payload);
#include "ocrandom.h"
#include "ocresourcehandler.h"
#include "cbor.h"
+#include "rdpayload.h"
#define TAG "OCPayloadConvert"
// Arbitrarily chosen size that seems to contain the majority of packages
#define INIT_SIZE (255)
+#define CBOR_ROOT_ARRAY_LENGTH 1
+
// Functions all return either a CborError, or a negative version of the OC_STACK return values
static int64_t OCConvertPayloadHelper(OCPayload* payload, uint8_t* outPayload, size_t* size);
static int64_t OCConvertDiscoveryPayload(OCDiscoveryPayload* payload, uint8_t* outPayload,
return OCConvertPresencePayload((OCPresencePayload*)payload, outPayload, size);
case PAYLOAD_TYPE_SECURITY:
return OCConvertSecurityPayload((OCSecurityPayload*)payload, outPayload, size);
+ case PAYLOAD_TYPE_RD:
+ return OCRDPayloadToCbor((OCRDPayload*)payload, outPayload, size);
default:
OC_LOG_V(INFO,TAG, "ConvertPayload default %d", payload->type);
return OC_STACK_NOTIMPL;
size_t* size)
{
CborEncoder encoder = {0};
+ CborEncoder rootArray = {0};
int64_t err = 0;
- size_t resourceCount = OCDiscoveryPayloadGetResourceCount(payload);
cbor_encoder_init(&encoder, outPayload, *size, 0);
- CborEncoder rootArray;
- err = err | cbor_encoder_create_array(&encoder, &rootArray, resourceCount);
-
- for(size_t i = 0; i < resourceCount; ++i)
+ if (payload->collectionResources)
{
- CborEncoder map;
- OCResourcePayload* resource = OCDiscoveryPayloadGetResource(payload, i);
+ CborError cborEncoderResult;
+ cborEncoderResult = cbor_encoder_create_array(&encoder, &rootArray, CBOR_ROOT_ARRAY_LENGTH);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating root array.");
+ goto cbor_error;
+ }
- if(!resource)
+ CborEncoder colArray;
+ cborEncoderResult = cbor_encoder_create_array(&rootArray, &colArray, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
{
- return OC_STACK_INVALID_PARAM;
+ OC_LOG(ERROR, TAG, "Failed creating collection array.");
+ goto cbor_error;
+ }
+ OCResourceCollectionPayload *colResources = payload->collectionResources;
+ while (colResources)
+ {
+ if (OC_STACK_OK != OCTagsPayloadToCbor(colResources->tags, &colArray))
+ {
+ goto cbor_error;
+ }
+ if (OC_STACK_OK != OCLinksPayloadToCbor(colResources->setLinks, &colArray))
+ {
+ goto cbor_error;
+ }
+ colResources = colResources->next;
}
+ cborEncoderResult = cbor_encoder_close_container(&rootArray, &colArray);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing collection array.");
+ goto cbor_error;
+ }
+ cborEncoderResult = cbor_encoder_close_container(&encoder, &rootArray);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing root array.");
+ goto cbor_error;
+ }
+ }
+ else if (payload->resources)
+ {
+ size_t resourceCount = OCDiscoveryPayloadGetResourceCount(payload);
+ err = err || cbor_encoder_create_array(&encoder, &rootArray, resourceCount);
- err = err | cbor_encoder_create_map(&rootArray, &map, 3);
- // Uri
- err = err | AddTextStringToMap(&map, OC_RSRVD_HREF,
- sizeof(OC_RSRVD_HREF) - 1,
- resource->uri);
-
- // Server ID
- err = err | cbor_encode_text_string(&map, OC_RSRVD_SERVER_INSTANCE_ID,
- sizeof(OC_RSRVD_SERVER_INSTANCE_ID) - 1);
- err = err | cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
- // Prop Tag
+ for(size_t i = 0; i < resourceCount; ++i)
{
- CborEncoder propMap;
- err = err | cbor_encode_text_string(&map, OC_RSRVD_PROPERTY,
- sizeof(OC_RSRVD_PROPERTY) -1 );
- err = err | cbor_encoder_create_map(&map, &propMap, 3);
+ CborEncoder map;
+ OCResourcePayload* resource = OCDiscoveryPayloadGetResource(payload, i);
- // Resource Type
- if (resource->types)
+ if(!resource)
{
- char* joinedTypes = OCStringLLJoin(resource->types);
- if (joinedTypes)
- {
- err = err | cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
- sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
- err = err | cbor_encode_text_string(&propMap, joinedTypes,
- strlen(joinedTypes));
- OICFree(joinedTypes);
- }
- else
- {
- return OC_STACK_NO_MEMORY;
- }
+ OICFree(outPayload);
+ return OC_STACK_INVALID_PARAM;
}
- // Interface Types
- if (resource->interfaces)
+
+ err = err | cbor_encoder_create_map(&rootArray, &map, 3);
+ // Uri
+ err = err | AddTextStringToMap(&map, OC_RSRVD_HREF,
+ sizeof(OC_RSRVD_HREF) - 1,
+ resource->uri);
+
+ // Server ID
+ err = err | cbor_encode_text_string(&map, OC_RSRVD_SERVER_INSTANCE_ID,
+ sizeof(OC_RSRVD_SERVER_INSTANCE_ID) - 1);
+ err = err | cbor_encode_byte_string(&map, resource->sid, UUID_SIZE);
+
+ // Prop Tag
{
- char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
- if (joinedInterfaces)
+ CborEncoder propMap;
+ err = err | cbor_encode_text_string(&map, OC_RSRVD_PROPERTY,
+ sizeof(OC_RSRVD_PROPERTY) -1 );
+ err = err | cbor_encoder_create_map(&map, &propMap, 3);
+ // Resource Type
+ if (resource->types)
{
- err = err | cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
- sizeof(OC_RSRVD_INTERFACE) - 1);
- err = err | cbor_encode_text_string(&propMap, joinedInterfaces,
- strlen(joinedInterfaces));
- OICFree(joinedInterfaces);
+ char* joinedTypes = OCStringLLJoin(resource->types);
+ if (joinedTypes)
+ {
+ err = err | cbor_encode_text_string(&propMap, OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1);
+ err = err | cbor_encode_text_string(&propMap, joinedTypes,
+ strlen(joinedTypes));
+ OICFree(joinedTypes);
+ }
+ else
+ {
+ return OC_STACK_NO_MEMORY;
+ }
}
- else
+ // Interface Types
+ if (resource->interfaces)
{
- return OC_STACK_NO_MEMORY;
+ char* joinedInterfaces = OCStringLLJoin(resource->interfaces);
+ if (joinedInterfaces)
+ {
+ err = err | cbor_encode_text_string(&propMap, OC_RSRVD_INTERFACE,
+ sizeof(OC_RSRVD_INTERFACE) - 1);
+ err = err | cbor_encode_text_string(&propMap, joinedInterfaces,
+ strlen(joinedInterfaces));
+ OICFree(joinedInterfaces);
+ }
+ else
+ {
+ return OC_STACK_NO_MEMORY;
+ }
}
- }
-
- // Policy
- {
- CborEncoder policyMap;
- err = err | cbor_encode_text_string(&propMap, OC_RSRVD_POLICY,
- sizeof(OC_RSRVD_POLICY) - 1);
- err = err | cbor_encoder_create_map(&propMap, &policyMap, CborIndefiniteLength);
-
- // Bitmap
- err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
- sizeof(OC_RSRVD_BITMAP) - 1);
- err = err | cbor_encode_uint(&policyMap, resource->bitmap);
-
- if(resource->secure)
+ // Policy
{
- err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
- sizeof(OC_RSRVD_SECURE) - 1);
- err = err | cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
+ CborEncoder policyMap;
+ err = err || cbor_encode_text_string(&propMap, OC_RSRVD_POLICY,
+ sizeof(OC_RSRVD_POLICY) - 1);
+ err = err || cbor_encoder_create_map(&propMap, &policyMap, CborIndefiniteLength);
- if(resource->port != 0)
+ // Bitmap
+ err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_BITMAP,
+ sizeof(OC_RSRVD_BITMAP) - 1);
+ err = err || cbor_encode_uint(&policyMap, resource->bitmap);
+
+ if(resource->secure)
{
- err = err | cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
- sizeof(OC_RSRVD_HOSTING_PORT) - 1);
- err = err | cbor_encode_uint(&policyMap, resource->port);
+ err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_SECURE,
+ sizeof(OC_RSRVD_SECURE) - 1);
+ err = err || cbor_encode_boolean(&policyMap, OC_RESOURCE_SECURE);
+
+ if(resource->port != 0)
+ {
+ err = err || cbor_encode_text_string(&policyMap, OC_RSRVD_HOSTING_PORT,
+ sizeof(OC_RSRVD_HOSTING_PORT) - 1);
+ err = err || cbor_encode_uint(&policyMap, resource->port);
+ }
}
+ err = err || cbor_encoder_close_container(&propMap, &policyMap);
}
-
- err = err | cbor_encoder_close_container(&propMap, &policyMap);
+ // Close
+ err = err || cbor_encoder_close_container(&map, &propMap);
}
- // Close
- err = err | cbor_encoder_close_container(&map, &propMap);
+ // Close Item
+ err = err || cbor_encoder_close_container(&rootArray, &map);
}
- // Close Item
- err = err | cbor_encoder_close_container(&rootArray, &map);
+ // Close main array
+ err = err | cbor_encoder_close_container(&encoder, &rootArray);
}
- // Close main array
- err = err | cbor_encoder_close_container(&encoder, &rootArray);
return checkError(err, &encoder, outPayload, size);
+cbor_error:
+ OICFree(outPayload);
+ return OC_STACK_ERROR;
}
static int64_t OCConvertDevicePayload(OCDevicePayload* payload, uint8_t* outPayload,
#include "ocpayloadcbor.h"
#include <stdlib.h>
#include "logger.h"
+#include "oic_string.h"
#include "oic_malloc.h"
#include "ocstackinternal.h"
#include "ocpayload.h"
#include "cbor.h"
#include "oic_string.h"
+#include "payload_logging.h"
+#include "rdpayload.h"
#define TAG "OCPayloadParse"
CborValue rootValue;
bool err = false;
- OC_LOG_V(INFO, TAG, "CBOR Parsing size: %d", payloadSize, payload);
+ OC_LOG_V(INFO, TAG, "CBOR Parsing size: %d %d", payloadSize, payloadType);
if((err = cbor_parser_init(payload, payloadSize, 0, &parser, &rootValue)) != false)
{
OC_LOG_V(ERROR, TAG, "CBOR Parser init failed: %d", err);
// enter the array
err = err || cbor_value_enter_container(&rootValue, &arrayValue);
- if(err || arrayValue.type != CborMapType)
+ if(err)
{
OC_LOG_V(ERROR, TAG, "CBOR payload parse failed :%d", err);
return OC_STACK_MALFORMED_RESPONSE;
case PAYLOAD_TYPE_SECURITY:
result = OCParseSecurityPayload(outPayload, &arrayValue);
break;
+ case PAYLOAD_TYPE_RD:
+ result = OCRDCborToPayload(&arrayValue, outPayload);
+ break;
default:
OC_LOG_V(ERROR, TAG, "ParsePayload Type default: %d", payloadType);
result = OC_STACK_ERROR;
return OC_STACK_NO_MEMORY;
}
- size_t resourceCount = 0;
- while(!err &&
- cbor_value_is_map(arrayVal))
+ if (cbor_value_is_array(arrayVal))
{
- OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
- if(!resource)
+ OCLinksPayload *linksPayload = NULL;
+ OCTagsPayload *tagsPayload = NULL;
+ while (cbor_value_is_container(arrayVal))
{
- OC_LOG(ERROR, TAG, "Memory allocation failed");
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
- }
- CborValue curVal;
+ linksPayload = NULL;
+ tagsPayload = NULL;
+ CborValue colResources;
+ CborError cborFindResult = cbor_value_enter_container(arrayVal, &colResources);
+ if (CborNoError != cborFindResult)
+ {
+ goto cbor_error;
+ }
- // Uri
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
- size_t len;
- err = err || cbor_value_dup_text_string(&curVal, &(resource->uri), &len, NULL);
+ if (OC_STACK_OK != OCTagsCborToPayload(&colResources, &tagsPayload))
+ {
+ OC_LOG(ERROR, TAG, "Tags cbor parsing failed.");
+ OCFreeTagsResource(tagsPayload);
+ goto cbor_error;
+ }
- // SID
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_SERVER_INSTANCE_ID, &curVal);
- err = err || cbor_value_dup_byte_string(&curVal, &(resource->sid), &len, NULL);
+ if (OC_STACK_OK != OCLinksCborToPayload(&colResources, &linksPayload))
+ {
+ OC_LOG(ERROR, TAG, "Links cbor parsing failed.");
+ OCFreeTagsResource(tagsPayload);
+ OCFreeLinksResource(linksPayload);
+ goto cbor_error;
+ }
- // Prop Tag
+ if (OC_STACK_OK != OCDiscoveryCollectionPayloadAddResource(out, tagsPayload, linksPayload))
+ {
+ OC_LOG(ERROR, TAG, "Memory allocation failed");
+ OCFreeLinksResource(linksPayload);
+ OCFreeTagsResource(tagsPayload);
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
+ }
+ if (CborNoError != cbor_value_advance(arrayVal))
+ {
+ OC_LOG(ERROR, TAG, "Cbor value advanced failed.");
+ goto cbor_error;
+ }
+ }
+ }
+ if (cbor_value_is_map(arrayVal))
+ {
+ size_t resourceCount = 0;
+ while(!err &&
+ cbor_value_is_map(arrayVal))
{
- err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_PROPERTY, &curVal);
- // ResourceTypes
- CborValue rtVal;
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE, &rtVal);
+ OCResourcePayload* resource = (OCResourcePayload*)OICCalloc(1, sizeof(OCResourcePayload));
+ if(!resource)
+ {
+ OC_LOG(ERROR, TAG, "Memory allocation failed");
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
+ }
+ CborValue curVal;
+
+ // Uri
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_HREF, &curVal);
+ size_t len;
+ err = err || cbor_value_dup_text_string(&curVal, &(resource->uri), &len, NULL);
- if (!err && cbor_value_is_text_string(&rtVal))
+ // SID
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_SERVER_INSTANCE_ID, &curVal);
+ err = err || cbor_value_dup_byte_string(&curVal, &(resource->sid), &len, NULL);
+
+ // Prop Tag
{
- char* input = NULL;
- char* savePtr;
- err = err || cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
+ err = err || cbor_value_map_find_value(arrayVal, OC_RSRVD_PROPERTY, &curVal);
+ // ResourceTypes
+ CborValue rtVal;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_RESOURCE_TYPE, &rtVal);
- if (input)
+ if (!err && cbor_value_is_text_string(&rtVal))
{
- char* curPtr = strtok_r(input, " ", &savePtr);
+ char* input = NULL;
+ char* savePtr;
+ err = err || cbor_value_dup_text_string(&rtVal, &input, &len, NULL);
- while (curPtr)
+ if (input)
{
- char* trimmed = InPlaceStringTrim(curPtr);
- if (trimmed[0] !='\0')
+ char* curPtr = strtok_r(input, " ", &savePtr);
+
+ while (curPtr)
{
- if (!OCResourcePayloadAddResourceType(resource, trimmed))
+ char* trimmed = InPlaceStringTrim(curPtr);
+ if (trimmed[0] !='\0')
{
- OICFree(resource->uri);
- OICFree(resource->sid);
- OCFreeOCStringLL(resource->types);
- OICFree(resource);
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
+ if (!OCResourcePayloadAddResourceType(resource, trimmed))
+ {
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OICFree(resource);
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
+ }
}
+ curPtr = strtok_r(NULL, " ", &savePtr);
}
- curPtr = strtok_r(NULL, " ", &savePtr);
+ OICFree(input);
}
- OICFree(input);
}
- }
-
- // Interface Types
- CborValue ifVal;
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &ifVal);
- if (!err && cbor_value_is_text_string(&ifVal))
- {
- char* input = NULL;
- char* savePtr;
- err = err || cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
+ // Interface Types
+ CborValue ifVal;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_INTERFACE, &ifVal);
- if (input)
+ if (!err && cbor_value_is_text_string(&ifVal))
{
- char* curPtr = strtok_r(input, " ", &savePtr);
+ char* input = NULL;
+ char* savePtr;
+ err = err || cbor_value_dup_text_string(&ifVal, &input, &len, NULL);
- while (curPtr)
+ if (input)
{
- char* trimmed = InPlaceStringTrim(curPtr);
- if (trimmed[0] !='\0')
+ char* curPtr = strtok_r(input, " ", &savePtr);
+
+ while (curPtr)
{
- if (!OCResourcePayloadAddInterface(resource, trimmed))
+ char* trimmed = InPlaceStringTrim(curPtr);
+ if (trimmed[0] !='\0')
{
- OICFree(resource->uri);
- OICFree(resource->sid);
- OCFreeOCStringLL(resource->types);
- OICFree(resource);
- OCDiscoveryPayloadDestroy(out);
- return OC_STACK_NO_MEMORY;
+ if (!OCResourcePayloadAddInterface(resource, trimmed))
+ {
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OICFree(resource);
+ OCDiscoveryPayloadDestroy(out);
+ return OC_STACK_NO_MEMORY;
+ }
}
+ curPtr = strtok_r(NULL, " ", &savePtr);
}
- curPtr = strtok_r(NULL, " ", &savePtr);
+ OICFree(input);
}
- OICFree(input);
}
- }
- // Policy
- {
- CborValue policyMap;
- err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_POLICY, &policyMap);
-
- // Bitmap
- CborValue val;
- err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
- uint64_t temp = 0;
- err = err || cbor_value_get_uint64(&val, &temp);
- resource->bitmap = (uint8_t)temp;
- // Secure Flag
- err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
- if(cbor_value_is_valid(&val))
+ // Policy
{
- err = err || cbor_value_get_boolean(&val, &(resource->secure));
- // Port
- CborValue port;
- err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
- &port);
- if(cbor_value_is_valid(&port))
+ CborValue policyMap;
+ err = err || cbor_value_map_find_value(&curVal, OC_RSRVD_POLICY, &policyMap);
+
+ // Bitmap
+ CborValue val;
+ err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_BITMAP, &val);
+ uint64_t temp = 0;
+ err = err || cbor_value_get_uint64(&val, &temp);
+ resource->bitmap = (uint8_t)temp;
+ // Secure Flag
+ err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_SECURE, &val);
+ if(cbor_value_is_valid(&val))
{
- err = err || cbor_value_get_uint64(&port, &temp);
- resource->port = (uint16_t)temp;
+ err = err || cbor_value_get_boolean(&val, &(resource->secure));
+ // Port
+ CborValue port;
+ err = err || cbor_value_map_find_value(&policyMap, OC_RSRVD_HOSTING_PORT,
+ &port);
+ if(cbor_value_is_valid(&port))
+ {
+ err = err || cbor_value_get_uint64(&port, &temp);
+ resource->port = (uint16_t)temp;
+ }
}
}
}
- }
- err = err || cbor_value_advance(arrayVal);
- if(err)
- {
- OICFree(resource->uri);
- OICFree(resource->sid);
- OCFreeOCStringLL(resource->types);
- OCFreeOCStringLL(resource->interfaces);
- OICFree(resource);
- OCDiscoveryPayloadDestroy(out);
- OC_LOG_V(ERROR, TAG, "CBOR in error condition", err);
- return OC_STACK_MALFORMED_RESPONSE;
+ err = err || cbor_value_advance(arrayVal);
+ if(err)
+ {
+ OICFree(resource->uri);
+ OICFree(resource->sid);
+ OCFreeOCStringLL(resource->types);
+ OCFreeOCStringLL(resource->interfaces);
+ OICFree(resource);
+ OCDiscoveryPayloadDestroy(out);
+ OC_LOG_V(ERROR, TAG, "CBOR in error condition: %d", err);
+ return OC_STACK_MALFORMED_RESPONSE;
+ }
+ ++resourceCount;
+ OCDiscoveryPayloadAddNewResource(out, resource);
}
- ++resourceCount;
- OCDiscoveryPayloadAddNewResource(out, resource);
}
if(err)
*outPayload = (OCPayload*)out;
return OC_STACK_OK;
}
+cbor_error:
+ OCDiscoveryCollectionPayloadDestroy(out);
+ return OC_STACK_MALFORMED_RESPONSE;
}
static OCStackResult OCParseDevicePayload(OCPayload** outPayload, CborValue* arrayVal)
#include "secureresourcemanager.h"
#include "cacommon.h"
#include "cainterface.h"
+#include "rdpayload.h"
+
+#ifdef WITH_RD
+#include "rd_server.h"
+#endif
+
#ifdef ROUTING_GATEWAY
#include "routingmanager.h"
#endif
return OC_STACK_OK;
}
+OCStackResult BuildVirtualCollectionResourceResponse(const OCResourceCollectionPayload *resourcePtr,
+ OCDiscoveryPayload *payload, OCDevAddr *devAddr)
+{
+ if (!resourcePtr || !payload)
+ {
+ return OC_STACK_INVALID_PARAM;
+ }
+ if (resourcePtr->tags && (resourcePtr->tags->bitmap & OC_SECURE))
+ {
+ if (GetSecurePortInfo(devAddr, &resourcePtr->tags->port) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Failed setting secure port.");
+ }
+ }
+ if (resourcePtr->tags && !resourcePtr->tags->baseURI)
+ {
+ resourcePtr->tags->baseURI = OICStrdup(devAddr->addr);
+ }
+ OCDiscoveryCollectionPayloadAddResource(payload, resourcePtr->tags, resourcePtr->setLinks);
+ return OC_STACK_OK;
+}
uint8_t IsCollectionResource (OCResource *resource)
{
return OCDoResponse(&response);
}
+#ifdef WITH_RD
+static OCStackResult checkResourceExistsAtRD(const char *interfaceType, const char *resourceType,
+ OCResourceCollectionPayload **repPayload)
+{
+ if (OCRDCheckPublishedResource(interfaceType, resourceType, repPayload) == OC_STACK_OK)
+ {
+ return OC_STACK_OK;
+ }
+ else
+ {
+ OC_LOG_V(ERROR, TAG, "The resource type or interface type doe not exist \
+ on the resource directory");
+ }
+ return OC_STACK_ERROR;
+}
+#endif
+
static OCStackResult HandleVirtualResource (OCServerRequest *request, OCResource* resource)
{
if (!request || !resource)
if(payload)
{
+ bool foundResourceAtRD = false;
for(;resource && discoveryResult == OC_STACK_OK; resource = resource->next)
{
- if(includeThisResourceInResponse(resource, filterOne, filterTwo))
+#ifdef WITH_RD
+ if (strcmp(resource->uri, OC_RSRVD_RD_URI) == 0)
+ {
+ OCResourceCollectionPayload *repPayload;
+ discoveryResult = checkResourceExistsAtRD(filterOne, filterTwo, &repPayload);
+ if (discoveryResult != OC_STACK_OK)
+ {
+ break;
+ }
+ discoveryResult = BuildVirtualCollectionResourceResponse(repPayload,
+ (OCDiscoveryPayload*)payload,
+ &request->devAddr);
+ foundResourceAtRD = true;
+ }
+#endif
+ if(!foundResourceAtRD && includeThisResourceInResponse(resource, filterOne, filterTwo))
{
discoveryResult = BuildVirtualResourceResponse(resource,
(OCDiscoveryPayload*)payload,
&request->devAddr);
}
}
- // Set discoveryResult appropriately if no 'valid' resources are available.
- if (((OCDiscoveryPayload*)payload)->resources == NULL)
+ // Set discoveryResult appropriately if no 'valid' resources are available
+ if (((OCDiscoveryPayload*)payload)->resources == NULL && !foundResourceAtRD)
{
discoveryResult = OC_STACK_NO_RESOURCE;
}
type = PAYLOAD_TYPE_SECURITY;
}
+
+ if (request && strcmp(request->resourceUrl, OC_RSRVD_RD_URI) == 0)
+ {
+ type = PAYLOAD_TYPE_RD;
+ }
+
result = FormOCEntityHandlerRequest(&ehRequest,
(OCRequestHandle)request,
request->method,
{
OC_LOG(INFO, TAG, "Observation registration requested");
+ ResourceObserver *obs = GetObserverUsingToken (request->requestToken,
+ request->tokenLength);
+
+ if (obs)
+ {
+ OC_LOG (INFO, TAG, "Observer with this token already present");
+ OC_LOG (INFO, TAG, "Possibly re-transmitted CON OBS request");
+ OC_LOG (INFO, TAG, "Not adding observer. Not responding to client");
+ OC_LOG (INFO, TAG, "The first request for this token is already ACKED.");
+
+ // server requests are usually free'd when the response is sent out
+ // for the request in ocserverrequest.c : HandleSingleResponse()
+ // Since we are making an early return and not responding, the server request
+ // needs to be deleted.
+ FindAndDeleteServerRequest (request);
+ return OC_STACK_OK;
+ }
+
result = GenerateObserverId(&ehRequest.obsInfo.obsId);
VERIFY_SUCCESS(result, OC_STACK_OK);
type = PAYLOAD_TYPE_REPRESENTATION;
}
#endif
+ else if (strcmp(cbNode->requestUri, OC_RSRVD_RD_URI) == 0)
+ {
+ type = PAYLOAD_TYPE_RD;
+ }
else
{
OC_LOG_V(ERROR, TAG, "Unknown Payload type in Discovery: %d %s",
cbNode->method == OC_REST_OBSERVE_ALL ||
cbNode->method == OC_REST_DELETE)
{
- OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
- cbNode->method, cbNode->requestUri);
- type = PAYLOAD_TYPE_REPRESENTATION;
+ char targetUri[MAX_URI_LENGTH];
+ snprintf(targetUri, MAX_URI_LENGTH, "%s?rt=%s",
+ OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
+ if (strcmp(targetUri, cbNode->requestUri) == 0)
+ {
+ type = PAYLOAD_TYPE_RD;
+ }
+ if (type == PAYLOAD_TYPE_INVALID)
+ {
+ OC_LOG_V(INFO, TAG, "Assuming PAYLOAD_TYPE_REPRESENTATION: %d %s",
+ cbNode->method, cbNode->requestUri);
+ type = PAYLOAD_TYPE_REPRESENTATION;
+ }
}
else
{
};
respInfo.info.messageId = coapID;
respInfo.info.numOptions = numOptions;
- respInfo.info.options = (CAHeaderOption_t*)options;
+
+ if (respInfo.info.numOptions)
+ {
+ respInfo.info.options =
+ (CAHeaderOption_t *)OICCalloc(respInfo.info.numOptions, sizeof(CAHeaderOption_t));
+ memcpy (respInfo.info.options, options,
+ sizeof(CAHeaderOption_t) * respInfo.info.numOptions);
+
+ }
+
respInfo.info.payload = NULL;
respInfo.info.token = token;
respInfo.info.tokenLength = tokenLength;
// resourceUri in the info field is cloned in the CA layer and
// thus ownership is still here.
OICFree (respInfo.info.resourceUri);
-
+ OICFree (respInfo.info.options);
if(CA_STATUS_OK != caResult)
{
OC_LOG(ERROR, TAG, "CASendResponse error");
return OC_STACK_OK;
}
+OCStackResult OCStartMulticastServer()
+{
+ if(stackState != OC_STACK_INITIALIZED)
+ {
+ OC_LOG(ERROR, TAG, "OCStack is not initalized. Cannot start multicast server.");
+ return OC_STACK_ERROR;
+ }
+ CAResult_t ret = CAStartListeningServer();
+ if (CA_STATUS_OK != ret)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed starting listening server: %d", ret);
+ return OC_STACK_ERROR;
+ }
+ return OC_STACK_OK;
+}
+
+OCStackResult OCStopMulticastServer()
+{
+ CAResult_t ret = CAStopListeningServer();
+ if (CA_STATUS_OK != ret)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed stopping listening server: %d", ret);
+ return OC_STACK_ERROR;
+ }
+ return OC_STACK_OK;
+}
+
CAMessageType_t qualityOfServiceToMessageType(OCQualityOfService qos)
{
switch (qos)
char *resourceUri = NULL;
char *resourceType = NULL;
- // To track if memory is allocated for additional header options
- uint8_t hdrOptionMemAlloc = 0;
-
// This validation is broken, but doesn't cause harm
size_t uriLen = strlen(requestUri );
if ((result = verifyUriQueryLength(requestUri , uriLen)) != OC_STACK_OK)
{
goto exit;
}
- hdrOptionMemAlloc = 1;
requestInfo.info.numOptions = numOptions + 1;
}
else
{
- requestInfo.info.options = (CAHeaderOption_t*)options;
requestInfo.info.numOptions = numOptions;
+ requestInfo.info.options =
+ (CAHeaderOption_t*) OICCalloc(numOptions, sizeof(CAHeaderOption_t));
+ memcpy(requestInfo.info.options, (CAHeaderOption_t*)options,
+ numOptions * sizeof(CAHeaderOption_t));
}
CopyDevAddrToEndpoint(devAddr, &endpoint);
OICFree(devAddr);
OICFree(resourceUri);
OICFree(resourceType);
- if (hdrOptionMemAlloc)
- {
- OICFree(requestInfo.info.options);
- }
+ OICFree(requestInfo.info.options);
return result;
}
return OC_STACK_ERROR;
}
}
-
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "rdpayload.h"
+
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "octypes.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
+
+#define TAG "OCRDPayload"
+
+#define CBOR_ROOT_ARRAY_LENGTH 1
+
+static CborError FindStringInMap(CborValue *map, char *tags, char **value);
+static CborError FindIntInMap(CborValue *map, char *tags, uint64_t *value);
+static CborError FindStringLLInMap(const CborValue *linksMap, char *tag, OCStringLL **links);
+static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen, const char *value);
+static int64_t ConditionalAddIntToMap(CborEncoder *map, const char *tags, const size_t size, const uint64_t *value);
+static int64_t AddStringLLToMap(CborEncoder *map, char *tag, const size_t size, OCStringLL *value);
+
+int64_t OCRDPayloadToCbor(const OCRDPayload *rdPayload, uint8_t *outPayload, size_t *size)
+{
+ if (!outPayload || !size)
+ {
+ OC_LOG(ERROR, TAG, "Invalid parameters.");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ CborEncoder encoder;
+ int flags = 0;
+ cbor_encoder_init(&encoder, outPayload, *size, flags);
+
+ CborEncoder rootArray;
+ CborError cborEncoderResult;
+ cborEncoderResult = cbor_encoder_create_array(&encoder, &rootArray, CBOR_ROOT_ARRAY_LENGTH);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating cbor array.");
+ goto cbor_error;
+ }
+
+ if (rdPayload->rdDiscovery)
+ {
+ CborEncoder map;
+ cborEncoderResult = cbor_encoder_create_map(&rootArray, &map, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating discovery map.");
+ goto cbor_error;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_NAME,
+ sizeof(OC_RSRVD_DEVICE_NAME) - 1, (char *)rdPayload->rdDiscovery->n.deviceName))
+ {
+ OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_DEVICE_NAME.");
+ goto cbor_error;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&map, OC_RSRVD_DEVICE_ID,
+ sizeof(OC_RSRVD_DEVICE_ID) - 1, (char *)rdPayload->rdDiscovery->di.id))
+ {
+ OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_DEVICE_ID.");
+ goto cbor_error;
+ }
+ uint64_t sel = (uint8_t) rdPayload->rdDiscovery->sel;
+ if (CborNoError != ConditionalAddIntToMap(&map, OC_RSRVD_RD_DISCOVERY_SEL,
+ sizeof(OC_RSRVD_RD_DISCOVERY_SEL) - 1, &sel))
+ {
+ OC_LOG(ERROR, TAG, "Failed setting OC_RSRVD_RD_DISCOVERY_SEL.");
+ goto cbor_error;
+ }
+ cborEncoderResult = cbor_encoder_close_container(&rootArray, &map);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing discovery map.");
+ goto cbor_error;
+ }
+ }
+ else if (rdPayload->rdPublish)
+ {
+ CborEncoder colArray;
+ cborEncoderResult = cbor_encoder_create_array(&rootArray, &colArray, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating collection array.");
+ goto cbor_error;
+ }
+
+ OCResourceCollectionPayload *rdPublish = rdPayload->rdPublish;
+ while (rdPublish)
+ {
+ if (OC_STACK_OK != OCTagsPayloadToCbor(rdPublish->tags, &colArray))
+ {
+ OC_LOG(ERROR, TAG, "Failed creating tags payload.");
+ goto cbor_error;
+ }
+ if (OC_STACK_OK != OCLinksPayloadToCbor(rdPublish->setLinks, &colArray))
+ {
+ OC_LOG(ERROR, TAG, "Failed creating links payload.");
+ goto cbor_error;
+ }
+ rdPublish = rdPublish->next;
+ }
+ cborEncoderResult = cbor_encoder_close_container(&rootArray, &colArray);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing collection array.");
+ goto cbor_error;
+ }
+ }
+ cborEncoderResult = cbor_encoder_close_container(&encoder, &rootArray);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing root array container. ");
+ goto cbor_error;
+ }
+
+ *size = encoder.ptr - outPayload;
+ return OC_STACK_OK;
+
+cbor_error:
+ OICFree(outPayload);
+ return OC_STACK_ERROR;
+}
+
+OCStackResult OCTagsPayloadToCbor(OCTagsPayload *tags, CborEncoder *setMap)
+{
+ CborEncoder tagsMap;
+ CborError cborEncoderResult = cbor_encoder_create_map(setMap, &tagsMap, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating TAGS map.");
+ return OC_STACK_ERROR;
+ }
+
+ if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_NAME,
+ sizeof(OC_RSRVD_DEVICE_NAME) - 1, (char *)tags->n.deviceName))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_DEVICE_NAME in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DEVICE_ID,
+ sizeof(OC_RSRVD_DEVICE_ID) - 1, (char *)tags->di.id))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_DEVICE_ID in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_RTS,
+ sizeof(OC_RSRVD_RTS) - 1, (char *)tags->rts))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_RTS in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_DREL,
+ sizeof(OC_RSRVD_DREL) - 1, (char *)tags->drel))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_DREL in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&tagsMap, OC_RSRVD_BASE_URI,
+ sizeof(OC_RSRVD_BASE_URI) - 1, (char *)tags->baseURI))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_BASE_URI in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ uint64_t temp = (uint64_t)tags->bitmap;
+ if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_BITMAP,
+ sizeof(OC_RSRVD_BITMAP) - 1, &temp))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_BITMAP in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ temp = (uint64_t)tags->port;
+ if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_HOSTING_PORT,
+ sizeof(OC_RSRVD_HOSTING_PORT) - 1, &temp))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_HOSTING_PORT in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ temp = (uint64_t)tags->ins;
+ if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_INS,
+ sizeof(OC_RSRVD_INS) - 1, &temp))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_INS in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ temp = (uint64_t)tags->ttl;
+ if (CborNoError != ConditionalAddIntToMap(&tagsMap, OC_RSRVD_TTL,
+ sizeof(OC_RSRVD_TTL) - 1, &temp))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_TTL in TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ cborEncoderResult = cbor_encoder_close_container(setMap, &tagsMap);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing TAGS map.");
+ return OC_STACK_ERROR;
+ }
+ return OC_STACK_OK;
+}
+
+OCStackResult OCLinksPayloadToCbor(OCLinksPayload *rtPtr, CborEncoder *setMap)
+{
+ CborEncoder linksArray;
+ CborError cborEncoderResult;
+
+ cborEncoderResult = cbor_encoder_create_array(setMap, &linksArray, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating LINKS array.");
+ return OC_STACK_ERROR;
+ }
+ while (rtPtr)
+ {
+ CborEncoder linksMap;
+ cborEncoderResult = cbor_encoder_create_map(&linksArray, &linksMap,
+ CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed creating LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_HREF,
+ sizeof(OC_RSRVD_HREF) - 1, rtPtr->href))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_HREF in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_REL,
+ sizeof(OC_RSRVD_REL) - 1, rtPtr->rel))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_REL in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_TITLE,
+ sizeof(OC_RSRVD_TITLE) - 1, rtPtr->title))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_TITLE in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != ConditionalAddTextStringToMap(&linksMap, OC_RSRVD_URI,
+ sizeof(OC_RSRVD_URI) - 1, rtPtr->uri))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_URI in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != AddStringLLToMap(&linksMap, OC_RSRVD_RESOURCE_TYPE,
+ sizeof(OC_RSRVD_RESOURCE_TYPE) - 1, rtPtr->rt))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_RESOURCE_TYPE in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != AddStringLLToMap(&linksMap, OC_RSRVD_INTERFACE,
+ sizeof(OC_RSRVD_INTERFACE) - 1, rtPtr->itf))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_INTERFACE in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != AddStringLLToMap(&linksMap, OC_RSRVD_MEDIA_TYPE,
+ sizeof(OC_RSRVD_MEDIA_TYPE) - 1, rtPtr->mt))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_MEDIA_TYPE in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ uint64_t temp = (uint64_t)rtPtr->ins;
+ if (CborNoError != ConditionalAddIntToMap(&linksMap, OC_RSRVD_INS,
+ sizeof(OC_RSRVD_INS) - 1, &temp))
+ {
+ OC_LOG(ERROR, TAG, "Failed adding OC_RSRVD_INS in LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ cborEncoderResult = cbor_encoder_close_container(&linksArray, &linksMap);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing LINKS map.");
+ return OC_STACK_ERROR;
+ }
+ rtPtr = rtPtr->next;
+ }
+ cborEncoderResult = cbor_encoder_close_container(setMap, &linksArray);
+ if (CborNoError != cborEncoderResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed closing LINKS array.");
+ return OC_STACK_ERROR;;
+ }
+ return OC_STACK_OK;
+}
+
+OCStackResult OCRDCborToPayload(const CborValue *cborPayload, OCPayload **outPayload)
+{
+ CborValue *rdCBORPayload = (CborValue *)cborPayload;
+ CborError cborFindResult;
+
+ OCRDPayload *rdPayload = OCRDPayloadCreate();
+ if (!rdPayload)
+ {
+ goto no_memory;
+ }
+
+ if (cbor_value_is_array(rdCBORPayload))
+ {
+ OCLinksPayload *linksPayload = NULL;
+ OCTagsPayload *tagsPayload = NULL;
+
+ while (cbor_value_is_container(rdCBORPayload))
+ {
+ // enter tags map
+ CborValue tags;
+ cborFindResult = cbor_value_enter_container(rdCBORPayload, &tags);
+ if (cborFindResult != CborNoError)
+ {
+ goto cbor_error;
+ }
+ if (OC_STACK_OK != OCTagsCborToPayload(&tags, &tagsPayload))
+ {
+ OCFreeTagsResource(tagsPayload);
+ goto cbor_error;
+ }
+ OCTagsLog(DEBUG, tagsPayload);
+ if (OC_STACK_OK != OCLinksCborToPayload(&tags, &linksPayload))
+ {
+ OCFreeLinksResource(linksPayload);
+ OCFreeTagsResource(tagsPayload);
+ goto cbor_error;
+ }
+ OCLinksLog(DEBUG, linksPayload);
+ // Move from tags payload to links array.
+ if (CborNoError != cbor_value_advance(rdCBORPayload))
+ {
+ OC_LOG(DEBUG, TAG, "Failed advancing from tags payload to links.");
+ OCFreeLinksResource(linksPayload);
+ OCFreeTagsResource(tagsPayload);
+ goto cbor_error;
+ }
+ }
+ rdPayload->rdPublish = OCCopyCollectionResource(tagsPayload, linksPayload);
+ if (!rdPayload->rdPublish)
+ {
+ goto cbor_error;
+ }
+ }
+ else if (cbor_value_is_map(rdCBORPayload))
+ {
+ char *name = NULL;
+ if (CborNoError != FindStringInMap(rdCBORPayload, OC_RSRVD_DEVICE_NAME, &name))
+ {
+ goto cbor_error;
+ }
+ char *id = NULL;
+ if (CborNoError != FindStringInMap(rdCBORPayload, OC_RSRVD_DEVICE_ID, &id))
+ {
+ goto cbor_error;
+ }
+ uint64_t biasFactor = 0;
+ if (CborNoError != FindIntInMap(rdCBORPayload, OC_RSRVD_RD_DISCOVERY_SEL, &biasFactor))
+ {
+ goto cbor_error;
+ }
+ rdPayload->rdDiscovery = OCRDDiscoveryPayloadCreate(name, id, (uint8_t)biasFactor);
+ if (!rdPayload->rdDiscovery)
+ {
+ goto no_memory;
+ }
+ OICFree(id);
+ OICFree(name);
+ cborFindResult = cbor_value_advance(rdCBORPayload);
+ if (CborNoError != cborFindResult)
+ {
+ goto cbor_error;
+ }
+ }
+ OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+ *outPayload = (OCPayload *)rdPayload;
+ return OC_STACK_OK;
+no_memory:
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ OCRDPayloadDestroy(rdPayload);
+ return OC_STACK_NO_MEMORY;
+
+cbor_error:
+ OCRDPayloadDestroy(rdPayload);
+ return OC_STACK_ERROR;
+}
+
+static CborError FindStringInMap(CborValue *map, char *tags, char **value)
+{
+ CborValue curVal;
+ size_t len;
+ CborError cborFindResult = cbor_value_map_find_value(map, tags, &curVal);
+ if (CborNoError == cborFindResult && cbor_value_is_text_string(&curVal))
+ {
+ cborFindResult = cbor_value_dup_text_string(&curVal, value, &len, NULL);
+ if (CborNoError != cborFindResult)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed finding value for tag %s .", tags);
+ return cborFindResult;
+ }
+ }
+ return CborNoError;
+}
+
+static CborError FindIntInMap(CborValue *map, char *tags, uint64_t *value)
+{
+ CborValue curVal;
+ CborError cborFindResult = cbor_value_map_find_value(map, tags, &curVal);
+ if (CborNoError == cborFindResult && cbor_value_is_unsigned_integer(&curVal))
+ {
+ cborFindResult = cbor_value_get_uint64(&curVal, value);
+ if (CborNoError != cborFindResult)
+ {
+ OC_LOG_V(ERROR, TAG, "Failed finding value for tag %s .", tags);
+ return cborFindResult;
+ }
+ }
+ return CborNoError;
+}
+
+static CborError FindStringLLInMap(const CborValue *linksMap, char *tag, OCStringLL **links)
+{
+ size_t len;
+ CborError cborFindResult;
+ CborValue rtArray;
+ cborFindResult = cbor_value_map_find_value(linksMap, tag, &rtArray);
+ if (CborNoError != cborFindResult)
+ {
+ return CborUnknownError;
+ }
+ CborValue rtVal;
+ cborFindResult = cbor_value_enter_container(&rtArray, &rtVal);
+ if (CborNoError != cborFindResult)
+ {
+ return CborUnknownError;
+ }
+ OCStringLL* llPtr = *links;
+ while (cbor_value_is_text_string(&rtVal))
+ {
+ if (llPtr == NULL)
+ {
+ llPtr = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ if (!llPtr)
+ {
+ return CborUnknownError;
+ }
+ *links = llPtr;
+ }
+ else if(llPtr)
+ {
+ while (llPtr->next)
+ {
+ llPtr = llPtr->next;
+ }
+ llPtr->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ if (!llPtr->next)
+ {
+ return CborUnknownError;
+ }
+ }
+ cborFindResult = cbor_value_dup_text_string(&rtVal, &(llPtr->value), &len, NULL);
+ if (CborNoError != cborFindResult)
+ {
+ return CborUnknownError;
+ }
+ cborFindResult = cbor_value_advance(&rtVal);
+ if (CborNoError != cborFindResult)
+ {
+ return CborUnknownError;
+ }
+ }
+
+ cborFindResult = cbor_value_leave_container(&rtArray, &rtVal);
+ return cborFindResult;
+}
+
+OCStackResult OCTagsCborToPayload(CborValue *tagsMap, OCTagsPayload **tagsPayload)
+{
+ OCTagsPayload *tags = (OCTagsPayload *)OICCalloc(1, sizeof(OCTagsPayload));
+ if (!tags)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ if (cbor_value_is_map(tagsMap))
+ {
+ if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_DEVICE_NAME, &tags->n.deviceName))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_DREL, &tags->drel))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_RTS, &tags->rts))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_BASE_URI, &tags->baseURI))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ char *id = NULL;
+ if (CborNoError != FindStringInMap(tagsMap, OC_RSRVD_DEVICE_ID, &id))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ if (id)
+ {
+ OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, id);
+ tags->di.id_length = MAX_IDENTITY_SIZE;
+ OICFree(id);
+ }
+ uint64_t temp;
+ if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_HOSTING_PORT, &temp))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ tags->port = (uint16_t) temp;
+ if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_BITMAP, &temp))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ tags->bitmap = (uint8_t) temp;
+ if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_INS, &temp))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ tags->ins = (uint8_t) temp;
+ if (CborNoError != FindIntInMap(tagsMap, OC_RSRVD_TTL, &temp))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ tags->ttl = (uint32_t) temp;
+
+ if (CborNoError != cbor_value_advance(tagsMap))
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_ERROR;
+ }
+ }
+ *tagsPayload = tags;
+ return OC_STACK_OK;
+}
+
+OCStackResult OCLinksCborToPayload(CborValue *linksArray, OCLinksPayload **linksPayload)
+{
+ CborValue linksMap;
+ CborError cborFindResult = cbor_value_enter_container(linksArray, &linksMap);
+ if (CborNoError != cborFindResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed enter links map");
+ return OC_STACK_ERROR;
+ }
+
+ while (cbor_value_is_map(&linksMap))
+ {
+ OCLinksPayload *setLinks = (OCLinksPayload *)OICCalloc(1, sizeof(OCLinksPayload));
+ if (!setLinks)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ OCFreeLinksResource(*linksPayload);
+ return OC_STACK_NO_MEMORY;
+ }
+ cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_HREF, &setLinks->href);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_REL, &setLinks->rel);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+
+ cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_TITLE, &setLinks->title);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ cborFindResult = FindStringInMap(&linksMap, OC_RSRVD_URI, &setLinks->uri);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ cborFindResult = FindStringLLInMap(&linksMap, OC_RSRVD_RESOURCE_TYPE, &setLinks->rt);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ cborFindResult = FindStringLLInMap(&linksMap, OC_RSRVD_INTERFACE, &setLinks->itf);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ cborFindResult = FindStringLLInMap(&linksMap, OC_RSRVD_MEDIA_TYPE, &setLinks->mt);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ uint64_t temp;
+ cborFindResult = FindIntInMap(&linksMap, OC_RSRVD_INS, &temp);
+ if (CborNoError != cborFindResult)
+ {
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ setLinks->ins = (uint8_t) temp;
+
+ if (!*linksPayload)
+ {
+ *linksPayload = setLinks;
+ }
+ else
+ {
+ OCLinksPayload *temp = *linksPayload;
+ while (temp->next)
+ {
+ temp = temp->next;
+ }
+ temp->next = setLinks;
+ }
+ cborFindResult = cbor_value_advance(&linksMap);
+ if (CborNoError != cborFindResult)
+ {
+ OC_LOG(ERROR, TAG, "Failed advancing links map");
+ OCFreeLinksResource(*linksPayload);
+ OCFreeLinksResource(setLinks);
+ return OC_STACK_ERROR;
+ }
+ }
+ return OC_STACK_OK;
+}
+
+static int64_t AddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+ const char* value)
+{
+ return cbor_encode_text_string(map, key, keylen) |
+ cbor_encode_text_string(map, value, strlen(value));
+}
+
+static int64_t ConditionalAddTextStringToMap(CborEncoder* map, const char* key, size_t keylen,
+ const char* value)
+{
+ return value ? AddTextStringToMap(map, key, keylen, value) : 0;
+}
+
+static int64_t ConditionalAddIntToMap(CborEncoder *map, const char *tags, const size_t size,
+ const uint64_t *value)
+{
+ return (*value) ? (cbor_encode_text_string(map, tags, size) |
+ cbor_encode_uint(map, *value)): 0;
+}
+
+static int64_t AddStringLLToMap(CborEncoder *map, char *tag, const size_t size, OCStringLL *value)
+{
+ CborEncoder array;
+ CborError cborEncoderResult;
+ cborEncoderResult = cbor_encode_text_string(map, tag, size);
+ if (CborNoError != cborEncoderResult)
+ {
+ return cborEncoderResult;
+ }
+ cborEncoderResult = cbor_encoder_create_array(map, &array, CborIndefiniteLength);
+ if (CborNoError != cborEncoderResult)
+ {
+ return cborEncoderResult;
+ }
+ OCStringLL *strType = value;
+ while (strType)
+ {
+ cborEncoderResult = cbor_encode_text_string(&array, strType->value, strlen(strType->value));
+ if (CborNoError != cborEncoderResult)
+ {
+ return cborEncoderResult;
+ }
+ strType = strType->next;
+ }
+ cborEncoderResult = cbor_encoder_close_container(map, &array);
+ if (CborNoError != cborEncoderResult)
+ {
+ return cborEncoderResult;
+ }
+ return cborEncoderResult;
+}
+
+OCRDPayload *OCRDPayloadCreate()
+{
+ OCRDPayload *rdPayload = (OCRDPayload *)OICCalloc(1, sizeof(OCRDPayload));
+
+ if (!rdPayload)
+ {
+ return NULL;
+ }
+
+ rdPayload->base.type = PAYLOAD_TYPE_RD;
+
+ return rdPayload;
+}
+
+OCRDDiscoveryPayload *OCRDDiscoveryPayloadCreate(const char *deviceName, const char *id, int biasFactor)
+{
+ OCRDDiscoveryPayload *discoveryPayload = (OCRDDiscoveryPayload *)OICCalloc(1, sizeof(OCRDDiscoveryPayload));
+
+ if (!discoveryPayload)
+ {
+ return NULL;
+ }
+
+ if (deviceName)
+ {
+ discoveryPayload->n.deviceName = OICStrdup(deviceName);
+ if (!discoveryPayload->n.deviceName)
+ {
+ OICFree(discoveryPayload);
+ return NULL;
+ }
+ }
+ if (id)
+ {
+ OICStrcpy((char*)discoveryPayload->di.id, MAX_IDENTITY_SIZE, id);
+ }
+
+ discoveryPayload->sel = biasFactor;
+
+ return discoveryPayload;
+}
+
+void OCRDPayloadDestroy(OCRDPayload *payload)
+{
+ if (!payload)
+ {
+ return;
+ }
+
+ if (payload->rdDiscovery)
+ {
+ if (payload->rdDiscovery->n.deviceName)
+ {
+ OICFree(payload->rdDiscovery->n.deviceName);
+ }
+ OICFree(payload->rdDiscovery);
+ }
+
+ if (payload->rdPublish)
+ {
+ for (OCResourceCollectionPayload *col = payload->rdPublish; col; )
+ {
+ if (col->setLinks)
+ {
+ OCFreeLinksResource(col->setLinks);
+ }
+
+ if (col->tags)
+ {
+ OCFreeTagsResource(col->tags);
+ }
+ OCResourceCollectionPayload *temp = col->next;
+ OICFree(col);
+ col = temp;
+ }
+ }
+
+ OICFree(payload);
+}
+
+OCTagsPayload* OCCopyTagsResources(const char *deviceName, const unsigned char *id, const char *baseURI,
+ uint8_t bitmap, uint16_t port, uint8_t ins, const char *rts,const char *drel, uint32_t ttl)
+{
+ OCTagsPayload *tags = (OCTagsPayload *)OICCalloc(1, sizeof(OCTagsPayload));
+ if (!tags)
+ {
+ return NULL;
+ }
+ if (deviceName)
+ {
+ tags->n.deviceName = OICStrdup(deviceName);
+ if (!tags->n.deviceName)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (id)
+ {
+ OICStrcpy((char*)tags->di.id, MAX_IDENTITY_SIZE, (char *)id);
+ if (!tags->di.id)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (baseURI)
+ {
+ tags->baseURI = OICStrdup(baseURI);
+ if (!tags->baseURI)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ tags->bitmap = bitmap;
+ tags->port = port;
+ tags->ins = ins;
+ if (rts)
+ {
+ tags->rts = OICStrdup(rts);
+ if (!tags->rts)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (drel)
+ {
+ tags->drel = OICStrdup(drel);
+ if (!tags->drel)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ tags->ttl = ttl;
+ return tags;
+
+memory_allocation_failed:
+ OC_LOG(ERROR, TAG, "Memory allocation failed.");
+ OCFreeTagsResource(tags);
+ return NULL;
+}
+
+OCLinksPayload* OCCopyLinksResources(const char *href, OCStringLL *rt, OCStringLL *itf,
+ const char *rel, bool obs, const char *title, const char *uri, uint8_t ins, OCStringLL *mt)
+{
+ OCLinksPayload *links = (OCLinksPayload *)OICCalloc(1, sizeof(OCLinksPayload));
+ if (!links)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ return NULL;
+ }
+ if (href)
+ {
+ links->href = OICStrdup(href);
+ if (!links->href)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (rt)
+ {
+ links->rt = CloneOCStringLL(rt);
+ if (!links->rt)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (itf)
+ {
+ links->itf = CloneOCStringLL(itf);
+ if (!links->itf)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (rel)
+ {
+ links->rel = OICStrdup(rel);
+ if (!links->rel)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ links->obs = obs;
+ if (title)
+ {
+ links->title = OICStrdup(title);
+ if (!links->title)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ if (uri)
+ {
+ links->uri = OICStrdup(uri);
+ if (!links->uri)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ links->ins = ins;
+ if (mt)
+ {
+ links->mt = CloneOCStringLL(mt);
+ if (!links->mt)
+ {
+ goto memory_allocation_failed;
+ }
+ }
+ links->next = NULL;
+ return links;
+
+memory_allocation_failed:
+ OC_LOG(ERROR, TAG, "Memory allocation failed.");
+ OCFreeLinksResource(links);
+ return NULL;
+}
+
+void OCLinksAddResource(OCDiscoveryPayload *payload, const char *href, OCStringLL *rt,
+ OCStringLL *itf, const char *rel, bool obs, const char *title, const char *uri,
+ uint8_t ins, OCStringLL *mt)
+{
+ if(!payload->collectionResources->setLinks)
+ {
+ payload->collectionResources->setLinks =
+ OCCopyLinksResources(href, rt, itf, rel, obs, title, uri, ins, mt);
+ }
+ else
+ {
+ OCLinksPayload *p = payload->collectionResources->setLinks;
+ while (p->next)
+ {
+ p = p->next;
+ }
+ p->next = OCCopyLinksResources(href, rt, itf, rel, obs, title, uri, ins, mt);
+ }
+}
+
+OCResourceCollectionPayload* OCCopyCollectionResource(OCTagsPayload *tags, OCLinksPayload *links)
+{
+ if (!tags || !links)
+ {
+ return NULL;
+ }
+ OCResourceCollectionPayload *pl = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
+ if(!pl)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory for the OCResourceCollectionPayload.");
+ return NULL;
+ }
+ pl->tags = tags;
+ pl->setLinks = links;
+
+ return pl;
+}
+
+OCStackResult OCDiscoveryCollectionPayloadAddResource(OCDiscoveryPayload *payload, OCTagsPayload *tags, OCLinksPayload *links)
+{
+ OCResourceCollectionPayload* res = OCCopyCollectionResource(tags, links);
+ if (res == NULL)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ if(!payload->collectionResources)
+ {
+ payload->collectionResources = res;
+ }
+ else
+ {
+ OCResourceCollectionPayload *p = payload->collectionResources;
+ while(p->next)
+ {
+ p = p->next;
+ }
+ p->next = res;
+ }
+ return OC_STACK_OK;
+}
+
+void OCFreeLinksResource(OCLinksPayload *payload)
+{
+ if (!payload)
+ {
+ return;
+ }
+ OICFree(payload->href);
+ OCFreeOCStringLL(payload->rt);
+ OCFreeOCStringLL(payload->itf);
+ OICFree(payload->rel);
+ OICFree(payload->title);
+ OICFree(payload->uri);
+ OCFreeOCStringLL(payload->mt);
+ OCFreeLinksResource(payload->next);
+ OICFree(payload);
+}
+
+void OCFreeTagsResource(OCTagsPayload *payload)
+{
+ if (!payload)
+ {
+ return;
+ }
+ OICFree(payload->n.deviceName);
+ OICFree(payload->baseURI);
+ OICFree(payload->rts);
+ OICFree(payload->drel);
+ OICFree(payload);
+}
+
+void OCFreeCollectionResource(OCResourceCollectionPayload *payload)
+{
+ if (!payload)
+ {
+ return;
+ }
+ if (payload->tags)
+ {
+ OCFreeTagsResource(payload->tags);
+ }
+ if (payload->setLinks)
+ {
+ OCFreeLinksResource(payload->setLinks);
+ }
+ OCFreeCollectionResource(payload->next);
+ OICFree(payload);
+}
+
+void OCDiscoveryCollectionPayloadDestroy(OCDiscoveryPayload* payload)
+{
+ if(!payload)
+ {
+ return;
+ }
+
+ OCFreeCollectionResource(payload->collectionResources);
+ OICFree(payload);
+}
+
+
+void OCTagsLog(const LogLevel level, const OCTagsPayload *tags)
+{
+ if (tags)
+ {
+ if (tags->n.deviceName)
+ {
+ OC_LOG_V(level, TAG, " Device Name : %s ",tags->n.deviceName);
+ }
+ if (tags->baseURI)
+ {
+ OC_LOG_V(level, TAG, " Base URI : %s ",tags->baseURI);
+ }
+ OC_LOG_V(level, TAG, " Device ID : %s ",tags->di.id);
+ OC_LOG_V(level, TAG, " Bitmap : %d ",tags->bitmap);
+ OC_LOG_V(level, TAG, " Port : %d ",tags->port);
+ OC_LOG_V(level, TAG, " Ins : %d ",tags->ins);
+ OC_LOG_V(level, TAG, " Ttl : %d ",tags->ttl);
+
+ if (tags->rts)
+ {
+ OC_LOG_V(level, TAG, " RTS : %s ",tags->rts);
+ }
+ if (tags->drel)
+ {
+ OC_LOG_V(level, TAG, " DREL : %s ",tags->drel);
+ }
+ }
+}
+
+void OCLinksLog(const LogLevel level, const OCLinksPayload *links)
+{
+ while (links)
+ {
+ if (links->href)
+ {
+ OC_LOG_V(level, TAG, " href: %s ",links->href);
+ }
+ OC_LOG(level, TAG, " RT: ");
+ OCStringLL *rt = links->rt;
+ while (rt)
+ {
+ if (rt->value)
+ {
+ OC_LOG_V(level, TAG, " %s", rt->value);
+ }
+ rt = rt->next;
+ }
+ OC_LOG(level, TAG, " IF: ");
+ OCStringLL *itf = links->itf;
+ while (itf)
+ {
+ if (itf->value)
+ {
+ OC_LOG_V(level, TAG, " %s", itf->value);
+ }
+ itf = itf->next;
+ }
+ OC_LOG(level, TAG, " MT: ");
+ OCStringLL *mt = links->mt;
+ while (mt)
+ {
+ if (mt->value)
+ {
+ OC_LOG_V(level, TAG, " %s", mt->value);
+ }
+ mt = mt->next;
+ }
+ OC_LOG_V(level, TAG, " INS: %d", links->ins);
+ OC_LOG_V(level, TAG, " OBS: %d", links->obs);
+ if (links->rel)
+ {
+ OC_LOG_V(level, TAG, " REL: %s", links->rel);
+ }
+ if (links->title)
+ {
+ OC_LOG_V(level, TAG, " TITLE: %s", links->title);
+ }
+ if (links->uri)
+ {
+ OC_LOG_V(level, TAG, " URI: %s", links->uri);
+ }
+ links = links->next;
+ }
+}
EXPECT_EQ(OC_STACK_OK, OCStop());
}
+TEST(StackStart, SetPlatformInfoWithClientMode)
+{
+ itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
+ EXPECT_EQ(OC_STACK_OK, OCInit("127.0.0.1", 5683, OC_CLIENT));
+
+ OCPlatformInfo info =
+ {
+ gDeviceUUID,
+ gManufacturerName,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0
+ };
+ EXPECT_EQ(OC_STACK_ERROR, OCSetPlatformInfo(info));
+ EXPECT_EQ(OC_STACK_OK, OCStop());
+}
+
TEST(StackStart, SetPlatformInfoWithNoPlatformID)
{
itst::DeadmanTimer killSwitch(SHORT_TEST_TIMEOUT);
../csdk/stack/include/octypes.h \
../csdk/stack/include/ocstackconfig.h \
guides \
- ../../service/things-manager/sdk/inc \
- ../../service/soft-sensor-manager/SDK/cpp/include \
- ../../service/protocol-plugin/plugin-manager/src/PluginManager.h \
- ../../service/notification-manager/NotificationManager/include/hosting.h \
../../service/resource-encapsulation/include \
+ ../../service/resource-hosting/include \
+ ../../service/resource-container/include \
+ ../../service/resource-container/bundle-api/include \
+ ../../service/things-manager/sdk/inc \
+ ../../service/easy-setup/sdk/enrollee/api \
+ ../../service/resource-directory/include
# This tag can be used to specify the character encoding of the source files
# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
static OCStackResult getDevInfoFromNetwork(unsigned short timeout,
DeviceList_t &ownedDevList,
DeviceList_t &unownedDevList);
-
+ /**
+ * Server API to register callback to display stack generated PIN.
+ *
+ * @param[in] GeneratePinCallback Method to display generated PIN.
+ * @return OC_STACK_OK in case of success and other value otherwise.
+ */
+ static OCStackResult setDisplayPinCB(GeneratePinCallback);
};
/**
: m_clientWrapper(cw), m_devAddr(devAddr)
{
OCResourcePayload* res = payload->resources;
-
- while(res)
+ OCResourceCollectionPayload* colRes = payload->collectionResources;
+ if (res)
{
- char uuidString[UUID_STRING_SIZE];
- if(OCConvertUuidToString(res->sid, uuidString) != RAND_UUID_OK)
+ while(res)
{
- uuidString[0]= '\0';
- }
+ char uuidString[UUID_STRING_SIZE];
+ if(OCConvertUuidToString(res->sid, uuidString) != RAND_UUID_OK)
+ {
+ uuidString[0]= '\0';
+ }
- if (res->secure)
- {
- m_devAddr.flags =
- (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
- }
+ if (res->secure)
+ {
+ m_devAddr.flags =
+ (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
+ }
- if (res->port != 0)
- {
- m_devAddr.port = res->port;
- }
+ if (res->port != 0)
+ {
+ m_devAddr.port = res->port;
+ }
- m_resources.push_back(std::shared_ptr<OC::OCResource>(
- new OC::OCResource(m_clientWrapper, m_devAddr,
- std::string(res->uri),
- std::string(uuidString),
- (res->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
- StringLLToVector(res->types),
- StringLLToVector(res->interfaces)
- )));
- res = res->next;
+ m_resources.push_back(std::shared_ptr<OC::OCResource>(
+ new OC::OCResource(m_clientWrapper, m_devAddr,
+ std::string(res->uri),
+ std::string(uuidString),
+ (res->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
+ StringLLToVector(res->types),
+ StringLLToVector(res->interfaces)
+ )));
+ res = res->next;
+ }
}
+ else if (colRes)
+ {
+ while(colRes)
+ {
+ if (colRes->tags->bitmap & OC_SECURE)
+ {
+ m_devAddr.flags =
+ (OCTransportFlags)(OC_FLAG_SECURE | m_devAddr.flags);
+ }
+ if (colRes->tags->port != 0)
+ {
+ m_devAddr.port = colRes->tags->port;
+ }
+
+ m_resources.push_back(std::shared_ptr<OC::OCResource>(
+ new OC::OCResource(m_clientWrapper, m_devAddr,
+ std::string(colRes->setLinks->href),
+ std::string((char*)colRes->tags->di.id),
+ (colRes->tags->bitmap & OC_OBSERVABLE) == OC_OBSERVABLE,
+ StringLLToVector(colRes->setLinks->rt),
+ StringLLToVector(colRes->setLinks->itf)
+ )));
+ colRes = colRes->next;
+ }
+ }
}
const std::vector<std::shared_ptr<OCResource>>& Resources() const
return result;
}
+ OCStackResult OCSecure::setDisplayPinCB(GeneratePinCallback displayPin)
+ {
+ if(!displayPin)
+ {
+ oclog() <<"displayPin can't be null";
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OCStackResult result = OC_STACK_OK;
+ auto cLock = OCPlatform_impl::Instance().csdkLock().lock();
+
+ if(cLock)
+ {
+ std::lock_guard<std::recursive_mutex> lock(*cLock);
+ SetGeneratePinCB(displayPin);
+ }
+ else
+ {
+ oclog() <<"Mutex not found";
+ result = OC_STACK_ERROR;
+ }
+
+ return result;
+ }
+
void OCSecureResource::callbackWrapper(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
{
PMResultList_t *results = nullptr;
owned, unowned));
}
+ TEST(SetDisplayPinCBTest, SetDisplayPinCBTestNullCB)
+ {
+ EXPECT_EQ(OC_STACK_INVALID_PARAM, OCSecure::setDisplayPinCB(nullptr));
+ }
+
TEST(ProvisionAclTest, ProvisionAclTestNullAcl)
{
OCSecureResource device;
SConscript('things-manager/SConscript')
# Build notification manager project
- SConscript('notification-manager/SConscript')
+ SConscript('resource-hosting/SConscript')
# Build resource-encapsulation project
SConscript('resource-encapsulation/SConscript')
+ # Build resource-container project
+ if target_os not in ['android']:
+ SConscript('resource-container/SConscript')
+
# Build simulator module
if target_os in ['linux'] and env.get('SIMULATOR', False):
SConscript('simulator/SConscript')
+
+ # Build resource directory project
+ if env.get('WITH_RD') == '1':
+ SConscript('resource-directory/SConscript')
+
+# Build EasySetup module
+if target_os in ['arduino','android', 'linux']:
+ SConscript('easy-setup/SConscript')
+
+
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+=== Prerequisites ===
+
+* 1. Scons
+
+Please refer to the following page to install scons:
+ http://www.scons.org/doc/production/HTML/scons-user.html#chap-build-install
+(Note: on Windows, install Python 2.x before installing scons)
+
+* 2. IDE/SDK Pre-requites
+To build for some OS (Android / Arduino / IOS ...), an IDE/SDK may be required,
+please go to the relative page to download and install the required IDE/SDK.
+
+Note: Connectivity module building has been changed. We have to build connectivity
+ from the iotivity root folder.
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Android Build:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Steps to build and deploy Easysetup Mediator in Android platform
+1) Compilation using Scons
+ 0) Prerequisite exports for Android
+ export ANDROID_HOME=<ANDROID_HOME>
+ export ANDROID_NDK=<ANDROID_NDK>
+
+ a) In the IoTivity root source folder execute
+ scons TARGET_OS=android TARGET_ARCH=armeabi TARGET_TRANSPORT=IP RELEASE=0
+
+ b) If the project is setup correctly, you should see a BUILD SUCCESSFUL message on the terminal
+ You should see the .aar files generated inside of '<iotivity>/android/android_api/base/build/outputs/aar' directory. The .aar files contain jni directory and also a .jar file
+
+ c) Now navigate to the Easysetup NDK folder
+ <iotivity-root>/service/easy-setup/sdk/mediator/android
+
+ d) Execute NDK-Build with the following command to cross compiled Easysetup JNI .so files
+ <iotivity>/extlibs/android/ndk/android-ndk-r10d/ndk-build
+
+ e) Step (d) will generate cross compiled Easysetup JNI .so files in the following folder
+ <iotivity>/service/easy-setup/sdk/mediator/android/libs/armeabi
+
+2) Compilation using Android Studio
+
+ 0) Prerequisite for running the Android application
+ Install Android Studio and use the Android SDK manager to update the Android API to 21
+
+ a) Import following projects to the Studio using the "File->New->Import Project"
+ - service\easy-setup\sdk\android\EasySetupCore
+ - service\easy-setup\sampleapp\android\EasySetup
+
+ b) EasySetupCore is dependent on the .aar files generated in 1.b
+ 1) To add an .aar file to the 'EasySetupCore' project,
+ a.Right click on EasySetup->New->Module->Import .JAR or .AAR Package
+ b.Select the .aar file(iotivity-armeabi-base-*.aar) from the location in steps 1.b
+ c.Right click on EasySetup->Open Module Settings
+ d.Select each sample app module under 'Modules'->Dependencies->Add->Module Dependency
+
+ c) Build EasySetupCore project using "Android Studio->Build->Make Module "easySetupCore"
+ If the project is setup correctly, you should see a BUILD SUCCESSFUL in the Android Studio Gradle Build terminal
+ You should see the .aar file generated inside of
+ 'iotivity\service\easy-setup\sdk\mediator\android\easySetupCore\build\outputs\aar'
+
+ d) EasySetup application is also dependent on the .so files generated in 1.d step
+ 1) Drag and drop the following .so files in to the EasySetup\app\src\main\jniLibs\armeabi folder
+ - libeasysetup-jni.so [Easy Setup file]
+
+ e) EasySetup is also dependent on the .aar files generated in 1.b and 2.c steps
+ 1) To add an .aar file to the 'EasySetup' project,
+ a.Right click on EasySetup->New->Module->Import .JAR or .AAR Package
+ b.Select the .aar file from the location in steps 1.b and 2.b above
+ c.Right click on EasySetup->Open Module Settings
+ d.Select each sample app module under 'Modules'->Dependencies->Add->Module Dependency
+ e.The .aar files (easySetupCore-*.aar & iotivity-armeabi-base-*.aar) selected in step 2.c.1.b above should be present. Select it.
+
+
+ e) Run "Easy Setup" as an Android application
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Arduino Build:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Steps to build and deploy Easysetup Mediator in Arduino platform
+1) Compilation using Scons for Arduino Due
+ a) Set up Arduino first before building. Refer to "connectivity\build\arduino\Arduino_Setup_README.txt" file for help.
+ b) Go to "iotivity/" folder.
+ c) Prerequisite exports for Arduino
+ export ARDUINO_HOME=<ARDUINO_HOME_DIR>
+ d) Start Arduino IDE. Select ""Tools->Port->Programming port"
+ e) scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI
+ - With debug or logging
+ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+ - With installation to Arduino
+ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0 UPLOAD=true
+ NOTE: BOARD=arduino_due_x_dbg|arduino_due_x. Default is arduino_due_x_dbg.
+
+ Possible values for <transport> are:
+ -> IP :
+ $ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+ -> BLE :
+ $ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=WIFI RELEASE=0
+
+ Note :- Only single transport can be built at a time for Arduino
+ f) The above command will build sample. The "enrollee.hex" can be found at "out/arduino/arm/release/service/easy-setup/sampleapp/enrollee/arduino"
+ g) After building sample, script will try to install on "/dev/ttyACM0" port in 'sudo' mode.
+ To skip installation, set command line argument 'UPLOAD=false' or without UPLOAD option
+ h) To set BLE Shield Name, include the option DEVICE_NAME during scons build.
+ -> $ scons TARGET_OS=arduino BOARD=arduino_due_x_dbg TARGET_ARCH=arm SHIELD=BLE RELEASE=0 DEVICE_NAME=OIC
+
+ Specified Device name length MUST be less than 10 characters. RBL Library has this limitation.
+ By Default DEVICE_NAME=OIC-DEVICE, if device name option is not specified
+
+ To change the port number, please modify "port" variable in __upload() function in: "/build/arduino/SConscript".
+
+
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+Folder structure:
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+
+iotivity/
+└── service
+ └── easy-setup/
+ │── SConscript
+ │── sdk
+ │ └── inc
+ │ └── src
+ │ └── android
+ │ └── arduino
+ │ └──wifi
+ │ └──inc
+ │ └──src
+ │── sampleapp
+ │ └──mediator/android
+ │ └──mediator/linux
+ │ └──enrollee/arduino
+ └── Build_Instructions_Android_Arduino.txt - You are reading this.
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# easy-setup project build script
+##
+
+import os
+
+Import('env')
+
+transport = env.get('TARGET_TRANSPORT')
+
+env.AppendUnique(CPPDEFINES = ['EASY_SETUP_CA_INIT'])
+
+easy_setup_env = env.Clone()
+#
+target_os = env.get('TARGET_OS')
+
+lib_env = env.Clone()
+if target_os == 'android':
+ SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', exports = 'lib_env')
+
+######################################################################
+# Build flags
+######################################################################
+easy_setup_env.AppendUnique(CPPPATH = ['sdk/inc', 'sdk/src', 'sdk/common'])
+
+if target_os not in ['windows', 'winrt']:
+ easy_setup_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+ if target_os not in ['android', 'arduino']:
+ easy_setup_env.AppendUnique(CXXFLAGS = ['-pthread'])
+
+if target_os in ['android', 'linux']:
+ easy_setup_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+ easy_setup_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+ easy_setup_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ if target_os not in ['linux', 'arduino']:
+ easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'gnustl_shared'])
+ if not env.get('RELEASE'):
+ easy_setup_env.AppendUnique(LIBS = ['log'])
+ else:
+ easy_setup_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction'])
+if target_os == 'arduino':
+ easy_setup_env.AppendUnique(CPPPATH = [
+ '../../resource/oc_logger/include',
+ '../../resource/csdk/logger/include',
+ '../../resource/csdk/stack/include',
+ '../../extlibs/cjson',
+ 'sdk/enrollee/arduino/wifi',
+ 'sdk/enrollee/api',
+ 'sdk/enrollee/src',
+ 'sdk/enrollee/inc'])
+ easy_setup_env.AppendUnique(CPPDEFINES = ['TB_LOG', 'ESWIFI'])
+if target_os in ['android','linux']:
+ easy_setup_env.PrependUnique(CPPPATH = [
+ env.get('SRC_DIR') + '/resource/c_common/oic_malloc/include',
+ env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
+ env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+ env.get('SRC_DIR') + '/resource/csdk/stack/include',
+ env.get('SRC_DIR') + '/resource/csdk/logger/include',
+ env.get('SRC_DIR') + '/resource/csdk/security/include',
+ env.get('SRC_DIR') + '/extlibs/cjson',
+ 'sdk/common',
+ 'sdk/mediator/inc'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+
+if target_os == 'arduino':
+ es_sdk_static = easy_setup_env.StaticLibrary('ESSDKLibrary',
+ ['sdk/enrollee/src/easysetup.cpp',
+ 'sdk/enrollee/src/resourceHandler.cpp',
+ 'sdk/enrollee/arduino/wifi/networkHandler.cpp'])
+ easy_setup_env.InstallTarget(es_sdk_static, 'libESSDK')
+
+if target_os == 'android':
+ es_sdk_shared = easy_setup_env.StaticLibrary('libESSDK',
+ ['sdk/mediator/src/prov_adapter.cpp',
+ 'sdk/mediator/src/wifi_provisioning.cpp',
+ 'sdk/mediator/src/provisioning.cpp'])
+ easy_setup_env.InstallTarget(es_sdk_shared, 'libESSDK')
+
+if target_os == 'linux':
+ es_sdk_shared = easy_setup_env.SharedLibrary('ESSDKLibrary',
+ ['sdk/mediator/src/prov_adapter.cpp',
+ 'sdk/mediator/src/wifi_provisioning.cpp',
+ 'sdk/mediator/src/provisioning.cpp'])
+ easy_setup_env.InstallTarget(es_sdk_shared, 'libESSDK')
+
+#Go to build sample apps
+SConscript('sampleapp/SConscript')
+
+
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# sampleapp build script
+##
+
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+
+sample_env = lib_env.Clone()
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+
+######################################################################
+# Source files and Targets
+######################################################################
+if target_os == 'arduino' :
+ # Build linux sample app
+ SConscript('enrollee/arduino/SConscript')
+
+if target_os == 'linux' :
+ # Build linux sample app
+ SConscript('mediator/linux/SConscript')
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+enrollee_env = env.Clone()
+transport = enrollee_env.get('TARGET_TRANSPORT')
+
+######################################################################
+# Build flags
+######################################################################
+enrollee_env.PrependUnique(CPPPATH = [
+ '../../../../../resource/oc_logger/include',
+ '../../../../../resource/csdk/logger/include',
+ '../../../../../resource/csdk/stack/include',
+ '../../../../../extlibs/cjson',
+ '../../../sdk/common',
+ '../../../sdk/enrollee/arduino/wifi',
+ '../../../sdk/enrollee/api',
+ '../../../sdk/enrollee/inc',
+ '../../../sdk/enrollee/src'
+ ])
+enrollee_env.AppendUnique(CPPDEFINES = ['TB_LOG', 'ESWIFI'])
+
+enrollee_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+
+enrollee_env.PrependUnique(LIBS = ['octbstack','ocsrm','connectivity_abstraction','coap', 'ESSDKLibrary'])
+enrollee = enrollee_env.Program('enrollee', 'enrollee_wifi.cpp')
+env.CreateBin('enrollee')
+
+i_enrollee = enrollee_env.Install(env.get('BUILD_DIR'), enrollee)
+
+Alias('enrollee', i_enrollee)
+env.AppendTarget('enrollee')
+
+if(enrollee_env['UPLOAD'] == True):
+ from sys import platform as _platform
+ if _platform == "linux" or _platform == "linux2":
+ enrollee_env.Upload(env.get('BUILD_DIR') + '/service/easy-setup/sampleapp/enrollee/arduino/enrollee.hex')
+ else:
+ print 'Please use appropriate install method for your developing machine. Linux is the only supported platform right now.'
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#include "logger.h"
+#include <string.h>
+
+#ifdef ARDUINOWIFI
+// Arduino WiFi Shield
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+#else
+// Arduino Ethernet Shield
+#include <EthernetServer.h>
+#include <Ethernet.h>
+#include <Dns.h>
+#include <EthernetClient.h>
+#include <util.h>
+#include <EthernetUdp.h>
+#include <Dhcp.h>
+#endif
+
+#include "easysetup.h"
+
+#define TAG "TS"
+
+const char *getResult(OCStackResult result);
+
+char ssid[] = "EasySetup123";
+char passwd[] = "EasySetup123";
+
+void EventCallbackInApp(ESResult eventFlag)
+{
+ Serial.println("callback!!! in app");
+}
+
+// On Arduino Atmel boards with Harvard memory architecture, the stack grows
+// downwards from the top and the heap grows upwards. This method will print
+// the distance(in terms of bytes) between those two.
+// See here for more details :
+// http://www.atmel.com/webdoc/AVRLibcReferenceManual/malloc_1malloc_intro.html
+void PrintArduinoMemoryStats()
+{
+#ifdef ARDUINO_AVR_MEGA2560
+ //This var is declared in avr-libc/stdlib/malloc.c
+ //It keeps the largest address not allocated for heap
+ extern char *__brkval;
+ //address of tmp gives us the current stack boundry
+ int tmp;
+ OC_LOG_V(INFO, TAG, "Stack: %u Heap: %u", (unsigned int)&tmp, (unsigned int)__brkval);
+ OC_LOG_V(INFO, TAG, "Unallocated Memory between heap and stack: %u",
+ ((unsigned int)&tmp - (unsigned int)__brkval));
+#endif
+}
+//The setup function is called once at startup of the sketch
+void setup()
+{
+ // Add your initialization code here
+ // Note : This will initialize Serial port on Arduino at 115200 bauds
+ OC_LOG_INIT();
+ OC_LOG(DEBUG, TAG, "OCServer is starting...");
+
+ if(InitEasySetup(CT_ADAPTER_IP, ssid, passwd, EventCallbackInApp) == ES_ERROR)
+ {
+ OC_LOG(ERROR, TAG, "EasySetup Init Failed");
+ return;
+ }
+
+ if(InitProvisioning()== ES_ERROR)
+ {
+ OC_LOG(ERROR, TAG, "Init Provisioning Failed");
+ return;
+ }
+}
+
+// The loop function is called in an endless loop
+void loop()
+{
+ // This artificial delay is kept here to avoid endless spinning
+ // of Arduino microcontroller. Modify it as per specific application needs.
+ delay(2000);
+
+ // This call displays the amount of free SRAM available on Arduino
+ PrintArduinoMemoryStats();
+
+ // Give CPU cycles to OCStack to perform send/recv and other OCStack stuff
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "OCStack process error");
+ return;
+ }
+}
--- /dev/null
+#built application files\r
+*.apk\r
+*.ap_\r
+\r
+# files for the dex VM\r
+*.dex\r
+\r
+# Java class files\r
+*.class\r
+\r
+# generated files\r
+bin/\r
+gen/\r
+\r
+# Local configuration file (sdk path, etc)\r
+local.properties\r
+\r
+# Proguard folder generated by Eclipse \r
+proguard/ \r
+\r
+# Windows thumbnail db\r
+Thumbs.db\r
+\r
+# OSX files\r
+.DS_Store\r
+\r
+# Eclipse project files\r
+.classpath\r
+.project\r
+\r
+#Android Studio & Gradle\r
+.gradle\r
+/local.properties\r
+/.idea/workspace.xml\r
+/.idea/libraries\r
+.DS_Store\r
+/build/*\r
+/base/build/*\r
+/base/obj/*\r
+/base/libs/*\r
+/sample/*\r
+\r
+#Some older projects\r
+/*/out\r
+/*/*/build\r
+/*/*/production\r
+*.iws\r
+*.ipr\r
+*~\r
+*.swp
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id="EasySetupGradle" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="java-gradle" name="Java-Gradle">
+ <configuration>
+ <option name="BUILD_FOLDER_PATH" value="$MODULE_DIR$/build" />
+ <option name="BUILDABLE" value="false" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" inherit-compiler-output="true">
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <excludeFolder url="file://$MODULE_DIR$/.gradle" />
+ </content>
+ <orderEntry type="inheritedJdk" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ </component>
+</module>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id=":app" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$/.." external.system.id="GRADLE" external.system.module.group="EasySetup" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":app" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />
+ <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+ <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+ <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+ <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+ <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+ <afterSyncTasks>
+ <task>generateDebugAndroidTestSources</task>
+ <task>generateDebugSources</task>
+ </afterSyncTasks>
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="RES_FOLDERS_RELATIVE_PATH" value="file://$MODULE_DIR$/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" LANGUAGE_LEVEL="JDK_1_7" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/EasySetupCore-debug/unspecified/jars" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetup/iotivity-armeabi-base-debug/unspecified/jars" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+ <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="module" module-name="EasySetupCore-debug" exported="" />
+ <orderEntry type="module" module-name="iotivity-armeabi-base-debug" exported="" />
+ <orderEntry type="library" exported="" name="EasySetupCore-debug-unspecified" level="project" />
+ <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+ </component>
+</module>
\ No newline at end of file
--- /dev/null
+apply plugin: 'com.android.application'\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion '21.1.2'\r
+\r
+ defaultConfig {\r
+ applicationId "org.iotivity.service.easysetup"\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ }\r
+\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'\r
+ }\r
+ }\r
+}\r
+\r
+dependencies {\r
+ compile project(':EasySetupCore-debug')\r
+ compile project(':iotivity-armeabi-base-debug')\r
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="org.iotivity.service.easysetup"
+ android:versionCode="1"
+ android:versionName="1.0">
+
+ <uses-permission android:name="android.permission.INTERNET" />
+ <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
+ <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
+ <uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
+
+ <uses-feature
+ android:name="android.hardware.camera"
+ android:required="true" />
+ <uses-feature
+ android:name="android.hardware.camera.autofocus"
+ android:required="false" />
+ <uses-feature
+ android:name="android.hardware.touchscreen"
+ android:required="false" />
+
+ <uses-permission android:name="android.permission.CAMERA" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme">
+ <activity
+ android:name=".MainActivity"
+ android:label="@string/app_name">
+
+ <intent-filter>
+ <action android:name="android.intent.action.MAIN" />
+
+ <category android:name="android.intent.category.LAUNCHER" />
+ </intent-filter>
+ </activity>
+ </application>
+
+</manifest>
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup;\r
+\r
+import java.io.IOException;\r
+\r
+import org.iotivity.service.easysetup.core.EasySetupService;\r
+import org.iotivity.service.easysetup.core.EasySetupStatus;\r
+import org.iotivity.service.easysetup.core.EnrolleeDevice;\r
+import org.iotivity.service.easysetup.core.EnrolleeState;\r
+import org.iotivity.service.easysetup.core.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;\r
+import org.iotivity.service.easysetup.impl.WiFiOnBoardingConfig;\r
+import org.iotivity.service.easysetup.impl.WiFiProvConfig;\r
+\r
+import android.app.Activity;\r
+import android.net.wifi.WifiConfiguration;\r
+import android.os.Bundle;\r
+import android.os.Handler;\r
+import android.os.Message;\r
+import android.util.Log;\r
+import android.view.View;\r
+import android.view.View.OnClickListener;\r
+import android.widget.Button;\r
+import android.widget.EditText;\r
+import android.widget.ProgressBar;\r
+import android.widget.TextView;\r
+import android.widget.Toast;\r
+\r
+public class MainActivity extends Activity {\r
+\r
+\r
+ /*Status to update the UI */\r
+ public static final int SUCCESS = 0;\r
+ public static final int FAILED = 1;\r
+ public static final int STATE_CHANGED = 2;\r
+\r
+ EditText mSsidText;\r
+ EditText mPassText;\r
+\r
+ EditText mEnrolleeSsidText;\r
+ EditText mmEnrolleePasswordPassText;\r
+\r
+\r
+ TextView mDeviceIpTextView;\r
+ TextView mDeviceMacTextView;\r
+\r
+\r
+ TextView mResultTextView;\r
+ ProgressBar mProgressbar;\r
+ Button mStartButton;\r
+ Button mStopButton;\r
+ Handler mHandler = new ThreadHandler();\r
+\r
+ /**\r
+ * Objects to be instantiated by the programmer\r
+ */\r
+ WiFiProvConfig mWiFiProvConfig;\r
+ WiFiOnBoardingConfig mWiFiOnBoardingConfig;\r
+ EasySetupService mEasySetupService;\r
+ EnrolleeDeviceFactory mDeviceFactory;\r
+ EnrolleeDevice mDevice;\r
+\r
+ @Override\r
+ protected void onCreate(Bundle savedInstanceState) {\r
+ super.onCreate(savedInstanceState);\r
+ setContentView(R.layout.activity_main);\r
+\r
+ /* Initialize widgets to get user input for target network's SSID & password*/\r
+ mSsidText = (EditText) findViewById(R.id.ssid);\r
+ mPassText = (EditText) findViewById(R.id.password);\r
+ mEnrolleeSsidText = (EditText) findViewById(R.id.enrolleeSsid);\r
+ mmEnrolleePasswordPassText = (EditText) findViewById(R.id.enrolleePass);\r
+ mDeviceIpTextView = (TextView) findViewById(R.id.ipAddr);\r
+ mDeviceMacTextView = (TextView) findViewById(R.id.hardAddr);\r
+\r
+ mResultTextView = (TextView) findViewById(R.id.status);\r
+ mProgressbar = (ProgressBar) findViewById(R.id.progressBar);\r
+\r
+\r
+\r
+\r
+ /* Create Easy Setup Service instance*/\r
+ mEasySetupService = EasySetupService.getInstance(getApplicationContext(),\r
+ new EasySetupStatus() {\r
+\r
+ @Override\r
+ public void onFinished(final EnrolleeDevice enrolledevice) {\r
+ Log.i("MainActivity", "onFinished() is received " + enrolledevice\r
+ .isSetupSuccessful());\r
+ if (enrolledevice.isSetupSuccessful()) {\r
+ mHandler.sendEmptyMessage(SUCCESS);\r
+ } else {\r
+ mHandler.sendEmptyMessage(FAILED);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void onProgress(EnrolleeDevice enrolleeDevice) {\r
+ Log.i("MainActivity", "onProgress() is received ");\r
+ mHandler.sendEmptyMessage(STATE_CHANGED);\r
+ }\r
+\r
+ });\r
+\r
+ /* Create EnrolleeDevice Factory instance*/\r
+ mDeviceFactory = EnrolleeDeviceFactory.newInstance(getApplicationContext());\r
+\r
+ /* Create a device using Factory instance*/\r
+ mDevice = mDeviceFactory.newEnrolleeDevice(getOnBoardingWifiConfig(),\r
+ getEnrollerWifiConfig());\r
+\r
+ addListenerForStartAP();\r
+ addListenerForStopAP();\r
+ }\r
+\r
+ public WiFiProvConfig getEnrollerWifiConfig() {\r
+ /* Provide the credentials for the Mediator Soft AP to be connected by Enrollee*/\r
+ mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
+ mEnrolleeSsidText.setText("hub2.4G");\r
+ mmEnrolleePasswordPassText.setText("11112222");\r
+\r
+ return mWiFiProvConfig;\r
+ }\r
+\r
+ public WiFiOnBoardingConfig getOnBoardingWifiConfig() {\r
+ mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
+\r
+ /* Provide the target credentials to be provisioned to the Enrollee by Mediator*/\r
+ mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
+ mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
+ mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
+ mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
+\r
+ // Updating the UI with default credentials\r
+ mSsidText.setText("EasySetup123");\r
+ mPassText.setText("EasySetup123");\r
+\r
+ return mWiFiOnBoardingConfig;\r
+ }\r
+\r
+\r
+ public void onDestroy() {\r
+ super.onDestroy();\r
+ /*Reset the Easy setup process*/\r
+ if (mEasySetupService != null) {\r
+ mEasySetupService.finish();\r
+ }\r
+ }\r
+\r
+ public void addListenerForStartAP() {\r
+ mStartButton = (Button) findViewById(R.id.startSetup);\r
+\r
+ mStartButton.setOnClickListener(new OnClickListener() {\r
+ @Override\r
+ public void onClick(View arg0) {\r
+ try {\r
+\r
+ mProgressbar.setVisibility(View.VISIBLE);\r
+ mProgressbar.setIndeterminate(true);\r
+ mStartButton.setEnabled(false);\r
+ mResultTextView.setText(R.string.running);\r
+\r
+ //Reset Device information\r
+ mDeviceIpTextView.setText(R.string.not_available);\r
+ mDeviceMacTextView.setText(R.string.not_available);\r
+\r
+\r
+ String ssid = mSsidText.getText().toString();\r
+ String password = mPassText.getText().toString();\r
+\r
+ String enrolleeSsid = mEnrolleeSsidText.getText().toString();\r
+ String enrolleePassword = mmEnrolleePasswordPassText.getText().toString();\r
+\r
+ mWiFiProvConfig = new WiFiProvConfig(enrolleeSsid, enrolleePassword);\r
+\r
+ mWiFiOnBoardingConfig.setSSId(ssid);\r
+ mWiFiOnBoardingConfig.setSharedKey(password);\r
+\r
+\r
+ mEasySetupService.startSetup(mDevice);\r
+\r
+ mStopButton.setEnabled(true);\r
+\r
+\r
+ } catch (IOException e) {\r
+ e.printStackTrace();\r
+ }\r
+\r
+ }\r
+ });\r
+ }\r
+\r
+ public void addListenerForStopAP() {\r
+ mStopButton = (Button) findViewById(R.id.stopSetup);\r
+\r
+ mStopButton.setOnClickListener(new OnClickListener() {\r
+ @Override\r
+ public void onClick(View arg0) {\r
+ mStartButton.setEnabled(true);\r
+ mStopButton.setEnabled(false);\r
+ mResultTextView.setText(R.string.stopped);\r
+ mProgressbar.setIndeterminate(false);\r
+ mProgressbar.setVisibility(View.INVISIBLE);\r
+ mEasySetupService.stopSetup(mDevice);\r
+ }\r
+ });\r
+ }\r
+\r
+\r
+ class ThreadHandler extends Handler {\r
+ @Override\r
+ public void handleMessage(Message msg) {\r
+\r
+ switch (msg.what) {\r
+ case SUCCESS: {\r
+\r
+ mProgressbar.setIndeterminate(false);\r
+ mStopButton.setEnabled(false);\r
+ mStartButton.setEnabled(true);\r
+ mProgressbar.setVisibility(View.INVISIBLE);\r
+ String resultMsg = "Device configured successfully";\r
+ mResultTextView.setText(R.string.success);\r
+\r
+ /* Update device information on the Ui */\r
+ IpOnBoardingConnection connection = (IpOnBoardingConnection) mDevice\r
+ .getConnection();\r
+ mDeviceIpTextView.setText(connection.getIp());\r
+ mDeviceMacTextView.setText(connection.getHardwareAddress());\r
+\r
+ Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+ break;\r
+ }\r
+ case FAILED: {\r
+\r
+ mProgressbar.setIndeterminate(false);\r
+ mStopButton.setEnabled(false);\r
+ mStartButton.setEnabled(true);\r
+ mProgressbar.setVisibility(View.INVISIBLE);\r
+ String resultMsg = "Device configuration failed";\r
+ mResultTextView.setText(R.string.failed);\r
+ Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+ break;\r
+ }\r
+\r
+ case STATE_CHANGED: {\r
+ String resultMsg = "Device state changed";\r
+ Toast.makeText(getApplicationContext(), resultMsg, Toast.LENGTH_SHORT).show();\r
+ break;\r
+ }\r
+\r
+ }\r
+\r
+\r
+ }\r
+ }\r
+\r
+}\r
--- /dev/null
+<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:tools="http://schemas.android.com/tools"
+ android:layout_width="match_parent"
+ android:layout_height="match_parent"
+ android:background="@drawable/background"
+ android:orientation="vertical"
+ android:paddingBottom="@dimen/activity_vertical_margin"
+ android:paddingLeft="@dimen/activity_horizontal_margin"
+ android:paddingRight="@dimen/activity_horizontal_margin"
+ android:paddingTop="@dimen/activity_vertical_margin"
+ tools:context="org.iotivity.service.easysetup.mediator.MainActivity">
+
+
+ <ProgressBar
+ android:id="@+id/progressBar"
+ style="?android:attr/progressBarStyleHorizontal"
+ android:layout_width="350dp"
+ android:layout_height="wrap_content"
+ android:visibility="invisible" />
+
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center"
+ android:layout_marginTop="5dp"
+ android:orientation="horizontal">
+
+
+ <TextView
+ android:id="@+id/lablestatus"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="8dp"
+ android:layout_marginRight="20dp"
+ android:elegantTextHeight="true"
+ android:text="@string/test_status"
+ android:textSize="15sp" />
+
+ <TextView
+ android:id="@+id/status"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginLeft="10dp"
+ android:layout_marginRight="30dp"
+ android:text="@string/not_started"
+ android:textColor="@android:color/background_light"
+ android:textSize="20dp" />
+
+ </LinearLayout>
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="10dp"
+ android:orientation="vertical">
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Enter Enroller's SSID" />
+
+
+ <EditText
+ android:id="@+id/enrolleeSsid"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal" />
+
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="10dp"
+ android:text="Enter Enroller's Password" />
+
+
+ <EditText
+ android:id="@+id/enrolleePass"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+
+ android:layout_gravity="center_horizontal" />
+
+ </LinearLayout>
+
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="10dp"
+ android:orientation="vertical">
+
+ <TextView
+ android:id="@+id/textView"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:text="Enter SoftAP SSID" />
+
+
+ <EditText
+ android:id="@+id/ssid"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal" />
+
+
+ <TextView
+ android:id="@+id/textView2"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_marginTop="10dp"
+ android:text="Enter SoftAP PWD" />
+
+
+ <EditText
+ android:id="@+id/password"
+ android:layout_width="250dp"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal" />
+
+ </LinearLayout>
+
+
+ <TextView
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_marginTop="5dp"
+ android:text="Device information"
+ android:textAppearance="?android:attr/textAppearanceMedium" />
+
+ <RelativeLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="10dp"
+ android:orientation="vertical">
+
+
+ <TextView
+ android:id="@+id/ipAddrLable"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:text="IP Address"
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+ <TextView
+ android:id="@+id/ipAddr"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_gravity="center_horizontal"
+ android:layout_toRightOf="@id/ipAddrLable"
+ android:text="@string/not_available"
+
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+
+ <TextView
+ android:id="@+id/hardAddrLable"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/ipAddrLable"
+ android:layout_gravity="center_horizontal"
+ android:text="MAC Address"
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+ <TextView
+ android:id="@+id/hardAddr"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@id/ipAddr"
+ android:layout_gravity="center_horizontal"
+ android:layout_toRightOf="@id/hardAddrLable"
+ android:text="@string/not_available"
+ android:textAppearance="?android:attr/textAppearanceSmall" />
+
+
+ </RelativeLayout>
+
+
+ <LinearLayout
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_centerHorizontal="true"
+ android:layout_gravity="center"
+ android:layout_marginTop="20dp"
+ android:orientation="horizontal">
+
+ <Button
+ android:id="@+id/startSetup"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_alignParentTop="true"
+ android:layout_centerHorizontal="true"
+ android:layout_margin="10dp"
+ android:layout_marginTop="20dp"
+ android:elegantTextHeight="true"
+ android:text="@string/startSetup"
+ android:textAllCaps="false"
+ android:textSize="18sp" />
+
+ <Button
+ android:id="@+id/stopSetup"
+ android:layout_width="wrap_content"
+ android:layout_height="wrap_content"
+ android:layout_below="@+id/startSetup"
+ android:layout_centerHorizontal="true"
+ android:layout_margin="10dp"
+ android:elegantTextHeight="true"
+ android:enabled="false"
+ android:text="@string/stopSetup"
+ android:textAllCaps="false"
+ android:textSize="18sp" />
+
+ </LinearLayout>
+
+</LinearLayout>
\ No newline at end of file
--- /dev/null
+<menu xmlns:android="http://schemas.android.com/apk/res/android"
+ xmlns:app="http://schemas.android.com/apk/res-auto"
+ xmlns:tools="http://schemas.android.com/tools"
+ tools:context="org.iotivity.service.easysetup.MainActivity" >
+
+ <item
+ android:id="@+id/action_settings"
+ android:orderInCategory="100"
+ android:title="@string/action_settings"/>
+
+</menu>
--- /dev/null
+<resources>
+
+ <!-- Default screen margins, per the Android Design guidelines. -->
+ <dimen name="activity_horizontal_margin">16dp</dimen>
+ <dimen name="activity_vertical_margin">1dp</dimen>
+
+</resources>
--- /dev/null
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <string name="app_name">Easy Setup</string>
+ <string name="action_settings">Settings</string>
+ <string name="textview2">Device Information</string>
+ <string name="textview1"> -- empty -- </string>
+ <string name="scan_qr_code">Scan QR Code</string>
+ <string name="start_easy_setup">Start Easy Setup</string>
+ <string name="start_soft_ap">Start Wi-Fi Soft AP</string>
+ <string name="stop_soft_ap">Stop Soft AP</string>
+ <string name="provision_device">Provision Connected Device</string>
+
+ <string name="startSetup">Start Setup</string>
+ <string name="stopSetup">Stop Setup</string>
+ <string name="SSID">SSID</string>
+ <string name="Password">Password</string>
+ <string name="success">Successful</string>
+ <string name="failed">Failed</string>
+ <string name="not_started">Not started</string>
+ <string name="test_status">Device configuration</string>
+ <string name="running">Running</string>
+ <string name="stopped">Stopped</string>
+ <string name="not_available">Not available</string>
+
+
+</resources>
--- /dev/null
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+buildscript {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+ dependencies {\r
+ classpath 'com.android.tools.build:gradle:1.2.3'\r
+ }\r
+}\r
+\r
+allprojects {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+}\r
--- /dev/null
+include ':app'\r
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+Import('env')
+
+mediator_env = env.Clone()
+
+target_os = env.get('TARGET_OS')
+
+######################################################################
+# Build flags
+######################################################################
+mediator_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+mediator_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+mediator_env.PrependUnique(CPPPATH = [
+ env.get('SRC_DIR') + '/resource/csdk/ocmalloc/include',
+ env.get('SRC_DIR') + '/resource/csdk/connectivity/common/inc',
+ env.get('SRC_DIR') + '/resource/csdk/connectivity/api',
+ env.get('SRC_DIR') + '/resource/csdk/stack/include',
+ env.get('SRC_DIR') + '/resource/csdk/logger/include',
+ env.get('SRC_DIR') + '/resource/csdk/security/include',
+ env.get('SRC_DIR') + '/extlibs/cjson',
+ env.get('SRC_DIR') + '/service/easy-setup/sdk/mediator/inc',
+ env.get('SRC_DIR') + '/service/easy-setup/sdk/common'])
+
+mediator_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'pthread', 'connectivity_abstraction', 'coap', 'ESSDKLibrary'])
+
+mediator = mediator_env.Program('mediator', 'mediator.cpp')
+
+i_mediator = mediator_env.Install(env.get('BUILD_DIR'), mediator)
+
+Alias('mediator', i_mediator)
+env.AppendTarget('mediator')
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <sstream>
+
+#include "prov_adapter.h"
+#include "logger.h"
+
+#define TAG "easysetupsample"
+
+int quitFlag = 0;
+
+/* SIGINT handler: set quitFlag to 1 for graceful termination */
+void handleSigInt(int signum) {
+ if (signum == SIGINT) {
+ quitFlag = 1;
+ }
+}
+
+/**
+ * This callback function is used to receive the notifications about the provisioning status
+ * In success or failure, ProvisioningInfo structure holds the current state of provisioning
+ * and also holds the Enrollee information for which provisioning is requested
+ * This function can be used to update the application about the current provisioning status of the Enrollee
+ */
+void ProvisioningStatusCallback(ProvisioningInfo * provInfo) {
+ OIC_LOG_V(INFO, TAG, "Enrollee connectivity: %d", provInfo->provDeviceInfo.connType);
+ if (provInfo->provStatus == DEVICE_PROVISIONED) {
+ OIC_LOG_V(INFO, TAG, "Successfully provisioned the Enrollee with IP : %s ",
+ provInfo->provDeviceInfo.addr->addr);
+ }
+ else {
+ OIC_LOG_V(INFO, TAG, "Provisioing Failed for the Enrollee with IP : %s",
+ provInfo->provDeviceInfo.addr->addr);
+ }
+}
+
+static void PrintUsage() {
+ OIC_LOG(INFO, TAG, "Usage : occlient -d \"192.168.0.20\"");
+}
+
+int main(int argc, char **argv) {
+ int opt;
+ EnrolleeNWProvInfo_t netInfo;
+ PrintUsage();
+ InitProvProcess();
+
+
+ RegisterCallback(ProvisioningStatusCallback);
+
+ while ((opt = getopt(argc, argv, "d:s:p:")) != -1) {
+ switch (opt) {
+ case 'd':
+ strncpy(netInfo.netAddressInfo.WIFI.ipAddress, optarg, IPV4_ADDR_SIZE - 1);
+ break;
+ case 's':
+ strncpy(netInfo.netAddressInfo.WIFI.ssid, optarg, NET_WIFI_SSID_SIZE - 1);
+ break;
+ case 'p':
+ strncpy(netInfo.netAddressInfo.WIFI.pwd, optarg, NET_WIFI_PWD_SIZE - 1);
+ break;
+ default:
+ PrintUsage();
+ return -1;
+ }
+ }
+
+ netInfo.connType = CT_ADAPTER_IP;
+ OIC_LOG_V(INFO, TAG, "IP Address of the Provisioning device is =%s\n",
+ netInfo.netAddressInfo.WIFI.ipAddress);
+ OIC_LOG_V(INFO, TAG, "SSID of the Enroller is =%s\n", netInfo.netAddressInfo.WIFI.ssid);
+ OIC_LOG_V(INFO, TAG, "Password of the Enroller is =%s\n", netInfo.netAddressInfo.WIFI.pwd);
+
+ StartProvisioning(&netInfo);
+
+ signal(SIGINT, handleSigInt);
+ while (!quitFlag) {
+ sleep(1);
+ }
+
+ ResetProvProcess();
+ OIC_LOG(INFO, TAG, "Exiting occlient main loop...");
+
+ return 0;
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 ES_COMMON_H_
+#define ES_COMMON_H_
+
+#include "ocstack.h"
+#include "octypes.h"
+
+// Defines
+#define OIC_STRING_MAX_VALUE 100
+#define IPV4_ADDR_SIZE 16
+#define IP_PORT 55555
+#define NET_WIFI_SSID_SIZE 16
+#define NET_WIFI_PWD_SIZE 16
+
+/**
+ * @brief Mac address length for BT port
+ */
+#define NET_MACADDR_SIZE 18
+
+//The following variable determines the interface (wifi, ethernet etc.)
+//to be used for sending unicast messages. Default set to Ethernet.
+static OCConnectivityType OC_CONNTYPE = CT_IP_USE_V4;
+static OCConnectivityType OC_CONNTYPE_BLE = CT_ADAPTER_GATT_BTLE;
+
+static const char * UNICAST_PROVISIONING_QUERY = "coap://%s:%d/oic/res?rt=oic.r.prov";
+static const char * UNICAST_PROV_STATUS_QUERY = "coap://%s:%d%s";
+
+/**
+ * Attributes used to form a proper easysetup conforming JSON message.
+ */
+#define OC_RSRVD_ES_PS "ps"
+#define OC_RSRVD_ES_TNN "tnn"
+#define OC_RSRVD_ES_CD "cd"
+#define OC_RSRVD_ES_TR "tr"
+#define OC_RSRVD_ES_TNT "tnt"
+#define OC_RSRVD_ES_ANT "ant"
+#define OC_RSRVD_ES_URI_PROV "/oic/prov"
+#define OC_RSRVD_ES_URI_NET "/oic/net"
+
+
+
+typedef enum
+{
+ ES_ERROR = -1,
+ ES_OK = 0,
+ ES_NETWORKFOUND = 1,
+ ES_NETWORKCONNECTED,
+ ES_NETWORKNOTCONNECTED,
+ ES_RESOURCECREATED = 11,
+ ES_RECVREQOFPROVRES = 21,
+ ES_RECVREQOFNETRES,
+ ES_RECVUPDATEOFPROVRES,
+ ES_RECVTRIGGEROFPROVRES,
+} ESResult;
+
+
+/**
+ * Provisioning Device Status
+ */
+typedef struct {
+ /// Address of remote server
+ OCDevAddr * addr;
+ /// Indicates adaptor type on which the response was received
+ OCConnectivityType connType;
+} ProvDeviceInfo;
+
+/**
+ * Provosioning Status
+ */
+typedef enum {
+ DEVICE_PROVISIONED = 0, DEVICE_NOT_PROVISIONED
+} ProvStatus;
+
+/**
+ * Response from queries to remote servers. Queries are made by calling the @ref OCDoResource API.
+ */
+typedef struct {
+ // Provisioning Status
+ ProvStatus provStatus;
+ // Provisioning Device Info
+ ProvDeviceInfo provDeviceInfo;
+} ProvisioningInfo;
+
+/**
+ * @brief Network information of the Enroller
+ */
+typedef union
+{
+ /**
+ * @brief BT Mac Information
+ */
+ struct
+ {
+ char btMacAddress[NET_MACADDR_SIZE]; /**< BT mac address **/
+ } BT;
+
+ /**
+ * @brief LE MAC Information
+ */
+ struct
+ {
+ char leMacAddress[NET_MACADDR_SIZE]; /**< BLE mac address **/
+ } LE;
+
+ /**
+ * @brief IP Information
+ */
+ struct
+ {
+ char ipAddress[IPV4_ADDR_SIZE]; /**< IP Address of the Enroller**/
+ char ssid[NET_WIFI_SSID_SIZE]; /**< ssid of the Enroller**/
+ char pwd[NET_WIFI_PWD_SIZE]; /**< pwd of the Enroller**/
+ } WIFI;
+} EnrolleeInfo_t;
+
+
+/**
+ * @brief Network Information
+ */
+typedef struct
+{
+ EnrolleeInfo_t netAddressInfo; /**< Enroller Network Info**/
+ OCConnectivityType connType; /**< Connectivity Type**/
+ bool isSecured; /**< Secure connection**/
+} EnrolleeNWProvInfo_t;
+
+/**
+ * Client applications implement this callback to consume responses received from Servers.
+ */
+typedef void (*OCProvisioningStatusCB)(ProvisioningInfo *provInfo);
+
+#endif
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains SDK APIs for device operating in Enrollee Mode of EasySetup
+ */
+
+#ifndef EASYSETUP_ENROLLEE_H__
+#define EASYSETUP_ENROLLEE_H__
+
+// Do not remove the include below
+#include "Arduino.h"
+#include "networkHandler.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/*
+ * Callback function for updating the Enrollee OnBoarding and Provisioning status result to the application
+ *
+ * @param esResult ESResult provides the current state of the Enrollee Device
+ */
+typedef void (*EventCallback)(ESResult esResult);
+
+/**
+ * This function Initializes the EasySetup. This API must be called prior to invoking any other API
+ *
+ * @param networkType NetworkType on which OnBoarding has to be performed.
+ * @param ssid SSID of the target SoftAP network to which the Enrollee is connecting.
+ * @param passwd Password of the target SoftAP network to which the Enrollee is connecting
+ * @param eventCallback EventCallback for for updating the Enrollee OnBoarding and Provisioning status
+ * result to the application
+ * @return ::ES_OK on success, some other value upon failure.
+ */
+ESResult InitEasySetup(OCConnectivityType networkType, const char *ssid,
+ const char *passwd,
+ EventCallback eventCallback);
+
+/**
+ * This function performs initialization of Provisioning and Network resources needed for EasySetup process.
+ *
+ * @return ::ES_OK on success, some other value upon failure.
+ */
+ESResult InitProvisioning();
+
+/**
+ * This function performs termination of Provisioning and Network resources.
+ * Also terminates the IoTivity core stack.
+ *
+ * @return ::ES_OK on success, some other value upon failure.
+ */
+ESResult TerminateEasySetup();
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+
+#endif /* EASYSETUP_ENROLLEE_H__ */
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "networkHandler.h"
+
+// Arduino WiFi Shield includes
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+
+#include <string.h>
+
+#include "logger.h"
+
+/**
+ * @var ES_NH_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_NH_TAG "ES_NH"
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+static IPAddress myIP;
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+int findNetwork(const char *ssid);
+int ConnectToNetwork(const char *ssid, const char *pass);
+void printEncryptionType(int thisType);
+
+// Arduino WiFi Shield
+// Note : Arduino WiFi Shield currently does NOT support multicast and therefore
+// this server will NOT be listening on 224.0.1.187 multicast address.
+static const char ARDUINO_WIFI_SHIELD_UDP_FW_VER[] = "1.1.0";
+
+ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback cb)
+{
+ char *fwVersion;
+ int status = WL_IDLE_STATUS;
+ int res;
+
+ // check for the presence of the shield:
+ if (WiFi.status() == WL_NO_SHIELD)
+ {
+ OC_LOG(ERROR, ES_NH_TAG, "WiFi shield not present");
+ return ES_ERROR;
+ }
+
+ // Verify that WiFi Shield is running the firmware with all UDP fixes
+ fwVersion = WiFi.firmwareVersion();
+ OC_LOG_V(INFO, ES_NH_TAG, "WiFi Shield Firmware version %s", fwVersion);
+ if (strncmp(fwVersion, ARDUINO_WIFI_SHIELD_UDP_FW_VER, sizeof(ARDUINO_WIFI_SHIELD_UDP_FW_VER))
+ != 0)
+ {
+ OC_LOG(DEBUG, ES_NH_TAG, "!!!!! Upgrade WiFi Shield Firmware version !!!!!!");
+ //return ES_ERROR;
+ }
+
+ OC_LOG_V(INFO, ES_NH_TAG, "Finding SSID: %s", ssid);
+
+ while (findNetwork(ssid) == 0) // found
+ {
+ delay(1000);
+ }
+
+ if (cb != NULL)
+ {
+ cb(ES_NETWORKFOUND);
+ }
+
+ if (WiFi.status() == WL_CONNECTED)
+ WiFi.disconnect();
+
+ res = ConnectToNetwork(ssid, pass);
+
+ if (res == 0)
+ {
+ return ES_NETWORKCONNECTED;
+ }
+ else
+ {
+ return ES_NETWORKNOTCONNECTED;
+ }
+}
+
+int findNetwork(const char *ssid)
+{
+ int res = 0;
+ // scan for nearby networks:
+ Serial.println("** Scan Networks **");
+ int numSsid = WiFi.scanNetworks();
+ if (numSsid == -1)
+ {
+ Serial.println("Couldn't get a wifi connection");
+
+ return res;
+ }
+
+ // print the list of networks seen:
+ Serial.print("number of available networks:");
+ Serial.println(numSsid);
+
+ // print the network number and name for each network found:
+ for (int thisNet = 0; thisNet < numSsid; thisNet++)
+ {
+ Serial.print(thisNet);
+ Serial.print(") ");
+ Serial.print(WiFi.SSID(thisNet));
+ Serial.print("\tEncryption: ");
+ printEncryptionType(WiFi.encryptionType(thisNet));
+
+ if (strcmp(WiFi.SSID(thisNet), ssid) == 0)
+ {
+ res = 1;
+ }
+ }
+
+ return res;
+}
+
+int ConnectToNetwork(const char *ssid, const char *pass)
+{
+ int status = WL_IDLE_STATUS;
+
+ // attempt to connect to Wifi network:
+ while (status != WL_CONNECTED)
+ {
+ OC_LOG_V(INFO, ES_NH_TAG, "Attempting to connect to SSID: %s", ssid);
+
+ status = WiFi.begin((char *) ssid, (char *) pass);
+
+ // wait 10 seconds for connection:
+ delay(10000);
+ }
+ OC_LOG(DEBUG, ES_NH_TAG, "Connected to wifi");
+
+ myIP = WiFi.localIP();
+ OC_LOG_V(INFO, ES_NH_TAG, "IP Address: %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
+
+ char buf[50];
+ sprintf(buf, "IP Address: %d.%d.%d.%d", myIP[0], myIP[1], myIP[2], myIP[3]);
+ Serial.println(buf);
+
+ return 0;
+}
+
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info)
+{
+ if (targetType == CT_ADAPTER_IP && WiFi.status() == WL_CONNECTED)
+ {
+ info->type = CT_ADAPTER_IP;
+ info->ipaddr = WiFi.localIP();
+ if(strlen(WiFi.SSID())<=MAXSSIDLEN)
+ {
+ strcpy(info->ssid, WiFi.SSID());
+ return ES_OK;
+ }
+ else
+ {
+ return ES_ERROR;
+ }
+ }
+
+ return ES_ERROR;
+}
+
+void printEncryptionType(int thisType)
+{
+ // read the encryption type and print out the name:
+ switch (thisType)
+ {
+ case ENC_TYPE_WEP:
+ Serial.println("WEP");
+ break;
+ case ENC_TYPE_TKIP:
+ Serial.println("WPA");
+ break;
+ case ENC_TYPE_CCMP:
+ Serial.println("WPA2");
+ break;
+ case ENC_TYPE_NONE:
+ Serial.println("None");
+ break;
+ case ENC_TYPE_AUTO:
+ Serial.println("Auto");
+ break;
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains IP network handling functionality for Enrollee device
+ */
+
+#ifndef ES_NETWORK_HANDLER_H_
+#define ES_NETWORK_HANDLER_H_
+
+// Do not remove the include below
+#include "Arduino.h"
+
+// Arduino WiFi Shield includes
+#include <SPI.h>
+#include <WiFi.h>
+#include <WiFiUdp.h>
+
+#include <string.h>
+#include "logger.h"
+#include "common.h"
+
+#define MAXSSIDLEN 33
+#define MAXNETCREDLEN 20
+#define MAXNUMTYPE 5
+#define MAXADDRLEN 15
+
+/*
+ * Callback function for updating the Network status to the subscribers
+ *
+ * @param esResult ESResult provides the current state of the network connection status
+ */
+typedef void (*NetworkEventCallback)(ESResult esResult);
+
+typedef struct
+{
+ OCConnectivityType type;
+ // for WiFI
+ IPAddress ipaddr;
+ char ssid[MAXSSIDLEN];
+ // for BT, BLE
+ byte mac[6];
+} NetworkInfo;
+
+ESResult ConnectToWiFiNetwork(const char *ssid, const char *pass, NetworkEventCallback);
+ESResult getCurrentNetworkInfo(OCConnectivityType targetType, NetworkInfo *info);
+
+#endif
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// Do not remove the include below
+#include "Arduino.h"
+
+#include <string.h>
+#include "logger.h"
+#include "ocstack.h"
+#include "common.h"
+#include "networkHandler.h"
+#include "octypes.h"
+
+#ifndef ES_RESOURCE_HANDLER_H_
+#define ES_RESOURCE_HANDLER_H_
+
+typedef void (*ResourceEventCallback)(ESResult);
+
+/* Structure to represent a Light resource */
+typedef struct PROVRESOURCE
+{
+ OCResourceHandle handle;
+ int ps; // provisiong status, 1 : need to provisioning, 2 : Connected to Internet
+ int tnt; // target network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
+ char tnn[MAXSSIDLEN]; // target network name, i.e. SSID for WLAN, MAC address for BT
+ char cd[MAXNETCREDLEN]; // credential information
+} ProvResource;
+
+/* Structure to represent a Light resource */
+typedef struct NETRESOURCE
+{
+ OCResourceHandle handle;
+ int cnt; // current network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
+ int ant[MAXNUMTYPE]; // available network type, 1: WLAN, 2: BT, 3: BLE, 4: Zigbee, ...
+ char ipaddr[MAXADDRLEN]; // ip address
+ char cnn[MAXSSIDLEN]; // current network name
+} NetResource;
+
+OCStackResult CreateProvisioningResource();
+
+//created only for in case of wifi
+#ifdef ESWIFI
+OCStackResult CreateNetworkResource();
+#endif
+
+void GetTargetNetworkInfoFromProvResource(char *, char *);
+void RegisterResourceEventCallBack(ResourceEventCallback);
+
+#endif
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+/**
+ * @file
+ *
+ * This file contains the implementation for EasySetup Enrollee device
+ */
+
+#include "easysetup.h"
+
+#include "logger.h"
+#include "resourceHandler.h"
+
+/**
+ * @var ES_ENROLLEE_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_ENROLLEE_TAG "ES"
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+
+/**
+ * @var targetSsid
+ * @brief Target SSID of the Soft Access point to which the device has to connect
+ */
+static char *targetSsid;
+
+/**
+ * @var targetPass
+ * @brief Password of the target access point to which the device has to connect
+ */
+static char *targetPass;
+
+/**
+ * @var g_cbForEnrolleeStatus
+ * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback
+ */
+static EventCallback g_cbForEnrolleeStatus = NULL;
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+
+void EventCallbackInOnboarding(ESResult event);
+void EventCallbackInProvisioning(ESResult event);
+void EventCallbackAfterProvisioning(ESResult event);
+
+void EventCallbackInOnboarding(ESResult event)
+{
+ if (event == ES_NETWORKFOUND || event == ES_NETWORKCONNECTED)
+ {
+ if (g_cbForEnrolleeStatus != NULL)
+ {
+ g_cbForEnrolleeStatus(event);
+ }
+ }
+}
+
+void EventCallbackInProvisioning(ESResult event)
+{
+ ESResult res = ES_OK;
+
+ if (event == ES_RECVTRIGGEROFPROVRES)
+ {
+ targetSsid = (char *) malloc(MAXSSIDLEN);
+ targetPass = (char *) malloc(MAXNETCREDLEN);
+
+ if(TerminateEasySetup() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, ES_ENROLLEE_TAG, "Terminating stack failed");
+ return;
+ }
+
+ GetTargetNetworkInfoFromProvResource(targetSsid, targetPass);
+
+ res = ConnectToWiFiNetwork(targetSsid, targetPass, EventCallbackAfterProvisioning);
+
+ if (g_cbForEnrolleeStatus != NULL)
+ {
+ g_cbForEnrolleeStatus(res);
+ }
+ }
+}
+
+void EventCallbackAfterProvisioning(ESResult event)
+{
+ if (event == ES_NETWORKFOUND || event == ES_NETWORKCONNECTED)
+ {
+ if (g_cbForEnrolleeStatus != NULL)
+ {
+ g_cbForEnrolleeStatus(event);
+ }
+ }
+}
+
+ESResult FindNetworkForOnboarding(OCConnectivityType networkType,
+ const char *ssid,
+ const char *passwd,
+ EventCallback cb)
+{
+ if (!ssid || !passwd)
+ {
+ return ES_ERROR;
+ }
+
+ if (networkType == CT_ADAPTER_IP)
+ {
+ if (g_cbForEnrolleeStatus == NULL)
+ {
+ g_cbForEnrolleeStatus = cb;
+ }
+
+ if(ConnectToWiFiNetwork(ssid, passwd, EventCallbackInOnboarding) != ES_NETWORKCONNECTED)
+ {
+ OC_LOG(ERROR, ES_ENROLLEE_TAG, "ConnectToWiFiNetwork Failed");
+ cb(ES_NETWORKNOTCONNECTED);
+ return ES_ERROR;
+ }
+ else{
+ OC_LOG(INFO, ES_ENROLLEE_TAG, "ConnectToWiFiNetwork Success");
+ cb(ES_NETWORKCONNECTED);
+ return ES_OK;
+ }
+ }
+ return ES_ERROR;
+}
+
+
+ESResult InitEasySetup(OCConnectivityType networkType, const char *ssid, const char *passwd,
+ EventCallback cb)
+{
+ if(FindNetworkForOnboarding(networkType, ssid, passwd, cb) != ES_OK)
+ {
+ OC_LOG(ERROR, ES_ENROLLEE_TAG, "OnBoarding Failed");
+ return ES_ERROR;
+ }
+
+ // Initialize the OC Stack in Server mode
+ if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, ES_ENROLLEE_TAG, "OCStack init error");
+ return ES_ERROR;
+ }
+ else
+ {
+ OC_LOG(DEBUG, ES_ENROLLEE_TAG, "OCStack init success");
+ return ES_OK;
+ }
+}
+
+ESResult TerminateEasySetup()
+{
+ if(OCStop() != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, ES_ENROLLEE_TAG, "OCStack stop failed");
+ return ES_ERROR;
+ }
+ else
+ {
+ OC_LOG(ERROR, ES_ENROLLEE_TAG, "OCStack stop success");
+ return ES_OK;
+ }
+}
+
+ESResult InitProvisioning()
+{
+ if (CreateProvisioningResource() != OC_STACK_OK)
+ {
+ return ES_ERROR;
+ }
+
+ if (CreateNetworkResource() != OC_STACK_OK)
+ {
+ return ES_ERROR;
+ }
+
+ RegisterResourceEventCallBack(EventCallbackInProvisioning);
+
+ return ES_RESOURCECREATED;
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "resourceHandler.h"
+#include "ocpayload.h"
+
+/**
+ * @var ES_RH_TAG
+ * @brief Logging tag for module name.
+ */
+#define ES_RH_TAG "ES_RH"
+
+//-----------------------------------------------------------------------------
+// Private variables
+//-----------------------------------------------------------------------------
+
+/**
+ * @var g_prov
+ * @brief Structure for holding the Provisioning status and target information required to connect to the target network
+ */
+static ProvResource g_prov;
+
+/**
+ * @var g_net
+ * @brief Structure forr holding the Provisioning status of network information
+ */
+static NetResource g_net;
+
+//-----------------------------------------------------------------------------
+// Private internal function prototypes
+//-----------------------------------------------------------------------------
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest *ehRequest, void *callback);
+const char *getResult(OCStackResult result);
+
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload** payload);
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload** payload);
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload** payload);
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest);
+
+int g_flag = 0;
+
+ResourceEventCallback g_cbForResEvent = NULL;
+
+void RegisterResourceEventCallBack(ResourceEventCallback cb)
+{
+ g_cbForResEvent = cb;
+}
+
+void GetTargetNetworkInfoFromProvResource(char *name, char *pass)
+{
+ if (name != NULL && pass != NULL)
+ {
+ sprintf(name, "%s", g_prov.tnn);
+ sprintf(pass, "%s", g_prov.cd);
+ }
+}
+
+OCStackResult CreateProvisioningResource()
+{
+ g_prov.ps = 1; // need to provisioning
+ g_prov.tnt = CT_ADAPTER_IP;
+ sprintf(g_prov.tnn, "Unknown");
+ sprintf(g_prov.cd, "Unknown");
+
+ OCStackResult res = OCCreateResource(&g_prov.handle, "oic.r.prov", OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_PROV, OCEntityHandlerCb, NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+ OC_LOG_V(INFO, ES_RH_TAG, "Created Prov resource with result: %s", getResult(res));
+
+ return res;
+}
+#ifdef ESWIFI
+OCStackResult CreateNetworkResource()
+{
+ NetworkInfo netInfo;
+
+ if (getCurrentNetworkInfo(CT_ADAPTER_IP, &netInfo) != ES_OK)
+ {
+ return OC_STACK_ERROR;
+ }
+
+ if (netInfo.type != CT_ADAPTER_IP)
+ {
+ return OC_STACK_ERROR;
+ }
+
+ g_net.cnt = (int) netInfo.type;
+ g_net.ant[0] = (int) CT_ADAPTER_IP;
+ sprintf(g_net.ipaddr, "%d.%d.%d.%d", netInfo.ipaddr[0], netInfo.ipaddr[1], netInfo.ipaddr[2],
+ netInfo.ipaddr[3]);
+ sprintf(g_net.cnn, "%s", netInfo.ssid);
+
+ OC_LOG_V(INFO, ES_RH_TAG, "SSID: %s", g_net.cnn);
+ OC_LOG_V(INFO, ES_RH_TAG, "IP Address: %s", g_net.ipaddr);
+
+ OCStackResult res = OCCreateResource(&g_net.handle, "oic.r.net", OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_ES_URI_NET, OCEntityHandlerCb,NULL, OC_DISCOVERABLE | OC_OBSERVABLE);
+ OC_LOG_V(INFO, ES_RH_TAG, "Created Net resource with result: %s", getResult(res));
+
+ return res;
+}
+#endif
+OCEntityHandlerResult ProcessGetRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload **payload)
+{
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ if (!ehRequest)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Request is Null");
+ return ehResult;
+ }
+ if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+ return ehResult;
+ }
+
+ OCRepPayload *getResp = constructResponse(ehRequest);
+ if (!getResp)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
+ return OC_EH_ERROR;
+ }
+
+ *payload = getResp;
+ ehResult = OC_EH_OK;
+
+ return ehResult;
+}
+
+OCEntityHandlerResult ProcessPutRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload** payload)
+{
+
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+ return ehResult;
+ }
+
+ OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
+ if (!input)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
+ return ehResult;
+ }
+
+ char* tnn;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn))
+ {
+ sprintf(g_prov.tnn, "%s", tnn);
+ }
+
+ char* cd;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd))
+ {
+ sprintf(g_prov.cd, "%s", cd);
+ }
+
+ g_flag = 1;
+
+ OCRepPayload *getResp = constructResponse(ehRequest);
+ if (!getResp)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "constructResponse failed");
+ return OC_EH_ERROR;
+ }
+
+ *payload = getResp;
+ ehResult = OC_EH_OK;
+
+ return ehResult;
+}
+
+OCEntityHandlerResult ProcessPostRequest(OCEntityHandlerRequest *ehRequest,
+ OCRepPayload** payload)
+{
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ if (!ehRequest)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Request is Null");
+ return ehResult;
+ }
+ if (ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Incoming payload not a representation");
+ return ehResult;
+ }
+
+ OCRepPayload* input = (OCRepPayload*) (ehRequest->payload);
+ if (!input)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Failed to parse");
+ return ehResult;
+ }
+ char* tr;
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TR, &tr))
+ {
+
+ // Triggering
+ ehResult = OC_EH_OK;
+ }
+
+ g_flag = 1;
+
+ return ehResult;
+}
+
+OCRepPayload* constructResponse(OCEntityHandlerRequest *ehRequest)
+{
+ OCRepPayload* payload = OCRepPayloadCreate();
+ if (!payload)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Failed to allocate Payload");
+ return NULL;
+ }
+
+ if (ehRequest->resource == g_prov.handle)
+ {
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_PROV);
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_PS, g_prov.ps);
+ OCRepPayloadSetPropInt(payload, OC_RSRVD_ES_TNT, g_prov.tnt);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, g_prov.tnn);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, g_prov.cd);
+ }
+ else if (ehRequest->requestHandle == g_net.handle)
+ {
+
+ OCRepPayloadSetUri(payload, OC_RSRVD_ES_URI_NET);
+ OCRepPayloadSetPropInt(payload, "ant", g_net.ant[0]);
+ }
+ return payload;
+}
+
+// This is the entity handler for the registered resource.
+// This is invoked by OCStack whenever it recevies a request for this resource.
+OCEntityHandlerResult OCEntityHandlerCb(OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest* entityHandlerRequest, void *callback)
+{
+ (void) callback;
+ OCEntityHandlerResult ehRet = OC_EH_OK;
+ OCEntityHandlerResponse response =
+ { 0 };
+ OCRepPayload* payload = NULL;
+ if (entityHandlerRequest && (flag & OC_REQUEST_FLAG))
+ {
+ if (OC_REST_GET == entityHandlerRequest->method)
+ {
+ OC_LOG(INFO, ES_RH_TAG, "Received GET request");
+ ehRet = ProcessGetRequest(entityHandlerRequest, &payload);
+ }
+ else if (OC_REST_PUT == entityHandlerRequest->method)
+ {
+ OC_LOG(INFO, ES_RH_TAG, "Received PUT request");
+
+ if (g_prov.handle != NULL && entityHandlerRequest->resource == g_prov.handle)
+ {
+ ehRet = ProcessPutRequest(entityHandlerRequest, &payload);
+ }
+ else
+ {
+ ehRet = OC_EH_ERROR;
+ }
+ }
+ else if (OC_REST_POST == entityHandlerRequest->method)
+ {
+ // TODO: As of now, POST request will be not received.
+ OC_LOG(INFO, ES_RH_TAG, "Received OC_REST_POST from client");
+ //ehRet = ProcessPostRequest (entityHandlerRequest, payload, sizeof(payload) - 1);
+ }
+
+ if (ehRet == OC_EH_OK)
+ {
+ // Format the response. Note this requires some info about the request
+ response.requestHandle = entityHandlerRequest->requestHandle;
+ response.resourceHandle = entityHandlerRequest->resource;
+ response.ehResult = ehRet;
+ //response uses OCPaylod while all get,put methodes use OCRepPayload
+ response.payload = (OCPayload*) (payload);
+ response.numSendVendorSpecificHeaderOptions = 0;
+ memset(response.sendVendorSpecificHeaderOptions, 0,
+ sizeof response.sendVendorSpecificHeaderOptions);
+ memset(response.resourceUri, 0, sizeof response.resourceUri);
+ // Indicate that response is NOT in a persistent buffer
+ response.persistentBufferFlag = 0;
+
+ // Send the response
+ if (OCDoResponse(&response) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, ES_RH_TAG, "Error sending response");
+ ehRet = OC_EH_ERROR;
+ }
+ }
+ }
+
+ if (g_flag == 1)
+ {
+ g_cbForResEvent(ES_RECVTRIGGEROFPROVRES);
+ g_flag = 0;
+ }
+
+ return ehRet;
+}
+
+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";
+ }
+}
+
--- /dev/null
+#built application files\r
+*.apk\r
+*.ap_\r
+\r
+# files for the dex VM\r
+*.dex\r
+\r
+# Java class files\r
+*.class\r
+\r
+# generated files\r
+bin/\r
+gen/\r
+\r
+# Local configuration file (sdk path, etc)\r
+local.properties\r
+\r
+# Proguard folder generated by Eclipse \r
+proguard/ \r
+\r
+# Windows thumbnail db\r
+Thumbs.db\r
+\r
+# OSX files\r
+.DS_Store\r
+\r
+# Eclipse project files\r
+.classpath\r
+.project\r
+\r
+#Android Studio & Gradle\r
+.gradle\r
+/local.properties\r
+/.idea/workspace.xml\r
+/.idea/libraries\r
+.DS_Store\r
+/build/*\r
+/base/build/*\r
+/base/obj/*\r
+/base/libs/*\r
+/sample/*\r
+\r
+#Some older projects\r
+/*/out\r
+/*/*/build\r
+/*/*/production\r
+*.iws\r
+*.ipr\r
+*~\r
+*.swp
\ No newline at end of file
--- /dev/null
+apply plugin: 'com.android.library'\r
+// Top-level build file where you can add configuration options common to all sub-projects/modules.\r
+buildscript {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+ dependencies {\r
+ classpath 'com.android.tools.build:gradle:1.2.3'\r
+ }\r
+}\r
+\r
+allprojects {\r
+ repositories {\r
+ jcenter()\r
+ }\r
+}\r
+\r
+android {\r
+ compileSdkVersion 21\r
+ buildToolsVersion '21.1.2'\r
+\r
+ defaultConfig {\r
+ minSdkVersion 21\r
+ targetSdkVersion 21\r
+ }\r
+\r
+ buildTypes {\r
+ release {\r
+ minifyEnabled false\r
+ proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'\r
+ }\r
+ }\r
+ sourceSets {\r
+ main { java.srcDirs = ['src/main/java', 'src/main/java/common', 'src/main/java/interface'] }\r
+ }\r
+}\r
+\r
+dependencies {\r
+ compile project(':iotivity-armeabi-base-debug')\r
+}
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module external.linked.project.id="EasySetupCore" external.linked.project.path="$MODULE_DIR$" external.root.project.path="$MODULE_DIR$" external.system.id="GRADLE" external.system.module.group="" external.system.module.version="unspecified" type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android-gradle" name="Android-Gradle">
+ <configuration>
+ <option name="GRADLE_PROJECT_PATH" value=":" />
+ </configuration>
+ </facet>
+ <facet type="android" name="Android">
+ <configuration>
+ <option name="SELECTED_BUILD_VARIANT" value="debug" />
+ <option name="SELECTED_TEST_ARTIFACT" value="_android_test_" />
+ <option name="ASSEMBLE_TASK_NAME" value="assembleDebug" />
+ <option name="COMPILE_JAVA_TASK_NAME" value="compileDebugSources" />
+ <option name="ASSEMBLE_TEST_TASK_NAME" value="assembleDebugAndroidTest" />
+ <option name="COMPILE_JAVA_TEST_TASK_NAME" value="compileDebugAndroidTestSources" />
+ <option name="ALLOW_USER_CONFIGURATION" value="false" />
+ <option name="MANIFEST_FILE_RELATIVE_PATH" value="/src/main/AndroidManifest.xml" />
+ <option name="RES_FOLDER_RELATIVE_PATH" value="/src/main/res" />
+ <option name="ASSETS_FOLDER_RELATIVE_PATH" value="/src/main/assets" />
+ <option name="LIBRARY_PROJECT" value="true" />
+ </configuration>
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" inherit-compiler-output="false">
+ <output url="file://$MODULE_DIR$/build/intermediates/classes/debug" />
+ <output-test url="file://$MODULE_DIR$/build/intermediates/classes/androidTest/debug" />
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/debug" isTestSource="false" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/debug" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/r/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/aidl/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/buildConfig/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/source/rs/androidTest/debug" isTestSource="true" generated="true" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/rs/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/build/generated/res/generated/androidTest/debug" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/debug/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/res" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/resources" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/assets" type="java-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/aidl" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java/common" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/java/interface" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/jni" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/main/rs" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/res" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/resources" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/assets" type="java-test-resource" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/aidl" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/java" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/jni" isTestSource="true" />
+ <sourceFolder url="file://$MODULE_DIR$/src/androidTest/rs" isTestSource="true" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/assets" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/bundles" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/coverage-instrumented-classes" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dependency-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/dex-cache" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/exploded-aar/EasySetupCore/iotivity-armeabi-base-debug/unspecified/jars" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/incremental" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/jacoco" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/javaResources" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/libs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/lint" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/manifests" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/ndk" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/pre-dexed" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/proguard" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/res" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/rs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/intermediates/symbols" />
+ <excludeFolder url="file://$MODULE_DIR$/build/outputs" />
+ <excludeFolder url="file://$MODULE_DIR$/build/tmp" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="module" module-name="iotivity-armeabi-base-debug" exported="" />
+ <orderEntry type="library" exported="" name="iotivity-armeabi-base-debug-unspecified" level="project" />
+ </component>
+</module>
\ No newline at end of file
--- /dev/null
+include ':iotivity-armeabi-base-debug'
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+ <component name="NewModuleRootManager" inherit-compiler-output="true">
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
+ </content>
+ <orderEntry type="inheritedJdk" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="library" name="classes" level="project" />
+ <orderEntry type="module" module-name="main" />
+ </component>
+</module>
\ No newline at end of file
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+import android.test.AndroidTestCase;\r
+\r
+import junit.framework.Assert;\r
+\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;\r
+\r
+\r
+public class EasySetupServiceConfigTest extends AndroidTestCase {\r
+\r
+\r
+ public void testConstruction() {\r
+\r
+ EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {\r
+ @Override\r
+ public void onFinished(EnrolleeDevice enrolledevice) {\r
+\r
+ }\r
+\r
+ @Override\r
+ public void onProgress(EnrolleeDevice enrolleeDevice) {\r
+\r
+ }\r
+ });\r
+\r
+ assertTrue(service != null);\r
+\r
+\r
+ }\r
+\r
+ public void testFinish() {\r
+ EasySetupService service = EasySetupService.getInstance(getContext(), new EasySetupStatus() {\r
+ @Override\r
+ public void onFinished(EnrolleeDevice enrolledevice) {\r
+\r
+ }\r
+\r
+ @Override\r
+ public void onProgress(EnrolleeDevice enrolleeDevice) {\r
+\r
+ }\r
+ });\r
+ service.finish();\r
+\r
+ // No runtime exception is thrown means test is successful\r
+ assertTrue(true);\r
+\r
+ }\r
+\r
+ public void testEnrolleeDeviceFacotryConstruction() {\r
+ EnrolleeDeviceFactory factory = EnrolleeDeviceFactory.newInstance(getContext());\r
+ assertTrue(factory != null);\r
+ }\r
+\r
+}\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2015 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+package org.iotivity.service.easysetup.core;\r
+\r
+import android.net.wifi.WifiConfiguration;\r
+import android.test.AndroidTestCase;\r
+import android.util.Log;\r
+\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceWiFiOnboarding;\r
+import org.iotivity.service.easysetup.impl.WiFiOnBoardingConfig;\r
+import org.iotivity.service.easysetup.impl.WiFiProvConfig;\r
+\r
+import java.io.IOException;\r
+\r
+public class EasySetupServiceTest extends AndroidTestCase {\r
+\r
+\r
+ public void testStartSetupWithWiFiOnboarding() {\r
+\r
+ EasySetupService mService;\r
+ EnrolleeDevice mDevice;\r
+ EnrolleeDeviceFactory mFactory;\r
+\r
+ final Object lock = new Object();\r
+\r
+\r
+ /* Create Easy Setup service */\r
+ mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {\r
+ @Override\r
+ public void onFinished(EnrolleeDevice enrolledevice) {\r
+\r
+ //countDownLatch.countDown();\r
+ Utility.toNotify(lock);\r
+\r
+ if (enrolledevice.isSetupSuccessful()) {\r
+\r
+ if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {\r
+ IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();\r
+ String ip = conn.getIp();\r
+ if (ip == null || ip.isEmpty()) {\r
+ assertTrue(false);\r
+ return;\r
+ }\r
+ String mac = conn.getHardwareAddress();\r
+ if (mac == null || mac.isEmpty()) {\r
+ assertTrue(false);\r
+ return;\r
+ }\r
+ // Device configured successfully\r
+ assertTrue(true);\r
+ }\r
+\r
+ } else {\r
+ assertTrue(false);\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void onProgress(EnrolleeDevice enrolleeDevice) {\r
+ // Handled in EasySetupStatusTest\r
+ }\r
+ });\r
+\r
+\r
+ /* Create On boarding configuration */\r
+ WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
+ mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
+ mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
+ mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
+ mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
+\r
+ /* Create provisioning configuration */\r
+ WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
+\r
+ /* Create enrolling device factory instance */\r
+ mFactory = EnrolleeDeviceFactory.newInstance(getContext());\r
+\r
+ /* Check if the factory created successfully */\r
+ assertTrue(mFactory != null);\r
+\r
+ /* Create enrolling device */\r
+ mDevice = mFactory.newEnrolleeDevice(mWiFiOnBoardingConfig, mWiFiProvConfig);\r
+\r
+ /* Check if the the device is created successfully*/\r
+ assertTrue(mDevice != null);\r
+\r
+ /* Check if the the correct device is created as per the given configuration*/\r
+ assertTrue((mDevice instanceof EnrolleeDeviceWiFiOnboarding));\r
+\r
+\r
+ try {\r
+ mService.startSetup(mDevice);\r
+ // If no exception is thrown means setup started successfully.\r
+ assertTrue(true);\r
+\r
+ } catch (IOException e) {\r
+ assertTrue(false);\r
+ }\r
+\r
+ try {\r
+\r
+ Utility.toWait(lock);\r
+\r
+ Log.i("EasySetupTest", "Lock is released");\r
+\r
+ if (!mDevice.isSetupSuccessful()) {\r
+ assertTrue(false);\r
+ return;\r
+ }\r
+\r
+ IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();\r
+ if (conn == null) {\r
+ assertTrue(false);\r
+ return;\r
+ }\r
+\r
+ String ip = conn.getIp();\r
+ if (ip == null || ip.isEmpty()) {\r
+ assertTrue(false);\r
+ return;\r
+ }\r
+\r
+ String mac = conn.getHardwareAddress();\r
+ if (mac == null || mac.isEmpty()) {\r
+ assertTrue(false);\r
+ return;\r
+ }\r
+\r
+ Log.i("EasySetupTest", "Ip" + conn.getIp());\r
+ Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());\r
+\r
+ // Device configured successfully\r
+ assertTrue(true);\r
+\r
+ } catch (Exception e) {\r
+ e.printStackTrace();\r
+ assertTrue(false);\r
+ }\r
+\r
+ }\r
+\r
+}
\ No newline at end of file
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+package org.iotivity.service.easysetup.core;
+
+import android.net.wifi.WifiConfiguration;
+import android.test.AndroidTestCase;
+import android.util.Log;
+
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceWiFiOnboarding;
+import org.iotivity.service.easysetup.impl.WiFiOnBoardingConfig;
+import org.iotivity.service.easysetup.impl.WiFiProvConfig;
+
+import java.io.IOException;
+
+public class EasySetupStatusTest extends AndroidTestCase {
+
+
+ public void testStartSetupWithWiFiOnboarding() {
+
+ EasySetupService mService;
+ EnrolleeDevice mDevice;
+ EnrolleeDeviceFactory mFactory;
+
+ final Object lock = new Object();
+
+
+ /* Create Easy Setup service */
+ mService = EasySetupService.getInstance(getContext(), new EasySetupStatus() {
+ EnrolleeState old_state = null;
+
+ @Override
+ public void onFinished(EnrolleeDevice enrolledevice) {
+
+ //countDownLatch.countDown();
+ Utility.toNotify(lock);
+
+ if (enrolledevice.isSetupSuccessful()) {
+
+ if (enrolledevice.mOnBoardingConfig.getConnType() == WiFiOnBoardingConfig.ConnType.WiFi) {
+ IpOnBoardingConnection conn = (IpOnBoardingConnection) enrolledevice.getConnection();
+ String ip = conn.getIp();
+ if (ip == null || ip.isEmpty()) {
+ assertTrue(false);
+ return;
+ }
+ String mac = conn.getHardwareAddress();
+ if (mac == null || mac.isEmpty()) {
+ assertTrue(false);
+ return;
+ }
+ // Device configured successfully
+ assertTrue(true);
+ }
+
+ } else {
+ assertTrue(false);
+ }
+ }
+
+ @Override
+ public void onProgress(EnrolleeDevice enrolleeDevice) {
+ EnrolleeState state = enrolleeDevice.mState;
+ // TODO
+ switch (state) {
+ case DEVICE_INIT_STATE:
+ Log.d("enrollee state", "DEVICE_INIT_STATE");
+ assertTrue(false);
+ break;
+ case DEVICE_ON_BOARDING_STATE:
+ if (old_state == null)
+ assertTrue(true);
+ else assertTrue(false);
+ old_state = EnrolleeState.DEVICE_ON_BOARDING_STATE;
+ Log.d("enrollee state", "DEVICE_ON_BOARDING_STATE");
+ break;
+
+ case DEVICE_ON_BOARDED_STATE:
+ if (old_state == EnrolleeState.DEVICE_ON_BOARDING_STATE)
+ assertTrue(true);
+ else assertTrue(false);
+ old_state = EnrolleeState.DEVICE_ON_BOARDED_STATE;
+ Log.d("enrollee state", "DEVICE_ON_BOARDED_STATE");
+ break;
+
+ case DEVICE_PROVISIONING_STATE:
+ if (old_state == EnrolleeState.DEVICE_ON_BOARDED_STATE)
+ assertTrue(true);
+ else assertTrue(false);
+ old_state = EnrolleeState.DEVICE_PROVISIONING_STATE;
+ Log.d("enrollee state", "DEVICE_PROVISIONING_STATE");
+ break;
+
+ case DEVICE_PROVISIONED_STATE:
+ if (old_state == EnrolleeState.DEVICE_PROVISIONING_STATE)
+ assertTrue(true);
+ else assertTrue(false);
+ Log.d("enrollee state", "DEVICE_PROVISIONING_SUCCESS_STATE");
+ break;
+
+ default:
+ Log.d("enrollee state", "unknown state");
+ assertTrue(false);
+ break;
+ }
+
+ }
+ });
+
+
+ /* Create On boarding configuration */
+ WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();
+ mWiFiOnBoardingConfig.setSSId("EasySetup123");
+ mWiFiOnBoardingConfig.setSharedKey("EasySetup123");
+ mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);
+ mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);
+
+ /* Create provisioning configuration */
+ WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");
+
+ /* Create enrolling device factory instance */
+ mFactory = EnrolleeDeviceFactory.newInstance(getContext());
+
+ /* Create enrolling device */
+ mDevice = mFactory.newEnrolleeDevice(mWiFiOnBoardingConfig, mWiFiProvConfig);
+
+ try {
+ mService.startSetup(mDevice);
+ } catch (IOException e) {
+ }
+
+ try {
+
+ Utility.toWait(lock);
+
+ Log.i("EasySetupTest", "Lock is released");
+
+ IpOnBoardingConnection conn = (IpOnBoardingConnection) mDevice.getConnection();
+
+ Log.i("EasySetupTest", "Ip" + conn.getIp());
+ Log.i("EasySetupTest", "MAC" + conn.getHardwareAddress());
+
+ // Device configured successfully
+
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+import android.net.wifi.WifiConfiguration;\r
+import android.test.AndroidTestCase;\r
+\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceFactory;\r
+import org.iotivity.service.easysetup.impl.EnrolleeDeviceWiFiOnboarding;\r
+import org.iotivity.service.easysetup.impl.WiFiOnBoardingConfig;\r
+import org.iotivity.service.easysetup.impl.WiFiProvConfig;\r
+\r
+public class EnrolleeDeviceFactoryTest extends AndroidTestCase {\r
+\r
+ EnrolleeDeviceFactory mFactory;\r
+\r
+ @Override\r
+ protected void setUp() throws Exception {\r
+ super.setUp();\r
+ mFactory = EnrolleeDeviceFactory.newInstance(getContext());\r
+ assertTrue(mFactory != null);\r
+\r
+ }\r
+\r
+ @Override\r
+ protected void tearDown() throws Exception {\r
+ super.tearDown();\r
+ mFactory = null;\r
+ }\r
+\r
+\r
+ public void testNewEnrolleeDevice_with_WiFiOnboarding() {\r
+\r
+ /* Create On boarding configuration */\r
+ WiFiOnBoardingConfig mWiFiOnBoardingConfig = new WiFiOnBoardingConfig();\r
+ mWiFiOnBoardingConfig.setSSId("EasySetup123");\r
+ mWiFiOnBoardingConfig.setSharedKey("EasySetup123");\r
+ mWiFiOnBoardingConfig.setAuthAlgo(WifiConfiguration.AuthAlgorithm.OPEN);\r
+ mWiFiOnBoardingConfig.setKms(WifiConfiguration.KeyMgmt.WPA_PSK);\r
+\r
+ /* Create provisioning configuration */\r
+ WiFiProvConfig mWiFiProvConfig = new WiFiProvConfig("hub2.4G", "11112222");\r
+\r
+ /* Create enrolling device */\r
+ EnrolleeDevice device = mFactory.newEnrolleeDevice(mWiFiOnBoardingConfig, mWiFiProvConfig);\r
+\r
+ /* Check if the the device is created */\r
+ assertTrue(device != null);\r
+\r
+ /* Check if the the correct device is created as per the given configuration*/\r
+ assertTrue((device instanceof EnrolleeDeviceWiFiOnboarding));\r
+\r
+ }\r
+\r
+}\r
--- /dev/null
+//******************************************************************\r
+//\r
+// Copyright 2015 Samsung Electronics All Rights Reserved.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+//\r
+// Licensed under the Apache License, Version 2.0 (the "License");\r
+// you may not use this file except in compliance with the License.\r
+// You may obtain a copy of the License at\r
+//\r
+// http://www.apache.org/licenses/LICENSE-2.0\r
+//\r
+// Unless required by applicable law or agreed to in writing, software\r
+// distributed under the License is distributed on an "AS IS" BASIS,\r
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+// See the License for the specific language governing permissions and\r
+// limitations under the License.\r
+//\r
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=\r
+\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+\r
+public class Utility {\r
+\r
+ public static void toNotify(Object toLock) {\r
+ synchronized (toLock) {\r
+ toLock.notify();\r
+ }\r
+ }\r
+\r
+ public static void toWait(Object toLock) {\r
+ synchronized (toLock) {\r
+ try {\r
+ toLock.wait(45000);\r
+ } catch (InterruptedException e) {\r
+ e.printStackTrace();\r
+ }\r
+ }\r
+ }\r
+}\r
--- /dev/null
+<manifest xmlns:android="http://schemas.android.com/apk/res/android"
+ package="org.iotivity.service.easysetup.mediator"
+ android:versionCode="1"
+ android:versionName="1.0" >
+
+ <uses-sdk
+ android:minSdkVersion="8"
+ android:targetSdkVersion="21" />
+
+ <application
+ android:allowBackup="true"
+ android:icon="@drawable/ic_launcher"
+ android:label="@string/app_name"
+ android:theme="@style/AppTheme" >
+ </application>
+
+</manifest>
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+import android.content.Context;\r
+import android.util.Log;\r
+\r
+import org.iotivity.service.easysetup.mediator.EasySetupManager;\r
+import org.iotivity.service.easysetup.mediator.ProvisionEnrollee;\r
+\r
+import java.io.IOException;\r
+import java.util.ArrayList;\r
+\r
+/**\r
+ * This is facade class, a single point of contact for Application.\r
+ * It contains set of APIs to do easy setup of the enrolling device.\r
+ * ON-BOARDING - This is a step to establish connectivity between the device & Mediator device.\r
+ * PROVISION - This is a step where the netowork's detail & credentials are given to the\r
+ * enrolling device.\r
+ */\r
+public class EasySetupService {\r
+\r
+ private static final String TAG = EasySetupService.class.getName();\r
+\r
+ private static EasySetupService sInstance;\r
+\r
+ private final EasySetupStatus mCallback;\r
+\r
+ private ArrayList<EnrolleeDevice> mEnrolleeDeviceList;\r
+\r
+ private final ProvisioningCallback mProvisioningCallback;\r
+\r
+ private static Context mContext;\r
+\r
+\r
+ ProvisionEnrollee mProvisionEnrolleeInstance;\r
+\r
+ private EasySetupService(EasySetupStatus callback) {\r
+ mCallback = callback;\r
+ mProvisioningCallback = new ProvisioningCallbackImpl(mCallback);\r
+ mEnrolleeDeviceList = new ArrayList<EnrolleeDevice>();\r
+ mContext = null;\r
+\r
+ }\r
+\r
+ /**\r
+ * Gives a singleton instance of Easy setup service and initialize the service\r
+ *\r
+ * @param callback Application needs to provide this callback to receive the status of easy\r
+ * setup process.\r
+ */\r
+\r
+ public synchronized static EasySetupService getInstance(Context context, EasySetupStatus\r
+ callback) {\r
+ if (sInstance == null) {\r
+ sInstance = new EasySetupService(callback);\r
+ mContext = context;\r
+ }\r
+ return sInstance;\r
+ }\r
+\r
+ /**\r
+ * Reset the Easy setup Service\r
+ */\r
+\r
+ public void finish() {\r
+\r
+ //Native Api call to reset OIC stack\r
+ if (mProvisionEnrolleeInstance != null) {\r
+ mProvisionEnrolleeInstance.stopEnrolleeProvisioning(0);\r
+ }\r
+ }\r
+\r
+ /**\r
+ * Starts Easy setup process for the enrolling device.\r
+ *\r
+ * @param enrolledevice Device to be enrolled in network\r
+ * @throws IOException Throws exception in case of any connection error.\r
+ */\r
+\r
+ public synchronized void startSetup(final EnrolleeDevice enrolledevice) throws IOException {\r
+\r
+ mEnrolleeDeviceList.add(enrolledevice);\r
+\r
+\r
+ // Starts the provisioning directly if the device is already on boarded on the network.\r
+ if (enrolledevice.onBoarded()) {\r
+ enrolledevice.startProvisioning(mProvisioningCallback);\r
+ return;\r
+ }\r
+ enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;\r
+\r
+ mCallback.onProgress(enrolledevice);\r
+ enrolledevice.startOnBoarding(new OnBoardingCallback() {\r
+\r
+ @Override\r
+ public void onFinished(OnBoardingConnection connection) {\r
+ if (connection.isConnected()) {\r
+ Log.i(TAG, "On boarding is successful ");\r
+ // Start provisioning here\r
+ enrolledevice.mState = EnrolleeState.DEVICE_ON_BOARDED_STATE;\r
+ mCallback.onProgress(enrolledevice);\r
+ enrolledevice.setConnection(connection);\r
+ enrolledevice.startProvisioning(mProvisioningCallback);\r
+ } else {\r
+ enrolledevice.mState = EnrolleeState.DEVICE_INIT_STATE;\r
+ mProvisioningCallback.onFinished(enrolledevice);\r
+ }\r
+\r
+ }\r
+\r
+ });\r
+\r
+ }\r
+\r
+ /**\r
+ * Stops on-going Easy setup process for enrolling device.\r
+ *\r
+ * @param enrolleedevice Device to be enrolled in network\r
+ */\r
+ public synchronized void stopSetup(EnrolleeDevice enrolleedevice) {\r
+ if (mEnrolleeDeviceList.contains(enrolleedevice)) {\r
+ enrolleedevice.mState = EnrolleeState.DEVICE_INIT_STATE;\r
+ mCallback.onProgress(enrolleedevice);\r
+ if (enrolleedevice.mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {\r
+ Log.i(TAG, "stopOnBoardingProcess for enrolleedevice");\r
+ enrolleedevice.stopOnBoardingProcess();\r
+ mEnrolleeDeviceList.remove(enrolleedevice);\r
+ } else if (enrolleedevice.mState == EnrolleeState.DEVICE_PROVISIONING_STATE) {\r
+ Log.i(TAG, "stopOnBoardingProcess for enrolleedevice");\r
+ enrolleedevice.stopOnBoardingProcess();\r
+ Log.i(TAG, "stopEnrolleeProvisioning for enrolleedevice");\r
+ //Native Api call to stop on-going enrolling process for the enrolling device\r
+ EasySetupManager.getInstance().stopEnrolleeProvisioning(enrolleedevice\r
+ .mOnBoardingConfig.getConnType().getValue());\r
+ mEnrolleeDeviceList.remove(enrolleedevice);\r
+\r
+ }\r
+ }\r
+ }\r
+\r
+ class ProvisioningCallbackImpl extends ProvisioningCallback {\r
+\r
+ private final EasySetupStatus mCallback;\r
+\r
+ ProvisioningCallbackImpl(EasySetupStatus callback) {\r
+ mCallback = callback;\r
+ }\r
+\r
+ @Override\r
+ public void onFinished(EnrolleeDevice enrolledevice) {\r
+ synchronized (EasySetupService.this) {\r
+ if (mEnrolleeDeviceList.contains(enrolledevice)) {\r
+ Log.i(TAG, "onFinished() is received " + enrolledevice.isSetupSuccessful());\r
+ mCallback.onFinished(enrolledevice);\r
+ mEnrolleeDeviceList.remove(enrolledevice);\r
+ }\r
+ }\r
+ }\r
+\r
+ @Override\r
+ public void onProgress(EnrolleeDevice enrolledevice) {\r
+ mCallback.onProgress(enrolledevice);\r
+ }\r
+\r
+\r
+ }\r
+}
\ No newline at end of file
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+/**
+ * This interface facilitates Application to get progress & result of Easy setup
+ * process Easy setup process.
+ */
+public interface EasySetupStatus {
+
+ /**
+ * This method is called back when easy setup process is finished. Easy
+ * setup process status can read from the APIs given in Enrollee class.This
+ * method is called on worker thread, UI operations to be executed on main /
+ * Ui Thread.
+ *
+ * @param enrolledevice Device to be enrolled in network through Easy setup process
+ */
+ public void onFinished(EnrolleeDevice enrolledevice);
+
+ /**
+ * This method is called back to give intermediate progress on the easy
+ * setup process This method is called on worker thread, UI operations to be
+ * executed on main / Ui Thread.
+ *
+ * @param enrolleeDevice Gives state of the device changed during easy setup process
+ */
+ public void onProgress(EnrolleeDevice enrolleeDevice);
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+/**\r
+ * This is an abstract class represents the device being provisioned into the network. The\r
+ * device being enrolled or provisioned into the network is called Enrollee.\r
+ * Application has to extend this class and provide implementation of abstract methods according\r
+ * to the ON-BOARDING & PROVISION connectivity i.e. WiFi etc.\r
+ */\r
+\r
+public abstract class EnrolleeDevice {\r
+\r
+ protected EnrolleeState mState;\r
+ private EnrolleeSetupError mError;\r
+\r
+ protected OnBoardingConnection mConnection;\r
+ protected final ProvisioningConfig mProvConfig;\r
+ protected final OnBoardingConfig mOnBoardingConfig;\r
+\r
+ protected OnBoardingCallback mOnBoardingCallback;\r
+ protected ProvisioningCallback mProvisioningCallback;\r
+\r
+ /**\r
+ * @param onBoardingConfig Contains details about the connectivity to be established between\r
+ * the Enrollee device & Mediator device in order to perform\r
+ * on-boarding\r
+ * @param provConfig Contains details about the network to which Enrollee device is\r
+ * going to connect.\r
+ */\r
+ protected EnrolleeDevice(OnBoardingConfig onBoardingConfig, ProvisioningConfig provConfig) {\r
+ mProvConfig = provConfig;\r
+ mOnBoardingConfig = onBoardingConfig;\r
+ }\r
+\r
+ /**\r
+ * Application has to implement it according to the on boarding connectivity the device is\r
+ * having.\r
+ * This method will be called back during the easy setup process.\r
+ */\r
+ protected abstract void startOnBoardingProcess();\r
+\r
+ /**\r
+ * This method is called back during the easy setup process if Application cancels the setup.\r
+ * Easy setup service checks the state of device and calls this function accordingly.\r
+ * Application has to provide implementation for this method to cancel the on boarding step.\r
+ */\r
+ protected abstract void stopOnBoardingProcess();\r
+\r
+ /**\r
+ * Application has to implement it according to the type of the network device is going to\r
+ * connect or provisioned.\r
+ * This method will be called back once on-boarding of the device is successful.\r
+ *\r
+ * @param conn Contains detail about the network established between the Enrollee device &\r
+ * Mediator device. Its implementation vary according to the connectivity type.\r
+ */\r
+ protected abstract void startProvisioningProcess(OnBoardingConnection conn);\r
+\r
+ /**\r
+ * Once on boarding is successful concrete Enrollee class would call this method and set the\r
+ * Connection.\r
+ *\r
+ * @param conn Connectivity between Enrollee device & Mediator device.\r
+ */\r
+ protected void setConnection(OnBoardingConnection conn) {\r
+ mConnection = conn;\r
+ }\r
+\r
+ /**\r
+ * This method returns the OnBoardingConnection object depending on the connection type\r
+ *\r
+ * @return onBoardingConnection object\r
+ */\r
+ public OnBoardingConnection getConnection() {\r
+ return mConnection;\r
+ }\r
+\r
+\r
+ /**\r
+ * This method is called back by Easy setup service if on boarding needs to be done.\r
+ *\r
+ * @param onBoardingCallback This is called back once the on boarding is completed.\r
+ */\r
+ void startOnBoarding(OnBoardingCallback onBoardingCallback) {\r
+ mOnBoardingCallback = onBoardingCallback;\r
+ startOnBoardingProcess();\r
+ }\r
+\r
+ /**\r
+ * This method is called back by Easy setup service once on boarding is successful\r
+ *\r
+ * @param provisioningCallback This is called back once the provisioning process is completed\r
+ */\r
+ void startProvisioning(ProvisioningCallback provisioningCallback) {\r
+ mProvisioningCallback = provisioningCallback;\r
+ startProvisioningProcess(mConnection);\r
+ }\r
+\r
+ /**\r
+ * This method is used to check easy setup status\r
+ *\r
+ * @return true if successful or false\r
+ */\r
+\r
+ public boolean isSetupSuccessful() {\r
+ return (mState == EnrolleeState.DEVICE_PROVISIONED_STATE) ? true : false;\r
+ }\r
+\r
+ /**\r
+ * sets error occured during easy setup process\r
+ */\r
+ protected void setError(EnrolleeSetupError error) {\r
+ mError = error;\r
+ }\r
+\r
+ /**\r
+ * Returns error occured during easy setup process\r
+ *\r
+ * @return True EnrolleeSetupError object\r
+ */\r
+ public EnrolleeSetupError getError() {\r
+ return mError;\r
+ }\r
+\r
+ /**\r
+ * Gives the state of the device being enrolled during the easy setup process.\r
+ *\r
+ * @return Returns EnrolleeState object\r
+ */\r
+ public EnrolleeState getState() {\r
+ return mState;\r
+ }\r
+\r
+ /**\r
+ * This method is used to know if the device is on boarded or not\r
+ *\r
+ * @return True if on-boarded successfully or False\r
+ */\r
+\r
+ protected boolean onBoarded() {\r
+ return (mState == EnrolleeState.DEVICE_PROVISIONING_STATE) ? true : false;\r
+ }\r
+\r
+\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+/**
+ * This class defines constants for Errors comes during Easy setup process
+ */
+public enum EnrolleeSetupError {
+ /**
+ * Device setup successful
+ */
+ DEVICE_SETUP_SUCCESSFUL,
+ /**
+ * Device setup failed
+ */
+ DEVICE_SETUP_FAILED,
+}
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+/**
+ * It defines various states of the Enrollee device during easy setup process
+ */
+
+public enum EnrolleeState {
+
+ /**
+ * Default state of the device
+ */
+ DEVICE_INIT_STATE,
+
+ /**
+ * Device will move to this state after successful on-boarding of the device
+ */
+ DEVICE_ON_BOARDED_STATE,
+
+ /**
+ * Device will move to this state once the on boarding begins
+ */
+ DEVICE_ON_BOARDING_STATE,
+
+ /**
+ * Device will move to this state once the on boarding is done
+ */
+ DEVICE_PROVISIONING_STATE,
+
+ /**
+ * Easy setup process is successful.
+ */
+ DEVICE_PROVISIONED_STATE,
+
+ /**
+ * This state is arbitrary one, any time device can come into this state
+ * Device will move to this state if the ownership transfer initiated by the Application
+ */
+ DEVICE_OWNERSHIP_TRANSFERRING_STATE,
+
+ /**
+ * This state is arbitrary one, any time device can come into this state
+ * Device will move to this state if the ownership transfer is completed
+ */
+ DEVICE_OWNERSHIP_TRANSFERRED_STATE,
+
+
+ /**
+ * This state is arbitrary one, any time device can come into this state
+ * Device will move to this state once the Application factory reset the device
+ */
+ DEVICE_FACTORY_RESET_STATE,
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+public class IpOnBoardingConnection implements OnBoardingConnection {\r
+\r
+ private boolean mIsConnected;\r
+ private String mIp;\r
+ private String mHardwareAddress;\r
+ private String mDeviceName;\r
+\r
+ public void setHardwareAddress(String address) {\r
+ mHardwareAddress = address;\r
+ }\r
+\r
+ public String getHardwareAddress() {\r
+ return mHardwareAddress;\r
+ }\r
+\r
+ public void setDeviceName(String name) {\r
+ mDeviceName = name;\r
+ }\r
+\r
+ public String getDeviceName() {\r
+ return mDeviceName;\r
+ }\r
+\r
+ public void setConnectivity(boolean connected) {\r
+ mIsConnected = connected;\r
+ }\r
+\r
+ public void setIp(String ip) {\r
+ mIp = ip;\r
+ }\r
+\r
+ public String getIp() {\r
+ return mIp;\r
+ }\r
+\r
+ @Override\r
+ public String getDesc() {\r
+ return "Description";\r
+ }\r
+\r
+ @Override\r
+ public boolean isConnected() {\r
+ return mIsConnected;\r
+ }\r
+\r
+ @Override\r
+ public Object getConnection() {\r
+ return this;\r
+ }\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+public abstract class OnBoardingCallback {\r
+ public abstract void onFinished(OnBoardingConnection connection);\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.core;\r
+\r
+import org.iotivity.base.OcConnectivityType;\r
+\r
+/**\r
+ * It contains configuration details about the connectivity type between the Enrollee device &\r
+ * Mediator device in order to perform on-boarding.\r
+ */\r
+\r
+public interface OnBoardingConfig {\r
+\r
+ /**\r
+ * It provides constants for connectivity types used for on-boarding Enrollee device\r
+ */\r
+ public static enum ConnType {\r
+ // Note : Enum Ids should matched with Native Ids\r
+ WiFi(OcConnectivityType.CT_DEFAULT.getValue()),\r
+ BLE(OcConnectivityType.CT_ADAPTER_GATT_BTLE.getValue());\r
+\r
+ private int mConnType;\r
+\r
+ ConnType(int connType) {\r
+ mConnType = connType;\r
+ }\r
+\r
+ public int getValue() {\r
+ return mConnType;\r
+ }\r
+\r
+ }\r
+\r
+ /**\r
+ * Gives configuration object specific to the on-boarding connectivity of the enrolling device.\r
+ *\r
+ * @return instance object of configuration according to connectivity type\r
+ */\r
+ public Object getConfig();\r
+\r
+ /**\r
+ * Gives connectivity type of on-boarding device\r
+ *\r
+ * @return on-boarding connectivity type\r
+ */\r
+ public ConnType getConnType();\r
+\r
+\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.core;\r
+\r
+/**\r
+ * This interface contains the connection details of the enrollee device\r
+ */\r
+public interface OnBoardingConnection {\r
+\r
+ /**\r
+ * This method returns the implementation of the Connection\r
+ *\r
+ * @return implementation\r
+ */\r
+ public Object getConnection();\r
+\r
+ /**\r
+ * This method returns description on the connectivity.\r
+ *\r
+ * @return description\r
+ */\r
+ public String getDesc();\r
+\r
+ /**\r
+ * This method is used to know if the device is connected or not\r
+ *\r
+ * @return True if connected or False\r
+ */\r
+ public boolean isConnected();\r
+\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+
+public abstract class ProvisioningCallback {
+ public abstract void onFinished(EnrolleeDevice enrolledevice);
+ public abstract void onProgress(EnrolleeDevice enrolledevice);
+}
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.core;
+/**
+ * It contains configuration details about the the target network where Enrollee device is
+ * going to be enrolled.
+ */
+public interface ProvisioningConfig {
+
+ /**
+ * It provides constants for connectivity types of target network
+ */
+ public static enum ConnType {
+ WiFi,
+ BT
+ }
+
+ /**
+ * Gives the instance of the configuration object created according to the connectivity
+ * type of target network.
+ *
+ * @return instance object of configuration according to connectivity type of target network
+ */
+ Object getConfig();
+
+
+ /**
+ * Gives connectivity type of target network
+ *
+ * @return Connectivity type of target network
+ */
+ ConnType getConnType();
+
+}
--- /dev/null
+/**
+ * ***************************************************************
+ * <p/>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p/>
+ * <p/>
+ * <p/>
+ * 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
+ * <p/>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p/>
+ * 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.
+ * <p/>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.impl;
+
+import android.content.Context;
+
+import org.iotivity.service.easysetup.core.EnrolleeDevice;
+import org.iotivity.service.easysetup.core.OnBoardingConfig;
+import org.iotivity.service.easysetup.core.ProvisioningConfig;
+
+/**
+ * This a factory class provides the native implementation of the various Enrollee devices.
+ * Application can make use of Enrollee factory if it does not want to create its own Enrollee devices.
+ */
+public class EnrolleeDeviceFactory {
+
+ Context mContext;
+
+ /**
+ * This method create & returns instance of EnrolleeDeviceFactory
+ *
+ * @param context This is Android Application context
+ */
+ public static EnrolleeDeviceFactory newInstance(Context context) {
+ return new EnrolleeDeviceFactory(context);
+ }
+
+ private EnrolleeDeviceFactory(Context context) {
+ mContext = context;
+ }
+
+ /**
+ * This method create & returns instance of Enrollee device of supported configuration
+ *
+ * @param onboardingConfig Contains details about the connectivity to be established between the Enrollee device & Mediator device in order to perform on-boarding
+ * @param provConfig Contains details about the network to which Enrollee device is going to connect.
+ * @return Instance of the Enrollee device created natively.
+ */
+
+ public EnrolleeDevice newEnrolleeDevice(OnBoardingConfig onboardingConfig, ProvisioningConfig provConfig) {
+
+ if (onboardingConfig.getConnType() != OnBoardingConfig.ConnType.WiFi) {
+ throw new IllegalArgumentException("OnBoarding configuration is not supported");
+ }
+
+ EnrolleeDevice enrolleeDevice;
+ enrolleeDevice = new EnrolleeDeviceWiFiOnboarding(mContext, onboardingConfig, provConfig);
+
+ return enrolleeDevice;
+ }
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.impl;\r
+\r
+import java.util.Timer;\r
+import java.util.TimerTask;\r
+\r
+import org.iotivity.service.easysetup.core.OnBoardingConnection;\r
+import org.iotivity.service.easysetup.core.EnrolleeDevice;\r
+import org.iotivity.service.easysetup.core.EnrolleeState;\r
+import org.iotivity.service.easysetup.core.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.core.OnBoardingConfig;\r
+import org.iotivity.service.easysetup.core.ProvisioningConfig;\r
+import org.iotivity.service.easysetup.mediator.EasySetupManager;\r
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;\r
+import org.iotivity.service.easysetup.mediator.IOnBoardingStatus;\r
+import org.iotivity.service.easysetup.mediator.IProvisioningListener;\r
+import org.iotivity.service.easysetup.mediator.ProvisionEnrollee;\r
+import org.iotivity.service.easysetup.mediator.ip.WiFiSoftAPManager;\r
+\r
+import android.content.Context;\r
+import android.net.wifi.WifiConfiguration;\r
+import android.util.Log;\r
+\r
+/**\r
+ * This is a ready to use class for Enrollee device having Soft AP as on-boarding connectivity.\r
+ */\r
+public class EnrolleeDeviceWiFiOnboarding extends EnrolleeDevice {\r
+\r
+ public static final String TAG = EnrolleeDeviceWiFiOnboarding.class.getName();\r
+\r
+ final Context mContext;\r
+ final WiFiSoftAPManager mWifiSoftAPManager;\r
+ EnrolleeInfo connectedDevice;\r
+ private EasySetupManager easySetupManagerNativeInstance;\r
+ ProvisionEnrollee provisionEnrolleInstance;\r
+ Timer myTimer;\r
+\r
+ IOnBoardingStatus deviceScanListener = new IOnBoardingStatus() {\r
+\r
+ @Override\r
+ public void deviceOnBoardingStatus(EnrolleeInfo enrolleStatus) {\r
+ myTimer.cancel();\r
+ Log.d("ESSoftAPOnBoarding", "Entered");\r
+ if (mState == EnrolleeState.DEVICE_ON_BOARDING_STATE) {\r
+ Log.d("ESSoftAPOnBoarding", "Device in OnBoarding State");\r
+ if (enrolleStatus != null && enrolleStatus.getIpAddr() != null) {\r
+ String finalResult = "Easy Connect : ";\r
+\r
+ if (enrolleStatus.isReachable()) {\r
+ finalResult = "Device OnBoarded" + "["\r
+ + enrolleStatus.getIpAddr() + "]";\r
+\r
+ connectedDevice = enrolleStatus;\r
+ IpOnBoardingConnection conn = new IpOnBoardingConnection();\r
+\r
+ conn.setConnectivity(true);\r
+ conn.setIp(connectedDevice.getIpAddr());\r
+ conn.setHardwareAddress(enrolleStatus.getHWAddr());\r
+ conn.setDeviceName(enrolleStatus.getDevice());\r
+\r
+ Log.d("ESSoftAPOnBoarding", "Entered" + finalResult);\r
+ mOnBoardingCallback.onFinished(conn);\r
+ return;\r
+\r
+ }\r
+ }\r
+\r
+ IpOnBoardingConnection conn = new IpOnBoardingConnection();\r
+ conn.setConnectivity(false);\r
+ mOnBoardingCallback.onFinished(conn);\r
+ } else {\r
+ Log.e("ESSoftAPOnBoarding", "Device NOT in OnBoarding State. Ignoring the event");\r
+ }\r
+ }\r
+ };\r
+\r
+\r
+ protected EnrolleeDeviceWiFiOnboarding(Context context, OnBoardingConfig onBoardingConfig,\r
+ ProvisioningConfig provConfig) {\r
+ super(onBoardingConfig, provConfig);\r
+ mContext = context;\r
+ mWifiSoftAPManager = new WiFiSoftAPManager(mContext);\r
+ }\r
+\r
+ @Override\r
+ protected void startOnBoardingProcess() {\r
+ Log.i(TAG, "Starting on boarding process");\r
+\r
+ //1. Create Soft AP\r
+ boolean status = mWifiSoftAPManager.setWifiApEnabled((WifiConfiguration)\r
+ mOnBoardingConfig.getConfig(), true);\r
+\r
+ mState = EnrolleeState.DEVICE_ON_BOARDING_STATE;\r
+\r
+ Log.i(TAG, "Soft AP is created with status " + status);\r
+\r
+ myTimer = new Timer();\r
+ myTimer.schedule(new TimerTask() {\r
+ @Override\r
+ public void run() {\r
+ // Below function to be called after 5 seconds\r
+ mWifiSoftAPManager.getClientList(deviceScanListener, 300);\r
+ }\r
+\r
+ }, 0, 5000);\r
+ }\r
+\r
+ protected void stopOnBoardingProcess() {\r
+ Log.i(TAG, "Stopping on boarding process");\r
+ myTimer.cancel();\r
+ boolean status = mWifiSoftAPManager.setWifiApEnabled(null, false);\r
+ Log.i(TAG, "Soft AP is disabled with status " + status);\r
+ }\r
+\r
+ @Override\r
+ protected void startProvisioningProcess(OnBoardingConnection conn) {\r
+ try {\r
+ Log.i(TAG, "waiting for 15 seconds to start provisioning");\r
+ Thread.sleep(15000);//Sleep for allowing thin device to start the services\r
+ } catch (InterruptedException e) {\r
+ e.printStackTrace();\r
+ }\r
+\r
+ mState = EnrolleeState.DEVICE_PROVISIONING_STATE;\r
+ mProvisioningCallback.onProgress(this);\r
+ final EnrolleeDevice device = this;\r
+ if (mProvConfig.getConnType() == ProvisioningConfig.ConnType.WiFi) {\r
+\r
+ provisionEnrolleInstance = new ProvisionEnrollee(mContext);\r
+\r
+ provisionEnrolleInstance.registerProvisioningHandler(new IProvisioningListener() {\r
+ @Override\r
+ public void onFinishProvisioning(int statuscode) {\r
+\r
+ Log.i(TAG, "Provisioning is finished with status code " + statuscode);\r
+ mState = (statuscode == 0) ? EnrolleeState.DEVICE_PROVISIONED_STATE\r
+ : EnrolleeState.DEVICE_INIT_STATE;\r
+ stopOnBoardingProcess();\r
+ mProvisioningCallback.onProgress(device);\r
+ mProvisioningCallback.onFinished(EnrolleeDeviceWiFiOnboarding.this);\r
+ }\r
+ });\r
+\r
+ IpOnBoardingConnection connection = (IpOnBoardingConnection) conn;\r
+ WiFiProvConfig wifiProvConfig = (WiFiProvConfig) mProvConfig;\r
+\r
+ easySetupManagerNativeInstance = EasySetupManager.getInstance();\r
+ easySetupManagerNativeInstance.setApplicationContext(mContext);\r
+ easySetupManagerNativeInstance.initEasySetup();\r
+\r
+ // Native Api call to start provisioning of the enrolling device\r
+ easySetupManagerNativeInstance.provisionEnrollee(connection.getIp(), wifiProvConfig\r
+ .getSsId(), wifiProvConfig.getPassword(), 1);\r
+ }\r
+ }\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p/>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p/>\r
+ * <p/>\r
+ * <p/>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p/>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p/>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p/>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.impl;\r
+\r
+import org.iotivity.service.easysetup.core.IpOnBoardingConnection;\r
+import org.iotivity.service.easysetup.core.OnBoardingConfig;\r
+\r
+import android.net.wifi.WifiConfiguration;\r
+\r
+/**\r
+ * This class contains on boarding configuration information for Soft AP on boarding connectivity.\r
+ * It implements OnBoardingConfig interface & provide implementation for WiFi Soft AP connectivity.\r
+ */\r
+\r
+public class WiFiOnBoardingConfig implements OnBoardingConfig {\r
+\r
+ private final WifiConfiguration config = new WifiConfiguration();\r
+ private final ConnType mConnType = OnBoardingConfig.ConnType.WiFi;\r
+\r
+ @Override\r
+ public Object getConfig() {\r
+ return config;\r
+ }\r
+\r
+ public void setSSId(String ssid) {\r
+ config.SSID = ssid;\r
+ }\r
+\r
+ public void setSharedKey(String sharedKey) {\r
+ config.preSharedKey = sharedKey;\r
+ }\r
+\r
+ public void setAuthAlgo(int aurthAlgo) {\r
+ config.allowedAuthAlgorithms.set(aurthAlgo);\r
+ }\r
+\r
+ public void setKms(int kms) {\r
+ config.allowedKeyManagement.set(kms);\r
+ }\r
+\r
+ @Override\r
+ public ConnType getConnType() {\r
+ return mConnType;\r
+ }\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.impl;
+
+import org.iotivity.service.easysetup.core.ProvisioningConfig;
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;
+
+import android.net.wifi.WifiConfiguration;
+
+/**
+ * This class contains on provisioning configuration information for for target network.
+ * It implements ProvisioningConfig interface and provide configuration object specific to WiFi target network
+ */
+public class WiFiProvConfig implements ProvisioningConfig {
+
+ private final ConnType mConnType = ProvisioningConfig.ConnType.WiFi;
+
+ private final String mSsId;
+ private final String mPassword;
+
+ public WiFiProvConfig(String ssid, String pass) {
+ mSsId = ssid;
+ mPassword = pass;
+ }
+
+ @Override
+ public Object getConfig() {
+ return this;
+ }
+
+ @Override
+ public ConnType getConnType() {
+ return mConnType;
+ }
+
+ /**
+ * This method returns the SSID of the Target WIFI network
+ * @return SSID of Target Network
+ */
+ public String getSsId() {
+ return mSsId;
+ }
+
+ /**
+ * This method returns the password of the Target WIFI network
+ * @return password of Target Network
+ */
+ public String getPassword() {
+ return mPassword;
+ }
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.util.Log;\r
+\r
+public class EasySetupCallbackHandler {\r
+ private static final String TAG = "ESCallbackHandler";\r
+ ProvisionEnrollee provisioningListener;\r
+\r
+ private static EasySetupCallbackHandler easySetupCallbackHandlerObj;\r
+\r
+ public static synchronized EasySetupCallbackHandler getInstance() {\r
+ if (null == easySetupCallbackHandlerObj) {\r
+ easySetupCallbackHandlerObj = new EasySetupCallbackHandler();\r
+ }\r
+ return easySetupCallbackHandlerObj;\r
+ }\r
+\r
+ public void ProvisioningStatusCallBack(int statuscode) {\r
+ Log.d(TAG,\r
+ "onFinishProvisioning() inside Android Java application. statuscode - "\r
+ + statuscode);\r
+ if (this.provisioningListener != null) {\r
+ this.provisioningListener.ProvisioningStatusCallBack(statuscode);\r
+ } else {\r
+ Log.e(TAG, "provisioningListener is not registered");\r
+ }\r
+ }\r
+\r
+ public void registerProvisioningHandler(\r
+ ProvisionEnrollee provisioningListener) {\r
+ this.provisioningListener = provisioningListener;\r
+ }\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+\r
+import org.iotivity.ca.CaInterface;\r
+\r
+public class EasySetupManager {\r
+ private native void InitEasySetup();\r
+\r
+ private native void TerminateEasySetup();\r
+\r
+ // TODO : "OcConnectivityType connectivityType" has to be passed as the\r
+ // second parameter for PerformEasySetup\r
+ // instead of integer\r
+ private native void ProvisionEnrollee(String ipAddress, String netSSID,\r
+ String netPWD, int connectivityType);\r
+\r
+ private native void StopEnrolleeProvisioning(int connectivityType);\r
+\r
+ public static native void initialize(Context context);\r
+\r
+ private static EasySetupManager easySetupManagerInterfaceObj = null;\r
+ private Context appContext = null;\r
+\r
+ static {\r
+ // Load Easy Setup JNI interface\r
+ System.loadLibrary("gnustl_shared");\r
+ System.loadLibrary("octbstack");\r
+ System.loadLibrary("connectivity_abstraction");\r
+ System.loadLibrary("easysetup-jni");\r
+ }\r
+\r
+ private EasySetupManager() {\r
+\r
+ }\r
+\r
+ /**\r
+ * Function for Getting instance of EasySetupManager object.\r
+ *\r
+ * @return EasySetupManager instance.\r
+ *\r
+ */\r
+ public static synchronized EasySetupManager getInstance() {\r
+ if (null == easySetupManagerInterfaceObj) {\r
+ easySetupManagerInterfaceObj = new EasySetupManager();\r
+ }\r
+ return easySetupManagerInterfaceObj;\r
+ }\r
+\r
+ public void setApplicationContext(Context context) {\r
+ appContext = context;\r
+ }\r
+\r
+ public void initEasySetup() {\r
+ CaInterface.initialize(appContext);\r
+ InitEasySetup();\r
+ }\r
+\r
+ public void terminateEasySetup() {\r
+ TerminateEasySetup();\r
+ }\r
+\r
+ public void provisionEnrollee(String ipAddress, String netSSID,\r
+ String netPWD, int connectivityType) {\r
+\r
+ ProvisionEnrollee(ipAddress, netSSID, netPWD, connectivityType);\r
+ }\r
+\r
+ public void stopEnrolleeProvisioning(int connectivityType) {\r
+ StopEnrolleeProvisioning(connectivityType);\r
+ }\r
+\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator;
+
+public class EnrolleeInfo {
+
+ private String IpAddr;
+ private String HWAddr;
+ private String Device;
+ private boolean isReachable;
+
+ public String getIpAddr() {
+ return IpAddr;
+ }
+
+ public void setIpAddr(String ipAddr) {
+ IpAddr = ipAddr;
+ }
+
+ public String getHWAddr() {
+ return HWAddr;
+ }
+
+ public void setHWAddr(String hWAddr) {
+ HWAddr = hWAddr;
+ }
+
+ public String getDevice() {
+ return Device;
+ }
+
+ public void setDevice(String device) {
+ Device = device;
+ }
+
+ public boolean isReachable() {
+ return isReachable;
+ }
+
+ public void setReachable(boolean isReachable) {
+ this.isReachable = isReachable;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+package org.iotivity.service.easysetup.mediator;
+
+public class EnrolleeOnBoardingInfo {
+
+ private String IpAddr;
+ private String HWAddr;
+ private String Device;
+ private boolean isReachable;
+ private boolean isAdditionNotified;
+ private boolean isRemovalNotified;
+
+ public EnrolleeOnBoardingInfo(String ipAddr, String hWAddr, String device,
+ boolean isReachable, boolean isRemovalNotified,
+ boolean isAdditionNotified) {
+ this.IpAddr = ipAddr;
+ this.HWAddr = hWAddr;
+ this.Device = device;
+ this.isReachable = isReachable;
+ this.isRemovalNotified = isRemovalNotified;
+ this.isAdditionNotified = isAdditionNotified;
+ }
+
+ public String getIpAddr() {
+ return IpAddr;
+ }
+
+ public void setIpAddr(String ipAddr) {
+ IpAddr = ipAddr;
+ }
+
+ public String getHWAddr() {
+ return HWAddr;
+ }
+
+ public void setHWAddr(String hWAddr) {
+ HWAddr = hWAddr;
+ }
+
+ public String getDevice() {
+ return Device;
+ }
+
+ public void setDevice(String device) {
+ Device = device;
+ }
+
+ public boolean isReachable() {
+ return isReachable;
+ }
+
+ public void setReachable(boolean isReachable) {
+ this.isReachable = isReachable;
+ }
+
+ public boolean isRemovalNotified() {
+ return isRemovalNotified;
+ }
+
+ public void setRemovalNotified(boolean isRemovalNotified) {
+ this.isRemovalNotified = isRemovalNotified;
+ }
+
+ public boolean isAdditionNotified() {
+ return isAdditionNotified;
+ }
+
+ public void setAdditionNotified(boolean isAdditionNotified) {
+ this.isAdditionNotified = isAdditionNotified;
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+package org.iotivity.service.easysetup.mediator;
+
+import java.util.ArrayList;
+
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;
+
+public interface IOnBoardingStatus {
+
+ /**
+ * Interface called when the scan method finishes. Network operations should
+ * not execute on UI thread
+ *
+ * @param clients of {@link EnrolleeInfo}
+ */
+
+ public void deviceOnBoardingStatus(EnrolleeInfo clients);
+
+}
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+public interface IProvisioningListener {\r
+ /**\r
+ * Interface called when the provisioning finishes\r
+ */\r
+\r
+ public void onFinishProvisioning(int statuscode);\r
+}\r
--- /dev/null
+/**\r
+ * ***************************************************************\r
+ * <p>\r
+ * Copyright 2015 Samsung Electronics All Rights Reserved.\r
+ * <p>\r
+ * <p>\r
+ * <p>\r
+ * Licensed under the Apache License, Version 2.0 (the "License");\r
+ * you may not use this file except in compliance with the License.\r
+ * You may obtain a copy of the License at\r
+ * <p>\r
+ * http://www.apache.org/licenses/LICENSE-2.0\r
+ * <p>\r
+ * Unless required by applicable law or agreed to in writing, software\r
+ * distributed under the License is distributed on an "AS IS" BASIS,\r
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
+ * See the License for the specific language governing permissions and\r
+ * limitations under the License.\r
+ * <p>\r
+ * ****************************************************************\r
+ */\r
+\r
+package org.iotivity.service.easysetup.mediator;\r
+\r
+import android.content.Context;\r
+import android.util.Log;\r
+\r
+public class ProvisionEnrollee {\r
+ private static final String TAG = "ProvisionEnrollee";\r
+ private IProvisioningListener provisioningListener;\r
+\r
+ /**\r
+ * Constructor for ProvisionEnrollee. Constructs a new ProvisionEnrollee.\r
+ */\r
+ public ProvisionEnrollee(Context context) {\r
+\r
+ }\r
+\r
+ public void provisionEnrollee(String ipAddress, String netSSID,\r
+ String netPWD, int connectivityType) {\r
+ Log.i(TAG, "JNI start provisioning is called ");\r
+ }\r
+\r
+ public void stopEnrolleeProvisioning(int connectivityType) {\r
+ Log.i(TAG, "JNI stop provisioning is called ");\r
+ }\r
+\r
+ public void ProvisioningStatusCallBack(int statuscode) {\r
+ Log.d(TAG,\r
+ "JNI onFinishProvisioning() inside Android Java application. statuscode - "\r
+ + statuscode);\r
+ this.provisioningListener.onFinishProvisioning(statuscode);\r
+ }\r
+\r
+ public void registerProvisioningHandler(\r
+ IProvisioningListener provisioningListener) {\r
+ this.provisioningListener = provisioningListener;\r
+ EasySetupCallbackHandler.getInstance()\r
+ .registerProvisioningHandler(this);\r
+ Log.i(TAG, "JNI Callback is registered for getting provisioning status");\r
+ }\r
+}\r
--- /dev/null
+/**
+ * ***************************************************************
+ * <p>
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ * <p>
+ * <p>
+ * <p>
+ * 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
+ * <p>
+ * http://www.apache.org/licenses/LICENSE-2.0
+ * <p>
+ * 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.
+ * <p>
+ * ****************************************************************
+ */
+
+package org.iotivity.service.easysetup.mediator.ip;
+
+import java.io.BufferedReader;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.util.ArrayList;
+
+import android.content.Context;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.util.Log;
+
+import org.iotivity.service.easysetup.mediator.EnrolleeInfo;
+import org.iotivity.service.easysetup.mediator.EnrolleeOnBoardingInfo;
+import org.iotivity.service.easysetup.mediator.IOnBoardingStatus;
+
+/**
+ * WiFiSoftAPManager provides wrapper methods for accessing Android Soft Access Point functionality.
+ * This is a convenient class, providing Android "WiFiManager" kind of equivalent class for Soft AP.
+ * <p>
+ * Note: Android doesn't provide public APIs for Soft Access Point feature access.
+ * This class provides only reference implementation to use the Soft AP and it uses Java reflection
+ * for access Soft Access point features.
+ * </p>
+ */
+public class WiFiSoftAPManager {
+ private static final String TAG = WiFiSoftAPManager.class.getName();
+ private final WifiManager mWifiManager;
+ private Context context;
+ static ArrayList<EnrolleeOnBoardingInfo> appNotification =
+ new ArrayList<EnrolleeOnBoardingInfo>();
+ IOnBoardingStatus finishListener = null;
+
+ public enum WIFI_AP_STATE {
+ WIFI_AP_STATE_DISABLING,
+ WIFI_AP_STATE_DISABLED,
+ WIFI_AP_STATE_ENABLING,
+ WIFI_AP_STATE_ENABLED,
+ WIFI_AP_STATE_FAILED
+ }
+
+ public WiFiSoftAPManager(Context context) {
+ this.context = context;
+ mWifiManager = (WifiManager) this.context
+ .getSystemService(Context.WIFI_SERVICE);
+ }
+
+ /*
+ * Utility API to check the validity of the MAC Address read from the ARP cache
+ */
+ private boolean CheckIfValidMacAddress(String macAddr) {
+ if (macAddr.matches("..:..:..:..:..:..")) {
+ return true;
+ } else {
+ return false;
+ }
+ }
+
+ /*
+ * The API is used for checking the device entry in the list maintained for the device
+ * notifications.
+ * If device entry is not found in the list, app is notified.
+ * If the device entry is found in the device, as application is already notified it will
+ * continue
+ */
+ private boolean CheckForDeviceEntryAndNotify(String ipAddr,
+ String macAddr, boolean isReachable) {
+ final EnrolleeInfo result = new EnrolleeInfo();
+ boolean deviceAddedToList = false;
+
+ if (appNotification.size() > 0) {
+ for (EnrolleeOnBoardingInfo ipDeviceOnBoardingNotification : appNotification) {
+ EnrolleeOnBoardingInfo ipEnrolleeDevice = (EnrolleeOnBoardingInfo)
+ ipDeviceOnBoardingNotification;
+ boolean macAddressComparison = ipEnrolleeDevice.getHWAddr().equalsIgnoreCase(
+ macAddr) ? true : false;
+
+ if (macAddressComparison) {
+ deviceAddedToList = true;
+
+ if (ipDeviceOnBoardingNotification
+ .isAdditionNotified()
+ && isReachable) {
+ continue;
+ } else if (ipDeviceOnBoardingNotification
+ .isRemovalNotified()
+ && !isReachable) {
+ continue;
+ } else {
+ result.setIpAddr(ipAddr);
+ result.setHWAddr(macAddr);
+ result.setReachable(isReachable);
+
+ appNotification
+ .remove(ipDeviceOnBoardingNotification);
+ if (isReachable) {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "",
+ isReachable,
+ false, true));
+ } else {
+ //This case will happen during the transition from connected to
+ // disconneted. This case need not be notified to application.
+ // Notifying this state will cause failure of OnBoarding
+ }
+ NotifyApplication(result);
+ return true;
+ }
+ }
+ }
+ if (!deviceAddedToList) {
+ if (isReachable) {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, false,
+ true));
+
+ result.setIpAddr(ipAddr);
+ result.setHWAddr(macAddr);
+ result.setReachable(isReachable);
+
+ NotifyApplication(result);
+ } else {
+ //This case will happen for the first time device is listed, but reachability
+ // is false. This case need not be notified to application. Notifying this
+ // state will cause failure of OnBoarding
+ }
+ return true;
+ }
+ } else {
+ if (isReachable) {
+ appNotification
+ .add(new EnrolleeOnBoardingInfo(ipAddr, macAddr, "", isReachable, false,
+ true));
+ result.setIpAddr(ipAddr);
+ result.setHWAddr(macAddr);
+ result.setReachable(isReachable);
+
+ NotifyApplication(result);
+ } else {
+ //This case will happen for the first time device is listed, but
+ // reachability is false. This case need not be notified to
+ // application. Notifying this state will cause failure of OnBoarding
+ }
+
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Start WiFi Soft AccessPoint mode with the specified configuration.
+ * If the Soft AP is already running, this API call will update the new configuration.
+ * <p>
+ * Note: Starting Wi-Fi Soft Access Point will disable the Wi-Fi normal operation.
+ * </p>
+ *
+ * @param wifiConfig SSID, security and channel details as part of WifiConfiguration
+ * @return {@code true} if the operation succeeds, {@code false} otherwise
+ */
+ public boolean setWifiApEnabled(WifiConfiguration wifiConfig,
+ boolean enabled) {
+ try {
+ appNotification.clear();
+ // Stopping Wi-Fi mode
+ if (enabled) {
+ mWifiManager.setWifiEnabled(false);
+ }
+
+ Method method = mWifiManager.getClass().getMethod(
+ "setWifiApEnabled", WifiConfiguration.class, boolean.class);
+ return (Boolean) method.invoke(mWifiManager, wifiConfig, enabled);
+ } catch (Exception e) {
+ Log.e(this.getClass().toString(), "", e);
+ return false;
+ }
+ }
+
+ /**
+ * Fetch the current state of the Wi-Fi Soft AP
+ *
+ * @return {@link WIFI_AP_STATE}
+ */
+ public WIFI_AP_STATE getWifiApState() {
+ try {
+ Method method = mWifiManager.getClass().getMethod("getWifiApState");
+
+ int currentWiFiState = ((Integer) method.invoke(mWifiManager));
+ WIFI_AP_STATE wifi_ap_state_enum[] = WIFI_AP_STATE.class.getEnumConstants();
+ if (wifi_ap_state_enum != null)
+ return wifi_ap_state_enum[currentWiFiState];
+ else return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
+ } catch (Exception e) {
+ Log.e(this.getClass().toString(), "", e);
+ return WIFI_AP_STATE.WIFI_AP_STATE_FAILED;
+ }
+ }
+
+ /**
+ * Fetch the current Wi-Fi AP Configuration.
+ *
+ * @return AP details in {@link WifiConfiguration}
+ */
+ public WifiConfiguration getWifiApConfiguration() {
+ try {
+ Method method = mWifiManager.getClass().getMethod(
+ "getWifiApConfiguration");
+ return (WifiConfiguration) method.invoke(mWifiManager);
+ } catch (Exception e) {
+ Log.e(this.getClass().toString(), "", e);
+ return null;
+ }
+ }
+
+ /**
+ * Set/Update the Wi-Fi AP Configuration.
+ *
+ * @return {@code true} if the operation succeeds, {@code false} otherwise
+ */
+ public boolean setWifiApConfiguration(WifiConfiguration wifiConfig) {
+ try {
+ Method method = mWifiManager.getClass().getMethod(
+ "setWifiApConfiguration", WifiConfiguration.class);
+ return (Boolean) method.invoke(mWifiManager, wifiConfig);
+ } catch (Exception e) {
+ Log.e(this.getClass().toString(), "", e);
+ return false;
+ }
+ }
+
+ /**
+ * Gets a list of the Soft AP clients connected to the Wi-Fi Soft Access point
+ *
+ * @param finishListener Interface called when the scan method finishes
+ * @param reachableTimeout Reachable Timeout in miliseconds
+ */
+ public synchronized void getClientList(IOnBoardingStatus finishListener, final int
+ reachableTimeout) {
+ this.finishListener = finishListener;
+ //Clearing the scan list for providing u
+ appNotification.clear();
+ Runnable runnable = new Runnable() {
+ public void run() {
+ Log.i(TAG, "Scanning enrolling device in the network");
+
+ BufferedReader bufferedReader = null;
+
+ try {
+ // Note : This is a reference implementation for getting the list of Enrollee's
+ // connected to the Soft AP.
+ // There is no Android API for getting list of connected devices to the Soft AP.
+ // The connected device information is fetched from Arp cache for Soft AP and
+ // it is maintained in the file "/proc/net/arp"
+ // This holds an ASCII readable dump of the kernel ARP table used
+ // for address resolutions. It will show both dynamically learned
+ // and preprogrammed ARP entries. The format is:
+ // IP address HW type Flags HW address Mask Device
+ // 192.168.0.50 0x1 0x2 00:50:BF:25:68:F3 * eth0
+ // 192.168.0.250 0x1 0xc 00:00:00:00:00:00 * eth0
+ bufferedReader = new BufferedReader(new InputStreamReader(
+ new FileInputStream("/proc/net/arp"), "UTF-8"));
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ //ARP entries are splitted using Regex for getting the IP and MAC Address
+ // info
+ String[] arpEntry = line.split(" +");
+
+ if ((arpEntry != null) && (arpEntry.length >= 4)) {
+ String ipAddr = arpEntry[0];
+ String macAddr = arpEntry[3];
+
+
+ // Checking if the string is matching MAC Address is matching the
+ // standard MAC address format.
+ // If the entry is not matching with MAC address format,
+ // it will continue
+ if (CheckIfValidMacAddress(macAddr)) {
+ boolean isReachable = InetAddress.getByName(
+ ipAddr).isReachable(
+ reachableTimeout);
+
+ Log.i("exec statement", ipAddr);
+ Log.i("Return Value", " " + isReachable);
+
+ // Checking if the app notification entries are available in the
+ // list for the current device
+ // API returns true is there is a notification to the application.
+ // API returns false if there is no entry or if device is
+ // already notified
+ if (CheckForDeviceEntryAndNotify(ipAddr, macAddr, isReachable)) {
+ break;
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ Log.e(this.getClass().toString(), e.toString());
+ } finally {
+ try {
+ bufferedReader.close();
+ } catch (IOException e) {
+ Log.e(this.getClass().toString(), e.getMessage());
+ }
+ }
+ }
+ };
+
+ Thread mythread = new Thread(runnable);
+ mythread.start();
+ }
+
+ void NotifyApplication(final EnrolleeInfo result) {
+ // Get a handler that can be used to post to the main thread
+/*
+ Handler mainHandler = new Handler(context.getMainLooper());
+ Runnable myRunnable = new Runnable() {
+ @Override
+ public void run() {
+ finishListener.deviceOnBoardingStatus(result);
+ }
+ };
+ mainHandler.post(myRunnable);
+*/
+ Log.i(TAG, "Scanning is finished with result, IP : " + result.getIpAddr() + "Notifying " +
+ "to Application");
+ finishListener.deviceOnBoardingStatus(result);
+
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+ <component name="FacetManager">
+ <facet type="android" name="Android">
+ <configuration />
+ </facet>
+ </component>
+ <component name="NewModuleRootManager" inherit-compiler-output="true">
+ <exclude-output />
+ <content url="file://$MODULE_DIR$">
+ <sourceFolder url="file://$MODULE_DIR$/java" isTestSource="false" />
+ <sourceFolder url="file://$MODULE_DIR$/gen" isTestSource="false" generated="true" />
+ </content>
+ <orderEntry type="jdk" jdkName="Android API 21 Platform" jdkType="Android SDK" />
+ <orderEntry type="sourceFolder" forTests="false" />
+ <orderEntry type="library" name="classes1" level="project" />
+ </component>
+</module>
\ No newline at end of file
--- /dev/null
+<resources>
+
+ <string name="app_name">EasySetupCore</string>
+
+</resources>
--- /dev/null
+<resources>
+
+ <!--
+ Base application theme, dependent on API level. This theme is replaced
+ by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+ -->
+ <style name="AppBaseTheme" parent="android:Theme.Light">
+ <!--
+ Theme customizations available in newer API levels can go in
+ res/values-vXX/styles.xml, while customizations related to
+ backward-compatibility can go here.
+ -->
+ </style>
+
+ <!-- Application theme. -->
+ <style name="AppTheme" parent="AppBaseTheme">
+ <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+ </style>
+
+</resources>
--- /dev/null
+LOCAL_PATH := $(call my-dir)
+
+ifeq ($(strip $(ANDROID_NDK)),)
+$(error ANDROID_NDK is not set!)
+endif
+
+$(warning "Current path" $(LOCAL_PATH))
+$(info TC_PREFIX=$(TOOLCHAIN_PREFIX))
+$(info CFLAGS=$(TARGET_CFLAGS))
+$(info CXXFLAGS=$(TARGET_CXXFLAGS) $(TARGET_NO_EXECUTE_CFLAGS))
+$(info CPPFLAGS=$(TARGET_CPPFLAGS))
+$(info CPPPATH=$(TARGET_C_INCLUDES) $(__ndk_modules.$(APP_STL).EXPORT_C_INCLUDES))
+$(info SYSROOT=$(SYSROOT_LINK))
+$(info LDFLAGS=$(TARGET_LDFLAGS) $(TARGET_NO_EXECUTE_LDFLAGS) $(TARGET_NO_UNDEFINED_LDFLAGS) $(TARGET_RELRO_LDFLAGS))
+$(info TC_VER=$(TOOLCHAIN_VERSION))
+$(info PLATFORM=$(APP_PLATFORM))
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-octbstack
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-connectivity_abstraction
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so
+include $(PREBUILT_SHARED_LIBRARY)
+
+include $(CLEAR_VARS)
+OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/debug
+LOCAL_MODULE := android-easysetup
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libESSDK.a
+include $(PREBUILT_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+
+LOCAL_MODULE := easysetup-jni
+
+#Add Pre processor definitions
+DEFINE_FLAG = -DWITH_POSIX -D__ANDROID__
+
+#Add Debug flags here
+DEBUG_FLAG = -DTB_LOG
+
+BUILD_FLAG = $(DEFINE_FLAG) $(DEBUG_FLAG)
+
+LOCAL_CPPFLAGS = $(BUILD_FLAG)
+LOCAL_CPPFLAGS += -std=c++0x -frtti -fexceptions
+
+$(info CPPFLAGSUPDATED=$(LOCAL_CPPFLAGS))
+
+NDK_ROOT := /home/madan/android-ndk-r10d
+
+LOCAL_C_INCLUDES := $(LOCAL_PATH) \
+ $(LOCAL_PATH)/jniutil/inc \
+ $(LOCAL_PATH)/../../../../../../service/easy-setup/sdk/mediator/inc \
+ $(LOCAL_PATH)/../../../../../../service/easy-setup/sdk/common \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/common/inc \
+ $(LOCAL_PATH)/../../../../../../resource/include \
+ $(LOCAL_PATH)/../../../../../../resource/c_common \
+ $(LOCAL_PATH)/../../../../../../resource/oc_logger/include \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/ocmalloc/include \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/connectivity/api \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/stack/include \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/logger/include \
+ $(LOCAL_PATH)/../../../../../../resource/csdk/security/include \
+ $(LOCAL_PATH)/../../../../../../extlibs/cjson \
+ $(LOCAL_PATH)/../../../../../../extlibs/boost/boost_1_58_0 \
+ $(LOCAL_PATH)/../../../../../../extlibs/timer \
+ $(LOCAL_PATH)/../../../../../../android/android_api/base/jni \
+ $(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/include \
+ $(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)/include \
+
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jni_easy_setup.cpp))
+LOCAL_SRC_FILES += $(patsubst $(LOCAL_PATH)/%, %, $(wildcard $(LOCAL_PATH)/jniutil/src/*.cpp))
+
+LOCAL_LDLIBS := -llog
+LOCAL_LDLIBS += -L$(NDK_ROOT)/sources/cxx-stl/gnu-libstdc++/$(TOOLCHAIN_VERSION)/libs/$(TARGET_ARCH_ABI)
+LOCAL_SHARED_LIBRARIES := android-easysetup
+LOCAL_SHARED_LIBRARIES += android-connectivity_abstraction
+LOCAL_SHARED_LIBRARIES += android-octbstack
+
+include $(BUILD_SHARED_LIBRARY)
\ No newline at end of file
--- /dev/null
+APP_STL := gnustl_shared
+APP_PLATFORM = android-21
+NDK_TOOLCHAIN_VERSION := 4.8
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "jni_easy_setup.h"
+
+#include "jni_easy_setup_jvm.h"
+#include "prov_adapter.h"
+
+void JNIProvisioningStatusCallback(ProvisioningInfo * provInfo) {
+ JNIEnv *env = EasySetupJVM::getEnv();
+ if (env == NULL) {
+ LOGE("JNIProvisioningStatusCallback : Getting JNIEnv failed");
+ return;
+ }
+
+ // Get EasySetupHandler class reference
+ jclass easysetupCallbacks = GetJClass(
+ EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);
+ if (NULL == easysetupCallbacks) {
+ LOGE(
+ "JNIProvisioningStatusCallback : GetJClass easysetupCallbacks failed");
+ EasySetupJVM::releaseEnv();
+ return;
+ }
+
+ // Get the easysetupCallback class instance
+ jobject jobjectCallback = GetJObjectInstance(
+ EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);
+ if (NULL == jobjectCallback) {
+ LOGE("getInstance( %s) failed!",
+ EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH);
+ EasySetupJVM::releaseEnv();
+ return;
+ }
+
+ // Get onResourceCallback method reference
+ jmethodID method_id = env->GetMethodID(easysetupCallbacks,
+ "ProvisioningStatusCallBack",
+ METHOD_PROVISIONING_STATUS_INTEGER_CALLBACK);
+ if (NULL == method_id) {
+ LOGE(
+ "JNIProvisioningStatusCallback: onResourceCallback : GetMethodID failed");
+ EasySetupJVM::releaseEnv();
+ return;
+ }
+
+ if ((env)->ExceptionCheck()) {
+ LOGE("JNIProvisioningStatusCallback : ExceptionCheck failed");
+ EasySetupJVM::releaseEnv();
+ return;
+ }
+
+ if (NULL == method_id) {
+ LOGI("JNI method_id is NULL");
+ } else {
+ LOGI("JNI method_id is VALID");
+
+ jint result;
+ if (provInfo->provStatus == DEVICE_PROVISIONED) {
+ result = 0;
+ } else {
+ result = -1;
+ }
+
+ env->CallVoidMethod(jobjectCallback, method_id, (jint) result);
+ }
+
+ EasySetupJVM::releaseEnv();
+}
+
+JNIEXPORT void JNICALL
+JNIInitEasySetup(JNIEnv
+ *env,
+ jobject thisObj
+)
+{
+ LOGI("JNI JNIInitEasySetup: Enter");
+
+ InitProvProcess();
+
+ RegisterCallback(JNIProvisioningStatusCallback);
+}
+
+JNIEXPORT void JNICALL
+JNITerminateEasySetup(JNIEnv
+ *env,
+ jobject thisObj
+)
+{
+ LOGI("JNI JNITerminateEasySetup: Enter");
+
+ ResetProvProcess();
+
+}
+
+JNIEXPORT void JNICALL
+JNIProvisionEnrollee(JNIEnv
+ *env,
+ jobject thisObj,
+ jstring
+ jIPAddress,
+ jstring jNetSSID,
+ jstring
+ jNetPWD,
+ jint jConnectivityType
+)
+{
+ LOGI("JNI JNIProvisionEnrollee: Enter");
+
+ if (!jIPAddress)
+ {
+ LOGE("JNI JNIProvisionEnrollee : jIPAddress is NULL!");
+ return;
+ }
+
+ const char *ipAddress = env->GetStringUTFChars(jIPAddress, NULL);
+ if (NULL == ipAddress)
+ {
+ LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");
+ }
+
+ LOGI("JNI JNIProvisionEnrollee : ipAddress is : %s",ipAddress);
+
+ const char *netSSID = env->GetStringUTFChars(jNetSSID, NULL);
+ if (NULL == netSSID)
+ {
+ LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");
+ }
+
+ LOGI("JNI JNIProvisionEnrollee : netSSID is : %s",netSSID);
+
+ const char *netPWD = env->GetStringUTFChars(jNetPWD, NULL);
+ if (NULL == netPWD)
+ {
+ LOGE("JNI JNIProvisionEnrollee : Failed to convert jstring to char string!");
+ }
+
+ LOGI("JNI JNIProvisionEnrollee : netPWD is : %s",netPWD);
+
+ OCConnectivityType connecitivityType;
+ EnrolleeNWProvInfo_t netInfo =
+ { 0};
+ strncpy(netInfo
+ .netAddressInfo.WIFI.ipAddress, ipAddress, IPV4_ADDR_SIZE-1);
+ strncpy(netInfo
+ .netAddressInfo.WIFI.ssid, netSSID, NET_WIFI_SSID_SIZE-1);
+ strncpy(netInfo
+ .netAddressInfo.WIFI.pwd, netPWD, NET_WIFI_PWD_SIZE-1);
+ netInfo.
+ connType = (OCConnectivityType) jConnectivityType;
+
+ netInfo.
+ isSecured = true;
+
+ StartProvisioning(&netInfo);
+
+ return;
+}
+
+JNIEXPORT void JNICALL
+JNIStopEnrolleeProvisioning(JNIEnv
+ *env,
+ jobject thisObj,
+ jint
+ jConnectivityType)
+{
+ LOGI("JNI Stop Easy Setup: Entering");
+
+ StopProvisioning((OCConnectivityType)
+ jConnectivityType);
+
+ return;
+}
+
--- /dev/null
+/* DO NOT EDIT THIS FILE - it is machine generated */\r
+#include <stdio.h>\r
+#include <string.h>\r
+\r
+#include <jni.h>\r
+#include <jni_string.h>\r
+\r
+#include "JniOcStack.h"\r
+\r
+#define METHOD_PROVISIONING_STATUS_VOID_CALLBACK "("")V"\r
+#define METHOD_PROVISIONING_STATUS_INTEGER_CALLBACK "("EASY_SETUP_JAVA_INTEGER_TYPE")V"\r
+\r
+/* Header for class org_iotivity_service_easyconnect_java_EasySetupHandler */\r
+\r
+#ifndef _Included_org_iotivity_service_easysetup_java_EasySetupHandler\r
+#define _Included_org_iotivity_service_easysetup_java_EasySetupHandler\r
+\r
+#ifdef __cplusplus\r
+extern "C" {\r
+#endif\r
+\r
+JNIEXPORT void JNICALL JNIInitEasySetup(JNIEnv *env, jobject thisObj);\r
+JNIEXPORT void JNICALL JNITerminateEasySetup(JNIEnv *env, jobject thisObj);\r
+\r
+/*\r
+ * Class: org_iotivity_service_easyconnect_java_EasySetupHandler\r
+ * Method: JNIProvisionEnrollee\r
+ * Signature: ()V\r
+ */\r
+JNIEXPORT void JNICALL JNIProvisionEnrollee(JNIEnv *env, jobject ,\r
+ jstring ,\r
+ jstring ,\r
+ jstring ,\r
+ jint jConnectivityType);\r
+\r
+JNIEXPORT void JNICALL JNIStopEnrolleeProvisioning(JNIEnv *, jobject, jint);\r
+\r
+\r
+#ifdef __cplusplus\r
+}\r
+#endif\r
+#endif\r
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_easy_setup_jvm.h
+ *
+ * @brief This file contains the essential declarations and functions required
+ * for JNI implementation
+ */
+
+#ifndef __JNI_EASY_SETUP_JVM_H_
+#define __JNI_EASY_SETUP_JVM_H_
+
+#include <jni.h>
+#include <thread>
+#include <mutex>
+
+#define EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH "org/iotivity/service/easysetup/mediator/EasySetupManager"
+#define EASY_SETUP_SERVICE_NATIVE_API_CLASS_TYPE "Lorg/iotivity/service/easysetup/mediator/EasySetupManager;"
+#define EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH "org/iotivity/service/easysetup/mediator/EasySetupCallbackHandler"
+#define EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_TYPE "Lorg/iotivity/service/easysetup/mediator/EasySetupCallbackHandler;"
+
+#define EASY_SETUP_JAVA_STRING_TYPE "Ljava/lang/String;"
+#define EASY_SETUP_JAVA_INTEGER_TYPE "I"
+
+/**
+ * @class EasySetupJVM
+ * @brief This class provides functions related to JNI Environment.
+ *
+ */
+class EasySetupJVM {
+public:
+ /**
+ * @brief destructor
+ */
+ ~EasySetupJVM() {
+ }
+ ;
+
+ /**
+ * @brief Get JVM instance
+ */
+ static JNIEnv *getEnv();
+
+ /**
+ * @brief Release aquired JVM instance
+ */
+ static void releaseEnv();
+
+public:
+ /**
+ * Java VM pointer
+ */
+ static JavaVM *m_jvm;
+
+private:
+ /**
+ * @brief constructor
+ */
+ EasySetupJVM();
+
+ /**
+ * Mutex for thread synchronization
+ */
+ static std::mutex m_currentThreadMutex;
+};
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+jclass GetJClass(const char *szClassPath);
+jobject GetJObjectInstance(const char *szClassPath);
+#ifdef __cplusplus
+}
+#endif
+#endif //__JNI_EASY_SETUP_JVM_H_
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_getter.h
+ *
+ * @brief This file contains the JGetter class declarations and its functions required
+ * for getting and setting basic data types in C++ and Java
+ */
+
+#ifndef __JNI_GETTER_H_
+#define __JNI_GETTER_H_
+
+#include <string>
+#include <jni.h>
+
+/**
+ * @class JGetter
+ * @brief This class provide utility for get/set basic data types in C++ and Java
+ *
+ */
+class JGetter {
+public:
+ /**
+ * This function is called to get String field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which string field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to string value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, std::string &value);
+
+ /**
+ * This function is called to get Boolean field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which boolean field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to boolean value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJBoolField(JNIEnv *env, jobject &object,
+ const char *fieldName, bool &value);
+
+ /**
+ * This function is called to get Integer field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which integer field is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param value
+ * reference to integer value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJIntField(JNIEnv *env, jobject &object,
+ const char *fieldName, int &value);
+
+ /**
+ * This function is called to get Object reference from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject from which Object reference is expected
+ * @param fieldName
+ * Name of the field to be extracted from JObject
+ * @param fieldType
+ * Type of the field to be extracted from JObject
+ * @param value
+ * reference to Object reference mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool getJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, jobject &value);
+};
+#endif //__JNI_GETTER_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_object.h
+ *
+ * @brief This file contains the JObject class declarations and its functions required
+ * for getting and setting basic data types in C++ and Java
+ */
+
+#ifndef __JNI_OBJECT_H_
+#define __JNI_OBJECT_H_
+
+#include <jni.h>
+#include "JniOcResource.h"
+
+/**
+ * @class JObject
+ * @brief This class provides a set of functions for JNI object.
+ *
+ */
+class JObject {
+public:
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env);
+
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env, jobject obj);
+
+ /**
+ * @brief constructor
+ */
+ JObject(JNIEnv *env, const char *classPath);
+
+ /**
+ * @brief destructor
+ *
+ */
+ virtual ~JObject();
+
+ /**
+ * Function to get the jobject.
+ *
+ * @return jobject, returns a new JNI object or NULL otherwise.
+ *
+ */
+ virtual jobject getObject() const;
+
+ /**
+ * Function to detach the jobject.
+ *
+ * @return void
+ *
+ */
+ void detachObject();
+
+protected:
+ /**
+ * JNI Environment Pointer
+ */
+ JNIEnv *m_pEnv;
+ /**
+ * Java Object
+ */
+ jobject m_pObject;
+ /**
+ * Java Class
+ */
+ jclass m_pClazz;
+ /**
+ * Boolean variable to check if an object is new
+ */
+ bool m_fIsNewObject;
+};
+#endif //__JNI_OBJECT_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_setter.h
+ *
+ * @brief This file contains the JSetter class declarations and and its functions required
+ * to set data types in C++ object from Java object
+ */
+
+#ifndef __JNI_SETTER_H_
+#define __JNI_SETTER_H_
+
+#include <jni.h>
+
+/**
+ * @class JSetter
+ * @brief This class provide utility to set data types in C++ object from Java object
+ *
+ */
+class JSetter {
+public:
+
+ /**
+ * This function is called to set Integer field in to C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which integer field will be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * integer value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJIntField(JNIEnv *env, jobject &object,
+ const char *fieldName, int value);
+
+ /**
+ * This function is called to set Long field in to C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which Long field will be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * Long value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJLongField(JNIEnv *env, jobject &object,
+ const char *fieldName, jlong value);
+
+ /**
+ * This function is called to Set Boolean field to C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which boolean field has to be set
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * boolean value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJBoolField(JNIEnv *env, jobject &object,
+ const char *fieldName, bool value);
+ /**
+ * This function is called to Set String field from the C++ object
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject in which string value has to be set
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param value
+ * string value mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *value);
+
+ /**
+ * This function is called to set Object reference in C++ object.
+ *
+ * @param env
+ * JNI Environment reference
+ * @param object
+ * JObject to which Object reference is to be set.
+ * @param fieldName
+ * Name of the field to be set in JObject
+ * @param fieldType
+ * Type of the field to be set in JObject
+ * @param value
+ * value of Object mentioned in fieldName
+ *
+ * @return returns true on success and false on failer.
+ */
+ static bool setJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, const jobject value);
+};
+
+#endif //__JNI_SETTER_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+/**
+ * @file jni_string.h
+ *
+ * @brief This file contains the declaration of JString class and its members related to JString.
+ *
+ */
+
+#ifndef __JNI_STRING_H_
+#define __JNI_STRING_H_
+
+#include <string>
+
+#include "jni_object.h"
+
+/**
+ * @class JString
+ * @brief This class inherits JObject class and provides a set of functions for JNI String.
+ *
+ */
+class JString: public JObject {
+public:
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, jstring value);
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, const char *value);
+ /**
+ * @brief constructor
+ */
+ JString(JNIEnv *env, const std::string &value);
+ /**
+ * @brief destructor
+ */
+ ~JString();
+
+ /**
+ * Function to get the string value and set it.
+ *
+ * @param value - String value to set to a private member variable.
+ *
+ * @return bool - true on success
+ *
+ */
+ bool getValue(std::string &value);
+
+ /**
+ * Function to get the private string value.
+ *
+ * @return C String value.
+ *
+ */
+ const char *c_str();
+
+private:
+ std::string m_cstr;
+};
+#endif //__JNI_STRING_H_
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "jni_easy_setup_jvm.h"
+#include <string>
+#include "jni_easy_setup.h"
+
+/**
+ * @class JClassMap
+ * @brief This class provides functions for initializing the Java class path and Java class.
+ *
+ */
+class JClassMap {
+public:
+ /**
+ * Java Class
+ */
+ jclass classRef;
+ /**
+ * Java Class Path
+ */
+ const char *szClassPath;
+
+ /**
+ * @brief constructor
+ */
+ JClassMap(const char *path) :
+ classRef(NULL) {
+ szClassPath = path;
+ }
+};
+
+/**
+ * @class JObjectMap
+ * @brief This class provides functins for initializing the Java Class path and Java Class
+ * Object.
+ *
+ */
+class JObjectMap {
+public:
+ /**
+ * Java Object
+ */
+ jobject object;
+ /**
+ * Java Class Path
+ */
+ const char *szClassPath;
+
+ /**
+ * @brief constructor
+ */
+ JObjectMap(const char *path) :
+ object(NULL) {
+ szClassPath = path;
+ }
+};
+
+static JClassMap gJClassMapArray[] = { JClassMap(
+ EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH), JClassMap(
+ EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH) };
+
+static JObjectMap gJObjectMapArray[] = { JObjectMap(
+ EASY_SETUP_SERVICE_CALLBACK_NATIVE_API_CLASS_PATH) };
+
+static JNINativeMethod gEasySetupMethodTable[] = {
+ { "InitEasySetup", "()V", (void *) JNIInitEasySetup },
+ { "TerminateEasySetup", "()V", (void *) JNITerminateEasySetup },
+ { "ProvisionEnrollee", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;I)V",
+ (void *) JNIProvisionEnrollee },
+ { "StopEnrolleeProvisioning", "(I)V", (void *) JNIStopEnrolleeProvisioning }, };
+
+static int gEasySetupMethodTableSize = sizeof(gEasySetupMethodTable)
+ / sizeof(gEasySetupMethodTable[0]);
+
+int InitializeJClassMapArray(JNIEnv *env) {
+ LOGI("InitializeJClassMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+
+ for (unsigned int i = 0; i < nLen; i++) {
+ jclass classRef = env->FindClass(gJClassMapArray[i].szClassPath);
+ if (NULL == classRef) {
+ LOGE("FindClass failed for [%s]", gJClassMapArray[i].szClassPath);
+ return -1;
+ }
+ gJClassMapArray[i].classRef = (jclass) env->NewGlobalRef(classRef);
+ env->DeleteLocalRef(classRef);
+ }
+
+ LOGI("InitializeJClassMapArray: Exit");
+ return 0;
+}
+
+jclass GetJClass(const char *szClassPath) {
+ unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+
+ jclass classRef = NULL;
+
+ for (unsigned int i = 0; i < nLen; i++) {
+ if (0 == strcmp(gJClassMapArray[i].szClassPath, szClassPath)) {
+ classRef = gJClassMapArray[i].classRef;
+ break;
+ }
+ }
+
+ return classRef;
+}
+
+void DeleteClassMapArray(JNIEnv *env) {
+ LOGI("DeleteClassMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJClassMapArray) / sizeof(JClassMap);
+ for (unsigned int i = 0; i < nLen; i++) {
+ if (NULL != gJClassMapArray[i].classRef) {
+ env->DeleteGlobalRef(gJClassMapArray[i].classRef);
+ gJClassMapArray[i].classRef = NULL;
+ }
+ }
+
+ LOGI("DeleteClassMapArray: Exit");
+}
+
+int InitializeJObjectMapArray(JNIEnv *env) {
+ LOGI("InitializeJObjectMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+
+ for (unsigned int i = 0; i < nLen; i++) {
+ jclass classRef = env->FindClass(gJObjectMapArray[i].szClassPath);
+ if (NULL == classRef) {
+ LOGE("InitializeJObjectMapArray: FindClass failed for [%s]",
+ gJObjectMapArray[i].szClassPath);
+ return -1;
+ }
+
+ std::string methodSignature = "()L";
+ methodSignature.append(gJObjectMapArray[i].szClassPath);
+ methodSignature.append(";");
+
+ // Get the object form "getInstance"
+ jmethodID methodid = env->GetStaticMethodID(classRef, "getInstance",
+ methodSignature.c_str());
+ if (NULL == methodid) {
+ LOGE("InitializeJObjectMapArray: GetStaticMethodID failed for [%s]",
+ gJObjectMapArray[i].szClassPath);
+ return -1;
+ }
+
+ // Get the singleton object
+ jobject objectRef = (jobject) env->CallStaticObjectMethod(classRef,
+ methodid);
+ if (NULL == objectRef) {
+ LOGE(
+ "InitializeJObjectMapArray: CallStaticObjectMethod failed for [%s]",
+ gJObjectMapArray[i].szClassPath);
+ return -1;
+ }
+
+ gJObjectMapArray[i].object = (jobject) env->NewGlobalRef(objectRef);
+ env->DeleteLocalRef(classRef);
+ }
+
+ LOGI("InitializeJObjectMapArray: Exit");
+ return 0;
+}
+
+jobject GetJObjectInstance(const char *szClassPath) {
+ unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+
+ jobject object = NULL;
+
+ for (unsigned int i = 0; i < nLen; i++) {
+ if (0 == strcmp(gJObjectMapArray[i].szClassPath, szClassPath)) {
+ object = gJObjectMapArray[i].object;
+ break;
+ }
+ }
+
+ return object;
+}
+
+void DeleteObjectMapArray(JNIEnv *env) {
+ LOGI("DeleteObjectMapArray: Enter");
+
+ unsigned int nLen = sizeof(gJObjectMapArray) / sizeof(JObjectMap);
+ for (unsigned int i = 0; i < nLen; i++) {
+ if (NULL != gJObjectMapArray[i].object) {
+ env->DeleteGlobalRef(gJObjectMapArray[i].object);
+ gJObjectMapArray[i].object = NULL;
+ }
+ }
+
+ LOGI("DeleteObjectMapArray: Exit");
+}
+
+JavaVM *EasySetupJVM::m_jvm = NULL;
+std::mutex EasySetupJVM::m_currentThreadMutex;
+JNIEnv *EasySetupJVM::getEnv() {
+ std::unique_lock < std::mutex > scoped_lock(m_currentThreadMutex);
+
+ if (NULL == m_jvm) {
+ LOGE("Failed to get JVM");
+ return NULL;
+ }
+
+ JNIEnv *env = NULL;
+ jint ret = m_jvm->GetEnv((void **) &env, JNI_CURRENT_VERSION);
+ switch (ret) {
+ case JNI_OK:
+ return env;
+ case JNI_EDETACHED:
+ if (0 > m_jvm->AttachCurrentThread(&env, NULL)) {
+ LOGE("Failed to attach current thread to env");
+ return NULL;
+ }
+ return env;
+ case JNI_EVERSION:
+ LOGE("JNI version not supported");
+ return NULL;
+ default:
+ LOGE("Failed to get the environment");
+ return NULL;
+ }
+}
+
+void EasySetupJVM::releaseEnv() {
+ std::unique_lock < std::mutex > scoped_lock(m_currentThreadMutex);
+
+ if (0 == m_jvm) {
+ LOGE("Failed to release JVM");
+ return;
+ }
+
+ m_jvm->DetachCurrentThread();
+}
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM *vm, void *reserved) {
+ LOGD("JNI_OnLoad: Enter");
+
+ if (!vm) {
+ LOGE("JNI_OnLoad: vm is invalid");
+ return JNI_ERR;
+ }
+
+ JNIEnv *env = NULL;
+ if (JNI_OK != vm->GetEnv((void **) &env, JNI_CURRENT_VERSION)) {
+ LOGE("JNI_OnLoad: Version check is failed!");
+ return JNI_ERR;
+ }
+
+ if (0 != InitializeJClassMapArray(env)) {
+ LOGE("JNI_OnLoad: Initialize JClass Array failed!");
+ return JNI_ERR;
+ }
+
+ if (0 != InitializeJObjectMapArray(env)) {
+ LOGE("JNI_OnLoad: Initialize JObject Array failed!");
+ return JNI_ERR;
+ }
+
+ jclass easySetupClassRef = GetJClass(
+ EASY_SETUP_SERVICE_NATIVE_API_CLASS_PATH);
+ if (NULL == easySetupClassRef) {
+ LOGE("JNI_OnLoad: GetJClass gEasySetupClass failed !");
+ return JNI_ERR;
+ }
+ env->RegisterNatives(easySetupClassRef, gEasySetupMethodTable,
+ gEasySetupMethodTableSize);
+
+ EasySetupJVM::m_jvm = vm;
+
+ LOGI("JNI_OnLoad: Exit");
+ return JNI_CURRENT_VERSION;
+}
+
+JNIEXPORT void JNICALL JNI_OnUnload(JavaVM *vm, void *reserved)
+{
+ LOGD("JNI_OnUnload: Enter");
+
+ JNIEnv *env = NULL;
+ if (JNI_OK != vm->GetEnv((void **)&env, JNI_CURRENT_VERSION))
+ {
+ LOGE("JNI_OnLoad: Version check is failed!");
+ return;
+ }
+
+ // delete all class references
+ DeleteClassMapArray(env);
+
+ // delete all jobject
+ DeleteObjectMapArray(env);
+
+ LOGD("JNI_OnUnload: Exit");
+}
+
+#ifdef __cplusplus
+}
+#endif
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "jni_getter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JGetter"
+
+bool JGetter::getJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, std::string &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ LOGE("getJStringField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed [%s]", fieldName);
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Ljava/lang/String;");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ jstring jValue = (jstring) env->GetObjectField(object, fieldID);
+ if (NULL == jValue) {
+ LOGE("GetObjectField failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ const char *cstr = env->GetStringUTFChars(jValue, 0);
+ if (cstr == NULL) {
+ LOGE("GetStringUTFChars failed");
+ } else {
+ value = cstr;
+ env->ReleaseStringUTFChars(jValue, cstr);
+ }
+
+ env->DeleteLocalRef(clazz);
+ env->DeleteLocalRef(jValue);
+
+ return true;
+}
+
+bool JGetter::getJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
+ bool &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ LOGE("getJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Z");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ value = env->GetBooleanField(object, fieldID);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JGetter::getJIntField(JNIEnv *env, jobject &object, const char *fieldName,
+ int &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ LOGE("getJIntField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "I");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ value = env->GetIntField(object, fieldID);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JGetter::getJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, jobject &value) {
+ if (NULL == env || NULL == object || NULL == fieldName) {
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, fieldType);
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s][%s]", fieldName, fieldType);
+ return false;
+ }
+
+ value = env->GetObjectField(object, fieldID);
+ if (NULL == value) {
+ return false;
+ }
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
--- /dev/null
+#include "jni_object.h"
+
+//#define NULL 0
+#define LOG_TAG "TM_JObject"
+
+JObject::JObject(JNIEnv *env) :
+ m_pEnv(env), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(true) {
+}
+
+JObject::JObject(JNIEnv *env, jobject obj) :
+ m_pEnv(NULL), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(false) {
+ if (NULL == env || NULL == obj) {
+ return;
+ }
+
+ m_pEnv = env;
+ m_pObject = obj;
+ m_pClazz = m_pEnv->GetObjectClass(obj);
+}
+
+JObject::JObject(JNIEnv *env, const char *classPath) :
+ m_pEnv(NULL), m_pObject(NULL), m_pClazz(NULL), m_fIsNewObject(true) {
+ if (NULL == env || NULL == classPath) {
+ LOGI("JObject Invalid parameters");
+ return;
+ }
+
+ m_pEnv = env;
+ //m_pClazz = GetJClass( classPath );
+
+ if (NULL == m_pClazz) {
+ LOGE("GetJClass failed [%s]", classPath);
+ return;
+ }
+
+ jmethodID mid = env->GetMethodID(m_pClazz, "<init>", "()V");
+ if (NULL == mid) {
+ LOGE("GetMethodID failed [%s]", classPath);
+ return;
+ }
+
+ m_pObject = env->NewObject(m_pClazz, mid);
+}
+
+JObject::~JObject() {
+ if (m_pEnv) {
+ if (m_pObject && m_fIsNewObject) {
+ m_pEnv->DeleteLocalRef(m_pObject);
+ }
+
+ if (m_pClazz && !m_fIsNewObject) {
+ m_pEnv->DeleteLocalRef(m_pClazz);
+ }
+ }
+}
+
+jobject JObject::getObject() const {
+ return m_pObject;
+}
+
+void JObject::detachObject() {
+ if (m_fIsNewObject) {
+ m_fIsNewObject = false;
+ m_pClazz = NULL;
+ }
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "jni_setter.h"
+
+#include <string>
+
+#include "JniOcResource.h"
+
+#define LOG_TAG "TM_JSetter"
+
+bool JSetter::setJStringField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJStringField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Ljava/lang/String;");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+
+ jstring jvalue;
+ if (value != NULL && strlen(value) > 0) {
+ jclass strClass = env->FindClass("java/lang/String");
+ jmethodID ctorID = env->GetMethodID(strClass, "<init>",
+ "([BLjava/lang/String;)V");
+ jbyteArray bytes = env->NewByteArray(strlen(value));
+ env->SetByteArrayRegion(bytes, 0, strlen(value), (jbyte *) value);
+ jstring encoding = env->NewStringUTF("utf-8");
+ jvalue = (jstring) env->NewObject(strClass, ctorID, bytes, encoding);
+ env->DeleteLocalRef(strClass);
+ env->DeleteLocalRef(bytes);
+ env->DeleteLocalRef(encoding);
+ } else {
+ jvalue = env->NewStringUTF("");
+ }
+
+ env->SetObjectField(object, fieldID, jvalue);
+
+ env->DeleteLocalRef(jvalue);
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJIntField(JNIEnv *env, jobject &object, const char *fieldName,
+ int value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJIntField invalid paramter");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "I");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetIntField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJLongField(JNIEnv *env, jobject &object, const char *fieldName,
+ jlong value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJLongField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "J");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetLongField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJBoolField(JNIEnv *env, jobject &object, const char *fieldName,
+ bool value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, "Z");
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s]", fieldName);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetBooleanField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
+bool JSetter::setJObjectField(JNIEnv *env, jobject &object,
+ const char *fieldName, const char *fieldType, const jobject value) {
+ if (NULL == env || NULL == fieldName) {
+ LOGE("setJBoolField invalid parameters");
+ return false;
+ }
+
+ jclass clazz = env->GetObjectClass(object);
+ if (NULL == clazz) {
+ LOGE("GetObjectClass failed");
+ return false;
+ }
+
+ jfieldID fieldID = env->GetFieldID(clazz, fieldName, fieldType);
+ if (0 == fieldID) {
+ LOGE("GetFieldID failed [%s] [%s]", fieldName, fieldType);
+ env->DeleteLocalRef(clazz);
+ return false;
+ }
+ env->SetObjectField(object, fieldID, value);
+
+ env->DeleteLocalRef(clazz);
+
+ return true;
+}
+
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "jni_string.h"
+
+#define LOG_TAG "TM_JString"
+
+JString::JString(JNIEnv *env, jstring value) :
+ JObject(env, value) {
+ const char *buff = env->GetStringUTFChars(value, 0);
+
+ m_cstr = buff;
+
+ env->ReleaseStringUTFChars(value, buff);
+}
+
+JString::JString(JNIEnv *env, const char *value) :
+ JObject(env) {
+ m_cstr = value;
+
+ if (env) {
+ m_pObject = env->NewStringUTF(value);
+ }
+}
+
+JString::JString(JNIEnv *env, const std::string &value) :
+ JObject(env) {
+ m_cstr = value;
+
+ if (env) {
+ m_pObject = env->NewStringUTF(value.c_str());
+ }
+}
+
+JString::~JString() {
+}
+
+bool JString::getValue(std::string &value) {
+ value = m_cstr;
+ return true;
+}
+
+const char *JString::c_str() {
+ return m_cstr.c_str();
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 __EASYSETUP_MGR_H_
+#define __EASYSETUP_MGR_H_
+
+#include <string.h>
+
+#include "logger.h"
+#include "ocstack.h"
+#include "octypes.h"
+#include "common.h"
+
+#include "provisioning.h"
+
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+OCStackResult InitProvProcess();
+
+OCStackResult ResetProvProcess();
+
+OCStackResult RegisterCallback(
+ OCProvisioningStatusCB provisioningStatusCallback);
+
+void UnRegisterCallback();
+
+OCStackResult StartProvisioning(const EnrolleeNWProvInfo_t *netInfo);
+
+OCStackResult StopProvisioning(OCConnectivityType connectivityType);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 __PROVISIONING_HANDLER_H_
+#define __PROVISIONING_HANDLER_H_
+
+#include "octypes.h"
+
+#include "logger.h"
+#include "ocstack.h"
+#include "common.h"
+
+//-----------------------------------------------------------------------------
+// Defines
+//-----------------------------------------------------------------------------
+#define EASY_SETUP_DEFAULT_CONTEXT_VALUE 0x99
+#define TAG "EASY_SETUP_PROVISIONING"
+
+//-----------------------------------------------------------------------------
+// Typedefs
+//-----------------------------------------------------------------------------
+
+/**
+ * List of methods that can be inititated from the client
+ */
+OCStackResult InitProvisioningHandler();
+
+OCStackResult TerminateProvisioningHandler();
+
+void *listeningFunc(void *);
+
+OCStackApplicationResult ProvisionEnrolleeResponse(void *ctx, OCDoHandle handle,
+ OCClientResponse *clientResponse);
+
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
+ OCDevAddr *destination, int pauseBeforeStart);
+
+OCStackApplicationResult GetProvisioningStatusResponse(void *ctx, OCDoHandle handle,
+ OCClientResponse *clientResponse);
+
+OCStackResult InvokeOCDoResource(const char *query, OCMethod method, const OCDevAddr *dest,
+ OCQualityOfService qos, OCClientResponseHandler cb,
+ OCRepPayload *payload,
+ OCHeaderOption *options, uint8_t numOptions);
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
+ const OCDevAddr *destination);
+
+OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback,
+ char *findResQuery);
+
+void StopProvisioningProcess();
+
+OCStackApplicationResult FindProvisioningResourceResponse(void *ctx, OCDoHandle handle,
+ OCClientResponse *clientResponse);
+
+void *FindProvisioningResource(void *data);
+
+//Invoke Provisioning Status Callback
+ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
+ ProvStatus provStatus);
+
+
+void LogProvisioningResponse(OCRepPayloadValue * val);
+
+bool ConfigEnrolleeObject(const EnrolleeNWProvInfo_t *netInfo);
+
+bool ClearMemory();
+
+void SuccessCallback(OCClientResponse * clientResponse);
+
+void ErrorCallback(ProvStatus status);
+
+bool ValidateEnrolleResponse(OCClientResponse * clientResponse);
+
+bool ValidateFinddResourceResponse(OCClientResponse * clientResponse);
+
+ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
+ ProvStatus provStatus);
+
+ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status);
+
+ProvisioningInfo *CreateCallBackObject();
+
+bool ResetProgress();
+
+bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback);
+
+bool InProgress();
+
+bool ValidateEasySetupParams(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback);
+
+bool IsSetupStopped();
+
+
+#endif
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <stdint.h>
+#include <sstream>
+
+#include "prov_adapter.h"
+
+//Use ipv4addr for both InitDiscovery and InitDeviceDiscovery
+char ipv4addr[IPV4_ADDR_SIZE] = {0};
+
+volatile static OCProvisioningStatusCB cbData = NULL;
+
+OCStackResult InitProvProcess() {
+
+
+ OCStackResult result = OC_STACK_ERROR;
+
+ if (InitProvisioningHandler() == OC_STACK_OK) {
+ result = OC_STACK_OK;
+ OIC_LOG(DEBUG, TAG, "InitProvisioningHandler returned Success");
+ } else {
+ result = OC_STACK_ERROR;
+ OIC_LOG_V(ERROR, TAG, "InitProvisioningHandler returned error = %s",
+ result);
+ }
+
+ return result;
+}
+
+OCStackResult ResetProvProcess() {
+ return TerminateProvisioningHandler();
+}
+
+OCStackResult RegisterCallback(
+ OCProvisioningStatusCB provisioningStatusCallback) {
+ OCStackResult result = OC_STACK_OK;
+
+ if (provisioningStatusCallback != NULL) {
+ cbData = provisioningStatusCallback;
+ }
+ else {
+ result = OC_STACK_ERROR;
+ OIC_LOG(ERROR, TAG, "provisioningStatusCallback is NULL");
+ }
+
+ return result;
+}
+
+void UnRegisterCallback() {
+ if (cbData) {
+ cbData = NULL;
+ }
+}
+
+OCStackResult StartProvisioning(const EnrolleeNWProvInfo_t *netInfo) {
+
+ char findQuery[64] = {0};
+ snprintf(findQuery, sizeof(findQuery) - 1, UNICAST_PROVISIONING_QUERY,
+ netInfo->netAddressInfo.WIFI.ipAddress, IP_PORT);
+
+ return StartProvisioningProcess(netInfo, cbData, findQuery);
+}
+
+OCStackResult StopProvisioning(OCConnectivityType connectivityType) {
+ OCStackResult result = OC_STACK_OK;
+
+ StopProvisioningProcess();
+
+ return result;
+}
+
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "provisioning.h"
+
+//Standard includes
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <pthread.h>
+
+//EasySetup include files
+#include "ocpayload.h"
+#include "common.h"
+
+
+// External includes
+#include "logger.h"
+#include "oic_malloc.h"
+
+bool g_provisioningCondFlag = false;
+
+static EnrolleeNWProvInfo_t *netProvInfo;
+
+char szFindResourceQueryUri[64] = {0};
+
+/**
+ * @var cbData
+ * @brief Callback for providing provisioning status callback to application
+ */
+static OCProvisioningStatusCB cbData = NULL;
+
+
+void ErrorCallback(ProvStatus status) {
+ ProvisioningInfo *provInfo = GetCallbackObjectOnError(status);
+ cbData(provInfo);
+ ResetProgress();
+}
+
+
+OCStackResult InitProvisioningHandler() {
+ OCStackResult ret = OC_STACK_ERROR;
+ /* Initialize OCStack*/
+ if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK) {
+ OIC_LOG(ERROR, TAG, "OCStack init error");
+ return ret;
+ }
+
+
+ char *string = "listeningFunc invoked in a thread";
+
+ pthread_t thread_handle;
+
+ if (pthread_create(&thread_handle, NULL, listeningFunc, (void *) string)) {
+ OIC_LOG(DEBUG, TAG, "Thread creation failed");
+ return OC_STACK_ERROR;
+ }
+
+ return OC_STACK_OK;
+}
+
+OCStackResult TerminateProvisioningHandler() {
+ OCStackResult ret = OC_STACK_ERROR;
+ if (OCStop() != OC_STACK_OK) {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ }
+
+ g_provisioningCondFlag = true;
+
+ ret = OC_STACK_OK;
+ return ret;
+}
+
+void *listeningFunc(void *data) {
+ while (!g_provisioningCondFlag) {
+ OCStackResult result;
+
+ result = OCProcess();
+
+ if (result != OC_STACK_OK) {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ }
+
+ // To minimize CPU utilization we may wish to do this with sleep
+ sleep(1);
+ }
+ return NULL;
+}
+
+
+OCStackApplicationResult ProvisionEnrolleeResponse(void *ctx, OCDoHandle handle,
+ OCClientResponse *clientResponse) {
+ OIC_LOG_V(DEBUG, TAG, "INSIDE ProvisionEnrolleeResponse");
+
+ // If user stopped the process then return from this function;
+ if (IsSetupStopped()) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ ProvisioningInfo *provInfo;
+
+ if (!ValidateEnrolleResponse(clientResponse)) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ char *tnn;
+ char *cd;
+
+ OCRepPayload *input = (OCRepPayload * )(clientResponse->payload);
+
+ while (input) {
+
+ int64_t ps;
+ if (OCRepPayloadGetPropInt(input, OC_RSRVD_ES_PS, &ps)) {
+
+ if (ps == 1) {
+ input = input->next;
+ continue;
+ }
+ else {
+ OIC_LOG_V(DEBUG, TAG, "PS is NOT proper");
+ goto Error;
+
+ }
+ }
+
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_TNN, &tnn)) {
+ if (!strcmp(tnn, netProvInfo->netAddressInfo.WIFI.ssid)) {
+ OIC_LOG_V(DEBUG, TAG, "SSID is proper");
+ input = input->next;
+ continue;
+ }
+ else {
+ OIC_LOG_V(DEBUG, TAG, "SSID is NOT proper");
+ goto Error;
+ }
+ }
+
+ if (OCRepPayloadGetPropString(input, OC_RSRVD_ES_CD, &cd)) {
+ if (!strcmp(cd, netProvInfo->netAddressInfo.WIFI.pwd)) {
+ OIC_LOG_V(DEBUG, TAG, "Password is proper");
+ input = input->next;
+ continue;
+ }
+ else {
+ OIC_LOG_V(DEBUG, TAG, "Password is NOT proper");
+ goto Error;
+ }
+ }
+
+ LogProvisioningResponse(input->values);
+
+ input = input->next;
+
+ }
+
+ SuccessCallback(clientResponse);
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+ Error:
+ {
+
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+}
+
+OCStackResult StartProvisioningProcess(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback,
+ char *findResQuery) {
+
+ OCStackResult result = OC_STACK_ERROR;
+
+ snprintf(szFindResourceQueryUri, sizeof(szFindResourceQueryUri) - 1, findResQuery);
+ char *string = "Starting provisioning process ";
+
+ pthread_t thread_handle;
+
+ if (!ValidateEasySetupParams(netInfo, provisioningStatusCallback)) {
+ goto Error;
+ }
+
+ if (!SetProgress(provisioningStatusCallback)) {
+ // Device provisioning session is running already.
+ OIC_LOG(INFO, TAG, PCF("Device provisioning session is running already"));
+ goto Error;
+ }
+
+ if (!ConfigEnrolleeObject(netInfo)) {
+ goto Error;
+ }
+
+ if (pthread_create(&thread_handle, NULL, FindProvisioningResource, (void *) string)) {
+ goto Error;
+
+ }
+
+ pthread_join(thread_handle, NULL);
+
+
+ return OC_STACK_OK;
+
+ Error:
+ {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_ERROR;
+ }
+
+}
+
+void StopProvisioningProcess() {
+ //Only basis test is done for below API
+ ResetProgress();
+}
+
+bool ClearMemory() {
+
+ OIC_LOG(DEBUG, TAG, "thread_pool_add_task of FindProvisioningResource failed");
+ return true;
+
+}
+
+bool ConfigEnrolleeObject(const EnrolleeNWProvInfo_t *netInfo) {
+
+ //Copy Network Provisioning Information
+ netProvInfo = (EnrolleeNWProvInfo_t *) OICCalloc(1, sizeof(EnrolleeNWProvInfo_t));
+
+ if (netProvInfo == NULL) {
+ OIC_LOG(ERROR, TAG, "Invalid input..");
+ return false;
+ }
+
+ memcpy(netProvInfo, netInfo, sizeof(EnrolleeNWProvInfo_t));
+
+ OIC_LOG_V(DEBUG, TAG, "Network Provisioning Info. SSID = %s",
+ netProvInfo->netAddressInfo.WIFI.ssid);
+
+ OIC_LOG_V(DEBUG, TAG, "Network Provisioning Info. PWD = %s",
+ netProvInfo->netAddressInfo.WIFI.pwd);
+
+ return true;
+
+}
+
+void LogProvisioningResponse(OCRepPayloadValue * val) {
+
+ switch (val->type) {
+ case OCREP_PROP_NULL:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s: NULL", val->name);
+ break;
+ case OCREP_PROP_INT:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(int):%lld", val->name, val->i);
+ break;
+ case OCREP_PROP_DOUBLE:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(double):%f", val->name, val->d);
+ break;
+ case OCREP_PROP_BOOL:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool):%s", val->name, val->b ? "true" : "false");
+ break;
+ case OCREP_PROP_STRING:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(string):%s", val->name, val->str);
+ break;
+ case OCREP_PROP_OBJECT:
+ // Note: Only prints the URI (if available), to print further, you'll
+ // need to dig into the object better!
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep):%s", val->name, val->obj->uri);
+ break;
+ case OCREP_PROP_ARRAY:
+ switch (val->arr.type) {
+ case OCREP_PROP_INT:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(int array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_DOUBLE:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(double array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_BOOL:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(bool array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_STRING:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(string array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ case OCREP_PROP_OBJECT:
+ OIC_LOG_V(DEBUG, TAG, "\t\t%s(OCRep array):%lld x %lld x %lld", val->name,
+ val->arr.dimensions[0], val->arr.dimensions[1],
+ val->arr.dimensions[2]);
+ break;
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+OCStackResult FindNetworkResource() {
+ OCStackResult ret = OC_STACK_ERROR;
+ if (OCStop() != OC_STACK_OK) {
+ OIC_LOG(ERROR, TAG, "OCStack stop error");
+ }
+
+ return ret;
+}
+
+ProvisioningInfo *PrepareProvisioingStatusCB(OCClientResponse *clientResponse,
+ ProvStatus provStatus) {
+
+ ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
+
+ if (provInfo == NULL) {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
+
+ if (devAddr == NULL) {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ strncpy(devAddr->addr, clientResponse->addr->addr, sizeof(devAddr->addr));
+ devAddr->port = clientResponse->addr->port;
+
+ provInfo->provDeviceInfo.addr = devAddr;
+
+ provInfo->provStatus = provStatus;
+
+ return provInfo;
+}
+
+
+bool InProgress() {
+
+ // It means already Easy Setup provisioning session is going on.
+ if (NULL != cbData) {
+ OIC_LOG(ERROR, TAG, "Easy setup session is already in progress");
+ return true;
+ }
+
+ return false;
+}
+
+bool SetProgress(OCProvisioningStatusCB provisioningStatusCallback) {
+
+ if (InProgress())
+ return false;
+
+ cbData = provisioningStatusCallback;
+
+
+ return true;
+}
+
+bool ResetProgress() {
+
+ cbData = NULL;
+ return true;
+}
+
+ProvisioningInfo *CreateCallBackObject() {
+
+ ProvisioningInfo *provInfo = (ProvisioningInfo *) OICCalloc(1, sizeof(ProvisioningInfo));
+
+ if (provInfo == NULL) {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ OCDevAddr *devAddr = (OCDevAddr *) OICCalloc(1, sizeof(OCDevAddr));
+
+ if (devAddr == NULL) {
+ OIC_LOG_V(ERROR, TAG, "Failed to allocate memory");
+ return NULL;
+ }
+
+ provInfo->provDeviceInfo.addr = devAddr;
+
+ return provInfo;
+
+}
+
+ProvisioningInfo *GetCallbackObjectOnError(ProvStatus status) {
+
+ ProvisioningInfo *provInfo = CreateCallBackObject();
+ strncpy(provInfo->provDeviceInfo.addr->addr, netProvInfo->netAddressInfo.WIFI.ipAddress,
+ sizeof(provInfo->provDeviceInfo.addr->addr));
+ provInfo->provDeviceInfo.addr->port = IP_PORT;
+ provInfo->provStatus = status;
+ return provInfo;
+}
+
+ProvisioningInfo *GetCallbackObjectOnSuccess(OCClientResponse *clientResponse,
+ ProvStatus provStatus) {
+ ProvisioningInfo *provInfo = CreateCallBackObject();
+ strncpy(provInfo->provDeviceInfo.addr->addr, clientResponse->addr->addr,
+ sizeof(provInfo->provDeviceInfo.addr->addr));
+ provInfo->provDeviceInfo.addr->port = clientResponse->addr->port;
+ provInfo->provStatus = provStatus;
+ return provInfo;
+}
+
+bool ValidateFinddResourceResponse(OCClientResponse * clientResponse) {
+
+ if (!(clientResponse) || !(clientResponse->payload)) {
+
+ OIC_LOG_V(INFO, TAG, "ProvisionEnrolleeResponse received Null clientResponse");
+
+ return false;
+
+ }
+ return true;
+}
+
+bool ValidateEnrolleResponse(OCClientResponse * clientResponse) {
+
+ if (!(clientResponse) || !(clientResponse->payload)) {
+
+ OIC_LOG_V(INFO, TAG, "ProvisionEnrolleeResponse received Null clientResponse");
+
+ return false;
+
+ }
+
+ if (clientResponse->payload->type != PAYLOAD_TYPE_REPRESENTATION) {
+
+ OIC_LOG_V(DEBUG, TAG, "Incoming payload not a representation");
+ return false;
+
+ }
+
+ // If flow reachese here means no error condition hit.
+ return true;
+
+}
+
+void SuccessCallback(OCClientResponse * clientResponse) {
+ ProvisioningInfo *provInfo = GetCallbackObjectOnSuccess(clientResponse, DEVICE_PROVISIONED);
+ cbData(provInfo);
+ ResetProgress();
+}
+
+void *FindProvisioningResource(void *data) {
+
+ // If user stopped the process before thread get scheduled then check and return from this function;
+ if (IsSetupStopped()) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return NULL;
+ }
+
+ OCStackResult ret = OC_STACK_ERROR;
+
+ OIC_LOG_V(DEBUG, TAG, "szFindResourceQueryUri = %s", szFindResourceQueryUri);
+
+ OCCallbackData ocCBData;
+
+ ocCBData.cb = FindProvisioningResourceResponse;
+ ocCBData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
+ ocCBData.cd = NULL;
+
+
+ ret = OCDoResource(NULL, OC_REST_DISCOVER, szFindResourceQueryUri, NULL, NULL,
+ netProvInfo->connType, OC_LOW_QOS,
+ &ocCBData, NULL, 0);
+
+ if (ret != OC_STACK_OK) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ }
+
+ return NULL;
+}
+
+OCStackResult InvokeOCDoResource(const char *query, OCMethod method, const OCDevAddr *dest,
+ OCQualityOfService qos, OCClientResponseHandler cb,
+ OCRepPayload *payload,
+ OCHeaderOption *options, uint8_t numOptions) {
+ OCStackResult ret;
+ OCCallbackData cbData;
+
+ cbData.cb = cb;
+ cbData.context = (void *) EASY_SETUP_DEFAULT_CONTEXT_VALUE;
+ cbData.cd = NULL;
+
+ ret = OCDoResource(NULL, method, query, dest, (OCPayload *) payload, netProvInfo->connType, qos,
+ &cbData, options, numOptions);
+
+ if (ret != OC_STACK_OK) {
+ OIC_LOG_V(ERROR, TAG, "OCDoResource returns error %d with method %d", ret, method);
+ }
+
+ return ret;
+}
+
+OCStackResult ProvisionEnrollee(OCQualityOfService qos, const char *query, const char *resUri,
+ OCDevAddr *destination, int pauseBeforeStart) {
+
+
+ // This sleep is required in case of BLE provisioning due to packet drop issue.
+ OIC_LOG_V(INFO, TAG, "Sleeping for %d seconds", pauseBeforeStart);
+ sleep(pauseBeforeStart);
+ OIC_LOG_V(INFO, TAG, "\n\nExecuting ProvisionEnrollee%s", __func__);
+
+ OCRepPayload *payload = OCRepPayloadCreate();
+
+ OCRepPayloadSetUri(payload, resUri);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_TNN, netProvInfo->netAddressInfo.WIFI.ssid);
+ OCRepPayloadSetPropString(payload, OC_RSRVD_ES_CD, netProvInfo->netAddressInfo.WIFI.pwd);
+
+ OIC_LOG_V(DEBUG, TAG, "OCPayload ready for ProvisionEnrollee");
+
+ OCStackResult ret = InvokeOCDoResource(query, OC_REST_PUT, destination, OC_HIGH_QOS,
+ ProvisionEnrolleeResponse, payload, NULL, 0);
+
+ return ret;
+}
+
+bool IsSetupStopped() {
+ return (cbData == NULL) ? true : false;
+}
+
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+// NOTE : Keeping Wifi provisioning in this file to have adaptability while doing OOPs refactoring
+
+#include "provisioning.h"
+
+//Standard includes
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <signal.h>
+#include <unistd.h>
+#include <pthread.h>
+
+//EasySetup include files
+#include "ocpayload.h"
+#include "common.h"
+
+// External includes
+#include "logger.h"
+#include "oic_malloc.h"
+
+
+static EnrolleeNWProvInfo_t *netProvInfo;
+
+/**
+ * @var cbData
+ * @brief Callback for providing provisioning status callback to application
+ */
+static OCProvisioningStatusCB cbData = NULL;
+
+
+OCStackApplicationResult GetProvisioningStatusResponse(void *ctx, OCDoHandle handle,
+ OCClientResponse *clientResponse) {
+
+
+ // If user stopped the process then return from this function;
+ if (IsSetupStopped()) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+
+ ProvisioningInfo *provInfo;
+
+ if (!ValidateEnrolleResponse(clientResponse)) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OCRepPayload *input = (OCRepPayload * )(clientResponse->payload);
+
+ char query[OIC_STRING_MAX_VALUE] =
+ {'\0'};
+ char resURI[MAX_URI_LENGTH] =
+ {'\0'};
+
+ OIC_LOG_V(DEBUG, TAG, "resUri = %s", input->uri);
+
+ strncpy(resURI, input->uri, sizeof(resURI) - 1);
+
+ snprintf(query, sizeof(query), UNICAST_PROV_STATUS_QUERY, clientResponse->addr->addr, IP_PORT,
+ resURI);
+
+ //OCPayloadLogRep(DEBUG,TAG,input);
+
+ if (ProvisionEnrollee(OC_HIGH_QOS, query, OC_RSRVD_ES_URI_PROV, clientResponse->addr, 0)
+ != OC_STACK_OK) {
+ OIC_LOG(INFO, TAG,
+ "GetProvisioningStatusResponse received NULL clientResponse.Invoking Provisioing Status Callback");
+
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+OCStackResult GetProvisioningStatus(OCQualityOfService qos, const char *query,
+ const OCDevAddr *destination) {
+ OCStackResult ret = OC_STACK_ERROR;
+ OCHeaderOption options[MAX_HEADER_OPTIONS];
+
+ OIC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
+
+ uint8_t option0[] =
+ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+ uint8_t option1[] =
+ {11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
+ memset(options, 0, sizeof(OCHeaderOption) * MAX_HEADER_OPTIONS);
+ options[0].protocolID = OC_COAP_ID;
+ options[0].optionID = 2048;
+ memcpy(options[0].optionData, option0, sizeof(option0));
+ options[0].optionLength = 10;
+ options[1].protocolID = OC_COAP_ID;
+ options[1].optionID = 3000;
+ memcpy(options[1].optionData, option1, sizeof(option1));
+ options[1].optionLength = 10;
+
+ ret = InvokeOCDoResource(query, OC_REST_GET, destination, OC_HIGH_QOS,
+ GetProvisioningStatusResponse, NULL, options, 2);
+ return ret;
+}
+
+
+// This is a function called back when a device is discovered
+OCStackApplicationResult FindProvisioningResourceResponse(void *ctx, OCDoHandle handle,
+ OCClientResponse *clientResponse) {
+
+ OIC_LOG(INFO, TAG, PCF("Entering FindProvisioningResourceResponse"));
+
+ // If user stopped the process then return from this function;
+ if (IsSetupStopped()) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ ClearMemory();
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+
+ if (!ValidateFinddResourceResponse(clientResponse)) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OCStackApplicationResult response = OC_STACK_DELETE_TRANSACTION;
+
+ ProvisioningInfo *provInfo;
+ char szQueryUri[64] =
+ {0};
+
+ OCDiscoveryPayload *discoveryPayload = (OCDiscoveryPayload * )(clientResponse->payload);
+
+ // Need to conform if below check is required or not. As Null check of clientResponse->payload is already performed above
+ if (!discoveryPayload) {
+ OIC_LOG_V(DEBUG, TAG, "Failed To parse");
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ OIC_LOG_V(DEBUG, TAG, "resUri = %s", discoveryPayload->resources->uri);
+
+ snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_PROV_STATUS_QUERY,
+ clientResponse->devAddr.addr, IP_PORT, discoveryPayload->resources->uri);
+
+ OIC_LOG_V(DEBUG, TAG, "query before GetProvisioningStatus call = %s", szQueryUri);
+
+ if (GetProvisioningStatus(OC_HIGH_QOS, szQueryUri, &clientResponse->devAddr) != OC_STACK_OK) {
+ ErrorCallback(DEVICE_NOT_PROVISIONED);
+ return OC_STACK_DELETE_TRANSACTION;
+ }
+
+ return OC_STACK_KEEP_TRANSACTION;
+
+}
+
+bool ValidateEasySetupParams(const EnrolleeNWProvInfo_t *netInfo,
+ OCProvisioningStatusCB provisioningStatusCallback) {
+
+ if (netInfo == NULL || strlen(netInfo->netAddressInfo.WIFI.ipAddress) == 0) {
+ OIC_LOG(ERROR, TAG, "Request URI is NULL");
+ return false;
+ }
+
+ if (provisioningStatusCallback == NULL) {
+ OIC_LOG(ERROR, TAG, "ProvisioningStatusCallback is NULL");
+ return false;
+ }
+
+ return true;
+
+}
+
+
+
+++ /dev/null
-LinuxMain.o
-NotificationManager.o
-RegistrationManager.o
-ResourceManager.o
-SampleConsumer.o
-SampleProvider.o
-VirtualRepresentation.o
-NotificationManager
-SampleConsumer
-SampleProvider
-
+++ /dev/null
-##
-# NotificationManager build script
-##
-
-Import('env')
-
-lib_env = env.Clone()
-SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-notimgr_env = lib_env.Clone()
-
-######################################################################
-# Build flags
-######################################################################
-notimgr_env.AppendUnique(CPPPATH = ['../../NotificationManager/include'])
-notimgr_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson'])
-notimgr_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/connectivity/api'])
-notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
-notimgr_sample_env = notimgr_env.Clone()
-notimgr_env.AppendUnique(LIBS = [
- 'NotificationManager',
- 'rcs_client',
- 'rcs_server',
- 'rcs_common',
- 'oc',
- 'octbstack',
- 'oc_logger',
- 'connectivity_abstraction',
- 'coap',
- 'pthread'
- ])
-notimgr_sample_env.AppendUnique(LIBS = [
- 'oc',
- 'octbstack',
- 'oc_logger',
- 'connectivity_abstraction',
- 'coap',
- 'pthread'
- ])
-
-if env.get('SECURED') == '1':
- notimgr_env.AppendUnique(LIBS = ['tinydtls'])
- notimgr_sample_env.AppendUnique(LIBS = ['tinydtls'])
-if 'rt' in notimgr_env.get('LIBS'):
- notimgr_env.Append(LIBS = ['rt'])
-if 'rt' in notimgr_sample_env.get('LIBS'):
- notimgr_sample_env.Append(LIBS = ['rt'])
-
-####################################################################
-# Source files and Targets
-######################################################################
-sampleprovider = notimgr_sample_env.Program('sampleprovider', 'sampleProvider/SampleProvider.cpp')
-sampleconsumer = notimgr_sample_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp')
-
-notificationmanager = notimgr_env.Program('notificationmanager', 'notificationManager/main.cpp')
-
-#notimgr_sample_env.InstallTarget(sampleprovider, 'sampleprovider')
-#notimgr_sample_env.InstallTarget(sampleconsumer, 'sampleconsumer')
-#notimgr_env.InstallTarget(notificationmanager, 'notificationmanager')
\ No newline at end of file
+++ /dev/null
-NotificationManager
-SampleConsumer
-SampleProvider
-
+++ /dev/null
-LINK_DIRECTORIES(${LIB_INSTALL_DIR})
-
-SET(NOTI_BASE_DIR "${BASE_SRC_DIR}/notification-manager")
-
-INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic)
-INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/oic/stack)
-INCLUDE_DIRECTORIES(${INCLUDE_INSTALL_DIR}/boost)
-INCLUDE_DIRECTORIES(${NOTI_BASE_DIR}/NotificationManager/include)
-
-SET(NOTIFICATIONMANAGER "NotificationManager")
-SET(EX_NOTIPROVIDER "SampleProvider")
-SET(EX_NOTICONSUMER "SampleConsumer")
-
-SET(EXTRA_CXXFLAGS "-std=c++0x")
-SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${EXTRA_CXXFLAGS}")
-
-FILE(GLOB MANAGER_SRCS ${NOTI_BASE_DIR}/NotificationManager/src/*.cpp)
-
-ADD_EXECUTABLE(${NOTIFICATIONMANAGER} ${MANAGER_SRCS})
-TARGET_LINK_LIBRARIES(${NOTIFICATIONMANAGER} ${OCLIB} ${OCTBSTACK} pthread)
-INSTALL(TARGETS ${NOTIFICATIONMANAGER} DESTINATION ${BIN_INSTALL_DIR})
-
-ADD_EXECUTABLE(${EX_NOTIPROVIDER} ${NOTI_BASE_DIR}/SampleApp/linux/sampleProvider/SampleProvider.cpp)
-TARGET_LINK_LIBRARIES(${EX_NOTIPROVIDER} ${OCLIB} ${OCTBSTACK} pthread)
-INSTALL(TARGETS ${EX_NOTIPROVIDER} DESTINATION ${BIN_INSTALL_DIR})
-
-ADD_EXECUTABLE(${EX_NOTICONSUMER} ${NOTI_BASE_DIR}/SampleApp/linux/sampleConsumer/SampleConsumer.cpp)
-TARGET_LINK_LIBRARIES(${EX_NOTICONSUMER} ${OCLIB} ${OCTBSTACK} pthread)
-INSTALL(TARGETS ${EX_NOTICONSUMER} DESTINATION ${BIN_INSTALL_DIR})
-
######################################################################
if int(containerJavaSupport):
- try:
- print 'Java Home: ', os.environ['JAVA_HOME']
- print 'Java Lib: ', os.environ['JAVA_LIB']
- resource_container_env.Append(CPPDEFINES={'JAVA_SUPPORT':1})
- except KeyError:
- print '''
- *********************************** Error *************************************
- * Building resource container without Java support. JAVA_HOME or JAVA_LIB are not set properly
- * Please configure JAVA_HOME to point to your Java 7 JDK and
- * JAVA_LIB to your folder containing libjvm
- * Example: export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386
- * export JAVA_LIB=/usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/server
- *******************************************************************************
- '''
- resource_container_env.Append(CPPDEFINES={'JAVA_SUPPORT':0})
+ try:
+ print 'Java Home: ', os.environ['JAVA_HOME']
+ print 'Java Lib: ', os.environ['JAVA_LIB']
+ resource_container_env.Append(CPPDEFINES={'JAVA_SUPPORT':1})
+ except KeyError:
+ print '''
+ *********************************** Error *************************************
+ * Building resource container without Java support. JAVA_HOME or JAVA_LIB are not set properly
+ * Please configure JAVA_HOME to point to your Java 7 JDK and
+ * JAVA_LIB to your folder containing libjvm
+ * Example: export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386
+ * export JAVA_LIB=/usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/server
+ *******************************************************************************
+ '''
+ resource_container_env.Append(CPPDEFINES={'JAVA_SUPPORT':0})
resource_container_env.AppendUnique(
- CPPPATH = [
- env.get('SRC_DIR')+'/extlibs',
- '../../include',
- 'include',
- 'bundle-api/include',
- 'src'
- ])
+ CPPPATH = [
+ env.get('SRC_DIR')+'/extlibs',
+ '../resource-encapsulation/include',
+ 'include',
+ 'bundle-api/include',
+ 'src'
+ ])
if int(containerJavaSupport):
- try:
- resource_container_env.AppendUnique(
- CPPPATH = [
- os.environ['JAVA_HOME']+'/include',
- os.environ['JAVA_HOME']+'/include/linux'
- ])
- except KeyError:
- print ''
+ try:
+ resource_container_env.AppendUnique(
+ CPPPATH = [
+ os.environ['JAVA_HOME']+'/include',
+ os.environ['JAVA_HOME']+'/include/linux'
+ ])
+ except KeyError:
+ print ''
if target_os not in ['windows', 'winrt']:
- resource_container_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
- if target_os != 'android':
- resource_container_env.AppendUnique(CXXFLAGS = ['-pthread'])
+ resource_container_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+ if target_os != 'android':
+ resource_container_env.AppendUnique(CXXFLAGS = ['-pthread'])
if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
- resource_container_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+ resource_container_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'android':
- resource_container_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
- resource_container_env.PrependUnique(LIBS = ['gnustl_shared', 'log'])
+ resource_container_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ resource_container_env.PrependUnique(LIBS = ['gnustl_shared', 'log'])
try:
- resource_container_env.AppendUnique(LIBPATH = [os.environ['JAVA_LIB']])
+ resource_container_env.AppendUnique(LIBPATH = [os.environ['JAVA_LIB']])
except KeyError:
- print ''
+ print ''
resource_container_env.PrependUnique(LIBS = ['rcs_client', 'rcs_server', 'rcs_common', 'oc','octbstack', 'oc_logger', 'connectivity_abstraction'])
resource_container_env.AppendUnique(LIBS = ['dl', 'boost_system', 'boost_date_time', 'boost_thread'])
if int(containerJavaSupport):
- try:
- print 'Java Lib: ', os.environ['JAVA_LIB']
- resource_container_env.AppendUnique(LIBS = ['jvm'])
- except KeyError:
- print ''
+ try:
+ print 'Java Lib: ', os.environ['JAVA_LIB']
+ resource_container_env.AppendUnique(LIBS = ['jvm'])
+ except KeyError:
+ print ''
######################################################################
# Source files and Targets
######################################################################
res_container_src = ['src/BaseActivator.cpp','src/BundleActivator.cpp','src/RCSBundleInfo.cpp',
- 'src/BundleInfoInternal.cpp', 'src/BundleResource.cpp', 'src/Configuration.cpp', 'src/JavaBundleResource.cpp', 'src/ProtocolBridgeResource.cpp',
- 'src/ProtocolBridgeConnector.cpp', 'src/RCSResourceContainer.cpp', 'src/ResourceContainerBundleAPI.cpp', 'src/ResourceContainerImpl.cpp',
- 'src/SoftSensorResource.cpp', 'src/DiscoverResourceUnit.cpp', 'src/RemoteResourceUnit.cpp',
- ]
+ 'src/BundleInfoInternal.cpp', 'src/BundleResource.cpp', 'src/Configuration.cpp', 'src/JavaBundleResource.cpp', 'src/ProtocolBridgeResource.cpp',
+ 'src/ProtocolBridgeConnector.cpp', 'src/RCSResourceContainer.cpp', 'src/ResourceContainerBundleAPI.cpp', 'src/ResourceContainerImpl.cpp',
+ 'src/SoftSensorResource.cpp', 'src/DiscoverResourceUnit.cpp', 'src/RemoteResourceUnit.cpp',
+ ]
res_container_static = resource_container_env.StaticLibrary('rcs_container', res_container_src)
res_container_shared = resource_container_env.SharedLibrary('rcs_container', res_container_src)
resource_container_env.InstallTarget([res_container_static,res_container_shared], 'libResContainer')
+resource_container_env.UserInstallTargetHeader('include/RCSBundleInfo.h', 'service/resource-container', 'RCSBundleInfo.h')
+resource_container_env.UserInstallTargetHeader('include/RCSResourceContainer.h', 'service/resource-container', 'RCSResourceContainer.h')
+
######################################################################
# build discomfort index sensor sample bundle
######################################################################
if target_os in ['linux', 'tizen', 'android']:
- DI_sensor_bundle_env = resource_container_env.Clone()
- DI_sensor_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
+ DI_sensor_bundle_env = resource_container_env.Clone()
+ DI_sensor_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
- DI_SENSOR_BUNDLE_DIR = 'examples/DiscomfortIndexSensorBundle/'
- DI_sensor_bundle_env.AppendUnique(CPPPATH = [ DI_SENSOR_BUNDLE_DIR + 'include' ])
+ DI_SENSOR_BUNDLE_DIR = 'examples/DiscomfortIndexSensorBundle/'
+ DI_sensor_bundle_env.AppendUnique(CPPPATH = [ DI_SENSOR_BUNDLE_DIR + 'include' ])
- DI_sensor_bundle_env.PrependUnique(LIBS = ['rcs_container'])
+ DI_sensor_bundle_env.PrependUnique(LIBS = ['rcs_container'])
- DI_sensor_bundle_src = [ Glob(DI_SENSOR_BUNDLE_DIR + 'src/*.cpp')]
+ DI_sensor_bundle_src = [ Glob(DI_SENSOR_BUNDLE_DIR + 'src/*.cpp')]
- DISensorBundle = DI_sensor_bundle_env.SharedLibrary('DISensorBundle', DI_sensor_bundle_src)
- DI_sensor_bundle_env.InstallTarget(DISensorBundle, 'libDISensorBundle')
+ DISensorBundle = DI_sensor_bundle_env.SharedLibrary('DISensorBundle', DI_sensor_bundle_src)
+ DI_sensor_bundle_env.InstallTarget(DISensorBundle, 'libDISensorBundle')
- if target_os == 'linux' :
- SConscript(DI_SENSOR_BUNDLE_DIR + 'src/inputSensors/SConscript')
- Command("THSensorApp", DI_SENSOR_BUNDLE_DIR + "src/inputSensors/THSensorApp/THSensorApp", Copy("$TARGET", "$SOURCE"))
- Command("THSensorApp1", DI_SENSOR_BUNDLE_DIR + "src/inputSensors/THSensorApp1/THSensorApp1", Copy("$TARGET", "$SOURCE"))
+ if target_os == 'linux' :
+ SConscript(DI_SENSOR_BUNDLE_DIR + 'src/inputSensors/SConscript')
+ Command("THSensorApp", DI_SENSOR_BUNDLE_DIR + "src/inputSensors/THSensorApp/THSensorApp", Copy("$TARGET", "$SOURCE"))
+ Command("THSensorApp1", DI_SENSOR_BUNDLE_DIR + "src/inputSensors/THSensorApp1/THSensorApp1", Copy("$TARGET", "$SOURCE"))
######################################################################
# build BMI sensor sample bundle
######################################################################
if target_os in ['linux', 'tizen', 'android']:
- BMI_sensor_bundle_env = resource_container_env.Clone()
- BMI_sensor_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
+ BMI_sensor_bundle_env = resource_container_env.Clone()
+ BMI_sensor_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
- BMI_SENSOR_BUNDLE_DIR = 'examples/BMISensorBundle/'
- BMI_sensor_bundle_env.AppendUnique(CPPPATH = [ BMI_SENSOR_BUNDLE_DIR + 'include' ])
+ BMI_SENSOR_BUNDLE_DIR = 'examples/BMISensorBundle/'
+ BMI_sensor_bundle_env.AppendUnique(CPPPATH = [ BMI_SENSOR_BUNDLE_DIR + 'include' ])
- BMI_sensor_bundle_env.PrependUnique(LIBS = ['rcs_container'])
+ BMI_sensor_bundle_env.PrependUnique(LIBS = ['rcs_container'])
- BMI_sensor_bundle_src = [ Glob(BMI_SENSOR_BUNDLE_DIR + 'src/*.cpp')]
+ BMI_sensor_bundle_src = [ Glob(BMI_SENSOR_BUNDLE_DIR + 'src/*.cpp')]
- BMISensorBundle = BMI_sensor_bundle_env.SharedLibrary('BMISensorBundle', BMI_sensor_bundle_src)
- BMI_sensor_bundle_env.InstallTarget(BMISensorBundle, 'libBMISensorBundle')
+ BMISensorBundle = BMI_sensor_bundle_env.SharedLibrary('BMISensorBundle', BMI_sensor_bundle_src)
+ BMI_sensor_bundle_env.InstallTarget(BMISensorBundle, 'libBMISensorBundle')
- if target_os == 'linux' :
- SConscript(BMI_SENSOR_BUNDLE_DIR + 'src/inputSensors/SConscript')
- Command("HeightSensorApp", BMI_SENSOR_BUNDLE_DIR + "src/inputSensors/HeightSensorApp/HeightSensorApp", Copy("$TARGET", "$SOURCE"))
- Command("WeightSensorApp", BMI_SENSOR_BUNDLE_DIR + "src/inputSensors/WeightSensorApp/WeightSensorApp", Copy("$TARGET", "$SOURCE"))
+ if target_os == 'linux' :
+ SConscript(BMI_SENSOR_BUNDLE_DIR + 'src/inputSensors/SConscript')
+ Command("HeightSensorApp", BMI_SENSOR_BUNDLE_DIR + "src/inputSensors/HeightSensorApp/HeightSensorApp", Copy("$TARGET", "$SOURCE"))
+ Command("WeightSensorApp", BMI_SENSOR_BUNDLE_DIR + "src/inputSensors/WeightSensorApp/WeightSensorApp", Copy("$TARGET", "$SOURCE"))
######################################################################
# build hue sample bundle
conf2 = Configure(lib_env)
if not conf2.CheckLib('curl'):
- print '''X
+ print '''X
*********************************** Error *************************************
* Cannot build hue sample. Please install libcurl.
* Example (Ubuntu):
-* sudo apt-get install libcurl4-openssl-dev
-* sudo ldconfig
+* sudo apt-get install libcurl4-openssl-dev
+* sudo ldconfig
* Hint: check with pkg-config --libs libcurl and clear scons cache.
* Skipping hue sample build.
*******************************************************************************
- '''
+ '''
else:
- hue_resource_bundle_env = resource_container_env.Clone()
- hue_resource_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
+ hue_resource_bundle_env = resource_container_env.Clone()
+ hue_resource_bundle_env.AppendUnique(CCFLAGS = ['-fPIC'])
- HUE_RESOURCE_BUNDLE_DIR = 'examples/HueSampleBundle/'
- hue_resource_bundle_env.AppendUnique(CPPPATH = [
- HUE_RESOURCE_BUNDLE_DIR + 'include',
- 'include/'
- ])
+ HUE_RESOURCE_BUNDLE_DIR = 'examples/HueSampleBundle/'
+ hue_resource_bundle_env.AppendUnique(CPPPATH = [
+ HUE_RESOURCE_BUNDLE_DIR + 'include',
+ 'include/'
+ ])
- hue_resource_bundle_env.PrependUnique(LIBS = ['curl', 'rcs_container'])
+ hue_resource_bundle_env.PrependUnique(LIBS = ['curl', 'rcs_container'])
- hue_resource_bundle_src = [ Glob(HUE_RESOURCE_BUNDLE_DIR + 'src/*.cpp')]
+ hue_resource_bundle_src = [ Glob(HUE_RESOURCE_BUNDLE_DIR + 'src/*.cpp')]
- HueBundle = hue_resource_bundle_env.SharedLibrary('HueBundle', hue_resource_bundle_src)
- hue_resource_bundle_env.InstallTarget(HueBundle, 'libHueBundle')
+ HueBundle = hue_resource_bundle_env.SharedLibrary('HueBundle', hue_resource_bundle_src)
+ hue_resource_bundle_env.InstallTarget(HueBundle, 'libHueBundle')
lib_env = conf2.Finish()
######################################################################
# build resource container unit tests
######################################################################
if target_os == 'linux':
- SConscript('unittests/SConscript')
+ SConscript('unittests/SConscript')
######################################################################
# Build Container Sample
containersampleclient_src = ['examples/ContainerSampleClient.cpp']
containersampleclientapp = containersample_env.Program('ContainerSampleClient',containersampleclient_src)
Alias("containersampleclient", containersampleclientapp)
-env.AppendTarget('containersampleclient')
-
-
+env.AppendTarget('containersampleclient')
\ No newline at end of file
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.resourcecontainer.bundle.api;
+
+import java.util.List;
+import java.util.Vector;
+
+/**
+ * The BaseActivator implements the native interface to the resource container.
+ * It loads the resource container library and provies native methods that can
+ * be used to register and unregister resources.
+ */
+public class BaseActivator implements BundleActivator {
+ private String bundleId;
+ private Vector<BundleResource> bundleResources = new Vector<BundleResource>();
+
+ /**
+ * Creates an instance of the BaseActivator
+ *
+ * @param bundleId
+ * unique bundle identifier (e.g., oic.bundle.hue)
+ */
+ public BaseActivator(String bundleId) {
+ this.bundleId = bundleId;
+ }
+
+ static {
+ try {
+ System.loadLibrary("rcs_container");
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Bundle activation needs to be provided by the subclass.
+ */
+ public void activateBundle() {
+
+ }
+
+ /**
+ * Deactivates the bundle and unregisters its resources.
+ */
+ public void deactivateBundle() {
+ System.out.println("Deactivating bundle (Base Activator).");
+ for (BundleResource bundleResource : bundleResources) {
+ unregisterResource(bundleResource);
+ }
+ }
+
+ /**
+ * Registers a bundle resource at the resource container.
+ *
+ * @param resource
+ * bundle resource instance that should be made available as OIC
+ * resource
+ */
+ public void registerResource(BundleResource resource) {
+ bundleResources.add(resource);
+ registerJavaResource(resource, resource.getAttributeKeys(), bundleId,
+ resource.getURI(), resource.getResourceType(),
+ resource.getName());
+ }
+
+ /**
+ * Wrapper to retrieve the resource configuration of the bundle resources.
+ *
+ * @return List of resource configurations.
+ */
+ public List<ResourceConfig> getConfiguredBundleResources() {
+ int configuredResources = getNumberOfConfiguredResources(bundleId);
+
+ Vector<ResourceConfig> configs = new Vector<ResourceConfig>();
+
+ for (int i = 0; i < configuredResources; i++) {
+ String[] resourceParams = getConfiguredResourceParams(bundleId, i);
+ ResourceConfig config = new ResourceConfig(resourceParams);
+ configs.add(config);
+
+ }
+ return configs;
+ }
+
+ /**
+ * Unregisters a resource from the resource container.
+ */
+ public void unregisterResource(BundleResource resource) {
+ bundleResources.remove(resource);
+ unregisterJavaResource(resource, resource.getURI());
+ }
+
+ /**
+ * Native method that calls to the resource container.
+ *
+ * @param attributes
+ * String array of attribute names
+ * @param bundleId
+ * unique bundle identifier
+ * @param uri
+ * Uri that should be used to register the resource
+ */
+ private native void registerJavaResource(BundleResource resource,
+ String[] attributes, String bundleId, String uri,
+ String resourceType, String name);
+
+ /**
+ * Native method that calls to the resource container.
+ *
+ * @param resource
+ * @param uri
+ */
+ private native void unregisterJavaResource(BundleResource resource,
+ String uri);
+
+ /**
+ * Native method to retrieve the number of configured resources.
+ *
+ * @param bundleId
+ * unique bundle identifier
+ */
+ private native int getNumberOfConfiguredResources(String bundleId);
+
+ /**
+ * Native method to retrieve the configured resource parameters.
+ *
+ * @param bundleId
+ * unique bundle identifier
+ * @param resId
+ * get the resource params for a certain resource
+ */
+ private native String[] getConfiguredResourceParams(String bundleId,
+ int resId);
+
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+package org.iotivity.resourcecontainer.bundle.api;
+
+import java.util.HashMap;
+import java.util.Set;
+
+/**
+ * Basic BundleResource that should be used as a base class by a bundle
+ * resources. A concrete technology has to override the setAttribute and
+ * getAttribute method and map the according reads and writes to the technology
+ * specific messages.
+ */
+public abstract class BundleResource {
+ protected String m_name, m_uri, m_resourceType, m_address;
+
+ protected HashMap<String, String> m_attributes = new HashMap<String, String>();
+
+ /**
+ * Initialize the internal attribute structure.
+ */
+ protected abstract void initAttributes();
+
+ /**
+ * Set the attribute (map to a send command for the according protocol)
+ *
+ * @param key
+ * name of the attribute to be set
+ * @param value
+ * new value of the attribute
+ */
+ protected final void setAttribute(String key, String value) {
+ m_attributes.put(key, value);
+ }
+
+ /**
+ * Set the attribute (map to a send command for the according protocol)
+ *
+ * @param key
+ * name of the attribute to be set
+ * @param value
+ * new value of the attribute
+ */
+ public abstract void handleSetAttributeRequest(String key, String value);
+
+ /**
+ * Retrieve the attribute (only data)
+ *
+ * @param key
+ * name of the attribute to be read
+ * @return Value of the attribute
+ */
+ protected final String getAttribute(String key) {
+ return m_attributes.get(key);
+ }
+
+ /**
+ * Retrieve the attribute (map to read command)
+ *
+ * @param key
+ * name of the attribute to be set
+ * @param value
+ * new value of the attribute
+ */
+ public abstract String handleGetAttributeRequest(String key);
+
+ /**
+ * Attribute keys provided through by the bundle resource.
+ *
+ * @return Name of attribute keys as string array
+ */
+ public String[] getAttributeKeys() {
+ Set<String> keys = m_attributes.keySet();
+ return keys.toArray(new String[keys.size()]);
+ }
+
+ /**
+ * Setter for the uri property
+ *
+ * @param uri
+ * URI of the resource
+ */
+ public void setURI(String uri) {
+ this.m_uri = uri;
+ }
+
+ /**
+ * Returns the URI of the resource
+ *
+ * @return Resource URI
+ */
+ public String getURI() {
+ return m_uri;
+ }
+
+ /**
+ * Sets the resource type property
+ *
+ * @param resourceType
+ * OIC resource type
+ */
+ public void setResourceType(String resourceType) {
+ this.m_resourceType = resourceType;
+ }
+
+ /**
+ * Getter for the resource type
+ *
+ * @return OIC resource type
+ */
+ public String getResourceType() {
+ return m_resourceType;
+ }
+
+ /**
+ * Sets the technology specific address information (e.g., ZigBee short or
+ * long identifier)
+ *
+ * @param address
+ * Resource address
+ */
+ public void setAddress(String address) {
+ this.m_address = address;
+ }
+
+ /**
+ * Returns the technology specific address information
+ *
+ * @return Resource address
+ */
+ public String getAddress() {
+ return m_address;
+ }
+
+ /**
+ * Sets the name property of the resource
+ *
+ * @param name
+ * Resource name
+ */
+ public void setName(String name) {
+ this.m_name = name;
+ }
+
+ /**
+ * Returns the name property of the resource
+ *
+ * @return Resource name
+ */
+ public String getName() {
+ return m_name;
+ }
+
+}
getchar();
bundleParams["libraryPath"] = ".";
std::string activator = "org.iotivity.bundle.hue.HueBundleActivator";
- container->addBundle("oic.bundle.hueJavaSample", "/hueJava",
- "../../../../../../../../service/resource-encapsulation/src/resourceContainer/" \
- "examples/HueJavaSampleBundle/hue/target/hue-0.1-jar-with-dependencies.jar",
- activator,
- bundleParams);
+ container->addBundle("oic.bundle.hueJavaSample2", "/hueJava",
+ "../../../../../../service/resource-container/" \
+ "examples/HueJavaSampleBundle/hue/target/hue-0.1-jar-with-dependencies.jar",
+ activator,
+ bundleParams);
bundles = container->listBundles();
cout << "\t>>> bundle list size : " << bundles.size() << endl;
cout << "\nPress enter to start java bundle " << endl;
getchar();
- container->startBundle("oic.bundle.hueJavaSample");
+ container->startBundle("oic.bundle.hueJavaSample2");
cout << "Press enter to stop java Bundle " << endl;
getchar();
- container->stopBundle("oic.bundle.hueJavaSample");
+ container->stopBundle("oic.bundle.hueJavaSample2");
cout << "Press enter to test remove java Bundle " << endl;
getchar();
- container->removeBundle("oic.bundle.hueJavaSample");
+ container->removeBundle("oic.bundle.hueJavaSample2");
bundles = container->listBundles();
cout << "\t>>> bundle list size : " << bundles.size() << endl;
--- /dev/null
+package org.iotivity.bundle.hue;
+
+import java.util.List;
+
+import org.iotivity.resourcecontainer.bundle.api.BaseActivator;
+import org.iotivity.resourcecontainer.bundle.api.ResourceConfig;
+
+public class HueBundleActivator extends BaseActivator {
+ private HueConnector connector;
+
+ public HueBundleActivator(String bundleId) {
+ super(bundleId);
+ }
+
+ public void activateBundle() {
+ super.activateBundle();
+ connector = new HueConnector();
+ List<ResourceConfig> resourceConfig = getConfiguredBundleResources();
+
+ for (ResourceConfig config : resourceConfig) {
+
+ HueLightResource hueLightResource = new HueLightResource(connector,
+ config.getName(), config.getURI(),
+ config.getResourceType(), config.getAddress());
+
+ System.out.println("Registration of Hue light resource " + config);
+ registerResource(hueLightResource);
+ }
+ }
+
+ public void deactivateBundle() {
+ System.out.println("Deactivate bundle called.");
+ super.deactivateBundle();
+ }
+
+ // test call
+ public static void main(String[] args) {
+ HueBundleActivator activator = new HueBundleActivator("oic.hue.bundle");
+ }
+}
--- /dev/null
+package org.iotivity.bundle.hue;
+
+import java.util.HashMap;
+
+import org.iotivity.resourcecontainer.bundle.api.BundleResource;
+
+/**
+ * This class maps a Philips Hue light to OIC light resource
+ *
+ * @author iotivity
+ */
+public class HueLightResource extends BundleResource {
+ private HueConnector m_hueConnector;
+
+ public HueLightResource() {
+ initAttributes();
+ m_resourceType = "oic.r.light.control";
+
+ }
+
+ public HueLightResource(HueConnector hueConnector, String name, String uri,
+ String resourceType, String address) {
+ this();
+ this.m_hueConnector = hueConnector;
+ m_name = name;
+ m_uri = uri;
+ m_resourceType = resourceType;
+ m_address = address;
+ }
+
+ protected void initAttributes() {
+ m_attributes.put("on-off", "true");
+ m_attributes.put("color", "0");
+ m_attributes.put("dim", "0");
+ }
+
+ public void handleSetAttributeRequest(String key, String value) {
+ System.out.println("Set attribute called - key: " + key + ", value: "
+ + value + " transmitting now.");
+
+ if ("on-off".equals(value)) {
+ m_hueConnector.transmit(m_address + "/state", "{\"on\":" + value
+ + "}");
+ }
+
+ if ("dim".equals(value)) {
+ m_hueConnector.transmit(m_address + "/state", "{\"bri\":" + value
+ + "}");
+ }
+
+ if ("color".equals(value)) {
+ m_hueConnector.transmit(m_address + "/state", "{\"hue\":" + value
+ + "}");
+ }
+ this.setAttribute(key, value);
+ }
+
+ public String handleGetAttributeRequest(String key) {
+ // map key to hue address
+ // read from Hue gateway, parse resource representation and return
+ // attribute
+ // m_hueConnector.read(m_address);
+ return this.getAttribute(key);
+ }
+
+ @Override
+ public String toString() {
+ return "HueLightResource [m_hueConnector=" + m_hueConnector
+ + ", m_name=" + m_name + ", m_uri=" + m_uri
+ + ", m_resourceType=" + m_resourceType + ", m_address="
+ + m_address + ", m_attributes=" + m_attributes + "]";
+ }
+
+}
static int lightCount = 1;
BundleResource::Ptr hueLight = std::make_shared< HueLight >(m_connector, resourceInfo.address);
resourceInfo.uri = "/hue/light/" + std::to_string(lightCount++);
- std::cout << "Registering resource " << resourceInfo.uri << std::endl;
hueLight->m_bundleId = m_bundleId;
hueLight->m_uri = resourceInfo.uri;
hueLight->m_resourceType = resourceInfo.resourceType;
</resourceInfo>
</resources>
</bundle>
+
<!--
<bundle>
<id>oic.bundle.hueJavaSample</id>
- <path>../../../../../../../../service/resource-encapsulation/src/resourceContainer/examples/HueJavaSampleBundle/hue/target/hue-0.1-jar-with-dependencies.jar</path>
+ <path>../../../../../../service/resource-container/examples/HueJavaSampleBundle/hue/target/hue-0.1-jar-with-dependencies.jar</path>
<libraryPath>.</libraryPath>
<uri>/hueJava</uri>
<activator>org.iotivity.bundle.hue.HueBundleActivator</activator>
<resources>
<resourceInfo>
<name>light</name>
- <uri>light/1</uri>
+ <resourceUri>/hueJava/light/1</resourceUri>
<resourceType>oic.r.light</resourceType>
<address>http://192.168.0.2/api/newdeveloper/lights/1</address>
</resourceInfo>
</resources>
</bundle>
-->
+
</container>
\ No newline at end of file
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+ <storageModule moduleId="org.eclipse.cdt.core.settings">
+ <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+ <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+ <externalSettings/>
+ <extensions>
+ <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+ <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ </extensions>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <configuration artifactName="containerclient" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug,org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+ <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
+ <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+ <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+ <builder arguments="--eval="SHELL=cmd" -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+ <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+ <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+ <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-mthumb"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ <listOptionValue builtIn="false" value=""C:\boost_1_56_0""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\resourceBroker\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\resourceCache\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\common\utils\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\common\expiryTimer\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\common\expiryTimer\src""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\src\common\primitiveResource\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\resource-encapsulation\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\c_common""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\stack\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\logger\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\occoap\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocrandom\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocsocket\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\oc_logger\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\extlibs\timer""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
+ <listOptionValue builtIn="false" value="_DEBUG"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+ <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+ </tool>
+ <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+ <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-mthumb"/>
+ </option>
+ <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
+ <listOptionValue builtIn="false" value="_DEBUG"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
+ <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+ <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+ </tool>
+ <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+ <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+ <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="-pie -lpthread "/>
+ <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+ <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
+ <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+ </option>
+ <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
+ </option>
+ <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+ <listOptionValue builtIn="false" value="oc"/>
+ <listOptionValue builtIn="false" value="octbstack"/>
+ <listOptionValue builtIn="false" value="oc_logger"/>
+ <listOptionValue builtIn="false" value="oc_logger_core"/>
+ <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+ <listOptionValue builtIn="false" value="uuid"/>
+ <listOptionValue builtIn="false" value="boost_date_time"/>
+ <listOptionValue builtIn="false" value="boost_system"/>
+ <listOptionValue builtIn="false" value="boost_thread"/>
+ <listOptionValue builtIn="false" value="rcs_client"/>
+ <listOptionValue builtIn="false" value="rcs_common"/>
+ <listOptionValue builtIn="false" value="rcs_container"/>
+ <listOptionValue builtIn="false" value="rcs_server"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+ <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+ <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+ </inputType>
+ </tool>
+ <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+ <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+ </tool>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+ <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+ <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+ <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+ <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+ </toolChain>
+ </folderInfo>
+ <sourceEntries>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+ </sourceEntries>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+ </cconfiguration>
+ <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+ <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
+ <externalSettings/>
+ <extensions>
+ <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+ <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ </extensions>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release,org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+ <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
+ <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+ <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+ <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+ <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+ <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+ <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+ <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ </option>
+ <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+ </tool>
+ <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+ <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+ <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ </option>
+ <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+ </tool>
+ <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+ <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+ <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="-pie -lpthread "/>
+ <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+ <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
+ <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+ </option>
+ <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+ <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+ <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+ </inputType>
+ </tool>
+ <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+ <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+ </tool>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+ <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+ <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+ <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+ <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+ </toolChain>
+ </folderInfo>
+ <sourceEntries>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+ </sourceEntries>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+ </cconfiguration>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+ </storageModule>
+ <storageModule moduleId="scannerConfiguration">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ </scannerConfigBuildInfo>
+ <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ </scannerConfigBuildInfo>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+ <storageModule moduleId="refreshScope" versionNumber="2">
+ <configuration configurationName="Release">
+ <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+ </configuration>
+ <configuration configurationName="Debug">
+ <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+</cproject>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>ContainerClientApp</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+ <triggers>full,incremental,</triggers>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.tizen.nativecore.apichecker.core.builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.cdt.core.cnature</nature>
+ <nature>org.eclipse.cdt.core.ccnature</nature>
+ <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+ <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+ <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+ </natures>
+ <filteredResources>
+ <filter>
+ <id>0</id>
+ <name></name>
+ <type>26</type>
+ <matcher>
+ <id>org.eclipse.ui.ide.multiFilter</id>
+ <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+ </matcher>
+ </filter>
+ </filteredResources>
+</projectDescription>
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+group
+{
+ name: "container_layout";
+ parts
+ {
+ part
+ {
+ name: "listnew";
+ type: SWALLOW;
+ scale: 1;
+ description
+ {
+ rel1.relative: 0.01 0.1;
+ rel2.relative: 0.99 0.7;
+ }
+ }
+ part
+ {
+ name: "log_bg";
+ type: RECT;
+ scale: 1;
+ description
+ {
+ state: "default" 0.0;
+ rel1.relative: 0.01 0.71;
+ rel2.relative: 0.98 1.0;
+ color: 220 220 220 255;
+ }
+ }
+ part
+ {
+ name: "log";
+ type: SWALLOW;
+ scale: 1;
+ description
+ {
+ rel1.to: "log_bg";
+ rel2.to: "log_bg";
+ }
+ }
+ }
+}
*
******************************************************************/
-#ifndef RESERVERMAIN_H__
-#define RESERVERMAIN_H__
+#ifndef CLIENTMAIN_H__
+#define CLIENTMAIN_H__
#include <app.h>
#include <Elementary.h>
#ifdef LOG_TAG
#undef LOG_TAG
#endif
-#define LOG_TAG "reservermain"
+#define LOG_TAG "clientmain"
#if !defined(PACKAGE)
-#define PACKAGE "org.tizen.resampleserver"
+#define PACKAGE "org.tizen.containerclient"
#endif
-#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.resampleserver/res/ui_controls.edj"
+#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.containerclient/res/ui_controls.edj"
-void start_server(void *data, Evas_Object *obj, void *event_info);
+void containerCreateUI(void *data, Evas_Object *obj, void *event_info);
-void start_server_cb(void *data, Evas_Object *obj, void *event_info);
-
-#endif // RESERVERMAIN_H__
\ No newline at end of file
+#endif // CLIENTMAIN_H__
*
******************************************************************/
-#include "reclientmain.h"
+#include "clientmain.h"
#include "RCSRemoteResourceObject.h"
#include <efl_extension.h>
#include <dlog.h>
-#ifndef RECONTAINER_H__
-#define RECONTAINER_H__
-
-# define LOG_TAG "recontainerclient"
+#ifndef CONTAINERCLIENT_H__
+#define CONTAINERCLIENT_H__
using namespace OIC::Service;
void onContainerDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource);
-static void find_resource_cb(void *data, Evas_Object *obj, void *event_info);
-
static void findLight(void *data, Evas_Object *obj, void *event_info);
static void findSoftsensor(void *data, Evas_Object *obj, void *event_info);
-#endif // RECONTAINER_H__
\ No newline at end of file
+static void cancelDiscoverResource(void *data, Evas_Object *obj, void *event_info);
+
+#endif // CONTAINERCLIENT_H__
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+collections
+{
+ base_scale: 1.8;
+ #include "../edc_resource/container_control.edc"
+}
\ No newline at end of file
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "clientmain.h"
+#include <tizen.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+typedef struct appdata
+{
+ Evas_Object *win;
+ Evas_Object *conform;
+ Evas_Object *layout;
+ Evas_Object *nf;
+ Evas_Object *findButton;
+ Evas_Object *logtext;
+ Evas_Object *listview;
+} appdata_s;
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+ ui_app_exit();
+}
+
+static void
+list_selected_cb(void *data, Evas_Object *obj, void *event_info)
+{
+ Elm_Object_Item *it = (Elm_Object_Item *)event_info;
+ elm_list_item_selected_set(it, EINA_FALSE);
+}
+
+static Eina_Bool
+naviframe_pop_cb(void *data, Elm_Object_Item *it)
+{
+ ui_app_exit();
+ return EINA_FALSE;
+}
+
+static void
+create_list_view(appdata_s *ad)
+{
+ Evas_Object *list;
+ Evas_Object *btn;
+ Evas_Object *nf = ad->nf;
+ Elm_Object_Item *nf_it;
+
+ // List
+ list = elm_list_add(nf);
+ elm_list_mode_set(list, ELM_LIST_COMPRESS);
+ evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
+
+ // Main Menu Items Here
+
+ elm_list_item_append(list, "Start Container Client", NULL, NULL, containerCreateUI, nf);
+
+ elm_list_go(list);
+
+ // This button is set for devices which doesn't have H/W back key.
+ btn = elm_button_add(nf);
+ elm_object_style_set(btn, "naviframe/end_btn/default");
+ nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
+ elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
+}
+
+
+static void
+create_base_gui(appdata_s *ad)
+{
+ // Window
+ ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+ elm_win_conformant_set(ad->win, EINA_TRUE);
+ elm_win_autodel_set(ad->win, EINA_TRUE);
+
+ if (elm_win_wm_rotation_supported_get(ad->win))
+ {
+ int rots[4] = { 0, 90, 180, 270 };
+ elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+ }
+
+ evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+
+ // Conformant
+ ad->conform = elm_conformant_add(ad->win);
+ evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+ elm_win_resize_object_add(ad->win, ad->conform);
+ evas_object_show(ad->conform);
+
+ // Base Layout
+ ad->layout = elm_layout_add(ad->conform);
+ evas_object_size_hint_weight_set(ad->layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+ elm_layout_theme_set(ad->layout, "layout", "application", "default");
+ evas_object_show(ad->layout);
+
+ elm_object_content_set(ad->conform, ad->layout);
+
+ // Naviframe
+ ad->nf = elm_naviframe_add(ad->layout);
+ create_list_view(ad);
+ elm_object_part_content_set(ad->layout, "elm.swallow.content", ad->nf);
+ eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_BACK, eext_naviframe_back_cb, NULL);
+ eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_MORE, eext_naviframe_more_cb, NULL);
+
+ // Show window after base gui is set up
+ evas_object_show(ad->win);
+}
+
+// Configures the OCPlatform
+static void
+configure_platform()
+{
+ try
+ {
+ PlatformConfig config
+ { OC::ServiceType::InProc, ModeType::Client, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+ OCPlatform::Configure(config);
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration done!!!!");
+ }
+ catch (OCException &e)
+ {
+ dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+ }
+}
+
+static bool
+app_create(void *data)
+{
+ /* Hook to take necessary actions before main event loop starts
+ Initialize UI resources and application's data
+ If this function returns true, the main loop of application starts
+ If this function returns false, the application is terminated */
+ appdata_s *ad = (appdata_s *)data;
+
+ elm_app_base_scale_set(1.8);
+
+ create_base_gui(ad);
+
+ configure_platform();
+
+ return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+ // Handle the launch request.
+}
+
+static void
+app_pause(void *data)
+{
+ // Take necessary actions when application becomes invisible.
+}
+
+static void
+app_resume(void *data)
+{
+ // Take necessary actions when application becomes visible.
+}
+
+static void
+app_terminate(void *data)
+{
+ // Release all resources.
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_LANGUAGE_CHANGED
+ char *locale = NULL;
+ system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+ elm_language_set(locale);
+ free(locale);
+ return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_DEVICE_ORIENTATION_CHANGED
+ return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_REGION_FORMAT_CHANGED
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_LOW_BATTERY
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_LOW_MEMORY
+}
+
+int
+main(int argc, char *argv[])
+{
+ appdata_s ad = {0,};
+ int ret = 0;
+
+ ui_app_lifecycle_callback_s event_callback = {0,};
+ app_event_handler_h handlers[5] = {NULL, };
+
+ event_callback.create = app_create;
+ event_callback.terminate = app_terminate;
+ event_callback.pause = app_pause;
+ event_callback.resume = app_resume;
+ event_callback.app_control = app_control;
+
+ ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY,
+ ui_app_low_battery, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY,
+ ui_app_low_memory, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED],
+ APP_EVENT_DEVICE_ORIENTATION_CHANGED,
+ ui_app_orient_changed, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED],
+ APP_EVENT_LANGUAGE_CHANGED,
+ ui_app_lang_changed, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED],
+ APP_EVENT_REGION_FORMAT_CHANGED,
+ ui_app_region_changed, &ad);
+ ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+ ret = ui_app_main(argc, argv, &event_callback, &ad);
+ if (APP_ERROR_NONE != ret)
+ {
+ dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+ }
+ return ret;
+}
*
******************************************************************/
-#include "recontainerclient.h"
+#include "containerclient.h"
-#include "reclientmain.h"
+#include "clientmain.h"
#include "RCSDiscoveryManager.h"
#include "RCSResourceAttributes.h"
#include "RCSAddress.h"
#include <string>
-#include "mutex"
-#include "condition_variable"
using namespace std;
using namespace OC;
using namespace OIC::Service;
std::shared_ptr<RCSRemoteResourceObject> g_containerResource;
+std::vector<RCSRemoteResourceObject::Ptr> resourceList;
+std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
-const std::string resourceTypeLight = "?rt=oic.light.control";
-const std::string resourceTypeSoftsensor = "?rt=oic.softsensor";
-const std::string targetLightUri = OC_RSRVD_WELL_KNOWN_URI + resourceTypeLight;
-const std::string targetSoftsensorUri = OC_RSRVD_WELL_KNOWN_URI + resourceTypeSoftsensor;
-
-std::mutex g_containerMtx;
-std::condition_variable g_containerCond;
+const std::string resourceTypeLight = "oic.r.light";
+const std::string resourceTypeSoftsensor = "oic.r.sensor";
static Evas_Object *log_entry = NULL;
static Evas_Object *listnew = NULL;
static void onDestroy()
{
- g_containerResource = NULL;
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Destroy sequence called");
+ resourceList.clear();
+ g_containerResource = nullptr;
}
void onContainerDiscovered(std::shared_ptr<RCSRemoteResourceObject> foundResource)
std::string resourceURI = foundResource->getUri();
std::string hostAddress = foundResource->getAddress();
- dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI : %s", resourceURI.c_str());
- dlog_print(DLOG_INFO, LOG_TAG, "#### Resource Host : %S", hostAddress.c_str());
-
+ int resourceSize = resourceList.size() + 1;
string logMessage = "Resource Found <br>";
logMessage = logMessage + "URI: " + resourceURI + "<br>";
logMessage = logMessage + "Host:" + hostAddress + "<br>";
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateContainerLog,
&logMessage);
+ resourceList.push_back(foundResource);
+
g_containerResource = foundResource;
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showContainerAPIs, NULL);
- g_containerCond.notify_all();
}
void *showContainerAPIs(void *data)
int count = eina_list_count(eina_list);
if (!count)
{
- elm_list_item_append(listnew, "1. Find Light resource", NULL, NULL,
+ elm_list_item_append(listnew, "1. Start Light resource Discovery", NULL, NULL,
findLight, NULL);
- elm_list_item_append(listnew, "1. Find Softsensor resource", NULL, NULL,
+ elm_list_item_append(listnew, "2. Start Softsensor resource Discovery", NULL, NULL,
findSoftsensor, NULL);
+ elm_list_item_append(listnew, "3.Stop Discovery", NULL, NULL,
+ cancelDiscoverResource, NULL);
+
elm_list_go(listnew);
}
return NULL;
static void findLight(void *data, Evas_Object *obj, void *event_info)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Wait 2 seconds until discovered");
-
- RCSDiscoveryManager::getInstance()->discoverResource(RCSAddress::multicast(), targetLightUri,
- &onContainerDiscovered);
-
- std::unique_lock<std::mutex> lck(g_containerMtx);
- g_containerCond.wait_for(lck, std::chrono::seconds(2));
-
- dlog_print(DLOG_INFO, LOG_TAG, "#### Light Discovery over");
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Light discovery started");
+
+ while (!discoveryTask)
+ {
+ try
+ {
+ discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+ RCSAddress::multicast(), resourceTypeLight, &onContainerDiscovered);
+ }
+ catch (const RCSPlatformException &e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+ }
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Light Discovery over");
}
static void findSoftsensor(void *data, Evas_Object *obj, void *event_info)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Wait 2 seconds until discovered");
+ dlog_print(DLOG_INFO, LOG_TAG, "#### SoftSensor discovery started");
+
+ while (!discoveryTask)
+ {
+ try
+ {
+ discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+ RCSAddress::multicast(), resourceTypeSoftsensor, &onContainerDiscovered);
+ }
+ catch (const RCSPlatformException &e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+ }
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### SoftSensor Discovery over");
+}
+
+static void cancelDiscoverResource(void *data, Evas_Object *obj, void *event_info)
+{
+ dlog_print(DLOG_INFO, LOG_TAG, "#### cancelDiscoverResource entry");
+ string logMessage = "";
+
+ if (!discoveryTask)
+ {
+ logMessage += "There is no discovery request <br>";
+ }
+ else
+ {
+ discoveryTask->cancel();
- RCSDiscoveryManager::getInstance()->discoverResource(RCSAddress::multicast(), targetSoftsensorUri,
- &onContainerDiscovered);
+ logMessage += "Discovery canceled <br>";
- std::unique_lock<std::mutex> lck(g_containerMtx);
- g_containerCond.wait_for(lck, std::chrono::seconds(2));
+ int resourceSize = resourceList.size();
+ if (!resourceSize)
+ {
+ logMessage += "No Resource Discovered <br>";
+ }
+ else
+ {
+ logMessage += std::to_string(resourceSize) + " : Resource Discovered <br>";
+ }
- dlog_print(DLOG_INFO, LOG_TAG, "#### Softsensor Discovery over");
+ }
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateContainerLog,
+ &logMessage);
}
static Eina_Bool
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.tizen.containerclient" version="1.0.0">
+ <profile name="mobile"/>
+ <ui-application appid="org.tizen.containerclient" exec="containerclient" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+ <label>containerclient</label>
+ <icon>containerclient.png</icon>
+ </ui-application>
+ <privileges>
+ <privilege>http://tizen.org/privilege/network.get</privilege>
+ <privilege>http://tizen.org/privilege/internet</privilege>
+ </privileges>
+ <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
+ <storageModule moduleId="org.eclipse.cdt.core.settings">
+ <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+ <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+ <externalSettings/>
+ <extensions>
+ <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+ <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ </extensions>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <configuration artifactName="containerserver" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug,org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+ <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
+ <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+ <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+ <builder arguments="--eval="SHELL=cmd" -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+ <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+ <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+ <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-mthumb"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ <listOptionValue builtIn="false" value=""C:\boost_1_56_0""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\resourceBroker\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\resourceCache\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\utils\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\expiryTimer\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\expiryTimer\src""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\primitiveResource\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\c_common""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\stack\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\logger\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\occoap\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocrandom\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocsocket\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\oc_logger\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\extlibs\timer""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
+ <listOptionValue builtIn="false" value="_DEBUG"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+ <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+ </tool>
+ <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+ <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-mthumb"/>
+ </option>
+ <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
+ <listOptionValue builtIn="false" value="_DEBUG"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
+ <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+ <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+ </tool>
+ <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+ <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+ <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="-pie -lpthread "/>
+ <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+ <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
+ <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+ </option>
+ <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
+ </option>
+ <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+ <listOptionValue builtIn="false" value="oc"/>
+ <listOptionValue builtIn="false" value="octbstack"/>
+ <listOptionValue builtIn="false" value="oc_logger"/>
+ <listOptionValue builtIn="false" value="oc_logger_core"/>
+ <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+ <listOptionValue builtIn="false" value="uuid"/>
+ <listOptionValue builtIn="false" value="boost_date_time"/>
+ <listOptionValue builtIn="false" value="boost_system"/>
+ <listOptionValue builtIn="false" value="boost_thread"/>
+ <listOptionValue builtIn="false" value="HueBundle"/>
+ <listOptionValue builtIn="false" value="BMISensorBundle"/>
+ <listOptionValue builtIn="false" value="DISensorBundle"/>
+ <listOptionValue builtIn="false" value="rcs_client"/>
+ <listOptionValue builtIn="false" value="rcs_common"/>
+ <listOptionValue builtIn="false" value="rcs_container"/>
+ <listOptionValue builtIn="false" value="rcs_server"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+ <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+ <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+ </inputType>
+ </tool>
+ <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+ <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+ </tool>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+ <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+ <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+ <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+ <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+ </toolChain>
+ </folderInfo>
+ <sourceEntries>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+ </sourceEntries>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+ </cconfiguration>
+ <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+ <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
+ <externalSettings/>
+ <extensions>
+ <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+ <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ </extensions>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release,org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+ <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
+ <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+ <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+ <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+ <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+ <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+ <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+ <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ </option>
+ <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+ </tool>
+ <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+ <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+ <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ </option>
+ <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+ </tool>
+ <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+ <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+ <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="-pie -lpthread "/>
+ <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+ <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
+ <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+ </option>
+ <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+ <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+ <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+ </inputType>
+ </tool>
+ <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+ <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+ </tool>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+ <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+ <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+ <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+ <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+ </toolChain>
+ </folderInfo>
+ <sourceEntries>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+ </sourceEntries>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+ </cconfiguration>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+ </storageModule>
+ <storageModule moduleId="scannerConfiguration">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ </scannerConfigBuildInfo>
+ <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ </scannerConfigBuildInfo>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+ <storageModule moduleId="refreshScope" versionNumber="2">
+ <configuration configurationName="Debug">
+ <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+ </configuration>
+ <configuration configurationName="Release">
+ <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+</cproject>
--- /dev/null
+{
+ global: main;
+ local: *;
+};
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<projectDescription>
+ <name>ContainerServerApp</name>
+ <comment></comment>
+ <projects>
+ </projects>
+ <buildSpec>
+ <buildCommand>
+ <name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
+ <triggers>full,incremental,</triggers>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ <buildCommand>
+ <name>org.tizen.nativecore.apichecker.core.builder</name>
+ <arguments>
+ </arguments>
+ </buildCommand>
+ </buildSpec>
+ <natures>
+ <nature>org.eclipse.cdt.core.cnature</nature>
+ <nature>org.eclipse.cdt.core.ccnature</nature>
+ <nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
+ <nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
+ <nature>org.tizen.nativecore.apichecker.core.tizenCppNature</nature>
+ </natures>
+ <filteredResources>
+ <filter>
+ <id>0</id>
+ <name></name>
+ <type>26</type>
+ <matcher>
+ <id>org.eclipse.ui.ide.multiFilter</id>
+ <arguments>1.0-projectRelativePath-matches-false-false-*/.tpk</arguments>
+ </matcher>
+ </filter>
+ </filteredResources>
+</projectDescription>
* limitations under the License.
*
******************************************************************/
-
+
group
{
name: "container_layout";
{
part
{
- name: "listnew";
+ name: "start_button";
type: SWALLOW;
scale: 1;
description
{
- rel1.relative: 0.01 0.1;
- rel2.relative: 0.99 0.7;
+ rel1.relative: 0.01 0.01;
+ rel2.relative: 0.5 0.09;
}
}
part
{
- name: "log_bg";
- type: RECT;
- scale: 1;
- description
- {
- state: "default" 0.0;
- rel1.relative: 0.01 0.71;
- rel2.relative: 0.98 1.0;
- color: 220 220 220 255;
- }
- }
- part
- {
- name: "log";
+ name: "stop_button";
type: SWALLOW;
scale: 1;
description
{
- rel1.to: "log_bg";
- rel2.to: "log_bg";
+ rel1.relative: 0.51 0.01;
+ rel2.relative: 1.0 0.09;
}
}
- }
-}
-
-group
-{
- name: "popup_datetime_text";
- parts
- {
part
{
- name: "pad_l";
- type: SPACER;
+ name: "listnew";
+ type: SWALLOW;
scale: 1;
description
{
- state: "default" 0.0;
- min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
- fixed: 1 0;
- rel1.relative: 0.0 0.0;
- rel2.relative: 0.0 1.0;
- align: 0.0 0.0;
+ rel1.relative: 0.01 0.1;
+ rel2.relative: 0.99 0.7;
}
}
part
{
- name: "pad_r";
- type: SPACER;
+ name: "log_bg";
+ type: RECT;
scale: 1;
description
{
state: "default" 0.0;
- min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
- fixed: 1 0;
- rel1.relative: 1.0 0.0;
- rel2.relative: 1.0 1.0;
- align: 1.0 0.0;
+ rel1.relative: 0.01 0.71;
+ rel2.relative: 0.98 1.0;
+ color: 220 220 220 255;
}
}
part
{
- name: "elm.swallow.content";
+ name: "log";
type: SWALLOW;
scale: 1;
description
{
- state: "default" 0.0;
- min: 0 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
- max: -1 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
- align: 0.5 0.5;
- rel1
- {
- relative: 1.0 0.0;
- to_x: "pad_l";
- }
- rel2
- {
- relative: 0.0 1.0;
- to_x: "pad_r";
- }
+ rel1.to: "log_bg";
+ rel2.to: "log_bg";
}
}
}
-}
+}
\ No newline at end of file
*
******************************************************************/
-#include "remain.h"
+#include "rcmain.h"
-#ifndef RECONTAINER_H__
-#define RECONTAINER_H__
-
-# define LOG_TAG "recontainer"
+#ifndef CONTAINER_H__
+#define CONTAINER_H__
using namespace std;
static void stopContainer(void *data, Evas_Object *obj, void *event_info);
-#endif // RECONTAINER_H__
+#endif // CONTAINER_H__
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 RCMAIN_H__
+#define RCMAIN_H__
+
+#include <app.h>
+#include <Elementary.h>
+#include <system_settings.h>
+#include <efl_extension.h>
+#include <dlog.h>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+using namespace OC;
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#endif
+#define LOG_TAG "containerserver"
+
+#if !defined(PACKAGE)
+#define PACKAGE "org.tizen.containerserver"
+#endif
+
+#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.containerserver/res/ui_controls.edj"
+
+void containerCreateUI(void *data, Evas_Object *obj, void *event_info);
+
+#endif // RCMAIN_H__
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<container>
+ <bundle>
+ <id>oic.bundle.hueSample</id>
+ <path>/opt/usr/apps/org.tizen.containerserver/lib/libHueBundle.so</path>
+ <activator>huesample</activator>
+ <version>1.0.0</version>
+ <resources>
+ <resourceInfo>
+ <name>light</name>
+ <resourceType>oic.r.control</resourceType>
+ <address>http://192.168.0.2/api/newdeveloper/lights/1</address>
+ </resourceInfo>
+ </resources>
+ </bundle>
+</container>
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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.
+ *
+ ******************************************************************/
+
+collections
+{
+ base_scale: 1.8;
+ #include "../edc_resource/container_control.edc"
+}
\ No newline at end of file
*
******************************************************************/
-#include "recontainer.h"
+#include "container.h"
-#include "remain.h"
-#include "PrimitiveResource.h"
+#include "rcmain.h"
#include "RCSResourceContainer.h"
#include <string>
if (checkContainer)
{
std::map<string, string> resourceParams;
- resourceParams["resourceType"] = "oic.light.control";
+ resourceParams["resourceType"] = "oic.r.light";
resourceParams["address"] = "http://192.168.0.2/api/newdeveloper/lights/1";
if (s_hueBundleFlag)
{
container->addResourceConfig("oic.bundle.hueSample", "", resourceParams);
- logMessage += "Resource added<br>";
+ logMessage += "1 Light Resource added<br>";
listHueResources(NULL, NULL, NULL);
}
else
{
std::map<string, string> bundleParams;
container->addBundle("oic.bundle.hueSample", "",
- "/opt/usr/apps/org.tizen.resampleserver/lib/libHueBundle.so", bundleParams);
+ "/opt/usr/apps/org.tizen.containerserver/lib/libHueBundle.so",
+ "huesample", bundleParams);
logMessage += "HUE Bundle added <br>";
}
else
{
std::map<string, string> bundleParams;
container->addBundle("oic.bundle.BMISensor", "",
- "/opt/usr/apps/org.tizen.resampleserver/lib/libBMISensorBundle.so", bundleParams);
+ "/opt/usr/apps/org.tizen.containerserver/lib/libBMISensorBundle.so",
+ "bmisensor", bundleParams);
logMessage += "BMI Bundle added <br>";
}
else
if (checkContainer)
{
container->startBundle("oic.bundle.hueSample");
- logMessage += "BMI Bundle started <br>";
+ logMessage += "HUE Bundle started <br>";
s_hueBundleFlag = true;
}
else
elm_list_item_append(listnew, "2. List Hue resources", NULL, NULL,
listHueResources, NULL);
- elm_list_item_append(listnew, "3. Add HUE Resource Config", NULL, NULL,
+ elm_list_item_append(listnew, "3. Add HUE Bundle Resource", NULL, NULL,
addHueResourceConfig, NULL);
- elm_list_item_append(listnew, "4. Remove HUE Resource Config", NULL, NULL,
+ elm_list_item_append(listnew, "4. Remove HUE Bundle Resource", NULL, NULL,
removeHueResourceConfig, NULL);
- elm_list_item_append(listnew, "5. List BMI resources", NULL, NULL,
- listBMIResources, NULL);
-
- elm_list_item_append(listnew, "6. Add BMI Bundle", NULL, NULL,
+ elm_list_item_append(listnew, "5. Add BMI Bundle", NULL, NULL,
addBMIBundle, NULL);
- elm_list_item_append(listnew, "7. Start BMI Bundle", NULL, NULL,
+ elm_list_item_append(listnew, "6. Start BMI Bundle", NULL, NULL,
startBMIBundle, NULL);
- elm_list_item_append(listnew, "8. Add BMI Resource Config", NULL, NULL,
- addBMIResourceConfig, NULL);
-
- elm_list_item_append(listnew, "9. Remove BMI Resource Config", NULL, NULL,
- removeBMIResourceConfig, NULL);
-
- elm_list_item_append(listnew, "10. Remove BMI Bundle", NULL, NULL,
+ elm_list_item_append(listnew, "7. Remove BMI Bundle", NULL, NULL,
removeBMIBundle, NULL);
- elm_list_item_append(listnew, "11. Stop BMI Bundle", NULL, NULL,
+ elm_list_item_append(listnew, "8. Stop BMI Bundle", NULL, NULL,
stopBMIBundle, NULL);
elm_list_go(listnew);
static void startContainer(void *data, Evas_Object *obj, void *event_info)
{
std::string xmlDescription =
- "/opt/usr/apps/org.tizen.resampleserver/lib/ResourceContainerConfig.xml";
+ "/opt/usr/apps/org.tizen.containerserver/lib/ResourceContainerConfig.xml";
string logMessage = "";
if (NULL != listnew)
s_containerFlag = true;
s_hueBundleFlag = true;
logMessage += "CONTAINER STARTED<br>";
- logMessage += "HUE BUNDLE ADDED<br>";
- logMessage += "HUE BUNDLE STARTED<br>";
+ logMessage += "ADD AND START BUNDLES<br>";
}
else
{
// Method to set up server screens
void containerCreateUI(void *data, Evas_Object *obj, void *event_info)
{
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI");
s_containerFlag = false;
s_hueBundleFlag = false;
Evas_Object *layout;
scroller = elm_scroller_add(nf);
elm_scroller_bounce_set(scroller, EINA_FALSE, EINA_TRUE);
elm_scroller_policy_set(scroller, ELM_SCROLLER_POLICY_OFF, ELM_SCROLLER_POLICY_AUTO);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 1");
// Layout
layout = elm_layout_add(nf);
evas_object_size_hint_weight_set(layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
elm_object_content_set(scroller, layout);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 2");
// Button
start_button = elm_button_add(layout);
elm_object_part_content_set(layout, "start_button", start_button);
elm_object_text_set(start_button, "Start Container");
evas_object_smart_callback_add(start_button, "clicked", startContainer, NULL);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 3");
// Button
stop_button = elm_button_add(layout);
elm_object_part_content_set(layout, "stop_button", stop_button);
elm_object_text_set(stop_button, "Stop Container");
evas_object_smart_callback_add(stop_button, "clicked", stopContainer, NULL);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 4");
// List
listnew = elm_list_add(layout);
evas_object_smart_callback_add(listnew, "selected", list_selected_cb, NULL);
elm_object_part_content_set(layout, "listnew", listnew);
elm_list_go(listnew);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 5");
// log_entry - text area for log
log_entry = elm_entry_add(layout);
nf_it = elm_naviframe_item_push(nf, "Resource Container", NULL, NULL, scroller, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, NULL);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### container UI 6");
}
--- /dev/null
+/******************************************************************
+ *
+ * Copyright 2015 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 "rcmain.h"
+#include <tizen.h>
+
+typedef struct appdata
+{
+ Evas_Object *win;
+ Evas_Object *conform;
+ Evas_Object *layout;
+ Evas_Object *nf;
+ Evas_Object *findButton;
+ Evas_Object *logtext;
+ Evas_Object *listview;
+} appdata_s;
+
+static void
+win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
+{
+ ui_app_exit();
+}
+
+static void
+list_selected_cb(void *data, Evas_Object *obj, void *event_info)
+{
+ Elm_Object_Item *it = (Elm_Object_Item *)event_info;
+ elm_list_item_selected_set(it, EINA_FALSE);
+}
+
+static Eina_Bool
+naviframe_pop_cb(void *data, Elm_Object_Item *it)
+{
+ ui_app_exit();
+ return EINA_FALSE;
+}
+
+static void
+create_list_view(appdata_s *ad)
+{
+ Evas_Object *list;
+ Evas_Object *btn;
+ Evas_Object *nf = ad->nf;
+ Elm_Object_Item *nf_it;
+
+ // List
+ list = elm_list_add(nf);
+ elm_list_mode_set(list, ELM_LIST_COMPRESS);
+ evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
+
+ // Main Menu Items Here
+ elm_list_item_append(list, "Resource Container", NULL, NULL, containerCreateUI, nf);
+
+ elm_list_go(list);
+
+ // This button is set for devices which doesn't have H/W back key.
+ btn = elm_button_add(nf);
+ elm_object_style_set(btn, "naviframe/end_btn/default");
+ nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
+ elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
+}
+
+
+static void
+create_base_gui(appdata_s *ad)
+{
+ // Window
+ ad->win = elm_win_util_standard_add(PACKAGE, PACKAGE);
+ elm_win_conformant_set(ad->win, EINA_TRUE);
+ elm_win_autodel_set(ad->win, EINA_TRUE);
+
+ if (elm_win_wm_rotation_supported_get(ad->win))
+ {
+ int rots[4] = { 0, 90, 180, 270 };
+ elm_win_wm_rotation_available_rotations_set(ad->win, (const int *)(&rots), 4);
+ }
+
+ evas_object_smart_callback_add(ad->win, "delete,request", win_delete_request_cb, NULL);
+
+ // Conformant
+ ad->conform = elm_conformant_add(ad->win);
+ evas_object_size_hint_weight_set(ad->conform, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+ elm_win_resize_object_add(ad->win, ad->conform);
+ evas_object_show(ad->conform);
+
+ // Base Layout
+ ad->layout = elm_layout_add(ad->conform);
+ evas_object_size_hint_weight_set(ad->layout, EVAS_HINT_EXPAND, EVAS_HINT_EXPAND);
+ elm_layout_theme_set(ad->layout, "layout", "application", "default");
+ evas_object_show(ad->layout);
+
+ elm_object_content_set(ad->conform, ad->layout);
+
+ // Naviframe
+ ad->nf = elm_naviframe_add(ad->layout);
+ create_list_view(ad);
+ elm_object_part_content_set(ad->layout, "elm.swallow.content", ad->nf);
+ eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_BACK, eext_naviframe_back_cb, NULL);
+ eext_object_event_callback_add(ad->nf, EEXT_CALLBACK_MORE, eext_naviframe_more_cb, NULL);
+
+ // Show window after base gui is set up
+ evas_object_show(ad->win);
+}
+
+// Configures the OCPlatform
+static void
+configure_platform()
+{
+ try
+ {
+ PlatformConfig config
+ { OC::ServiceType::InProc, ModeType::Server, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+
+ OCPlatform::Configure(config);
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### Platform configuration done!!!!");
+ }
+ catch (OCException &e)
+ {
+ dlog_print(DLOG_ERROR, LOG_TAG, "Exception occured! (%s)", e.what());
+ }
+}
+
+static bool
+app_create(void *data)
+{
+ /* Hook to take necessary actions before main event loop starts
+ Initialize UI resources and application's data
+ If this function returns true, the main loop of application starts
+ If this function returns false, the application is terminated */
+ appdata_s *ad = (appdata_s *)data;
+
+ elm_app_base_scale_set(1.8);
+
+ create_base_gui(ad);
+
+ configure_platform();
+
+ return true;
+}
+
+static void
+app_control(app_control_h app_control, void *data)
+{
+ // Handle the launch request.
+}
+
+static void
+app_pause(void *data)
+{
+ // Take necessary actions when application becomes invisible.
+}
+
+static void
+app_resume(void *data)
+{
+ // Take necessary actions when application becomes visible.
+}
+
+static void
+app_terminate(void *data)
+{
+ // Release all resources.
+}
+
+static void
+ui_app_lang_changed(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_LANGUAGE_CHANGED
+ char *locale = NULL;
+ system_settings_get_value_string(SYSTEM_SETTINGS_KEY_LOCALE_LANGUAGE, &locale);
+ elm_language_set(locale);
+ free(locale);
+ return;
+}
+
+static void
+ui_app_orient_changed(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_DEVICE_ORIENTATION_CHANGED
+ return;
+}
+
+static void
+ui_app_region_changed(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_REGION_FORMAT_CHANGED
+}
+
+static void
+ui_app_low_battery(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_LOW_BATTERY
+}
+
+static void
+ui_app_low_memory(app_event_info_h event_info, void *user_data)
+{
+ // APP_EVENT_LOW_MEMORY
+}
+
+int
+main(int argc, char *argv[])
+{
+ appdata_s ad = {0,};
+ int ret = 0;
+
+ ui_app_lifecycle_callback_s event_callback = {0,};
+ app_event_handler_h handlers[5] = {NULL, };
+
+ event_callback.create = app_create;
+ event_callback.terminate = app_terminate;
+ event_callback.pause = app_pause;
+ event_callback.resume = app_resume;
+ event_callback.app_control = app_control;
+
+ ui_app_add_event_handler(&handlers[APP_EVENT_LOW_BATTERY], APP_EVENT_LOW_BATTERY,
+ ui_app_low_battery, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_LOW_MEMORY], APP_EVENT_LOW_MEMORY,
+ ui_app_low_memory, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_DEVICE_ORIENTATION_CHANGED],
+ APP_EVENT_DEVICE_ORIENTATION_CHANGED,
+ ui_app_orient_changed, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_LANGUAGE_CHANGED],
+ APP_EVENT_LANGUAGE_CHANGED,
+ ui_app_lang_changed, &ad);
+ ui_app_add_event_handler(&handlers[APP_EVENT_REGION_FORMAT_CHANGED],
+ APP_EVENT_REGION_FORMAT_CHANGED,
+ ui_app_region_changed, &ad);
+ ui_app_remove_event_handler(handlers[APP_EVENT_LOW_MEMORY]);
+
+ ret = ui_app_main(argc, argv, &event_callback, &ad);
+ if (APP_ERROR_NONE != ret)
+ {
+ dlog_print(DLOG_ERROR, LOG_TAG, "app_main() is failed. err = %d", ret);
+ }
+ return ret;
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<manifest xmlns="http://tizen.org/ns/packages" api-version="2.3" package="org.tizen.containerserver" version="1.0.0">
+ <profile name="mobile"/>
+ <ui-application appid="org.tizen.containerserver" exec="containerserver" multiple="false" nodisplay="false" taskmanage="true" type="capp">
+ <label>containerserver</label>
+ <icon>containerServer.png</icon>
+ </ui-application>
+ <privileges>
+ <privilege>http://tizen.org/privilege/network.get</privilege>
+ <privilege>http://tizen.org/privilege/internet</privilege>
+ </privileges>
+ <feature name="http://tizen.org/feature/network.wifi">true</feature>
+</manifest>
#include <jni.h>
#include "org_iotivity_resourcecontainer_bundle_api_BaseActivator.h"
#include "JavaBundleResource.h"
-#include "ResourceContainerImpl.h"
using namespace OIC::Service;
-std::map< string, JavaBundleResource * > java_resources;
+std::map< string, BundleResource::Ptr > java_resources;
/*
* Class: org_iotivity_resourcecontainer_bundle_api_BaseActivator
const char *str_resourceType = env->GetStringUTFChars(resourceType, 0);
const char *str_res_name = env->GetStringUTFChars(res_name, 0);
- JavaBundleResource *javaBundleResource = new JavaBundleResource(env, obj, bundleResource,
- str_bundleId, attributes);
+ BundleResource::Ptr javaBundleResource = std::make_shared< JavaBundleResource >
+ (env, obj, bundleResource, str_bundleId, attributes);
ResourceContainerImpl *container = ResourceContainerImpl::getImplInstance();
javaBundleResource->m_uri = string(str_uri, strlen(str_uri));
container->registerResource(javaBundleResource);
java_resources[str_uri] = javaBundleResource;
-
}
/*
m_bundleId = bundleId;
- this->bundleResource = env->NewGlobalRef(bundleResource);
+ this->m_bundleResource = env->NewGlobalRef(bundleResource);
- bundleResourceClass = env->GetObjectClass(bundleResource);
+ m_bundleResourceClass = env->GetObjectClass(bundleResource);
- attributeSetter = env->GetMethodID(bundleResourceClass, "setAttribute",
- "(Ljava/lang/String;Ljava/lang/String;)V");
+ m_attributeSetRequestHandler = env->GetMethodID(m_bundleResourceClass,
+ "handleSetAttributeRequest", "(Ljava/lang/String;Ljava/lang/String;)V");
- attributeGetter = env->GetMethodID(bundleResourceClass, "getAttribute",
- "(Ljava/lang/String;)Ljava/lang/String;");
+ m_attributeGetRequestHandler = env->GetMethodID(m_bundleResourceClass,
+ "handleGetAttributeRequest", "(Ljava/lang/String;)Ljava/lang/String;");
}
}
-RCSResourceAttributes &JavaBundleResource::getAttributes()
-{
- return BundleResource::getAttributes();
-}
-
-RCSResourceAttributes::Value JavaBundleResource::getAttribute(const std::string &attributeName)
+RCSResourceAttributes::Value JavaBundleResource::handleGetAttributeRequest(
+ const std::string &attributeName)
{
JavaVM *vm = ResourceContainerImpl::getImplInstance()->getJavaVM(m_bundleId);
{
if (vm->AttachCurrentThread((void **) &env, NULL) != 0)
{
- OC_LOG_V(ERROR, CONTAINER_TAG, "[JavaBundleResource::getAttribute] Failed to attach ");
+ OC_LOG_V(ERROR, CONTAINER_TAG,
+ "[JavaBundleResource::handleGetAttributeRequest] Failed to attach ");
}
}
else if (envStat == JNI_EVERSION)
{
- OC_LOG_V(ERROR, CONTAINER_TAG, "[JavaBundleResource::getAttribute] Env: version not supported");
+ OC_LOG_V(ERROR, CONTAINER_TAG,
+ "[JavaBundleResource::handleGetAttributeRequest] Env: version not supported");
}
jstring attrName = env->NewStringUTF(attributeName.c_str());
- jstring returnString = (jstring) env->CallObjectMethod(bundleResource, attributeGetter,
- attrName);
+ jstring returnString = (jstring) env->CallObjectMethod(m_bundleResource,
+ m_attributeGetRequestHandler, attrName);
const char *js = env->GetStringUTFChars(returnString, NULL);
std::string val(js);
return BundleResource::getAttribute(attributeName);
}
-void JavaBundleResource::setAttribute(std::string attributeName,
+void JavaBundleResource::handleSetAttributeRequest(const std::string &attributeName,
RCSResourceAttributes::Value &&value)
{
JavaVM *vm = ResourceContainerImpl::getImplInstance()->getJavaVM(m_bundleId);
{
if (vm->AttachCurrentThread((void **) &env, NULL) != 0)
{
- OC_LOG_V(ERROR, CONTAINER_TAG, "[JavaBundleResource::setAttribute] Failed to attach ");
+ OC_LOG_V(ERROR, CONTAINER_TAG,
+ "[JavaBundleResource::handleSetAttributeRequest] Failed to attach ");
}
}
else if (envStat == JNI_EVERSION)
{
- OC_LOG_V(ERROR, CONTAINER_TAG, "[JavaBundleResource::setAttribute] Env: version not supported ");
+ OC_LOG_V(ERROR, CONTAINER_TAG,
+ "[JavaBundleResource::handleSetAttributeRequest] Env: version not supported ");
}
jstring attrName = env->NewStringUTF(attributeName.c_str());
jstring val = env->NewStringUTF(value.toString().c_str());
- env->CallObjectMethod(bundleResource, attributeSetter, attrName, val);
+ env->CallObjectMethod(m_bundleResource, m_attributeSetRequestHandler, attrName, val);
BundleResource::setAttribute(attributeName, std::move(value));
}
+
+
+void JavaBundleResource::handleSetAttributesRequest(RCSResourceAttributes &attrs){
+ for (RCSResourceAttributes::iterator it = attrs.begin(); it != attrs.end(); ++it)
+ {
+ handleSetAttributeRequest(it->key(),std::move(it->value()));
+ }
+}
+
+RCSResourceAttributes & JavaBundleResource::handleGetAttributesRequest()
+{
+ std::list<string> attrsNames = getAttributeNames();
+ for(std::list<string>::iterator iterator = attrsNames.begin();
+ iterator != attrsNames.end(); ++iterator )
+ {
+ handleGetAttributeRequest(*iterator);
+ }
+ return BundleResource::getAttributes();
+}
#endif
jobjectArray attributes);
virtual ~JavaBundleResource();
- virtual RCSResourceAttributes& getAttributes();
+ void handleSetAttributeRequest(const std::string& key,
+ RCSResourceAttributes::Value&&);
- virtual void setAttribute(std::string key, RCSResourceAttributes::Value&&);
+ RCSResourceAttributes::Value handleGetAttributeRequest(const std::string& key);
+
+ virtual void handleSetAttributesRequest(RCSResourceAttributes &attrs);
+
+ virtual RCSResourceAttributes& handleGetAttributesRequest();
- virtual RCSResourceAttributes::Value getAttribute(const std::string& key);
virtual void initAttributes();
private:
// needs to be a GlobalRef
- jobject bundleResource;
- jobjectArray attributes;
- jclass bundleResourceClass;
- jmethodID attributeSetter;
- jmethodID attributeGetter;
+ jobject m_bundleResource;
+ jobjectArray m_attributes;
+ jclass m_bundleResourceClass;
+ jmethodID m_attributeSetRequestHandler;
+ jmethodID m_attributeGetRequestHandler;
string m_bundleId;
};
}
bundles[i][BUNDLE_LIBRARY_PATH]);
}
- OC_LOG_V(INFO, CONTAINER_TAG, "Init Bundle:(%s)", std::string(bundles[i][BUNDLE_ID] + ";" +
- bundles[i][BUNDLE_PATH]).c_str());
+ OC_LOG_V(INFO, CONTAINER_TAG, "Init Bundle:(%s)",
+ std::string(bundles[i][BUNDLE_ID] + ";" +
+ bundles[i][BUNDLE_PATH]).c_str());
+
registerBundle(bundleInfo);
activateBundle(bundleInfo);
}
std::bind(&ResourceContainerImpl::setRequestHandler, this,
std::placeholders::_1, std::placeholders::_2));
- OC_LOG_V(INFO, CONTAINER_TAG, "Registration finished (%s)", std::string(strUri + ", " +
- strResourceType).c_str());
+ OC_LOG_V(INFO, CONTAINER_TAG, "Registration finished (%s)",
+ std::string(strUri + ", " +
+ strResourceType).c_str());
if (m_config->isHasInput(resource->m_bundleId))
{
void ResourceContainerImpl::onNotificationReceived(const std::string &strResourceUri)
{
- OC_LOG_V(INFO, CONTAINER_TAG, "notification from (%s)", std::string(strResourceUri + ".").c_str());
+ OC_LOG_V(INFO, CONTAINER_TAG,
+ "notification from (%s)", std::string(strResourceUri + ".").c_str());
if (m_mapServers.find(strResourceUri) != m_mapServers.end())
{
RCSResourceObject::Ptr ResourceContainerImpl::buildResourceObject(const std::string &strUri,
const std::string &strResourceType)
{
- return RCSResourceObject::Builder(strUri, strResourceType, "oic.if.baseline").setObservable(
+ return RCSResourceObject::Builder(strUri, strResourceType,
+ "oic.if.baseline").setObservable(
true).setDiscoverable(true).build();
}
bundleInfo->setActivatorName(activator);
if (params.find("libraryPath") != params.end())
{
- string activatorName = params["activator"]; // modify activator for Java bundle
+ string activatorName = activator; // modify activator for Java bundle
std::replace(activatorName.begin(), activatorName.end(), '.', '/');
((BundleInfoInternal *) bundleInfo)->setActivatorName(activatorName);
((BundleInfoInternal *)bundleInfo)->setLibraryPath(params[BUNDLE_LIBRARY_PATH]);
}
- OC_LOG_V(INFO, CONTAINER_TAG, "Add Bundle: (%s)", std::string(bundleInfo->getID() + "; " +
- bundleInfo->getPath()).c_str());
+ OC_LOG_V(INFO, CONTAINER_TAG, "Add Bundle: (%s)",
+ std::string(bundleInfo->getID() + "; " +
+ bundleInfo->getPath()).c_str());
registerBundle(bundleInfo);
}
{
OC_LOG_V(INFO, CONTAINER_TAG, "Registering Java bundle (%s)",
std::string(bundleInfo->getID()).c_str());
-
JavaVM *jvm;
JNIEnv *env;
JavaVMInitArgs vm_args;
{
fclose(file);
- OC_LOG_V(INFO, CONTAINER_TAG, "Resource bundle (%s)", std::string(bundleInfo->getPath() +
- " available.").c_str());
+ OC_LOG_V(INFO, CONTAINER_TAG, "Resource bundle (%s)",
+ std::string(bundleInfo->getPath() +
+ " available.").c_str());
}
else
{
strcpy(classpath, "-Djava.class.path=");
strcat(classpath, bundleInfo->getPath().c_str());
- OC_LOG(INFO, CONTAINER_TAG, std::string("Configured classpath: ").append(classpath).c_str());
+ OC_LOG(INFO, CONTAINER_TAG,
+ std::string("Configured classpath: ").append(classpath).c_str());
options[1].optionString = classpath;
strcat(libraryPath, bundleInfo->getLibraryPath().c_str());
options[2].optionString = libraryPath;
- OC_LOG(INFO, CONTAINER_TAG, std::string("Configured library path: ").append(libraryPath).c_str());
+ OC_LOG(INFO, CONTAINER_TAG,
+ std::string("Configured library path: ").append(libraryPath).c_str());
vm_args.version = JNI_VERSION_1_4;
vm_args.options = options;
OC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
std::string( bundleInfoInternal->getID()
+ " activate bundle method not found ").c_str());
-
return;
}
bundleInfoInternal->setJavaBundleActivatorMethod(activateMethod);
OC_LOG_V(ERROR, CONTAINER_TAG, "Cannot register bundle (%s)",
std::string( bundleInfoInternal->getID()
+ " deactivate bundle method not found ").c_str());
-
return;
}
m_bundles[bundleInfo->getID()] = ((BundleInfoInternal *)bundleInfo);
+
OC_LOG(INFO, CONTAINER_TAG, "Bundle registered");
}
env.AddMethod(filtered_glob, "FilteredGlob");
if env.get('RELEASE'):
- env.AppendUnique(CCFLAGS = ['-Os'])
- env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
else:
- env.AppendUnique(CCFLAGS = ['-g'])
+ env.AppendUnique(CCFLAGS = ['-g'])
if env.get('LOGGING'):
- env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+ env.AppendUnique(CPPDEFINES = ['TB_LOG'])
container_gtest_env = lib_env.Clone()
if int(containerJavaSupport):
- try:
- print 'Java Home: ', os.environ['JAVA_HOME']
- print 'Java Lib: ', os.environ['JAVA_LIB']
- container_gtest_env.Append(CPPDEFINES={'JAVA_SUPPORT_TEST':1})
- except KeyError:
- print '''
- *********************************** Error *************************************
- * Building resource container without Java support. JAVA_HOME or JAVA_LIB are not set properly
- * Please configure JAVA_HOME to point to your Java 7 JDK and
- * JAVA_LIB to your folder containing libjvm
- * Example: export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386
- * export JAVA_LIB=/usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/server/
- *******************************************************************************
- '''
- container_gtest_env.Append(CPPDEFINES={'JAVA_SUPPORT_TEST':0})
+ try:
+ print 'Java Home: ', os.environ['JAVA_HOME']
+ print 'Java Lib: ', os.environ['JAVA_LIB']
+ container_gtest_env.Append(CPPDEFINES={'JAVA_SUPPORT_TEST':1})
+ except KeyError:
+ print '''
+ *********************************** Error *************************************
+ * Building resource container without Java support. JAVA_HOME or JAVA_LIB are not set properly
+ * Please configure JAVA_HOME to point to your Java 7 JDK and
+ * JAVA_LIB to your folder containing libjvm
+ * Example: export JAVA_HOME=/usr/lib/jvm/java-7-openjdk-i386
+ * export JAVA_LIB=/usr/lib/jvm/java-7-openjdk-i386/jre/lib/i386/server/
+ *******************************************************************************
+ '''
+ container_gtest_env.Append(CPPDEFINES={'JAVA_SUPPORT_TEST':0})
target_os = env.get('TARGET_OS')
gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
container_gtest_env.AppendUnique(
- CPPPATH = [
- env.get('SRC_DIR')+'/extlibs',
- '../include',
- '../../../include',
- '../include/internal',
- '../../common/utils/include',
- '../bundle-api/include'
- ])
+ CPPPATH = [
+ env.get('SRC_DIR')+'/extlibs',
+ '../include',
+ '../../resource-encapsulation/include',
+ '../../resource-encapsulation/src/common/utils/include',
+ '../bundle-api/include',
+ '../src'
+ ])
if int(containerJavaSupport):
- try:
- container_gtest_env.AppendUnique(
- CPPPATH = [
- os.environ['JAVA_HOME']+'/include',
- os.environ['JAVA_HOME']+'/include/linux'
- ])
- except KeyError:
- print ''
+ try:
+ container_gtest_env.AppendUnique(
+ CPPPATH = [
+ os.environ['JAVA_HOME']+'/include',
+ os.environ['JAVA_HOME']+'/include/linux'
+ ])
+ except KeyError:
+ print ''
if target_os not in ['windows', 'winrt']:
- container_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
- if target_os != 'android':
- container_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
- container_gtest_env.AppendUnique(LIBS = ['pthread'])
+ container_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+ if target_os != 'android':
+ container_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
+ container_gtest_env.AppendUnique(LIBS = ['pthread'])
if target_os == 'android':
container_gtest_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
gtest_dir + '/include'])
if int(containerJavaSupport):
- try:
- container_gtest_env.AppendUnique(LIBPATH = [os.environ['JAVA_LIB']])
- except KeyError:
- print ''
+ try:
+ container_gtest_env.AppendUnique(LIBPATH = [os.environ['JAVA_LIB']])
+ except KeyError:
+ print ''
container_gtest_env.AppendUnique(CCFLAGS = ['-Wnoexcept'])
container_gtest_env.AppendUnique(LIBS = ['dl'])
if int(containerJavaSupport):
- try:
- print 'Java Lib: ', os.environ['JAVA_LIB']
- container_gtest_env.AppendUnique(LIBS = ['jvm'])
- except KeyError:
- print ''
+ try:
+ print 'Java Lib: ', os.environ['JAVA_LIB']
+ container_gtest_env.AppendUnique(LIBS = ['jvm'])
+ except KeyError:
+ print ''
######################################################################
# build test bundle
TEST_BUNDLE_DIR = 'TestBundle/'
test_bundle_env.AppendUnique(CPPPATH = [
- TEST_BUNDLE_DIR + 'include',
- '../include/'
- ])
+ TEST_BUNDLE_DIR + 'include'
+ ])
test_bundle_src = [ Glob(TEST_BUNDLE_DIR + 'src/*.cpp'), Glob('src/*.cpp')]
Ignore("./TestBundleJava/hue-0.1-jar-with-dependencies.jar", "./TestBundleJava/hue-0.1-jar-with-dependencies.jar")
if env.get('TEST') == '1':
- target_os = env.get('TARGET_OS')
- if target_os == 'linux':
- from tools.scons.RunTest import *
- run_test(container_gtest_env,
- '',
- 'service/resource-encapsulation/src/resourceContainer/unittests/container_test')
\ No newline at end of file
+ target_os = env.get('TARGET_OS')
+ if target_os == 'linux':
+ from tools.scons.RunTest import *
+ run_test(container_gtest_env,
+ '',
+ 'service/resource-container/unittests/container_test')
\ No newline at end of file
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# Resource Directory build script
+##
+
+Import('env')
+
+if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+ env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+ env.AppendUnique(CPPDEFINES = ['-DTB_LOG'])
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+rd_env = lib_env.Clone()
+
+target_os = env.get('TARGET_OS')
+######################################################################
+# Build flags
+######################################################################
+rd_env.AppendUnique(CPPPATH = ['include'])
+rd_env.AppendUnique(CPPPATH = ['src/internal'])
+rd_env.AppendUnique(CPPPATH = ['../../resource/csdk/logger/include'])
+rd_env.PrependUnique(LIBS = ['oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'libcoap'])
+
+if target_os not in ['windows', 'winrt']:
+ rd_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra'])
+
+if target_os == 'linux':
+ rd_env.AppendUnique(LIBS = ['pthread'])
+
+if target_os == 'android':
+ rd_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ rd_env.AppendUnique(LIBS = ['gnustl_static'])
+
+ if not env.get('RELEASE'):
+ rd_env.AppendUnique(LIBS = ['log'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+RD_SRC_DIR = 'src/'
+rd_src = [
+ RD_SRC_DIR + '/internal/rd_storage.c',
+ RD_SRC_DIR + 'rd_server.c',
+ RD_SRC_DIR + 'rd_client.c',
+ ]
+
+if target_os in ['tizen'] :
+ rdsdk = rd_env.SharedLibrary('resource_directory', rd_src)
+else :
+ rdsdk = rd_env.StaticLibrary('resource_directory', rd_src)
+
+rd_env.InstallTarget(rdsdk, 'libresource_directory')
+
+######################################################################
+# Samples for the resource directory
+######################################################################
+SConscript('samples/SConscript')
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 _RESOURCE_DIRECTORY_CLIENT_H_
+#define _RESOURCE_DIRECTORY_CLIENT_H_
+
+// Iotivity Base CAPI
+#include "ocstack.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/** Max ADDR SIZE */
+#define MAX_ADDR_STR_SIZE (40)
+
+/** Callback function for returning RDDiscovery Result. */
+typedef int (* OCRDBiasFactorCB)(char addr[MAX_ADDR_STR_SIZE], uint16_t port);
+
+/** Context structure used sending it as part of the callback context. */
+typedef struct
+{
+ /** Stores the context value of the message sent. */
+ void *context;
+ /** Pointing to the callback function that OCRDDiscover() received. */
+ OCRDBiasFactorCB cbFunc;
+} OCRDClientContextCB;
+
+/**
+ * Discovers the resource directory.
+ * This function searches a RD server and obtain the bias factor.
+ *
+ * @param cbBiasFactor callback function invoked when bias factor is returned by
+ * the Resource Directory Server
+ *
+ * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR in case of error.
+ */
+OCStackResult OCRDDiscover(OCRDBiasFactorCB cbBiasFactor);
+
+/**
+ * Publish resource on the RD.
+ *
+ * @param addr The IP address of the RD, it could be either retrieved via OCRDDiscover().
+ * @param port The port of the RD.
+ * @param num This denotes the number of registered resource handles being passed
+ * for the remaining arguments.
+ *
+ * @returns ::OC_STACK_OK when successful and OC_STACK_ERROR when query failed.
+ */
+OCStackResult OCRDPublish(char *addr, uint16_t port, int num, ...);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif //_RESOURCE_DIRECTORY_CLIENT_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 _RESOURCE_DIRECTORY_PAYLOAD_H_
+#define _RESOURCE_DIRECTORY_PAYLOAD_H_
+
+#include <cbor.h>
+
+#include "rd_types.h"
+#include "logger.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+ * Converts RD payload from structure to CBOR format. It creates the outPayload
+ * which is then transmitted over the wire.
+ *
+ * @param rdPayload Contains structure holding values of OCRDPayload.
+ * @param outPayload The payload in the CBOR format converting OCRDPayload
+ * structure.
+ * @param size Length of the payload.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in creating CBOR.
+ */
+OCStackResult OCRDPayloadToCbor(const OCRDPayload *rdPayload,
+ uint8_t *outPayload, size_t *size);
+
+/**
+ * Converts CBOR to OCRDPayload.
+ *
+ * @param rdCBORPayload Payload received from other end in CBOR format.
+ * @param outPayload Parsing the values from CBOR into OCRDPayload structure.
+ *
+ * @return ::OC_STACK_OK returns if successful and OC_STACK_ERROR returns if
+ * failed in parsing CBOR.
+ */
+OCStackResult OCRDCborToPayload(const CborValue *rdCBORPayload, OCPayload **outPayload);
+
+/**
+ * Initializes RD payload structure.
+ *
+ * @param payloadType Defines whether payload is RD_PAYLOAD_TYPE_DISCOVERY or
+ * RD_PAYLOAD_TYPE_PUBLISH.
+ *
+ * @return Allocated memory for the OCRDPayload and NULL in case if failed to
+ * allocate memory
+ */
+OCRDPayload *OCRDPayloadCreate(OCRDPayloadType payloadType);
+
+/**
+ * Initializes RD Discovery payload structure and sets the bias factor.
+ *
+ * @param biasFactor Value specifies the selection factor. It is weigthage of
+ * CPU, Memory, Network, Load and Power capability of the RD server.
+ *
+ * @return Allocated memory for the OCRDDiscoveryPayload and NULL in case if
+ * failed to allocate memory.
+ */
+OCRDDiscoveryPayload *OCRDDiscoveryPayloadCreate(int biasFactor);
+
+/**
+ * Creates the links payload, which is then embedded inside OCRDPublishPayload.
+ *
+ * @param uri The Web Link Address of the resource.
+ * @param rt The resource type of the published resource.
+ * @param itf The interface type of the published resource.
+ * @param linkPayload The address of the allocated memory or NULL in case if failed
+ * to allocate memory.
+ */
+void OCRDLinksPayloadCreate(const char *uri, const char *rt, const char *itf,
+ OCRDLinksPayload **linkPayload);
+
+/**
+ * Creates the links payload, which is then embedded inside OCRDPublishPayload.
+ *
+ * @param ttl Time to live of the published resource..
+ * @param linkPayload The link payload with uri, rt and itf.
+ *
+ * @return Allocated memory of OCRDPublishPayload or NULL in case if failed
+ * to allocate memory.
+ */
+OCRDPublishPayload *OCRDPublishPayloadCreate(const int ttl,
+ OCRDLinksPayload *linkPayload);
+
+/**
+ * Free memory allocation of the RDPayload and its internal structure.
+ *
+ * @param payload Pointer to already allocated memory for OCRDPayload.
+ */
+void OCRDPayloadDestroy(OCRDPayload *payload);
+
+/**
+ * Logs the content of the OCRDPayload.
+ *
+ * @param level Log level DEBUG or INFO or ERROR.
+ * @param tag File specific tag to use.
+ * @param payload Pointer to already allocated memory for OCRDPayload.
+ */
+void OCRDPayloadLog(LogLevel level, const char *tag, const OCRDPayload *payload);
+
+/**
+ * Logs the subset of the OCRDPayload, prints separately OCRDPublish.
+ *
+ * @param level Log level DEBUG or INFO or ERROR.
+ * @param tag File specific tag to use.
+ * @param payload Pointer to already allocated memory for OCRDPublish.
+ */
+void OCRDPublishPayloadLog(LogLevel level, const char *tag,
+ const OCRDPublishPayload *rdPublish);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 _RESOURCE_DIRECTORY_SERVER_H_
+#define _RESOURCE_DIRECTORY_SERVER_H_
+
+// Iotivity Base CAPI
+#include "ocstack.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/**
+* This function creates resource /oic/rd.
+*
+* @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR in case of error.
+*/
+OCStackResult OCRDStart();
+
+/**
+* Stops resource directory.
+* This function will stop the resource directory and removes all published
+* resources information.
+*
+* @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR is returned except
+* the case that OC_STACK_SUCCESS is returned.
+*/
+OCStackResult OCRDStop();
+
+/**
+ * Checks based on the resource type if the entity exists in the resource directory.
+ *
+ * @param interfaceType a interface type that is being queried.
+ * @param resourceType a resource type that is being queried.
+ * @param uri A URI of the resource found;
+ * @param rt A resource type of the message queried.
+ * @param itf A resource type of the interface.
+ *
+ * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR is returned except
+ * the case that OC_STACK_SUCCESS is returned.
+ */
+OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *resourceType,
+ OCResourceCollectionPayload **payload);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif //_RESOURCE_DIRECTORY_H_
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# ResourceDirectory Sample Apps build script
+##
+
+Import('env')
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+rd_sample_app_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+rd_sample_app_env.AppendUnique(CPPPATH = ['../include'])
+
+rd_sample_app_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+rd_sample_app_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+rd_sample_app_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+rd_sample_app_env.PrependUnique(LIBS = ['resource_directory', 'oc', 'octbstack'])
+
+if env.get('SECURED') == '1':
+ rd_sample_app_env.AppendUnique(LIBS = ['tinydtls'])
+
+####################################################################
+# Source files and Targets
+######################################################################
+rd_server = rd_sample_app_env.Program('rd_server', 'rd_main.c')
+rd_publishingClient = rd_sample_app_env.Program('rd_publishingClient', 'rd_publishingClient.cpp')
+rd_queryClient = rd_sample_app_env.Program('rd_queryClient', 'rd_queryClient.cpp')
+
+Alias("resource_directory", [rd_server, rd_publishingClient])
+
+env.AppendTarget('resource_directory')
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "rd_server.h"
+
+#include <signal.h>
+#include <unistd.h>
+
+int g_quitFlag = 0;
+
+void handleSigInt(int signum);
+
+/*
+* This method is an entry point of Resource Directory.
+* This function should be run only on the device that it could be host device.
+*/
+
+int main()
+{
+ printf("OCResourceDirectory is starting...\n");
+ OCStackResult result = OCInit(NULL, 0, OC_CLIENT_SERVER);
+ if (result != OC_STACK_OK)
+ {
+ printf("Failed starting RD server ...\n");
+ return 0;
+ }
+ if (OCRDStart() != OC_STACK_OK)
+ {
+ printf("OCRDStart failed...\n");
+ return 0;
+ }
+
+ printf("OCRDStart successfully...\n");
+
+ signal(SIGINT, handleSigInt);
+ while (!g_quitFlag)
+ {
+ if (OCProcess() != OC_STACK_OK)
+ {
+ OCRDStop();
+ printf("OCStack process error\n");
+ return 0;
+ }
+ }
+
+ if (OCRDStop() != OC_STACK_OK)
+ {
+ printf("OCRDStop failed...\n");
+ }
+ else
+ {
+ printf("OCRDStop success...\n");
+ }
+
+ printf("Exiting OCResourceDirectory main loop...\n");
+ return 0;
+
+}
+
+/*
+* This is a signal handling function for SIGINT(CTRL+C).
+* A Resource Directory handle the SIGINT signal for safe exit.
+*
+* @param[in] signal
+* signal number of caught signal.
+*/
+void handleSigInt(int signum)
+{
+ if (signum == SIGINT)
+ {
+ g_quitFlag = 1;
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 <iostream>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "oic_string.h"
+
+#include "rd_client.h"
+
+using namespace OC;
+
+OCResourceHandle g_curResource_t = NULL;
+OCResourceHandle g_curResource_l = NULL;
+char rdAddress[MAX_ADDR_STR_SIZE];
+uint16_t rdPort;
+
+void registerLocalResources()
+{
+ std::string resourceURI_thermostat = "/a/thermostat";
+ std::string resourceTypeName_thermostat = "core.thermostat";
+ std::string resourceURI_light = "/a/light";
+ std::string resourceTypeName_light = "core.light";
+ std::string resourceInterface = DEFAULT_INTERFACE;
+ uint8_t resourceProperty = OC_DISCOVERABLE;
+
+ OCStackResult result = OCPlatform::registerResource(g_curResource_t,
+ resourceURI_thermostat,
+ resourceTypeName_thermostat,
+ resourceInterface,
+ NULL,
+ resourceProperty);
+
+ if (OC_STACK_OK != result)
+ {
+ throw std::runtime_error(
+ std::string("Device Resource failed to start") + std::to_string(result));
+ }
+
+ result = OCPlatform::registerResource(g_curResource_l,
+ resourceURI_light,
+ resourceTypeName_light,
+ resourceInterface,
+ NULL,
+ resourceProperty);
+
+ if (OC_STACK_OK != result)
+ {
+ throw std::runtime_error(
+ std::string("Device Resource failed to start") + std::to_string(result));
+ }
+}
+
+void printHelp()
+{
+ std::cout << std::endl;
+ std::cout << "********************************************" << std::endl;
+ std::cout << "* method Type : 1 - Discover RD *" << std::endl;
+ std::cout << "* method Type : 2 - Publish *" << std::endl;
+ std::cout << "* method Type : 3 - Update *" << std::endl;
+ std::cout << "* method Type : 4 - Delete *" << std::endl;
+ std::cout << "* method Type : 5 - Status *" << std::endl;
+ std::cout << "********************************************" << std::endl;
+ std::cout << std::endl;
+}
+
+int biasFactorCB(char addr[MAX_ADDR_STR_SIZE], uint16_t port)
+{
+ OICStrcpy(rdAddress, MAX_ADDR_STR_SIZE, addr);
+ rdPort = port;
+ std::cout << "RD Address is : " << addr << ":" << port << std::endl;
+ return 0;
+}
+
+int main()
+{
+ int in;
+ PlatformConfig cfg;
+
+ OCPlatform::Configure(cfg);
+
+ std::cout << "Created Platform..." << std::endl;
+
+ registerLocalResources();
+
+ while (1)
+ {
+ sleep(2);
+
+ if (g_curResource_t == NULL || g_curResource_l == NULL)
+ {
+ continue;
+ }
+ printHelp();
+
+ in = 0;
+ std::cin >> in;
+
+ if (std::cin.fail())
+ {
+ std::cin.clear();
+ std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+ std::cout << "Invalid input type, please try again" << std::endl;
+ continue;
+ }
+
+ try
+ {
+ switch ((int)in)
+ {
+ case 1:
+ OCRDDiscover(biasFactorCB);
+ break;
+ case 2:
+ OCRDPublish(rdAddress, rdPort, 2, g_curResource_t, g_curResource_l);
+ break;
+ case 3:
+ break;
+ default:
+ std::cout << "Invalid input, please try again" << std::endl;
+ break;
+ }
+ }
+ catch (OCException e)
+ {
+ std::cout << "Caught OCException [Code: " << e.code() << " Reason: " << e.reason() << std::endl;
+ }
+ }
+ return 0;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "OCApi.h"
+#include "OCPlatform.h"
+
+bool g_foundResource = true;
+
+void foundResource(std::shared_ptr< OC::OCResource > resource)
+{
+ try
+ {
+ std::cout << "Found resource response." << std::endl;
+ if (resource)
+ {
+ if (resource->uri() == "/a/light")
+ {
+ std::cout << "Found Resource at @ URI: " << resource->uri() << "\tHost Address: " <<
+ resource->host() << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "Resource is invalid " << resource->uri() << std::endl;
+ }
+ g_foundResource = false;
+ exit(0);
+ }
+ catch (std::exception &ex)
+ {
+ std::cout << "Exception: " << ex.what() << " in foundResource" << std::endl;
+ exit(1);
+ }
+}
+
+int main()
+{
+ OC::PlatformConfig cfg;
+ OC::OCPlatform::Configure(cfg);
+ bool sendRequest = true;
+
+ std::cout << "Created Platform..." << std::endl;
+
+ while (g_foundResource)
+ {
+ try
+ {
+ if (sendRequest)
+ {
+ sendRequest = false;
+ std::cout << "Finding Resource light" << std::endl;
+ OC::OCPlatform::findResource("", "/oic/res?rt=core.light", CT_DEFAULT, &foundResource);
+ }
+ }
+ catch (OC::OCException &ex)
+ {
+ sendRequest = true;
+ std::cout << "Exception finding resources : " << ex.reason() << std::endl;
+ }
+ }
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "rd_storage.h"
+
+#include <pthread.h>
+#include <string.h>
+
+#include "payload_logging.h"
+#include "oic_malloc.h"
+
+#include "rdpayload.h"
+
+#define TAG PCF("RDStorage")
+
+pthread_mutex_t storageMutex = PTHREAD_MUTEX_INITIALIZER;
+// This variable holds the published resources on the RD.
+static OCRDStorePublishResources *g_rdStorage = NULL;
+
+static void printStoragedResources(OCRDStorePublishResources *payload)
+{
+ OC_LOG(DEBUG, TAG, "Print Storage Resources ... ");
+ for (OCRDStorePublishResources *temp = payload; temp; temp = temp->next)
+ {
+ if (temp->publishedResource)
+ {
+ OCTagsLog(DEBUG, temp->publishedResource->tags);
+ OCLinksLog(DEBUG, temp->publishedResource->setLinks);
+ }
+ }
+}
+
+OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload)
+{
+ OCResourceCollectionPayload *storeResource = (OCResourceCollectionPayload *)OICCalloc(1, sizeof(OCResourceCollectionPayload));
+ if (!storeResource)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory for OCRDStorePublishResources.");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ OC_LOG(DEBUG, TAG, "Storing Resources ... ");
+
+ OCTagsPayload *tags = payload->tags;
+ storeResource->tags = OCCopyTagsResources(tags->n.deviceName, tags->di.id, tags->baseURI,
+ tags->bitmap, tags->port, tags->ins, tags->rts, tags->drel, tags->ttl);
+ if (!storeResource->tags)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory for tags.");
+ OCFreeCollectionResource(storeResource);
+ return OC_STACK_NO_MEMORY;
+ }
+
+ for (OCLinksPayload *links = payload->setLinks; links; links = links->next)
+ {
+ if (!storeResource->setLinks)
+ {
+ storeResource->setLinks = OCCopyLinksResources(links->href, links->rt, links->itf,
+ links->rel, links->obs, links->title, links->uri, links->ins, links->mt);
+ if (!storeResource->setLinks)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory for links.");
+ OCFreeCollectionResource(storeResource);
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ else
+ {
+ OCLinksPayload *temp = storeResource->setLinks;
+ while (temp->next)
+ {
+ temp = temp->next;
+ }
+ temp->next = OCCopyLinksResources(links->href, links->rt, links->itf, links->rel,
+ links->obs, links->title, links->uri, links->ins, links->mt);
+ if (!temp->next)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory for links.");
+ OCFreeCollectionResource(storeResource);
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+
+ }
+ storeResource->next = NULL;
+ OCRDStorePublishResources *resources = (OCRDStorePublishResources *)OICCalloc(1, sizeof(OCRDStorePublishResources));
+ if (!resources)
+ {
+ OCFreeCollectionResource(storeResource);
+ return OC_STACK_NO_MEMORY;
+ }
+ resources->publishedResource = storeResource;
+
+ pthread_mutex_lock(&storageMutex);
+ if (g_rdStorage)
+ {
+ OCRDStorePublishResources *temp = g_rdStorage;
+ while (temp->next)
+ {
+ temp = temp->next;
+ }
+ temp->next = resources;
+ }
+ else
+ {
+ g_rdStorage = resources;
+ }
+ pthread_mutex_unlock(&storageMutex);
+
+ printStoragedResources(g_rdStorage);
+ return OC_STACK_OK;
+}
+
+OCStackResult OCRDCheckPublishedResource(const char *interfaceType, const char *resourceType,
+ OCResourceCollectionPayload **payload)
+{
+ // ResourceType and InterfaceType if both are NULL it will return. If either is
+ // not null it will continue execution.
+ if (!resourceType && !interfaceType)
+ {
+ OC_LOG(DEBUG, TAG, "Missing resource type and interace type.");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ OC_LOG(DEBUG, TAG, "Check Resource in RD");
+ if (g_rdStorage && g_rdStorage->publishedResource)
+ {
+ for (OCRDStorePublishResources *pResource = g_rdStorage;
+ pResource; pResource = pResource->next)
+ {
+ if (pResource->publishedResource->setLinks)
+ {
+ for (OCLinksPayload *tLinks = pResource->publishedResource->setLinks; tLinks; tLinks = tLinks->next)
+ {
+ // If either rt or itf are NULL, it should skip remaining code execution.
+ if (!tLinks->rt || !tLinks->itf)
+ {
+ OC_LOG(DEBUG, TAG, "Either resource type and interface type are missing.");
+ continue;
+ }
+ if (resourceType)
+ {
+ OCStringLL *temp = tLinks->rt;
+ while(temp)
+ {
+ OC_LOG_V(DEBUG, TAG, "Resource Type: %s %s", resourceType, temp->value);
+ if (strcmp(resourceType, temp->value) == 0)
+ {
+ OCTagsPayload *tag = pResource->publishedResource->tags;
+ OCTagsPayload *tags = OCCopyTagsResources(tag->n.deviceName, tag->di.id, tag->baseURI,
+ tag->bitmap, tag->port, tag->ins, tag->rts, tag->drel, tag->ttl);
+ if (!tags)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ OCLinksPayload *links = OCCopyLinksResources(tLinks->href, tLinks->rt, tLinks->itf,
+ tLinks->rel, tLinks->obs, tLinks->title, tLinks->uri, tLinks->ins, tLinks->mt);
+ if (!links)
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_NO_MEMORY;
+ }
+ *payload = OCCopyCollectionResource(tags, links);
+ if (!*payload)
+ {
+ OCFreeTagsResource(tags);
+ OCFreeLinksResource(links);
+ return OC_STACK_NO_MEMORY;
+ }
+ return OC_STACK_OK;
+ }
+ temp = temp->next;
+ }
+ }
+ if (interfaceType)
+ {
+ OCStringLL *temp = tLinks->itf;
+ while (temp)
+ {
+ OC_LOG_V(DEBUG, TAG, "Interface Type: %s %s", interfaceType, temp->value);
+ if (strcmp(interfaceType, temp->value) == 0)
+ {
+ OCTagsPayload *tag = pResource->publishedResource->tags;
+ OCTagsPayload *tags = OCCopyTagsResources(tag->n.deviceName, tag->di.id, tag->baseURI,
+ tag->bitmap, tag->port, tag->ins, tag->rts, tag->drel, tag->ttl);
+ if (!tags)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+ OCLinksPayload *links = OCCopyLinksResources(tLinks->uri, tLinks->rt, tLinks->itf,
+ tLinks->rel, tLinks->obs, tLinks->title, tLinks->uri, tLinks->ins, tLinks->mt);
+ if (!links)
+ {
+ OCFreeTagsResource(tags);
+ return OC_STACK_NO_MEMORY;
+ }
+ *payload = OCCopyCollectionResource(tags, links);
+ if (!*payload)
+ {
+ OCFreeTagsResource(tags);
+ OCFreeLinksResource(links);
+ return OC_STACK_NO_MEMORY;
+ }
+ return OC_STACK_OK;
+ }
+ temp = temp->next;
+ }
+ }
+ }
+ }
+ }
+ }
+ return OC_STACK_ERROR;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 _RESOURCE_DIRECTORY_SERVER_STORAGE_H_
+#define _RESOURCE_DIRECTORY_SERVER_STORAGE_H_
+
+#include "octypes.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif // __cplusplus
+
+/** Stucture holding Published Resources on the Resource Directory. */
+typedef struct OCRDStorePublishResources
+{
+ /** Publish resource. */
+ OCResourceCollectionPayload *publishedResource;
+ /** Linked list pointing to next published resource. */
+ struct OCRDStorePublishResources *next;
+} OCRDStorePublishResources;
+
+/**
+ * Stores the publish resources.
+ *
+ * @param payload RDPublish payload sent from the remote device.
+ *
+ * @return ::OC_STACK_OK upon success, ::OC_STACK_ERROR in case of error.
+ */
+OCStackResult OCRDStorePublishedResources(const OCResourceCollectionPayload *payload);
+
+#ifdef __cplusplus
+}
+#endif // __cplusplus
+
+#endif //_RESOURCE_DIRECTORY_SERVER_STORAGE_H_
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "rd_client.h"
+
+#include <stdarg.h>
+
+#include "oic_string.h"
+#include "oic_malloc.h"
+#include "payload_logging.h"
+
+#include "rdpayload.h"
+#include "ocpayload.h"
+
+#define DEFAULT_CONTEXT_VALUE 0x99
+#define OC_RD_PUBLISH_TTL 86400
+
+#define TAG PCF("RDClient")
+
+static OCStackResult sendRequest(OCMethod method, char *uri, OCDevAddr *addr,
+ OCPayload *payload, OCCallbackData cbData)
+{
+ OCDoHandle handle;
+ OCStackResult result;
+
+ result = OCDoResource(&handle,
+ method,
+ uri,
+ addr,
+ payload,
+ CT_ADAPTER_IP,
+ OC_LOW_QOS,
+ &cbData,
+ NULL,
+ 0);
+
+ if (result == OC_STACK_OK)
+ {
+ OC_LOG(DEBUG, TAG, "Resource Directory send successful...");
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, "Resource Directory send failed...");
+ }
+
+ return result;
+}
+
+static OCStackApplicationResult handlePublishCB(__attribute__((unused))void *ctx,
+ __attribute__((unused)) OCDoHandle handle,
+ __attribute__((unused)) OCClientResponse *clientResponse)
+{
+ OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
+ OC_LOG(DEBUG, TAG, "Successfully published resources.");
+
+ if (OC_STACK_OK == OCStopMulticastServer())
+ {
+ OC_LOG_V(DEBUG, TAG, "Stopped receiving the multicast traffic.");
+ }
+ else
+ {
+ OC_LOG_V(DEBUG, TAG, "Failed stopping the multicast traffic.");
+ }
+
+ return ret;
+}
+
+static void retreiveRDDetails(OCClientResponse *clientResponse, OCRDBiasFactorCB clientCB)
+{
+ OC_LOG_V(DEBUG, TAG, "\tAddress of the RD: %s:%d", clientResponse->devAddr.addr,
+ clientResponse->devAddr.port);
+
+ OCRDPayload *payload = (OCRDPayload *) clientResponse->payload;
+ OC_LOG_PAYLOAD(DEBUG, (OCPayload *) payload);
+
+ // TODO: Multiple Resource Directory will have different biasFactor,
+ // needs to cache here detail
+ // and after certain timeout then decide based on the biasFactor.
+ //if (biasFactor > 75)
+ if (clientCB)
+ {
+ clientCB(clientResponse->devAddr.addr, clientResponse->devAddr.port);
+ }
+}
+
+static OCStackApplicationResult handleDiscoverCB(void *ctx,
+ __attribute__((unused)) OCDoHandle handle, OCClientResponse *clientResponse)
+{
+ OC_LOG(DEBUG, TAG, "Found Resource Directory");
+ OCStackApplicationResult ret = OC_STACK_DELETE_TRANSACTION;
+
+ OCRDClientContextCB *cb = (OCRDClientContextCB *)ctx;
+ if (!cb)
+ {
+ OC_LOG(ERROR, TAG, "RD Context Invalid Parameters.");
+ return ret;
+ }
+
+ if (cb->context != (void *) DEFAULT_CONTEXT_VALUE)
+ {
+ OC_LOG(ERROR, TAG, "RD Context Invalid Context Value Parameters.");
+ return ret;
+ }
+
+ OC_LOG_V(DEBUG, TAG, "Callback Context for DISCOVER query received successfully :%d.", clientResponse->result);
+
+ if (clientResponse && clientResponse->result == OC_STACK_OK)
+ {
+ retreiveRDDetails(clientResponse, cb->cbFunc);
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, "Discovery of RD Failed");
+ }
+
+ OICFree(cb);
+
+ return ret;
+}
+
+OCStackResult OCRDDiscover(OCRDBiasFactorCB cbBiasFactor)
+{
+ if (!cbBiasFactor)
+ {
+ OC_LOG(DEBUG, TAG, "No callback function specified.");
+ return OC_STACK_INVALID_CALLBACK;
+ }
+
+ /* Start a discovery query*/
+ char queryUri[MAX_URI_LENGTH] = { '\0' };
+ snprintf(queryUri, MAX_URI_LENGTH, "coap://%s%s", OC_MULTICAST_PREFIX, OC_RSRVD_RD_URI);
+
+ OC_LOG_V(DEBUG, TAG, "Querying RD: %s\n", queryUri);
+
+ OCRDClientContextCB *cbContext = (OCRDClientContextCB *)OICCalloc(1, sizeof(OCRDClientContextCB));
+ if (!cbContext)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ cbContext->context = (void *)DEFAULT_CONTEXT_VALUE;
+ cbContext->cbFunc = cbBiasFactor;
+
+ OCCallbackData cbData;
+ cbData.cb = handleDiscoverCB;
+ cbData.context = (void *)(cbContext);
+ cbData.cd = NULL;
+
+ return sendRequest(OC_REST_DISCOVER, queryUri, NULL, NULL, cbData);
+}
+
+static OCStackResult createStringLL(uint8_t numElements, OCResourceHandle handle,
+ const char* (*getValue)(OCResourceHandle handle, uint8_t i), OCStringLL **stringLL)
+{
+ for (uint8_t i = 0; i < numElements; ++i)
+ {
+ const char *value = getValue(handle, i);
+ if (!*stringLL)
+ {
+ *stringLL = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ if (!*stringLL)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ return OC_STACK_NO_MEMORY;
+ }
+ (*stringLL)->value = OICStrdup(value);
+ if (!(*stringLL)->value)
+ {
+ OC_LOG(ERROR, TAG, "Failed copying to OCStringLL.");
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ else
+ {
+ OCStringLL *cur = *stringLL;
+ while (cur->next)
+ {
+ cur = cur->next;
+ }
+ cur->next = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ if (!cur->next)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ return OC_STACK_NO_MEMORY;
+ }
+ cur->next->value = OICStrdup(value);
+ if (!cur->next->value)
+ {
+ OC_LOG(ERROR, TAG, "Failed copying to OCStringLL.");
+ return OC_STACK_NO_MEMORY;
+ }
+ }
+ }
+ return OC_STACK_OK;
+}
+
+OCStackResult OCRDPublish(char *addr, uint16_t port, int numArg, ... )
+{
+ if (!addr)
+ {
+ OC_LOG(ERROR, TAG, "RD address not specified.");
+ return OC_STACK_INVALID_PARAM;
+ }
+
+ char targetUri[MAX_URI_LENGTH];
+ snprintf(targetUri, MAX_URI_LENGTH, "coap://%s:%d%s?rt=%s", addr, port,
+ OC_RSRVD_RD_URI, OC_RSRVD_RESOURCE_TYPE_RDPUBLISH);
+ OC_LOG_V(DEBUG, TAG, "Target URI : %s", targetUri);
+
+ // Gather all resources locally and do publish
+ OCCallbackData cbData = { 0 };
+ cbData.cb = &handlePublishCB;
+ cbData.cd = NULL;
+ cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
+
+ OCTagsPayload *tagsPayload = NULL;
+ OCLinksPayload *linksPayload = NULL;
+ OCStringLL *rt = NULL;
+ OCStringLL *itf = NULL;
+ OCStringLL *mt = NULL;
+
+ OCRDPayload *rdPayload = OCRDPayloadCreate();
+ if (!rdPayload)
+ {
+ goto no_memory;
+ }
+
+ const unsigned char *id = (unsigned char*) OCGetServerInstanceIDString();
+ tagsPayload = OCCopyTagsResources(NULL, id,
+ NULL, OC_DISCOVERABLE, 0, 0, NULL, NULL, OC_RD_PUBLISH_TTL);
+ if (!tagsPayload)
+ {
+ goto no_memory;
+ }
+
+ va_list arguments;
+ va_start (arguments, numArg);
+
+ for (int j = 0 ; j < numArg; j++)
+ {
+ OCResourceHandle handle = va_arg(arguments, OCResourceHandle);
+ if (handle)
+ {
+ rt = itf = mt = NULL;
+ const char *uri = OCGetResourceUri(handle);
+ uint8_t numElement;
+ if (OC_STACK_OK == OCGetNumberOfResourceTypes(handle, &numElement))
+ {
+ OCStackResult res = createStringLL(numElement, handle, OCGetResourceTypeName, &rt);
+ if (res != OC_STACK_OK || !rt)
+ {
+ va_end(arguments);
+ goto no_memory;
+ }
+ }
+
+ if (OC_STACK_OK == OCGetNumberOfResourceTypes(handle, &numElement))
+ {
+ OCStackResult res = createStringLL(numElement, handle, OCGetResourceInterfaceName, &itf);
+ if (res != OC_STACK_OK || !itf)
+ {
+ va_end(arguments);
+ goto no_memory;
+ }
+ }
+
+ mt = (OCStringLL *)OICCalloc(1, sizeof(OCStringLL));
+ if (!mt)
+ {
+ va_end(arguments);
+ goto no_memory;
+ }
+ mt->value = OICStrdup("application/json");
+ if (!mt->value)
+ {
+ va_end(arguments);
+ goto no_memory;
+ }
+
+ if (!linksPayload)
+ {
+ linksPayload = OCCopyLinksResources(uri, rt, itf, NULL, 0, NULL,
+ NULL, j, mt);;
+ if (!linksPayload)
+ {
+ goto no_memory;
+ }
+ }
+ else
+ {
+ OCLinksPayload *temp = linksPayload;
+ while (temp->next)
+ {
+ temp = temp->next;
+ }
+ temp->next = OCCopyLinksResources(uri, rt, itf, NULL, 0, NULL,
+ NULL, j, mt);
+ if (!temp->next)
+ {
+ goto no_memory;
+ }
+ }
+ OCFreeOCStringLL(rt);
+ OCFreeOCStringLL(itf);
+ OCFreeOCStringLL(mt);
+ }
+ }
+ va_end(arguments);
+
+ rdPayload->rdPublish = OCCopyCollectionResource(tagsPayload, linksPayload);
+ if (!rdPayload->rdPublish)
+ {
+ goto no_memory;
+ }
+
+ OCDevAddr rdAddr = { 0 };
+ OICStrcpy(rdAddr.addr, MAX_ADDR_STR_SIZE, addr);
+ rdAddr.port = port;
+
+ OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+
+ return sendRequest(OC_REST_POST, targetUri, &rdAddr, (OCPayload *)rdPayload, cbData);
+
+no_memory:
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ OCFreeOCStringLL(rt);
+ OCFreeOCStringLL(itf);
+ OCFreeOCStringLL(mt);
+ OCFreeTagsResource(tagsPayload);
+ OCFreeLinksResource(linksPayload);
+ OCRDPayloadDestroy(rdPayload);
+ return OC_STACK_NO_MEMORY;
+}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "rd_server.h"
+
+#include "rd_storage.h"
+
+#include "rdpayload.h"
+#include "payload_logging.h"
+
+#define TAG PCF("RDServer")
+
+// This is temporary hardcoded value for bias factor.
+#define OC_RD_DISC_SEL 100
+
+static OCStackResult sendResponse(const OCEntityHandlerRequest *ehRequest, OCRDPayload *rdPayload)
+{
+ OCEntityHandlerResponse response = { 0 };
+ response.requestHandle = ehRequest->requestHandle;
+ response.resourceHandle = ehRequest->resource;
+ response.ehResult = OC_EH_OK;
+ response.payload = (OCPayload*)(rdPayload);
+ return OCDoResponse(&response);
+}
+
+/**
+ * This internal method handles RD discovery request.
+ * Responds with the RD discovery payload message.
+ */
+static OCEntityHandlerResult handleGetRequest(const OCEntityHandlerRequest *ehRequest)
+{
+ if (!ehRequest)
+ {
+ OC_LOG(DEBUG, TAG, "Invalid request pointer.");
+ return OC_EH_ERROR;
+ }
+
+ OCEntityHandlerResult ehResult = OC_EH_OK;
+ OC_LOG_V(DEBUG, TAG, "Received OC_REST_GET from client with query: %s.", ehRequest->query);
+
+ OCRDPayload *rdPayload = OCRDPayloadCreate();
+ if (!rdPayload)
+ {
+ return OC_STACK_NO_MEMORY;
+ }
+
+ rdPayload->rdDiscovery = OCRDDiscoveryPayloadCreate(NULL, OCGetServerInstanceIDString(), OC_RD_DISC_SEL);
+ if (!rdPayload->rdDiscovery)
+ {
+ OCRDPayloadDestroy(rdPayload);
+ return OC_STACK_NO_MEMORY;
+ }
+
+ OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+
+ if (sendResponse(ehRequest, rdPayload) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Sending response failed.");
+ ehResult = OC_EH_ERROR;
+ }
+
+ return ehResult;
+}
+
+/**
+ * This internal method handles RD publish request.
+ * Responds with the RD success message.
+ */
+static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *ehRequest)
+{
+ OCEntityHandlerResult ehResult = OC_EH_OK;
+
+ if (!ehRequest)
+ {
+ OC_LOG(DEBUG, TAG, "Invalid request pointer");
+ return OC_EH_ERROR;
+ }
+
+ OC_LOG_V(DEBUG, TAG, "Received OC_REST_PUT from client with query: %s.", ehRequest->query);
+
+ OCRDPayload *payload = (OCRDPayload *)ehRequest->payload;
+ if (payload && payload->rdPublish)
+ {
+ OCRDStorePublishedResources(payload->rdPublish);
+ }
+
+ OCRDPayload *rdPayload = OCRDPayloadCreate();
+ if (!rdPayload)
+ {
+ OC_LOG(ERROR, TAG, "Failed allocating memory.");
+ return OC_STACK_NO_MEMORY;
+ }
+
+ OC_LOG_PAYLOAD(DEBUG, (OCPayload *) rdPayload);
+
+ if (sendResponse(ehRequest, rdPayload) != OC_STACK_OK)
+ {
+ OC_LOG(ERROR, TAG, "Sending response failed.");
+ ehResult = OC_EH_ERROR;
+ }
+
+ return ehResult;
+}
+
+/*
+ * This internal method is the entity handler for RD resources and
+ * will handle REST request (GET/PUT/POST/DEL) for them.
+ */
+static OCEntityHandlerResult rdEntityHandler(OCEntityHandlerFlag flag,
+ OCEntityHandlerRequest *ehRequest, __attribute__((unused)) void *callbackParameter)
+{
+ OCEntityHandlerResult ehRet = OC_EH_ERROR;
+
+ if (!ehRequest)
+ {
+ return ehRet;
+ }
+
+ if (flag & OC_REQUEST_FLAG)
+ {
+ OC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG.");
+ switch (ehRequest->method)
+ {
+ case OC_REST_GET:
+ case OC_REST_DISCOVER:
+ handleGetRequest(ehRequest);
+ break;
+ case OC_REST_POST:
+ handlePublishRequest(ehRequest);
+ break;
+ case OC_REST_PUT:
+ case OC_REST_DELETE:
+ case OC_REST_OBSERVE:
+ case OC_REST_OBSERVE_ALL:
+ case OC_REST_CANCEL_OBSERVE:
+ case OC_REST_PRESENCE:
+ case OC_REST_NOMETHOD:
+ break;
+ }
+ }
+
+ return ehRet;
+}
+
+/**
+ * Registers RD resource
+ */
+OCStackResult OCRDStart()
+{
+ OCResourceHandle rdHandle = NULL;
+
+ OCStackResult result = OCCreateResource(&rdHandle,
+ OC_RSRVD_RESOURCE_TYPE_RD,
+ OC_RSRVD_INTERFACE_DEFAULT,
+ OC_RSRVD_RD_URI,
+ rdEntityHandler,
+ NULL,
+ (OC_ACTIVE | OC_DISCOVERABLE | OC_OBSERVABLE));
+
+ if (result == OC_STACK_OK)
+ {
+ OC_LOG(DEBUG, TAG, "Resource Directory Started.");
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, "Failed starting Resource Directory.");
+ }
+
+ return result;
+}
+
+/**
+ * Stops resource directory server
+ */
+OCStackResult OCRDStop()
+{
+ OCStackResult result = OCStop();
+
+ if (result == OC_STACK_OK)
+ {
+ OC_LOG(DEBUG, TAG, "Resource Directory Stopped.");
+ }
+ else
+ {
+ OC_LOG(ERROR, TAG, "Failed stopping Resource Directory.");
+ }
+ return result;
+}
SConscript('src/common/SConscript')
SConscript('src/serverBuilder/SConscript')
-SConscript('src/resourceContainer/SConscript')
######################################################################
#building Resource client, resourceBroker and resourceCache
RESOURCECLIENT_DIR + 'RCSDiscoveryManager.cpp',
RESOURCECLIENT_DIR + 'RCSDiscoveryManagerImpl.cpp',
RESOURCECLIENT_DIR + 'RCSRemoteResourceObject.cpp'
- ]
+ ]
ResourceClientsdk_static = resourceClient_env.StaticLibrary('rcs_client', client_src)
ResourceClientsdk_shared = resourceClient_env.SharedLibrary('rcs_client', client_src)
resourceClient_env.UserInstallTargetHeader('include/RCSRemoteResourceObject.h', 'service/resource-encapsulation', 'RCSRemoteResourceObject.h')
resourceClient_env.UserInstallTargetHeader('include/RCSResourceAttributes.h', 'service/resource-encapsulation', 'RCSResourceAttributes.h')
resourceClient_env.UserInstallTargetHeader('include/RCSResourceObject.h', 'service/resource-encapsulation', 'RCSResourceObject.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSBundleInfo.h', 'service/resource-encapsulation', 'RCSBundleInfo.h')
resourceClient_env.UserInstallTargetHeader('include/RCSException.h', 'service/resource-encapsulation', 'RCSException.h')
resourceClient_env.UserInstallTargetHeader('include/RCSRequest.h', 'service/resource-encapsulation', 'RCSRequest.h')
-resourceClient_env.UserInstallTargetHeader('include/RCSResourceContainer.h', 'service/resource-encapsulation', 'RCSResourceContainer.h')
resourceClient_env.UserInstallTargetHeader('include/RCSResponse.h', 'service/resource-encapsulation', 'RCSResponse.h')
######################################################################
SConscript('unittests/SConscript')
SConscript('src/resourceCache/unittests/SConscript')
SConscript('src/resourceBroker/unittest/SConscript')
- SConscript('src/resourceClient/unittests/SConscript')
if target_os == 'android':
- SConscript('android/SConscript')
+ SConscript('android/SConscript')
\ No newline at end of file
def ensure_libs(target, source, env):
return target, [source, env.get('BUILD_DIR') + 'librcs_server.so',
- env.get('BUILD_DIR') + 'librcs_client.so',
- env.get('BUILD_DIR') + 'librcs_container.so']
+ env.get('BUILD_DIR') + 'librcs_client.so']
jdk_env = Environment(ENV=os.environ)
jdk_env['BUILDERS']['Gradle'] = Builder(action = env.get('ANDROID_GRADLE') +
System.loadLibrary("rcs_client");
System.loadLibrary("rcs_server");
System.loadLibrary("rcs_common");
- System.loadLibrary("rcs_container");
System.loadLibrary("rcs_jni");
}
import java.util.Map;
import java.util.Set;
+import org.iotivity.service.server.RcsLockedAttributes;
+
/**
*
- * RCSResourceAttributes represents the attributes for a resource.
+ * This class represents the attributes for a resource.
*
* @see RcsValue
*/
public RcsResourceAttributes() {
}
+ public RcsResourceAttributes(RcsLockedAttributes lockedAttrs)
+ throws RcsException {
+ for (final String key : lockedAttrs.keySet()) {
+ mCache.put(key, lockedAttrs.get(key));
+ }
+ }
+
/**
* Returns a unmodifiable Set view of the keys contained in this attributes.
*
* If the object previously contained a mapping for the key, the old value
* is replaced by the specified value.
*
- *
* @param key
* key with which the specified value is to be associated
*
* @param value
* value to be associated with the specified key
*
+ * @throws NullPointerException
+ * if key or value is null
+ *
*/
public void put(String key, RcsValue value) {
if (key == null) throw new NullPointerException("key is null");
if (hasHandle()) nativeRemove(key);
}
+ /**
+ * Sets the specified value with the specified key.
+ * If the object previously contained a mapping for the key, the old value
+ * is replaced by the specified value.
+ *
+ * @param key
+ * key with which the specified value is to be associated
+ *
+ * @param value
+ * value to be associated with the specified key
+ *
+ * @throws NullPointerException
+ * if key or value is null
+ * @throws IllegalArgumentException
+ * if object is not supported type by {@link RcsValue}
+ */
public void put(String key, Object object) {
+ if (key == null) throw new NullPointerException("key is null");
+
put(key, new RcsValue(object));
}
* key whose presence is to be tested
*
* @return true if this contains a mapping for the specified key.
+ *
+ * @throws NullPointerException
+ * if key is null
*/
public boolean contains(String key) {
if (key == null) throw new NullPointerException("key is null");
*
* Type helps identify type information of Value.
*
- * @see RCSResourceAttributes
+ * @see RcsResourceAttributes
* @see Type
*/
public final class RcsValue {
/**
* A Helper class to identify types of Value.
*
- * @see RCSResourceAttributes
- * @see Value
+ * @see RcsResourceAttributes
+ * @see RcsValue
* @see TypeId
*/
public static class Type {
*
* @return Identifier of type
*
- * @see getBaseTypeId
+ * @see #getBaseTypeId(RcsValue.Type)
*/
- public final TypeId getTypeId() {
+ public final TypeId getId() {
return mTypeId;
}
/**
* Returns the type identifier of a base type of sequence.
*
- * For non sequence types, it is equivalent to calling getId.
+ * For non sequence types, it is equivalent to calling {@link #getId()}.
*
* @return identifier of type
*
/**
* Factory method to create Type instance from an object.
+ * Note that object must be a supported type by RcsValue.
*
* @return An instance that has TypeId for obj.
*
- * @note object must be a supported type by Value.
- *
* @throws NullPointerException
* if obj is null.
* @throws IllegalArgumentException
}
/**
- * Factory method to create Type instance from a clss.
+ * Factory method to create Type instance from a class.
+ * Note that class must be a supported type by RcsValue.
*
* @return An instance that has TypeId for class.
*
- * @note class must be a supported type by Value.
- *
* @throws NullPointerException
* if cls is null.
* @throws IllegalArgumentException
}
/**
- * Constructs a new value that holds null value.
+ * Constructs a new value that holds a boolean value.
*
* @param value
* a boolean
}
/**
- * Returns the value it represents is null.
+ * Returns whether the value is null.
*
* @return true if the value is null.
*/
}
/**
- * Returns the object represents null for RcsValue.
+ * Returns whether the object represents null for RcsValue.
*
* @param o
* an object to be tested
package org.iotivity.service.client;
/**
- * This class provides a set of APIs for constructing RCSAddress object.
- *
- * <p>
- * RCSAddress object is the first parameter for Discover Resource APIs of
- * RCSDiscoveryManager Class.
- * <p>
- * {@link RcsDiscoveryManager}
+ * This is to specify a target address to discover.
+ *
+ * @see RcsDiscoveryManager
*/
public final class RcsAddress {
private final String mAddress;
System.loadLibrary("rcs_client");
System.loadLibrary("rcs_server");
System.loadLibrary("rcs_common");
- System.loadLibrary("rcs_container");
System.loadLibrary("rcs_jni");
}
+ /**
+ * This represents a task for discovery.
+ *
+ * The task must be canceled if no longer needed.
+ *
+ */
public static class DiscoveryTask extends RcsObject {
private DiscoveryTask() {
}
*
* @param address
* the target address
+ * @param listener
+ * the listener to be invoked when a resource is discovered
*
* @return a task object indicating this request.
*
* the target address
* @param uri
* the relative uri of resource to be searched
- *
+ * @param listener
+ * the listener to be invoked when a resource is discovered
+ *
* @return a task object indicating this request.
*
* @throws RcsPlatformException
* the target address
* @param resourceType
* the resource type
+ * @param listener
+ * the listener to be invoked when a resource is discovered
*
* @return a task object indicating this request.
*
* the relative uri of resource to be searched
* @param resourceType
* the resource type
+ * @param listener
+ * the listener to be invoked when a resource is discovered
*
* @return a task object indicating this request.
*
import org.iotivity.service.RcsPlatformException;
import org.iotivity.service.RcsResourceAttributes;
import org.iotivity.service.RcsValue;
-import org.iotivity.service.server.RcsResourceObject;
/**
*
/**
* This represents states of monitoring.
*
- * @see #startMonitoring()
+ * @see #startMonitoring(OnStateChangedListener)
* @see #getState()
* @see OnStateChangedListener
*
*/
public enum ResourceState {
+ /** Monitoring is not started. */
+ NONE,
+
+ /**
+ * Monitoring is started and checking state is in progress.
+ * This is the default state after startMonitoring.
+ */
+ REQUESTED,
+
+ /** The resource is alive. */
+ ALIVE,
- NONE, /** < Monitoring is not started. */
- REQUESTED, /**
- * < Monitoring is started and checking state is in progress.
- * This is the default state after startMonitoring.
- */
- ALIVE, /** < The resource is alive. */
- LOST_SIGNAL, /** < Failed to reach the resource. */
- DESTROYED /** < The resource is deleted. */
+ /** Failed to reach the resource. */
+ LOST_SIGNAL,
+
+ /** The resource is deleted. */
+ DESTROYED
}
/**
* @see #getCacheState()
*/
public enum CacheState {
+ /** Caching is not started. */
+ NONE,
+
+ /**
+ * Caching is started, but the data is not ready yet. This is
+ * the default state after startCaching.
+ */
+ UNREADY,
- NONE, /** < Caching is not started. */
- UNREADY, /**
- * < Caching is started, but the data is not ready yet. This is
- * the default state after startCaching.
- */
- READY, /** < The data is ready. */
- LOST_SIGNAL /** < Failed to reach the resource. */
+ /** The data is ready. */
+ READY,
+
+ /** Failed to reach the resource. */
+ LOST_SIGNAL
}
/**
* @throws RcsDestroyedObjectException
* if the object is already destroyed
*
- * @see RcsResourceObject.Builder#setObservable(boolean)
+ * @see org.iotivity.service.server.RcsResourceObject.Builder#setObservable(boolean)
*/
public boolean isObservable() throws RcsException {
assertAlive();
* This will start data caching for the resource. Once caching started it
* will look for the data updation on the resource and updates the cache
* data accordingly.
- *
- * It is equivalent to calling startCaching(CacheUpdatedCallback) with null.
+ * <p>
+ * It is equivalent to calling {@link #startCaching(OnCacheUpdatedListener)}
+ * with null.
*
* @throws RcsDestroyedObjectException
* if the object is already destroyed
/**
* Returns whether cached data is available.
*
- * Cache will be available always once cache state had been READY even if
- * current state is LOST_SIGNAL.
+ * Cache will be available always once cache state had been
+ * {@link CacheState#READY} even if current state is
+ * {@link CacheState#LOST_SIGNAL} until stopped.
*
* @return true if cache data is available.
*
/**
* Returns the cached attributes.
- * This works only when cache is available.
+ * <p>
+ * Note that this works only when cache is available.
*
* @return the cached attributes.
*
/**
* Returns the cached value to which the specified key is mapped, or null if
- * RcsResourceAttributes contains no mapping for the key.
- *
- * This works only when cache is available.
+ * no mapping for the key.
+ * <p>
+ * Note that this works only when cache is available.
*
* @param key
* the key whose associated value is to be returned
}
/**
- * Sends a request for the resource attributes directly to the server.
+ * Sends a request for the resource attributes directly to the resource.
*
* @param listener
* the listener to receive the response
}
/**
- * Sends a set request with resource attributes to the server.
- *
+ * Sends a set request with resource attributes to the resource.
+ * <p>
* The SetRequest behavior depends on the server, whether updating its
* attributes or not.
*
import org.iotivity.service.RcsResourceAttributes;
/**
- * This class provides methods to create the response for a received get
- * request.
+ * This class provides methods to create the response for a get request.
*
* @see RcsResourceObject
* @see RcsSetResponse
public class RcsGetResponse extends RcsResponse {
/**
- * Creates a default RcsResourceObject. The response will have
- * RCSResponse.DEFAULT_ERROR_CODE for the errorCode. The attributes of
- * RCSResourceObject will be set as the result attributes.
+ * Creates a default RCcsGetResponse. The response will have
+ * {@link #DEFAULT_ERROR_CODE} for the errorCode. The attributes of
+ * {@link RcsResourceObject} will be set as the result attributes.
*
*/
public static RcsGetResponse defaultAction() {
}
/**
- * Creates a RcsResourceObject with error code passed. The
- * attributes of the RCSResourceObject will be set as the result attributes.
+ * Creates a RcsGetResponse with error code passed. The
+ * attributes of the {@link RcsResourceObject} will be set as the result
+ * attributes.
*
* @param errorCode
- * The error code to set in response.
+ * error code to be set in response
*
*/
public static RcsGetResponse create(int errorCode) {
}
/**
- * Creates a RcsResourceObject with custom attributes. This sends the passed
+ * Creates a RcsGetResponse with custom attributes and
+ * {@link #DEFAULT_ERROR_CODE} for the errorCode. This sends the passed
* attributes as the result attributes instead of the one the
- * RCSResourceObject holds.
+ * {@link RcsResourceObject} holds.
*
* @param attributes
- * The attributes to send in response.
+ * attributes to be sent as the result
*
*/
public static RcsGetResponse create(RcsResourceAttributes attributes) {
}
/**
- * Creates a RcsResourceObject with error code passed. This sends
+ * Creates a RcsGetResponse with error code passed. This sends
* the passed attributes as the result attributes instead of one the
- * RCSResourceObject holds.
+ * {@link RcsResourceObject} holds.
*
* @param attributes
- * The attributes to send in response.
+ * attributes to be sent as the result
* @param errorCode
- * The error code for response.
+ * error code for response
*
*/
public static RcsGetResponse create(RcsResourceAttributes attributes,
}
}
+ /**
+ * Returns a unmodifiable Set view of the keys contained in this attributes.
+ *
+ * @return an unmodifiable set view of the keys in this attributes
+ *
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
+ */
public Set<String> keySet() throws RcsException {
ensureLocked();
return Collections.unmodifiableSet(keySet);
}
+ /**
+ * Returns the value to which the specified key is mapped, or null if this
+ * contains no mapping for the key.
+ *
+ * @param key
+ * the key whose associated value is to be returned
+ *
+ * @return the value to which the specified key is mapped, or null if this
+ * contains no mapping for the key
+ *
+ * @throws NullPointerException
+ * if key is null
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
+ */
public RcsValue get(String key) throws RcsException {
ensureLocked();
return mCache.get(key);
}
- public RcsLockedAttributes putAll(RcsResourceAttributes attributes) {
+ /**
+ * Copies all of the mappings from the specified to this
+ *
+ * @param attributes
+ * attributes to be copied
+ *
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
+ *
+ */
+ public RcsLockedAttributes putAll(RcsResourceAttributes attributes)
+ throws RcsException {
+ ensureLocked();
+
final Set<String> keys = attributes.keySet();
for (final String k : keys) {
}
/**
- * set a attribute value.
+ * Sets the specified value with the specified key.
+ * If the object previously contained a mapping for the key, the old value
+ * is replaced by the specified value.
*
* @param key
- * - Key of the element to be added.
+ * key with which the specified value is to be associated
*
* @param value
- * - value to be set.
+ * value to be associated with the specified key
+ *
+ * @throws NullPointerException
+ * if key or value is null
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
*
*/
public RcsLockedAttributes put(String key, RcsValue value)
}
/**
+ * Sets the specified value with the specified key.
+ * If the object previously contained a mapping for the key, the old value
+ * is replaced by the specified value.
+ *
+ * @param key
+ * key with which the specified value is to be associated
+ *
+ * @param value
+ * value to be associated with the specified key
+ *
+ * @throws NullPointerException
+ * if key or value is null
+ * @throws IllegalArgumentException
+ * if object is not supported type by {@link RcsValue}
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
+ */
+ public void put(String key, Object value) throws RcsException {
+ if (key == null) throw new NullPointerException("key is null");
+
+ put(key, new RcsValue(value));
+ }
+
+ /**
* Returns whether attribute is empty.
*
- * @return boolean
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
*/
public boolean isEmpty() throws RcsException {
ensureLocked();
}
/**
- * Returns the number of elements.
+ * Returns the number of key-value mappings.
*
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
*/
public int size() throws RcsException {
ensureLocked();
}
/**
- * Removes a single attribute
+ * Removes the mapping for a key from this attributes if it is present.
*
* @param key
- * Key to be removed.
+ * key whose mapping is to be removed
+ *
+ * @return true if the key is present and the the value mapped is removed.
*
- * @return true if an attribute is removed, false otherwise.
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
*/
public boolean remove(String key) throws RcsException {
ensureLocked();
return cacheRemove || nativeRemove;
}
- public void clear() {
+ /**
+ * Removes all elements.
+ *
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
+ */
+ public void clear() throws RcsException {
+ ensureLocked();
+
nativeClear(mResourceObject);
}
/**
- * Checks the container has an attribute with a Key equivalent to the
- * provided key.
+ * Returns true if this contains a mapping for the specified key.
*
* @param key
- * Key to check.
+ * key whose presence is to be tested
+ *
+ * @return true if this contains a mapping for the specified key.
*
- * @return true if an attribute with requests key exists, false otherwise.
+ * @throws NullPointerException
+ * if key is null
+ * @throws RcsUnlockedException
+ * if the {@link RcsResourceObject.AttributesLock} for this
+ * object is unlocked
*/
public boolean contains(String key) throws RcsException {
ensureLocked();
* <p>
* It also provides an auto notification mechanism that notifies to the
* observers. Requests are handled automatically by defaultAction of
- * RCSGetResponse and RCSSetResponse. Developer can override them and send your
- * own response.
+ * {@link RcsGetResponse} and {@link RcsSetResponse}. You can override them and
+ * send your own response with {@link GetRequestHandler} and
+ * {@link SetRequestHandler}.
* <p>
- * For simple resources, developer may want to know whenever attributes are
- * changed by a set request. In this case, add an AttributeUpdatedListener with
- * a key interested in instead of overriding SetRequestHandler.
+ * For simple resources, they are simply required to notify whenever attributes
+ * are changed by a set request. In this case, add an
+ * {@link OnAttributeUpdatedListener} with a key interested in instead of
+ * overriding {@link SetRequestHandler}.
*
* @see Builder
*/
public final class RcsResourceObject extends RcsObject {
/**
- * This class provides APIs for resource creation, setting properties and
- * attributes for the constructed resource. It provides the build() API
- * which
- * builds a resource and returns RCSResourceObject.
+ * This is a builder to create resource with properties and attributes.
+ *
+ * The resource will be observable and discoverable by default, to make them
+ * disable
+ * set these properties explicitly with setDiscoverable and setObservable.
*
- * {@link RcsResourceObject}
*/
public static class Builder {
private final String mUri;
private RcsResourceAttributes mAttributes;
/**
- * Constructor
+ * Constructs a Builder.
*
* @param uri
- * Resource URI value to be set
+ * resource uri
* @param resourceType
- * Resource type value to be set
+ * resource type
* @param resourceInterface
- * Interface value to be set
+ * resource interface
*
* @throws NullPointerException
- * If any parameter is null.
+ * if any parameter is null
*/
public Builder(String uri, String resourceType,
String resourceInterface) {
-
if (uri == null) {
throw new NullPointerException("uri is null.");
}
}
/**
- * Sets the discoverable(OC_DISCOVERABLE) property for the resource.
+ * Sets whether the resource is discoverable.
*
* @param isDiscoverable
- * Whether to be discovered or not
+ * whether to be discoverable or not
*
*/
public Builder setDiscoverable(boolean isDiscoverable) {
* Sets the observable(OC_OBSERVABLE) property of the resource.
*
* @param isObservable
- * Whether to be observed or not
+ * whether to be observable or not
*
*/
public Builder setObservable(boolean isObservable) {
}
/**
- * API for setting attributes of the resource.
- *
- * @param attributes
- * Attributes to set
+ * Sets attributes foe the resource.
*
*/
public Builder setAttributes(RcsResourceAttributes attributes) {
}
/**
- * Creates a RCSResourceObject.
+ * Register a resource and returns a RCSResourceObject.
*
* @throws RcsPlatformException
* If registering a resource is failed.
* {@code
* AttributesLock lock = rcsResourceObject.getAttributesLock();
*
- * try
- * {
+ * try {
* lock.lock();
*
* ....
* } finally {
* lock.unlock();
* }
+ * }
* </pre>
*/
public static class AttributesLock {
}
private RcsResourceObject ensureResourceObject() throws RcsException {
-
final RcsResourceObject object = mResourceObjectRef.get();
+
if (object == null || object.isDestroyed()) {
throw new RcsDestroyedObjectException(
"The object is already destroyed!");
* @return Locked attributes.
*
* @throws RcsException
- * If the RcsResourceObject is destroyed.
+ * if the RcsResourceObject is destroyed
*/
public RcsLockedAttributes lock() throws RcsException {
return mCurrentAttributes = new RcsLockedAttributes(
* Applies the modified attributes to the RcsResourceObject.
*
* @throws RcsIllegalStateException
- * If not in locked state.
+ * if not in locked state
*/
public void apply() throws RcsIllegalStateException {
if (mCurrentAttributes == null) {
/**
* Represents the policy of AutoNotify function of RCSResourceObject class
- * In accord with this policy, observers are notified of attributes that are
+ * In accord with this, observers are notified of attributes that are
* changed or updated.
*
* <p>
* Attributes are changed or updated according to execution of some
- * functions or receipt of 'set-request'.
+ * functions which modify attributes or receipt of set requests.
+ *
+ * @see setAttribute
+ * @see removeAttribute
+ * @see getAttributesLock
*
- * {@link RcsResourceObject}
*/
public enum AutoNotifyPolicy {
- NEVER, /** < Never notify. */
- ALWAYS, /** < Always notify. */
- UPDATED;
- /** < When attributes are changed, notify. */
+ /** Never */
+ NEVER,
+
+ /** Always */
+ ALWAYS,
+
+ /** When attributes are changed */
+ UPDATED
}
+ /**
+ * Represents the policy of set-request handler.
+ * In accord with this, the RCSResourceObject decides whether a set-request
+ * is
+ * acceptable or not.
+ */
public enum SetRequestHandlerPolicy {
+ /**
+ * Requests will be ignored if attributes of the request contain
+ * a new key or a value that has different type from the current
+ * value of the key.
+ */
+ NEVER,
- NEVER, /**
- * < Server ignore when server is received set-request of
- * attributes of the new key.
- */
- ACCEPT;
/**
- * < Server creates attributes of the new key When server is received
- * set-request of attributes of the new key.
+ * The attributes of the request will be applied unconditionally
+ * even if there are new name or type conflicts.
*/
+ ACCEPT
}
/**
* Interface definition for a handler to be invoked when a get request is
* received.
+ * <p>
+ * The handler will be called first when a get request is received, before
+ * the RCSResourceObject handles.
+ *
+ * @see setGetRequestHandler
*/
public interface GetRequestHandler {
/**
* Interface definition for a handler to be invoked when a set request is
* received.
+ * <p>
+ * The handler will be called first when a get request is received, before
+ * the RCSResourceObject handles. If the attributes are modified in the
+ * callback, the modified attributes will be set in the RCSResourceObject if
+ * the request is not ignored.
+ *
+ * @see setGetRequestHandler
*/
public interface SetRequestHandler {
* Called when received a set request from the client.
*
* @param request
- * Request information.
+ * request information
* @param attributes
- * The attributes of the request.
- * It will be applied to the RcsResourceObject.
+ * the attributes of the request.
+ * it will be applied to the RcsResourceObject
*
* @return A response indicating how to handle this request.
*
* Called when an attribute value is updated.
*
* @param oldValue
- * The attribute value before updated.
+ * the attribute value before updated
* @param newValue
- * The current resource attribute value.
+ * the current resource attribute value
*/
void onAttributeUpdated(RcsValue oldValue, RcsValue newValue);
}
}
/**
- * Sets a particular attribute value as a integer.
- * The thread-safety for attributes is taken care internally.
+ * Sets a particular attribute value.
*
* @param key
- * name of attribute(used to map the attribute value).
+ * key with which the specified value is to be associated
* @param value
- * value to be mapped against the key.
+ * value to be associated with the specified key
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
* @throws NullPointerException
- * If key or value is null.
+ * if key or value is null
*
*/
public void setAttribute(String key, RcsValue value) throws RcsException {
/**
* Returns a copied attribute value associated with the supplied key.
- * The thread-safety for attributes is taken care internally.
*
* @param key
- * key of an attribute.
+ * the key whose associated value is to be returned
*
- * @return An attributes value.
+ * @return the value to which the specified key is mapped, or null if no
+ * attribute for the key
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
* @throws NullPointerException
- * If key is null.
+ * if key is null
*/
public RcsValue getAttributeValue(String key) throws RcsException {
assertAlive();
}
/**
- * API for removing a particular attribute of the resource.
- * The thread-safety for attributes is taken care internally.
+ * Removes the mapping for a key from the attributes if it is present.
*
* @param key
- * Name of the attribute.
+ * key whose mapping is to be removed
*
- * @return If the key exist and matched attribute is deleted, return true.
+ * @return true if the key is present and the the value mapped is removed.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
* @throws NullPointerException
- * If key is null.
+ * if key is null
*/
public boolean removeAttribute(String key) throws RcsException {
assertAlive();
}
/**
- * API for checking whether a particular attribute is there for a resource
- * or not.
- * The thread-safety for attributes is taken care internally.
+ * Returns true if the attributes contains a mapping for the specified key.
*
* @param key
- * Name of the attribute.
+ * key whose presence is to be tested
*
- * @return If the key exist, return true.
+ * @return true if the attributes contains a mapping for the specified key.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
* @throws NullPointerException
- * If key is null.
+ * if key is null
*/
public boolean containsAttribute(String key) throws RcsException {
assertAlive();
/**
* Returns a copied attributes of the RCSResourceObject.
- * To modify the attributes, use AttrbutesLock.
+ * To modify the attributes, use {@link AttributesLock}.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*
* @see getAttributesLock
*/
}
/**
- * Returns the AttributesLock for this RcsResourceObject.
+ * Returns an AttributesLock for this RcsResourceObject.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*/
public AttributesLock getAttributesLock() throws RcsException {
assertAlive();
}
/**
- * API for checking whether the particular resource is observable or not.
- *
- * @return true if this is observable. Otherwise false.
+ * Checks whether the resource is observable or not.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*/
public boolean isObservable() throws RcsException {
assertAlive();
}
/**
- * API for checking whether the particular resource is discoverable or not.
+ * Checks whether the resource is discoverable or not.
*
- * @return true if this is discoverable. Otherwise false.
- *
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*/
public boolean isDiscoverable() throws RcsException {
assertAlive();
}
/**
- * API for setting the resource's get request handler by the
- * developer/application. If developer set this handler then all get request
- * will come to the application and developer can send the response to the
- * client using APIs of RCSGetResponse class.
+ * Sets the get request handler. To remove handler, pass null.
+ *
+ * Default behavior is {@link RcsGetResponse#defaultAction()}.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*/
public void setGetRequestHandler(GetRequestHandler handler)
throws RcsException {
}
/**
- * API for setting the resource's set request handler by the
- * developer/application. If developer set this handler then all set request
- * will come to the application and developer can send the response to the
- * client using APIs of RCSSetResponse class.
+ * Sets the set request handler. To remove handler, pass null.
*
- * @throws RcsException
- * If the object is destroyed.
+ * Default behavior is {@link RcsSetResponse#defaultAction()}.
+ *
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*
*/
public void setSetRequestHandler(SetRequestHandler handler)
}
/**
- * API for setting the Listener for a particular attribute update.
+ * Adds a listener for a particular attribute updated.
*
* @param key
- * The interested attribute's key
+ * the interested attribute's key
+ * @param listener
+ * listener to be invoked
*
* @throws NullPointerException
- * If key or listener is null.
- *
- * @throws RcsException
- * If the object is destroyed.
+ * if key or listener is null
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*/
public void addAttributeUpdatedListener(String key,
OnAttributeUpdatedListener listener) throws RcsException {
}
/**
- * API for removing the handler for a particular attribute update.
+ * Removes a listener for a particular attribute updated.
*
* @param key
- * The interested attribute's key
+ * key the key associated with the listener to be removed
*
- * @return true if the requested attribute is removed successfully.
- * Otherwise false.
+ * @return true if the listener added with same key exists and is removed.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
* @throws NullPointerException
- * If key is null.
+ * if key is null
*/
public boolean removeAttributeUpdatedListener(String key)
throws RcsException {
}
/**
- * API for notifying all observers of the RCSResourceObject with the updated
- * attributes value
+ * Notifies all observers of the current attributes.
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
* @throws RcsPlatformException
- * If the operation failed.
+ * if the operation failed
*/
public void notifyObservers() throws RcsException {
assertAlive();
}
/**
- * API for setting Auto notify policy
+ * Sets auto notify policy
*
* @param policy
* policy to be set
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*
*/
public void setAutoNotifyPolicy(AutoNotifyPolicy policy)
}
/**
- * API for getting auto notify policy
+ * Returns the current policy
*
- * @return AntoNotify policy
- *
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*
*/
public AutoNotifyPolicy getAutoNotifyPolicy() throws RcsException {
}
/**
- * API for setting the policy for a setRequestHandler.
+ * Sets the policy for handling a set request.
*
* @param policy
* policy to be set
*
- * @throws RcsException
- * If the object is destroyed.
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*
*/
public void setSetRequestHandlerPolicy(SetRequestHandlerPolicy policy)
}
/**
- * API for getting the SetRequestHandler Policy.
- *
- * @return Property of setRequesthandler
- *
- * @throws RcsException
- * If the object is destroyed.
+ * Returns the current policy.
*
+ * @throws RcsDestroyedObjectException
+ * if the object is destroyed
*/
public SetRequestHandlerPolicy getSetRequestHandlerPolicy()
throws RcsException {
import org.iotivity.service.RcsResourceAttributes;
-public class RcsResponse {
+class RcsResponse {
private native static int nativeGetDefaultErrorCode();
public static final int DEFAULT_ERROR_CODE;
/**
* Options for handling a set request.
*
- * This overrides RcsResourceObject#SetRequestHandlerPolicy.
- *
- * @see RcsResourceObject#SetRequestHandlerPolicy
+ * This overrides {@link RcsResourceObject.SetRequestHandlerPolicy}.
*
*/
public enum AcceptanceMethod {
/**
- * Follow RcsResourceObject#SetRequestHandlerPolicy.
+ * Follow {@link RcsResourceObject.SetRequestHandlerPolicy}.
*/
DEFAULT,
private AcceptanceMethod mAcceptanceMethod = AcceptanceMethod.DEFAULT;
/**
- * Creates a default RCSSetResponse with DEFAULT acceptance method. The
- * response will have RCSResponse.DEFAULT_ERROR_CODE for the errorCode. The
- * attributes of RCSResourceObject will be set as the result attributes.
+ * Creates a default RcsSetResponse with {@link AcceptanceMethod#DEFAULT}.
+ * The response will have {@link #DEFAULT_ERROR_CODE} for the errorCode. The
+ * attributes of {@link RcsResourceObject} will be set as the result
+ * attributes.
*
*/
public static RcsSetResponse defaultAction() {
}
/**
- * Creates a default RCSSetResponse with ACCEPT acceptance method. The
- * response will have RCSResponse.DEFAULT_ERROR_CODE for the errorCode. The
- * attributes of RCSResourceObject will be set as the result attributes.
+ * Creates a default RcsSetResponse with {@link AcceptanceMethod#ACCEPT}
+ * The response will have {@link #DEFAULT_ERROR_CODE} for the errorCode. The
+ * attributes of {@link RcsResourceObject} will be set as the result
+ * attributes.
*
*/
public static RcsSetResponse accept() {
}
/**
- * Creates a RCSSetResponse with ACCEPT acceptance method and error code
- * passed.
- * The attributes of the RCSResourceObject will be set as the result
+ * Creates a RcsSetResponse with {@link AcceptanceMethod#ACCEPT} and error
+ * code passed.
+ * The attributes of the {@link RcsResourceObject} will be set as the result
* attributes.
*
* @param errorCode
- * The error code to set in response.
+ * error code to be set in response
*
*/
public static RcsSetResponse accept(int errorCode) {
}
/**
- * Creates a default RCSSetResponse with IGNORE acceptance method. The
- * response will have RCSResponse.DEFAULT_ERROR_CODE for the errorCode. The
- * attributes of RCSResourceObject will be set as the result attributes.
+ * Creates a default RcsSetResponse with {@link AcceptanceMethod#IGNORE}.
+ * The response will have {@link #DEFAULT_ERROR_CODE} for the errorCode. The
+ * attributes of {@link RcsResourceObject} will be set as the result
+ * attributes.
*
*/
public static RcsSetResponse ignore() {
}
/**
- * Creates a RCSSetResponse with IGNORE acceptance method and
- * error code passed. The attributes of the RCSResourceObject will be set as
- * the result attributes.
+ * Creates a RcsSetResponse with {@link AcceptanceMethod#IGNORE} and error
+ * code passed. The attributes of the {@link RcsResourceObject} will be set
+ * as the result attributes.
*
* @param errorCode
- * The error code to set in response.
+ * error code to be set in response
*
*/
public static RcsSetResponse ignore(int errorCode) {
}
/**
- * Creates a RCSSetResponse with error code passed and has
- * DEFAULT acceptance method. The attributes of the RCSResourceObject will
- * be set as the result attributes.
+ * Creates a RcsSetResponse with error code passed and
+ * {@link AcceptanceMethod#DEFAULT}. The attributes of the
+ * {@link RcsResourceObject} will be set as the result attributes.
*
* @param errorCode
- * The error code to set in response.
+ * error code to be set in response
*
*/
public static RcsSetResponse create(int errorCode) {
}
/**
- * Creates a RCSSetResponse with custom attributes and has DEFAULT
- * acceptance method. This sends the passed attributes as the result
- * attributes instead of one the RCSResourceObject holds.
+ * Creates a RcsSetResponse with custom attributes and
+ * {@link AcceptanceMethod#DEFAULT}. This sends the passed attributes as the
+ * result attributes instead of one the {@link RcsResourceObject} holds.
*
* @param attributes
- * The attributes to send in response.
+ * attributes to be sent as the result
*
*/
public static RcsSetResponse create(RcsResourceAttributes attributes) {
}
/**
+ * Creates a RcsSetResponse with error code passed and
+ * {@link AcceptanceMethod#DEFAULT}. This sends the passed attributes as the
+ * result attributes instead of one the {@link RcsResourceObject} holds.
+ *
+ * @param attributes
+ * attributes to be sent as the result
+ * @param errorCode
+ * error code for response
+ *
+ */
+ public static RcsSetResponse create(RcsResourceAttributes attributes,
+ int errorCode) {
+ return new RcsSetResponse(attributes, errorCode);
+ }
+
+ /**
* Returns the acceptance method.
*
*/
}
/**
- * Sets the acceptance method for the RCSSetResponse.
+ * Sets the acceptance method.
*
* @param method
- * AcceptanceMethod value to set
+ * method to be set
*
- * @return The reference to this RCSSetResponse
+ * @return The reference to this RcsSetResponse
*
*/
public RcsSetResponse setAcceptanceMethod(AcceptanceMethod method) {
return this;
}
- /**
- * Creates a RCSSetResponse with error code passed. This sends
- * the passed attributes as the result attributes instead of one the
- * RCSResourceObject holds.
- *
- * @param attributes
- * The attributes to send in response.
- * @param errorCode
- * The error code for response.
- *
- */
- public static RcsSetResponse create(RcsResourceAttributes attributes,
- int errorCode) {
- return new RcsSetResponse(attributes, errorCode);
- }
-
private RcsSetResponse() {
super();
}
import org.iotivity.service.RcsException;
/**
- * Thrown when trying to access a unlocked RcsLockedAttributes.
+ * Thrown when trying to access a unlocked {@link RcsLockedAttributes}.
*
*/
public class RcsUnlockedException extends RcsException {
JNIEXPORT jobject JNICALL Java_org_iotivity_service_RcsResourceAttributes_nativeExtract
(JNIEnv* env, jobject obj, jstring keyObj)
{
- LOGD("extractAsJavaObject");
+ LOGD("extract");
EXPECT_RET_DEF(keyObj, "Key is null.");
EXPECT_RET_DEF(hasNativeHandle(env, obj), "no native handle.");
VERIFY_NO_EXC_RET_DEF(env);
attrs.erase(key);
+ if (attrs.empty()) releaseNativeHandle(env, obj);
return valueObj;
}
{
part
{
- name: "find_button";
+ name: "button1";
type: SWALLOW;
scale: 1;
description
{
rel1.relative: 0.01 0.01;
- rel2.relative: 0.7 0.09;
+ rel2.relative: 0.5 0.09;
+ }
+ }
+ part
+ {
+ name: "button2";
+ type: SWALLOW;
+ scale: 1;
+ description
+ {
+ rel1.relative: 0.51 0.01;
+ rel2.relative: 1.0 0.09;
}
}
part
description
{
state: "default" 0.0;
- rel1.relative: 0.01 0.71;
+ rel1.relative: 0.01 0.45;
rel2.relative: 0.98 1.0;
color: 220 220 220 255;
}
#include "reclient.h"
#include<iostream>
-#include "mutex"
-#include "condition_variable"
#include "reclientmain.h"
constexpr int QUIT_INPUT = 3;
std::shared_ptr<RCSRemoteResourceObject> resource;
+std::vector<RCSRemoteResourceObject::Ptr> resourceList;
+std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
const std::string defaultKey = "deviceInfo";
-const std::string resourceType = "core.ac";
-const std::string relativeUri = OC_RSRVD_WELL_KNOWN_URI;
-
-std::mutex mtx;
-std::condition_variable cond;
+const std::string resourceType = "oic.r.ac";
RCSResourceAttributes model;
RCSResourceAttributes speed;
static void onDestroy()
{
dlog_print(DLOG_INFO, LOG_TAG, "#### Destroy sequence called");
+ resourceList.clear();
resource = nullptr;
}
std::string resourceURI = foundResource->getUri();
std::string hostAddress = foundResource->getAddress();
- dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI : %s", resourceURI.c_str());
- dlog_print(DLOG_INFO, LOG_TAG, "#### Resource Host : %S", hostAddress.c_str());
-
- string logMessage = "Resource Found <br>";
+ int resourceSize = resourceList.size() + 1;
+ string logMessage = "Resource Found : " + std::to_string(resourceSize) + "<br>";
logMessage = logMessage + "URI: " + resourceURI + "<br>";
logMessage = logMessage + "Host:" + hostAddress + "<br>";
logMessage += "----------------------<br>";
- dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+ dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
- resource = foundResource;
+ resourceList.push_back(foundResource);
+
+ if ("/a/airConditioner" == resourceURI)
+ resource = foundResource;
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showClientAPIs, NULL);
- cond.notify_all();
}
-void onRemoteAttributesReceivedCallback(const RCSResourceAttributes &attributes)
+void onRemoteAttributesReceived(const RCSResourceAttributes &attributes, int)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### onRemoteAttributesReceivedCallback callback");
+ dlog_print(DLOG_INFO, LOG_TAG, "#### onRemoteAttributesReceived entry");
string logMessage = "Remote Attribute Updated : <br> ";
{
if (checkResource)
{
- resource->getRemoteAttributes(&onRemoteAttributesReceivedCallback);
+ resource->getRemoteAttributes(&onRemoteAttributesReceived);
}
else
{
if (checkResource)
{
resource->setRemoteAttributes(setAttribute,
- &onRemoteAttributesReceivedCallback);
+ &onRemoteAttributesReceived);
}
else
{
void discoverResource()
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Wait 2 seconds until discovered");
-
- RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(), relativeUri,
- resourceType, &onResourceDiscovered);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### discovery started");
- std::unique_lock<std::mutex> lck(mtx);
- cond.wait_for(lck, std::chrono::seconds(2));
+ while (!discoveryTask)
+ {
+ try
+ {
+ discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+ RCSAddress::multicast(), resourceType, &onResourceDiscovered);
+ }
+ catch (const RCSPlatformException &e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+ }
dlog_print(DLOG_INFO, LOG_TAG, "#### Discovery over");
}
+void cancelDiscoverResource()
+{
+ dlog_print(DLOG_INFO, LOG_TAG, "#### cancelDiscoverResource entry");
+ string logMessage = "";
+
+ if (!discoveryTask)
+ {
+ logMessage += "There is no discovery request <br>";
+ }
+ else
+ {
+ discoveryTask->cancel();
+
+ logMessage += "Discovery canceled <br>";
+
+ int resourceSize = resourceList.size();
+ if (!resourceSize)
+ {
+ logMessage += "No Resource Discovered <br>";
+ }
+ else
+ {
+ logMessage += std::to_string(resourceSize) + " : Resource Discovered <br>";
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showClientAPIs, NULL);
+ }
+
+ }
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+ &logMessage);
+}
+
static void
popup_cancel_clicked_cb(void *data, Evas_Object *obj, void *event_info)
{
}
}
+// Method to be called when the Cancel Discovery UI Button is selected
+static void
+cancel_resource_cb(void *data, Evas_Object *obj, void *event_info)
+{
+ if (NULL != list)
+ {
+ cancelDiscoverResource();
+ }
+ else
+ {
+ dlog_print(DLOG_ERROR, "cancel_resource_cb", "list is NULL - So unable to add items!!!");
+ }
+}
+
void *showClientAPIs(void *data)
{
// Add items to the list only if the list is empty
Evas_Object *layout;
Evas_Object *scroller;
Evas_Object *nf = (Evas_Object *)data;
- Evas_Object *find_button;
+ Evas_Object *button1;
+ Evas_Object *button2;
Elm_Object_Item *nf_it;
naviframe = nf;
elm_object_content_set(scroller, layout);
- // Button
- find_button = elm_button_add(layout);
- elm_object_part_content_set(layout, "find_button", find_button);
- elm_object_text_set(find_button, "Discover Resource");
- evas_object_smart_callback_add(find_button, "clicked", find_resource_cb, NULL);
+ // Start Discovery Button
+ button1 = elm_button_add(layout);
+ elm_object_part_content_set(layout, "button1", button1);
+ elm_object_text_set(button1, "Start Discovery");
+ evas_object_smart_callback_add(button1, "clicked", find_resource_cb, NULL);
+
+ // Cancel Discovery Button
+ button2 = elm_button_add(layout);
+ elm_object_part_content_set(layout, "button2", button2);
+ elm_object_text_set(button2, "Cancel Discovery");
+ evas_object_smart_callback_add(button2, "clicked", cancel_resource_cb, NULL);
// List
list = elm_list_add(layout);
typedef int ReturnValue;
std::string resourceUri = "/a/airConditioner";
-std::string resourceType = "core.ac";
+std::string resourceType = "oic.r.ac";
std::string resourceInterface = "oic.if.";
std::string attributeKey = "deviceInfo";
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
- <storageModule moduleId="org.eclipse.cdt.core.settings">
- <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
- <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
- <externalSettings/>
- <extensions>
- <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
- <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- </extensions>
- </storageModule>
- <storageModule moduleId="cdtBuildSystem" version="4.0.0">
- <configuration artifactName="resampleclient" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
- <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
- <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
- <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
- <builder arguments="--eval="SHELL=cmd" -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
- <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
- <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
- <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
- <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
- <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
- <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
- </option>
- <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
- <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
- </option>
- <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
- <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value=" -fPIE"/>
- <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
- <listOptionValue builtIn="false" value="-mthumb"/>
- </option>
- <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
- <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\src\resourceBroker\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\src\resourceCache\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\src\common\utils\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\src\common\expiryTimer\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\src\common\expiryTimer\src""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\src\common\primitiveResource\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\c_common""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\stack\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\logger\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\occoap\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocrandom\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocsocket\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\oc_logger\include""/>
- <listOptionValue builtIn="false" value=""..\..\..\..\..\..\extlibs\timer""/>
- </option>
- <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
- <listOptionValue builtIn="false" value="Native_API"/>
- </option>
- <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
- <listOptionValue builtIn="false" value="_DEBUG"/>
- </option>
- <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
- <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
- <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
- <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
- </tool>
- <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
- <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
- <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
- <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
- <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
- </option>
- <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
- <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
- </option>
- <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
- <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value=" -fPIE"/>
- <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
- <listOptionValue builtIn="false" value="-mthumb"/>
- </option>
- <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
- <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
- </option>
- <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
- <listOptionValue builtIn="false" value="Native_API"/>
- </option>
- <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
- <listOptionValue builtIn="false" value="_DEBUG"/>
- </option>
- <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
- <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
- <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
- </tool>
- <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
- <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
- <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
- <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
- <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
- <listOptionValue builtIn="false" value="-pie -lpthread "/>
- <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
- <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
- <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
- <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
- <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
- </option>
- <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
- <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
- </option>
- <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
- <listOptionValue builtIn="false" value="oc"/>
- <listOptionValue builtIn="false" value="octbstack"/>
- <listOptionValue builtIn="false" value="oc_logger"/>
- <listOptionValue builtIn="false" value="oc_logger_core"/>
- <listOptionValue builtIn="false" value="connectivity_abstraction"/>
- <listOptionValue builtIn="false" value="uuid"/>
- <listOptionValue builtIn="false" value="rcs_client"/>
- <listOptionValue builtIn="false" value="rcs_common"/>
- <listOptionValue builtIn="false" value="rcs_container"/>
- <listOptionValue builtIn="false" value="rcs_server"/>
- </option>
- <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
- <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
- <additionalInput kind="additionalinput" paths="$(LIBS)"/>
- </inputType>
- </tool>
- <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
- <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
- </tool>
- <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
- <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
- <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
- <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
- <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
- <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
- </toolChain>
- </folderInfo>
- <sourceEntries>
- <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
- <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
- <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
- </sourceEntries>
- </configuration>
- </storageModule>
- <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
- </cconfiguration>
- <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
- <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
- <externalSettings/>
- <extensions>
- <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
- <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
- <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
- </extensions>
- </storageModule>
- <storageModule moduleId="cdtBuildSystem" version="4.0.0">
- <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
- <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
- <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
- <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
- <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
- <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
- <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
- <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
- <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
- <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
- <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
- </option>
- <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
- <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
- </option>
- <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
- <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value=" -fPIE"/>
- <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
- </option>
- <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
- <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
- </option>
- <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
- <listOptionValue builtIn="false" value="Native_API"/>
- </option>
- <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
- </tool>
- <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
- <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
- <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
- <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
- <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
- </option>
- <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
- <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
- <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
- </option>
- <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
- <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
- <listOptionValue builtIn="false" value=" -fPIE"/>
- <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
- </option>
- <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
- <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
- </option>
- <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
- <listOptionValue builtIn="false" value="Native_API"/>
- </option>
- <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
- </tool>
- <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
- <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
- <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
- <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
- <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
- <listOptionValue builtIn="false" value="-pie -lpthread "/>
- <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
- <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
- <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
- <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
- <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
- </option>
- <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
- <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
- </option>
- <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
- <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
- <additionalInput kind="additionalinput" paths="$(LIBS)"/>
- </inputType>
- </tool>
- <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
- <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
- </tool>
- <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
- <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
- <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
- <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
- <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
- <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
- </toolChain>
- </folderInfo>
- <sourceEntries>
- <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
- <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
- <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
- </sourceEntries>
- </configuration>
- </storageModule>
- <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
- </cconfiguration>
- </storageModule>
- <storageModule moduleId="cdtBuildSystem" version="4.0.0">
- <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
- </storageModule>
- <storageModule moduleId="scannerConfiguration">
- <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
- <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
- <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
- </scannerConfigBuildInfo>
- <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
- <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
- </scannerConfigBuildInfo>
- </storageModule>
- <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
- <storageModule moduleId="refreshScope" versionNumber="2">
- <configuration configurationName="Debug">
- <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
- </configuration>
- <configuration configurationName="Release">
- <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
- </configuration>
- </storageModule>
- <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
+ <storageModule moduleId="org.eclipse.cdt.core.settings">
+ <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+ <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" moduleId="org.eclipse.cdt.core.settings" name="Debug">
+ <externalSettings/>
+ <extensions>
+ <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+ <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ </extensions>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <configuration artifactName="resampleclient" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.debug" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109" name="Debug" parent="org.tizen.nativecore.config.sbi.gcc45.app.debug">
+ <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109." name="/" resourcePath="">
+ <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug.266200202" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.debug">
+ <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1788661429" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+ <builder arguments="--eval="SHELL=cmd" -r" autoBuildTarget="all" buildPath="${workspace_loc:/TMSampleApp}/Debug" enableAutoBuild="true" id="org.tizen.nativecore.target.sbi.gnu.builder.1749302123" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+ <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.345678603" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+ <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1794187316" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+ <option id="gnu.cpp.compiler.option.optimization.level.719656926" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" useByScannerDiscovery="false" value="gnu.cpp.compiler.optimization.level.none" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.378028433" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.cpp.compiler.debugging.level.max" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.831567474" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1543030783" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1612037830" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-mthumb"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.include.paths.1501991974" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\resourceBroker\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\resourceCache\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\utils\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\expiryTimer\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\expiryTimer\src""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\src\common\primitiveResource\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\c_common""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\stack\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\logger\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\occoap\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocrandom\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\ocsocket\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\oc_logger\include""/>
+ <listOptionValue builtIn="false" value=""..\..\..\..\..\..\extlibs\timer""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks.core.1095600730" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.preprocessor.def.371963530" name="Defined symbols (-D)" superClass="gnu.cpp.compiler.option.preprocessor.def" useByScannerDiscovery="false" valueType="definedSymbols">
+ <listOptionValue builtIn="false" value="_DEBUG"/>
+ </option>
+ <option id="gnu.cpp.compiler.option.dialect.std.1929207991" name="Language standard" superClass="gnu.cpp.compiler.option.dialect.std" value="gnu.cpp.compiler.dialect.default" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.misc.pic.core.755649926" name="-fPIC option" superClass="sbi.gnu.cpp.compiler.option.misc.pic.core" value="true" valueType="boolean"/>
+ <option id="gnu.cpp.compiler.option.other.other.1760093561" name="Other flags" superClass="gnu.cpp.compiler.option.other.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1956958926" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+ </tool>
+ <tool command="arm-linux-gnueabi-gcc.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.2072036030" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+ <option defaultValue="gnu.c.optimization.level.none" id="gnu.c.compiler.option.optimization.level.1042898971" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" useByScannerDiscovery="false" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.debugging.level.core.135607770" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core" useByScannerDiscovery="false" value="gnu.c.debugging.level.max" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.571493571" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-device.core_gcc46.armel.core.app"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.107632308" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.1275911900" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" useByScannerDiscovery="false" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-mthumb"/>
+ </option>
+ <option id="gnu.c.compiler.option.include.paths.109116980" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" useByScannerDiscovery="false" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks.core.1552601669" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" useByScannerDiscovery="false" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <option id="gnu.c.compiler.option.preprocessor.def.symbols.2021130927" name="Defined symbols (-D)" superClass="gnu.c.compiler.option.preprocessor.def.symbols" useByScannerDiscovery="false" valueType="definedSymbols">
+ <listOptionValue builtIn="false" value="_DEBUG"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.misc.pic.core.1304419386" name="-fPIC option" superClass="sbi.gnu.c.compiler.option.misc.pic.core" value="false" valueType="boolean"/>
+ <option id="gnu.c.compiler.option.misc.other.2029079564" name="Other flags" superClass="gnu.c.compiler.option.misc.other" value="-c -fmessage-length=0 -std=c++0x" valueType="string"/>
+ <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1859092644" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+ </tool>
+ <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.944066372" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+ <tool command="arm-linux-gnueabi-g++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.1667264058" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+ <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1178784315" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="-pie -lpthread "/>
+ <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+ <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
+ <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+ </option>
+ <option id="gnu.cpp.link.option.paths.1087248355" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
+ </option>
+ <option id="gnu.cpp.link.option.libs.2039500142" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" valueType="libs">
+ <listOptionValue builtIn="false" value="oc"/>
+ <listOptionValue builtIn="false" value="octbstack"/>
+ <listOptionValue builtIn="false" value="oc_logger"/>
+ <listOptionValue builtIn="false" value="oc_logger_core"/>
+ <listOptionValue builtIn="false" value="connectivity_abstraction"/>
+ <listOptionValue builtIn="false" value="uuid"/>
+ <listOptionValue builtIn="false" value="boost_date_time"/>
+ <listOptionValue builtIn="false" value="boost_system"/>
+ <listOptionValue builtIn="false" value="boost_thread"/>
+ <listOptionValue builtIn="false" value="rcs_client"/>
+ <listOptionValue builtIn="false" value="rcs_common"/>
+ <listOptionValue builtIn="false" value="rcs_server"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+ <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+ <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+ </inputType>
+ </tool>
+ <tool command="arm-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.1585687908" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+ <inputType id="cdt.managedbuild.tool.gnu.assembler.input.89256350" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+ </tool>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.353447784" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.734608698" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+ <tool id="org.tizen.nativecore.tool.ast.125567506" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+ <tool id="org.tizen.nativecore.tool.ast.cpp.2107204356" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+ <tool id="org.tizen.nativecore.tool.sbi.po.compiler.1190161351" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+ <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1621384631" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+ </toolChain>
+ </folderInfo>
+ <sourceEntries>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+ </sourceEntries>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+ </cconfiguration>
+ <cconfiguration id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+ <storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" moduleId="org.eclipse.cdt.core.settings" name="Release">
+ <externalSettings/>
+ <extensions>
+ <extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
+ <extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.MakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
+ <extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
+ </extensions>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <configuration artifactName="tmsampleapp" buildArtefactType="org.tizen.nativecore.buildArtefactType.app" buildProperties="org.eclipse.cdt.build.core.buildArtefactType=org.tizen.nativecore.buildArtefactType.app,org.eclipse.cdt.build.core.buildType=org.eclipse.cdt.build.core.buildType.release" description="" errorParsers="org.eclipse.cdt.core.MakeErrorParser;org.eclipse.cdt.core.GCCErrorParser;" id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396" name="Release" parent="org.tizen.nativecore.config.sbi.gcc45.app.release">
+ <folderInfo id="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396." name="/" resourcePath="">
+ <toolChain id="org.tizen.nativecore.toolchain.sbi.gcc45.app.release.32000863" name="Tizen Native Toolchain" superClass="org.tizen.nativecore.toolchain.sbi.gcc45.app.release">
+ <targetPlatform binaryParser="org.eclipse.cdt.core.ELF" id="org.tizen.nativeide.target.sbi.gnu.platform.base.1750758769" osList="linux,win32" superClass="org.tizen.nativeide.target.sbi.gnu.platform.base"/>
+ <builder buildPath="${workspace_loc:/TMSampleApp}/Release" id="org.tizen.nativecore.target.sbi.gnu.builder.2029564551" keepEnvironmentInBuildfile="false" managedBuildOn="true" name="Tizen Application Builder" superClass="org.tizen.nativecore.target.sbi.gnu.builder"/>
+ <tool id="org.tizen.nativecore.tool.sbi.gnu.archiver.224082468" name="Archiver" superClass="org.tizen.nativecore.tool.sbi.gnu.archiver"/>
+ <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler.1434486618" name="C++ Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.compiler">
+ <option id="gnu.cpp.compiler.option.optimization.level.1709393206" name="Optimization Level" superClass="gnu.cpp.compiler.option.optimization.level" value="gnu.cpp.compiler.optimization.level.most" valueType="enumerated"/>
+ <option id="sbi.gnu.cpp.compiler.option.debugging.level.core.221700213" name="Debug level" superClass="sbi.gnu.cpp.compiler.option.debugging.level.core"/>
+ <option id="sbi.gnu.cpp.compiler.option.710876023" name="Tizen-Target" superClass="sbi.gnu.cpp.compiler.option" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_inc.core.1622581330" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.cpp.compiler.option.frameworks_inc.core" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks_cflags.core.1695583788" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.cpp.compiler.option.frameworks_cflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ </option>
+ <option id="gnu.cpp.compiler.option.include.paths.585301879" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.cpp.compiler.option.frameworks.core.708669314" name="Tizen-Frameworks" superClass="sbi.gnu.cpp.compiler.option.frameworks.core" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.2006056090" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
+ </tool>
+ <tool command="clang.exe" id="org.tizen.nativecore.tool.sbi.gnu.c.compiler.601285388" name="C Compiler" superClass="org.tizen.nativecore.tool.sbi.gnu.c.compiler">
+ <option defaultValue="gnu.c.optimization.level.most" id="gnu.c.compiler.option.optimization.level.1778561828" name="Optimization Level" superClass="gnu.c.compiler.option.optimization.level" valueType="enumerated"/>
+ <option id="sbi.gnu.c.compiler.option.debugging.level.core.1695949408" name="Debug level" superClass="sbi.gnu.c.compiler.option.debugging.level.core"/>
+ <option id="sbi.gnu.c.compiler.option.1422818783" name="Tizen-Target" superClass="sbi.gnu.c.compiler.option" valueType="userObjs">
+ <listOptionValue builtIn="false" value="mobile-2.3-emulator.core_llvm34.i386.core.app"/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_inc.core.1871683675" name="Tizen-Frameworks-Include-Path" superClass="sbi.gnu.c.compiler.option.frameworks_inc.core" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libxml2""/>
+ <listOptionValue builtIn="false" value=""${SDK_PATH}/library""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/AL""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appcore-agent""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/appfw""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/base""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/cairo""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/calendar-service2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ckm""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/contacts-svc""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/curl""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dbus-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/dbus-1.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/dlog""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ecore-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/e_dbus-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/edje-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efreet-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1/eina""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eina-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/elementary-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ethumb-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/evas-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/fontconfig""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/freetype2""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/gio-unix-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/glib-2.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/lib/glib-2.0/include""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/json-glib-1.0/json-glib""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/libexif""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media-content""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/media""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/minizip""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/network""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/notification""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/shortcut""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/storage""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/system""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ui""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/vconf""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/web""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/badge""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/eio-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/email-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/embryo-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/messaging""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/msg-service""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ug-1""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/context-manager""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/telephony-client""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/ewebkit2-0""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/location""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/sensor""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/efl-extension""/>
+ <listOptionValue builtIn="false" value=""${SBI_SYSROOT}/usr/include/wifi-direct""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks_cflags.core.371848582" name="Tizen-Frameworks-Other-Cflags" superClass="sbi.gnu.c.compiler.option.frameworks_cflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_COMPILER_MISC}"/>
+ <listOptionValue builtIn="false" value=" -fPIE"/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ </option>
+ <option id="gnu.c.compiler.option.include.paths.1254567673" name="Include paths (-I)" superClass="gnu.c.compiler.option.include.paths" valueType="includePath">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
+ </option>
+ <option id="sbi.gnu.c.compiler.option.frameworks.core.627340354" name="Tizen-Frameworks" superClass="sbi.gnu.c.compiler.option.frameworks.core" valueType="userObjs">
+ <listOptionValue builtIn="false" value="Native_API"/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.749706957" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
+ </tool>
+ <tool id="org.tizen.nativeide.tool.sbi.gnu.c.linker.base.1794486202" name="C Linker" superClass="org.tizen.nativeide.tool.sbi.gnu.c.linker.base"/>
+ <tool command="clang++.exe" id="org.tizen.nativecore.tool.sbi.gnu.cpp.linker.2579106" name="C++ Linker" superClass="org.tizen.nativecore.tool.sbi.gnu.cpp.linker">
+ <option id="sbi.gnu.cpp.linker.option.frameworks_lflags.core.1582557344" name="Tizen-Frameworks-Other-Lflags" superClass="sbi.gnu.cpp.linker.option.frameworks_lflags.core" valueType="stringList">
+ <listOptionValue builtIn="false" value="${TC_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="${RS_LINKER_MISC}"/>
+ <listOptionValue builtIn="false" value="-pie -lpthread "/>
+ <listOptionValue builtIn="false" value="-Xlinker -rpath="/home/developer/sdk_tools/lib""/>
+ <listOptionValue builtIn="false" value="--sysroot="${SBI_SYSROOT}""/>
+ <listOptionValue builtIn="false" value="-Xlinker --version-script=${PROJ_PATH}/.exportMap"/>
+ <listOptionValue builtIn="false" value="-L"${SBI_SYSROOT}/usr/lib""/>
+ <listOptionValue builtIn="false" value="$(RS_LIBRARIES)"/>
+ </option>
+ <option id="gnu.cpp.link.option.paths.1396123174" name="Library search path (-L)" superClass="gnu.cpp.link.option.paths" valueType="libPaths">
+ <listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/lib}""/>
+ </option>
+ <inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.768667264" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+ <additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
+ <additionalInput kind="additionalinput" paths="$(LIBS)"/>
+ </inputType>
+ </tool>
+ <tool command="i386-linux-gnueabi-as.exe" id="org.tizen.nativeapp.tool.sbi.gnu.assembler.base.380499784" name="Assembler" superClass="org.tizen.nativeapp.tool.sbi.gnu.assembler.base">
+ <inputType id="cdt.managedbuild.tool.gnu.assembler.input.1638213209" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
+ </tool>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.1617359663" name="C FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen"/>
+ <tool id="org.tizen.nativecore.tool.fnmapgen.cpp.759297757" name="C++ FN-Map Generator" superClass="org.tizen.nativecore.tool.fnmapgen.cpp"/>
+ <tool id="org.tizen.nativecore.tool.ast.495578509" name="C Static Analyzer" superClass="org.tizen.nativecore.tool.ast"/>
+ <tool id="org.tizen.nativecore.tool.ast.cpp.91235808" name="C++ Static Analyzer" superClass="org.tizen.nativecore.tool.ast.cpp"/>
+ <tool id="org.tizen.nativecore.tool.sbi.po.compiler.619869321" name="PO Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.po.compiler"/>
+ <tool id="org.tizen.nativecore.tool.sbi.edc.compiler.1045552473" name="EDC Resource Compiler" superClass="org.tizen.nativecore.tool.sbi.edc.compiler"/>
+ </toolChain>
+ </folderInfo>
+ <sourceEntries>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="inc"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="res"/>
+ <entry flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="src"/>
+ </sourceEntries>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
+ </cconfiguration>
+ </storageModule>
+ <storageModule moduleId="cdtBuildSystem" version="4.0.0">
+ <project id="TMSampleApp.org.tizen.nativecore.target.sbi.gcc45.app.278712545" name="Tizen Native Application" projectType="org.tizen.nativecore.target.sbi.gcc45.app"/>
+ </storageModule>
+ <storageModule moduleId="scannerConfiguration">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.release.1584352396">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ </scannerConfigBuildInfo>
+ <scannerConfigBuildInfo instanceId="org.tizen.nativecore.config.sbi.gcc45.app.debug.109194109">
+ <autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
+ </scannerConfigBuildInfo>
+ </storageModule>
+ <storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
+ <storageModule moduleId="refreshScope" versionNumber="2">
+ <configuration configurationName="Debug">
+ <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+ </configuration>
+ <configuration configurationName="Release">
+ <resource resourceType="PROJECT" workspacePath="/TMSampleApp"/>
+ </configuration>
+ </storageModule>
+ <storageModule moduleId="com.samsung.tizen.nativeapp.projectInfo" version="1.0.0"/>
</cproject>
{
part
{
- name: "find_button";
+ name: "button1";
type: SWALLOW;
scale: 1;
description
{
rel1.relative: 0.01 0.01;
- rel2.relative: 0.7 0.09;
+ rel2.relative: 0.5 0.09;
+ }
+ }
+ part
+ {
+ name: "button2";
+ type: SWALLOW;
+ scale: 1;
+ description
+ {
+ rel1.relative: 0.51 0.01;
+ rel2.relative: 1.0 0.09;
}
}
part
#ifdef LOG_TAG
#undef LOG_TAG
#endif
-#define LOG_TAG "reclientmain"
+#define LOG_TAG "reclient"
#if !defined(PACKAGE)
#define PACKAGE "org.tizen.resampleclient"
#define ELM_DEMO_EDJ "opt/usr/apps/org.tizen.resampleclient/res/ui_controls.edj"
-void group_cb(void *data, Evas_Object *obj, void *event_info);
-
-void containerCreateUI(void *data, Evas_Object *obj, void *event_info);
+void client_cb(void *data, Evas_Object *obj, void *event_info);
#endif // RECLIENTMAIN_H__
\ No newline at end of file
{
base_scale: 1.8;
#include "../edc_resource/re_client_control.edc"
- #include "../edc_resource/re_container_control.edc"
}
\ No newline at end of file
#include "reclient.h"
#include<iostream>
-#include "mutex"
-#include "condition_variable"
#include "reclientmain.h"
constexpr int QUIT_INPUT = 3;
std::shared_ptr<RCSRemoteResourceObject> resource;
+std::vector<RCSRemoteResourceObject::Ptr> resourceList;
+std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
const std::string defaultKey = "Temperature";
-const std::string resourceType = "?rt=core.TemperatureSensor";
-const std::string targetUri = OC_RSRVD_WELL_KNOWN_URI + resourceType;
-
-std::mutex mtx;
-std::condition_variable cond;
+const std::string resourceType = "oic.r.temperaturesensor";
static Evas_Object *log_entry = NULL;
static Evas_Object *list = NULL;
static void onDestroy()
{
dlog_print(DLOG_INFO, LOG_TAG, "#### Destroy sequence called");
+ resourceList.clear();
resource = nullptr;
}
std::string resourceURI = foundResource->getUri();
std::string hostAddress = foundResource->getAddress();
- dlog_print(DLOG_INFO, LOG_TAG, "#### Resource URI : %s", resourceURI.c_str());
- dlog_print(DLOG_INFO, LOG_TAG, "#### Resource Host : %S", hostAddress.c_str());
-
- string logMessage = "Resource Found <br>";
+ int resourceSize = resourceList.size() + 1;
+ string logMessage = "Resource Found : " + std::to_string(resourceSize) + "<br>";
logMessage = logMessage + "URI: " + resourceURI + "<br>";
logMessage = logMessage + "Host:" + hostAddress + "<br>";
logMessage += "----------------------<br>";
- dlog_print(DLOG_INFO, LOG_TAG, " %s", logMessage.c_str());
+ dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
- resource = foundResource;
+ resourceList.push_back(foundResource);
- ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showClientAPIs, NULL);
- cond.notify_all();
+ if ("/a/TempSensor" == resourceURI)
+ resource = foundResource;
}
void onResourceStateChanged(const ResourceState &resourceState)
&logMessage);
}
-void onRemoteAttributesReceivedCallback(const RCSResourceAttributes &attributes)
+void onRemoteAttributesReceived(const RCSResourceAttributes &attributes, int)
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### onRemoteAttributesReceivedCallback callback");
+ dlog_print(DLOG_INFO, LOG_TAG, "#### onRemoteAttributesReceived entry");
string logMessage = "Remote Attribute Updated : <br> ";
{
if (checkResource)
{
- resource->getRemoteAttributes(&onRemoteAttributesReceivedCallback);
+ resource->getRemoteAttributes(&onRemoteAttributesReceived);
}
else
{
if (checkResource)
{
resource->setRemoteAttributes(setAttribute,
- &onRemoteAttributesReceivedCallback);
+ &onRemoteAttributesReceived);
}
else
{
void discoverResource()
{
- dlog_print(DLOG_INFO, LOG_TAG, "#### Wait 2 seconds until discovered");
-
- RCSDiscoveryManager::getInstance()->discoverResource(RCSAddress::multicast(), targetUri,
- &onResourceDiscovered);
+ dlog_print(DLOG_INFO, LOG_TAG, "#### discovery started");
- std::unique_lock<std::mutex> lck(mtx);
- cond.wait_for(lck, std::chrono::seconds(2));
+ while (!discoveryTask)
+ {
+ try
+ {
+ discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(
+ RCSAddress::multicast(), resourceType, &onResourceDiscovered);
+ }
+ catch (const RCSPlatformException &e)
+ {
+ std::cout << e.what() << std::endl;
+ }
+ }
dlog_print(DLOG_INFO, LOG_TAG, "#### Discovery over");
}
+void cancelDiscoverResource()
+{
+ dlog_print(DLOG_INFO, LOG_TAG, "#### cancelDiscoverResource entry");
+ string logMessage = "";
+
+ if (!discoveryTask)
+ {
+ logMessage += "There is no discovery request <br>";
+ }
+ else
+ {
+ discoveryTask->cancel();
+
+ logMessage += "Discovery canceled <br>";
+
+ int resourceSize = resourceList.size();
+ if (!resourceSize)
+ {
+ logMessage += "No Resource Discovered <br>";
+ }
+ else
+ {
+ logMessage += std::to_string(resourceSize) + " : Resource Discovered <br>";
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))showClientAPIs, NULL);
+ }
+
+ }
+
+ dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
+ ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
+ &logMessage);
+}
+
static void
popup_cancel_clicked_cb(void *data, Evas_Object *obj, void *event_info)
{
evas_object_show(popup);
}
-// Method to be called when the Discover Resource UI Button is selected
+// Method to be called when the Start Discovery UI Button is selected
static void
find_resource_cb(void *data, Evas_Object *obj, void *event_info)
{
}
}
+// Method to be called when the Cancel Discovery UI Button is selected
+static void
+cancel_resource_cb(void *data, Evas_Object *obj, void *event_info)
+{
+ if (NULL != list)
+ {
+ cancelDiscoverResource();
+ }
+ else
+ {
+ dlog_print(DLOG_ERROR, "cancel_resource_cb", "list is NULL - So unable to add items!!!");
+ }
+}
+
void *showClientAPIs(void *data)
{
// Add items to the list only if the list is empty
}
// Method to be called when the Group APIs UI Button is selected
-void group_cb(void *data, Evas_Object *obj, void *event_info)
+void client_cb(void *data, Evas_Object *obj, void *event_info)
{
Evas_Object *layout;
Evas_Object *scroller;
Evas_Object *nf = (Evas_Object *)data;
- Evas_Object *find_button;
+ Evas_Object *button1;
+ Evas_Object *button2;
Elm_Object_Item *nf_it;
naviframe = nf;
elm_object_content_set(scroller, layout);
- // Button
- find_button = elm_button_add(layout);
- elm_object_part_content_set(layout, "find_button", find_button);
- elm_object_text_set(find_button, "Discover Resource");
- evas_object_smart_callback_add(find_button, "clicked", find_resource_cb, NULL);
+ // Start Discovery Button
+ button1 = elm_button_add(layout);
+ elm_object_part_content_set(layout, "button1", button1);
+ elm_object_text_set(button1, "Start Discovery");
+ evas_object_smart_callback_add(button1, "clicked", find_resource_cb, NULL);
+
+ // Cancel Discovery Button
+ button2 = elm_button_add(layout);
+ elm_object_part_content_set(layout, "button2", button2);
+ elm_object_text_set(button2, "Cancel Discovery");
+ evas_object_smart_callback_add(button2, "clicked", cancel_resource_cb, NULL);
// List
list = elm_list_add(layout);
evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
// Main Menu Items Here
- elm_list_item_append(list, "Resource Client", NULL, NULL, group_cb, nf);
-
- elm_list_item_append(list, "Resource Container", NULL, NULL, containerCreateUI, nf);
-
elm_list_go(list);
// This button is set for devices which doesn't have H/W back key.
elm_object_style_set(btn, "naviframe/end_btn/default");
nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
+
+ client_cb(nf, NULL, NULL);
}
<listOptionValue builtIn="false" value="boost_date_time"/>
<listOptionValue builtIn="false" value="boost_system"/>
<listOptionValue builtIn="false" value="boost_thread"/>
- <listOptionValue builtIn="false" value="HueBundle"/>
- <listOptionValue builtIn="false" value="BMISensorBundle"/>
- <listOptionValue builtIn="false" value="DISensorBundle"/>
<listOptionValue builtIn="false" value="rcs_client"/>
<listOptionValue builtIn="false" value="rcs_common"/>
- <listOptionValue builtIn="false" value="rcs_container"/>
<listOptionValue builtIn="false" value="rcs_server"/>
</option>
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.618645708" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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.
- *
- ******************************************************************/
-
-group
-{
- name: "container_layout";
- parts
- {
- part
- {
- name: "start_button";
- type: SWALLOW;
- scale: 1;
- description
- {
- rel1.relative: 0.01 0.01;
- rel2.relative: 0.5 0.09;
- }
- }
- part
- {
- name: "stop_button";
- type: SWALLOW;
- scale: 1;
- description
- {
- rel1.relative: 0.51 0.01;
- rel2.relative: 1.0 0.09;
- }
- }
- part
- {
- name: "listnew";
- type: SWALLOW;
- scale: 1;
- description
- {
- rel1.relative: 0.01 0.1;
- rel2.relative: 0.99 0.7;
- }
- }
- part
- {
- name: "log_bg";
- type: RECT;
- scale: 1;
- description
- {
- state: "default" 0.0;
- rel1.relative: 0.01 0.71;
- rel2.relative: 0.98 1.0;
- color: 220 220 220 255;
- }
- }
- part
- {
- name: "log";
- type: SWALLOW;
- scale: 1;
- description
- {
- rel1.to: "log_bg";
- rel2.to: "log_bg";
- }
- }
- }
-}
-
-group
-{
- name: "popup_datetime_text";
- parts
- {
- part
- {
- name: "pad_l";
- type: SPACER;
- scale: 1;
- description
- {
- state: "default" 0.0;
- min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
- fixed: 1 0;
- rel1.relative: 0.0 0.0;
- rel2.relative: 0.0 1.0;
- align: 0.0 0.0;
- }
- }
- part
- {
- name: "pad_r";
- type: SPACER;
- scale: 1;
- description
- {
- state: "default" 0.0;
- min: POPUP_CONTENT_DEFAULT_PADDING_LEFT_MIN_INC 0;
- fixed: 1 0;
- rel1.relative: 1.0 0.0;
- rel2.relative: 1.0 1.0;
- align: 1.0 0.0;
- }
- }
- part
- {
- name: "elm.swallow.content";
- type: SWALLOW;
- scale: 1;
- description
- {
- state: "default" 0.0;
- min: 0 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
- max: -1 POPUP_EDITFIELD_LAYOUT_MINMAX_HEIGHT_INC;
- align: 0.5 0.5;
- rel1
- {
- relative: 1.0 0.0;
- to_x: "pad_l";
- }
- rel2
- {
- relative: 0.0 1.0;
- to_x: "pad_r";
- }
- }
- }
- }
-}
void serverCreateUI(void *data, Evas_Object *obj, void *event_info);
-void containerCreateUI(void *data, Evas_Object *obj, void *event_info);
-
#endif // REMAIN_H__
\ No newline at end of file
constexpr int DEFALUT_VALUE = 0;
+constexpr int PRESENCE_ON = 1;
+constexpr int PRESENCE_OFF = 2;
+
std::string resourceUri = "/a/TempSensor";
-std::string resourceType = "core.TemperatureSensor";
+std::string resourceType = "oic.r.temperaturesensor";
std::string resourceInterface = "oic.if.";
std::string attributeKey = "Temperature";
+int isPresenceOn = PRESENCE_ON;
enum class Control
{
{
base_scale: 1.8;
#include "../edc_resource/re_server_control.edc"
- #include "../edc_resource/re_container_control.edc"
}
\ No newline at end of file
evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
// Main Menu Items Here
- elm_list_item_append(list, "Resource Server", NULL, NULL, serverCreateUI, nf);
-
- elm_list_item_append(list, "Resource Container", NULL, NULL, containerCreateUI, nf);
+ elm_list_item_append(list, "Start Temperature Sensor", NULL, NULL, serverCreateUI, nf);
elm_list_go(list);
server = NULL;
string logMessage = "SERVER DESTROYED";
+ if(isPresenceOn == PRESENCE_ON)
+ {
+ OCPlatform::stopPresence();
+ }
+
dlog_print(DLOG_INFO, LOG_TAG, "#### %s", logMessage.c_str());
ecore_main_loop_thread_safe_call_sync((void * ( *)(void *))updateGroupLog,
&logMessage);
+++ /dev/null
-/******************************************************************
- *
- * Copyright 2015 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 "reservermain.h"
-#include <tizen.h>
-
-typedef struct appdata
-{
- Evas_Object *win;
- Evas_Object *conform;
- Evas_Object *layout;
- Evas_Object *nf;
- Evas_Object *findButton;
- Evas_Object *logtext;
- Evas_Object *listview;
-} appdata_s;
-
-static void
-win_delete_request_cb(void *data , Evas_Object *obj , void *event_info)
-{
- ui_app_exit();
-}
-
-static void
-list_selected_cb(void *data, Evas_Object *obj, void *event_info)
-{
- Elm_Object_Item *it = (Elm_Object_Item *)event_info;
- elm_list_item_selected_set(it, EINA_FALSE);
-}
-
-static Eina_Bool
-naviframe_pop_cb(void *data, Elm_Object_Item *it)
-{
- ui_app_exit();
- return EINA_FALSE;
-}
-
-static void
-create_list_view(appdata_s *ad)
-{
- Evas_Object *list;
- Evas_Object *btn;
- Evas_Object *nf = ad->nf;
- Elm_Object_Item *nf_it;
-
- // List
- list = elm_list_add(nf);
- elm_list_mode_set(list, ELM_LIST_COMPRESS);
- evas_object_smart_callback_add(list, "selected", list_selected_cb, NULL);
-
- // Main Menu Items Here
- elm_list_item_append(list, "Create Resource [Auto control]", NULL, NULL, start_server, nf);
-
- elm_list_item_append(list, "Create Resource [Developer control]", NULL, NULL, start_server_cb, nf);
-
- elm_list_go(list);
-
- // This button is set for devices which doesn't have H/W back key.
- btn = elm_button_add(nf);
- elm_object_style_set(btn, "naviframe/end_btn/default");
- nf_it = elm_naviframe_item_push(nf, "Resource Encapsulation", btn, NULL, list, NULL);
- elm_naviframe_item_pop_cb_set(nf_it, naviframe_pop_cb, ad->win);
-}
*
*/
-#ifndef RCSDISCOVERYMANAGER_H
-#define RCSDISCOVERYMANAGER_H
+#ifndef RCS_DISCOVERYMANAGER_H_
+#define RCS_DISCOVERYMANAGER_H_
#include <memory>
#include <functional>
-#include "octypes.h"
-
namespace OIC
{
namespace Service
{
- class RCSRemoteResourceObject;
class RCSAddress;
-
+ class RCSRemoteResourceObject;
/**
* This class contains the resource discovery methods.
*
*/
class RCSDiscoveryManager
{
- public:
+ public:
/**
* This class represents a discovery task.
*
- * @note A discovery task will be automatically canceled when destroyed.
*/
- class DiscoveryTask
- {
- public:
-
- /**
- * Cancel the task for discovery request. If cancel is called in duplicate, the request is ignored.
- */
- void cancel();
-
- /**
- * Return a boolean value whether the discovery request is canceled or not.
- */
- bool isCanceled();
-
- ~DiscoveryTask();
-
- public:
-
- DiscoveryTask(const DiscoveryTask&) = delete;
- DiscoveryTask(DiscoveryTask&&) = delete;
- DiscoveryTask& operator = (const DiscoveryTask&) const = delete;
- DiscoveryTask& operator = (DiscoveryTask&&) const = delete;
+ class DiscoveryTask
+ {
+ public:
+ typedef std::unique_ptr< DiscoveryTask > Ptr;
- private:
+ ~DiscoveryTask() = default;
- explicit DiscoveryTask(unsigned int id) : m_id{ id } {};
- private:
-
- unsigned int m_id;
- friend class RCSDiscoveryManagerImpl;
- };
- public:
+ DiscoveryTask(const DiscoveryTask&) = delete;
+ DiscoveryTask(DiscoveryTask&&) = delete;
+ DiscoveryTask& operator =(const DiscoveryTask&) const = delete;
+ DiscoveryTask& operator =(DiscoveryTask&&) const = delete;
/**
- * Typedef for callback of discoverResource APIs
- *
- * @see discoverResource
+ * It is cancelling the task of discovery.
+ * If it is already canceled, the operation is ignored.
*/
- typedef std::function< void(std::shared_ptr< RCSRemoteResourceObject >) >
- ResourceDiscoveredCallback;
+ void cancel();
/**
- * @return RCSDiscoveryManager instance.
- *
+ * Returns whether the discovery request is canceled or not.
*/
- static RCSDiscoveryManager* getInstance();
+ bool isCanceled();
- /**
- * Discovering the resource of interest, regardless of uri and resource type.
- * Find resource matching request periodically until returned resource is disappeared or destroyed.
- *
- * @return Returned object must be received.
- *
- * @param address A RCSAddress object
- * @param cb A callback to obtain discovered resource
- *
- * @throws InvalidParameterException If cb is empty.
- *
- * @note The callback will be invoked in an internal thread.
- *
- */
- std::unique_ptr<DiscoveryTask> discoverResource(const RCSAddress& address,
- ResourceDiscoveredCallback cb);
+ private:
+ explicit DiscoveryTask(unsigned int);
- /**
- * Discovering the resource of Interest, regardless of resource type.
- * Find resource matching request periodically until returned resource is disappeared or destroyed.
- *
- * @return Returned object must be received.
- *
- * @param address A RCSAddress object
- * @param relativeURI The relative uri of resource to be searched
- * @param cb A callback to obtain discovered resource
- *
- * @throws InvalidParameterException If cb is empty.
- *
- * @note The callback will be invoked in an internal thread.
- *
- * @see RCSAddress
- *
- */
- std::unique_ptr<DiscoveryTask> discoverResource(const RCSAddress& address,
- const std::string& relativeURI, ResourceDiscoveredCallback cb);
+ private:
+ unsigned int m_id;
- /**
- * Discovering the resource of Interest by Resource type.
- * Find resource matching request periodically until returned resource is disappeared or destroyed.
- *
- * @return Returned object must be received.
- *
- * @param address A RCSAddress object
- * @param resourceType Resource Type
- * @param cb A callback to obtain discovered resource
- *
- * @throws InvalidParameterException If cb is empty.
- *
- * @note The callback will be invoked in an internal thread.
- *
- * @see RCSAddress
- *
- */
- std::unique_ptr<DiscoveryTask> discoverResourceByType(const RCSAddress& address,
- const std::string& resourceType, ResourceDiscoveredCallback cb);
+ friend class RCSDiscoveryManagerImpl;
+ };
- /**
- * Discovering the resource of Interest by Resource type with provided relativeURI.
- * Find resource matching request periodically until returned resource is disappeared or destroyed.
- *
- * @return Returned object must be received.
- *
- * @param address A RCSAddress object
- * @param relativeURI The relative uri of resource to be searched
- * @param resourceType Resource Type
- * @param cb A callback to obtain discovered resource
- *
- * @throws InvalidParameterException If cb is empty.
- *
- * @note The callback will be invoked in an internal thread.
- *
- * @see RCSAddress
- *
- */
- std::unique_ptr<DiscoveryTask> discoverResourceByType(const RCSAddress& address,
- const std::string& relativeURI, const std::string& resourceType,
- ResourceDiscoveredCallback cb);
+ public:
- private:
+ /**
+ * Typedef for callback of discoverResource APIs
+ *
+ * @see discoverResource
+ */
+ typedef std::function< void(std::shared_ptr< RCSRemoteResourceObject >)
+ > ResourceDiscoveredCallback;
+
+ /**
+ * @return RCSDiscoveryManager instance.
+ *
+ */
+ static RCSDiscoveryManager* getInstance();
- RCSDiscoveryManager() = default;
- ~RCSDiscoveryManager()= default;;
+ /**
+ * Discovers resources of interest, regardless of uri and resource type.
+ * It is Consistently discovering resources until the discovery task is canceled.
+ *
+ * @param address A RCSAddress object
+ * @param cb A callback to obtain discovered resource
+ *
+ * @throws InvalidParameterException If cb is empty.
+ *
+ * @note The callback will be invoked in an internal thread.
+ *
+ */
+ DiscoveryTask::Ptr discoverResource(const RCSAddress& address,
+ ResourceDiscoveredCallback cb);
+
+ /**
+ * Discovers resources of interest, regardless of resource type.
+ * It is Consistently discovering resources until the discovery task is canceled.
+ *
+ * @param address A RCSAddress object
+ * @param relativeUri The relative uri of resource to be searched
+ * @param cb A callback to obtain discovered resource
+ *
+ * @throws InvalidParameterException If cb is empty.
+ *
+ * @note The callback will be invoked in an internal thread.
+ *
+ */
+ DiscoveryTask::Ptr discoverResource(const RCSAddress& address,
+ const std::string& relativeUri, ResourceDiscoveredCallback cb);
+
+ /**
+ * Discovers resources of interest by resource type.
+ * It is Consistently discovering resources until the discovery task is canceled.
+ *
+ * @param address A RCSAddress object
+ * @param resourceType Resource Type
+ * @param cb A callback to obtain discovered resource
+ *
+ * @throws InvalidParameterException If cb is empty.
+ *
+ * @note The callback will be invoked in an internal thread.
+ *
+ */
+ DiscoveryTask::Ptr discoverResourceByType(const RCSAddress& address,
+ const std::string& resourceType, ResourceDiscoveredCallback cb);
+
+ /**
+ * Discovers resources of interest by resource type with provided relativeUri.
+ * It is Consistently discovering resources until the discovery task is canceled.
+ *
+ * @param address A RCSAddress object
+ * @param relativeUri The relative uri of resource to be searched
+ * @param resourceType Resource Type
+ * @param cb A callback to obtain discovered resource
+ *
+ * @throws InvalidParameterException If cb is empty.
+ *
+ * @note The callback will be invoked in an internal thread.
+ *
+ */
+ DiscoveryTask::Ptr discoverResourceByType(const RCSAddress& address,
+ const std::string& relativeUri, const std::string& resourceType,
+ ResourceDiscoveredCallback cb);
- friend class DiscoveryTask;
+ private:
+ RCSDiscoveryManager() = default;
+ ~RCSDiscoveryManager() = default;
};
}
}
bool erase(const std::string& key);
/**
- * Checks the container has an element with a Key equivalent to key.
+ * Checks this contains an element for the specified key.
*
* @param key Key to check.
*
const Value& m_valueRef;
};
+ //! @cond
template< typename T >
struct RCSResourceAttributes::IsSupportedTypeHelper
{
};
template < typename T > constexpr int RCSResourceAttributes::IndexOfType< T >::value;
+ //! @endcond
/**
* @relates RCSResourceAttributes::Type
NEVER, /**< Requests will be ignored if attributes of the request contain
a new key or a value that has different type from the current
value of the key. */
- ACCEPTANCE /**< The whole attributes of the request will be applied
+ ACCEPTANCE /**< The attributes of the request will be applied unconditionally
even if there are new name or type conflicts. */
};
/**
* Sets whether the resource is discoverable.
*
- * @param discoverable whether to be discovered.
+ * @param discoverable whether to be discoverable.
*
*/
Builder& setDiscoverable(bool discoverable);
/**
* Sets the observable property of the resource.
*
- * @param observable whether to be observed.
+ * @param observable whether to be observable.
*
*/
Builder& setObservable(bool observable);
/**
- * Sets attribute of the resource.
+ * Sets attributes for the resource.
*
* @param attributes attributes to set
*
const RCSResourceAttributes& getAttributes() const;
/**
- * Checks whether the particular resource is observable or not.
+ * Checks whether the resource is observable or not.
*/
virtual bool isObservable() const;
/**
- * Checks whether the particular resource is discoverable or not.
+ * Checks whether the resource is discoverable or not.
*/
virtual bool isDiscoverable() const;
* Sets the get request handler.
* To remove handler, pass empty handler or nullptr.
*
- * Default behavior is RCSGetResponse::defaultAction()
+ * Default behavior is RCSGetResponse::defaultAction().
*
* @param handler a get request handler
*
* Sets the set request handler.
* To remove handler, pass empty handler or nullptr.
*
- * Default behavior is RCSGetResponse::defaultAction()
+ * Default behavior is RCSSetResponse::defaultAction().
*
* @param handler a set request handler
*
virtual void setSetRequestHandler(SetRequestHandler handler);
/**
- * Adds a listener for a particular attribute update.
+ * Adds a listener for a particular attribute updated.
*
* @param key the interested attribute's key
* @param listener listener to be invoked
AttributeUpdatedListener listener);
/**
- * Removes a listener for a particular attribute update.
+ * Removes a listener for a particular attribute updated.
*
- * @param key the key to be removed
+ * @param key the key associated with the listener to be removed
+ *
+ * @return True if the listener added with same key exists and is removed.
*
*/
virtual bool removeAttributeUpdatedListener(const std::string& key);
};
/**
- * The class provides a convinent RAII-style mechanism for the attributes of a
+ * The class provides a convenient RAII-style mechanism for the attributes of a
* RCSResourceObject. When a LockGuard is created, it attempts to lock the attributes of
* the RCSResourceObject it is given. When control leaves the scope in which the LockGuard
* object was created, the LockGuard is destructed and the attributes is unlocked.
ExpiryTimerImpl::ExpiryTimerImpl() :
m_tasks{ },
- m_thread{ std::thread(&ExpiryTimerImpl::run, this) },
+ m_thread{ },
m_mutex{ },
m_cond{ },
m_stop{ false },
m_mt{ std::random_device{ }() },
m_dist{ }
{
+ m_thread = std::thread(&ExpiryTimerImpl::run, this);
}
ExpiryTimerImpl::~ExpiryTimerImpl()
#include "RCSDiscoveryManager.h"
#include "RCSDiscoveryManagerImpl.h"
-#define TAG "RCSDiscoveryManager"
-
-namespace OIC {
- namespace Service {
-
- RCSDiscoveryManager* RCSDiscoveryManager::getInstance() {
- static RCSDiscoveryManager instance;
- return &instance;
+namespace OIC
+{
+ namespace Service
+ {
+ RCSDiscoveryManager::DiscoveryTask::DiscoveryTask(unsigned int id) :
+ m_id { id }
+ {
}
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResource
- (const RCSAddress& address, ResourceDiscoveredCallback cb) {
- return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI, "",
- std::move(cb));
+ bool RCSDiscoveryManager::DiscoveryTask::isCanceled()
+ {
+ return RCSDiscoveryManagerImpl::getInstance()->isCanceled(m_id);
}
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResource
- (const RCSAddress& address, const std::string& relativeURI, ResourceDiscoveredCallback cb) {
- return discoverResourceByType(address, relativeURI, "", std::move(cb));
+ void RCSDiscoveryManager::DiscoveryTask::cancel()
+ {
+ RCSDiscoveryManagerImpl::getInstance()->cancel(m_id);
}
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResourceByType(
- const RCSAddress& address, const std::string& resourceType, ResourceDiscoveredCallback cb) {
- return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI,
- resourceType, std::move(cb));
+ RCSDiscoveryManager* RCSDiscoveryManager::getInstance()
+ {
+ static RCSDiscoveryManager instance;
+ return &instance;
}
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManager::discoverResourceByType(
- const RCSAddress& address, const std::string& relativeURI,
- const std::string& resourceType, ResourceDiscoveredCallback cb) {
- return RCSDiscoveryManagerImpl::getInstance()->startDiscovery(address,
- relativeURI.empty() ? OC_RSRVD_WELL_KNOWN_URI : relativeURI,
- resourceType, std::move(cb));
+ RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResource(
+ const RCSAddress& address, ResourceDiscoveredCallback cb)
+ {
+ return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI, "", std::move(cb));
}
- RCSDiscoveryManager::DiscoveryTask::~DiscoveryTask(){
- cancel();
+
+ RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResource(
+ const RCSAddress& address, const std::string& relativeUri,
+ ResourceDiscoveredCallback cb)
+ {
+ return discoverResourceByType(address, relativeUri, "", std::move(cb));
}
- bool RCSDiscoveryManager::DiscoveryTask::isCanceled() {
- auto it = RCSDiscoveryManagerImpl::getInstance();
- if(it->m_discoveryMap.find(m_id) == it->m_discoveryMap.end())
- {
- return true;
- }
- return false;
+ RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResourceByType(
+ const RCSAddress& address, const std::string& resourceType,
+ ResourceDiscoveredCallback cb)
+ {
+ return discoverResourceByType(address, OC_RSRVD_WELL_KNOWN_URI, resourceType,
+ std::move(cb));
}
- void RCSDiscoveryManager::DiscoveryTask::cancel(){
- RCSDiscoveryManagerImpl::getInstance()->cancel(m_id);
+ RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManager::discoverResourceByType(
+ const RCSAddress& address, const std::string& relativeUri,
+ const std::string& resourceType, ResourceDiscoveredCallback cb)
+ {
+ return RCSDiscoveryManagerImpl::getInstance()->startDiscovery(address,
+ relativeUri.empty() ? OC_RSRVD_WELL_KNOWN_URI : relativeUri, resourceType,
+ std::move(cb));
}
}
}
#include "RCSDiscoveryManagerImpl.h"
#include "OCPlatform.h"
-
#include "PresenceSubscriber.h"
#include "RCSAddressDetail.h"
#include "RCSAddress.h"
-constexpr unsigned int RESETNUMBER = 0;
-constexpr unsigned int LIMITNUMBER = 1000;
-constexpr unsigned int INTERVALTIME = 60000;
+namespace
+{
+ constexpr unsigned int POLLING_INTERVAL_TIME = 60000;
+}
namespace OIC
{
namespace Service
{
- unsigned int RCSDiscoveryManagerImpl::s_uniqueId = RESETNUMBER;
- RCSDiscoveryManagerImpl * RCSDiscoveryManagerImpl::s_instance(nullptr);
- std::mutex RCSDiscoveryManagerImpl::s_mutexForCreation;
-
- RCSDiscoveryManagerImpl::RCSDiscoveryManagerImpl() : m_timerHandle(0){}
+ RCSDiscoveryManagerImpl::RCSDiscoveryManagerImpl()
+ {
+ srand (time(NULL));
+ requestMulticastPresence();
+ m_timer.post(POLLING_INTERVAL_TIME, std::bind(&RCSDiscoveryManagerImpl::onPolling, this));
+ }
RCSDiscoveryManagerImpl* RCSDiscoveryManagerImpl::getInstance()
{
- if (!s_instance)
- {
- s_mutexForCreation.lock();
- if (!s_instance)
- {
- s_instance = new RCSDiscoveryManagerImpl();
- srand(time(NULL));
- s_instance->initializedDiscoveryEnvironment();
- s_instance->requestMulticastPresence();
- s_instance->m_timerHandle = s_instance->m_timer.post(INTERVALTIME, s_instance->m_pollingCB);
- }
- s_mutexForCreation.unlock();
- }
- return s_instance;
+ static RCSDiscoveryManagerImpl instance;
+ return &instance;
}
- void RCSDiscoveryManagerImpl::findCallback(std::shared_ptr< PrimitiveResource > resource,
- RCSDiscoveryManagerImpl::ID discoverID)
+ void RCSDiscoveryManagerImpl::onResourceFound(std::shared_ptr<PrimitiveResource> resource,
+ RCSDiscoveryManagerImpl::ID discoveryId,
+ const RCSDiscoveryManager::ResourceDiscoveredCallback& discoverCB)
{
- std::lock_guard<std::mutex> lock(m_mutex);
-
- if(!isDuplicatedCallback(resource,discoverID))
{
- for(auto it = m_discoveryMap.begin(); it != m_discoveryMap.end(); ++it)
- {
- if(it->first == discoverID)
- {
- it->second.m_isReceivedFindCallback = true;
- it->second.m_discoverCB(std::make_shared<RCSRemoteResourceObject>(resource));
- }
- }
+ std::lock_guard < std::mutex > lock(m_mutex);
+ auto it = m_discoveryMap.find(discoveryId);
+
+ if (it == m_discoveryMap.end()) return;
+ if (it->second.isKnownResource(resource)) return;
}
+ discoverCB(std::make_shared < RCSRemoteResourceObject > (resource));
}
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> RCSDiscoveryManagerImpl::startDiscovery
- (const RCSAddress& address, const std::string& relativeURI, const std::string& resourceType,
- RCSDiscoveryManager::ResourceDiscoveredCallback cb)
+ RCSDiscoveryManager::DiscoveryTask::Ptr RCSDiscoveryManagerImpl::startDiscovery(
+ const RCSAddress& address, const std::string& relativeUri,
+ const std::string& resourceType, RCSDiscoveryManager::ResourceDiscoveredCallback cb)
{
if (!cb)
{
- throw RCSInvalidParameterException { "input Parameter(callback) is NULL" };
+ throw RCSInvalidParameterException { "Callback is empty" };
}
- DiscoverRequestInfo discoveryItem;
- discoveryItem.m_address = RCSAddressDetail::getDetail(address)->getAddress();
- discoveryItem.m_relativeUri = relativeURI;
- discoveryItem.m_resourceType = resourceType;
- discoveryItem.m_discoverCB = std::move(cb);
- discoveryItem.m_isReceivedFindCallback = false;
-
- ID discoverID = createId();
- discoveryItem.m_findCB = std::bind(&RCSDiscoveryManagerImpl::findCallback, this,
- std::placeholders::_1, discoverID);
- m_discoveryMap.insert(std::make_pair(discoverID, discoveryItem));
+ ID discoveryId = createId();
+ auto discoverCb = std::bind(&RCSDiscoveryManagerImpl::onResourceFound, this,
+ std::placeholders::_1, discoveryId, std::move(cb));
+ DiscoveryRequestInfo discoveryInfo(RCSAddressDetail::getDetail(address)->getAddress(),
+ relativeUri, resourceType, std::move(discoverCb));
+ discoveryInfo.discover();
- OIC::Service::discoverResource(RCSAddressDetail::getDetail(RCSAddress::multicast())->getAddress(),
- discoveryItem.m_relativeUri + "?rt=" +discoveryItem.m_resourceType,
- OCConnectivityType::CT_DEFAULT, discoveryItem.m_findCB);
+ {
+ std::lock_guard < std::mutex > lock(m_mutex);
+ m_discoveryMap.insert(std::make_pair(discoveryId, std::move(discoveryInfo)));
+ }
- return std::unique_ptr<RCSDiscoveryManager::DiscoveryTask>(
- new RCSDiscoveryManager::DiscoveryTask(discoverID));
- }
-
- void RCSDiscoveryManagerImpl::initializedDiscoveryEnvironment()
- {
- m_presenceCB = std::bind(&RCSDiscoveryManagerImpl::presenceCallback, this,
- std::placeholders::_1, std::placeholders::_2,std::placeholders::_3);
- m_pollingCB = std::bind(&RCSDiscoveryManagerImpl::pollingCallback, this,
- std::placeholders::_1);
+ return std::unique_ptr < RCSDiscoveryManager::DiscoveryTask> (
+ new RCSDiscoveryManager::DiscoveryTask(discoveryId));
}
void RCSDiscoveryManagerImpl::requestMulticastPresence()
{
- static constexpr char MULTICAST_PRESENCE_ADDRESS[] = "coap://" OC_MULTICAST_PREFIX;
+ constexpr char MULTICAST_PRESENCE_ADDRESS[] = "coap://" OC_MULTICAST_PREFIX;
OCDoHandle presenceHandle;
subscribePresence(presenceHandle, MULTICAST_PRESENCE_ADDRESS,
- OCConnectivityType::CT_DEFAULT, std::move(m_presenceCB));
+ OCConnectivityType::CT_DEFAULT,
+ std::move(std::bind(&RCSDiscoveryManagerImpl::onPresence, this,
+ std::placeholders::_1, std::placeholders::_2,
+ std::placeholders::_3)));
}
- bool RCSDiscoveryManagerImpl::isDuplicatedCallback(std::shared_ptr< PrimitiveResource > resource,
- ID discoverID)
+ void RCSDiscoveryManagerImpl::onPolling()
{
- std::string retID = resource->getSid()+resource->getUri();
- auto it = m_discoveryMap.find(discoverID);
- std::list<std::string>::iterator itor;
- if(it==m_discoveryMap.end())
- {
- return false;
- }
- itor = std::find(it->second.m_receivedIds.begin(),it->second.m_receivedIds.end(),retID);
- if(itor != it->second.m_receivedIds.end())
- {
- return true;
- }
- it->second.m_receivedIds.push_back(retID);
+ std::lock_guard < std::mutex > lock(m_mutex);
- return false;
- }
-
- void RCSDiscoveryManagerImpl::pollingCallback(unsigned int /*msg*/)
- {
- std::lock_guard<std::mutex> lock(m_mutex);
- for(auto it = m_discoveryMap.begin(); it != m_discoveryMap.end(); ++it)
+ for (const auto& it : m_discoveryMap)
{
- OIC::Service::discoverResource(it->second.m_address,it->second.m_relativeUri+ "?rt="
- +it->second.m_resourceType, OCConnectivityType::CT_DEFAULT, it->second.m_findCB);
+ it.second.discover();
}
- m_timerHandle = m_timer.post(INTERVALTIME, m_pollingCB);
+ m_timer.post(POLLING_INTERVAL_TIME, std::bind(&RCSDiscoveryManagerImpl::onPolling, this));
}
- void RCSDiscoveryManagerImpl::presenceCallback(OCStackResult ret,
- const unsigned int /*seq*/, const std::string& /*address*/)
+ void RCSDiscoveryManagerImpl::onPresence(OCStackResult ret, const unsigned int /*seq*/,
+ const std::string& address)
{
- if(ret == OC_STACK_OK || ret == OC_STACK_RESOURCE_CREATED || ret == OC_STACK_RESOURCE_DELETED)
+ if (ret != OC_STACK_OK && ret != OC_STACK_RESOURCE_CREATED) return;
+
+ std::lock_guard < std::mutex > lock(m_mutex);
+ for (const auto& it : m_discoveryMap)
{
- std::lock_guard<std::mutex> lock(m_mutex);
- for(auto it = m_discoveryMap.begin(); it != m_discoveryMap.end(); ++it)
+ if (it.second.isMatchingAddress(address))
{
- if(!it->second.m_isReceivedFindCallback)
- {
- OIC::Service::discoverResource(it->second.m_address, it->second.m_relativeUri+ "?rt=" +
- it->second.m_resourceType, OCConnectivityType::CT_DEFAULT, it->second.m_findCB);
- }
+ it.second.discover();
}
}
}
RCSDiscoveryManagerImpl::ID RCSDiscoveryManagerImpl::createId()
{
- std::lock_guard<std::mutex> lock(m_mutex);
- if(s_uniqueId<LIMITNUMBER)
- {
- s_uniqueId++;
- }
- else
- {
- s_uniqueId = RESETNUMBER;
- }
- while(m_discoveryMap.size() != LIMITNUMBER)
+ std::lock_guard < std::mutex > lock(m_mutex);
+ static ID s_uniqueId;
+
+ s_uniqueId++;
+ while (m_discoveryMap.find(s_uniqueId) != m_discoveryMap.end())
{
- if(m_discoveryMap.find(s_uniqueId) == m_discoveryMap.end())
- {
- return s_uniqueId;
- }
s_uniqueId++;
}
-
- return RESETNUMBER;
+ return s_uniqueId;
}
void RCSDiscoveryManagerImpl::cancel(ID id)
{
- std::lock_guard<std::mutex> lock(m_mutex);
+ std::lock_guard < std::mutex > lock(m_mutex);
m_discoveryMap.erase(id);
}
+
+ bool RCSDiscoveryManagerImpl::isCanceled(ID id)
+ {
+ std::lock_guard < std::mutex > lock(m_mutex);
+ auto it = m_discoveryMap.find(id);
+ if (it == m_discoveryMap.end()) return true;
+
+ return false;
+ }
+
+ DiscoveryRequestInfo::DiscoveryRequestInfo(const std::string &address,
+ const std::string &relativeUri, const std::string &resourceType,
+ DiscoverCallback cb) :
+ m_address(address), m_relativeUri(relativeUri), m_resourceType(resourceType),
+ m_discoverCb(std::move(cb))
+ {
+ }
+
+ void DiscoveryRequestInfo::discover() const
+ {
+ OIC::Service::discoverResource(m_address, m_relativeUri + "?rt=" + m_resourceType,
+ OCConnectivityType::CT_DEFAULT, m_discoverCb);
+ }
+
+ bool DiscoveryRequestInfo::isKnownResource(
+ const std::shared_ptr<PrimitiveResource>& resource)
+ {
+ std::string resourceId = resource->getSid() + resource->getUri();
+
+ auto it = std::find(m_receivedIds.begin(), m_receivedIds.end(), resourceId);
+
+ if (it != m_receivedIds.end()) return true;
+ m_receivedIds.insert(resourceId);
+ return false;
+ }
+
+ bool DiscoveryRequestInfo::isMatchingAddress(const std::string& address) const
+ {
+ return m_address == RCSAddressDetail::getDetail(RCSAddress::multicast())->getAddress()
+ || m_address == address;
+ }
}
}
#include <memory>
#include <functional>
-#include <list>
#include <mutex>
#include <unordered_map>
-#include <algorithm>
-
-#include "octypes.h"
+#include <unordered_set>
#include "RCSDiscoveryManager.h"
-#include "RCSAddress.h"
#include "ExpiryTimer.h"
#include "PrimitiveResource.h"
#include "RCSRemoteResourceObject.h"
*
* @see RCSDiscoveryManager
*/
- class DiscoverRequestInfo
+ class DiscoveryRequestInfo
{
public:
+ DiscoveryRequestInfo(const std::string &, const std::string &,
+ const std::string &, DiscoverCallback);
+
+ public:
+ void discover() const;
+ bool isKnownResource(const std::shared_ptr<PrimitiveResource>&);
+ bool isMatchingAddress(const std::string&) const;
+ private:
std::string m_address;
std::string m_relativeUri;
std::string m_resourceType;
- std::list<std::string> m_receivedIds;
- bool m_isReceivedFindCallback;
- DiscoverCallback m_findCB;
- RCSDiscoveryManager::ResourceDiscoveredCallback m_discoverCB;
+ std::unordered_set<std::string> m_receivedIds;
+ DiscoverCallback m_discoverCb;
};
/**
*/
class RCSDiscoveryManagerImpl
{
- static unsigned int s_uniqueId;
-
public:
/*
- * Typedef for callback of requesting presence API
- *
- * @see requestMulticastPresence
- */
- typedef std::function<void(OCStackResult, const unsigned int,
- const std::string&)> PresenceCallback;
-
- /*
* Typedef for discovery request ID
*
* @note This is generated for each discovery request
*/
typedef unsigned int ID;
- /*
- * Typedef for callback of discoverResource API
- */
- typedef std::function<void(std::shared_ptr< PrimitiveResource >, ID)> FindCallback;
-
public:
- /*
- * @return Returns RCSDiscoveryManagerImpl instance.
- */
static RCSDiscoveryManagerImpl* getInstance();
- DiscoverRequestInfo m_discoveryItem;
- std::unordered_map<ID,DiscoverRequestInfo> m_discoveryMap;
- PresenceCallback m_presenceCB;
- ExpiryTimer::Callback m_pollingCB;
- ExpiryTimer m_timer;
- ID m_timerHandle;
-
- private:
- static RCSDiscoveryManagerImpl * s_instance;
- static std::mutex s_mutexForCreation;
- std::mutex m_mutex;
-
- public:
-
/**
- * Starting discovery of resource
+ * Start discovery of resource
*
* @return DiscoverTask pointer
*
*
* @throws InvalidParameterException If cb is empty
*
- * @note If relativeURI is empty, will be discovered after be changed into "OC_RSRVD_WELL_KNOWN_URI"
+ * @note If relativeURI is empty, will be discovered after be changed into
+ * "OC_RSRVD_WELL_KNOWN_URI"
* @note If resourceType is empty, will be discovered all resources in network
*
* @see RCSAddress
* @see RCSDiscoveryManager
*/
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> startDiscovery(const RCSAddress& address,
+ RCSDiscoveryManager::DiscoveryTask::Ptr startDiscovery(const RCSAddress& address,
const std::string& relativeURI,const std::string& resourceType,
RCSDiscoveryManager::ResourceDiscoveredCallback cb);
+
void cancel(ID);
+ bool isCanceled(ID);
+
private:
+ RCSDiscoveryManagerImpl();
+ ~RCSDiscoveryManagerImpl() = default;
/**
- * Requesting presence by multicast
+ * Request presence by multicast
*/
void requestMulticastPresence();
/**
- * Initializing callback of presence and polling
- */
- void initializedDiscoveryEnvironment();
-
- /**
- * Checking duplicated callback and invoking callback when resource is discovered
+ * Check duplicated callback and invoke callback when resource is discovered
*
* @param resource A pointer of discovered resource
* @param discoverID The ID of discovery request
+ * @param cb Callback
*
* @see PrimitiveResource
*/
- void findCallback(std::shared_ptr< PrimitiveResource > resource, ID discoverID);
+ void onResourceFound(std::shared_ptr<PrimitiveResource> resource, ID discoveryId,
+ const RCSDiscoveryManager::ResourceDiscoveredCallback& cb);
/**
- * Discovering resource on all requests and posting timer when timer is expired
+ * Discover resource on all requests and posting timer when timer is expired
*/
- void pollingCallback(unsigned int /*msg*/);
+ void onPolling();
/**
- * Discovering resource on all requests when supporting presence function resource enter into network
- *
- * @param ret Not used in this class
- * @param seq Not used in this class
- * @param address A address of supporting presence function resource
+ * Discover resource on all requests when supporting presence function resource
+ * enter into network
*/
- void presenceCallback(OCStackResult, const unsigned int,const std::string&);
+ void onPresence(OCStackResult ret, const unsigned int seq, const std::string& address);
/**
- * Checking duplicated callback
- *
- * @return The callback is duplicated or not
- *
- * @param resource A pointer of discovered resource
- * @param discoverID The ID of discovery request
- *
- * @see PrimitiveResource
- */
- bool isDuplicatedCallback(std::shared_ptr<PrimitiveResource> resource, ID discoverID);
-
- /**
- * Creating unique id
+ * Create unique id
*
* @return Returns the id
*/
ID createId();
+ public:
+ ExpiryTimer m_timer;
+
private:
- RCSDiscoveryManagerImpl();
- ~RCSDiscoveryManagerImpl() = default;
+ std::unordered_map<ID,DiscoveryRequestInfo> m_discoveryMap;
+ std::mutex m_mutex;
};
}
}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.resourcecontainer.bundle.api;
-
-import java.util.List;
-import java.util.Vector;
-
-/**
- * The BaseActivator implements the native interface to the resource container.
- * It loads the resource container library and provies native methods
- * that can be used to register and unregister resources.
- */
-public class BaseActivator implements BundleActivator {
- private String bundleId;
- private Vector<BundleResource> bundleResources = new Vector<BundleResource>();
-
- /**
- * Creates an instance of the BaseActivator
- * @param bundleId unique bundle identifier (e.g., oic.bundle.hue)
- */
- public BaseActivator(String bundleId) {
- this.bundleId = bundleId;
-
- }
-
- static {
- try {
- System.loadLibrary("ResContainerLib");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Bundle activation needs to be provided by the subclass.
- */
- public void activateBundle() {
-
- }
-
- /**
- * Deactivates the bundle and unregisters its resources.
- */
- public void deactivateBundle() {
- System.out.println("Deactivating bundle (Base Activator).");
- for(BundleResource bundleResource : bundleResources){
- unregisterResource(bundleResource);
- }
- }
-
- /**
- * Registers a bundle resource at the resource container.
- * @param resource bundle resource instance that should be made available as OIC resource
- */
- public void registerResource(BundleResource resource) {
- bundleResources.add(resource);
- registerJavaResource(resource, resource.getAttributeKeys(), bundleId,
- resource.getURI(), resource.getResourceType(),
- resource.getName());
- }
-
- /**
- * Wrapper to retrieve the resource configuration of the bundle resources.
- * @return List of resource configurations.
- */
- public List<ResourceConfig> getConfiguredBundleResources() {
- int configuredResources = getNumberOfConfiguredResources(bundleId);
-
- Vector<ResourceConfig> configs = new Vector<ResourceConfig>();
-
- for (int i = 0; i < configuredResources; i++) {
- String[] resourceParams = getConfiguredResourceParams(bundleId, i);
- ResourceConfig config = new ResourceConfig(resourceParams);
- configs.add(config);
-
- }
- return configs;
- }
-
- /**
- * Unregisters a resource from the resource container.
- */
- public void unregisterResource(BundleResource resource) {
- bundleResources.remove(resource);
- unregisterJavaResource(resource, resource.getURI());
- }
-
- /**
- * Native method that calls to the resource container.
- * @param attributes String array of attribute names
- * @param bundleId unique bundle identifier
- * @param uri Uri that should be used to register the resource
- */
- private native void registerJavaResource(BundleResource resource,
- String[] attributes, String bundleId, String uri,
- String resourceType, String name);
-
- /**
- * Native method that calls to the resource container.
- * @param resource
- * @param uri
- */
- private native void unregisterJavaResource(BundleResource resource, String uri);
-
- /**
- * Native method to retrieve the number of configured resources.
- * @param bundleId unique bundle identifier
- */
- private native int getNumberOfConfiguredResources(String bundleId);
-
- /**
- * Native method to retrieve the configured resource parameters.
- * @param bundleId unique bundle identifier
- * @param resId get the resource params for a certain resource
- */
- private native String[] getConfiguredResourceParams(String bundleId,
- int resId);
-
-}
+++ /dev/null
-//******************************************************************
-//
-// Copyright 2015 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.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-package org.iotivity.resourcecontainer.bundle.api;
-
-import java.util.HashMap;
-import java.util.Set;
-
-/**
- * Basic BundleResource that should be used as a base class
- * by a bundle resources. A concrete technology has
- * to override the setAttribute and getAttribute method
- * and map the according reads and writes to the technology specific
- * messages.
- */
-public abstract class BundleResource {
- protected String m_name, m_uri, m_resourceType, m_address;
-
- protected HashMap<String, String> m_attributes;
-
- /**
- * Initialize the internal attribute structure.
- */
- protected abstract void initAttributes();
-
- /**
- * Set the attribute (map to a send command for the according protocol)
- * @param key name of the attribute to be set
- * @param value new value of the attribute
- */
- public abstract void setAttribute(String key, String value);
-
- /**
- * Retrieve the attribute (map to read command for the according protocol)
- * @param key name of the attribute to be read
- * @return Value of the attribute
- */
- public abstract String getAttribute(String key);
-
- /**
- * Attribute keys provided through by the bundle resource.
- * @return Name of attribute keys as string array
- */
- public String[] getAttributeKeys() {
- Set<String> keys = m_attributes.keySet();
- return keys.toArray(new String[keys.size()]);
- }
-
- /**
- * Setter for the uri property
- * @param uri URI of the resource
- */
- public void setURI(String uri) {
- this.m_uri = uri;
- }
-
- /**
- * Returns the URI of the resource
- * @return Resource URI
- */
- public String getURI() {
- return m_uri;
- }
-
- /**
- * Sets the resource type property
- * @param resourceType OIC resource type
- */
- public void setResourceType(String resourceType) {
- this.m_resourceType = resourceType;
- }
-
- /**
- * Getter for the resource type
- * @return OIC resource type
- */
- public String getResourceType() {
- return m_resourceType;
- }
-
- /**
- * Sets the technology specific address information (e.g., ZigBee short or long identifier)
- * @param address Resource address
- */
- public void setAddress(String address) {
- this.m_address = address;
- }
-
- /**
- * Returns the technology specific address information
- * @return Resource address
- */
- public String getAddress() {
- return m_address;
- }
-
- /**
- * Sets the name property of the resource
- * @param name Resource name
- */
- public void setName(String name) {
- this.m_name = name;
- }
-
- /**
- * Returns the name property of the resource
- * @return Resource name
- */
- public String getName() {
- return m_name;
- }
-
-}
+++ /dev/null
-package org.iotivity.bundle.hue;
-
-import java.util.List;
-
-import org.iotivity.resourcecontainer.bundle.api.BaseActivator;
-import org.iotivity.resourcecontainer.bundle.api.ResourceConfig;
-
-public class HueBundleActivator extends BaseActivator {
- private HueConnector connector;
-
- public HueBundleActivator(String bundleId) {
- super(bundleId);
- }
-
- public void activateBundle() {
- super.activateBundle();
- connector = new HueConnector();
- List<ResourceConfig> resourceConfig = getConfiguredBundleResources();
-
- for (ResourceConfig config : resourceConfig) {
-
- HueLightResource hueLightResource = new HueLightResource(connector,
- config.getName(), config.getURI(),
- config.getResourceType(), config.getAddress());
-
- System.out.println("Registration of HueLightresource");
- registerResource(hueLightResource);
- }
- }
-
- public void deactivateBundle() {
- System.out.println("Deactivate bundle called.");
- super.deactivateBundle();
- }
-
- // test call
- public static void main(String[] args) {
- HueBundleActivator activator = new HueBundleActivator("oic.hue.bundle");
- }
-}
+++ /dev/null
-package org.iotivity.bundle.hue;
-
-import java.util.HashMap;
-
-import org.iotivity.resourcecontainer.bundle.api.BundleResource;
-
-/**
- * This class maps a Philips Hue light to OIC light resource
- *
- * @author iotivity
- */
-public class HueLightResource extends BundleResource {
- private HueConnector m_hueConnector;
-
- public HueLightResource() {
- initAttributes();
- m_resourceType = "oic.light.control";
-
- }
-
- public HueLightResource(HueConnector hueConnector, String name, String uri,
- String resourceType, String address) {
- this();
- this.m_hueConnector = hueConnector;
- m_name = name;
- m_uri = uri;
- m_resourceType = resourceType;
- m_address = address;
- }
-
- protected void initAttributes() {
- m_attributes = new HashMap<String, String>();
- m_attributes.put("on-off", "true");
- m_attributes.put("color", "0");
- m_attributes.put("dim", "0");
- }
-
- public void setAttribute(String key, String value) {
- System.out.println("Set attribute called - key: " + key + ", value: "
- + value + " transmitting now.");
-
- if ("on-off".equals(value)) {
- m_hueConnector.transmit(m_address + "/state", "{\"on\":" + value
- + "}");
- }
-
- if ("dim".equals(value)) {
- m_hueConnector.transmit(m_address + "/state", "{\"bri\":" + value
- + "}");
- }
-
- if ("color".equals(value)) {
- m_hueConnector.transmit(m_address + "/state", "{\"hue\":" + value
- + "}");
- }
- m_attributes.put(key, value);
- }
-
- public String getAttribute(String key) {
-
- // map key to hue address
- // read from Hue gateway, parse resource representation and return
- // attribute
- //m_hueConnector.read(m_address);
- return m_attributes.get(key);
- }
-
- @Override
- public String toString() {
- return "HueLightResource [m_hueConnector=" + m_hueConnector
- + ", m_name=" + m_name + ", m_uri=" + m_uri
- + ", m_resourceType=" + m_resourceType + ", m_address="
- + m_address + ", m_attributes=" + m_attributes + "]";
- }
-
-}
#include "OCPlatform.h"
+#include <condition_variable>
+#include <mutex>
+
using namespace OIC::Service;
using namespace OC::OCPlatform;
constexpr char RESOURCEURI[]{ "/a/TemperatureSensor" };
constexpr char RESOURCETYPE[]{ "resource.type" };
constexpr char RESOURCEINTERFACE[]{ "oic.if.baseline" };
-constexpr int DiscoveryTaskDELAYTIME = 7;
+constexpr int DEFAULT_DISCOVERYTASK_DELAYTIME = 3000;
+
+void resourceDiscoveredForCall(RCSRemoteResourceObject::Ptr) {}
+void resourceDiscoveredForNeverCall(RCSRemoteResourceObject::Ptr) {}
class DiscoveryManagerTest: public TestWithMock
{
public:
- RCSResourceObject::Ptr server;
- RCSRemoteResourceObject::Ptr object;
- std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
-
+ typedef std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> DiscoveryTaskPtr;
+ typedef std::function< void(std::shared_ptr< RCSRemoteResourceObject >) >
+ ResourceDiscoveredCallback;
public:
- void startDiscovery()
+ static DiscoveryTaskPtr discoverResource(ResourceDiscoveredCallback cb)
{
const std::string uri = "/oic/res";
- discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
- uri, RESOURCETYPE, &resourceDiscovered);
+ return RCSDiscoveryManager::getInstance()->discoverResourceByType(RCSAddress::multicast(),
+ uri, RESOURCETYPE, cb);
+ }
+
+ void startDiscovery()
+ {
+ discoveryTask = discoverResource(resourceDiscoveredForCall);
}
void cancelDiscovery()
discoveryTask->cancel();
}
+ bool isCanceled()
+ {
+ return discoveryTask->isCanceled();
+ }
+
void createResource()
{
server = RCSResourceObject::Builder(RESOURCEURI, RESOURCETYPE, RESOURCEINTERFACE).build();
}
- void waitForDiscoveryTask()
+ void proceed()
+ {
+ cond.notify_all();
+ }
+
+ void waitForDiscoveryTask(int waitingTime = DEFAULT_DISCOVERYTASK_DELAYTIME)
{
- sleep(DiscoveryTaskDELAYTIME);
+ std::unique_lock< std::mutex > lock{ mutex };
+ cond.wait_for(lock, std::chrono::milliseconds{ waitingTime });
}
- static void resourceDiscovered(std::shared_ptr< RCSRemoteResourceObject >) {}
+private:
+ std::condition_variable cond;
+ std::mutex mutex;
+ RCSResourceObject::Ptr server;
+ RCSRemoteResourceObject::Ptr object;
+ DiscoveryTaskPtr discoveryTask;
};
TEST_F(DiscoveryManagerTest, resourceIsNotSupportedPresenceBeforeDiscovering)
{
createResource();
- mocks.ExpectCallFunc(resourceDiscovered);
+ mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
+ [this](RCSRemoteResourceObject::Ptr){ proceed();});
startDiscovery();
waitForDiscoveryTask();
startPresence(10);
createResource();
- mocks.ExpectCallFunc(resourceDiscovered);
+ mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
+ [this](RCSRemoteResourceObject::Ptr){ proceed();});
startDiscovery();
waitForDiscoveryTask();
+ stopPresence();
}
TEST_F(DiscoveryManagerTest, resourceIsNotSupportedPresenceAfterDiscovering)
{
- mocks.ExpectCallFunc(resourceDiscovered);
+ mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
+ [this](RCSRemoteResourceObject::Ptr){ proceed();});
startDiscovery();
createResource();
TEST_F(DiscoveryManagerTest, resourceIsSupportedPresenceAndAfterDiscovering)
{
- mocks.ExpectCallFunc(resourceDiscovered);
+ mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
+ [this](RCSRemoteResourceObject::Ptr){ proceed();});
startPresence(10);
startDiscovery();
createResource();
waitForDiscoveryTask();
+ stopPresence();
}
TEST_F(DiscoveryManagerTest, cancelDiscoveryTaskAfterDiscoveryResource)
startDiscovery();
cancelDiscovery();
- mocks.NeverCallFunc(resourceDiscovered);
+ mocks.NeverCallFunc(resourceDiscoveredForCall);
- sleep(3);
+ waitForDiscoveryTask();
createResource();
-
}
TEST_F(DiscoveryManagerTest, cancelDiscoveryTaskNotStartDiscoveryResource)
cancelDiscovery();
cancelDiscovery();
}
+
+TEST_F(DiscoveryManagerTest, isCanceledAfterCancelDiscoveryTask)
+{
+ startDiscovery();
+ cancelDiscovery();
+
+ ASSERT_TRUE(isCanceled());
+}
+
+TEST_F(DiscoveryManagerTest, multipleDiscoveryRequestAndCancelJustOneDiscoveryRequest)
+{
+ DiscoveryTaskPtr canceledTask = discoverResource(resourceDiscoveredForCall);
+ DiscoveryTaskPtr notCanceledTask_1 = discoverResource(resourceDiscoveredForCall);
+ DiscoveryTaskPtr notCanceledTask_2 = discoverResource(resourceDiscoveredForCall);
+
+ canceledTask->cancel();
+
+ ASSERT_TRUE(canceledTask->isCanceled());
+ ASSERT_FALSE(notCanceledTask_1->isCanceled());
+ ASSERT_FALSE(notCanceledTask_2->isCanceled());
+}
+
+TEST_F(DiscoveryManagerTest, equalDiscoveryRequestsAndCancelJustOneRequest)
+{
+ mocks.ExpectCallFunc(resourceDiscoveredForCall).Do(
+ [this](RCSRemoteResourceObject::Ptr){ proceed();});
+
+ mocks.NeverCallFunc(resourceDiscoveredForNeverCall);
+
+ DiscoveryTaskPtr notCanceledTask = discoverResource(resourceDiscoveredForCall);
+ DiscoveryTaskPtr canceledTask = discoverResource(resourceDiscoveredForNeverCall);
+ canceledTask->cancel();
+
+ createResource();
+ waitForDiscoveryTask();
+}
lib_env = env.Clone()
SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
-notimgr_env = lib_env.Clone()
+resourcehosting_env = lib_env.Clone()
target_os = env.get('TARGET_OS')
######################################################################
# Build flags
######################################################################
-notimgr_env.AppendUnique(CPPPATH = ['NotificationManager/include'])
-notimgr_env.AppendUnique(CPPPATH = ['../resource-encapsulation/include'])
-notimgr_env.AppendUnique(CPPPATH = ['../resource-encapsulation/src/common/primitiveResource/include'])
+resourcehosting_env.AppendUnique(CPPPATH = ['include'])
+resourcehosting_env.AppendUnique(CPPPATH = ['../resource-encapsulation/include'])
+resourcehosting_env.AppendUnique(CPPPATH = ['../resource-encapsulation/src/common/primitiveResource/include'])
-notimgr_env.PrependUnique(LIBS = [
+resourcehosting_env.PrependUnique(LIBS = [
'rcs_client',
'rcs_server',
'rcs_common',
])
if target_os not in ['windows', 'winrt']:
- notimgr_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+ resourcehosting_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
if target_os not in ['darwin', 'ios', 'windows', 'winrt']:
- notimgr_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
+ resourcehosting_env.AppendUnique(LINKFLAGS = ['-Wl,--no-undefined'])
if target_os == 'linux':
- notimgr_env.AppendUnique(LIBS = ['pthread'])
+ resourcehosting_env.AppendUnique(LIBS = ['pthread'])
if target_os == 'android':
- notimgr_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
- notimgr_env.AppendUnique(LIBS = ['gnustl_shared','log'])
+ resourcehosting_env.AppendUnique(CXXFLAGS = ['-frtti', '-fexceptions'])
+ resourcehosting_env.AppendUnique(LIBS = ['gnustl_shared','log'])
if not env.get('RELEASE'):
- notimgr_env.AppendUnique(LIBS = ['log'])
+ resourcehosting_env.AppendUnique(LIBS = ['log'])
######################################################################
# Source files and Targets
######################################################################
-NOTI_SRC_DIR = 'NotificationManager/src/'
-notimgr_src = [
- NOTI_SRC_DIR + 'hosting.cpp',
- NOTI_SRC_DIR + 'ResourceHosting.cpp',
- NOTI_SRC_DIR + 'HostingObject.cpp',
- NOTI_SRC_DIR + 'RequestObject.cpp'
+HOSTING_SRC_DIR = 'src/'
+resourcehosting_src = [
+ HOSTING_SRC_DIR + 'Hosting.cpp',
+ HOSTING_SRC_DIR + 'ResourceHosting.cpp',
+ HOSTING_SRC_DIR + 'HostingObject.cpp',
+ HOSTING_SRC_DIR + 'RequestObject.cpp'
]
if target_os in ['tizen','android'] :
- notificationsdk = notimgr_env.SharedLibrary('NotificationManager', notimgr_src)
+ resourcehostingsdk = resourcehosting_env.SharedLibrary('resource_hosting', resourcehosting_src)
else :
- notificationsdk = notimgr_env.StaticLibrary('NotificationManager', notimgr_src)
+ resourcehostingsdk = resourcehosting_env.StaticLibrary('resource_hosting', resourcehosting_src)
-notimgr_env.InstallTarget(notificationsdk, 'libResouceHosting')
-notimgr_env.UserInstallTargetLib(notificationsdk, 'libResouceHosting')
-notimgr_env.UserInstallTargetHeader('NotificationManager/include/hosting.h',\
- 'service/notification-manager', 'hosting.h')
+resourcehosting_env.InstallTarget(resourcehostingsdk, 'libresource_hosting')
+resourcehosting_env.UserInstallTargetLib(resourcehostingsdk, 'libresource_hosting')
+resourcehosting_env.UserInstallTargetHeader('include/Hosting.h',\
+ 'service/resource-hosting', 'Hosting.h')
# Go to build Unit test
if target_os == 'linux':
- SConscript('NotificationManager/src/unittest/SConscript')
+ SConscript('src/unittest/SConscript')
# Go to build sample apps
SConscript('SampleApp/SConscript')
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
- <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
# Project target.
target=android-19
+android.library.reference.1=../../../android/resource_hosting
}
public void findResourceCandidate() {
- nmfindResource("", "/oic/res?rt=resource.hosting");
+ nmfindResource("", "/oic/res?rt=oic.r.resourcehosting");
current_log_result += "Finding Resource... \n";
tv_current_log_result.setText(current_log_result);
Log.i(TAG, current_log_result);
<classpathentry exported="true" kind="con" path="com.android.ide.eclipse.adt.DEPENDENCIES"/>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="gen"/>
- <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/iotivity/android/android_api/base/build/intermediates/bundles/release/classes.jar"/>
- <classpathentry exported="true" kind="lib" path="C:/Users/jay.sharma/Desktop/master_19_may/android-support-v4.jar"/>
<classpathentry kind="output" path="bin/classes"/>
</classpath>
# Project target.
target=android-19
+android.library.reference.1=../../../android/resource_hosting
public class StringConstants {
public static final String RESOURCE_URI = "/a/TempHumSensor/hosting";
- public static final String RESOURCE_TYPENAME = "resource.hosting";
+ public static final String RESOURCE_TYPENAME = "oic.r.resourcehosting";
public static final String RESOURCE_INTERFACE = OcPlatform.DEFAULT_INTERFACE; // resource interface
public static final String HUMIDITY = "humidity";
public static final String TEMPERATURE = "temperature";
# Project target.
target=android-19
+android.library.reference.1=../../../android/resource_hosting
--- /dev/null
+<resources>
+
+ <!--
+ Base application theme, dependent on API level. This theme is replaced
+ by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
+ -->
+ <style name="AppBaseTheme" parent="android:Theme.Light">
+ <!--
+ Theme customizations available in newer API levels can go in
+ res/values-vXX/styles.xml, while customizations related to
+ backward-compatibility can go here.
+ -->
+ </style>
+
+ <!-- Application theme. -->
+ <style name="AppTheme" parent="AppBaseTheme">
+ <!-- All customizations that are NOT specific to a particular API-level can go here. -->
+ </style>
+
+</resources>
--- /dev/null
+##
+# NotificationManager build script
+##
+
+Import('env')
+
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+resourcehosting_env = lib_env.Clone()
+
+######################################################################
+# Build flags
+######################################################################
+resourcehosting_env.AppendUnique(CPPPATH = ['../../include'])
+resourcehosting_env.AppendUnique(CPPPATH = ['../../../../extlibs/cjson'])
+resourcehosting_env.AppendUnique(CPPPATH = ['../../../../resource/csdk/connectivity/api'])
+resourcehosting_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-fmessage-length=0', '-std=c++0x'])
+resourcehosting_sample_env = resourcehosting_env.Clone()
+resourcehosting_env.AppendUnique(LIBS = [
+ 'resource_hosting',
+ 'rcs_client',
+ 'rcs_server',
+ 'rcs_common',
+ 'oc',
+ 'octbstack',
+ 'oc_logger',
+ 'connectivity_abstraction',
+ 'coap',
+ 'pthread'
+ ])
+resourcehosting_sample_env.AppendUnique(LIBS = [
+ 'oc',
+ 'octbstack',
+ 'oc_logger',
+ 'connectivity_abstraction',
+ 'coap',
+ 'pthread'
+ ])
+
+if env.get('SECURED') == '1':
+ resourcehosting_env.AppendUnique(LIBS = ['tinydtls'])
+ resourcehosting_sample_env.AppendUnique(LIBS = ['tinydtls'])
+if 'rt' in resourcehosting_env.get('LIBS'):
+ resourcehosting_env.Append(LIBS = ['rt'])
+if 'rt' in resourcehosting_sample_env.get('LIBS'):
+ resourcehosting_sample_env.Append(LIBS = ['rt'])
+
+####################################################################
+# Source files and Targets
+######################################################################
+sampleprovider = resourcehosting_sample_env.Program('sampleprovider', 'sampleProvider/SampleProvider.cpp')
+sampleconsumer = resourcehosting_sample_env.Program('sampleconsumer', 'sampleConsumer/SampleConsumer.cpp')
+
+sampleresourcehosting = resourcehosting_env.Program('sampleresourcehosting', 'sampleResourceHosting/main.cpp')
+
+#resourcehosting_sample_env.InstallTarget(sampleprovider, 'sampleprovider')
+#resourcehosting_sample_env.InstallTarget(sampleconsumer, 'sampleconsumer')
+#resourcehosting_env.InstallTarget(sampleresourcehosting, 'sampleresourcehosting')
const int SUCCESS_RESPONSE = OC_STACK_OK;
-#define OC_WELL_KNOWN_COORDINATING_QUERY "/oic/res?rt=resource.hosting"
+#define OC_WELL_KNOWN_COORDINATING_QUERY "/oic/res?rt=oic.r.resourcehosting"
#define OBSERVE 1
#define GET 2
std::cout << "* method Type : 1 - Observe *" << std::endl;
std::cout << "* method Type : 2 - Get *" << std::endl;
std::cout << "* method Type : 3 - Put *" << std::endl;
- std::cout << "* method Type : 4 - Delete *" << std::endl;
std::cout << "********************************************" << std::endl;
std::cout << std::endl;
}
case PUT:
startPut(g_curResource);
break;
- case DELETE:
- startDelete(g_curResource);
- break;
default:
std::cout << "Invalid input, please try again" << std::endl;
break;
void createResource()
{
std::string resourceURI = "/a/TempHumSensor/hosting";
- std::string resourceTypeName = "resource.hosting";
+ std::string resourceTypeName = "oic.r.resourcehosting";
std::string resourceInterface = DEFAULT_INTERFACE;
m_uri = resourceURI;
{
std::string resourceURI = "/a/NM/TempHumSensor1"; // URI of the resource
std::string resourceTypeName =
- "notificationmanager.hosting"; // resource type name. In this case, it is light
+ "oic.r.resourcehosting"; // resource type name.
std::string resourceInterface = DEFAULT_INTERFACE; // resource interface.
// OCResourceProperty is defined ocstack.h
#include <signal.h>
#include <unistd.h>
-#include "hosting.h"
+#include "Hosting.h"
int g_quitFlag = 0;
<option id="gnu.cpp.compiler.option.include.paths.1698435591" name="Include paths (-I)" superClass="gnu.cpp.compiler.option.include.paths" valueType="includePath">
<listOptionValue builtIn="false" value=""${workspace_loc:/${ProjName}/inc}""/>
<listOptionValue builtIn="false" value="../../../../../../extlibs/cjson"/>
- <listOptionValue builtIn="false" value="../../../../NotificationManager/include"/>
- <listOptionValue builtIn="false" value="../../../../NotificationManager/src"/>
+ <listOptionValue builtIn="false" value="../../../../include"/>
+ <listOptionValue builtIn="false" value="../../../../src"/>
<listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\include""/>
<listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\c_common""/>
<listOptionValue builtIn="false" value=""..\..\..\..\..\..\resource\csdk\stack\include""/>
<listOptionValue builtIn="false" value="rcs_client"/>
<listOptionValue builtIn="false" value="rcs_server"/>
<listOptionValue builtIn="false" value="rcs_common"/>
- <listOptionValue builtIn="false" value="NotificationManager"/>
+ <listOptionValue builtIn="false" value="resource_hosting"/>
</option>
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.361234161" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
--- /dev/null
+{
+ global: main;
+ local: *;
+};
#include "nmutil.h"
#include <algorithm>
#include <signal.h>
-#include "hosting.h"
+#include "Hosting.h"
using namespace std;
using namespace OC;
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
+OIC_LIB_PATH := ../../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
LOCAL_MODULE := ca_interface
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libca-interface.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := ca
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libconnectivity_abstraction.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := oc_logger_core
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger_core.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := oc_logger
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc_logger.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := octbstack
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboctbstack.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := oc
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/liboc.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
+OIC_LIB_PATH := ../../../../../android/android_api/base/libs/$(TARGET_ARCH_ABI)
LOCAL_MODULE := ocstack-jni
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libocstack-jni.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := rcsCommon
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/librcs_common.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := rcsClient
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/librcs_client.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
LOCAL_MODULE := rcsServer
LOCAL_SRC_FILES := $(OIC_LIB_PATH)/librcs_server.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
-OIC_LIB_PATH := ../../../../../../out/android/$(TARGET_ARCH_ABI)/release
-LOCAL_MODULE := NotificationManager
-LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libNotificationManager.so
+OIC_LIB_PATH := ../../../../../out/android/$(TARGET_ARCH_ABI)/release
+LOCAL_MODULE := resourceHosting
+LOCAL_SRC_FILES := $(OIC_LIB_PATH)/libresource_hosting.so
include $(PREBUILT_SHARED_LIBRARY)
include $(CLEAR_VARS)
LOCAL_STATIC_LIBRARIES += rcsCommon
LOCAL_STATIC_LIBRARIES += rcsClient
LOCAL_STATIC_LIBRARIES += rcsServer
-LOCAL_STATIC_LIBRARIES += NotificationManager
+LOCAL_STATIC_LIBRARIES += resourceHosting
-OIC_SRC_DIR := ../../../../..
+OIC_SRC_DIR := ../../../..
LOCAL_C_INCLUDES := $(OIC_SRC_DIR)/resource/csdk/stack/include \
$(OIC_SRC_DIR)/resource/csdk/logger/include \
$(OIC_SRC_DIR)/resource/oc_logger/include \
$(OIC_SRC_DIR)/extlibs/boost/boost_1_58_0 \
$(OIC_SRC_DIR)/service/resource-encapsulation/include \
- $(OIC_SRC_DIR)/service/notification-manager/NotificationManager/include \
+ $(OIC_SRC_DIR)/service/resource-hosting/include \
LOCAL_SRC_FILES := ResourceHosing_JNI.cpp
include $(BUILD_SHARED_LIBRARY)
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
extern "C" {
-#include "hosting.h"
+#include "Hosting.h"
}
#include "ResourceHosing_JNI.h"
#include "OCAndroid.h"
# Project target.
target=android-22
+android.library=true
System.loadLibrary("rcs_common");
System.loadLibrary("rcs_client");
System.loadLibrary("rcs_server");
- System.loadLibrary("NotificationManager");
+ System.loadLibrary("resource_hosting");
System.loadLibrary("ResourceHosing_JNI");
}
}
//
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include "hosting.h"
+#include "Hosting.h"
// Standard API
#include <stdio.h>
std::string HOSTING_TAG = "/hosting";
size_t HOSTING_TAG_SIZE = (size_t)HOSTING_TAG.size();
std::string MULTICAST_PRESENCE_ADDRESS = std::string("coap://") + OC_MULTICAST_PREFIX;
- std::string HOSTING_RESOURSE_TYPE = "resource.hosting";
+ std::string HOSTING_RESOURSE_TYPE = "oic.r.resourcehosting";
}
ResourceHosting * ResourceHosting::s_instance(nullptr);
ResourceHosting::ResourceHosting()
: hostingObjectList(),
discoveryManager(nullptr),
- presenceHandle(),
- pPresenceCB(nullptr), pDiscoveryCB(nullptr)
+ pDiscoveryCB(nullptr)
{
}
{
try
{
- requestMulticastPresence();
requestMulticastDiscovery();
}catch(const RCSPlatformException &e)
{
void ResourceHosting::stopHosting()
{
- // clear list hostingObjectList
- if(presenceHandle.isSubscribing())
- {
- presenceHandle.unsubscribe();
- }
hostingObjectList.clear();
}
void ResourceHosting::initializeResourceHosting()
{
- pPresenceCB = std::bind(&ResourceHosting::presenceHandler, this,
- std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
pDiscoveryCB = std::bind(&ResourceHosting::discoverHandler, this,
std::placeholders::_1);
discoveryManager = RCSDiscoveryManager::getInstance();
}
-void ResourceHosting::requestMulticastPresence()
-{
- try
- {
- presenceHandle = PresenceSubscriber(MULTICAST_PRESENCE_ADDRESS,
- OCConnectivityType::CT_DEFAULT, pPresenceCB);
- }catch(...)
- {
- throw;
- }
-}
-
-void ResourceHosting::presenceHandler(OCStackResult ret, const unsigned int /*seq*/,
- const std::string & address)
-{
- switch(ret)
- {
- case OC_STACK_OK:
- case OC_STACK_CONTINUE:
- case OC_STACK_RESOURCE_CREATED:
- {
- // TODO start discovery
- requestDiscovery(address);
- break;
- }
-
- case OC_STACK_RESOURCE_DELETED:
- case OC_STACK_COMM_ERROR:
- case OC_STACK_TIMEOUT:
- case OC_STACK_PRESENCE_STOPPED:
- case OC_STACK_PRESENCE_TIMEOUT:
- case OC_STACK_PRESENCE_DO_NOT_HANDLE:
- case OC_STACK_ERROR:
- // TODO presence error
- break;
-
- case OC_STACK_INVALID_URI:
- case OC_STACK_INVALID_QUERY:
- case OC_STACK_INVALID_IP:
- case OC_STACK_INVALID_PORT:
- case OC_STACK_INVALID_CALLBACK:
- case OC_STACK_INVALID_METHOD:
- case OC_STACK_INVALID_PARAM:
- case OC_STACK_INVALID_OBSERVE_PARAM:
- case OC_STACK_NO_MEMORY:
- case OC_STACK_ADAPTER_NOT_ENABLED:
- case OC_STACK_NOTIMPL:
- case OC_STACK_NO_RESOURCE:
- case OC_STACK_RESOURCE_ERROR:
- case OC_STACK_SLOW_RESOURCE:
- case OC_STACK_DUPLICATE_REQUEST:
- case OC_STACK_NO_OBSERVERS:
- case OC_STACK_OBSERVER_NOT_FOUND:
- case OC_STACK_INVALID_OPTION:
- case OC_STACK_VIRTUAL_DO_NOT_HANDLE:
- case OC_STACK_MALFORMED_RESPONSE:
- case OC_STACK_PERSISTENT_BUFFER_REQUIRED:
- case OC_STACK_INVALID_REQUEST_HANDLE:
- case OC_STACK_INVALID_DEVICE_INFO:
- case OC_STACK_INVALID_JSON:
- break;
- default:
- // TODO unknown presence result
- break;
- }
-}
-
void ResourceHosting::requestMulticastDiscovery()
{
- requestDiscovery();
-}
-void ResourceHosting::requestDiscovery(std::string address)
-{
- std::string host = address;
- RCSAddress rcsAddress = RCSAddress::unicast(host);
discoveryTask = discoveryManager->discoverResourceByType(
- rcsAddress, OC_RSRVD_WELL_KNOWN_URI, HOSTING_RESOURSE_TYPE, pDiscoveryCB);
+ RCSAddress::multicast(), OC_RSRVD_WELL_KNOWN_URI, HOSTING_RESOURSE_TYPE, pDiscoveryCB);
}
void ResourceHosting::discoverHandler(RemoteObjectPtr remoteResource)
typedef std::shared_ptr<PrimitiveResource> PrimiteveResourcePtr;
typedef std::function<
- void(OCStackResult, const unsigned int, const std::string&)> SubscribeCallback;
- typedef std::function<
void(std::shared_ptr<RCSRemoteResourceObject>)> DiscoveryCallback;
typedef std::function<void()> DestroyedCallback;
std::list<HostingObjectPtr> hostingObjectList;
RCSDiscoveryManager * discoveryManager;
- PresenceSubscriber presenceHandle;
std::unique_ptr<RCSDiscoveryManager::DiscoveryTask> discoveryTask;
- SubscribeCallback pPresenceCB;
DiscoveryCallback pDiscoveryCB;
void initializeResourceHosting();
- void requestMulticastPresence();
void requestMulticastDiscovery();
- void requestDiscovery(std::string address = std::string());
- void presenceHandler(OCStackResult ret, const unsigned int seq, const std::string & address);
void discoverHandler(RemoteObjectPtr remoteResource);
HostingObjectPtr findRemoteResource(RemoteObjectPtr remoteResource);
#hosting_test_env.AppendUnique(LIBPATH = [gtest_dir + '/lib/.libs'])
hosting_test_env.AppendUnique(LIBPATH = [lib_env.get('BUILD_DIR')])
hosting_test_env.AppendUnique(LIBS = [
- 'NotificationManager', 'rcs_server', 'rcs_client','rcs_common',
+ 'resource_hosting', 'rcs_server', 'rcs_client','rcs_common',
'oc', 'octbstack', 'oc_logger', 'connectivity_abstraction', 'coap',
GTest_Main, GTest])
hosting_test_env.PrependUnique(CPPPATH = [ src_dir + '/extlibs/hippomocks-master',
gtest_dir + '/include'])
hosting_test_env.AppendUnique(CPPPATH = ['../'])
-hosting_test_env.AppendUnique(CPPPATH = ['../../../../resource-encapsulation/include'])
-hosting_test_env.AppendUnique(CPPPATH = ['../../../../resource-encapsulation/src/common/primitiveResource/include'])
-hosting_test_env.AppendUnique(CPPPATH = ['../../../../resource-encapsulation/src/common/utils/include'])
+hosting_test_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/include'])
+hosting_test_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/src/common/primitiveResource/include'])
+hosting_test_env.AppendUnique(CPPPATH = ['../../../resource-encapsulation/src/common/utils/include'])
######################################################################
# Build Test
######################################################################
void write(std::string time, ILogger::Level level, std::string message)
{
std::cout << "[APPLogger] " << time << " " << ILogger::getString(level) << " "
- << message;
+ << message;
}
};
std::shared_ptr<AppLogger> gAppLogger(new AppLogger());
{
case 1 : simulateResource(configPath); break;
case 2 : displayResource(); break;
- case 3 : deleteResource(); break;
+ case 3 :
+ try
+ {
+ deleteResource();
+ }
+ catch (InvalidArgsException &e)
+ {
+ std::cout << "InvalidArgsException occured [code : " << e.code() <<
+ " Detail: " << e.what() << "]" << std::endl;
+ }
+ break;
case 4 : updateAttributePower(); break;
case 5 : updateAttributeIntensity(); break;
case 6 : automateResourceUpdate(); break;
const SimulatorResourceModel &resModel)
{
std::cout << "[callback] Resource model is changed URI: " << uri.c_str()
- << " Count : " << resModel.size() << std::endl;
+ << " Count : " << resModel.size() << std::endl;
std::cout << "#### Modified attributes are ####" << std::endl;
for (auto & attribute : resModel.getAttributes())
{
std::cout << attribute.second.getName() << " : "
- << attribute.second.valueToString().c_str() << std::endl;
+ << attribute.second.valueToString().c_str() << std::endl;
}
std::cout << "########################" << std::endl;
}
try
{
SimulatorResourceServerSP resource =
- SimulatorManager::getInstance()->createResource(configPath, callback);
+ SimulatorManager::getInstance()->createResource(configPath, callback);
m_resources.push_back(resource);
std::cout << "Resource created successfully! URI= " << resource->getURI().c_str()
- << std::endl;
+ << std::endl;
}
catch (InvalidArgsException &e)
{
std::cout << "InvalidArgsException occured [code : " << e.code() << " Detail: "
- << e.what() << "]" << std::endl;
+ << e.what() << "]" << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code() << " Detail: "
- << e.what() << "]" << std::endl;
+ << e.what() << "]" << std::endl;
}
}
{
SimulatorManager::getInstance()->deleteResource(resourceType);
std::cout << "Resources of type \"" << resourceType << "\"" <<
- " deleted successfully! " << std::endl;
+ " deleted successfully! " << std::endl;
std::vector<SimulatorResourceServerSP>::iterator ite = m_resources.begin();
while (ite != m_resources.end())
{
catch (InvalidArgsException &e)
{
std::cout << "InvalidArgsException occured [code : " << e.code()
- << " Detail: " << e.what() << "]" << std::endl;
+ << " Detail: " << e.what() << "]" << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code()
- << " Detail: " << e.what() << "]" << std::endl;
+ << " Detail: " << e.what() << "]" << std::endl;
}
} break;
}
std::cout << "Setting the new values from allowed values list to power attribute" <<
- std::endl;
+ std::endl;
// Update all possible values from allowed values
for (int index = 0; index < allowedValuesSize; index++)
{
}
std::cout << "Setting the new values from allowed values list to intensity attribute"
- << std::endl;
+ << std::endl;
// Update all possible values from allowed values
for (int index = min; index <= max; index++)
{
// Attributes
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes =
- resModel.getAttributes();
+ resModel.getAttributes();
std::cout << "##### Attributes [" << attributes.size() << "]" << std::endl;
for (auto & attribute : attributes)
{
const int id)
{
std::cout << "Update automation is completed [URI: " << uri.c_str()
- << " AutomationID: " << id << "] ###" << std::endl;
+ << " AutomationID: " << id << "] ###" << std::endl;
}
void automateResourceUpdate()
{
int id = m_resources[index - 1]->startUpdateAutomation(type,
std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
- std::placeholders::_1, std::placeholders::_2));
+ std::placeholders::_1, std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [code : " << e.code() << " Detail: " <<
- e.what() << "]" << std::endl;
+ e.what() << "]" << std::endl;
}
}
SimulatorResourceServerSP resource = m_resources[index - 1];
SimulatorResourceModel resModel = resource->getModel();
std::map<std::string, SimulatorResourceModel::Attribute> attributes =
- resModel.getAttributes();
+ resModel.getAttributes();
int size = 0;
for (auto & attribute : attributes)
{
int choice = -1;
std::cout << "Select the attribute which you want to automate for updation: " <<
- std::endl;
+ std::endl;
std::cin >> choice;
if (choice < 0 || choice > size)
{
type = AutomationType::RECURRENT;
std::cout << "Requesting attribute automation for " << attributeName.c_str() <<
- std::endl;
+ std::endl;
try
{
int id = resource->startUpdateAutomation(attributeName, type,
std::bind(&SimLightResource::onUpdateAutomationCompleted, this,
- std::placeholders::_1, std::placeholders::_2));
+ std::placeholders::_1, std::placeholders::_2));
std::cout << "startUpdateAutomation() returned succces : " << id << std::endl;
}
catch (SimulatorException &e)
{
std::cout << "SimulatorException occured [Error: " << e.code() << " Details: " <<
- e.what() << "]" << std::endl;
+ e.what() << "]" << std::endl;
}
}
if (!ids.size())
{
std::cout << "No automation operation is going on this resource right now!" <<
- std::endl;
+ std::endl;
return;
}
std::ostringstream out;
out << "ID: " << (int) observerInfo.id << std::endl;
out << " [address: " << observerInfo.address << " port: " << observerInfo.port
- << "]" << std::endl;
+ << "]" << std::endl;
std::cout << out.str();
}
for (auto & observerInfo : observersList)
{
std::cout << " ID : " << (int) observerInfo.id << " [address: " <<
- observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
+ observerInfo.address << " port: " << observerInfo.port << "]" << std::endl;
}
std::cout << "########################" << std::endl;
}
// TODO: For debugging
if (null != attributeMap) {
RemoteResourceAttribute.printAttributes(attributeMap);
- System.out.println("Attributes found: " + (null != attributeMap));
+ System.out.println("Attributes found: ");
System.out.println("No of attributes: " + attributeMap.size());
resource.setResourceAttributesMap(attributeMap);
}
public boolean isResourceObserved(String resourceURI) {
- boolean observed = false;
+ boolean observed;
synchronized (observedResourceURIList) {
observed = observedResourceURIList.contains(resourceURI);
}
}
public boolean isDisplayName(String displayName) {
- boolean exist = false;
+ boolean exist;
synchronized (displayNameMap) {
exist = displayNameMap.containsKey(displayName);
}
}
public String getCompleteUriFromDisplayName(String displayName) {
- String completeURI = null;
+ String completeURI;
synchronized (displayNameMap) {
completeURI = displayNameMap.get(displayName);
}
@Override
public void run() {
Map<String, SimulatorResource> resourceTypeMap;
- SimulatorResourceServer[] simulatorResourceServers = null;
+ SimulatorResourceServer[] simulatorResourceServers;
try {
simulatorResourceServers = SimulatorManager.createResource(
configFilePath, noOfInstances,
}
public List<String> getURIList() {
- List<String> list = null;
+ List<String> list;
synchronized (orderedResourceUriMap) {
Set<String> typeSet = orderedResourceUriMap.keySet();
List<String> typeList = Utility.convertSetToList(typeSet);
if (null == typeList || typeList.size() < 1) {
- return list;
+ return null;
}
list = new ArrayList<String>();
int val;
try {
val = Integer.parseInt(value);
+ server.updateAttributeInteger(attributeName, val);
} catch (NumberFormatException nfe) {
return;
}
- server.updateAttributeInteger(attributeName, val);
} else if (baseType == Type.DOUBLE) {
double val;
try {
val = Double.parseDouble(value);
+ server.updateAttributeDouble(attributeName, val);
} catch (NumberFormatException nfe) {
return;
}
- server.updateAttributeDouble(attributeName, val);
} else if (baseType == Type.BOOL) {
boolean val;
val = Boolean.parseBoolean(value);
return;
}
+ delete jniSimulatorResource;
releaseEnv();
}
{
throwSimulatorException(env, e.code(), e.what());
}
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
env->ReleaseStringUTFChars(deviceInfo, deviceName);
}
{
throwSimulatorException(env, e.code(), e.what());
}
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
}
JNIEXPORT void JNICALL
{
throwSimulatorException(env, e.code(), e.what());
}
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
}
JNIEXPORT void JNICALL
{
throwSimulatorException(env, e.code(), e.what());
}
+ catch (...)
+ {
+ throwSimulatorException(env, SIMULATOR_ERROR, "Unknown Exception");
+ return;
+ }
}
static bool getClassRef(JNIEnv *env, const char *className, jclass &classRef)
} catch(Throwable t){
throw t;
} finally{
- System.out.println("Calling finalize of Super Class");
super.finalize();
}
}
@Override
protected void finalize() throws Throwable {
- super.finalize();
-
- dispose();
+ try {
+ dispose();
+ } catch(Throwable t){
+ throw t;
+ } finally{
+ super.finalize();
+ }
}
private native void dispose();
} catch(Throwable t){
throw t;
} finally{
- System.out.println("Calling finalize of Super Class");
super.finalize();
}
}
******************************************************************/\r
\r
#include "RamlParser.h"\r
+#include "Helpers.h"\r
#include <iostream>\r
#include <string>\r
#include <memory>\r
\r
for ( auto pro : body->getSchema()->getProperties()->getProperties() )\r
{\r
+ std::cout << "-----------------------------" << std::endl;\r
std::cout << "Name : " << pro.second->getName() << std::endl;\r
- std::cout << "default : " << pro.second->getValue() << std::endl;\r
- std::cout << "update_frequency : " << pro.second->getUpdateFrequencyTime() << std::endl;\r
- int min = 0, max = 0, multipleOf = 0;\r
- pro.second->getRange(min, max, multipleOf);\r
-\r
- std::cout << "range_min : " << min << std::endl;\r
- std::cout << "range_max : " << max << std::endl;\r
- std::cout << "allowed values : " << std::endl;\r
- for (auto v : pro.second->getAllowedValues())\r
- std::cout << v << " ";\r
- std::cout << std::endl;\r
+ std::cout << "-----------------------------" << std::endl;\r
+ try\r
+ {\r
+ switch (pro.second->getVariantType())\r
+ {\r
+ case VariantType::INT : // Integer\r
+ std::cout << "Defaut: " << pro.second->getValueInt() << std::endl;\r
+ for (auto tt : pro.second->getAllowedValuesInt())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ {\r
+ int min = 0, max = 0, mul = 0;\r
+ pro.second->getRange(min, max, mul);\r
+ std::cout << "Minimum: " << min << std::endl;\r
+ std::cout << "Maximum: " << max << std::endl;\r
+ }\r
+ break;\r
+\r
+ case VariantType::DOUBLE : // Double\r
+ std::cout << "Defaut: " << pro.second->getValueDouble() << std::endl;\r
+ for (auto tt : pro.second->getAllowedValuesDouble())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ {\r
+ double min = 0, max = 0;\r
+ int mul = 0;\r
+ pro.second->getRangeDouble(min, max, mul);\r
+ std::cout << "MinimumDouble: " << min << std::endl;\r
+ std::cout << "MaximumDouble: " << max << std::endl;\r
+ }\r
+ break;\r
+\r
+ case VariantType::BOOL : // Boolean\r
+ std::cout << "Defaut: " << std::boolalpha << pro.second->getValueBool() << std::noboolalpha <<\r
+ std::endl;\r
+ for (auto tt : pro.second->getAllowedValuesBool())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ break;\r
+\r
+ case VariantType::STRING : // String\r
+ std::cout << "Defaut: " << pro.second->getValueString() << std::endl;\r
+ for (auto tt : pro.second->getAllowedValuesString())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ {\r
+ int min = 0, max = 0, mul = 0;\r
+ pro.second->getRange(min, max, mul);\r
+ std::cout << "MinimumLength: " << min << std::endl;\r
+ std::cout << "MaximumLength: " << max << std::endl;\r
+ }\r
+ break;\r
+ default:\r
+ break;\r
+\r
+ }\r
+ }\r
+ catch (const boost::bad_lexical_cast &e)\r
+ {\r
+ std::cout << e.what() << std::endl;\r
+ }\r
+ catch ( ... )\r
+ {\r
+ std::cout << "Unknown exception caught!" << std::endl;\r
+ }\r
\r
}\r
+ std::cout << "-----------------------------" << std::endl;\r
std::cout << "Body : example : " << body->getExample() << std::endl;\r
\r
#ifdef PRINT_REQUEST_RESPONSE_BODY_PARAMS\r
std::cout << "-------------------------------" << std::endl;\r
std::cout << "Type: " << prop->getType() << std::endl;\r
std::cout << "Description: " << prop->getDescription() << std::endl;\r
- int type = prop->getValueType();\r
- if (type)\r
+ try\r
{\r
- std::cout << "Defaut: " << prop->getValueString() << std::endl;\r
- for (auto tt : prop->getAllowedValuesString())\r
+ switch (prop->getVariantType())\r
{\r
- std::cout << "enum value : " << tt << std::endl;\r
+ case VariantType::INT : // Integer\r
+ std::cout << "Defaut: " << prop->getValueInt() << std::endl;\r
+ for (auto tt : prop->getAllowedValuesInt())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ {\r
+ int min = 0, max = 0, mul = 0;\r
+ prop->getRange(min, max, mul);\r
+ std::cout << "Minimum: " << min << std::endl;\r
+ std::cout << "Maximum: " << max << std::endl;\r
+ }\r
+ break;\r
+\r
+ case VariantType::DOUBLE : // Double\r
+ std::cout << "Defaut: " << prop->getValueDouble() << std::endl;\r
+ for (auto tt : prop->getAllowedValuesDouble())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ {\r
+ double min = 0, max = 0;\r
+ int mul = 0;\r
+ prop->getRangeDouble(min, max, mul);\r
+ std::cout << "MinimumDouble: " << min << std::endl;\r
+ std::cout << "MaximumDouble: " << max << std::endl;\r
+ }\r
+ break;\r
+\r
+ case VariantType::BOOL : // Boolean\r
+ std::cout << "Defaut: " << std::boolalpha << prop->getValueBool() << std::noboolalpha << std::endl;\r
+ for (auto tt : prop->getAllowedValuesBool())\r
+ {\r
+ std::cout << std::boolalpha << "enum value : " << tt << std::noboolalpha << std::endl;\r
+ }\r
+ break;\r
+\r
+ case VariantType::STRING : // String\r
+ std::cout << "Defaut: " << prop->getValueString() << std::endl;\r
+ for (auto tt : prop->getAllowedValuesString())\r
+ {\r
+ std::cout << "enum value : " << tt << std::endl;\r
+ }\r
+ {\r
+ int min = 0, max = 0, mul = 0;\r
+ prop->getRange(min, max, mul);\r
+ std::cout << "MinimumLength: " << min << std::endl;\r
+ std::cout << "MaximumLength: " << max << std::endl;\r
+ }\r
+ break;\r
+ default:\r
+ break;\r
+\r
}\r
}\r
- else\r
+ catch (const boost::bad_lexical_cast &e)\r
{\r
- std::cout << "Defaut: " << prop->getValueInt() << std::endl;\r
- for (auto tt : prop->getAllowedValuesString())\r
- {\r
- std::cout << "enum value : " << tt << std::endl;\r
- }\r
+ std::cout << e.what() << std::endl;\r
}\r
+ catch ( ... )\r
+ {\r
+ std::cout << "Unknown exception caught!" << std::endl;\r
+ }\r
+\r
if (prop->getType() == "array")\r
{\r
for (auto it : prop->getItems())\r
{\r
std::cout << "enum value : " << tt << std::endl;\r
}\r
+ for (auto tt : it->getProperties())\r
+ {\r
+ printProperties(tt.second);\r
+ }\r
+ std::cout << "Item Required Values : " << std::endl;\r
+ for (auto tt : it->getRequiredValues())\r
+ {\r
+ std::cout << tt << std::endl;\r
+ }\r
}\r
}\r
- int min = 0, max = 0, mul = 0;\r
- prop->getRange(min, max, mul);\r
- std::cout << "Minimum: " << min << std::endl;\r
- std::cout << "Maximum: " << max << std::endl;\r
- std::cout << "MultipleOf: " << mul << std::endl;\r
#endif\r
\r
}\r
if (*it == reqValue)\r
break;\r
}\r
- if (m_required.end() != it)\r
+ if (m_required.end() == it)\r
{\r
m_required.push_back(reqValue);\r
}\r
if (*it == reqValue)\r
break;\r
}\r
- if (m_required.end() != it)\r
+ if (m_required.end() == it)\r
{\r
m_required.push_back(reqValue);\r
}\r
{\r
PropertiesPtr property = std::make_shared<Properties>(attName);\r
\r
- cJSON *propertyUpdateFrequency = cJSON_GetObjectItem(childProperties, "update_frequency");\r
- if (propertyUpdateFrequency)\r
- {\r
- property->setUpdateFrequencyTime(propertyUpdateFrequency->valueint);\r
- }\r
cJSON *propertyDescription = cJSON_GetObjectItem(childProperties, "description");\r
if (propertyDescription)\r
{\r
}\r
else if (attType == "integer")\r
{\r
- readNumber(childProperties, property);\r
+ readInteger(childProperties, property);\r
}\r
else if (attType == "array")\r
{\r
}\r
else if (attType == "number")\r
{\r
- readNumber(childProperties, property);\r
+ readDouble(childProperties, property);\r
}\r
}\r
\r
}\r
}\r
\r
- void JsonSchema::readNumber(cJSON *childProperties, PropertiesPtr property)\r
+ void JsonSchema::readInteger(cJSON *childProperties, PropertiesPtr property)\r
{\r
cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum");\r
if (Max)\r
}\r
\r
}\r
+\r
+ void JsonSchema::readDouble(cJSON *childProperties, PropertiesPtr property)\r
+ {\r
+ cJSON *Max = cJSON_GetObjectItem(childProperties, "maximum");\r
+ if (Max)\r
+ {\r
+ cJSON *exclusiveMax = cJSON_GetObjectItem(childProperties, "exclusiveMaximum");\r
+ if (exclusiveMax)\r
+ {\r
+ if (exclusiveMax->type == cJSON_True)\r
+ property->setMaxDouble( --(Max->valuedouble));\r
+ else\r
+ property->setMaxDouble(Max->valuedouble);\r
+ }\r
+ else\r
+ property->setMaxDouble(Max->valuedouble);\r
+ }\r
+ cJSON *Min = cJSON_GetObjectItem(childProperties, "minimum");\r
+ if (Min)\r
+ {\r
+ cJSON *exclusiveMin = cJSON_GetObjectItem(childProperties, "exclusiveMinimum");\r
+ if (exclusiveMin)\r
+ {\r
+ if (exclusiveMin->type == cJSON_True)\r
+ property->setMinDouble( ++(Min->valuedouble));\r
+ else\r
+ property->setMinDouble(Min->valuedouble);\r
+ }\r
+ else\r
+ property->setMinDouble(Min->valuedouble);\r
+ }\r
+ cJSON *multipleOf = cJSON_GetObjectItem(childProperties, "multipleOf");\r
+ if (multipleOf)\r
+ {\r
+ property->setMultipleOf(multipleOf->valueint);\r
+ }\r
+\r
+ }\r
+\r
DefinitionsPtr JsonSchema::readRef(std::string m_ref)\r
{\r
std::string delimiter1 = "#";\r
const std::string &attType);\r
void readString( cJSON *childProperties, PropertiesPtr property);\r
void readArray( cJSON *childProperties, PropertiesPtr property);\r
- void readNumber( cJSON *childProperties, PropertiesPtr property);\r
+ void readInteger( cJSON *childProperties, PropertiesPtr property);\r
+ void readDouble( cJSON *childProperties, PropertiesPtr property);\r
DefinitionsPtr readRef(std::string m_ref);\r
\r
\r
/**\r
* Constructor of Properties.\r
*/\r
- Properties(): m_min(INT_MAX), m_max(INT_MAX), m_multipleOf(INT_MAX), m_updateInterval(0),\r
- m_unique(false), m_additionalItems(false) {}\r
+ Properties(): m_min(INT_MAX), m_max(INT_MAX), m_doubleMin(INT_MAX), m_doubleMax(INT_MAX),\r
+ m_multipleOf(INT_MAX), m_unique(false), m_additionalItems(false) {}\r
\r
/**\r
* Constructor of Properties.\r
* @param name - Properties name as string.\r
*/\r
Properties(const std::string &name) : m_name(name), m_min(INT_MAX), m_max(INT_MAX),\r
- m_multipleOf(INT_MAX), m_updateInterval(0), m_unique(false), m_additionalItems(false) {}\r
+ m_doubleMin(INT_MAX), m_doubleMax(INT_MAX), m_multipleOf(INT_MAX),\r
+ m_unique(false), m_additionalItems(false) {}\r
\r
/**\r
* This method is for getting Name from Properties.\r
}\r
\r
/**\r
+ * This method is for getting Range from Properties.\r
+ *\r
+ * @param min - reference to hold Minimum value of Properties.\r
+ * @param max - reference to hold Maximum value of Properties.\r
+ * @param multipleOf - reference to hold multipleOf value of Properties.\r
+ */\r
+ inline void getRangeDouble(double &min, double &max, int &multipleOf) const\r
+ {\r
+ min = m_doubleMin;\r
+ max = m_doubleMax;\r
+ multipleOf = m_multipleOf;\r
+ }\r
+ /**\r
* This method is for setting Minimum to Properties\r
*\r
* @param min - Minimum value of Properties.\r
}\r
\r
/**\r
+ * This method is for setting Minimum to Properties\r
+ *\r
+ * @param min - Minimum value of Properties.\r
+ */\r
+ inline void setMinDouble(const double &min)\r
+ {\r
+ m_doubleMin = min;\r
+ }\r
+\r
+ /**\r
+ * This method is for setting Maximum to Properties\r
+ *\r
+ * @param max - Maximum value of Properties.\r
+ */\r
+ inline void setMaxDouble(const double &max)\r
+ {\r
+ m_doubleMax = max;\r
+ }\r
+ /**\r
* This method is for setting multipleOf to Properties\r
*\r
* @param multipleOf - multipleOf value of Properties.\r
}\r
\r
/**\r
- * This method is for getting UpdateFrequency from Properties.\r
- *\r
- * @return UpdateFrequency as int\r
- */\r
- inline int getUpdateFrequencyTime()\r
- {\r
- return m_updateInterval;\r
- }\r
-\r
- /**\r
- * This method is for setting UpdateFrequency to Properties\r
- *\r
- * @param interval - UpdateFrequency as int.\r
- */\r
- inline void setUpdateFrequencyTime(int interval)\r
- {\r
- m_updateInterval = interval;\r
- }\r
-\r
- /**\r
* This method is for setting Type to Properties\r
*\r
* @param type - Type as string.\r
ValueVariant m_value;\r
int m_min;\r
int m_max;\r
+ double m_doubleMin;\r
+ double m_doubleMax;\r
int m_multipleOf;\r
AllowedValues m_allowedValues;\r
- int m_updateInterval;\r
std::string m_type;\r
std::string m_pattern;\r
std::string m_format;\r
if (m_getRequestSender)
{
return m_autoRequestGenMngr->startOnGET(m_getRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_GET]->getQueryParams(),
+ localCallback);
}
break;
if (m_putRequestSender)
{
return m_autoRequestGenMngr->startOnPUT(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_PUT]->getRepSchema(),
+ localCallback);
}
break;
if (m_postRequestSender)
{
return m_autoRequestGenMngr->startOnPOST(m_putRequestSender,
- m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
- m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
- localCallback);
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getQueryParams(),
+ m_requestModelList[RequestType::RQ_TYPE_POST]->getRepSchema(),
+ localCallback);
}
break;
throw InvalidArgsException(SIMULATOR_INVALID_PARAM, "Empty path string!");
}
- RAML::RamlParser *ramlParser = new RAML::RamlParser(path);
+ std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(path);
RAML::RamlPtr raml = ramlParser->getRamlPtr();
configure(raml);
time_t timeInfo = time(NULL);
struct tm *localTime = localtime(&timeInfo);
+ if (nullptr == localTime)
+ return false;
std::ostringstream newFileName;
newFileName << path << "/Simulator_";
newFileName << localTime->tm_year << localTime->tm_mon << localTime->tm_mday << localTime->tm_hour
<< localTime->tm_min << localTime->tm_sec;
newFileName << ".log";
- std::shared_ptr<FileLogger> fileLogger(new FileLogger(newFileName.str()));
+ std::shared_ptr<FileLogger> fileLogger = std::make_shared<FileLogger>(newFileName.str());
if (fileLogger->open())
{
m_target = fileLogger;
{
time_t timeInfo = time(NULL);
struct tm *localTime = localtime(&timeInfo);
+ if (nullptr == localTime)
+ return;
std::ostringstream timeStr;
timeStr << localTime->tm_hour << "." << localTime->tm_min << "." << localTime->tm_sec;
m_target->write(timeStr.str(), level, str.str());
try
{
- RAML::RamlParser *ramlParser = new RAML::RamlParser(configPath);
+ std::shared_ptr<RAML::RamlParser> ramlParser = std::make_shared<RAML::RamlParser>(configPath);
raml = ramlParser->getRamlPtr();
}
catch (RAML::RamlException &e)
if (ramlResource)
{
- SimulatorResourceServerImplSP simResource(new SimulatorResourceServerImpl());
+ SimulatorResourceServerImplSP simResource = std::make_shared<SimulatorResourceServerImpl>();
simResource->setName(ramlResource->getDisplayName());
simResource->setURI(ramlResource->getResourceUri());
if (!action)
{
OC_LOG(ERROR, TAG, "Failed to create resource representation schema as it does not"
- "posess the GET request!");
+ "posess the GET request!");
return nullptr;
}
if (responseBody)
{
RAML::JsonSchemaPtr resourceProperties = responseBody->getSchema()->getProperties();
- for ( auto &propertyElement : resourceProperties->getProperties())
+ for ( auto & propertyElement : resourceProperties->getProperties())
{
if (!propertyElement.second)
continue;
break;
}
- // Set attriute update frequency interval
- attribute.setUpdateFrequencyTime(propertyElement.second->getUpdateFrequencyTime());
-
// Set range/supported values set
int min = 0, max = 0, multipleof = 0;
propertyElement.second->getRange(min, max, multipleof);
"] UNKNOWN type request received. \n**Payload details**" << payload)
response->setResponseResult(OC_EH_ERROR);
- OC::OCPlatform::sendResponse(response);
- errCode = OC_EH_ERROR;
+ if (OC_STACK_OK == OC::OCPlatform::sendResponse(response))
+ {
+ errCode = OC_EH_ERROR;
+ }
}
}
#Go to build sample apps
SConscript('sampleapp/SConscript')
+######################################################################
+# Build UnitTests Things Manager
+################################################ ######################
+if target_os == 'linux':
+ SConscript('unittests/SConscript')
private final String CONFIGURATION_COLLECTION_RESOURCE_URI = "/core/configuration/resourceset";
private final String CONFIGURATION_COLLECTION_RESOURCE_TYPE = "core.configuration.resourceset";
+ private final String CONFIGURATION_RESOURCE_TYPE = "oic.wk.con";
private final String MAINTENANCE_COLLECTION_RESOURCE_URI = "/core/maintenance/resourceset";
private final String MAINTENANCE_COLLECTION_RESOURCE_TYPE = "core.maintenance.resourceset";
+ private final String MAINTENANCE_RESOURCE_TYPE = "oic.wk.mnt";
private final String FACTORYSET_COLLECTION_RESOURCE_URI = "/core/factoryset/resourceset";
private final String FACTORYSET_COLLECTION_RESOURCE_TYPE = "core.factoryset.resourceset";
+ private final String FACTORYSET_RESOURCE_TYPE = "factoryset";
private final String CONFIGURATION_RESOURCE_URI = "/oic/con";
private final String MAINTENANCE_RESOURCE_URI = "/oic/mnt";
// set the listeners
setResourceListener();
setConfigurationListener();
- setDiagnosticsListener();
+ setMaintenanceListener();
// Create API menu list
configurationApisList = new ArrayList<String>();
// Find All Groups
if (position == 0) {
Vector<String> resourceTypes = new Vector<String>();
- resourceTypes.add("core.configuration.resourceset");
+ resourceTypes.add(CONFIGURATION_COLLECTION_RESOURCE_TYPE);
findCandidateResources(resourceTypes);
logMessage = "";
messageCount++;
resourceTypes.clear();
- resourceTypes.add("core.diagnostics.resourceset");
+ resourceTypes.add(MAINTENANCE_COLLECTION_RESOURCE_TYPE);
findCandidateResources(resourceTypes);
messageCount++;
resourceTypes.clear();
- resourceTypes.add("core.factoryset.resourceset");
+ resourceTypes.add(FACTORYSET_COLLECTION_RESOURCE_TYPE);
findCandidateResources(resourceTypes);
messageCount++;
displayToastMessage("Configuration collection resource does not exist!");
} else {
Vector<String> resourceTypes = new Vector<String>();
- resourceTypes.add("oic.wk.con");
+ resourceTypes.add(CONFIGURATION_RESOURCE_TYPE);
findCandidateResources(resourceTypes);
logMessage = "";
messageCount++;
resourceTypes.clear();
- resourceTypes.add("oic.wk.mnt");
+ resourceTypes.add(MAINTENANCE_RESOURCE_TYPE);
findCandidateResources(resourceTypes);
messageCount++;
resourceTypes.clear();
- resourceTypes.add("factoryset");
+ resourceTypes.add(FACTORYSET_RESOURCE_TYPE);
findCandidateResources(resourceTypes);
messageCount++;
});
}
- private void setDiagnosticsListener() {
+ private void setMaintenanceListener() {
thingsMaintenance
.setThingsMaintenanceListener(new IThingsMaintenanceListener() {
* to default.
*/
private void factoryReset() {
- ResourceInformation diagnosticsCollection = collectionList
+ ResourceInformation MaintenanceCollection = collectionList
.get(MAINTENANCE_COLLECTION_RESOURCE_URI);
- if (null == diagnosticsCollection
- || null == diagnosticsCollection.resource) {
- displayToastMessage("Diagnostic collection does not exist!");
+ if (null == MaintenanceCollection
+ || null == MaintenanceCollection.resource) {
+ displayToastMessage("Maintenance collection does not exist!");
return;
}
if (false == maintenanceResourceFlag) {
- displayToastMessage("Diagnostic resource does not exist!");
+ displayToastMessage("Maintenance resource does not exist!");
return;
}
try {
result = thingsMaintenance
- .factoryReset(diagnosticsCollection.resource);
+ .factoryReset(MaintenanceCollection.resource);
} catch (OcException e) {
e.printStackTrace();
}
* This method send request to reboot server.
*/
private void reboot() {
- ResourceInformation diagnosticsCollection = collectionList
+ ResourceInformation MaintenanceCollection = collectionList
.get(MAINTENANCE_COLLECTION_RESOURCE_URI);
- if (null == diagnosticsCollection
- || null == diagnosticsCollection.resource) {
- displayToastMessage("Diagnostic collection does not exist!");
+ if (null == MaintenanceCollection
+ || null == MaintenanceCollection.resource) {
+ displayToastMessage("Maintenance collection does not exist!");
return;
}
if (false == maintenanceResourceFlag) {
- displayToastMessage("Diagnostic resource does not exist!");
+ displayToastMessage("Maintenance resource does not exist!");
return;
}
OCStackResult result = OCStackResult.OC_STACK_ERROR;
try {
- result = thingsMaintenance.reboot(diagnosticsCollection.resource);
+ result = thingsMaintenance.reboot(MaintenanceCollection.resource);
} catch (OcException e) {
e.printStackTrace();
}
resourceList.put(uri + host, resourceInfo);
configurationResourceFlag = true;
} else if (uri.equalsIgnoreCase("/oic/mnt")) {
- ResourceInformation diagnosticResource = collectionList
+ ResourceInformation maintenanceResource = collectionList
.get(MAINTENANCE_COLLECTION_RESOURCE_URI);
- if (null == diagnosticResource
- || null == diagnosticResource.resourceHandle) {
+ if (null == maintenanceResource
+ || null == maintenanceResource.resourceHandle) {
Log.e(LOG_TAG, "Invalid Configuration collection!");
return;
}
OcResourceHandle resourceHandle = null;
try {
- resourceHandle = OcPlatform.registerResource(
- uri,
- typename,
- OcPlatform.BATCH_INTERFACE, null, EnumSet.of(
- ResourceProperty.DISCOVERABLE));
+ resourceHandle = OcPlatform.registerResource(uri, typename,
+ OcPlatform.BATCH_INTERFACE, null,
+ EnumSet.of(ResourceProperty.DISCOVERABLE));
} catch (OcException e) {
Log.e(LOG_TAG, "go exception");
Log.e(LOG_TAG, "RegisterResource error. " + e.getMessage());
}
try {
- OcPlatform.bindInterfaceToResource(resourceHandle, OcPlatform.GROUP_INTERFACE);
+ OcPlatform.bindInterfaceToResource(resourceHandle,
+ OcPlatform.GROUP_INTERFACE);
} catch (OcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
- OcPlatform.bindInterfaceToResource(resourceHandle, OcPlatform.DEFAULT_INTERFACE);
+ OcPlatform.bindInterfaceToResource(resourceHandle,
+ OcPlatform.DEFAULT_INTERFACE);
} catch (OcException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (resource.resource.getUri().equalsIgnoreCase(
MAINTENANCE_RESOURCE_URI)) {
- ResourceInformation diagnosticResource = collectionList
+ ResourceInformation maintenanceResource = collectionList
.get(MAINTENANCE_COLLECTION_RESOURCE_URI);
- if (null != diagnosticResource
- && null != diagnosticResource.resourceHandle) {
+ if (null != maintenanceResource
+ && null != maintenanceResource.resourceHandle) {
OcPlatform
.unregisterResource(resource.resourceHandle);
Log.i(LOG_TAG, "unregistered resource"
import java.util.Map;
import java.util.Vector;
-import org.iotivity.base.EntityHandlerResult;
import org.iotivity.base.ObserveType;
import org.iotivity.base.OcException;
import org.iotivity.base.OcHeaderOption;
import org.iotivity.base.OcPlatform;
import org.iotivity.base.OcRepresentation;
import org.iotivity.base.OcResource;
-import org.iotivity.base.OcResourceRequest;
-import org.iotivity.base.OcStackConfig;
import org.iotivity.base.ResourceProperty;
import org.iotivity.base.OcResource.OnObserveListener;
import org.iotivity.base.OcResourceHandle;
mainActivityObj = this;
Button doBootStrap = (Button) findViewById(R.id.button1);
final Button createConfig = (Button) findViewById(R.id.button2);
+ createConfig.setEnabled(false);
editText = (EditText) findViewById(R.id.EditText);
conServerObj = new ConfigurationServer();
int waitTime) {
OCStackResult result;
if (null == s_resourceListener) {
- result = OCStackResult.OC_STACK_ERROR;
+ result = OCStackResult.OC_STACK_LISTENER_NOT_SET;
} else {
int ordinal = nativeFindCandidateResource(resourceTypes, waitTime);
result = OCStackResult.conversion(ordinal);
OCStackResult result;
if (null == s_presenceListener) {
- result = OCStackResult.OC_STACK_ERROR;
+ result = OCStackResult.OC_STACK_LISTENER_NOT_SET;
} else {
int ordinal = nativeSubscribeCollectionPresence(resource);
Map<String, String> configurations) throws OcException {
OCStackResult result;
if (null == configurationListener) {
- result = OCStackResult.OC_STACK_ERROR;
+ result = OCStackResult.OC_STACK_LISTENER_NOT_SET;
} else {
int ordinal = nativeUpdateConfigurations(resource, configurations);
result = OCStackResult.conversion(ordinal);
Vector<String> configurations) throws OcException {
OCStackResult result;
if (null == configurationListener) {
- result = OCStackResult.OC_STACK_ERROR;
+ result = OCStackResult.OC_STACK_LISTENER_NOT_SET;
} else {
int ordinal = nativeGetConfigurations(resource, configurations);
result = OCStackResult.conversion(ordinal);
public OCStackResult reboot(OcResource resource) throws OcException {
OCStackResult result;
- int ordinal = nativeReboot(resource);
- result = OCStackResult.conversion(ordinal);
-
+ if (null == thingsMaintenanceListener) {
+ result = OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ } else {
+ int ordinal = nativeReboot(resource);
+ result = OCStackResult.conversion(ordinal);
+ }
return result;
}
public OCStackResult factoryReset(OcResource resource) throws OcException {
OCStackResult result;
- int ordinal = nativeFactoryReset(resource);
- result = OCStackResult.conversion(ordinal);
-
+ if (null == thingsMaintenanceListener) {
+ result = OCStackResult.OC_STACK_LISTENER_NOT_SET;
+ } else {
+ int ordinal = nativeFactoryReset(resource);
+ result = OCStackResult.conversion(ordinal);
+ }
return result;
}
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function <
+OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+
+static std::string defaultConURI = "/oic/con";
+static std::string defaultConResourceType = "oic.wk.con";
+
+extern std::string defaultDeviceName;
+extern std::string defaultLocation;
+extern std::string defaultLocationName;
+extern std::string defaultCurrency;
+extern std::string defaultRegion;
+
+class ConfigurationResource
+{
+ public:
+ // Configuration members
+ std::string m_configurationUri;
+ std::string m_deviceName;
+ std::string m_location;
+ std::string m_locationName;
+ std::string m_currency;
+ std::string m_region;
+ std::vector< std::string > m_configurationTypes;
+ std::vector< std::string > m_configurationInterfaces;
+ OCResourceHandle m_configurationHandle;
+ OCRepresentation m_configurationRep;
+
+ public:
+ /// Constructor
+ ConfigurationResource() :
+ m_deviceName(defaultDeviceName), m_location(defaultLocation),
+ m_locationName(defaultLocationName), m_currency(defaultCurrency),
+ m_region(defaultRegion)
+ {
+ m_configurationUri = defaultConURI; // URI of the resource
+ m_configurationTypes.push_back(defaultConResourceType); // resource type name.
+ m_configurationInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+ m_configurationRep.setValue("st", m_deviceName);
+ m_configurationRep.setValue("loc", m_location);
+ m_configurationRep.setValue("locn", m_locationName);
+ m_configurationRep.setValue("c", m_currency);
+ m_configurationRep.setValue("r", m_region);
+ m_configurationRep.setUri(m_configurationUri);
+ m_configurationRep.setResourceTypes(m_configurationTypes);
+ m_configurationRep.setResourceInterfaces(m_configurationInterfaces);
+ m_configurationHandle = NULL;
+ }
+ ;
+
+ ~ConfigurationResource()
+ {
+
+ }
+
+ /// This function internally calls registerResource API.
+ void createResources(ResourceEntityHandler callback);
+ void setConfigurationRepresentation(OCRepresentation &rep);
+ OCRepresentation getConfigurationRepresentation();
+ std::string getUri();
+
+ void factoryReset();
+
+};
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+#include "ConfigurationCollection.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function <
+OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+
+class FactorySetResource : public ConfigurationResource
+{
+ public:
+ /// Constructor
+ FactorySetResource();
+
+ ~FactorySetResource();
+
+ /// This function internally calls registerResource API.
+ void createResources(ResourceEntityHandler callback);
+ void setFactorySetRepresentation(OCRepresentation &rep);
+ OCRepresentation getFactorySetRepresentation();
+
+ std::string getUri();
+};
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+///
+/// create a resource (collection) with children.
+///
+
+#include <functional>
+#include <thread>
+
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+#pragma once
+
+using namespace OC;
+
+typedef std::function <
+OCEntityHandlerResult(std::shared_ptr< OCResourceRequest > request) > ResourceEntityHandler;
+
+static std::string defaultMntURI = "/oic/mnt";
+static std::string defaultMntResourceType = "oic.wk.mnt";
+
+static std::string defaultFactoryReset = "false";
+static std::string defaultReboot = "false";
+static std::string defaultStartStatCollection = "false";
+
+class MaintenanceResource
+{
+ public:
+
+ // Maintenance members
+ std::string m_maintenanceUri;
+ std::string m_factoryReset;
+ std::string m_reboot;
+ std::string m_startStatCollection;
+ std::vector< std::string > m_maintenanceTypes;
+ std::vector< std::string > m_maintenanceInterfaces;
+ OCResourceHandle m_maintenanceHandle;
+ OCRepresentation m_maintenanceRep;
+
+ public:
+ /// Constructor
+ MaintenanceResource() :
+ m_factoryReset(defaultFactoryReset), m_reboot(defaultReboot),
+ m_startStatCollection(defaultStartStatCollection)
+ {
+ m_maintenanceUri = defaultMntURI; // URI of the resource
+ m_maintenanceTypes.push_back(defaultMntResourceType); // resource type name.
+ m_maintenanceInterfaces.push_back(DEFAULT_INTERFACE); // resource interface.
+ m_maintenanceRep.setValue("fr", m_factoryReset);
+ m_maintenanceRep.setValue("rb", m_reboot);
+ m_maintenanceRep.setValue("ssc", m_startStatCollection);
+ m_maintenanceRep.setUri(m_maintenanceUri);
+ m_maintenanceRep.setResourceTypes(m_maintenanceTypes);
+ m_maintenanceRep.setResourceInterfaces(m_maintenanceInterfaces);
+ m_maintenanceHandle = NULL;
+ }
+ ;
+
+ /// This function internally calls registerResource API.
+ void createResources(ResourceEntityHandler callback);
+
+ void setMaintenanceRepresentation(OCRepresentation &rep);
+
+ OCRepresentation getMaintenanceRepresentation();
+
+ std::string getUri();
+
+ void maintenanceMonitor(int second);
+
+ std::function< void() > factoryReset;
+};
+
--- /dev/null
+#******************************************************************
+#
+# Copyright 2015 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# ThingsManager Unit Test build script
+##
+import os
+Import('env')
+
+if env.get('RELEASE'):
+ env.AppendUnique(CCFLAGS = ['-Os'])
+ env.AppendUnique(CPPDEFINES = ['NDEBUG'])
+else:
+ env.AppendUnique(CCFLAGS = ['-g'])
+
+if env.get('LOGGING'):
+ env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+target_os = env.get('TARGET_OS')
+if target_os == 'linux':
+ # Verify that 'google unit test' library is installed. If not,
+ # get it and install it
+ SConscript(env.get('SRC_DIR') + '/extlibs/gtest/SConscript')
+
+ # Verify that 'hippomocks' mocking code is installed. If not,
+ # get it and install it
+ SConscript(env.get('SRC_DIR') + '/extlibs/hippomocks.scons')
+
+ThingsManager_gtest_env = lib_env.Clone()
+
+######################################################################
+#unit test setting
+######################################################################
+src_dir = lib_env.get('SRC_DIR')
+gtest_dir = src_dir + '/extlibs/gtest/gtest-1.7.0'
+
+######################################################################
+# Build flags
+######################################################################
+gtest = File(gtest_dir + '/lib/.libs/libgtest.a')
+gtest_main = File(gtest_dir + '/lib/.libs/libgtest_main.a')
+
+ThingsManager_gtest_env.AppendUnique(
+ CPPPATH = [
+ src_dir + '/extlibs/hippomocks-master',
+ src_dir + '/extlibs/gtest/gtest-1.7.0/include',
+ '../sdk/inc',
+ '../../../extlibs/timer'
+ ])
+
+if target_os not in ['windows', 'winrt']:
+ ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall'])
+ if target_os != 'android':
+ ThingsManager_gtest_env.AppendUnique(CXXFLAGS = ['-pthread'])
+ ThingsManager_gtest_env.AppendUnique(LIBS = ['pthread'])
+
+ThingsManager_gtest_env.PrependUnique(LIBS = [
+ 'libTGMSDKLibrary',
+ 'oc',
+ 'octbstack',
+ 'oc_logger',
+ 'oc_logger_core',
+ 'connectivity_abstraction',
+ gtest,
+ gtest_main])
+
+ThingsManager_gtest_env.AppendUnique(LIBS = ['dl'])
+
+######################################################################
+# Build Test
+######################################################################
+ThingsManager_gtest_src = env.Glob('./*.cpp')
+
+ThingsManagerTest = ThingsManager_gtest_env.Program('ThingsManagerTest', ThingsManager_gtest_src)
+Alias("ThingsManagerTest", ThingsManagerTest)
+env.AppendTarget('ThingsManagerTest')
+
+if env.get('TEST') == '1':
+ target_os = env.get('TARGET_OS')
+ if target_os == 'linux':
+ from tools.scons.RunTest import *
+ run_test(ThingsManager_gtest_env, '',
+ 'service/things-manager/unittests/ThingsManagerTest')
\ No newline at end of file
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 "UnitTestHelper.h"
+#include "MaintenanceCollection.h"
+#include "ConfigurationCollection.h"
+#include "FactorySetCollection.h"
+
+#include "timer.h"
+#include "ActionSet.h"
+#include "GroupManager.h"
+#include "ThingsConfiguration.h"
+#include "ThingsMaintenance.h"
+#include "ocstack.h"
+#include "OCPlatform.h"
+#include "OCApi.h"
+
+#include <iostream>
+#include <functional>
+#include <pthread.h>
+#include <condition_variable>
+
+#define SUCCESS_RESPONSE 0
+constexpr int DEFAULT_WAITING_TIME_IN_MILLIS = 3000;
+
+using namespace OIC;
+using namespace OC;
+using namespace std;
+namespace PH = std::placeholders;
+
+int result = 0;
+bool isSlowResponse = false;
+
+std::string defaultDeviceName = "Legacy Device";
+std::string defaultLocation = "37.256616, 127.052806";
+std::string defaultLocationName = "Living Room";
+std::string defaultRegion = "Won";
+std::string defaultCurrency = "Seoul, Korea";
+
+OCResourceHandle resourceHandle;
+OCResourceHandle foundResourceHandle;
+
+std::shared_ptr<OCResource> g_resource;
+std::shared_ptr<OCResource> g_room_resource;
+std::shared_ptr<OCResource> g_light;
+std::shared_ptr<OCResource> configurationResource;
+std::vector<string> lights;
+std::vector<OCResourceHandle> resourceHandleVector;
+
+GroupManager *groupMgr = new GroupManager();
+ConfigurationResource *myConfigurationResource;
+MaintenanceResource *myMaintenanceResource;
+FactorySetResource *myFactorySetResource;
+
+std::condition_variable cv1;
+std::condition_variable cv2;
+std::condition_variable cv3;
+std::condition_variable cv4;
+std::condition_variable cv5;
+
+bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request);
+OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest);
+OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request);
+OCEntityHandlerResult entityHandlerBootstrap(std::shared_ptr< OCResourceRequest > request);
+
+typedef std::function< void(OCRepresentation &) > putFunc;
+typedef std::function< OCRepresentation(void) > getFunc;
+
+void *ChangeLightRepresentation(void *param);
+void *handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest);
+
+
+/****** Light Resource [Required to gtestcases of GroupManager APIs] ******/
+
+class LightResource
+{
+ public:
+ std::string m_power;
+ std::string testing;
+ std::string m_lightUri;
+ OCResourceHandle m_resourceHandle;
+ OCRepresentation m_lightRep;
+
+ public:
+ LightResource() :
+ m_power("on"), m_lightUri("/a/light"), m_resourceHandle(0)
+ {
+ m_lightRep.setUri(m_lightUri);
+ m_lightRep.setValue("power", m_power);
+ }
+
+ void createResource()
+ {
+ std::string resourceURI = m_lightUri;
+ std::string resourceTypeName = "core.light";
+ std::string resourceInterface = DEFAULT_INTERFACE;
+ EntityHandler cb = std::bind(&LightResource::entityHandler, this, PH::_1);
+
+ OCStackResult result = OCPlatform::registerResource(m_resourceHandle, resourceURI,
+ resourceTypeName, resourceInterface, cb, OC_DISCOVERABLE | OC_OBSERVABLE);
+
+ if (OC_STACK_OK != result)
+ {
+ printf("\nLightResource : OC_STACK_OK != result...");
+ }
+ else
+ {
+ cv2.notify_all();
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv.wait(lock);
+ }
+ }
+
+ OCResourceHandle getHandle()
+ {
+ return m_resourceHandle;
+ }
+
+ void put(OCRepresentation &rep)
+ {
+ try
+ {
+ std::string test;
+ if (rep.getValue<std::string>("power", test))
+ {
+ cout << "\t\t\t\t" << "power: " << test << endl;
+ }
+ else
+ {
+ cout << "\t\t\t\t" << "power not found in the representation" << endl;
+ }
+ }
+ catch (exception &e)
+ {
+ cout << e.what() << endl;
+ }
+ }
+
+ OCRepresentation post(OCRepresentation &rep)
+ {
+ put(rep);
+ return get();
+ }
+
+ OCRepresentation get()
+ {
+ m_lightRep.setValue("power", m_power);
+
+ return m_lightRep;
+ }
+
+ void addType(const std::string &type) const
+ {
+ OCStackResult result = OCPlatform::bindTypeToResource(m_resourceHandle, type);
+ if (OC_STACK_OK != result)
+ {
+ cout << "Binding TypeName to Resource was unsuccessful\n";
+ }
+ }
+
+ void addInterface(const std::string &interface) const
+ {
+ OCStackResult result = OCPlatform::bindInterfaceToResource(m_resourceHandle, interface);
+ if (OC_STACK_OK != result)
+ {
+ cout << "Binding TypeName to Resource was unsuccessful\n";
+ }
+ }
+
+ private:
+ OCEntityHandlerResult entityHandler(std::shared_ptr< OCResourceRequest > request)
+ {
+ cout << "\tIn Server CPP entity handler:\n";
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+ if (request)
+ {
+ std::string requestType = request->getRequestType();
+ int requestFlag = request->getRequestHandlerFlag();
+
+ if (requestFlag & RequestHandlerFlag::RequestFlag)
+ {
+ cout << "\t\trequestFlag : Request\n";
+ auto pResponse = std::make_shared< OC::OCResourceResponse >();
+ pResponse->setRequestHandle(request->getRequestHandle());
+ pResponse->setResourceHandle(request->getResourceHandle());
+
+ if (requestType == "GET")
+ {
+ cout << "\t\t\trequestType : GET\n";
+ if (isSlowResponse)
+ {
+ static int startedThread = 0;
+ if (!startedThread)
+ {
+ std::thread t(handleSlowResponse, (void *) this, request);
+ startedThread = 1;
+ t.detach();
+ }
+ ehResult = OC_EH_SLOW;
+ }
+ else
+ {
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+ pResponse->setResourceRepresentation(get());
+ if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ }
+ else if (requestType == "PUT")
+ {
+ cout << "\t\t\trequestType : PUT\n";
+ OCRepresentation rep = request->getResourceRepresentation();
+ put(rep);
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+ pResponse->setResourceRepresentation(rep);
+ if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ else if (requestType == "POST")
+ {
+ cout << "\t\t\trequestType : POST\n";
+
+ OCRepresentation rep = request->getResourceRepresentation();
+ OCRepresentation rep_post = post(rep);
+
+ pResponse->setResourceRepresentation(rep_post);
+ pResponse->setErrorCode(200);
+ if (rep_post.hasAttribute("createduri"))
+ {
+ pResponse->setResponseResult(OC_EH_RESOURCE_CREATED);
+ pResponse->setNewResourceUri(
+ rep_post.getValue< std::string >("createduri"));
+ }
+
+ if (OC_STACK_OK == OCPlatform::sendResponse(pResponse))
+ {
+ ehResult = OC_EH_OK;
+ }
+ }
+ else if (requestType == "DELETE")
+ {
+ }
+ }
+ }
+ else
+ {
+ std::cout << "Request invalid" << std::endl;
+ }
+ return ehResult;
+ }
+};
+
+void *handleSlowResponse(void *param, std::shared_ptr< OCResourceRequest > pRequest)
+{
+ LightResource *lightPtr = (LightResource *) param;
+ sleep(10);
+
+ auto pResponse = std::make_shared< OC::OCResourceResponse >();
+ pResponse->setRequestHandle(pRequest->getRequestHandle());
+ pResponse->setResourceHandle(pRequest->getResourceHandle());
+ pResponse->setResourceRepresentation(lightPtr->get());
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+
+ isSlowResponse = false;
+ OCPlatform::sendResponse(pResponse);
+ return NULL;
+}
+
+/****** Configuration Resource ******/
+
+void ConfigurationResource::createResources(ResourceEntityHandler callback)
+{
+ using namespace OC::OCPlatform;
+
+ if (callback == NULL)
+ {
+ std::cout << "callback should be binded\t";
+ return;
+ }
+
+ OCStackResult result = registerResource(m_configurationHandle, m_configurationUri,
+ m_configurationTypes[0], m_configurationInterfaces[0], callback,
+ OC_DISCOVERABLE | OC_OBSERVABLE);
+
+ if (OC_STACK_OK != result)
+ {
+ std::cout << "Resource creation (configuration) was unsuccessful\n";
+ }
+ else
+ {
+ cv2.notify_all();
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv.wait(lock);
+ }
+}
+
+void ConfigurationResource::setConfigurationRepresentation(OCRepresentation &rep)
+{
+ string value;
+ if (rep.getValue("n", value))
+ {
+ m_deviceName = value;
+ std::cout << "\t\t\t\t" << "m_deviceName: " << m_deviceName << std::endl;
+ }
+
+ if (rep.getValue("loc", value))
+ {
+ m_location = value;
+ std::cout << "\t\t\t\t" << "m_location: " << m_location << std::endl;
+ }
+
+ if (rep.getValue("locn", value))
+ {
+ m_locationName = value;
+ std::cout << "\t\t\t\t" << "m_locationName: " << m_locationName << std::endl;
+ }
+
+ if (rep.getValue("c", value))
+ {
+ m_currency = value;
+ std::cout << "\t\t\t\t" << "m_currency: " << m_currency << std::endl;
+ }
+
+ if (rep.getValue("r", value))
+ {
+ m_region = value;
+ std::cout << "\t\t\t\t" << "m_region: " << m_region << std::endl;
+ }
+}
+
+OCRepresentation ConfigurationResource::getConfigurationRepresentation()
+{
+ m_configurationRep.setValue("n", m_deviceName);
+ m_configurationRep.setValue("loc", m_location);
+ m_configurationRep.setValue("locn", m_locationName);
+ m_configurationRep.setValue("c", m_currency);
+ m_configurationRep.setValue("r", m_region);
+
+ return m_configurationRep;
+}
+
+std::string ConfigurationResource::getUri()
+{
+ return m_configurationUri;
+}
+
+void ConfigurationResource::factoryReset()
+{
+ m_deviceName = defaultDeviceName;
+ m_location = defaultLocation;
+ m_locationName = defaultLocationName;
+ m_currency = defaultCurrency;
+ m_region = defaultRegion;
+}
+
+
+/****** FactorySet Resource ******/
+
+FactorySetResource::FactorySetResource()
+{
+ m_configurationUri = "/factoryset"; // URI of the resource
+ m_configurationTypes.clear();
+ m_configurationTypes.push_back("factoryset"); // resource type name.
+ m_configurationRep.setUri(m_configurationUri);
+ m_configurationRep.setResourceTypes(m_configurationTypes);
+}
+
+FactorySetResource::~FactorySetResource() {}
+
+void FactorySetResource::createResources(ResourceEntityHandler callback)
+{
+ using namespace OC::OCPlatform;
+
+ if (callback == NULL)
+ {
+ std::cout << "callback should be binded\t";
+ return;
+ }
+
+ OCStackResult result = registerResource(m_configurationHandle, m_configurationUri,
+ m_configurationTypes[0], m_configurationInterfaces[0], callback,
+ OC_DISCOVERABLE | OC_OBSERVABLE);
+
+ if (OC_STACK_OK != result)
+ {
+ std::cout << "Resource creation (configuration) was unsuccessful\n";
+ }
+
+ else
+ {
+ cv4.notify_all();
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv.wait(lock);
+ }
+}
+
+void FactorySetResource::setFactorySetRepresentation(OCRepresentation &rep)
+{
+ string value;
+
+ if (rep.getValue("n", value))
+ {
+ m_deviceName = value;
+ std::cout << "\t\t\t\t" << "m_deviceName: " << m_deviceName << std::endl;
+ }
+
+ if (rep.getValue("loc", value))
+ {
+ m_location = value;
+ std::cout << "\t\t\t\t" << "m_location: " << m_location << std::endl;
+ }
+
+ if (rep.getValue("locn", value))
+ {
+ m_locationName = value;
+ std::cout << "\t\t\t\t" << "m_locationName: " << m_locationName << std::endl;
+ }
+
+ if (rep.getValue("c", value))
+ {
+ m_currency = value;
+ std::cout << "\t\t\t\t" << "m_currency: " << m_currency << std::endl;
+ }
+
+ if (rep.getValue("r", value))
+ {
+ m_region = value;
+ std::cout << "\t\t\t\t" << "m_region: " << m_region << std::endl;
+ }
+}
+
+OCRepresentation FactorySetResource::getFactorySetRepresentation()
+{
+ m_configurationRep.setValue("n", m_deviceName);
+ m_configurationRep.setValue("loc", m_location);
+ m_configurationRep.setValue("locn", m_locationName);
+ m_configurationRep.setValue("c", m_currency);
+ m_configurationRep.setValue("r", m_region);
+
+ return m_configurationRep;
+}
+
+std::string FactorySetResource::getUri()
+{
+ return m_configurationUri;
+}
+
+
+/****** Maintenance Resource ********/
+
+void MaintenanceResource::createResources(ResourceEntityHandler callback)
+{
+ using namespace OC::OCPlatform;
+
+ if (callback == NULL)
+ {
+ std::cout << "callback should be binded\t";
+ return;
+ }
+
+ OCStackResult result = registerResource(m_maintenanceHandle, m_maintenanceUri,
+ m_maintenanceTypes[0], m_maintenanceInterfaces[0], callback,
+ OC_DISCOVERABLE | OC_OBSERVABLE);
+
+ if (OC_STACK_OK != result)
+ {
+ std::cout << "Resource creation (maintenance) was unsuccessful\n";
+ }
+
+ thread exec(
+ std::function< void(int second) >(
+ std::bind(&MaintenanceResource::maintenanceMonitor, this,
+ std::placeholders::_1)), 10);
+ exec.detach();
+ cv3.notify_all();
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv.wait(lock);
+
+ std::cout << "maintenance Resource is Created!\n";
+}
+
+void MaintenanceResource::setMaintenanceRepresentation(OCRepresentation &rep)
+{
+ string value;
+
+ if (rep.getValue("fr", value))
+ {
+ m_factoryReset = value;
+ std::cout << "\t\t\t\t" << "m_factoryReset: " << m_factoryReset << std::endl;
+ }
+
+ if (rep.getValue("rb", value))
+ {
+ m_reboot = value;
+ std::cout << "\t\t\t\t" << "m_reboot: " << m_reboot << std::endl;
+ }
+
+ if (rep.getValue("ssc", value))
+ {
+ m_startStatCollection = value;
+ std::cout << "\t\t\t\t" << "m_startStatCollection: " << m_startStatCollection << std::endl;
+ }
+}
+
+OCRepresentation MaintenanceResource::getMaintenanceRepresentation()
+{
+ m_maintenanceRep.setValue("fr", m_factoryReset);
+ m_maintenanceRep.setValue("rb", m_reboot);
+ m_maintenanceRep.setValue("ssc", m_startStatCollection);
+
+ return m_maintenanceRep;
+}
+
+std::string MaintenanceResource::getUri()
+{
+ return m_maintenanceUri;
+}
+
+void MaintenanceResource::maintenanceMonitor(int second)
+{
+ while (1)
+ {
+ sleep(second);
+
+ if (m_reboot == "true")
+ {
+ int res;
+ std::cout << "Reboot will be soon..." << std::endl;
+ m_reboot = defaultReboot;
+ res = system("sudo reboot");
+
+ std::cout << "return: " << res << std::endl;
+
+ }
+ else if (m_factoryReset == "true")
+ {
+ std::cout << "Factory Reset will be soon..." << std::endl;
+ m_factoryReset = defaultFactoryReset;
+ factoryReset();
+ }
+ }
+}
+
+getFunc getGetFunction(std::string uri)
+{
+ getFunc res = NULL;
+
+ if (uri == myConfigurationResource->getUri())
+ {
+ res = std::bind(&ConfigurationResource::getConfigurationRepresentation,
+ myConfigurationResource);
+ }
+ else if (uri == myMaintenanceResource->getUri())
+ {
+ res = std::bind(&MaintenanceResource::getMaintenanceRepresentation,
+ myMaintenanceResource);
+ }
+ return res;
+}
+
+putFunc getPutFunction(std::string uri)
+{
+ putFunc res = NULL;
+
+ if (uri == myConfigurationResource->getUri())
+ {
+ res = std::bind(&ConfigurationResource::setConfigurationRepresentation,
+ myConfigurationResource, std::placeholders::_1);
+ }
+ else if (uri == myMaintenanceResource->getUri())
+ {
+ res = std::bind(&MaintenanceResource::setMaintenanceRepresentation,
+ myMaintenanceResource, std::placeholders::_1);
+ }
+ return res;
+}
+
+bool prepareResponseForResource(std::shared_ptr< OCResourceRequest > request)
+{
+ std::cout << "\tIn Server CPP prepareResponseForResource:\n";
+ bool result = false;
+ if (request)
+ {
+ std::string requestType = request->getRequestType();
+ int requestFlag = request->getRequestHandlerFlag();
+
+ if (requestFlag == RequestHandlerFlag::RequestFlag)
+ {
+ std::cout << "\t\trequestFlag : Request\n";
+ if (requestType == "GET")
+ {
+ std::cout << "\t\t\trequestType : GET\n";
+ result = true;
+ }
+ else if (requestType == "PUT")
+ {
+ std::cout << "\t\t\trequestType : PUT\n";
+ putFunc putFunction;
+ OCRepresentation rep = request->getResourceRepresentation();
+
+ putFunction = getPutFunction(request->getResourceUri());
+ putFunction(rep);
+ result = true;
+ }
+ else if (requestType == "POST")
+ {
+ }
+ else if (requestType == "DELETE")
+ {
+ }
+ }
+ else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+ {
+ std::cout << "\t\trequestFlag : Observer\n";
+ }
+ }
+ else
+ {
+ std::cout << "Request invalid" << std::endl;
+ }
+
+ return result;
+}
+
+OCStackResult sendResponseForResource(std::shared_ptr< OCResourceRequest > pRequest)
+{
+ auto pResponse = std::make_shared< OC::OCResourceResponse >();
+ QueryParamsMap queryParamsMap = pRequest->getQueryParameters();
+
+ pResponse->setRequestHandle(pRequest->getRequestHandle());
+ pResponse->setResourceHandle(pRequest->getResourceHandle());
+
+ getFunc getFunction;
+ getFunction = getGetFunction(pRequest->getResourceUri());
+
+ OCRepresentation rep;
+ rep = getFunction();
+
+ auto findRes = queryParamsMap.find("if");
+
+ if (findRes != queryParamsMap.end())
+ {
+ pResponse->setResourceRepresentation(rep, findRes->second);
+ }
+ else
+ {
+ pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE);
+ }
+
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+
+ return OCPlatform::sendResponse(pResponse);
+}
+
+OCEntityHandlerResult entityHandlerForResource(std::shared_ptr< OCResourceRequest > request)
+{
+ std::cout << "\tIn Server CPP (entityHandlerForResource) entity handler:\n";
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+ QueryParamsMap test = request->getQueryParameters();
+
+ if (prepareResponseForResource(request))
+ {
+ if (OC_STACK_OK == sendResponseForResource(request))
+ {
+ ehResult = OC_EH_OK;
+ }
+ else
+ {
+ std::cout << "sendResponse failed." << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "PrepareResponse failed." << std::endl;
+ }
+ return ehResult;
+}
+
+
+/****** BootStrap Resource [Required for doBootstrap API of ThingsConfiguration class] ******/
+
+class BootstrapResource
+{
+ public:
+ std::string m_bootstrapUri;
+ std::vector< std::string > m_bootstrapTypes;
+ std::vector< std::string > m_bootstrapInterfaces;
+ OCResourceHandle m_bootstrapHandle;
+ OCRepresentation m_bootstrapRep;
+
+ public:
+ BootstrapResource()
+ {
+ m_bootstrapUri = "/bootstrap";
+ m_bootstrapTypes.push_back("bootstrap");
+ m_bootstrapInterfaces.push_back(DEFAULT_INTERFACE);
+ m_bootstrapRep.setUri(m_bootstrapUri);
+ m_bootstrapRep.setResourceTypes(m_bootstrapTypes);
+ m_bootstrapRep.setResourceInterfaces(m_bootstrapInterfaces);
+ m_bootstrapHandle = NULL;
+ }
+ void createResources()
+ {
+ using namespace OC::OCPlatform;
+ OCStackResult result = registerResource(m_bootstrapHandle, m_bootstrapUri,
+ m_bootstrapTypes[0], m_bootstrapInterfaces[0], entityHandlerBootstrap,
+ OC_DISCOVERABLE | OC_OBSERVABLE);
+
+ if (OC_STACK_OK != result)
+ {
+ cout << "Resource creation (room) was unsuccessful\n";
+ }
+
+ cv5.notify_all();
+ std::mutex blocker;
+ std::condition_variable cv;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv.wait(lock);
+ }
+
+ void setBootstrapRepresentation(OCRepresentation &rep)
+ {
+ }
+
+ OCRepresentation getBootstrapRepresentation()
+ {
+ m_bootstrapRep.setValue< std::string >("n", defaultDeviceName);
+ m_bootstrapRep.setValue< std::string >("loc", defaultLocation);
+ m_bootstrapRep.setValue< std::string >("locn", defaultLocationName);
+ m_bootstrapRep.setValue< std::string >("c", defaultCurrency);
+ m_bootstrapRep.setValue< std::string >("r", defaultRegion);
+
+ return m_bootstrapRep;
+ }
+};
+
+BootstrapResource myBootstrapResource;
+
+bool prepareResponse(std::shared_ptr< OCResourceRequest > request)
+{
+ cout << "\tIn Server CPP prepareResponse:\n";
+ bool result = false;
+ if (request)
+ {
+ std::string requestType = request->getRequestType();
+ int requestFlag = request->getRequestHandlerFlag();
+
+ if (requestFlag == RequestHandlerFlag::RequestFlag)
+ {
+ cout << "\t\trequestFlag : Request\n";
+ if (requestType == "GET")
+ {
+ cout << "\t\t\trequestType : GET\n";
+ result = true;
+ }
+ else if (requestType == "PUT")
+ {
+ cout << "\t\t\trequestType : PUT\n";
+
+ OCRepresentation rep = request->getResourceRepresentation();
+ myBootstrapResource.setBootstrapRepresentation(rep);
+ result = true;
+ }
+ else if (requestType == "POST")
+ {
+ }
+ else if (requestType == "DELETE")
+ {
+ }
+ }
+ else if (requestFlag == RequestHandlerFlag::ObserverFlag)
+ {
+ cout << "\t\trequestFlag : Observer\n";
+ }
+ }
+ else
+ {
+ std::cout << "Request invalid" << std::endl;
+ }
+
+ return result;
+}
+
+OCStackResult sendResponse(std::shared_ptr< OCResourceRequest > pRequest)
+{
+ auto pResponse = std::make_shared< OC::OCResourceResponse >();
+ pResponse->setRequestHandle(pRequest->getRequestHandle());
+ pResponse->setResourceHandle(pRequest->getResourceHandle());
+ pResponse->setResourceRepresentation(myBootstrapResource.getBootstrapRepresentation());
+ pResponse->setErrorCode(200);
+ pResponse->setResponseResult(OC_EH_OK);
+
+ return OCPlatform::sendResponse(pResponse);
+}
+
+OCEntityHandlerResult entityHandlerBootstrap(std::shared_ptr< OCResourceRequest > request)
+{
+ cout << "\tIn Server CPP (entityHandlerBootstrap) entity handler:\n";
+ OCEntityHandlerResult ehResult = OC_EH_ERROR;
+
+ if (prepareResponse(request))
+ {
+ if (OC_STACK_OK == sendResponse(request))
+ {
+ ehResult = OC_EH_OK;
+ }
+ else
+ {
+ std::cout << "sendResponse failed." << std::endl;
+ }
+ }
+ else
+ {
+ std::cout << "PrepareResponse failed." << std::endl;
+ }
+ return ehResult;
+}
+
+
+/****** gtest class ******/
+
+class ThingsManagerTest: public TestWithMock
+{
+ public :
+ void Proceed()
+ {
+ cond.notify_all();
+ }
+
+ void Wait(int waitingTime = DEFAULT_WAITING_TIME_IN_MILLIS)
+ {
+ std::unique_lock< std::mutex > lock { mutex };
+ cond.wait_for(lock, std::chrono::milliseconds { waitingTime });
+ }
+
+ protected:
+ void SetUp()
+ {
+ TestWithMock::SetUp();
+ }
+
+ void TearDown()
+ {
+ TestWithMock::TearDown();
+ }
+
+ private:
+ std::condition_variable cond;
+ std::mutex mutex;
+};
+
+//Callbacks
+void onUpdate(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode) {}
+
+void onGetBootstrapInformation(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+ const int eCode) {}
+
+void onReboot(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode) {}
+
+void onFactoryReset(const HeaderOptions &headerOptions, const OCRepresentation &rep,
+ const int eCode) {}
+
+void onGet(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode) {}
+
+void onPut(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode) {}
+
+void onPost(const HeaderOptions &headerOptions, const OCRepresentation &rep, const int eCode) {}
+
+void foundResources(std::vector<std::shared_ptr<OC::OCResource> > listOfResource)
+{
+ for (auto rsrc = listOfResource.begin(); rsrc != listOfResource.end();
+ ++rsrc)
+ {
+ std::string resourceURI = (*rsrc)->uri();
+ std::string hostAddress = (*rsrc)->host();
+
+ if (resourceURI == "/a/light")
+ {
+ result = OCPlatform::registerResource(
+ foundResourceHandle, (*rsrc));
+ if (result == OC_STACK_OK)
+ {
+ OCPlatform::bindResource(resourceHandle, foundResourceHandle);
+ resourceHandleVector.push_back(foundResourceHandle);
+ }
+ else
+ {
+ cout << "\tresource Error!" << endl;
+ }
+ lights.push_back((hostAddress + resourceURI));
+
+ g_light = (*rsrc);
+ }
+ else
+ {
+ configurationResource = (*rsrc);
+ }
+ }
+ cv2.notify_all();
+}
+
+void foundGroupResource(std::shared_ptr<OCResource> resource)
+{
+ std::string resourceURI;
+ resourceURI = resource->uri();
+ if (resourceURI == "/core/a/collection")
+ {
+ g_resource = resource;
+ }
+ else
+ {
+ g_room_resource = resource;
+ }
+ cv1.notify_all();
+}
+
+//This test case is to create the lightserver , BootstrapServer & configuration sever
+TEST_F(ThingsManagerTest, testCreateResources)
+{
+ PlatformConfig cfg { OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0, OC::QualityOfService::LowQos };
+ OCPlatform::Configure(cfg);
+ bool actual = true;
+
+ LightResource myLight;
+ std::thread t1(&LightResource::createResource, &myLight);
+ t1.detach();
+ std::mutex blocker1;
+ std::unique_lock < std::mutex > lock1(blocker1);
+ cv2.wait(lock1);
+
+ std::thread t2(&BootstrapResource::createResources, &myBootstrapResource);
+ t2.detach();
+ std::mutex blocker2;
+ std::unique_lock < std::mutex > lock2(blocker2);
+ cv5.wait(lock2);
+
+ myConfigurationResource = new ConfigurationResource();
+ std::thread t3(&ConfigurationResource::createResources, myConfigurationResource,
+ &entityHandlerForResource);
+
+ t3.detach();
+ std::mutex blocker3;
+ std::unique_lock < std::mutex > lock3(blocker3);
+ cv2.wait(lock3);
+
+ myMaintenanceResource = new MaintenanceResource();
+ std::thread t4(&MaintenanceResource::createResources, myMaintenanceResource,
+ &entityHandlerForResource);
+ t4.detach();
+
+ std::mutex blocker4;
+ std::unique_lock < std::mutex > lock4(blocker4);
+ cv3.wait(lock4);
+
+ myFactorySetResource = new FactorySetResource();
+ std::thread t5(&FactorySetResource::createResources, myFactorySetResource,
+ &entityHandlerForResource);
+ t5.detach();
+
+ std::mutex blocker5;
+ std::unique_lock < std::mutex > lock5(blocker5);
+ cv4.wait(lock5);
+
+ myMaintenanceResource->factoryReset = std::function < void()
+ > (std::bind(&ConfigurationResource::factoryReset,
+ myConfigurationResource));
+}
+
+//Check findCandidateResources
+TEST_F(ThingsManagerTest, testFindCandidateResources)
+{
+
+ string resourceURI = "/core/a/collection";
+ string resourceTypeName = "a.collection";
+ string resourceInterface = BATCH_INTERFACE;
+
+ OCStackResult res = OCPlatform::registerResource(resourceHandle, resourceURI,
+ resourceTypeName, resourceInterface, NULL, OC_DISCOVERABLE);
+
+ if ( res != OC_STACK_OK )
+ {
+ cout << "Resource registeration failed." << endl;
+ }
+
+ OCPlatform::bindInterfaceToResource(resourceHandle, GROUP_INTERFACE);
+ OCPlatform::bindInterfaceToResource(resourceHandle, DEFAULT_INTERFACE);
+
+ std::string query = OC_RSRVD_WELL_KNOWN_URI;
+ query.append("?rt=");
+ query.append(resourceTypeName);
+
+ OCPlatform::findResource("", query, CT_DEFAULT, &foundGroupResource);
+
+ std::mutex blocker1;
+ std::unique_lock < std::mutex > lock1(blocker1);
+ cv1.wait(lock1);
+
+ GroupManager *instance = new GroupManager();
+ vector<string> types;
+ types.push_back("core.light");
+
+ result = instance->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker2;
+ std::unique_lock < std::mutex > lock2(blocker2);
+ cv2.wait(lock2);
+}
+
+//Find Candidate Resource when no resources are specified
+TEST_F(ThingsManagerTest, testFindCandidateResourcesEmptyResourceType)
+{
+ GroupManager *instance = new GroupManager();
+ vector<string> types;
+ result = instance->findCandidateResources(types, &foundResources);
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+}
+
+//Find Candidate Resource when Callback is null
+TEST_F(ThingsManagerTest, testFindCandidateResourcesNullCallback)
+{
+ GroupManager *instance = new GroupManager();
+ vector<string> types;
+ types.push_back("core.light");
+ result = instance->findCandidateResources(types, NULL);
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+}
+
+//test bind resource to group
+TEST_F(ThingsManagerTest, testBindResourceToGroup)
+{
+ GroupManager *instance = new GroupManager();
+ OCResourceHandle groupHandle = NULL;
+ OCResourceHandle foundHandle = NULL;
+ OCResourceHandle rHandle = NULL;
+
+ string resourceURI = "/core/room-large";
+ string resourceTypeName = "core.room-large";
+ string resourceInterface = BATCH_INTERFACE;
+
+ OCStackResult res = OCPlatform::registerResource(rHandle, resourceURI,
+ resourceTypeName, resourceInterface, NULL, OC_DISCOVERABLE);
+
+ if ( res != OC_STACK_OK )
+ {
+ cout << "Resource registeration failed." << endl;
+ }
+
+ OCPlatform::bindInterfaceToResource(rHandle, GROUP_INTERFACE);
+ OCPlatform::bindInterfaceToResource(rHandle, DEFAULT_INTERFACE);
+
+
+ std::string query = OC_RSRVD_WELL_KNOWN_URI;
+ query.append("?rt=");
+ query.append(resourceTypeName);
+
+ OCPlatform::findResource("", query, CT_DEFAULT, &foundGroupResource);
+
+ std::mutex blocker1;
+ std::unique_lock < std::mutex > lock1(blocker1);
+ cv1.wait(lock1);
+
+ result = instance->bindResourceToGroup (resourceHandle, g_room_resource, rHandle);
+
+ EXPECT_TRUE(result == OC_STACK_OK);
+}
+
+//Add actionset
+TEST_F(ThingsManagerTest, testAddActionSetAllBulbOff)
+{
+ string actionsetDesc;
+ ActionSet *allBulbOff = new ActionSet();
+ allBulbOff->actionsetName = "AllBulbOff";
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "off";
+
+ action->listOfCapability.push_back(capa);
+ allBulbOff->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbOff, &onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+ delete allBulbOff;
+}
+
+//Add actionset with NULL resource
+TEST_F(ThingsManagerTest, testAddActionSetAllBulbOffResourceNull)
+{
+ string actionsetDesc;
+ ActionSet *allBulbOff = new ActionSet();
+ allBulbOff->actionsetName = "AllBulbOff";
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "off";
+
+ action->listOfCapability.push_back(capa);
+ allBulbOff->listOfAction.push_back(action);
+ }
+
+ result = groupMgr->addActionSet(NULL, allBulbOff, &onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+
+ delete allBulbOff;
+}
+
+//Add actionset with NULL ActionSet
+TEST_F(ThingsManagerTest, testAddActionSetAllBulbOffActionsetNull)
+{
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, NULL, &onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+ }
+}
+
+//Add actionset
+TEST_F(ThingsManagerTest, testAddActionSetAllBulbOn)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOn";
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "on";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbON, onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+ delete allBulbON;
+}
+
+//Add actionset with NULL Resource
+TEST_F(ThingsManagerTest, testAddActionSetAllBulbOnResourceNull)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOn";
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "on";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+
+ result = groupMgr->addActionSet(NULL, allBulbON, onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+
+ delete allBulbON;
+}
+
+//Add actionset with NULL ActionSet
+TEST_F(ThingsManagerTest, testAddActionSetAllBulbOnActionSetNull)
+{
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, NULL, onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+ }
+}
+
+//Execute actionset
+TEST_F(ThingsManagerTest, testExecuteActionSetAllBulbOn)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOn1";
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "on";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbON, onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+
+ mocks.ExpectCallFunc(onPost).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ if (g_resource)
+ {
+ result = groupMgr->executeActionSet(g_resource, "AllBulbOn", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Execute actionset with NULL Resource
+TEST_F(ThingsManagerTest, testExecuteActionSetAllBulbOnResourceNull)
+{
+ result = groupMgr->executeActionSet(NULL, "AllBulbOn", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Execute actionset
+TEST_F(ThingsManagerTest, testExecuteActionSetAllBulbOff)
+{
+ mocks.ExpectCallFunc(onPost).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ if (g_resource)
+ {
+ result = groupMgr->executeActionSet(g_resource, "AllBulbOff", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Execute actionset with NULL resource
+TEST_F(ThingsManagerTest, testExecuteActionSetAllBulbOffResourceNull)
+{
+ result = groupMgr->executeActionSet(NULL, "AllBulbOff", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Execute actionset with Delay
+TEST_F(ThingsManagerTest, testExcecuteActionSetWithDelay)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOnDelay";
+ allBulbON->setDelay(1);
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "off";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbON, onPut);
+ Wait();
+ }
+
+ mocks.ExpectCallFunc(onPost).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ if (g_resource)
+ {
+ result = groupMgr->executeActionSet(g_resource, "AllBulbOnDelay", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Execute actionset with Delay = 0
+TEST_F(ThingsManagerTest, testExcecuteActionSetWithDelayEqulasZero)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOnDelay";
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "off";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbON, onPut);
+ Wait();
+ }
+
+ if (g_resource)
+ {
+ result = groupMgr->executeActionSet(g_resource, "AllBulbOnDelay", 0, &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_INVALID_PARAM);
+ result = 0;
+ }
+}
+
+//Execute actionset with invalid Delay
+TEST_F(ThingsManagerTest, testExcecuteActionSetWithInvalidDelay)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOnDelay";
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "off";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbON, onPut);
+ Wait();
+ }
+
+ if (g_resource)
+ {
+ result = groupMgr->executeActionSet(g_resource, "AllBulbOnDelay", -10, &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_INVALID_PARAM);
+ result = 0;
+ }
+}
+
+//Execute actionset with delay on NULL Resource
+TEST_F(ThingsManagerTest, testExcecuteActionSetWithDelayWithResourceNull)
+{
+ string actionsetDesc;
+ ActionSet *allBulbON = new ActionSet();
+ allBulbON->actionsetName = "AllBulbOnDelay";
+ allBulbON->setDelay(5);
+
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ for (auto iter = lights.begin(); iter != lights.end(); ++iter)
+ {
+ Action *action = new Action();
+ action->target = (*iter);
+
+ Capability *capa = new Capability();
+ capa->capability = "power";
+ capa->status = "off";
+
+ action->listOfCapability.push_back(capa);
+ allBulbON->listOfAction.push_back(action);
+ }
+ if (g_resource)
+ {
+ result = groupMgr->addActionSet(g_resource, allBulbON, onPut);
+ Wait();
+ }
+ result = groupMgr->executeActionSet(NULL, "AllBulbOnDelay", &onPost);
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+
+}
+
+//Cancel ActionSet
+TEST_F(ThingsManagerTest, testCancelActionSet)
+{
+ mocks.ExpectCallFunc(onPost).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ if (g_resource)
+ {
+ result = groupMgr->cancelActionSet(g_resource, "AllBulbOff", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Cancel ActionSet on NULL Resource
+TEST_F(ThingsManagerTest, testCancelActionSetResourceNull)
+{
+ result = groupMgr->cancelActionSet(NULL, "AllBulbOff", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Delete ActionSet
+TEST_F(ThingsManagerTest, testDeleteActionSet)
+{
+ mocks.ExpectCallFunc(onPut).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ if (g_resource)
+ {
+ result = groupMgr->deleteActionSet(g_resource, "AllBulbOff", &onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Delete ActionSet on NULL Resource
+TEST_F(ThingsManagerTest, testDeleteActionSetResourceNull)
+{
+ result = groupMgr->deleteActionSet(NULL, "AllBulbOff", &onPut);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Get ActionSet
+TEST_F(ThingsManagerTest, testGetActionSet)
+{
+ mocks.ExpectCallFunc(onPost).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ if (g_resource)
+ {
+ result = groupMgr->getActionSet(g_resource, "AllBulbOn", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Get ActionSet on NULL Resource
+TEST_F(ThingsManagerTest, testGetActionSetResourceNull)
+{
+ result = groupMgr->getActionSet(NULL, "AllBulbOn", &onPost);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Get Configurations
+TEST_F(ThingsManagerTest, testGetConfigurations)
+{
+ ConfigurationName name = "all";
+
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+ std::vector< ConfigurationName > configurations;
+
+ configurations.push_back(name);
+
+ mocks.ExpectCallFunc(onGet).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ vector<string> types;
+ types.push_back("oic.wk.con");
+
+ result = groupMgr->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv2.wait(lock);
+
+ if (result == OC_STACK_OK)
+ {
+ result = g_thingsConf->getConfigurations(configurationResource, configurations, &onGet);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Get Configurations with empty Configuration
+TEST_F(ThingsManagerTest, testGetConfigurationsEmptyConfiguration)
+{
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+ std::vector< ConfigurationName > configurations;
+
+ vector<string> types;
+ types.push_back("oic.wk.con");
+
+ result = groupMgr->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv2.wait(lock);
+
+ if (result == OC_STACK_OK)
+ {
+ result = g_thingsConf->getConfigurations(configurationResource, configurations, &onGet);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+ }
+}
+
+//Get Configurations on NULL Resource
+TEST_F(ThingsManagerTest, testGetConfigurationsResourceNull)
+{
+ ConfigurationName name = "all";
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+ std::vector< ConfigurationName > configurations;
+
+ configurations.push_back(name);
+
+ result = g_thingsConf->getConfigurations(NULL, configurations, &onGet);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Get all supported Configurations
+TEST_F(ThingsManagerTest, testGetallSupportedCOnfigurations)
+{
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+ string retVal = g_thingsConf->getListOfSupportedConfigurationUnits();
+ EXPECT_FALSE(retVal.size() == 0);
+}
+
+//DoBootstrap
+TEST_F(ThingsManagerTest, testDoBootstrap)
+{
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+
+ mocks.ExpectCallFunc(onGetBootstrapInformation).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+ result = g_thingsConf->doBootstrap(&onGetBootstrapInformation);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+}
+
+//DoBootstrap with NULL callback
+TEST_F(ThingsManagerTest, testDoBootstrapCallBackNull)
+{
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+
+ result = g_thingsConf->doBootstrap(NULL);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Update Configuration
+TEST_F(ThingsManagerTest, testUpdateConfiguration)
+{
+ ConfigurationName name = "r";
+ ConfigurationValue value = "INDIA";
+
+ std::map< ConfigurationName, ConfigurationValue > configurations;
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+ configurations.insert(std::make_pair(name, value));
+
+ mocks.ExpectCallFunc(onUpdate).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ vector<string> types;
+ types.push_back("oic.wk.con");
+ result = groupMgr->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker2;
+ std::unique_lock < std::mutex > lock2(blocker2);
+ cv2.wait(lock2);
+
+ if (result == OC_STACK_OK)
+ {
+ result = g_thingsConf->updateConfigurations(configurationResource, configurations, &onUpdate);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Update Configuration with Empty Configuration
+TEST_F(ThingsManagerTest, testUpdateConfigurationEmptyConfiguration)
+{
+ std::map< ConfigurationName, ConfigurationValue > configurations;
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+
+ vector<string> types;
+ types.push_back("oic.wk.con");
+ result = groupMgr->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker2;
+ std::unique_lock < std::mutex > lock2(blocker2);
+ cv2.wait(lock2);
+
+ if (result == OC_STACK_OK)
+ {
+ result = g_thingsConf->updateConfigurations(configurationResource, configurations, &onUpdate);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+ }
+}
+
+//Update Configuration on NULL Resource
+TEST_F(ThingsManagerTest, testUpdateConfigurationResourceNull)
+{
+ ConfigurationName name = "r";
+ ConfigurationValue value = "INDIA";
+
+ std::map< ConfigurationName, ConfigurationValue > configurations;
+ ThingsConfiguration *g_thingsConf = ThingsConfiguration::getInstance();
+
+ configurations.insert(std::make_pair(name, value));
+
+ result = g_thingsConf->updateConfigurations(NULL, configurations, &onUpdate);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Reboot
+TEST_F(ThingsManagerTest, testReboot)
+{
+ ThingsMaintenance *g_thingsMnt = ThingsMaintenance::getInstance();
+
+ mocks.ExpectCallFunc(onReboot).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ vector<string> types;
+ types.push_back("oic.wk.mnt");
+ result = groupMgr->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv2.wait(lock);
+
+ if (result == OC_STACK_OK)
+ {
+ result = g_thingsMnt->reboot(configurationResource, &onReboot);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Reboot on NULL Resource
+TEST_F(ThingsManagerTest, testRebootResourceNull)
+{
+ ThingsMaintenance *g_thingsMnt = ThingsMaintenance::getInstance();
+
+ result = g_thingsMnt->reboot(NULL, &onReboot);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
+//Factory Reset
+TEST_F(ThingsManagerTest, testFactoryReset)
+{
+ ThingsMaintenance *g_thingsMnt = ThingsMaintenance::getInstance();
+
+ mocks.ExpectCallFunc(onFactoryReset).
+ Do([this](const HeaderOptions & headerOptions, const OCRepresentation & rep, const int eCode) { Proceed(); });
+
+ vector<string> types;
+ types.push_back("oic.wk.mnt");
+ result = groupMgr->findCandidateResources(types, &foundResources);
+
+ std::mutex blocker;
+ std::unique_lock < std::mutex > lock(blocker);
+ cv2.wait(lock);
+
+ if (result == OC_STACK_OK)
+ {
+ result = g_thingsMnt->factoryReset(configurationResource, &onFactoryReset);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_OK);
+ result = 0;
+ }
+}
+
+//Factory Reset on NULL Resource
+TEST_F(ThingsManagerTest, testFactoryResetResourceNull)
+{
+ ThingsMaintenance *g_thingsMnt = ThingsMaintenance::getInstance();
+
+ result = g_thingsMnt->factoryReset(NULL, &onFactoryReset);
+ Wait();
+ EXPECT_TRUE(result == OC_STACK_ERROR);
+ result = 0;
+}
+
--- /dev/null
+//******************************************************************
+//
+// Copyright 2015 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 COMMON_UTILS_UNITTESTHELPER_H
+#define COMMON_UTILS_UNITTESTHELPER_H
+
+#include <gtest/gtest.h>
+#include <HippoMocks/hippomocks.h>
+
+class TestWithMock: public testing::Test
+{
+ public:
+ MockRepository mocks;
+
+ protected:
+ virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
+
+ virtual void TearDown()
+ {
+ try
+ {
+ mocks.VerifyAll();
+ }
+ catch (...)
+ {
+ mocks.reset();
+ throw;
+ }
+ }
+};
+
+#endif // COMMON_UTILS_UNITTESTHELPER_H
cp out/tizen/*/%{build_mode}/resource/examples/simpleserver %{buildroot}%{_bindir}
cp out/tizen/*/%{build_mode}/resource/examples/simpleserverHQ %{buildroot}%{_bindir}
cp out/tizen/*/%{build_mode}/resource/examples/threadingsample %{buildroot}%{_bindir}
-
+if echo %{secure_mode}|grep -qi '1'; then
+ cp out/tizen/*/%{build_mode}/libocpmapi.a %{buildroot}%{_libdir}
+fi
+cp out/tizen/*/%{build_mode}/libcoap.a %{buildroot}%{_libdir}
cp out/tizen/*/%{build_mode}/lib*.so %{buildroot}%{_libdir}
cp resource/csdk/stack/include/*.h %{buildroot}%{_includedir}
%{_libdir}/liboc_logger_core.so
%{_libdir}/liboctbstack.so
%{_libdir}/libconnectivity_abstraction.so
+%{_libdir}/lib*.a
%files service
%manifest %{name}.manifest
%defattr(-,root,root,-)
%{_libdir}/libBMISensorBundle.so
%{_libdir}/libDISensorBundle.so
-%{_libdir}/libNotificationManager.so
+%{_libdir}/libresource_hosting.so
%{_libdir}/libTGMSDKLibrary.so
%{_libdir}/libHueBundle.so
%{_libdir}/librcs_client.so