Added jot plugins features

revert-dabc3590
ayyoob 9 years ago
parent 8656f84ac6
commit 71d2897f20

@ -0,0 +1,56 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.iot.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.core.service.GroupManagementProviderService;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
public static GroupManagementProviderService getGroupManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
GroupManagementProviderService groupManagementProviderService =
(GroupManagementProviderService) ctx.getOSGiService(GroupManagementProviderService.class, null);
if (groupManagementProviderService == null) {
String msg = "Group Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return groupManagementProviderService;
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
(DeviceManagementProviderService) ctx.getOSGiService(DeviceManagementProviderService.class, null);
if (deviceManagementProviderService == null) {
String msg = "Device Management service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceManagementProviderService;
}
}

@ -1,54 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.device.mgt.iot.internal;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.databridge.core.DataBridgeReceiverService;
public class IoTCommonDataHolder {
private static IoTCommonDataHolder thisInstance = new IoTCommonDataHolder();
String trustStoreLocaiton;
String trustStorePassword;
private IoTCommonDataHolder() {
}
public void initialize(){
setTrustStore();
}
public static IoTCommonDataHolder getInstance() {
return thisInstance;
}
private void setTrustStore(){
this.trustStoreLocaiton = ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Location");
this.trustStorePassword = ServerConfiguration.getInstance().getFirstProperty("Security.TrustStore.Password");
}
public String getTrustStoreLocation(){
return trustStoreLocaiton;
}
public String getTrustStorePassword(){
return trustStorePassword;
}
}

@ -54,7 +54,6 @@ public class IotDeviceManagementServiceComponent {
/* Initialize the data source configuration */
DeviceManagementConfigurationManager.getInstance().initConfig();
bundleContext.registerService(ServerStartupObserver.class.getName(), new IoTServerStartupListener(), null);
IoTCommonDataHolder.getInstance().initialize();
if (log.isDebugEnabled()) {
log.debug("Iot Device Management Service Component has been successfully activated");
}

@ -0,0 +1,232 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>androidsense-plugin-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Android Sense Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the Android Sense Device type specific implementations for the IoT Server
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.plugin</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.manager.api</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.controller.api</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.analytics
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.manager.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>android_sense_mgt.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.controller.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>android_sense.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Android Sense Plugin Management schema -->
<id>create-android-sense-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create Android Sense plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/AndroidSenseDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.androidsense</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.androidsense.plugin:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,120 @@
{
"deviceType": {
"label": "Android Sense",
"category": "iot"
},
"analyticStreams": [
{
"name": "Accelerometer",
"table": "DEVICE_ACCELEROMETER_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"ACCELEROMETER", "label":"Accelerometer", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Battery",
"table": "DEVICE_BATTERY_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"BATTERY", "label":"Battery Level", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "GPS",
"table": "DEVICE_GPS_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.google-map",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"time"}},
{"column": {"name":"LATITUDE", "label":"Latitude", "ui-mapping":"lat"}},
{"column": {"name":"LONGITUDE", "label":"Longitude", "ui-mapping":"lat"}}
]
}
},
{
"name": "Gravity",
"table": "DEVICE_GRAVITY_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"GRAVITY", "label":"Gravity", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Gyroscope",
"table": "DEVICE_GYROSCOPE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"GYROSCOPE", "label":"Gyroscope", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Light",
"table": "DEVICE_LIGHT_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"LIGHT", "label":"Light", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Magnetic",
"table": "DEVICE_MAGNETIC_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"MAGNETIC", "label":"Magnetic", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Pressure",
"table": "DEVICE_PRESSURE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"PRESSURE", "label":"Pressure", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Proximity",
"table": "DEVICE_PROXIMITY_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.bar-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"PROXIMITY", "label":"Proximity", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Rotation",
"table": "DEVICE_ROTATION_SUMMARY",
"ui_unit": "cdmf.unit.analytics.line-chart",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"ROTATION", "label":"Rotation", "ui-mapping":"y-axis"}}
]
}
}
]
}

@ -0,0 +1,46 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>AndroidSenseDM_DB</name>
<description>The datasource used for the Android Sense database</description>
<jndiConfig>
<name>jdbc/AndroidSenseDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/AndroidSenseDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table `ANDROID_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ANDROID_SENSE_DEVICE` (
`ANDROID_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`ANDROID_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table `ANDROID_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ANDROID_SENSE_DEVICE` (
`ANDROID_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`ANDROID_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,17 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/android_sense,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/android_sense/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/android_sense/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.androidsense_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-plugins-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>androidsense-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Android Sense Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.androidsense.feature</module>
</modules>
</project>

@ -0,0 +1,237 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>arduino-plugin-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Arduino Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the Arduino Device type specific implementations for the IoT Server
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.plugin.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.analytics
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>arduino_mgt.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>arduino.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Arduino Plugin Management schema -->
<id>create-arduino-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create Arduino plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/ArduinoDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.arduino</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.arduino.plugin.impl:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,69 @@
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 ArduinoWifiAgent_H
#define ArduinoWifiAgent_H
#include "Arduino.h"
// These are the interrupt and control pins
#define ADAFRUIT_CC3000_IRQ 3 // MUST be an interrupt pin!
// These can be any two pins
#define ADAFRUIT_CC3000_VBAT 5
#define ADAFRUIT_CC3000_CS 10
#define WLAN_SSID "ssid" // Your wifi network SSID (cannot be longer than 32 characters!)
#define WLAN_PASS "password" // Your wifi network password
#define WLAN_SECURITY WLAN_SEC_WPA2
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define IDLE_TIMEOUT_MS 3000
#define DEVICE_OWNER "${DEVICE_OWNER}"
#define DEVICE_ID "${DEVICE_ID}"
#define DEVICE_TOKEN "${DEVICE_TOKEN}"
#define REFRESH_DEVICE_TOKEN "${DEVICE_REFRESH_TOKEN}"
#define SERVICE_EPOINT "/arduino/controller/"
#define POLL_INTERVAL 1000
#define PUSH_INTERVAL 10000
#define DEBUG true
#define CON_DEBUG true
#define SERVICE_PORT 9763 //http port of iot server
byte server[4] = {192,168,43,168}; //Ip address of iot server
byte deviceIP[4] = { 192, 168, 43,11 }; //Ststic ip address of arduino
byte dns2[] = { 8, 8, 8, 8 }; //Ststic dns of arduino
byte subnet[] = { 255, 255, 255, 0 }; //Ststic subnet of arduino
byte gateway[] = { 192, 168, 43, 1 }; //Ststic gateway of arduino
String host, jsonPayLoad, replyMsg;
String responseMsg, subStrn;
double cpuTemperature =0;
static unsigned long pushTimestamp = 0;
static unsigned long pollTimestamp = 0;
#endif

@ -0,0 +1,83 @@
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 "ArduinoBoardSketch.h"
#include <Adafruit_CC3000.h>
#include <SPI.h>
#include <avr/wdt.h>
Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
SPI_CLOCK_DIVIDER); // you can change this clock speed
Adafruit_CC3000_Client client;
uint32_t sserver;
void setup()
{
Serial.begin(115200);
Serial.println(F("Internal Temperature Sensor"));
pinMode(6, OUTPUT);
pinMode(13, OUTPUT);
connectHttp();
setupResource();
wdt_enable(WDTO_8S);
}
void loop()
{
wdt_reset();
while( !cc3000.checkConnected() ){
connectHttp();
}
cpuTemperature=getBoardTemp();
if(millis() - pushTimestamp > PUSH_INTERVAL){
while (!client.connected()) {
setupClient();
}
pushData();
pushTimestamp = millis();
}
//Serial.println("PUSHED");
wdt_reset();
if(millis() - pollTimestamp > POLL_INTERVAL){
while (!client.connected()) {
setupClient();
}
Serial.println("Read Controls");
readControls();
pollTimestamp = millis();
}
// //Serial.println("LOOPING");
wdt_reset();
}

@ -0,0 +1,158 @@
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 "ArduinoBoardSketch.h"
/**********************************************************************************************
Use the below variables when required to set a static IP for the WifiSheild
***********************************************************************************************/
uint32_t ip, ddns, ssubnet, ggateway;
String connecting = "connecting.... ";
void connectHttp() {
/* Initialise the module */
if(DEBUG) Serial.println(F("\nInitializing..."));
if (!cc3000.begin())
{
if(DEBUG) Serial.println(F("Couldn't begin()! Check your wiring?"));
while(1);
}
/**********************************************************************************************
Only required if using static IP for the WifiSheild
***********************************************************************************************/
ip = cc3000.IP2U32(deviceIP[0], deviceIP[1], deviceIP[2], deviceIP[3]);
ddns = cc3000.IP2U32(dns2[0], dns2[1], dns2[2], dns2[3]);
ssubnet = cc3000.IP2U32(subnet[0], subnet[1], subnet[2], subnet[3]);
ggateway = cc3000.IP2U32(gateway[0], gateway[1], gateway[2], gateway[3]);
cc3000.setStaticIPAddress(ip, ssubnet, ggateway, ddns); // required for setting static IP
/***********************************************************************************************/
sserver = cc3000.IP2U32(server[0], server[1], server[2], server[3]);
if(CON_DEBUG) {
Serial.print(F("\nAttempting to connect to "));
Serial.println(WLAN_SSID);
}
cc3000.deleteProfiles();
if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
if(CON_DEBUG) Serial.println(F("Failed!"));
while(1);
}
if(CON_DEBUG) Serial.println(F("Connected to Wifi network!"));
if(CON_DEBUG) Serial.println(F("Request DHCP"));
while (!cc3000.checkDHCP())
{
delay(100);
}
/* Display the IP address DNS, Gateway, etc. */
while (! displayConnectionDetails()) {
delay(1000);
}
if (cc3000.checkConnected()) {
Serial.println("client Connected to AP");
client = cc3000.connectTCP(sserver, SERVICE_PORT);
if (client.connected()) {
if(CON_DEBUG) Serial.println("client Connected to server");
} else {
if(CON_DEBUG) Serial.println(F("client Connection failed"));
}
} else {
Serial.println(F("client Connection to AP failed"));
}
if(CON_DEBUG) Serial.println(F("-------------------------------------"));
}
void setupResource(){
String hostIP = getHostIP(server);
String port = String(SERVICE_PORT);
host = "Host: " + hostIP + ":" + port;
if(DEBUG) Serial.println(host);
jsonPayLoad = "{\"owner\":\"";
jsonPayLoad += String(DEVICE_OWNER);
jsonPayLoad += "\",\"deviceId\":\"";
jsonPayLoad += String(DEVICE_ID);
jsonPayLoad += "\",\"reply\":\"";
if(DEBUG) {
Serial.print("JSON Payload: ");
Serial.println(jsonPayLoad);
Serial.println("-------------------------------");
}
}
String getHostIP(byte server[4]){
String hostIP = String(server[0]);
for ( int index = 1; index < 4; index++) {
hostIP += "." + String(server[index]);
}
return hostIP;
}
bool displayConnectionDetails(void)
{
uint32_t ipAddress, netmask, gateway, dhcpserv, dnsserv;
if(!cc3000.getIPAddress(&ipAddress, &netmask, &gateway, &dhcpserv, &dnsserv))
{
if(DEBUG) Serial.println(F("Unable to retrieve the IP Address!\r\n"));
return false;
}
else
{
if(CON_DEBUG) {
Serial.print(F("\nIP Addr: ")); cc3000.printIPdotsRev(ipAddress);
Serial.print(F("\nNetmask: ")); cc3000.printIPdotsRev(netmask);
Serial.print(F("\nGateway: ")); cc3000.printIPdotsRev(gateway);
Serial.print(F("\nDHCPsrv: ")); cc3000.printIPdotsRev(dhcpserv);
Serial.print(F("\nDNSserv: ")); cc3000.printIPdotsRev(dnsserv);
Serial.println();
}
return true;
}
}
void setupClient(){
client = cc3000.connectTCP(sserver, SERVICE_PORT); //SERVICE_PORT
if (client.connected()) {
if(CON_DEBUG) Serial.println("client Connected to server");
} else {
while( !cc3000.checkConnected() ){
connectHttp();
}
if(CON_DEBUG) Serial.println(F("client Connection failed"));
}
}

@ -0,0 +1,76 @@
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 "ArduinoBoardSketch.h"
void readControls() {
// String responseMsg;
Serial.println("Started..");
client.fastrprint(F("GET "));
client.fastrprint(SERVICE_EPOINT);
client.fastrprint(F("readcontrols"));
client.fastrprint(F(" HTTP/1.1"));
client.fastrprint(F("\n"));
client.fastrprint(host.c_str());
client.fastrprint(F("\n"));
client.fastrprint(DEVICE_ID);
client.fastrprint(F("owner: "));
client.fastrprint(DEVICE_OWNER);
client.fastrprint(F("\n"));
client.fastrprint(F("deviceId: "));
client.fastrprint(F(DEVICE_ID));
client.fastrprint(F("\n"));
client.fastrprint(F("deviceId: "));
client.fastrprint(F("protocol: HTTP\n"));
client.println();
delay(1000);
Serial.println("Ended..");
while (client.available()) {
char response = client.read();
responseMsg += response;
}
int index = responseMsg.lastIndexOf(":");
int newLine = responseMsg.lastIndexOf("\n");
subStrn = responseMsg.substring(index + 1);
responseMsg = responseMsg.substring(newLine + 1, index);
if(DEBUG) {
Serial.print(responseMsg);
Serial.println();
Serial.println("-------------------------------");
}
if (subStrn.equals("ON")) {
Serial.println("ITS ON");
digitalWrite(13, HIGH);
digitalWrite(6, HIGH);
} else if (subStrn.equals("OFF")){
Serial.println("ITS OFF");
digitalWrite(13, LOW);
digitalWrite(6, LOW);
}
}

@ -0,0 +1,138 @@
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 "ArduinoBoardSketch.h"
/**********************************************************************************************
This method will traverse the array of digital pins and batch the data from the those pins together.
It makes a single call to the server and sends all pin values as a batch.
Server dis-assembles it accordingly and makes multiple publish calls for each sensor type.
***********************************************************************************************/
void pushData(){
String payLoad = "Temp";
payLoad = payLoad + "\",\"value\":\"";
payLoad+=cpuTemperature;
payLoad += "\"}";
client.fastrprint(F("POST "));
client.fastrprint(SERVICE_EPOINT); client.fastrprint(F("pushdata"));
client.fastrprint(F(" HTTP/1.1")); client.fastrprint(F("\n"));
client.fastrprint(host.c_str()); client.fastrprint(F("\n"));
client.fastrprint(F("Content-Type: application/json")); client.fastrprint(F("\n"));
client.fastrprint(F("Content-Length: "));
int payLength = jsonPayLoad.length() + payLoad.length();
client.fastrprint(String(payLength).c_str()); client.fastrprint(F("\n"));
client.fastrprint(F("\n"));
if(DEBUG) {
Serial.print("POST ");
Serial.print(SERVICE_EPOINT);
Serial.print("pushdata");
Serial.print(" HTTP/1.1"); Serial.println();
Serial.print(host); Serial.println();
Serial.print("Content-Type: application/json"); Serial.println();
Serial.print("Content-Length: ");
Serial.print(payLength); Serial.println();
Serial.println();
}
int chunkSize = 50;
for (int i = 0; i < jsonPayLoad.length(); i++) {
if ( (i+1)*chunkSize > jsonPayLoad.length()) {
client.print(jsonPayLoad.substring(i*chunkSize, jsonPayLoad.length()));
if(DEBUG) Serial.print(jsonPayLoad.substring(i*chunkSize, jsonPayLoad.length()));
i = jsonPayLoad.length();
} else {
client.print(jsonPayLoad.substring(i*chunkSize, (i+1)*chunkSize));
if(DEBUG) Serial.print(jsonPayLoad.substring(i*chunkSize, (i+1)*chunkSize));
}
}
for (int i = 0; i < payLoad.length(); i++) {
if ( (i+1)*chunkSize > payLoad.length()) {
client.print(payLoad.substring(i*chunkSize, payLoad.length()));
if(DEBUG) Serial.print(payLoad.substring(i*chunkSize, payLoad.length()));
i = payLoad.length();
} else {
client.print(payLoad.substring(i*chunkSize, (i+1)*chunkSize));
if(DEBUG) Serial.print(payLoad.substring(i*chunkSize, (i+1)*chunkSize));
}
}
client.fastrprint(F("\n"));
if(DEBUG) Serial.println();
delay(1000);
while (client.available()) {
char response = client.read();
if(DEBUG) Serial.print(response);
}
if(DEBUG) {
Serial.println();
Serial.println("-------------------------------");
}
payLoad = "";
}
double getBoardTemp(void)
{
unsigned int wADC;
double t;
// The internal temperature has to be used
// with the internal reference of 1.1V.
// Channel 8 can not be selected with
// the analogRead function yet.
// Set the internal reference and mux.
ADMUX = (_BV(REFS1) | _BV(REFS0) | _BV(MUX3));
ADCSRA |= _BV(ADEN); // enable the ADC
delay(20); // wait for voltages to become stable.
ADCSRA |= _BV(ADSC); // Start the ADC
// Detect end-of-conversion
while (bit_is_set(ADCSRA,ADSC));
// Reading register "ADCW" takes care of how to read ADCL and ADCH.
wADC = ADCW;
// The offset of 324.31 could be wrong. It is just an indication.
t = (wADC - 324.31 ) / 1.22;
// The returned temperature is in degrees Celcius.
return (t);
}

@ -0,0 +1,20 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# WSO2 Inc. licenses this file to you 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.
#
templates=ArduinoBoardSketch.h
zipfilename=ArduinoBoardSketch.zip

@ -0,0 +1,20 @@
{
"deviceType": {
"label": "Arduino",
"category": "iot",
"downloadAgentUri": "manager/device/arduino/download",
},
"analyticStreams": [
{
"name": "Temperature",
"table": "DEVICE_TEMPERATURE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"TEMPERATURE", "label":"temperature", "ui-mapping":"y-axis"}}
]
}
}
]
}

@ -0,0 +1,48 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>Arduino_DB</name>
<description>The datasource used for the Arduino database</description>
<jndiConfig>
<name>jdbc/ArduinoDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/ArduinoDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table for `ARDUINO_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ARDUINO_DEVICE` (
`ARDUINO_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`ARDUINO_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table for `ARDUINO_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `ARDUINO_DEVICE` (
`ARDUINO_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`ARDUINO_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,14 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/arduino/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/arduino/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/arduino,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.arduino_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-plugins-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>arduino-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Arduino Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.arduino.feature</module>
</modules>
</project>

@ -0,0 +1,228 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>digital-display-plugin-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server DigitalDisplay Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the DigitalDisplay Device type specific implementations for the IoT Server
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>digital_display_mgt.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>digital_display.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Digital Display Plugin Management schema -->
<id>create-digital-display-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create Digital Display plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/DigitalDisplayDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.digitaldisplay</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,29 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
#
#
#[Device-Configurations]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/digital_display/controller
mqtt-ep=${MQTT_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,16 @@
#!/bin/bash
# installing dependencies
echo ===Installing Dependencies
sudo apt-get install python-pip
sudo pip install paho-mqtt
sudo apt-get install python-lxml
sudo apt-get install gtk2
sudo apt-get install xdotool
# unzipping the archive
echo ===Unzipping DigitalDisplay.zip
unzip DigitalDisplay
# copying the property file
echo ===Moving deviceConfig.properties
cp ./deviceConfig.properties ./DigitalDisplay

@ -0,0 +1,12 @@
#!/bin/bash
ps aux|grep wso2server.py|awk '{print $2}'|xargs kill -9
ps aux|grep httpserver.py|awk '{print $2}'|xargs kill -9
#xdotool mousemove 0 0
#xdotool search -name LXTerminal windowunmap
#cd ~/
cd ./DigitalDisplay/
mkdir -p tmp/dd-kernel-test
python displayagent.py
while true; do
sleep 100
done

@ -0,0 +1,46 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>DigitalDisplayDM_DB</name>
<description>The datasource used for the Digital Display database</description>
<jndiConfig>
<name>jdbc/DigitalDisplayDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/DigitalDisplayDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table `DIGITAL_DISPLAY_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DIGITAL_DISPLAY_DEVICE` (
`DIGITAL_DISPLAY_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`DIGITAL_DISPLAY_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table `DIGITAL_DISPLAY_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DIGITAL_DISPLAY_DEVICE` (
`DIGITAL_DISPLAY_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`DIGITAL_DISPLAY_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,14 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/digital_display/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/digital_display/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/digital_display,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.digitaldisplay_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\

@ -0,0 +1,23 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-plugins-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>digital-display-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server DigitalDisplay Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.digitaldisplay.feature</module>
</modules>
</project>

@ -0,0 +1,224 @@
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>drone-analyzer-plugin-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Drone Analyzer Feature</name>
<url>http://maven.apache.org</url>
<description>This feature contains the Drone Device type specific implementations for the IoT Server
</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>drone_analyzer.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>drone_analyzer_mgt.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Drone Analyser Plugin Management schema -->
<id>create-drone-analyzer-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create Drone Analyser plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/DroneAnalyzerDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.droneanalyzer</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,33 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
#
#
[Device-Configurations]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/drone_analyzer/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,73 @@
#!/usr/bin/env python
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.
**/
"""
#This script can be used to observe drone attribute (state) changes and push those status changes to xmpp server.
import argparse
import time
from dronekit import connect, VehicleMode
import xmppClient
CONNECTION_TARGET = "/dev/ttyACM0"
PUSH_INTERVAL = 1
BAUD = 57600
parser = argparse.ArgumentParser(description='Connects to drone on ')
parser.add_argument("-c", "--connect", default='/dev/ttyACM0',help="vehicle connection target. Default '/dev/ttyACM0'")
parser.add_argument("-b", '--baud', type=int ,default=57600,help="Serial communication speed. Default 57600")
parser.add_argument("-i", "--push_interval", type=int, default=1,help="This is the interval which is used to push drone"
" status to xmpp server")
args = parser.parse_args()
if args.connect:
CONNECTION_TARGET = args.connect
if args.push_interval:
PUSH_INTERVAL = args.push_interval
if args.baud:
BAUD = args.baud
isConnected = xmppClient.connectToXMPPServer()
if isConnected:
print "\nConnecting to vehicle on: %s" % CONNECTION_TARGET
print "----------------------------------------------------------------------"
vehicle = connect(CONNECTION_TARGET, wait_ready=True, baud=BAUD)
while (True):
print " Attitude: %s" % vehicle.attitude.yaw
current_state = "{\"quatanium_val\":["+str(vehicle.attitude.yaw)+","+str(vehicle.attitude.pitch)+ \
", "+str(vehicle.attitude.roll)+"],\"basicParam\":{\"velocity\":["+str(vehicle.velocity[0])+"," \
+str(vehicle.velocity[1])+","+str(vehicle.velocity[2])+"],\"global_location\":["+ \
str(vehicle.location.global_relative_frame.alt)+","+str(vehicle.location.global_relative_frame.lat)+ \
","+str(vehicle.location.global_relative_frame.lon)+"]},\"battery_level\":"+ \
str(vehicle.battery.level)+",\"battery_voltage\":"+str(vehicle.battery.voltage)+ \
",\"device_type\":\"IRIS_DRONE\"}";
#current_state = "{\"quatanium_val\":[0.345, 0.567, 0.456, 0.6345],\"basicParam\":{\"velocity\":[3, 2, 1], " \
#"\"global_location\":[0.567, 2.345, 0.456]},\"battery_level\":56,\"battery_voltage\":34,\"device_type\":\"SIMULATOR\"}";
xmppClient.sendMessage(current_state)
time.sleep(PUSH_INTERVAL)
print "-------------------------------------------------------------------------------------------------"
print "\nClose vehicle object"
vehicle.close()
print("Completed")

@ -0,0 +1,40 @@
#!/usr/bin/env python
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 ConfigParser, os
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Device specific info when pushing data to server
# Read from a file "deviceConfig.properties" in the same folder level
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
configParser = ConfigParser.RawConfigParser()
configFilePath = r'./deviceConfig.properties'
configParser.read(configFilePath)
DEVICE_OWNER = configParser.get('Device-Configurations', 'owner')
DEVICE_ID = configParser.get('Device-Configurations', 'deviceId')
XMPP_EP = configParser.get('Device-Configurations', 'xmpp-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
DEVICE_PASSWORD = configParser.get('Device-Configurations', 'auth-token')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
HTTP_EP = configParser.get('Device-Configurations', 'http-ep')
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

@ -0,0 +1,66 @@
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 xmpp
import util
XMPP_ENDPOINT = util.XMPP_EP.split(":")
XMPP_IP = XMPP_ENDPOINT[1].replace('//', '')
XMPP_PORT = int(XMPP_ENDPOINT[2])
MESSAGE_TO = util.DEVICE_OWNER
XMPP_PWD = util.DEVICE_PASSWORD
XMPP_OWN = util.DEVICE_ID
XMPP_RESOURCE = "drone_current_status"
XMPP_JID = MESSAGE_TO + "@" + XMPP_IP + "/" + XMPP_RESOURCE
global droneClient
droneClient = xmpp.Client(XMPP_IP, debug=[])
def loginToXMPPServer():
auth = droneClient.auth(XMPP_OWN, XMPP_PWD, resource=XMPP_RESOURCE)
if not auth:
print 'could not authenticate!'
return 0
print 'authenticated using', auth
droneClient.sendInitPresence()
return 1
def connectToXMPPServer():
connection = droneClient.connect(server=(XMPP_IP, XMPP_PORT))
if not connection:
print 'could not connect to xmpp server at ' + str(XMPP_IP)
return 0
print 'connected with', connection
response = loginToXMPPServer()
if response:
return 1
else:
return 0
def sendMessage(message):
xmpp_message = xmpp.Message(XMPP_JID, message)
xmpp_message.setAttr('type', 'chat')
droneClient.send(xmpp_message)
print message

@ -0,0 +1,83 @@
#/**
#* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#*
#* WSO2 Inc. licenses this file to you 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.
#**/
#!/bin/bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Sample "
echo "| Drone Analyzer "
echo "| ---------------- "
echo "| ....initializing startup-script "
echo "----------------------------------------------------------------"
currentDir=$PWD
while true; do
read -p "Do you wish to run 'apt-get update' and continue? [Yes/No] " yn
case $yn in
[Yy]* ) sudo apt-get update;
break;;
[Nn]* ) echo "Continuing without apt-get update...";
break;;
* ) echo "Please answer yes or no.";
esac
done
for f in ./deviceConfig.properties; do
if [ -e "$f" ]; then
echo "Configuration file found......"
else
echo "'deviceConfig.properties' file does not exist in current path. \nExiting installation...";
exit;
fi
break
done
#installing dependencies
sudo apt-get install python-pip python-dev
sudo pip install dronekit
sudo apt-get install python-xmpp
while true; do
read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the XMPP server (ex: '60' indicates 1 minute) > " push_interval
read -p "Vehicle connection target. Default '/dev/ttyACM0' :" connection_target
read -p "Serial communication speed. Default 57600 :" baud
if [ $input -eq $input 2>/dev/null ]
then
echo "Setting data-push interval to $push_interval seconds."
break
else
echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
fi
done
cp deviceConfig.properties ./src
python ./src/IRIS+DroneStatistics.py -i $push_interval -b $baud -c $connection_target
if [ $? -ne 0 ]; then
echo "Could not start the service..."
exit;
fi
echo "--------------------------------------------------------------------------"
echo "| Successfully Started "
echo "---------------------------------------------------------------------------"

@ -0,0 +1,50 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>DroneAnalyzerDM_DB</name>
<description>The datasource used for the Drone Analyzer database</description>
<jndiConfig>
<name>jdbc/DroneAnalyzerDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/DroneAnalyzerDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table `DRONE_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DRONE_DEVICE` (
`DRONE_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`DRONE_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table `DRONE_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `DRONE_DEVICE` (
`DRONE_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`DRONE_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,14 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/drone_analyzer/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/drone_analyzer/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/drone_analyzer,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.droneanalyzer_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\

@ -0,0 +1,40 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-plugins-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>drone-analyzer-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server Drone Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.feature</module>
</modules>
</project>

@ -34,6 +34,12 @@
<url>http://wso2.org</url>
<modules>
<module>androidsense-plugin-feature</module>
<module>arduino-plugin-feature</module>
<module>digital-display-plugin-feature</module>
<module>drone-analyzer-plugin-feature</module>
<module>raspberrypi-plugin-feature</module>
<module>virtual-fire-alarm-plugin-feature</module>
<module>iot-base-plugin-feature</module>
</modules>

@ -0,0 +1,235 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>raspberrypi-plugin-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the RaspberryPi Device type specific implementations for the IoT Server
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.analytics
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>raspberrypi.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>raspberrypi_mgt.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating RaspberryPi Plugin Management schema -->
<id>create-raspberrypi-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create RaspberryPi plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/RaspberryPiDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.raspberrypi</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,43 @@
## Copyright and license
Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
WSO2 Inc. licenses this file to you 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.
--------------
testAgent.sh
--------------
This script is used to run this service in a testing environment. It can be run on a real Raspberry Pi device or in a
virtual environment.
To run: ` sudo ./testAgent.sh ` and follow the instructions.
-------------------
startService.sh
-------------------
After testing, this script can be used to deploy this application as a service on Raspberry Pi which will get loaded
during boot up process.
create a service:
` sudo ./startService.sh `
get current state of the service:
` sudo service RaspberryService.sh status `
start service:
` sudo service RaspberryService.sh start `
stop service:
` sudo service RaspberryService.sh stop `
restart service:
` sudo service RaspberryService.sh restart `

@ -0,0 +1,96 @@
#"""
#/**
#* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#*
#* WSO2 Inc. licenses this file to you 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.
#**/
#"""
#!/bin/sh
### BEGIN INIT INFO
# Provides: RaspberryService
# Required-Start: $remote_fs $syslog $network
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: WSO2-IOT RPi Service
# Description: RPi Service used to Publish RPi Stats to the WSO2 Device Cloud
### END INIT INFO
PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/sbin:/usr/local/bin
DESC="This service is used to publish events from the Raspberry Pi to the WSO2 Device Cloud"
NAME=RaspberryStats
DIR=/usr/local/src/RaspberryAgent/src/
DAEMON=$DIR/RaspberryAgent.py
DAEMON_NAME=$NAME
SCRIPTNAME=RaspberryService.sh
# The process ID of the script when it runs is stored here:
PIDFILE=/var/run/$DAEMON_NAME.pid
# Add any command line options for your daemon here
DAEMON_OPTS="-l /usr/local/src/RaspberryAgent/RaspberryStats.log -m N -i 60"
# This next line determines what user the script runs as.
DAEMON_USER=root #pi
# Load the VERBOSE setting and other rcS variables
. /lib/init/vars.sh
# Define LSB log_* functions.
# Depend on lsb-base (>= 3.2-14) to ensure that this file is present
# and status_of_proc is working.
. /lib/lsb/init-functions
do_start () {
log_daemon_msg "Starting system $DAEMON_NAME daemon"
start-stop-daemon --start --background --pidfile $PIDFILE --make-pidfile --user $DAEMON_USER --chuid $DAEMON_USER --startas $DAEMON -- $DAEMON_OPTS
log_end_msg $?
}
do_stop () {
log_daemon_msg "Stopping system $DAEMON_NAME daemon"
start-stop-daemon --stop --pidfile $PIDFILE --retry 10
log_end_msg $?
}
case "$1" in
start|stop)
do_${1}
;;
restart|reload|force-reload)
do_stop
do_start
;;
status)
status_of_proc "$DAEMON_NAME" "$DAEMON" && exit 0 || exit $?
;;
getdeviceid)
$DIR/getMac.sh && exit 0 || exit $?
;;
*)
#echo Usage: /etc/init.d/$DAEMON_NAME {start|stop|restart|status}"
echo "Usage: /etc/init.d/$SCRIPTNAME {start|stop|restart|status}"
exit 1
;;
esac
exit 0

@ -0,0 +1,33 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
#
#
[Device-Configurations]
server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/raspberrypi/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,323 @@
#!/usr/bin/env python
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 logging, logging.handlers
import sys, os, signal, argparse
import running_mode
import time, threading, datetime
import httplib, ssl
from functools import wraps
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Overriding the default SSL version used in some of the Python (2.7.x) versions
# This is a known issue in earlier Python releases
# But was fixed in later versions. Ex-2.7.11
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def sslwrap(func):
@wraps(func)
def bar(*args, **kw):
kw['ssl_version'] = ssl.PROTOCOL_TLSv1
return func(*args, **kw)
return bar
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PUSH_INTERVAL = 5000 # time interval between successive data pushes in seconds
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Logger defaults
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
LOG_FILENAME = "RaspberryStats.log"
logging_enabled = False
LOG_LEVEL = logging.INFO # Could be e.g. "DEBUG" or "WARNING"
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Python version
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if sys.version_info<(2,7,0):
sys.stderr.write("You need python 2.7.0 or later to run this script\n")
exit(1)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Define and parse command line arguments
# If the log file is specified on the command line then override the default
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
parser = argparse.ArgumentParser(description="Python service to push RPi info to the Device Cloud")
parser.add_argument("-l", "--log", help="file to write log to (default '" + LOG_FILENAME + "')")
help_string_for_data_push_interval = "time interval between successive data pushes (default '" + str(PUSH_INTERVAL) + "')"
help_string_for_running_mode = "where is going to run on the real device or not"
parser.add_argument("-i", "--interval", type=int, help=help_string_for_data_push_interval)
parser.add_argument("-m", "--mode", type=str, help=help_string_for_running_mode)
args = parser.parse_args()
if args.log:
LOG_FILENAME = args.log
if args.interval:
PUSH_INTERVAL = args.interval
if args.mode:
running_mode.RUNNING_MODE = args.mode
iotUtils = __import__('iotUtils')
httpServer = __import__('httpServer') # python script used to start a http-server to listen for operations
# (includes the TEMPERATURE global variable)
if running_mode.RUNNING_MODE == 'N':
Adafruit_DHT = __import__('Adafruit_DHT') # Adafruit library required for temperature sensing
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Endpoint specific settings to which the data is pushed
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DC_ENDPOINT = iotUtils.HTTPS_EP.split(":")
DC_IP = DC_ENDPOINT[1].replace('//', '')
DC_PORT = int(DC_ENDPOINT[2])
DC_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT
PUSH_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/push_temperature/'
REGISTER_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/register'
HOST = iotUtils.getDeviceIP()
HOST_HTTP_SERVER_PORT = iotUtils.getHTTPServerPort()
HOST_AND_PORT = str(HOST)+ ":" + str(HOST_HTTP_SERVER_PORT)
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# A class we can use to capture stdout and sterr in the log
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class IOTLogger(object):
def __init__(self, logger, level):
"""Needs a logger and a logger level."""
self.logger = logger
self.level = level
def write(self, message):
if message.rstrip() != "": # Only log if there is a message (not just a new line)
self.logger.log(self.level, message.rstrip())
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Configure logging to log to a file,
# making a new file at midnight and keeping the last 3 day's data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def configureLogger(loggerName):
logger = logging.getLogger(loggerName)
logger.setLevel(LOG_LEVEL) # Set the log level to LOG_LEVEL
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight",
backupCount=3) # Handler that writes to a file,
# ~~~make new file at midnight and keep 3 backups
formatter = logging.Formatter('%(asctime)s %(levelname)-8s %(message)s') # Format each log message like this
handler.setFormatter(formatter) # Attach the formatter to the handler
logger.addHandler(handler) # Attach the handler to the logger
if (logging_enabled):
sys.stdout = IOTLogger(logger, logging.INFO) # Replace stdout with logging to file at INFO level
sys.stderr = IOTLogger(logger, logging.ERROR) # Replace stderr with logging to file at ERROR level
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method registers the DevieIP in the Device-Cloud
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def registerDeviceIP():
ssl.wrap_socket = sslwrap(ssl.wrap_socket) # using the overridden sslwrap that uses TLSv1
if sys.version_info<(2,7,9):
dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
else:
dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
#TODO need to get server certificate when initializing https connection
dcConncection.set_debuglevel(1)
dcConncection.connect()
registerURL = str(REGISTER_ENDPOINT) + '/' + str(iotUtils.DEVICE_OWNER) + '/' + str(iotUtils.DEVICE_ID) + '/' + \
str(HOST) + '/' + str(HOST_HTTP_SERVER_PORT) + '/'
dcConncection.putrequest('POST', registerURL)
dcConncection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
dcConncection.endheaders()
dcResponse = dcConncection.getresponse()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('RASPBERRY_STATS: ' + str(registerURL))
print ('RASPBERRY_STATS: ' + str(dcResponse.status))
print ('RASPBERRY_STATS: ' + str(dcResponse.reason))
print ('RASPBERRY_STATS: Response Message')
print str(dcResponse.msg)
dcConncection.close()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method connects to the Device-Cloud and pushes data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def connectAndPushData():
if sys.version_info<(2,7,9):
dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
else:
dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
dcConnection.set_debuglevel(1)
dcConnection.connect()
request = dcConnection.putrequest('POST', PUSH_ENDPOINT)
dcConnection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
dcConnection.putheader('Content-Type', 'application/json')
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
### Read the Temperature and Load info of RPi and construct payload
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rPiTemperature = iotUtils.LAST_TEMP # Push the last read temperature value
PUSH_DATA = iotUtils.DEVICE_INFO + iotUtils.DEVICE_IP.format(ip=HOST_AND_PORT) + iotUtils.DEVICE_DATA.format(
temperature=rPiTemperature)
PUSH_DATA += '}'
dcConnection.putheader('Content-Length', len(PUSH_DATA))
dcConnection.endheaders()
print PUSH_DATA
print '~~~~~~~~~~~~~~~~~~~~~~~~ Pushing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~'
dcConnection.send(PUSH_DATA) # Push the data
dcResponse = dcConnection.getresponse()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('RASPBERRY_STATS: ' + str(dcResponse.status))
print ('RASPBERRY_STATS: ' + str(dcResponse.reason))
print ('RASPBERRY_STATS: Response Message')
print str(dcResponse.msg)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
dcConnection.close()
if (dcResponse.status == 409 or dcResponse.status == 412):
print 'RASPBERRY_STATS: Re-registering Device IP'
registerDeviceIP()
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is a Thread object for reading temperature continuously
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class TemperatureReaderThread(object):
def __init__(self):
if running_mode.RUNNING_MODE == 'N':
self.interval = iotUtils.TEMPERATURE_READING_INTERVAL_REAL_MODE
else:
self.interval = iotUtils.TEMPERATURE_READING_INTERVAL_VIRTUAL_MODE
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
# Try to grab a sensor reading. Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
while True:
try:
if running_mode.RUNNING_MODE == 'N':
humidity, temperature = Adafruit_DHT.read_retry(iotUtils.TEMP_SENSOR_TYPE, iotUtils.TEMP_PIN)
else:
humidity, temperature = iotUtils.generateRandomTemperatureAndHumidityValues()
if temperature != iotUtils.LAST_TEMP:
time.sleep(PUSH_INTERVAL)
iotUtils.LAST_TEMP = temperature
connectAndPushData()
iotUtils.LAST_TEMP = temperature
print 'RASPBERRY_STATS: Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)
except Exception, e:
print "RASPBERRY_STATS: Exception in TempReaderThread: Could not successfully read Temperature"
print ("RASPBERRY_STATS: " + str(e))
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass
time.sleep(self.interval)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is a Thread object for listening for MQTT Messages
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class UtilsThread(object):
def __init__(self):
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
iotUtils.main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is a Thread object for HTTP-Server that listens for operations on RPi
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class ListenHTTPServerThread(object):
def __init__(self):
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
httpServer.main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# When sysvinit sends the TERM signal, cleanup before exiting
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def sigterm_handler(_signo, _stack_frame):
print("[] received signal {}, exiting...".format(_signo))
sys.exit(0)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
signal.signal(signal.SIGTERM, sigterm_handler)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The Main method of the RPi Agent
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
configureLogger("WSO2IOT_RPiStats")
if running_mode.RUNNING_MODE == 'N':
iotUtils.setUpGPIOPins()
UtilsThread()
registerDeviceIP() # Call the register endpoint and register Device IP
TemperatureReaderThread() # initiates and runs the thread to continuously read temperature from DHT Sensor
ListenHTTPServerThread() # starts an HTTP Server that listens for operational commands to switch ON/OFF Led
while True:
try:
if iotUtils.LAST_TEMP > 0: # Push data only if there had been a successful temperature read
connectAndPushData() # Push Sensor (Temperature) data to WSO2 BAM
time.sleep(PUSH_INTERVAL)
except (KeyboardInterrupt, Exception) as e:
print "RASPBERRY_STATS: Exception in RaspberryAgentThread (either KeyboardInterrupt or Other)"
print ("RASPBERRY_STATS: " + str(e))
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == "__main__":
main()

@ -0,0 +1,33 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
#
#
[Device-Configurations]
server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/raspberrypi/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,118 @@
#!/usr/bin/env python
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 time
import BaseHTTPServer
import iotUtils
import running_mode
import os
import subprocess
import re
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Class that handles HTTP GET requests for operations on the RPi
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class OnRequestListener(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(request):
# """Respond to a GET request."""
if not processURLPath(request.path):
return
print request.path.split("/")[1].upper()
resource = request.path.split("/")[1].upper()
state = request.path.split("/")[2].upper()
print "HTTP_SERVER: Resource - " + resource
if resource == "TEMPERATURE":
request.send_response(200)
request.send_header('Content-Type', 'application/json')
request.send_header('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
request.end_headers()
request.wfile.write(iotUtils.LAST_TEMP)
elif resource == "BULB":
iotUtils.switchBulb(state)
print "HTTP_SERVER: Requested Switch State - " + state
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Check the URL string of the request and validate
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def processURLPath(path):
if path.count("/") != 2 and not "favicon" in path:
print "HTTP_SERVER: Invalid URL String: " + path
return False
resource = path.split("/")[1]
if not iequal("BULB", resource) and not iequal("TEMPERATURE", resource):
if not "favicon" in resource:
print "HTTP_SERVER: Invalid resource - " + resource + " to execute operation"
return False
return True
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Case-Insensitive check on whether two string are similar
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def iequal(a, b):
try:
return a.upper() == b.upper()
except AttributeError:
return a == b
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The Main method of the server script
# This method is invoked from RaspberryStats.py on a new thread
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
HOST_NAME = iotUtils.getDeviceIP()
HTTP_SERVER_PORT = iotUtils.getHTTPServerPort()
server_class = BaseHTTPServer.HTTPServer
while True:
try:
httpd = server_class((HOST_NAME, HTTP_SERVER_PORT), OnRequestListener)
print "HTTP_SERVER: " + time.asctime(), "Server Starts - %s:%s" % (HOST_NAME, HTTP_SERVER_PORT)
httpd.serve_forever()
except (KeyboardInterrupt, Exception) as e:
print "HTTP_SERVER: Exception in HttpServerThread (either KeyboardInterrupt or Other)"
print ("HTTP_SERVER: " + str(e))
if running_mode.RUNNING_MODE == "N":
iotUtils.switchBulb("OFF")
else :
iotUtils.switchBulb("OFF")
httpd.server_close()
print "HTTP_SERVER: " + time.asctime(), "Server Stops - %s:%s" % (HOST_NAME, HTTP_SERVER_PORT)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == '__main__':
main()

@ -0,0 +1,185 @@
#!/usr/bin/env python
"""
/**
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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 time
import ConfigParser, os
import random
import running_mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# HOST_NAME(IP) of the Device
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
global HOST_NAME
HOST_NAME = "0.0.0.0"
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HTTP_SERVER_PORT = 5678 # http server port which is listning on
global LAST_TEMP
LAST_TEMP = 25 # The Last read temperature value from the DHT sensor. Kept globally
# Updated by the temperature reading thread
# Associate pin 23 to TRIG
TEMPERATURE_READING_INTERVAL_REAL_MODE = 3
TEMPERATURE_READING_INTERVAL_VIRTUAL_MODE = 60
TEMP_PIN = 4
TEMP_SENSOR_TYPE = 11
BULB_PIN = 11 # The GPIO Pin# in RPi to which the LED is connected
global GPIO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Device specific info when pushing data to server
# Read from a file "deviceConfig.properties" in the same folder level
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), './deviceConfig.properties')
configParser.read(configFilePath)
DEVICE_OWNER = configParser.get('Device-Configurations', 'owner')
DEVICE_ID = configParser.get('Device-Configurations', 'deviceId')
MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
XMPP_EP = configParser.get('Device-Configurations', 'xmpp-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '","reply":'
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
HTTP_EP = configParser.get('Device-Configurations', 'http-ep')
APIM_EP = configParser.get('Device-Configurations', 'apim-ep')
DEVICE_IP = '"{ip}","value":'
DEVICE_DATA = '"{temperature}"' # '"{temperature}:{load}:OFF"'
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Method used to switch ON/OFF the LED attached to RPi
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def switchBulb(state):
print "Requested Switch State: " + state
if running_mode.RUNNING_MODE == "N":
import RPi.GPIO as GPIO
if state == "ON":
GPIO.output(BULB_PIN, True)
print "BULB Switched ON"
elif state == "OFF":
GPIO.output(BULB_PIN, False)
print "BULB Switched OFF"
else:
if state == "ON":
print "BULB Switched ON"
elif state == "OFF":
print "BULB Switched OFF"
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method generate a random temperature value
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def generateRandomTemperatureAndHumidityValues():
return [random.randint(15, 40),random.randint(15, 40)]
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# If an agent runs on a real setup GPIO needs to be imported
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def initGPIOModule():
if running_mode.RUNNING_MODE == 'N':
import RPi.GPIO as GPIO
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Get the IP-Address of the interface via which the RPi is connected
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def getDeviceIP():
# for POSIX system like MacOS and Linux
if os.name != "nt":
import commands
rPi_IP = commands.getoutput("ifconfig | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}'").split('\n')
if len(rPi_IP) > 0:
print "------------------------------------------------------------------------------------"
print "IOT_UTILS: IP Addresses of RaspberryPi: " + str(rPi_IP)
print "IOT_UTILS: IP Address used for HTTP Server: " + rPi_IP[0]
print "------------------------------------------------------------------------------------"
if len(rPi_IP[0].split(":"))>1:
return rPi_IP[0].split(":")[1]
else:
return rPi_IP[0]
# for windows systems
else:
from subprocess import check_output
rPi_IP = check_output("for /f \"tokens=14\" %a in ('ipconfig ^| findstr \"IPv4\" ^| findstr /v \"127.0.0.1\"') do echo %a", shell=True).decode()
rPi_IP = rPi_IP.replace('\r', '')
rPi_IP = rPi_IP.split('\n')
for IPs in rPi_IP:
if IPs != '' and len(aps) < 16:
print("------------------------------------------------------------------------------------")
print("IOT_UTILS: IP Address used for HTTP Server: " + IPs)
print("------------------------------------------------------------------------------------")
return IPs
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Get the port which http server is listening on
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def getHTTPServerPort():
return HTTP_SERVER_PORT
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Set the GPIO pin modes for the ones to be read
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def setUpGPIOPins():
import RPi.GPIO as GPIO
try:
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
except Exception as e:
print "IOT_UTILS: Exception at 'GPIO.setmode'"
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass
GPIO.setup(BULB_PIN, GPIO.OUT)
GPIO.output(BULB_PIN, False)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The Main method of the server script
# This method is invoked from RaspberryStats.py on a new thread
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
global HOST_NAME
HOST_NAME = getDeviceIP()
if running_mode.RUNNING_MODE == 'N':
setUpGPIOPins()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if __name__ == '__main__':
main()

@ -0,0 +1,43 @@
#"""
#/**
#* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#*
#* WSO2 Inc. licenses this file to you 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.
#**/
#"""
#!/usr/bin/env bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Sample "
echo "| RaspiAgent "
echo "| ---------------- "
echo "| ....initializing service-start-script "
echo "----------------------------------------------------------------"
destination="/usr/local/src/RaspberryAgent"
currentDir=$PWD
if [ ! -d "$destination" ]
then
mkdir $destination
fi
sudo cp $currentDir/deviceConfig.properties $currentDir/src
sudo cp -r $currentDir/src $destination
sudo chmod +x $destination/src/RaspberryAgent.py
sudo update-rc.d -f RaspberryService.sh remove
sudo cp $currentDir/RaspberryService.sh /etc/init.d
sudo chmod +x /etc/init.d/RaspberryService.sh
sudo update-rc.d RaspberryService.sh defaults
sudo service RaspberryService.sh start

@ -0,0 +1,117 @@
#"""
#/**
#* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#*
#* WSO2 Inc. licenses this file to you 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.
#**/
#"""
#!/bin/bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Sample "
echo "| RaspiAgent "
echo "| ---------------- "
echo "| ....initializing startup-script "
echo "----------------------------------------------------------------"
currentDir=$PWD
while true; do
read -p "Do you wish to run 'apt-get update' and continue? [Yes/No] " yn
case $yn in
[Yy]* ) sudo apt-get update;
break;;
[Nn]* ) echo "Continuing without apt-get update...";
break;;
* ) echo "Please answer yes or no.";
esac
done
if [ $? -ne 0 ]; then
echo "apt-get update failed.... Some dependencies may not get installed"
echo "If an already installed version of the package exists, try running:"
echo "----------------------------------------------------------------"
echo "sudo -i"
echo "cd /var/lib/dpkg/info"
echo "rm -rf wso2-raspi-alarm*"
echo "dpkg --remove --force-remove-reinstreq wso2-raspi-agent"
echo "exit"
echo "----------------------------------------------------------------"
echo "Retry Installation...."
break;
fi
for f in ./deviceConfig.properties; do
## Check if the glob gets expanded to existing files.
## If not, f here will be exactly the pattern above
## and the exists test will evaluate to false.
if [ -e "$f" ]; then
echo "Configuration file found......"
else
echo "'deviceConfig.properties' file does not exist in current path. \nExiting installation...";
exit;
fi
## This is all we needed to know, so we can break after the first iteration
break
done
cd $currentDir
while true; do
read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute) > " input
read -p "Are you want to run this as a virtual agent? (Yes/No) " mode
if [ $input -eq $input 2>/dev/null ]
then
echo "Setting data-push interval to $input seconds."
else
echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
fi
case $mode in
[Yy]* ) mode="Y"
echo "----------------------------------------------------------"
echo " This will run as a virtual agent "
echo "----------------------------------------------------------"
break;;
[Nn]* ) mode="N"
echo "----------------------------------------------------------"
echo " This will run as a real agent "
echo "----------------------------------------------------------"
break;;
* ) echo "Please answer yes or no.";
esac
done
cp deviceConfig.properties ./src
if [ "$mode" = "N" ]; then
sudo apt-get install rpi.gpio
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
sudo apt-get install build-essential python-dev python-openssl
sudo python ./Adafruit_Python_DHT/setup.py install
fi
chmod +x ./src/RaspberryAgent.py
./src/RaspberryAgent.py -i $input -m $mode
if [ $? -ne 0 ]; then
echo "Could not start the service..."
exit;
fi
echo "--------------------------------------------------------------------------"
echo "| Successfully Started "
echo "| -------------------------- "

@ -0,0 +1,19 @@
{
"deviceType": {
"label": "RaspberryPi",
"category": "iot"
},
"analyticStreams": [
{
"name": "Temperature",
"table": "DEVICE_TEMPERATURE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"TEMPERATURE", "label":"Temperature", "ui-mapping":"y-axis"}}
]
}
}
]
}

@ -0,0 +1,48 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>RaspberryPi_DB</name>
<description>The datasource used for the RaspberryPi database</description>
<jndiConfig>
<name>jdbc/RaspberryPiDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/RaspberryPiDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table `RASPBERRYPI_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RASPBERRYPI_DEVICE` (
`RASPBERRYPI_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`RASPBERRYPI_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table `RASPBERRYPI_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `RASPBERRYPI_DEVICE` (
`RASPBERRYPI_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`RASPBERRYPI_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,14 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/raspberrypi/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/raspberrypi/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/raspberrypi,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.raspberrypi_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-plugins-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>raspberrypi-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.feature</module>
</modules>
</project>

@ -0,0 +1,264 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>virtual-fire-alarm-plugin-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server VirtualFireAlarm Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the VirtualFireAlarm Device type specific implementations for the IoT Server
</description>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.manager.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>unpack</id>
<phase>package</phase>
<goals>
<goal>unpack</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.analytics
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.ui
</artifactId>
<version>${project.version}</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.controller.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>virtual_firealarm.war</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.manager.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>virtual_firealarm_mgt.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-agent-jar</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl
</artifactId>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/agent/</outputDirectory>
<destFileName>wso2-firealarm-virtual-agent.jar</destFileName>
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.impl
</artifactId>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/advanced_agent/</outputDirectory>
<destFileName>wso2-firealarm-virtual-agent-advanced.jar</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Virtual Firealarm Plugin Management schema -->
<id>create-virtual-firealarm-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo message="########### Create Virtual Firealarm plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="target/maven-shared-archive-resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/VirtualFireAlarmDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.virtualfirealarm</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl:${carbon.devicemgt.plugins.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,34 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
#
#
#[Device-Configurations]
server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/virtual_firealarm/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,190 @@
#!/bin/bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Sample "
echo "| Virtual RaspiAlarm "
echo "| ---------------- "
echo "| ....initializing startup-script "
echo "----------------------------------------------------------------"
#while true; do
# read -p "What is the network-interface of your device that the Agent should use (find from ifconfig. ex: wlan0,en0,eth0..) > " interface
#
# echo "Setting the network-interface to " $interface
# sed s/^network-interface=.*/network-interface=$interface/ deviceConfig.properties > myTmp
# mv -f myTmp deviceConfig.properties
# break;
#done
#
#while true; do
# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-IoT-Server (ex: '60' indicates 1 minute) > " interval
#
# if [ $interval -eq $interval 2>/dev/null ]
# then
# echo "Setting data-push interval to " $interval " seconds."
# sed s/^push-interval=.*/push-interval=$interval/ deviceConfig.properties > myTmp
# mv -f myTmp deviceConfig.properties
# break;
# else
# echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
# fi
#done
java -jar wso2-firealarm-virtual-agent-advanced.jar
#while true; do
# read -p "Do you wish to run 'apt-get update' and continue? [Yes/No] " yn
# case $yn in
# [Yy]* ) sudo apt-get update;
# break;;
# [Nn]* ) echo "Continuing without apt-get update...";
# break;;
# * ) echo "Please answer yes or no.";
# esac
#done
#
#if [ $? -ne 0 ]; then
# echo "apt-get update failed.... Some dependencies may not get installed"
# echo "If an already installed version of the package exists, try running:"
# echo "----------------------------------------------------------------"
# echo "sudo -i"
# echo "cd /var/lib/dpkg/info"
# echo "rm -rf wso2-raspi-alarm*"
# echo "dpkg --remove --force-remove-reinstreq wso2-raspi-alarm"
# echo "exit"
# echo "----------------------------------------------------------------"
# echo "Retry Installation...."
# break;
#fi
#
#echo "Installing 'gdebi' package..."
#sudo apt-get install gdebi # installation of gdebi
#
#
#if [ $? -ne 0 ]; then
# echo "gdebi installation failed.... dependencies will not be installed without gdebi"
# read -p "Do you wish to continue without gdebi? [Yes/No] " yn
# case $yn in
# [Yy]* ) echo "Continueing without gdebi.....";;
# [Nn]* ) echo "Try to resolve errors and re-run the script.";
# exit;;
# * ) exit;;
# esac
#fi
#
#
#for f in ./wso2-raspi-alarm_1.0_armhf.deb; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit;
# if [ -e "$f" ]; then
# echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing now...."
# else
# echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path. \nExiting installation...";
# exit;
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#echo "Installing the 'wso2-raspi-alarm deb package'"
#sudo gdebi wso2-raspi-alarm_1.0_armhf.deb
#
#if [ $? -ne 0 ]; then
# echo "Installation Failed...."
# exit;
#fi
#sudo killall -9 python
#
#for f in ./RaspberryAgent.zip; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit;
# if [ -e "$f" ]; then
# echo "Agent files found......"
# sudo rm -rf /usr/local/src/RaspberryAgent
# sudo unzip RaspberryAgent.zip -d /usr/local/src/
# else
# echo "'RaspberryAgent.zip' file does not exist in current path. \nInstalling without upgrading agent...";
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#for f in /usr/local/src/RaspberryAgent/rc.local; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# if [ -e "$f" ]; then
# echo "Copying boot script"
# sudo mv /usr/local/src/RaspberryAgent/rc.local /etc/rc.local
# sudo chmod +x /etc/rc.local
# else
# echo "Unable to set agent statup on boot";
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#for f in ./deviceConfigs.cfg; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# if [ -e "$f" ]; then
# echo "Configuration file found......"
# else
# echo "'deviceConfigs.cfg' file does not exist in current path. \nExiting installation...";
# exit;
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#echo "Altering Configuration file"
#sed -i 's|[/,]||g' deviceConfigs.cfg
#
#echo "Copying configurations file to /usr/local/src/RaspberryAgent"
#sudo cp ./deviceConfigs.cfg /usr/local/src/RaspberryAgent/
#
#if [ $? -ne 0 ]; then
# echo "Copying configuration file failed...."
# exit;
#fi
#
#while true; do
# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute) > " input
#
# if [ $input -eq $input 2>/dev/null ]
# then
# echo "Setting data-push interval to $input seconds."
# echo $input > /usr/local/src/RaspberryAgent/time-interval
# break;
# else
# echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
# fi
#done
#
#cd /usr/local/src/RaspberryAgent/
#sudo chmod +x RaspberryStats.py
#sudo nohup ./RaspberryStats.py -i $input </dev/null &
#
#if [ $? -ne 0 ]; then
# echo "Could not start the service..."
# exit;
#else
# echo "Running the RaspberryAgent service...."
#fi
#
#echo "--------------------------------------------------------------------------"
#echo "| Successfully Started "
#echo "| -------------------------- "
#echo "| cd to /usr/local/src/RaspberryAgent"
#echo "| run 'sudo nohup ./RaspberryStats.py -i time </dev/null &'to start service manually."
#echo "| Relapce time with the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute)"
#echo "| Find logs at: /usr/local/src/RaspberryAgent/logs/RaspberryStats.log"
#echo "---------------------------------------------------------------------------"

@ -0,0 +1,34 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) 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.
#
#
#[Device-Configurations]
server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/virtual_firealarm/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,190 @@
#!/bin/bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Sample "
echo "| Virtual RaspiAlarm "
echo "| ---------------- "
echo "| ....initializing startup-script "
echo "----------------------------------------------------------------"
#while true; do
# read -p "What is the network-interface of your device that the Agent should use (find from ifconfig. ex: wlan0,en0,eth0..) > " interface
#
# echo "Setting the network-interface to " $interface
# sed s/^network-interface=.*/network-interface=$interface/ deviceConfig.properties > myTmp
# mv -f myTmp deviceConfig.properties
# break;
#done
#
#while true; do
# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-IoT-Server (ex: '60' indicates 1 minute) > " interval
#
# if [ $interval -eq $interval 2>/dev/null ]
# then
# echo "Setting data-push interval to " $interval " seconds."
# sed s/^push-interval=.*/push-interval=$interval/ deviceConfig.properties > myTmp
# mv -f myTmp deviceConfig.properties
# break;
# else
# echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
# fi
#done
java -jar wso2-firealarm-virtual-agent.jar
#while true; do
# read -p "Do you wish to run 'apt-get update' and continue? [Yes/No] " yn
# case $yn in
# [Yy]* ) sudo apt-get update;
# break;;
# [Nn]* ) echo "Continuing without apt-get update...";
# break;;
# * ) echo "Please answer yes or no.";
# esac
#done
#
#if [ $? -ne 0 ]; then
# echo "apt-get update failed.... Some dependencies may not get installed"
# echo "If an already installed version of the package exists, try running:"
# echo "----------------------------------------------------------------"
# echo "sudo -i"
# echo "cd /var/lib/dpkg/info"
# echo "rm -rf wso2-raspi-alarm*"
# echo "dpkg --remove --force-remove-reinstreq wso2-raspi-alarm"
# echo "exit"
# echo "----------------------------------------------------------------"
# echo "Retry Installation...."
# break;
#fi
#
#echo "Installing 'gdebi' package..."
#sudo apt-get install gdebi # installation of gdebi
#
#
#if [ $? -ne 0 ]; then
# echo "gdebi installation failed.... dependencies will not be installed without gdebi"
# read -p "Do you wish to continue without gdebi? [Yes/No] " yn
# case $yn in
# [Yy]* ) echo "Continueing without gdebi.....";;
# [Nn]* ) echo "Try to resolve errors and re-run the script.";
# exit;;
# * ) exit;;
# esac
#fi
#
#
#for f in ./wso2-raspi-alarm_1.0_armhf.deb; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit;
# if [ -e "$f" ]; then
# echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing now...."
# else
# echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path. \nExiting installation...";
# exit;
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#echo "Installing the 'wso2-raspi-alarm deb package'"
#sudo gdebi wso2-raspi-alarm_1.0_armhf.deb
#
#if [ $? -ne 0 ]; then
# echo "Installation Failed...."
# exit;
#fi
#sudo killall -9 python
#
#for f in ./RaspberryAgent.zip; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit;
# if [ -e "$f" ]; then
# echo "Agent files found......"
# sudo rm -rf /usr/local/src/RaspberryAgent
# sudo unzip RaspberryAgent.zip -d /usr/local/src/
# else
# echo "'RaspberryAgent.zip' file does not exist in current path. \nInstalling without upgrading agent...";
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#for f in /usr/local/src/RaspberryAgent/rc.local; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# if [ -e "$f" ]; then
# echo "Copying boot script"
# sudo mv /usr/local/src/RaspberryAgent/rc.local /etc/rc.local
# sudo chmod +x /etc/rc.local
# else
# echo "Unable to set agent statup on boot";
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#for f in ./deviceConfigs.cfg; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# if [ -e "$f" ]; then
# echo "Configuration file found......"
# else
# echo "'deviceConfigs.cfg' file does not exist in current path. \nExiting installation...";
# exit;
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#echo "Altering Configuration file"
#sed -i 's|[/,]||g' deviceConfigs.cfg
#
#echo "Copying configurations file to /usr/local/src/RaspberryAgent"
#sudo cp ./deviceConfigs.cfg /usr/local/src/RaspberryAgent/
#
#if [ $? -ne 0 ]; then
# echo "Copying configuration file failed...."
# exit;
#fi
#
#while true; do
# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute) > " input
#
# if [ $input -eq $input 2>/dev/null ]
# then
# echo "Setting data-push interval to $input seconds."
# echo $input > /usr/local/src/RaspberryAgent/time-interval
# break;
# else
# echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
# fi
#done
#
#cd /usr/local/src/RaspberryAgent/
#sudo chmod +x RaspberryStats.py
#sudo nohup ./RaspberryStats.py -i $input </dev/null &
#
#if [ $? -ne 0 ]; then
# echo "Could not start the service..."
# exit;
#else
# echo "Running the RaspberryAgent service...."
#fi
#
#echo "--------------------------------------------------------------------------"
#echo "| Successfully Started "
#echo "| -------------------------- "
#echo "| cd to /usr/local/src/RaspberryAgent"
#echo "| run 'sudo nohup ./RaspberryStats.py -i time </dev/null &'to start service manually."
#echo "| Relapce time with the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute)"
#echo "| Find logs at: /usr/local/src/RaspberryAgent/logs/RaspberryStats.log"
#echo "---------------------------------------------------------------------------"

@ -0,0 +1,20 @@
{
"deviceType": {
"label": "Virtual Firealarm",
"category": "virtual",
"downloadAgentLinkGenUri": "manager/device/virtual_firealarm/generate_link"
},
"analyticStreams": [
{
"name": "Temperature",
"table": "DEVICE_TEMPERATURE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"TEMPERATURE", "label":"Temperature", "ui-mapping":"y-axis"}}
]
}
}
]
}

@ -0,0 +1,48 @@
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>VirtualFireAlarmDM_DB</name>
<description>The datasource used for the Virtual-Firealarm database</description>
<jndiConfig>
<name>jdbc/VirtualFireAlarmDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/VirtualFireAlarmDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,11 @@
-- -----------------------------------------------------
-- Table `FIREALARM_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `VIRTUAL_FIREALARM_DEVICE` (
`VIRTUAL_FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`VIRTUAL_FIREALARM_DEVICE_ID`) );

@ -0,0 +1,12 @@
-- -----------------------------------------------------
-- Table `FIREALARM_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `VIRTUAL_FIREALARM_DEVICE` (
`VIRTUAL_FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`VIRTUAL_FIREALARM_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,18 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/virtual_firealarm/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/virtual_firealarm/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/virtual_firealarm_advanced/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/advanced_agent/,target:${installFolder}/../../resources/sketches/virtual_firealarm_advanced/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/virtual_firealarm,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\

@ -0,0 +1,41 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you 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 xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>iot-plugins-feature</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>virtual-fire-alarm-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server VirtualFireAlarm Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.virtualfirealarm.feature</module>
</modules>
</project>
Loading…
Cancel
Save