Add Smart Water Tank device type

application-manager-new
charitha 9 years ago
parent 44a0a61a85
commit d5a56c4620

@ -0,0 +1,42 @@
<?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 name="create-sample-sensor-capps" default="zip" basedir=".">
<property name="project-name" value="${ant.project.name}"/>
<property name="target-dir" value="target/carbonapps"/>
<property name="src-dir" value="src/main/resources/carbonapps"/>
<property name="relay_sensor_dir" value="relay_sensor"/>
<property name="waterlevel_sensor_dir" value="waterlevel_sensor"/>
<property name="devicetype_dir" value="watertank"/>
<target name="clean">
<delete dir="${target-dir}"/>
</target>
<target name="zip" depends="clean">
<mkdir dir="${target-dir}"/>
<zip destfile="${target-dir}/${relay_sensor_dir}.car">
<zipfileset dir="${src-dir}/${relay_sensor_dir}"/>
</zip>
<zip destfile="${target-dir}/${waterlevel_sensor_dir}.car">
<zipfileset dir="${src-dir}/${waterlevel_sensor_dir}"/>
</zip>
<zip destfile="${target-dir}/${devicetype_dir}.car">
<zipfileset dir="${src-dir}/${devicetype_dir}"/>
</zip>
</target>
</project>

@ -0,0 +1,86 @@
<!--/*
* 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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank-component</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.watertank.analytics</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>${groupId}.watertank.analytics</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>${maven-clean-plugin.version}</version>
<executions>
<execution>
<id>auto-clean</id>
<phase>initialize</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>${wso2.maven.compiler.source}</version>
<executions>
<execution>
<phase>process-resources</phase>
<configuration>
<target>
<ant antfile="build.xml" target="zip"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<finalName>${project.artifactId}-1.0-SNAPSHOT</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,36 @@
<!--
~ 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.
-->
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/target/carbonapps</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -0,0 +1,28 @@
<?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.
-->
<artifacts>
<artifact name="relay" version="1.0.0" type="carbon/application">
<dependency artifact="relay_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="relay_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="relay_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="relay_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="relay_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="relay_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>relay_publisher.xml</file>
</artifact>

@ -0,0 +1,26 @@
<?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.
-->
<eventPublisher name="relay_publisher" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.relay" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/>
</eventPublisher>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="relay_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>relay_receiver.xml</file>
</artifact>

@ -0,0 +1,26 @@
<?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.
-->
<eventReceiver name="relay_receiver" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.relay" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="relay_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>relay_script.xml</file>
</artifact>

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>relay_script</Name>
<Script>
CREATE TEMPORARY TABLE DevicerelayData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_relay");
CREATE TEMPORARY TABLE DevicerelaySummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_relay_SUMMARY",
schema "relay FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys
"deviceType, deviceId, owner, time");
insert into table DevicerelaySummaryData select relay, meta_deviceType as deviceType, meta_deviceId as deviceId,
meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicerelayData group by relay, meta_deviceType,
meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="relay_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_relay.xml</file>
</artifact>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.relay:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>relay</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>BOOLEAN</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,23 @@
<?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.
-->
<artifact name="relay_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.relay_1.0.0.json</file>
</artifact>

@ -0,0 +1,33 @@
{
"name": "org.wso2.iot.devices.relay",
"version": "1.0.0",
"nickName": "Water Pump / Valve Relay",
"description": "Status of the relay which used to control water pump or valve",
"metaData": [
{
"name": "owner",
"type": "STRING"
},
{
"name": "deviceType",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
},
{
"name": "time",
"type": "LONG"
}
],
"payloadData": [
{
"name": "relay",
"type": "BOOLEAN"
}
]
}

@ -0,0 +1,27 @@
<?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.
-->
<artifacts>
<artifact name="waterlevel" version="1.0.0" type="carbon/application">
<dependency artifact="waterlevel_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="waterlevel_store" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="waterlevel_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="waterlevel_script" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="waterlevel_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>waterlevel_receiver.xml</file>
</artifact>

@ -0,0 +1,27 @@
<?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.
-->
<eventReceiver name="waterlevel_receiver" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.waterlevel" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="waterlevel_script" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>waterlevel_script.xml</file>
</artifact>

@ -0,0 +1,35 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<Analytics>
<Name>waterlevel_script</Name>
<Script>
CREATE TEMPORARY TABLE DevicewaterlevelData USING CarbonAnalytics OPTIONS(tableName
"ORG_WSO2_IOT_DEVICES_waterlevel");
CREATE TEMPORARY TABLE DevicewaterlevelSummaryData USING CarbonAnalytics OPTIONS (tableName
"DEVICE_waterlevel_SUMMARY", schema "waterlevel FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING
-i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert into table DevicewaterlevelSummaryData select waterlevel, meta_deviceType as deviceType, meta_deviceId as
deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicewaterlevelData group by
waterlevel, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="waterlevel_store" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_waterlevel.xml</file>
</artifact>

@ -0,0 +1,62 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!--
~ 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.
-->
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.waterlevel:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>waterlevel</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,23 @@
<?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.
-->
<artifact name="waterlevel_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.waterlevel_1.0.0.json</file>
</artifact>

@ -0,0 +1,33 @@
{
"name": "org.wso2.iot.devices.waterlevel",
"version": "1.0.0",
"nickName": "Water Level Data",
"description": "Water Level data received from the Device",
"metaData": [
{
"name": "owner",
"type": "STRING"
},
{
"name": "deviceType",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
},
{
"name": "time",
"type": "LONG"
}
],
"payloadData": [
{
"name": "waterlevel",
"type": "FLOAT"
}
]
}

@ -0,0 +1,27 @@
<?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.
-->
<artifacts>
<artifact name="watertank" version="1.0.0" type="carbon/application">
<dependency artifact="watertank_stream" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="watertank_receiver" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="watertank_publisher" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="watertank_execution" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,23 @@
<?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.
-->
<artifact name="watertank_execution" version="1.0.0" type="event/execution-plan" serverRole="DataAnalyticsServer">
<file>watertank_execution.siddhiql</file>
</artifact>

@ -0,0 +1,24 @@
/* Enter a unique ExecutionPlan */
@Plan:name('watertank_execution')
/* Enter a unique description for ExecutionPlan */
-- @Plan:description('watertank_execution')
/* define streams/tables and write queries here ... */
@Import('org.wso2.iot.watertank:1.0.0')
define stream watertank (meta_owner string, meta_deviceId string, relay float, waterlevel float);
@Export('org.wso2.iot.devices.relay:1.0.0')
define stream relay (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, relay float);
@Export('org.wso2.iot.devices.waterlevel:1.0.0')
define stream waterlevel (meta_owner string, meta_deviceType string, meta_deviceId string, meta_time long, waterlevel float);
from watertank
select meta_owner, 'watertank' as meta_deviceType, meta_deviceId, time:timestampInMilliseconds() as meta_time, relay
insert into relay;
from watertank
select meta_owner, 'watertank' as meta_deviceType, meta_deviceId, time:timestampInMilliseconds() as meta_time, waterlevel
insert into waterlevel;

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="watertank_publisher" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>watertank_publisher.xml</file>
</artifact>

@ -0,0 +1,26 @@
<?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.
-->
<eventPublisher name="watertank_publisher" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.watertank" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/>
</eventPublisher>

@ -0,0 +1,22 @@
<?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.
-->
<artifact name="watertank_receiver" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>watertank_receiver.xml</file>
</artifact>

@ -0,0 +1,38 @@
<?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.
-->
<eventReceiver name="watertank_receiver" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/watertank/+/data</property>
<property name="username">admin</property>
<property name="contentValidatorParams">
device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:2
</property>
<property name="contentValidator">org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTContentValidator
</property>
<property name="contentTransformer">default</property>
<property name="dcrUrl">https://localhost:${carbon.https.port}/dynamic-client-web/register</property>
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
<property name="cleanSession">true</property>
</from>
<mapping customMapping="disable" type="json"/>
<to streamName="org.wso2.iot.watertank" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,23 @@
<?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.
-->
<artifact name="watertank_stream" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.watertank_1.0.0.json</file>
</artifact>

@ -0,0 +1,26 @@
{
"name": "org.wso2.iot.watertank",
"version": "1.0.0",
"nickName": "Water Tank stream",
"description": "This hold the device type stream of water tank",
"metaData": [
{
"name": "owner",
"type": "STRING"
},
{
"name": "deviceId",
"type": "STRING"
}
],
"payloadData": [
{
"name": "relay",
"type": "BOOLEAN"
},
{
"name": "waterlevel",
"type": "FLOAT"
}
]
}

@ -0,0 +1,168 @@
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank-component</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${project-base-package}.api</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>${project-base-package}.api</name>
<url>http://wso2.com</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>${maven-war-plugin.version}</version>
<configuration>
<warName>${project-base-package}.api</warName>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
</project>

@ -0,0 +1,119 @@
/*
* 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.homeautomation.watertank.api;
import org.homeautomation.watertank.api.dto.DeviceJSON;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
/**
* This is the controller API which is used to control agent side functionality
*/
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "watertank", version = "1.0.0", context = "/watertank", tags = "watertank")
@DeviceType(value = "watertank")
interface DeviceTypeService {
/**
* @param agentInfo device owner,id and sensor value
*/
@Path("device/register")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/user/register"})
Response registerDevice(final DeviceJSON agentInfo);
/**
* @param deviceId unique identifier for given device type
* @param onLevel level to turn on the relay
* @param offLevel level to turn off thr relay
*/
@Path("device/{deviceId}/change-levels")
@POST
@Feature(code = "change-levels", name = "Change on/off water levels",
description = "Change on/off water levels")
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/change-levels"})
Response changeOnOffLevels(@PathParam("deviceId") String deviceId,
@QueryParam("on") int onLevel,
@QueryParam("off") int offLevel,
@Context HttpServletResponse response);
/**
* Retrieve Sensor data for the given time period
* @param deviceId unique identifier for given device type instance
* @param sensorName name of the sensor
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
*/
@Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getSensorStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensorName,
@QueryParam("from") long from, @QueryParam("to") long to);
@Path("/device/{device_id}")
@DELETE
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/removeDevice"})
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("/device/{device_id}")
@PUT
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response getDevice(@PathParam("device_id") String deviceId);
@Path("/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/devices"})
Response getAllDevices();
@Path("/device/download")
@GET
@Produces("application/zip")
@Permission(scope = "watertank_user", permissions = {"/permission/admin/device-mgt/download"})
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
}

@ -0,0 +1,434 @@
/*
* 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.homeautomation.watertank.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.api.dto.DeviceJSON;
import org.homeautomation.watertank.api.dto.SensorRecord;
import org.homeautomation.watertank.api.util.APIUtil;
import org.homeautomation.watertank.api.util.ZipUtil;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.json.JSONObject;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* This is the API which is used to control and manage device type functionality
*/
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "watertank", version = "1.0.0", context = "/watertank", tags = "watertank")
@DeviceType(value = "watertank")
public class DeviceTypeServiceImpl implements DeviceTypeService {
private static final String KEY_TYPE = "PRODUCTION";
private static Log log = LogFactory.getLog(DeviceTypeService.class);
private static ApiApplicationKey apiApplicationKey;
private ConcurrentHashMap<String, DeviceJSON> deviceToIpMap = new ConcurrentHashMap<>();
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
/**
* @param agentInfo device owner,id
* @return true if device instance is added to map
*/
@Path("device/register")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response registerDevice(final DeviceJSON agentInfo) {
String deviceId = agentInfo.deviceId;
if ((agentInfo.deviceId != null) && (agentInfo.owner != null)) {
deviceToIpMap.put(deviceId, agentInfo);
return Response.status(Response.Status.OK).build();
}
return Response.status(Response.Status.NOT_ACCEPTABLE).build();
}
/**
/**
* @param deviceId unique identifier for given device type
* @param onLevel level to turn on the relay
* @param offLevel level to turn off thr relay
*/
@Path("device/{deviceId}/change-levels")
@POST
@Feature(code = "change-levels", name = "Change on/off water levels",
description = "Change on/off water levels")
public Response changeOnOffLevels(@PathParam("deviceId") String deviceId,
@QueryParam("on") int onLevel,
@QueryParam("off") int offLevel,
@Context HttpServletResponse response) {
try {
if (!APIUtil.getDeviceAccessAuthorizationService()
.isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("on", onLevel);
jsonObject.put("off", offLevel);
Map<String, String> dynamicProperties = new HashMap<>();
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + DeviceTypeConstants.DEVICE_TYPE + "/" + deviceId + "/command";
dynamicProperties.put(DeviceTypeConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
APIUtil.getOutputEventAdapterService().publish(DeviceTypeConstants.MQTT_ADAPTER_NAME,
dynamicProperties, jsonObject.toString());
return Response.ok().build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Retrieve Sensor data for the given time period
*
* @param deviceId unique identifier for given device type instance
* @param sensorName name of the sensor
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
*/
@Path("device/stats/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getSensorStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensorName,
@QueryParam("from") long from, @QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND deviceType:" +
DeviceTypeConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName;
switch (sensorName) {
case DeviceTypeConstants.STREAM_RELAY:
sensorTableName = DeviceTypeConstants.RELAY_EVENT_TABLE;
break;
case DeviceTypeConstants.STREAM_WATERLEVEL:
sensorTableName = DeviceTypeConstants.WATERLEVEL_EVENT_TABLE;
break;
default:
return Response.status(Response.Status.BAD_REQUEST).entity("Invalid event stream").build();
}
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DeviceTypeConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
/**
* Remove device type instance using device id
*
* @param deviceId unique identifier for given device type instance
*/
@Path("/device/{deviceId}")
@DELETE
public Response removeDevice(@PathParam("deviceId") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Update device instance name
*
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
*/
@Path("/device/{deviceId}")
@PUT
public Response updateDevice(@PathParam("deviceId") String deviceId, @QueryParam("name") String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DeviceTypeConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* To get device information
*
* @param deviceId unique identifier for given device type instance
* @return
*/
@Path("/device/{deviceId}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("deviceId") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Get all device type instance which belongs to user
*
* @return Array of devices which includes device's information
*/
@Path("/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getAllDevices() {
try {
List<Device> userDevices =
APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforwatertank = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DeviceTypeConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforwatertank.add(device);
}
}
Device[] devices = userDevicesforwatertank.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* To download device type agent source code as zip file
*
* @param deviceName name for the device type instance
* @param sketchType folder name where device type agent was installed into server
* @return Agent source code as zip file
*/
@Path("/device/download")
@GET
@Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@QueryParam("sketchType") String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.status(Response.Status.OK);
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response resp = response.build();
zipFile.getZipFile().delete();
return resp;
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
}
}
/**
* Register device into device management service
*
* @param deviceId unique identifier for given device type instance
* @param name name for the device type instance
* @return check whether device is installed into cdmf
*/
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(DeviceTypeConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
}
return added;
} catch (DeviceManagementException e) {
log.error(e.getMessage(), e);
return false;
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException,
UserStoreException {
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DeviceTypeConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken();
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);
return zipFile;
}
}

@ -0,0 +1,37 @@
/*
* 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.homeautomation.watertank.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* These information are sent by agent in each request to server
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
@XmlElement(required = true)
public String owner;
@XmlElement(required = true)
public String deviceId;
@XmlElement(required = true)
public Float sensorValue;
}

@ -0,0 +1,88 @@
/*
* 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.homeautomation.watertank.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* This stores sensor event data for watertank.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class SensorRecord {
@XmlElementWrapper(required = true, name = "values")
private Map<String, Object> values;
/**
* Unique identifier for each recode
*/
@XmlElement(required = false, name = "id")
private String id;
/**
* Gets the values.
* @return the values
*/
public Map<String, Object> getValues() {
return values;
}
/**
* Sets the values.
* @param values
*/
public void setValues(Map<String, Object> values) {
this.values = values;
}
/**
* Gets the id.
* @return the id
*/
public String getId() {
return id;
}
/**
* Sets the id.
* @param id set unique identifier
*/
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
List<String> valueList = new ArrayList<String>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue());
}
return valueList.toString();
}
}

@ -0,0 +1,57 @@
/*
* 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.homeautomation.watertank.api.exception;
public class DeviceTypeException extends Exception {
private static final long serialVersionUID = 2736466563251105441L;
private String errorMessage;
public DeviceTypeException(String msg, DeviceTypeException nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DeviceTypeException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DeviceTypeException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DeviceTypeException() {
super();
}
public DeviceTypeException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -0,0 +1,221 @@
package org.homeautomation.watertank.api.util;
import org.homeautomation.watertank.api.dto.SensorRecord;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.service.RealmService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* This class provides utility functions used by REST-API.
*/
public class APIUtil {
private static Log log = LogFactory.getLog(APIUtil.class);
public static String getAuthenticatedUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String username = threadLocalCarbonContext.getUsername();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
if (username.endsWith(tenantDomain)) {
return username.substring(0, username.lastIndexOf("@"));
}
return username;
}
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;
}
public static APIManagementProviderService getAPIManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
APIManagementProviderService apiManagementProviderService =
(APIManagementProviderService) ctx.getOSGiService(APIManagementProviderService.class, null);
if (apiManagementProviderService == null) {
String msg = "API management provider service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return apiManagementProviderService;
}
public static JWTClientManagerService getJWTClientManagerService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
JWTClientManagerService jwtClientManagerService =
(JWTClientManagerService) ctx.getOSGiService(JWTClientManagerService.class, null);
if (jwtClientManagerService == null) {
String msg = "JWT Client manager service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return jwtClientManagerService;
}
public static String getTenantDomainOftheUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static UserStoreManager getUserStoreManager() {
RealmService realmService;
UserStoreManager userStoreManager;
try {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
realmService = (RealmService) ctx.getOSGiService(RealmService.class, null);
if (realmService == null) {
String msg = "Realm service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
int tenantId = ctx.getTenantId();
userStoreManager = realmService.getTenantUserRealm(tenantId).getUserStoreManager();
} catch (UserStoreException e) {
String msg = "Error occurred while retrieving current user store manager";
log.error(msg, e);
throw new IllegalStateException(msg);
}
return userStoreManager;
}
public static void registerApiAccessRoles(String user) {
UserStoreManager userStoreManager = null;
try {
userStoreManager = getUserStoreManager();
String[] userList = new String[]{user};
if (userStoreManager != null) {
String rolesOfUser[] = userStoreManager.getRoleListOfUser(user);
if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) {
userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION);
} else if (rolesOfUser != null && Arrays.asList(rolesOfUser).contains(Constants.DEFAULT_ROLE_NAME)) {
return;
} else {
userStoreManager.updateUserListOfRole(Constants.DEFAULT_ROLE_NAME, new String[0], userList);
}
}
} catch (UserStoreException e) {
log.error("Error while creating a role and adding a user for watertank.", e);
}
}
public static DeviceAccessAuthorizationService getDeviceAccessAuthorizationService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAccessAuthorizationService deviceAccessAuthorizationService =
(DeviceAccessAuthorizationService) ctx.getOSGiService(DeviceAccessAuthorizationService.class, null);
if (deviceAccessAuthorizationService == null) {
String msg = "Device Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return deviceAccessAuthorizationService;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData;
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) {
SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData);
}
return sensorDatas;
}
public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId());
recordBean.setValues(record.getValues());
return recordBean;
}
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
String msg = "Analytics api service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return analyticsDataAPI;
}
public static String getAuthenticatedUserTenantDomain() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static OutputEventAdapterService getOutputEventAdapterService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
OutputEventAdapterService outputEventAdapterService =
(OutputEventAdapterService) ctx.getOSGiService(OutputEventAdapterService.class, null);
if (outputEventAdapterService == null) {
String msg = "Device Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return outputEventAdapterService;
}
}

@ -0,0 +1,32 @@
/*
* 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.homeautomation.watertank.api.util;
import org.wso2.carbon.user.core.Permission;
/**
* This hold the constants related to the device type.
*/
public class Constants {
public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/watertank/user";
public static final String DEFAULT_ROLE_NAME = "watertank_user";
public static final Permission DEFAULT_PERMISSION[]
= new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
}

@ -0,0 +1,91 @@
/*
* 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.homeautomation.watertank.api.util;
import org.homeautomation.watertank.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* This is used to create a zip file that includes the necessary configuration required for the agent.
*/
public class ZipUtil {
private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String LOCALHOST = "localhost";
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
String deviceId, String deviceName, String token,
String refreshToken) throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP;
try {
iotServerIP = Utils.getServerUrl();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String apimEndpoint = httpsServerEP;
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
}
String[] mqttEPParams = mqttEndpoint.split(":");
String mqttEPIP = mqttEPParams[1].replace("//", "");
String mqttPort = mqttEPParams[2];
Map<String, String> contextParams = new HashMap<>();
contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser());
contextParams.put("DEVICE_OWNER", owner);
contextParams.put("DEVICE_ID", deviceId);
contextParams.put("DEVICE_NAME", deviceName);
contextParams.put("HTTPS_EP", httpsServerEP);
contextParams.put("HTTP_EP", httpServerEP);
contextParams.put("APIM_EP", apimEndpoint);
contextParams.put("MQTT_EP", mqttEPIP);
contextParams.put("MQTT_PORT", mqttPort);
contextParams.put("DEVICE_TOKEN", token);
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile;
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile;
} catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e);
}
}
}

@ -0,0 +1,87 @@
<?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.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/watertank/user</path>
<url>/device/*</url>
<method>GET</method>
<scope>watertank_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/watertank/user</path>
<url>/device/*</url>
<method>DELETE</method>
<scope>watertank_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/watertank/user</path>
<url>/device/download</url>
<method>GET</method>
<scope>watertank_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/watertank/user</path>
<url>/device/*</url>
<method>POST</method>
<scope>watertank_user</scope>
</Permission>
<Permission>
<name>Get Devices</name>
<path>/device-mgt/watertank/user</path>
<url>/device</url>
<method>GET</method>
<scope>watertank_user</scope>
</Permission>
<Permission>
<name>Register Device</name>
<path>/device-mgt/watertank/user</path>
<url>/device/register</url>
<method>POST</method>
<scope>watertank_device</scope>
</Permission>
<Permission>
<name>Control Sensor</name>
<path>/device-mgt/watertank/user</path>
<url>/device/*/change-levels</url>
<method>POST</method>
<scope>watertank_user</scope>
</Permission>
<Permission>
<name>Get Stats</name>
<path>/device-mgt/watertank/user</path>
<url>/device/stats/*</url>
<method>GET</method>
<scope>watertank_device</scope>
</Permission>
</PermissionConfiguration>

@ -0,0 +1,33 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ 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.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,36 @@
<?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.
-->
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xmlns="http://www.springframework.org/schema/beans"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="watertank" address="/">
<jaxrs:serviceBeans>
<bean id="DeviceTypeService"
class="org.homeautomation.watertank.api.DeviceTypeServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -0,0 +1,46 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>isSharedWithAllTenants</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>providerTenantDomain</param-name>
<param-value>carbon.super</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
</web-app>

@ -0,0 +1,133 @@
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank-component</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0-SNAPSHOT</version>
<artifactId>${project-base-package}.plugin</artifactId>
<packaging>bundle</packaging>
<name>${project-base-package}.plugin</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<version>${org.apache.felix.version}</version>
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
<Bundle-Name>${project-base-package}.plugin</Bundle-Name>
<Bundle-Version>1.0-SNAPSHOT</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>${project-base-package}.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
org.apache.commons.logging,
javax.naming;resolution:=optional,
javax.sql;resolution:=optional,
org.wso2.carbon.device.mgt.common.*,
org.wso2.carbon.device.mgt.common,
org.wso2.carbon.device.mgt.iot.*,
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
org.wso2.carbon.utils.*,
org.wso2.carbon.event.output.adapter.core,
org.wso2.carbon.event.output.adapter.core.exception,
org.wso2.carbon.base,
org.wso2.carbon.core.util,
org.wso2.carbon.context,
org.wso2.carbon.core,
org.apache.commons.codec.binary
</Import-Package>
<Export-Package>
!${project-base-package}.plugin.internal,
${project-base-package}.plugin.*
</Export-Package>
</instructions>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,63 @@
/*
* 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.homeautomation.watertank.plugin.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
public class DeviceTypeConstants {
public final static String DEVICE_TYPE = "watertank";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "watertank_DEVICE_ID";
public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
//sensor events summarized table name
public final static String STREAM_RELAY = "relay";
public final static String STREAM_WATERLEVEL = "waterlevel";
public final static String RELAY_EVENT_TABLE = "DEVICE_relay_SUMMARY";
public final static String WATERLEVEL_EVENT_TABLE = "DEVICE_waterlevel_SUMMARY";
public static final String DATA_SOURCE_NAME = "jdbc/watertankDM_DB";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt transport related constants
public static final String MQTT_ADAPTER_NAME = "watertank_mqtt";
public static final String MQTT_ADAPTER_TYPE = "oauth-mqtt";
public static final String ADAPTER_TOPIC_PROPERTY = "topic";
public static final String MQTT_PORT = "\\{mqtt.broker.port\\}";
public static final String MQTT_BROKER_HOST = "\\{mqtt.broker.host\\}";
public static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset";
public static final String DEFAULT_CARBON_LOCAL_IP_PROPERTY = "carbon.local.ip";
public static final int CARBON_DEFAULT_PORT_OFFSET = 0;
public static final int DEFAULT_MQTT_PORT = 1883;
public static final String RESOURCE = "resource";
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String DCR_PROPERTY_KEY = "dcrUrl";
public static final String BROKER_URL_PROPERTY_KEY = "url";
public static final String SCOPES_PROPERTY_KEY = "scopes";
public static final String QOS_PROPERTY_KEY = "qos";
public static final String CLIENT_ID_PROPERTY_KEY = "qos";
public static final String CLEAR_SESSION_PROPERTY_KEY = "clearSession";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
}

@ -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.homeautomation.watertank.plugin.exception;
public class DeviceMgtPluginException extends Exception {
private String errorMessage;
public DeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DeviceMgtPluginException() {
super();
}
public DeviceMgtPluginException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -0,0 +1,257 @@
/*
* 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.homeautomation.watertank.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.plugin.impl.dao.DeviceTypeDAO;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.watertank.plugin.impl.feature.DeviceTypeFeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.common.configuration.mgt.TenantConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
import java.util.List;
/**
* This represents the watertank implementation of DeviceManagerService.
*/
public class DeviceTypeManager implements DeviceManager {
private static final Log log = LogFactory.getLog(DeviceTypeManager.class);
private static final DeviceTypeDAO deviceTypeDAO = new DeviceTypeDAO();
private FeatureManager featureManager = new DeviceTypeFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return featureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
//TODO implement this
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
return null;
}
@Override
public boolean enrollDevice(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new watertank device : " + device.getDeviceIdentifier());
}
DeviceTypeDAO.beginTransaction();
status = deviceTypeDAO.getDeviceTypeDAO().addDevice(device);
DeviceTypeDAO.commitTransaction();
} catch (DeviceMgtPluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (DeviceMgtPluginException iotDAOEx) {
log.warn("Error occurred while roll back the device enrol transaction :" + device.toString(), iotDAOEx);
}
String msg = "Error while enrolling the watertank device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the watertank device enrollment data");
}
DeviceTypeDAO.beginTransaction();
status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
DeviceTypeDAO.commitTransaction();
} catch (DeviceMgtPluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (DeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while updating the enrollment of the watertank device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling watertank device : " + deviceId);
}
DeviceTypeDAO.beginTransaction();
status = deviceTypeDAO.getDeviceTypeDAO().deleteDevice(deviceId.getId());
DeviceTypeDAO.commitTransaction();
} catch (DeviceMgtPluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (DeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device dis enrol transaction :" + deviceId.toString();
log.warn(msg, iotDAOEx);
}
String msg = "Error while removing the watertank device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of watertank device : " + deviceId.getId());
}
Device iotDevice =
deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (DeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of watertank device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return isEnrolled;
}
@Override
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
return true;
}
@Override
public boolean setActive(DeviceIdentifier deviceId, boolean status)
throws DeviceManagementException {
return true;
}
@Override
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of watertank device : " + deviceId.getId());
}
device = deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
} catch (DeviceMgtPluginException e) {
String msg = "Error while fetching the watertank device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return device;
}
@Override
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
throws DeviceManagementException {
return true;
}
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
return false;
}
@Override
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
EnrolmentInfo.Status status) throws DeviceManagementException {
return false;
}
@Override
public License getLicense(String s) throws LicenseManagementException {
return null;
}
@Override
public void addLicense(License license) throws LicenseManagementException {
}
@Override
public boolean requireDeviceAuthorization() {
return true;
}
@Override
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("updating the details of watertank device : " + deviceIdentifier);
}
DeviceTypeDAO.beginTransaction();
status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
DeviceTypeDAO.commitTransaction();
} catch (DeviceMgtPluginException e) {
try {
DeviceTypeDAO.rollbackTransaction();
} catch (DeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the update device info transaction :" + device.toString();
log.warn(msg, iotDAOEx);
}
String msg =
"Error while updating the watertank device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return status;
}
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all watertank devices");
}
devices = deviceTypeDAO.getDeviceTypeDAO().getAllDevices();
} catch (DeviceMgtPluginException e) {
String msg = "Error while fetching all watertank devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
}

@ -0,0 +1,62 @@
/*
* 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.homeautomation.watertank.plugin.impl;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
public class DeviceTypeManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
@Override
public String getType() {
return DeviceTypeConstants.DEVICE_TYPE;
}
@Override
public void init() throws DeviceManagementException {
this.deviceManager = new DeviceTypeManager();
}
@Override
public DeviceManager getDeviceManager() {
return deviceManager;
}
@Override
public ApplicationManager getApplicationManager() {
return null;
}
@Override
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false);
}
@Override
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
}

@ -0,0 +1,129 @@
/*
* 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.homeautomation.watertank.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.homeautomation.watertank.plugin.impl.dao.impl.DeviceTypeDAOImpl;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class DeviceTypeDAO {
private static final Log log = LogFactory.getLog(DeviceTypeDAO.class);
static DataSource dataSource; // package local variable
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public DeviceTypeDAO() {
initDeviceTypeDAO();
}
public static void initDeviceTypeDAO() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME);
} catch (NamingException e) {
log.error("Error while looking up the data source: " +
DeviceTypeConstants.DATA_SOURCE_NAME);
}
}
public static void beginTransaction() throws DeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new DeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws DeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new DeviceMgtPluginException("Error occurred while retrieving data source connection",
e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws DeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws DeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws DeviceMgtPluginException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
public DeviceTypeDAOImpl getDeviceTypeDAO() {
return new DeviceTypeDAOImpl();
}
}

@ -0,0 +1,204 @@
/*
* 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.homeautomation.watertank.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.watertank.plugin.impl.dao.DeviceTypeDAO;
import org.homeautomation.watertank.plugin.impl.util.DeviceTypeUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Implements IotDeviceDAO for watertank Devices.
*/
public class DeviceTypeDAOImpl {
private static final Log log = LogFactory.getLog(DeviceTypeDAOImpl.class);
public Device getDevice(String deviceId) throws DeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device iotDevice = null;
ResultSet resultSet = null;
try {
conn = DeviceTypeDAO.getConnection();
String selectDBQuery =
"SELECT watertank_DEVICE_ID, DEVICE_NAME" +
" FROM watertank_DEVICE WHERE watertank_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
iotDevice = new Device();
iotDevice.setName(resultSet.getString(
DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("watertank device " + deviceId + " data has been fetched from " +
"watertank database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching watertank device : '" + deviceId + "'";
log.error(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DeviceTypeUtils.cleanupResources(stmt, resultSet);
DeviceTypeDAO.closeConnection();
}
return iotDevice;
}
public boolean addDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DeviceTypeDAO.getConnection();
String createDBQuery =
"INSERT INTO watertank_DEVICE(watertank_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("watertank device " + device.getDeviceIdentifier() + " data has been" +
" added to the watertank database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the watertank device '" +
device.getDeviceIdentifier() + "' to the watertank db.";
log.error(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DeviceTypeUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DeviceTypeDAO.getConnection();
String updateDBQuery =
"UPDATE watertank_DEVICE SET DEVICE_NAME = ? WHERE watertank_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (device.getProperties() == null) {
device.setProperties(new ArrayList<Device.Property>());
}
stmt.setString(1, device.getName());
stmt.setString(2, device.getDeviceIdentifier());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("watertank device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the watertank device '" +
device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DeviceTypeUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteDevice(String deviceId) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DeviceTypeDAO.getConnection();
String deleteDBQuery =
"DELETE FROM watertank_DEVICE WHERE watertank_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("watertank device " + deviceId + " data has deleted" +
" from the watertank database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting watertank device " + deviceId;
log.error(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DeviceTypeUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws DeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> iotDevices = new ArrayList<>();
try {
conn = DeviceTypeDAO.getConnection();
String selectDBQuery =
"SELECT watertank_DEVICE_ID, DEVICE_NAME " +
"FROM watertank_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
device = new Device();
device.setDeviceIdentifier(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<>();
device.setProperties(propertyList);
}
if (log.isDebugEnabled()) {
log.debug("All watertank device details have fetched from watertank database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all watertank device data'";
log.error(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DeviceTypeUtils.cleanupResources(stmt, resultSet);
DeviceTypeDAO.closeConnection();
}
}
}

@ -0,0 +1,58 @@
/*
* Copyright (c) 2016, 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.
*/
package org.homeautomation.watertank.plugin.impl.feature;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import java.util.List;
public class DeviceTypeFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
return false;
}
@Override
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
return false;
}
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(DeviceTypeConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(DeviceTypeConstants.DEVICE_TYPE);
}
@Override
public boolean removeFeature(String name) throws DeviceManagementException {
return false;
}
@Override
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
return false;
}
}

@ -0,0 +1,49 @@
/*
* 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.homeautomation.watertank.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
import javax.sql.DataSource;
import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator{
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome() + File.separator + "dbscripts"
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);
}
@Override
protected String getDbScriptLocation(String databaseType) {
String scriptName = databaseType + ".sql";
if (log.isDebugEnabled()) {
log.debug("Loading database script from :" + scriptName);
}
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
}
}

@ -0,0 +1,42 @@
/*
* 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.homeautomation.watertank.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
import java.io.IOException;
public class DeviceTypeStartupListener implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(DeviceTypeStartupListener.class);
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
try {
DeviceTypeUtils.setupMqttOutputAdapter();
} catch (IOException e) {
log.error("Failed to initialize the watertank output adapter", e);
}
}
}

@ -0,0 +1,189 @@
/*
* 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.homeautomation.watertank.plugin.impl.util;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.watertank.plugin.internal.DeviceTypeManagementDataHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.event.output.adapter.core.MessageType;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterConfiguration;
import org.wso2.carbon.event.output.adapter.core.exception.OutputEventAdapterException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* Contains utility methods used by watertank plugin.
*/
public class DeviceTypeUtils {
private static Log log = LogFactory.getLog(DeviceTypeUtils.class);
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
log.warn("Error occurred while closing result set", e);
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
log.warn("Error occurred while closing prepared statement", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
log.warn("Error occurred while closing database connection", e);
}
}
}
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
cleanupResources(null, stmt, rs);
}
/**
* Creates the device management schema.
*/
public static void setupDeviceManagementSchema() throws DeviceMgtPluginException {
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME);
DeviceSchemaInitializer initializer =
new DeviceSchemaInitializer(dataSource);
log.info("Initializing device management repository database schema");
initializer.createRegistryDatabase();
} catch (NamingException e) {
log.error("Error while looking up the data source: " + DeviceTypeConstants.DATA_SOURCE_NAME);
} catch (Exception e) {
throw new DeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
public static String replaceMqttProperty(String urlWithPlaceholders) {
String MQTT_BROKER_HOST = null;
String MQTT_PORT = null;
if(!DeviceTypeConstants.MQTT_BROKER_HOST.startsWith("$")){
MQTT_BROKER_HOST = "\\$".concat(DeviceTypeConstants.MQTT_BROKER_HOST);
}
if(!DeviceTypeConstants.MQTT_PORT.startsWith("$")){
MQTT_PORT = "\\$".concat(DeviceTypeConstants.MQTT_PORT);
}
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_PORT, "" +
(DeviceTypeConstants.DEFAULT_MQTT_PORT + getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_BROKER_HOST,
System.getProperty(DeviceTypeConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
return urlWithPlaceholders;
}
private static int getPortOffset() {
ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
DeviceTypeConstants.CARBON_CONFIG_PORT_OFFSET));
try {
if ((portOffset != null)) {
return Integer.parseInt(portOffset.trim());
} else {
return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
}
} catch (NumberFormatException e) {
return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
}
}
public static void setupMqttOutputAdapter() throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createMqttOutputEventAdapterConfiguration(DeviceTypeConstants.MQTT_ADAPTER_NAME,
DeviceTypeConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
DeviceTypeManagementDataHolder.getInstance().getOutputEventAdapterService()
.create(outputEventAdapterConfiguration);
} catch (OutputEventAdapterException e) {
log.error("Unable to create Output Event Adapter : " + DeviceTypeConstants.MQTT_ADAPTER_NAME, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Create Output Event Adapter Configuration for given configuration.
*
* @param name Output Event Adapter name
* @param type Output Event Adapter type
* @param msgFormat Output Event Adapter message format
* @return OutputEventAdapterConfiguration instance for given configuration
*/
private static OutputEventAdapterConfiguration createMqttOutputEventAdapterConfiguration(String name, String type,
String msgFormat) throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration = new OutputEventAdapterConfiguration();
outputEventAdapterConfiguration.setName(name);
outputEventAdapterConfiguration.setType(type);
outputEventAdapterConfiguration.setMessageFormat(msgFormat);
File configFile = new File(DeviceTypeConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
Map<String, String> mqttAdapterProperties = new HashMap<>();
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
mqttAdapterProperties.put(DeviceTypeConstants.USERNAME_PROPERTY_KEY, properties.getProperty(
DeviceTypeConstants.USERNAME_PROPERTY_KEY));
mqttAdapterProperties.put(DeviceTypeConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty(
properties.getProperty(DeviceTypeConstants.DCR_PROPERTY_KEY)));
mqttAdapterProperties.put(DeviceTypeConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty(
properties.getProperty(DeviceTypeConstants.BROKER_URL_PROPERTY_KEY)));
mqttAdapterProperties.put(DeviceTypeConstants.SCOPES_PROPERTY_KEY, properties.getProperty(
DeviceTypeConstants.SCOPES_PROPERTY_KEY));
mqttAdapterProperties.put(DeviceTypeConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty(
DeviceTypeConstants.CLEAR_SESSION_PROPERTY_KEY));
mqttAdapterProperties.put(DeviceTypeConstants.QOS_PROPERTY_KEY, properties.getProperty(
DeviceTypeConstants.QOS_PROPERTY_KEY));
mqttAdapterProperties.put(DeviceTypeConstants.CLIENT_ID_PROPERTY_KEY, "");
mqttAdapterProperties.put(DeviceTypeConstants.RESOURCE, "output-event");
outputEventAdapterConfiguration.setStaticProperties(mqttAdapterProperties);
}
return outputEventAdapterConfiguration;
}
}

@ -0,0 +1,47 @@
/*
* 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.homeautomation.watertank.plugin.internal;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* DataHolder class of watertank plugins component.
*/
public class DeviceTypeManagementDataHolder {
private static DeviceTypeManagementDataHolder thisInstance = new DeviceTypeManagementDataHolder();
private OutputEventAdapterService outputEventAdapterService;
private DeviceTypeManagementDataHolder() {
}
public static DeviceTypeManagementDataHolder getInstance() {
return thisInstance;
}
public OutputEventAdapterService getOutputEventAdapterService() {
return outputEventAdapterService;
}
public void setOutputEventAdapterService(
OutputEventAdapterService outputEventAdapterService) {
this.outputEventAdapterService = outputEventAdapterService;
}
}

@ -0,0 +1,113 @@
/*
* 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.homeautomation.watertank.plugin.internal;
import org.homeautomation.watertank.plugin.impl.util.DeviceTypeStartupListener;
import org.homeautomation.watertank.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.watertank.plugin.impl.util.DeviceTypeUtils;
import org.homeautomation.watertank.plugin.impl.DeviceTypeManagerService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.core.ServerStartupObserver;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* @scr.component name="ServiceComponent"
* immediate="true"
* @scr.reference name="event.output.adapter.service"
* interface="org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService"
* cardinality="1..1"
* policy="dynamic"
* bind="setOutputEventAdapterService"
* unbind="unsetOutputEventAdapterService"
*/
public class ServiceComponent {
private static final Log log = LogFactory.getLog(ServiceComponent.class);
private ServiceRegistration serviceRegistration;
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating b Management Service Component");
}
try {
DeviceTypeManagerService deviceTypeManagerService = new DeviceTypeManagerService();
BundleContext bundleContext = ctx.getBundleContext();
serviceRegistration =
bundleContext.registerService(DeviceManagementService.class.getName(),
deviceTypeManagerService, null);
bundleContext.registerService(ServerStartupObserver.class.getName(), new DeviceTypeStartupListener(),
null);
String setupOption = System.getProperty("setup");
if (setupOption != null) {
if (log.isDebugEnabled()) {
log.debug("-Dsetup is enabled. Iot Device management repository schema initialization is about " +
"to begin");
}
try {
DeviceTypeUtils.setupDeviceManagementSchema();
} catch (DeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug("b Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Current Sensor Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating b Management Service Component");
}
try {
if (serviceRegistration != null) {
serviceRegistration.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Current Sensor Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error("Error occurred while de-activating Iot Device Management bundle", e);
}
}
/**
* Initialize the Output EventAdapter Service dependency
*
* @param outputEventAdapterService Output EventAdapter Service reference
*/
protected void setOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
DeviceTypeManagementDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService);
}
/**
* De-reference the Output EventAdapter Service dependency.
*/
protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
DeviceTypeManagementDataHolder.getInstance().setOutputEventAdapterService(null);
}
}

@ -0,0 +1,60 @@
/*
* 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.homeautomation.watertank.plugin.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.watertank.plugin.constants.DeviceTypeConstants;
import org.homeautomation.watertank.plugin.impl.util.DeviceTypeUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class MqttConfig {
private static String brokerEndpoint;
private static MqttConfig mqttConfig = new MqttConfig();
private static final Log log = LogFactory.getLog(MqttConfig.class);
private MqttConfig() {
File configFile = new File(DeviceTypeConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
try {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
brokerEndpoint = DeviceTypeUtils.replaceMqttProperty(
properties.getProperty(DeviceTypeConstants.BROKER_URL_PROPERTY_KEY));
} catch (IOException e) {
log.error("Failed to read the mqtt.properties file" + e);
}
}
}
public static MqttConfig getInstance() {
return mqttConfig;
}
public String getBrokerEndpoint() {
return brokerEndpoint;
}
}

@ -0,0 +1,56 @@
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0-SNAPSHOT</version>
<artifactId>watertank-component</artifactId>
<packaging>pom</packaging>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>${maven-scr-plugin.version}</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
<modules>
<module>plugin</module>
<module>api</module>
<module>ui</module>
<module>analytics</module>
</modules>
</project>

@ -0,0 +1,56 @@
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank-component</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${project-base-package}.ui</artifactId>
<name>${project-base-package}.ui</name>
<packaging>pom</packaging>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<finalName>${project.artifactId}-1.0-SNAPSHOT</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
</descriptors>
</configuration>
<executions>
<execution>
<id>create-archive</id>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,37 @@
<?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.
-->
<assembly
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>src</id>
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<baseDirectory>${basedir}/src</baseDirectory>
<fileSets>
<fileSet>
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
<outputDirectory>/</outputDirectory>
<useDefaultExcludes>true</useDefaultExcludes>
</fileSet>
</fileSets>
</assembly>

@ -0,0 +1,50 @@
{{!
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.
}}
<span id="watertank-details" data-devices="{{devices}}" data-devicename="{{device.name}}"
data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span>
<div id="watertank-div-chart" data-backend-api-url= {{backendApiUrl}}>
<div class="chartWrapper" id="chartWrapper-temperature">
<span id="span-title">Temperature</span>
<div id="y_axis-temperature" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-temperature" title="Smoothing"></div>
<div id="legend-temperature"></div>
</div>
<div id="chart-temperature" class="custom_rickshaw_graph"></div>
<div id="x_axis-temperature" class="custom_x_axis"></div>
<div id="slider-temperature" class="custom_slider"></div>
</div>
<div class="chartWrapper" id="chartWrapper-humidity">
<span id="span-title">Humidity</span>
<div id="y_axis-humidity" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-humidity" title="Smoothing"></div>
<div id="legend-humidity"></div>
</div>
<div id="chart-humidity" class="custom_rickshaw_graph"></div>
<div id="x_axis-humidity" class="custom_x_axis"></div>
<div id="slider-humidity" class="custom_slider"></div>
</div>
</div>
{{#zone "bottomJs"}}
{{js "js/watertank.js"}}
{{/zone}}

@ -0,0 +1,42 @@
/*
* 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.
*/
function onRequest(context) {
var devices = context.unit.params.devices;
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("deviceId");
if (devices) {
return {
"devices": stringify(devices),
"backendApiUri": devicemgtProps["httpsURL"] + "/watertank/device/stats/"
};
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
return {
"device": device,
"backendApiUrl": devicemgtProps["httpsURL"] + "/watertank/device/stats/" + deviceId + "/sensors/"
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
exit();
}
}
}

@ -0,0 +1,228 @@
/*
* 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.
*/
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
var graphMap = {};
function drawGraph_watertank(from, to) {
var devices = $("#watertank-details").data("devices");
var tzOffset = new Date().getTimezoneOffset() * 60;
var streamIndex = 0;
var streams = ["temperature", "humidity"];
populateGraph();
function populateGraph() {
retrieveDataAndDrawLineGraph(streams[streamIndex], from, to);
streamIndex++;
}
function clearContent(type) {
$("#y_axis-" + type).html("");
$("#smoother-" + type).html("");
$("#legend-" + type).html("");
$("#chart-" + type).html("");
$("#x_axis-" + type).html("");
$("#slider-" + type).html("");
}
function initGraph(type) {
if (graphMap[type]) {
return graphMap[type];
}
var chartWrapperElmId = "#watertank-div-chart";
var graphWidth = $(chartWrapperElmId).width() - 50;
var graphConfig = {
element: document.getElementById("chart-" + type),
width: graphWidth,
height: 400,
strokeWidth: 2,
renderer: 'line',
interpolation: "linear",
unstack: true,
stack: false,
xScale: d3.time.scale(),
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
series: []
};
if (devices) {
for (var i = 0; i < devices.length; i++) {
graphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': devices[i].name
});
}
} else {
graphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $("#watertank-details").data("devicename")
});
}
var graph = new Rickshaw.Graph(graphConfig);
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
element: document.getElementById("y_axis-" + type),
width: 40,
height: 410
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById("slider-" + type)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById("legend-" + type)
});
var hoverDetail = new Rickshaw.Graph.HoverDetail({
graph: graph,
formatter: function (series, x, y) {
var date = '<span class="date">' +
moment((x + tzOffset) * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' +
series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
}
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
graphMap[type] = {};
graphMap[type].graph = graph;
graphMap[type].config = graphConfig;
return graphMap[type];
}
function retrieveDataAndDrawLineGraph(type, from, to) {
clearContent(type);
var graphObj = initGraph(type);
var graph = graphObj.graph;
var graphConfig = graphObj.config;
var deviceIndex = 0;
if (devices) {
getData();
} else {
var backendApiUrl = $("#watertank-div-chart").data("backend-api-url") + type + "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data));
}
populateGraph();
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
});
}
function getData() {
if (deviceIndex >= devices.length) {
return;
}
var backendApiUrl = $("#watertank-div-chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
+ "/sensors/" + type + "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data));
}
deviceIndex++;
getData();
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
deviceIndex++;
getData();
});
}
function drawLineGraph(data) {
if (data.length === 0 || data.length === undefined) {
return;
}
var chartData = [];
for (var i = 0; i < data.length; i++) {
chartData.push(
{
x: parseInt(data[i].values.time) - tzOffset,
y: parseInt(getFieldData(data[i], type))
}
);
}
graphConfig.series[deviceIndex].data = chartData;
graph.update();
}
}
function getFieldData(data, type) {
var columnData;
switch (type) {
case "temperature" :
columnData = data.values.temperature;
break;
case "humidity" :
columnData = data.values.humidity;
break;
}
return columnData;
}
}

@ -0,0 +1,68 @@
{{#zone "topCss"}}
<style>
.thumbnail.icon:before {
padding-top: 0;
}
</style>
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/deviceType.png"/>
{{/zone}}
{{#zone "device-opetations"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<div class="add-margin-top-4x">
{{unit "iot.unit.device.operation-bar" device=device backendApiUri=backendApiUri autoCompleteParams=autoCompleteParams}}
</div>
{{/zone}}
{{#zone "device-detail-properties"}}
<div class="media">
<div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2">
<ul class="list-group" role="tablist">
<li class="active"><a class="list-group-item" href="#device_statistics" role="tab"
data-toggle="tab" aria-controls="device_statistics">Device
Statistics</a>
</li>
<li><a class="list-group-item" href="#event_log" role="tab" data-toggle="tab"
aria-controls="event_log">Operations Log</a></li>
</ul>
</div>
<div class="media-body add-padding-left-5x remove-padding-xs tab-content">
<div class="panel-group tab-content">
<div class="panel panel-default tab-pane active"
id="device_statistics" role="tabpanel" aria-labelledby="device_statistics">
<div class="panel-heading">Device Statistics</div>
{{unit "cdmf.unit.device.type.watertank.realtime.analytics-view" device=device}}
</div>
<div class="panel panel-default tab-pane" id="event_log" role="tabpanel"
aria-labelledby="event_log">
<div class="panel-heading">Operations Log <span><a href="#"
id="refresh-operations"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="operations-spinner" class="wr-advance-operations-init hidden">
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<i class="fw fw-settings fw-spin fw-2x"></i>
&nbsp;&nbsp;&nbsp;
Loading Operations Log . . .
<br>
<br>
</div>
<div id="operations-log-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
</div>
</div>
</div>
{{/zone}}

@ -0,0 +1,41 @@
/*
* 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.
*/
function onRequest(context) {
var log = new Log("cdmf.unit.device.type.watertank.device-view.js");
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id");
var autoCompleteParams = [
{"name": "deviceId", "value": deviceId}
];
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
return {
"device": device,
"backendApiUri": devicemgtProps["httpsURL"] + "/" + deviceType + "/",
"autoCompleteParams": autoCompleteParams
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
exit();
}
}
}

@ -0,0 +1,48 @@
{{!
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.
}}
{{unit "cdmf.unit.lib.rickshaw-graph"}}
<div id="chartWrapper">
</div>
<div id="div-chart" data-websocketurl="{{websocketEndpoint}}">
<div id="chartWrapper-temperature" class="chartWrapper">
<div id="y_axis-temperature" class="custom_y_axis" style="margin-top: -20px;">Temperature</div>
<div id="chart-temperature" class="custom_rickshaw_graph"></div>
<div class="custom_x_axis">Time</div>
</div>
<div id="chartWrapper-humidity" class="chartWrapper">
<div id="y_axis-humidity" class="custom_y_axis" style="margin-top: -20px;">Humidity</div>
<div id="chart-humidity" class="custom_rickshaw_graph"></div>
<div class="custom_x_axis">Time</div>
</div>
</div>
<a class="padding-left"
href="{{@app.context}}/device/{{device.type}}/analytics?deviceId={{device.deviceIdentifier}}&deviceName={{device.name}}">
<span class="fw-stack">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-statistics fw-stack-1x"></i>
</span> View Device Analytics
</a>
<!-- /statistics -->
{{#zone "bottomJs"}}
{{js "js/moment.min.js"}}
{{js "js/socket.io.min.js"}}
{{js "js/device-stats.js"}}
{{/zone}}

@ -0,0 +1,32 @@
/*
* 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.
*/
function onRequest(context) {
var device = context.unit.params.device;
var devicemgtProps = require('/app/conf/devicemgt-props.js').config();
var constants = require("/app/modules/constants.js");
var websocketEndpoint = devicemgtProps["httpsURL"].replace("https", "wss");
var tokenPair = session.get(constants.ACCESS_TOKEN_PAIR_IDENTIFIER);
var token = "";
if (tokenPair) {
token = tokenPair.accessToken;
}
websocketEndpoint = websocketEndpoint + "/secured-outputui/org.wso2.iot.watertank/1.0.0?" +
"token=" + token + "&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type;
return {"device": device, "websocketEndpoint": websocketEndpoint};
}

@ -0,0 +1,128 @@
/*
* 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.
*/
var ws;
var temperature;
var temperatureData = [];
var humidity;
var humidityData = [];
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
$(window).load(function () {
temperature = lineGraph("temperature", temperatureData);
humidity = lineGraph("humidity", humidityData);
var websocketUrl = $("#div-chart").data("websocketurl");
connect(websocketUrl)
});
$(window).unload(function () {
disconnect();
});
function lineGraph(type, chartData) {
var tNow = new Date().getTime() / 1000;
for (var i = 0; i < 30; i++) {
chartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
}
var graph = new Rickshaw.Graph({
element: document.getElementById("chart-" + type),
width: $("#div-chart").width() - 50,
height: 300,
renderer: "line",
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
xScale: d3.time.scale(),
series: [{
'color': palette.color(),
'data': chartData,
'name': type && type[0].toUpperCase() + type.slice(1)
}]
});
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
height: 300,
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis-' + type)
});
new Rickshaw.Graph.HoverDetail({
graph: graph,
formatter: function (series, x, y) {
var date = '<span class="date">' + moment(x * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
}
});
return graph;
}
//websocket connection
function connect(target) {
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
console.log('WebSocket is not supported by this browser.');
}
if (ws) {
ws.onmessage = function (event) {
var dataPoint = JSON.parse(event.data);
if (dataPoint) {
var time = parseInt(dataPoint[0]) / 1000;
graphUpdate(temperatureData, time, dataPoint[3], temperature);
graphUpdate(humidityData, time, dataPoint[4], humidity);
}
};
}
}
function graphUpdate(chartData, xValue, yValue, graph) {
chartData.push({
x: parseInt(xValue),
y: parseFloat(yValue)
});
chartData.shift();
graph.update();
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
}

@ -0,0 +1,7 @@
{
"deviceType": {
"label": "Smart Water Tank",
"category": "iot",
"downloadAgentUri": "watertank/device/download"
}
}

@ -0,0 +1,183 @@
/*
* 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.
*/
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
$('#downloadForm').validate({
rules: {
deviceName: {
minlength: 4,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
$(element).closest('.control-group').removeClass('error').addClass('success');
$('label[for=deviceName]').remove();
}
});
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
}
/*
* hide popup function.
*/
function hidePopup() {
$('label[for=deviceName]').remove();
$('.control-group').removeClass('success').removeClass('error');
$(modalPopupContent).html('');
$(modalPopup).hide();
}
/*
* DOM ready functions.
*/
$(document).ready(function () {
attachEvents();
});
function attachEvents() {
/**
* Following click function would execute
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
var sketchType = $(this).data("sketchtype");
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType};
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
var deviceName;
$("a#download-device-download-link").click(function () {
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
$('label[for=deviceName]').remove();
if (deviceName && deviceName.length >= 4) {
payload.deviceName = deviceName;
invokerUtil.post(
downloadDeviceAPI,
payload,
function (data, textStatus, jqxhr) {
doAction(data);
},
function (data) {
doAction(data);
}
);
} else if (deviceName) {
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">Please enter at least 4 ' +
'characters.</label>');
$('.control-group').removeClass('success').addClass('error');
} else {
$('.controls').append('<label for="deviceName" generated="true" class="error" ' +
'style="display: inline-block;">This field is required.' +
'</label>');
$('.control-group').removeClass('success').addClass('error');
}
});
$("a#download-device-cancel-link").click(function () {
hidePopup();
});
});
}
function downloadAgent() {
var deviceName;
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
if (deviceName && deviceNameFormat.test(deviceName)) {
$('#downloadForm').submit();
hidePopup();
$(modalPopupContent).html($('#device-agent-downloading-content').html());
showPopup();
setTimeout(function () {
hidePopup();
}, 1000);
} else {
$("#invalid-username-error-msg span").text("Invalid device name");
$("#invalid-username-error-msg").removeClass("hidden");
}
}
function doAction(data) {
//if it is saml redirection response
if (data.status == null) {
document.write(data);
}
if (data.status == "200") {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
$(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else if (data == "403") {
$(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () {
hidePopup();
});
}
}

@ -0,0 +1,372 @@
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Smart Water Tank</h1>
<hr>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 padding-top">
<img src="{{@unit.publicUri}}/images/deviceType.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<h3 class="uppercase">What it Does</h3>
<hr>
<p class="grey margin-top">Connect your Smart Water Tank to WSO2 IoT Server.</p>
<br>
<p>An ESP8266 based Smart Water Tank device. Once run, the Smart Water Tank will connect to WSO2 IoTServer
and push Water Levels and Water pump/Supply valve status via MQTT. You can also configure on and off limits for
Water pump/Supply valve remotely with IoTServer.
</p>
<br/>
<h3 class="uppercase">What You Need</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">STEP 01</span>
&nbsp;&nbsp;&nbsp;NodeMCU loaded ESP8266 201 Module.
</li>
<li class="padding-top-double">
<span class="circle">STEP 02</span>
&nbsp;&nbsp;&nbsp;Water level Sensor.
</li>
<li class="padding-top-double">
<span class="circle">STEP 03</span>
&nbsp;&nbsp;&nbsp;Relay to on off Water pump or Supply valve.
</li>
<li class="padding-top-double">
<span class="circle">STEP 04</span>
&nbsp;&nbsp;&nbsp;USB to TTL converter.
</li>
<li class="padding-top-double">
<span class="circle">STEP 05</span>
&nbsp;&nbsp;&nbsp;ESPlorer software. If you don't have please click
<a href="http://esp8266.ru/esplorer-latest/?f=ESPlorer.zip" target="_blank">[here]</a>
to download.
</li>
</ul>
<br/>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
class="btn-operations"
target="_blank"><i class="fw fw-api"></i> View API</i> &nbsp;</a>
<a href="#" class="download-link btn-operations"><i class="fw fw-download"></i>Download
Agent</a>
<div id="download-device-modal-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 center-container">
<h3>Name your device and download the agent from following link.</h3>
<br/>
<form id="downloadForm" method="GET"
action="{{@app.context}}/api/devices/sketch/download">
<div id="invalid-username-error-msg" class="alert alert-danger hidden"
role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<div class="control-group">
<div class="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px"
type="text" placeholder="Ex. Home water tank"
name="deviceName" size="60" required>
<br/>
<input type="hidden" class="deviceType" name="deviceType"
value="watertank"/>
<input type="hidden" class="sketchType" name="sketchType"
value="watertank"/>
</div>
</div>
<div class="buttons" style="padding-bottom: 0px">
<a class="btn btn-operations" onclick="downloadAgent()">Download Now</a>
&nbsp;&nbsp;
</div>
</form>
</div>
</div>
</div>
</div>
<div id="device-agent-downloading-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Agent will download shortly.</h3>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px"
type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-401-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>You have to log in first.</h3><br/>
<div class="buttons">
<a href="#" id="device-401-link" class="blue-button">
Goto Login Page
</a>&nbsp;&nbsp;
<a href="#" onclick="hidePopup();" class="btn-operations">
Cancel
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Action not permitted.</h3><br/>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Sketch does not exist.</h3><br/>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Unexpected error.</h3><br/>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding-double grey-bg">
<h3 class="uppercase">Prepare</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">01</span>
&nbsp;&nbsp;&nbsp;Connect USB to TTL converter and other component with ESP8266 201
module
as schematic in Smart Water Tank SETUP.
</li>
<li class="padding-top-double">
<span class="circle">02</span>
&nbsp;&nbsp;&nbsp;Download Agent files from [Download Agent] link above.
</li>
<li class="padding-top-double">
<span class="circle">03</span>
&nbsp;&nbsp;&nbsp;Unzip the downloaded Smart Water Tank Agent
</li>
<li class="padding-top-double">
<span class="circle">04</span>
&nbsp;&nbsp;&nbsp;Open wifi-connect.lua and provide appropriate values for
<i>[SSID]</i> and
<i>[Password]</i>
variables according to your network.
</li>
<li class="padding-top-double">
<span class="circle">05</span>
&nbsp;&nbsp;&nbsp;Upload all .lua files to ESP8266 using ESPlorer in following order.
Then restart the ESP8266.
<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span>
&nbsp;&nbsp;&nbsp;dht_lib.lua
<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span>
&nbsp;&nbsp;&nbsp;wifi-connect.lua
<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span>
&nbsp;&nbsp;&nbsp;water-tank.lua
<br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span>
&nbsp;&nbsp;&nbsp;init.lua
<br/><br/>
</li>
<li class="padding-top-double">
<span class="circle">06</span>
&nbsp;&nbsp;&nbsp;Now you can remove USB to TTL module and fix Smart Water Tank device in your water tank.
<br/><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span>
&nbsp;&nbsp;&nbsp;ESP8266 will publish water level and Water pump/Valve status to WSO2 IoT Server.
<br/><br/>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"></i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span>
&nbsp;&nbsp;&nbsp;Water levels can be configured from Device Management page to on or off Water pump/Valve.
</li>
</ul>
<br>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Smart Water Tank Setup</h3>
<hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
<img src="{{@unit.publicUri}}/images/schematicsGuide.png" class="img-responsive">
</a>
</center>
<br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Try Out</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double"><span class="circle">01</span>&nbsp;&nbsp;&nbsp;You can view
all your connected
devices at <a
href="{{@app.context}}/devices">[Device
Management]</a>
page.
</li>
<li class="padding-top-double"><span class="circle">02</span>&nbsp;&nbsp;&nbsp;Select one of
connected devices and check for
available control operations.
</li>
</ul>
<br/>
</div>
<style type="text/css">
.circle {
background: none repeat scroll 0 0 #191919;
border-radius: 50px;
height: 50px;
padding: 10px;
width: 50px;
color: #fff;
}
.padding-top-double {
padding-top: 20px;
}
.padding-double {
padding: 20px;
}
.grey {
color: #333;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #7f7f7f;
margin: 1em 0;
padding: 0;
opacity: 0.2;
}
.light-grey {
color: #7c7c7c;
}
.uppercase {
text-transform: uppercase;
}
.grey-bg {
background-color: #f6f4f4;
}
.doc-link {
background: #11375B;
padding: 20px;
color: white;
margin-top: 0;
}
.doc-link a {
color: white;
}
</style>
{{#zone "bottomJs"}}
{{js "/js/download.js"}}
{{js "/js/jquery.validate.js"}}
{{/zone}}

@ -0,0 +1,207 @@
<!--
~ 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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank-feature</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>1.0-SNAPSHOT</version>
<artifactId>${project-base-package}.feature</artifactId>
<packaging>pom</packaging>
<name>${project-base-package}.feature</name>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.api</artifactId>
<version>1.0-SNAPSHOT</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.homeautomation</groupId>
<artifactId>${project-base-package}.analytics</artifactId>
<version>1.0-SNAPSHOT</version>
<type>zip</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/carbonapps
</outputDirectory>
<includes>**/*</includes>
</artifactItem>
<artifactItem>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.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.homeautomation</groupId>
<artifactId>${project-base-package}.api</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>
${project.build.directory}/maven-shared-archive-resources/webapps/
</outputDirectory>
<destFileName>watertank.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>${maven-antrun-plugin.version}</version>
<executions>
<execution>
<id>create-watertank-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<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}/watertankDM_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>
</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>${project-base-package}</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:true</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.homeautomation:${project-base-package}.plugin:1.0-SNAPSHOT
</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,4 @@
tmr.alarm(0, 1000, 0, function()
dofile("wifi-connect.lua");
dofile("read-sensor.lua");
end)

@ -0,0 +1,16 @@
#/*
# * 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.
# */
templates=water-tank.lua
zipfilename=watertank.zip

@ -0,0 +1,76 @@
DHT = require("dht_lib")
dht_data = 2
buzzer = 1
gpio.mode(buzzer, gpio.OUTPUT)
client_connected = false
m = mqtt.Client("ESP8266-" .. node.chipid(), 120, "${DEVICE_TOKEN}", "")
tmr.alarm(0, 10000, 1, function()
DHT.read(dht_data)
local t = DHT.getTemperature()
local h = DHT.getHumidity()
if t == nil then
print("Error reading from DHTxx")
else
if (client_connected) then
local payload = "{event:{metaData:{owner:\"${DEVICE_OWNER}\",deviceId:\"${DEVICE_ID}\"},payloadData:{temperature:" .. t .. ", humidity:" .. h .. "}}}"
m:publish("carbon.super/watertank/${DEVICE_ID}/data", payload, 0, 0, function(client)
print("Published> Temperature: " .. t .. "C Humidity: " .. h .. "%")
end)
else
connectMQTTClient()
end
end
end)
function connectMQTTClient()
local ip = wifi.sta.getip()
if ip == nil then
print("Waiting for network")
else
print("Client IP: " .. ip)
print("Trying to connect MQTT client")
m:connect("${MQTT_EP}", $ { MQTT_PORT } , 0 , function (client)
client_connected = true
print("MQTT client connected")
subscribeToMQTTQueue()
end)
end
end
function subscribeToMQTTQueue()
m: subscribe("carbon.super/watertank/${DEVICE_ID}/command", 0, function(client, topic, message)
print("Subscribed to MQTT Queue")
end)
m: on("message", function(client, topic, message)
print("MQTT message received")
print(message)
buzz(message == "on")
end)
m: on("offline", function(client)
print("Disconnected")
client_connected = false
end)
end
function buzz(status)
local buzzerOn = true
if(status) then
tmr. alarm(1, 500, 1, function()
if buzzerOn then
buzzerOn = false
gpio. write(buzzer, gpio. HIGH)
else
buzzerOn = true
gpio. write(buzzer, gpio. LOW)
end
end)
else
tmr. stop(1)
gpio. write(buzzer, gpio. LOW)
end
end

@ -0,0 +1,2 @@
wifi.setmode(wifi.STATION)
wifi.sta.config("SSID", "Password")

@ -0,0 +1,18 @@
#<!--
# ~ 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.
# -->
custom=true

@ -0,0 +1,24 @@
<?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.
-->
<DeviceTypeConfigurations>
<DeviceTypeConfig type="watertank">
<DatasourceName>jdbc/watertankDM_DB</DatasourceName>
</DeviceTypeConfig>
</DeviceTypeConfigurations>

@ -0,0 +1,47 @@
<?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.
-->
<datasources-configuration>
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>watertankDM_DB</name>
<description>The datasource used for the this device type</description>
<jndiConfig>
<name>jdbc/watertankDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/watertankDM_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 @@
-- -----------------------------------------------------
-- Agent Database
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `watertank_DEVICE` (
`watertank_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`watertank_DEVICE_ID`) );

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

@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS `watertank_DEVICE` (
`watertank_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
PRIMARY KEY (`watertank_DEVICE_ID`) )
ENGINE = InnoDB;

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

@ -0,0 +1,28 @@
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.homeautomation.watertank_${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.homeautomation.watertank_${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/watertank/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.watertank_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/watertank/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.watertank_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/watertank,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.homeautomation.watertank_${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.homeautomation.watertank_${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.homeautomation.watertank_${feature.version}/database/,target:${installFolder}/../../database/,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.homeautomation.watertank_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/device-types/watertank.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/watertank.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/webapps/watertank);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/watertank);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../conf/datasources/watertank-datasources.xml);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../database/watertankDM_DB.h2.db);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.watertank.device-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.watertank.type-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.watertank.realtime.analytics-view);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.watertank.analytics-view);\

@ -0,0 +1,34 @@
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>watertank-feature</artifactId>
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>feature</module>
</modules>
</project>

@ -0,0 +1,418 @@
<?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:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2</groupId>
<artifactId>wso2</artifactId>
<version>1</version>
</parent>
<groupId>org.homeautomation</groupId>
<artifactId>watertank</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>pom</packaging>
<modelVersion>4.0.0</modelVersion>
<url>http://wso2.com</url>
<modules>
<module>component</module>
<module>feature</module>
</modules>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi</artifactId>
<version>${eclipse.osgi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.equinox</groupId>
<artifactId>org.eclipse.equinox.common</artifactId>
<version>${eclipse.equinox.common.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.eclipse.osgi</groupId>
<artifactId>org.eclipse.osgi.services</artifactId>
<version>3.3.100.v20120522-1822</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.logging</artifactId>
<version>${carbon.kernel.version}</version>
<exclusions>
<exclusion>
<groupId>org.apache.log4j.wso2</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.bootstrap</artifactId>
</exclusion>
</exclusions>
<scope>provided</scope>
</dependency>
<!-- CXF dependencies -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>${paho.mqtt.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<version>${javax.ws.rs.version}</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>${org.apache.httpcomponents.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>${project-base-package}.plugin</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
<version>${carbon.kernel.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<version>${carbon.device.mgt.plugin.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.api</artifactId>
<version>${carbon.analytics.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
<version>${carbon.analytics.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.dataservice.commons</artifactId>
<version>${carbon.analytics.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics</groupId>
<artifactId>org.wso2.carbon.analytics.dataservice.core</artifactId>
<version>${carbon.analytics.version}</version>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<version>${commons-httpclient.orbit.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<version>${carbon.kernel.version}</version>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
<version>${smack.wso2.version}</version>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<version>${smackx.wso2.version}</version>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
<version>${commons-json.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
<version>${carbon.device.mgt.version}</version>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<version>1.2.140.wso2v3</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
<version>${carbon.analytics.common.version}</version>
</dependency>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
<version>${commons-codec.wso2.version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<pluginRepositories>
<pluginRepository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2.snapshots</id>
<name>Apache Snapshot Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</pluginRepository>
<pluginRepository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</pluginRepository>
</pluginRepositories>
<repositories>
<!-- Before adding ANYTHING in here, please start a discussion on the dev list.
Ideally the Axis2 build should only use Maven central (which is available
by default) and nothing else. We had troubles with other repositories in
the past. Therefore configuring additional repositories here should be
considered very carefully. -->
<repository>
<id>wso2-nexus</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
<repository>
<id>wso2.releases</id>
<name>WSO2 internal Repository</name>
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
</repository>
</repositories>
<properties>
<!-- Carbon Analytics -->
<carbon.analytics.common.version>5.0.11</carbon.analytics.common.version>
<carbon.analytics.common.version.range>[5.0.11,6.0.0)</carbon.analytics.common.version.range>
<carbon.analytics.version.range>[1.0.5,2.0.0]</carbon.analytics.version.range>
<carbon.analytics.version>1.0.6-ALPHA</carbon.analytics.version>
<!-- Carbon Device Management -->
<carbon.device.mgt.version>1.1.0</carbon.device.mgt.version>
<carbon.device.mgt.plugin.version>2.1.0</carbon.device.mgt.plugin.version>
<carbon.commons.version>4.4.8</carbon.commons.version>
<carbon.kernel.version>4.4.3</carbon.kernel.version>
<carbon-p2-plugin.version>1.5.3</carbon-p2-plugin.version>
<org.apache.httpcomponents.version>4.1</org.apache.httpcomponents.version>
<project-base-package>${project.groupId}.watertank</project-base-package>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<maven-clean-plugin.version>2.4.1</maven-clean-plugin.version>
<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
<maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
<maven-scr-plugin.version>1.7.2</maven-scr-plugin.version>
<maven-assembly-plugin.version>2.5.5</maven-assembly-plugin.version>
<!--Orbit versions-->
<orbit.h2.engine.version>1.2.140.wso2v3</orbit.h2.engine.version>
<commons-json.version.range>(3.0.0, 4.0.0]</commons-json.version.range>
<commons-codec.wso2.version>1.4.0.wso2v1</commons-codec.wso2.version>
<commons-json.version>3.0.0.wso2v1</commons-json.version>
<commons-io.version>2.4</commons-io.version>
<commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.version>
<jackson.version>1.9.0</jackson.version>
<!--XMPP/MQTT Version-->
<smack.wso2.version>3.0.4.wso2v1</smack.wso2.version>
<smackx.wso2.version>3.0.4.wso2v1</smackx.wso2.version>
<paho.mqtt.version>1.0.2</paho.mqtt.version>
<cxf.version>2.6.1</cxf.version>
<javaee-web-api.version>6.0</javaee-web-api.version>
<javax.ws.rs.version>1.1.1</javax.ws.rs.version>
<junit.version>3.8.1</junit.version>
<eclipse.equinox.common.version>3.6.100.v20120522-1841</eclipse.equinox.common.version>
<h2-database-engine>1.2.140.wso2v3</h2-database-engine>
<eclipse.osgi.version>3.8.1.v20120830-144521</eclipse.osgi.version>
<org.apache.felix.version>1.4.0</org.apache.felix.version>
<org.eclipse.osgi.services.version>3.3.100.v20120522-1822</org.eclipse.osgi.services.version>
<eclipse.equinox.common.version>3.6.100.v20120522-1841</eclipse.equinox.common.version>
</properties>
</project>
Loading…
Cancel
Save