merge with upstream

application-manager-new
ayyoob 9 years ago
commit af5d6250fc

@ -218,7 +218,6 @@ d <exclude name="**/shindig.properties" /
<exclude name="**/digitaldisplay/**" />
<exclude name="**/doormanager/**" />
<exclude name="**/droneanalyzer/**" />
<exclude name="**/firealarm/**" />
<exclude name="**/installer/**" />
</fileset>
</copy>

@ -0,0 +1,63 @@
<api xmlns="http://ws.apache.org/ns/synapse" name="_WSO2APIRegistrationApplication_" context="/api-application-registration">
<resource methods="POST" url-mapping="/register/tenants" faultSequence="_api_registration_fault_">
<inSequence>
<property name="uri.var.portnum" expression="get-property('keyManager.port')"/>
<property name="uri.var.hostname" expression="get-property('keyManager.hostname')"/>
<send>
<endpoint>
<http uri-template="https://{uri.var.hostname}:{uri.var.portnum}/api-application-registration">
<timeout>
<duration>60000</duration>
<responseAction>fault</responseAction>
</timeout>
</http>
</endpoint>
</send>
</inSequence>
<outSequence>
<send/>
</outSequence>
</resource>
<resource methods="POST" url-mapping="/register" faultSequence="_api_registration_fault_">
<inSequence>
<property name="uri.var.portnum" expression="get-property('keyManager.port')"/>
<property name="uri.var.hostname" expression="get-property('keyManager.hostname')"/>
<send>
<endpoint>
<http uri-template="https://{uri.var.hostname}:{uri.var.portnum}/api-application-registration">
<timeout>
<duration>60000</duration>
<responseAction>fault</responseAction>
</timeout>
</http>
</endpoint>
</send>
</inSequence>
<outSequence>
<send/>
</outSequence>
</resource>
<resource methods="DELETE" url-mapping="/unregister" faultSequence="_api_registration_fault_">
<inSequence>
<property name="uri.var.portnum" expression="get-property('keyManager.port')"/>
<property name="uri.var.hostname" expression="get-property('keyManager.hostname')"/>
<send>
<endpoint>
<http uri-template="https://{uri.var.hostname}:{uri.var.portnum}/api-application-registration">
<timeout>
<duration>60000</duration>
<responseAction>fault</responseAction>
</timeout>
</http>
</endpoint>
</send>
</inSequence>
<outSequence>
<send/>
</outSequence>
</resource>
<handlers>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerCacheExtensionHandler"/>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.common.SynapsePropertiesHandler"/>
</handlers>
</api>

@ -0,0 +1,25 @@
<api xmlns="http://ws.apache.org/ns/synapse" name="_WSO2DCRAPI_" context="/dcr">
<resource methods="POST DELETE" url-mapping="/register" faultSequence="_dcr_fault_">
<inSequence>
<property name="uri.var.portnum" expression="get-property('keyManager.port')"/>
<property name="uri.var.hostname" expression="get-property('keyManager.hostname')"/>
<send>
<endpoint>
<http uri-template="https://{uri.var.hostname}:{uri.var.portnum}/dynamic-client-web/register">
<timeout>
<duration>60000</duration>
<responseAction>fault</responseAction>
</timeout>
</http>
</endpoint>
</send>
</inSequence>
<outSequence>
<send/>
</outSequence>
</resource>
<handlers>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.ext.APIManagerCacheExtensionHandler"/>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.common.SynapsePropertiesHandler"/>
</handlers>
</api>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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.
-->
<sequence xmlns="http://ws.apache.org/ns/synapse" name="_api_registration_fault_">
<property name="ERROR_MESSAGE" value="Error occurred while invoking api application registration endpoint"/>
<sequence key="fault"/>
</sequence>

@ -0,0 +1,22 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://wso2.com) 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.
-->
<sequence xmlns="http://ws.apache.org/ns/synapse" name="_dcr_fault_">
<property name="ERROR_MESSAGE" value="Error occurred while invoking dynamic client registration endpoint"/>
<sequence key="fault"/>
</sequence>

@ -729,12 +729,6 @@
</outputDirectory>
<fileMode>755</fileMode>
</file>
<file>
<source>src/repository/jaggeryapps/ues/configs/designer.json</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/deployment/server/jaggeryapps/portal/configs
</outputDirectory>
<fileMode>755</fileMode>
</file>
<!-- End of "portal" app specific modifications -->
<!-- Copying synapse.properties file -->
<file>
@ -1325,15 +1319,13 @@
<filtered>true</filtered>
<fileMode>644</fileMode>
</file>
<!-- Copying virtual-fire-alarm-config.xml -->
<!--<file>-->
<!--<source>-->
<!--../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/conf/etc/device-mgt-plugins/virtual-fire-alarm/virtual-fire-alarm-config.xml-->
<!--</source>-->
<!--<outputDirectory>${pom.artifactId}-${pom.version}/repository/conf/etc/device-mgt-plugins/virtual-fire-alarm</outputDirectory>-->
<!--<filtered>true</filtered>-->
<!--<fileMode>644</fileMode>-->
<!--</file>-->
<!-- Adding IoT Analytics Dashboard and gadget CApps -->
<file>
<source>
../p2-profile-gen/target/wso2carbon-core-${carbon.kernel.version}/repository/deployment/server/carbonapps/org_wso2_carbon_analytics_cdmf-1.0.0.car
</source>
<outputDirectory>${pom.artifactId}-${pom.version}/repository/deployment/server/carbonapps/</outputDirectory>
<fileMode>644</fileMode>
</file>
</files>
</assembly>

@ -79,6 +79,9 @@
<Role>${default.server.role}</Role>
<Role>${das.server.role}</Role>
<Role>${cep.server.role}</Role>
<Role>IoTServer</Role>
<Role>CDMFPlatform</Role>
<Role>GeoDashboard</Role>
</ServerRoles>
<!-- uncommnet this line to subscribe to a bam instance automatically -->

@ -685,8 +685,7 @@
<featureArtifactDef>
org.wso2.carbon.analytics-common:org.wso2.carbon.event.execution.manager.feature:${carbon.analytics.common.version}
</featureArtifactDef>
<featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.commons:org.wso2.carbon.deployment.synchronizer.feature:${carbon.commons.version}
</featureArtifactDef>
<!--End of DAS Feature-->
@ -708,6 +707,13 @@
<featureArtifactDef>
org.wso2.carbon.identity:org.wso2.carbon.identity.oauth2.grant.jwt.feature:${identity.jwt.extension.version}
</featureArtifactDef>
<!-- Analytics related features -->
<featureArtifactDef>
org.wso2.carbon.devicemgt:org.wso2.carbon.device.mgt.analytics.dashboard.feature:${carbon.device.mgt.version}
</featureArtifactDef>
<featureArtifactDef>
org.wso2.carbon.analytics.cdmf:org.wso2.carbon.analytics.cdmf.feature:${cdmf.analytics.version}
</featureArtifactDef>
</featureArtifacts>
</configuration>
</execution>
@ -1513,6 +1519,15 @@
<id>org.wso2.carbon.identity.oauth2.grant.jwt.feature.group</id>
<version>${identity.jwt.extension.version}</version>
</feature>
<!-- Analytics related features -->
<feature>
<id>org.wso2.carbon.device.mgt.analytics.dashboard.feature.group</id>
<version>${carbon.device.mgt.version}</version>
</feature>
<feature>
<id>org.wso2.carbon.analytics.cdmf.feature.group</id>
<version>${cdmf.analytics.version}</version>
</feature>
</features>
</configuration>
</execution>

@ -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 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="sensor_dir" value="droneStats"/>
<target name="clean">
<delete dir="${target-dir}" />
</target>
<target name="zip" depends="clean">
<mkdir dir="${target-dir}"/>
<zip destfile="${target-dir}/${sensor_dir}.car">
<zipfileset dir="${src-dir}/${sensor_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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>droneanalyzer-component</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.droneanalyzer.analytics</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name> ${groupId}.droneanalyzer.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.0</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="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
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,25 @@
<?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="EventPublisher_droneStats" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="org.wso2.iot.devices.droneStats" version="1.0.0"/>
<mapping customMapping="disable" type="wso2event"/>
<to eventAdapterType="iot-ui"/>
</eventPublisher>

@ -17,7 +17,6 @@
~ under the License.
-->
<artifact name="Eventreceiver_humidity" version="1.0.0" type="event/receiver"
serverRole="DataAnalyticsServer">
<file>EventReceiver_humidity.xml</file>
<artifact name="Eventpublisher_droneStats" version="1.0.0" type="event/publisher" serverRole="DataAnalyticsServer">
<file>EventPublisher_droneStats.xml</file>
</artifact>

@ -0,0 +1,32 @@
<?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="droneStats-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="topic">carbon.super/drone/+/publisher</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.devices.droneStats" version="1.0.0"/>
</eventReceiver>

@ -17,7 +17,6 @@
~ under the License.
-->
<artifact name="Eventreceiver_temperature" version="1.0.0" type="event/receiver"
serverRole="DataAnalyticsServer">
<file>EventReceiver_temperature.xml</file>
<artifact name="Eventreceiver_mqtt_droneStats" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>EventReceiver_mqtt_droneStats.xml</file>
</artifact>

@ -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="Eventstore_droneStats" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_droneStats.xml</file>
</artifact>

@ -0,0 +1,159 @@
<?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.droneStats: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>quatanium_val_q1</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>quatanium_val_q2</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>quatanium_val_q3</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>quatanium_val_q4</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>velocity_x</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>velocity_y</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>velocity_z</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>global_location_lat</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>global_location_alt</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>global_location_lon</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>battery_level</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>battery_voltage</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>pitch</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>roll</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>yaw</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>DOUBLE</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="Eventstream_droneStats" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.droneStats_1.0.0.json</file>
</artifact>

@ -0,0 +1,29 @@
{
"name": "org.wso2.iot.devices.droneStats",
"version": "1.0.0",
"nickName": "droneStats",
"description": "droneStats data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{"name": "quatanium_val_q1", "type": "DOUBLE"},
{"name": "quatanium_val_q2", "type": "DOUBLE"},
{"name": "quatanium_val_q3", "type": "DOUBLE"},
{"name": "quatanium_val_q4", "type": "DOUBLE"},
{"name": "velocity_x", "type": "DOUBLE"},
{"name": "velocity_y", "type": "DOUBLE"},
{"name": "velocity_z", "type": "DOUBLE"},
{"name": "global_location_lat", "type": "DOUBLE"},
{"name": "global_location_alt", "type": "DOUBLE"},
{"name": "global_location_lon", "type": "DOUBLE"},
{"name": "battery_level", "type": "DOUBLE"},
{"name": "battery_voltage", "type": "DOUBLE"},
{"name": "pitch", "type": "DOUBLE"},
{"name": "roll", "type": "DOUBLE"},
{"name": "yaw", "type": "DOUBLE"}
]
}

@ -17,7 +17,6 @@
~ under the License.
-->
<artifact name="Sparkscripts" version="1.0.0" type="analytics/spark"
serverRole="DataAnalyticsServer">
<file>Humidity_Sensor_Script.xml</file>
<artifact name="Sparkscripts" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>droneStats_Script.xml</file>
</artifact>

@ -0,0 +1,28 @@
<?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>IoTServer_Sensor_Script</Name>
<Script>
CREATE TEMPORARY TABLE DevicedroneStatsData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_droneStats");
CREATE TEMPORARY TABLE DevicedroneStatsSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_droneStats_SUMMARY", schema "quatanium_val_q1 DOUBLE -i,quatanium_val_q2 DOUBLE -i,quatanium_val_q3 DOUBLE -i,quatanium_val_q4 DOUBLE -i,velocity_x DOUBLE -i,velocity_y DOUBLE -i,velocity_z DOUBLE -i,global_location_lat DOUBLE -i,global_location_alt DOUBLE -i,global_location_lon DOUBLE -i,battery_level DOUBLE -i,battery_voltage DOUBLE -i,pitch DOUBLE -i,roll DOUBLE -i,yaw DOUBLE -i, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert into table DevicedroneStatsSummaryData select quatanium_val_q1,quatanium_val_q2,quatanium_val_q3,quatanium_val_q4,velocity_x,velocity_y,velocity_z,global_location_lat,global_location_alt,global_location_lon,battery_level,battery_voltage,pitch,roll,yaw, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT) as time from DevicedroneStatsData group by meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT),quatanium_val_q1,quatanium_val_q2,quatanium_val_q3,quatanium_val_q4,velocity_x,velocity_y,velocity_z,global_location_lat,global_location_alt,global_location_lon,battery_level,battery_voltage,pitch,roll,yaw ;
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -18,16 +18,11 @@
-->
<artifacts>
<artifact name="Humidity_Sensor_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="Eventstream_humidity" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventstore_humidity" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventreceiver_humidity" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/>
<dependency artifact="Sparkscripts" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/>
<artifact name="droneStats_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="Eventstream_droneStats" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventstore_droneStats" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventreceiver_mqtt_droneStats" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventpublisher_droneStats" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Sparkscripts" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -16,44 +17,53 @@
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>droneanalyzer-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${groupId}.droneanalyzer.api</artifactId>
<version>2.1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>${groupId}.droneanalyzer API</name>
<url>http://wso2.com</url>
<dependencies>
<!-- CDM -->
<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>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<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>droneanalyzer-component</artifactId>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>${project-base-package}.api</artifactId>
<version>1.0.0</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>
@ -62,220 +72,102 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</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>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</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.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl</artifactId>
<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>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</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</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<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>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</dependency>
<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>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
</dependency>
<dependency>
<groupId>org.homeautomation</groupId>
<artifactId>org.homeautomation.droneanalyzer.plugin</artifactId>
</dependency>
<dependency>
<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.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>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<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>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<!--plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin-->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>drone_analyzer</warName>
</configuration>
</plugin>
</plugins>
</build>
</dependencies>
</project>

@ -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.droneanalyzer.api;
import org.homeautomation.droneanalyzer.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 API which is used to control and manage device type functionality
*/
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "drone", version = "1.0.0", context = "/drone", tags = "drone")
@DeviceType(value = "drone")
public interface DroneAnalyzerService {
/**
* @param agentInfo device owner,id
* @return true if device instance is added to map
*/
@Path("device/register")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/user/register"})
Response registerDevice(final DeviceJSON agentInfo);
/**
* Retrieve Sensor data for the given time period
* @param deviceId unique identifier for given device type instance
* @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}")
@GET
@Consumes("application/json")
@Produces("application/json")
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/stats"})
Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to);
/**
* Remove device type instance using device id
* @param deviceId unique identifier for given device type instance
*/
@Path("/device/{device_id}")
@DELETE
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/removeDevice"})
Response removeDevice(@PathParam("device_id") String deviceId);
/**
* Update device instance name
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
*/
@Path("/device/{device_id}")
@PUT
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
/**
* To get device information
* @param deviceId unique identifier for given device type instance
* @return
*/
@Path("/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/updateDevice"})
Response getDevice(@PathParam("device_id") String deviceId);
/**
* 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)
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/devices"})
Response getAllDevices();
/**
* 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")
@Permission(scope = "drone_user", permissions = {"/permission/admin/device-mgt/download"})
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
}

@ -0,0 +1,382 @@
/*
* 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.droneanalyzer.api;
import org.homeautomation.droneanalyzer.api.dto.DeviceJSON;
import org.homeautomation.droneanalyzer.api.dto.SensorRecord;
import org.homeautomation.droneanalyzer.api.util.APIUtil;
import org.homeautomation.droneanalyzer.api.util.ZipUtil;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.api.DroneAnalyzerService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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.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;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
/**
* This is the API which is used to control and manage device type functionality
*/
@SuppressWarnings("NonJaxWsWebServices")
@API(name = "drone", version = "1.0.0", context = "/drone", tags = "drone")
@DeviceType(value = "drone")
public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
private static final String KEY_TYPE = "PRODUCTION";
private static Log log = LogFactory.getLog(DroneAnalyzerService.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();
}
/**
* Retrieve Sensor data for the given time period
* @param deviceId unique identifier for given device type instance
* @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}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "meta_deviceId:" + deviceId + " AND meta_deviceType:" +
DroneAnalyzerConstants.DEVICE_TYPE + " AND meta_time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = DroneAnalyzerConstants.SENSOR_EVENT_TABLE;
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DroneAnalyzerConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
if (sensorTableName != null) {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("meta_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();
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
/**
* Remove device type instance using device id
* @param deviceId unique identifier for given device type instance
*/
@Path("/device/{device_id}")
@DELETE
public Response removeDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneAnalyzerConstants.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/{device_id}")
@PUT
public Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneAnalyzerConstants.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(DroneAnalyzerConstants.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/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getDevice(@PathParam("device_id") String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneAnalyzerConstants.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> userDevicesforFirealarm = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DroneAnalyzerConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforFirealarm.add(device);
}
}
Device[] devices = userDevicesforFirealarm.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(DroneAnalyzerConstants.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(DroneAnalyzerConstants.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 = {DroneAnalyzerConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DroneAnalyzerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DroneAnalyzerConstants.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.droneanalyzer.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.droneanalyzer.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 drone.
*/
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class SensorRecord {
@XmlElementWrapper(required = true, name = "values")
private Map<String, Object> values;
/**
* The id.
*/
@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 the 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 the new id
*/
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.droneanalyzer.api.exception;
public class DroneAnalyzerException extends Exception {
private static final long serialVersionUID = 2736466230451105441L;
private String errorMessage;
public DroneAnalyzerException(String msg, DroneAnalyzerException nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DroneAnalyzerException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DroneAnalyzerException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DroneAnalyzerException() {
super();
}
public DroneAnalyzerException(Throwable cause) {
super(cause);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -0,0 +1,221 @@
package org.homeautomation.droneanalyzer.api.util;
import org.homeautomation.droneanalyzer.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 virtual_firealarm.", 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;
}
}

@ -15,15 +15,18 @@
* specific language governing permissions and limitations
* under the License.
*/
$("#module_control button").click(function (index) {
console.log("Asking Server to send the " + $(this).attr('id') + " command to Ar Drone");
var url = config_api.drone_control;
ajax_handler.ajaxRequest(url, config_api.drone_controlType, {action: $(this).attr('id'), speed: 7, duration: 7},
config_api.drone_controlDataType, function (data, status) {
console.log(JSON.stringify(data));
}
);
});
package org.homeautomation.droneanalyzer.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/drone/user";
public static final String DEFAULT_ROLE_NAME = "drone_user";
public static final Permission DEFAULT_PERMISSION[]
= new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
}

@ -0,0 +1,108 @@
/*
* 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.droneanalyzer.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ResponsePayload {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public static ResponsePayloadBuilder statusCode(int statusCode) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().statusCode(statusCode);
}
public static ResponsePayloadBuilder messageFromServer(
String messageFromServer) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().messageFromServer(messageFromServer);
}
public static ResponsePayloadBuilder responseContent(String responseContent) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().responseContent(responseContent);
}
@XmlElement
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@XmlElement
public String getMessageFromServer() {
return messageFromServer;
}
public void setMessageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
}
@XmlElement
public Object getResponseContent() {
return responseContent;
}
public void setResponseContent(Object responseContent) {
this.responseContent = responseContent;
}
private ResponsePayloadBuilder getBuilder() {
return new ResponsePayloadBuilder();
}
public class ResponsePayloadBuilder {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public ResponsePayloadBuilder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public ResponsePayloadBuilder messageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
return this;
}
public ResponsePayloadBuilder responseContent(String responseContent) {
this.responseContent = responseContent;
return this;
}
public ResponsePayload build() {
ResponsePayload payload = new ResponsePayload();
payload.setStatusCode(statusCode);
payload.setMessageFromServer(messageFromServer);
payload.setResponseContent(responseContent);
return payload;
}
}
}

@ -0,0 +1,58 @@
/*
* 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.droneanalyzer.api.util;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
/**
* This can be used to publish data to DAS for given stream definition
*/
public class ServiceUtils {
private static final Log log = LogFactory.getLog(ServiceUtils.class);
/**
* Sensor data are published to DAS
*
* @param deviceId unique identifier of the device
* @param sensorValue current value of sensor which is set at agent side
* @return
*/
public static boolean publishToDAS(String deviceId, float sensorValue) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService(
EventsPublisherService.class, null);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Object metdaData[] = {owner, DroneAnalyzerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadData[] = {sensorValue};
try {
deviceAnalyticsService.publishEvent(DroneAnalyzerConstants.SENSOR_STREAM_DEFINITION,
DroneAnalyzerConstants.SENSOR_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
}
return true;
}
}

@ -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.
*/
package org.homeautomation.droneanalyzer.api.util;
import org.homeautomation.droneanalyzer.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);
}
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", mqttEndpoint);
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);
}
}
}

@ -1,46 +0,0 @@
/*
* 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.droneanalyzer.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@API(name = "drone_analyzer", version = "1.0.0", context = "/drone_analyzer", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer")
public interface DroneControllerService {
@Path("device/register/{deviceId}/{ip}/{port}")
@POST
Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort);
@Path("device/{deviceId}/send_command")
@POST
/*@Feature( code="send_command", name="Send Command", type="operation",
description="Send Commands to Drone")*/
Response droneController(@PathParam("deviceId") String deviceId, @FormParam("action") String action,
@FormParam("duration") String duration, @FormParam("speed") String speed);
}

@ -1,55 +0,0 @@
/*
* 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.droneanalyzer.api;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.util.DroneAnalyzerServiceUtils;
import org.homeautomation.droneanalyzer.plugin.controller.DroneController;
import org.homeautomation.droneanalyzer.plugin.controller.impl.DroneControllerImpl;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
public class DroneControllerServiceImpl implements DroneControllerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneControllerServiceImpl.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private DroneController droneController = new DroneControllerImpl();
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort) {
String result;
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok(Response.Status.OK.getStatusCode()).build();
}
public Response droneController(String deviceId, String action, String duration, String speed) {
try {
DroneAnalyzerServiceUtils.sendControlCommand(droneController, deviceId, action, Double.valueOf(speed),
Double.valueOf(duration));
return Response.status(Response.Status.ACCEPTED).build();
} catch (DeviceManagementException e) {
log.error("Drone command didn't success. Try again, \n" + e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
}

@ -1,69 +0,0 @@
/*
* 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.droneanalyzer.api;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
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.Response;
@API(name = "drone_analyzer_mgt", version = "1.0.0", context = "/drone_analyzer_mgt", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer")
public interface DroneManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDroneDevices();
@Path("devices/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String sketchType);
@Path("devices/{sketch_type}/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType);
}

@ -1,259 +0,0 @@
/*
* 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.droneanalyzer.api;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.util.APIUtil;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
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.iot.controlqueue.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.JWTClientManager;
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.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class DroneManagerServiceImpl implements DroneManagerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.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(DroneConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
public Response removeDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
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) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response updateDevice(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DroneConstants.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) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDroneDevices() {
try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforDrone = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DroneConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(
EnrolmentInfo.Status.ACTIVE)) {
userDevicesforDrone.add(device);
}
}
Device[] devices = userDevicesforDrone.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response downloadSketch(String deviceName, String sketchType) {
//create new device id
String deviceId = shortUUID();
//create token
String token = UUID.randomUUID().toString();
String refreshToken = UUID.randomUUID().toString();
//adding registering data
boolean status = register(deviceId, deviceName);
if (!status) {
return Response.status(500).entity(
"Error occurred while registering the device with " + "id: " + deviceId + " owner:" +
APIUtil.getAuthenticatedUser()).build();
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile;
try {
zipFile = ziputil.createZipFile(APIUtil.getAuthenticatedUser(), APIUtil.getTenantDomainOftheUser(),
sketchType, deviceId, deviceName, token, refreshToken);
} catch (DeviceManagementException ex) {
return Response.status(500).entity("Error occurred while creating zip file").build();
}
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
}
public Response generateSketchLink(String deviceName, String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(deviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException,
UserStoreException {
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DroneConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DroneConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String scopes = "device_type_" + DroneConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(APIUtil.getAuthenticatedUser() + "_" + deviceId);
newXmppAccount.setUsername(deviceId);
newXmppAccount.setPassword(accessToken);
newXmppAccount.setEmail(deviceId + "@wso2.com");
XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue();
boolean status;
if (XmppConfig.getInstance().isEnabled()) {
status = xmppServerClient.createXMPPAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " +
APIUtil.getAuthenticatedUser() + ".XMPP might have been disabled in " +
"org.wso2.carbon.device.mgt.iot.common.config.server.configs";
log.warn(msg);
throw new DeviceManagementException(msg);
}
}
//Register the device with CDMF
status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + APIUtil.getAuthenticatedUser();
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(APIUtil.getAuthenticatedUser(), APIUtil.getTenantDomainOftheUser(),
sketchType, deviceId, deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
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);
}
}

@ -1,125 +0,0 @@
/*
* 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.droneanalyzer.api;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.transport.DroneAnalyzerXMPPConnector;
import org.homeautomation.droneanalyzer.api.trasformer.MessageTransformer;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@ServerEndpoint("/datastream/drone_status")
public class DroneRealTimeService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneRealTimeService.class);
private MessageTransformer messageController;
private DroneAnalyzerXMPPConnector xmppConnector;
public DroneRealTimeService() {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
messageController = new MessageTransformer();
xmppConnector = new DroneAnalyzerXMPPConnector(messageController);
if (XmppConfig.getInstance().isEnabled()){
xmppConnector.connect();
} else {
log.warn("XMPP disabled in 'devicemgt-config.xml'. Hence, DroneAnalyzerXMPPConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
@OnOpen
public void onOpen(Session session){
log.info(session.getId() + " has opened a connection");
try {
session.getBasicRemote().sendText("Connection Established");
} catch (IOException e) {
log.error( e.getMessage()+"\n"+ e);
}
}
@OnMessage
public void onMessage(String message, Session session){
while (true) {
try {
if (messageController != null && !messageController.isEmptyQueue()) {
String messageControllerMessage = messageController.getMessage();
session.getBasicRemote().sendText(messageControllerMessage);
break;
}
Thread.sleep(DroneConstants.MINIMUM_TIME_DURATION);
} catch (IOException | InterruptedException ex) {
log.error(ex.getMessage(), ex);
break;
}
}
}
@OnClose
public void onClose(Session session){
try {
xmppConnector.disconnect();
log.info("XMPP connection is disconnected");
}
catch (Exception e) {
log.error(e.getMessage() + "\n" + e);
}
log.info("Session " + session.getId() + " has ended");
}
@OnError
public void onError(Session session, Throwable t) {
try {
session.getBasicRemote().sendText("Connection closed");
xmppConnector.disconnect();
log.info("XMPP connection is disconnected");
} catch (Exception e) {
log.error(e.getMessage()+"\n"+ e);
}
log.info("Session " + session.getId() + " has ended");
}
}

@ -1,32 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.exception;
public class DroneAnalyzerException extends Exception {
private static final long serialVersionUID = 118512086958330189L;
public DroneAnalyzerException(String errorMessage) {
super(errorMessage);
}
public DroneAnalyzerException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

@ -1,160 +0,0 @@
/*
* 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.droneanalyzer.api.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.trasformer.MessageTransformer;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.jivesoftware.smack.packet.Message;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.xmpp.XMPPTransportHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class DroneAnalyzerXMPPConnector extends XMPPTransportHandler {
private static Log log = LogFactory.getLog(DroneAnalyzerXMPPConnector.class);
private static String xmppServerIP;
private static String xmppAdminUsername;
private static String xmppAdminPassword;
private static String xmppAdminAccountJID;
private MessageTransformer messageTransformer;
private ScheduledFuture<?> connectorServiceHandler;
private ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
public DroneAnalyzerXMPPConnector(MessageTransformer messageTransformer) {
super(XmppConfig.getInstance().getXmppServerIP(), XmppConfig.getInstance().getSERVER_CONNECTION_PORT());
this.messageTransformer = messageTransformer;
}
@Override
public void connect() {
Runnable connector = new Runnable() {
@Override
public void run() {
if (!isConnected()) {
try {
initConnector();
connectToServer();
loginToServer(xmppAdminUsername, xmppAdminPassword, null);
setFilterOnReceiver(xmppAdminAccountJID);
} catch (TransportHandlerException e) {
if (log.isDebugEnabled()) {
log.warn("Connection/Login to XMPP server at: " + server + " as " +
xmppAdminUsername + " failed for device-type [" +
DroneConstants.DEVICE_TYPE + "].", e);
}
}
}
}
};
connectorServiceHandler = service.scheduleAtFixedRate(connector, 0, timeoutInterval, TimeUnit.MILLISECONDS);
}
public void initConnector() {
xmppServerIP = XmppConfig.getInstance().getXmppServerIP();
xmppAdminUsername = XmppConfig.getInstance().getXmppUsername();
xmppAdminPassword = XmppConfig.getInstance().getXmppPassword();
xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP;
}
@Override
public void processIncomingMessage(Message message) throws TransportHandlerException {
try {
String from = message.getFrom();
String inboundMessage = message.getBody();
int indexOfSlash = from.indexOf("/");
if (indexOfSlash == 0) {
if (log.isDebugEnabled()) {
log.debug("Required resource not available.");
}
} else {
String resource = from.substring(indexOfSlash + 1, from.length());
if ((inboundMessage != null) && (resource.equals(DroneConstants.MESSAGE_RESOURCE))) {
messageTransformer.messageTranslater(inboundMessage);
} else {
if (log.isDebugEnabled()) {
log.debug("Message is empty or it is not belongs to " + xmppAdminUsername);
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
log.error("Wrong message format: input message", e);
} catch (RuntimeException e) {
log.error("Unexpected error has been occurred, ", e);
}
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
String xmppJID = publishData[0];
String xmppMessage = publishData[1];
String xmppSubject = publishData[2];
sendXMPPMessage(xmppJID, xmppMessage, xmppSubject);
}
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
connectorServiceHandler.cancel(true);
closeConnection();
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' connection to XMPP server at: " + server +
" for user - " + xmppAdminUsername);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("XMPP-Terminator: Thread Sleep Interrupt Exception for "
+ DroneConstants.DEVICE_TYPE + " type.", e1);
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void processIncomingMessage() throws TransportHandlerException {
}
@Override
public void processIncomingMessage(Message message, String... messageParams) throws TransportHandlerException {
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(Message publishData) throws TransportHandlerException {
}
}

@ -1,134 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.trasformer;
import org.apache.commons.collections4.queue.CircularFifoQueue;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.constants.MessageConfig;
import java.io.IOException;
public class MessageTransformer {
private Log log = LogFactory.getLog(MessageTransformer.class);
private CircularFifoQueue<String> sharedQueue;
private String outboundMessageFormatForSimulator = "{\"quatanium_val\":[%f, %f, %f, %f]," +
"\"basicParam\":{\"velocity\":[%f, %f, %f], \"global_location\":[%f, %f, %f]},\"battery_level\":%f, \"device_type\":\"SIMULATOR\"}";
private String outboundMessageFormatForIrisDrone = "{\"quatanium_val\":[%f, %f, %f]," +
"\"basicParam\":{\"velocity\":[%f, %f, %f], \"global_location\":[%f, %f, %f]},\"battery_level\":%f," +
"\"device_type\":\"IRIS_DRONE\"}";
public MessageTransformer(){
sharedQueue = new CircularFifoQueue<String>(DroneConstants.MAXIMUM_BUFFERE_SIZE_OF_SHARED_QUEUE);
}
private void messageTranslaterForSimulator(JsonNode inbound_message){
JsonNode node = inbound_message;
String outboundMessage;
try {
JsonNode velocity = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(MessageConfig.OUT_BASIC_PARAM_VELOCITY);
JsonNode globalLocation = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(
MessageConfig.OUT_BASIC_PARAM_GLOBAL_LOCATION);
JsonNode quataniumVals = node.get(MessageConfig.OUT_QUATANNIM_VAL);
JsonNode batteryLevel = node.get(MessageConfig.OUT_BATTERY_LEVEL);
outboundMessage = String.format(outboundMessageFormatForSimulator, sTd(quataniumVals.get(0)),
sTd(quataniumVals.get(1)), sTd(quataniumVals.get(2)), sTd(quataniumVals.get(0)),
sTd(velocity.get(0)), sTd(velocity.get(1)), sTd(velocity.get(2)), sTd(globalLocation.get(0)),
sTd(globalLocation.get(1)), sTd(globalLocation.get(2)), sTd(batteryLevel));
sharedQueue.add(outboundMessage);
} catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
}
}
private void messageTranslaterForIRISDrone(JsonNode inbound_message){
JsonNode node = inbound_message;
String outboundMessage;
try {
JsonNode velocity = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(MessageConfig.OUT_BASIC_PARAM_VELOCITY);
JsonNode globalLocation = node.get(MessageConfig.OUT_BASIC_PARAM_VAL).get(
MessageConfig.OUT_BASIC_PARAM_GLOBAL_LOCATION);
JsonNode quataniumVals = node.get(MessageConfig.OUT_QUATANNIM_VAL);
JsonNode batteryLevel = node.get(MessageConfig.OUT_BATTERY_LEVEL);
outboundMessage = String.format(outboundMessageFormatForIrisDrone, sTd(quataniumVals.get(0)),
sTd(quataniumVals.get(1)), sTd(quataniumVals.get(2)), sTd(velocity.get(0)),
sTd(velocity.get(1)), sTd(velocity.get(2)), sTd(globalLocation.get(0)),
sTd(globalLocation.get(1)), sTd(globalLocation.get(2)), sTd(batteryLevel));
sharedQueue.add(outboundMessage);
}catch (Exception e) {
log.error(e.getMessage()+",\n"+ e);
}
}
public void messageTranslater(String inbound_message){
JsonNode actualMessage;
ObjectMapper objectMapper = new ObjectMapper();
try {
actualMessage = objectMapper.readValue(inbound_message, JsonNode.class);
JsonNode deviceType = actualMessage.get(MessageConfig.IN_DEVICE_TYPE);
switch (deviceType.getTextValue()) {
case MessageConfig.IN_IRIS_DRONE:
messageTranslaterForIRISDrone(actualMessage);
break;
case MessageConfig.IN_SIMULATOR:
messageTranslaterForSimulator(actualMessage);
break;
default:
if(log.isDebugEnabled()){
log.debug("Wrong message format");
}
}
} catch (JsonProcessingException e) {
log.error("Incoming message might be corrupted, "+ e);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
private double sTd(JsonNode s)
{
return Double.parseDouble(s.toString());
}
public String getMessage() {
try{
if(sharedQueue.isEmpty() || sharedQueue == null){
return "";
}
return sharedQueue.remove();
}catch(Exception e) {
log.error("There is no more messages to send or internal server error has been occurred, \n"+ e );
return "";
}
}
public boolean isEmptyQueue(){
return sharedQueue != null? sharedQueue.isEmpty():false;
}
}

@ -1,55 +0,0 @@
package org.homeautomation.droneanalyzer.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* 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 String getTenantDomainOftheUser() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
String tenantDomain = threadLocalCarbonContext.getTenantDomain();
return tenantDomain;
}
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;
}
}

@ -1,95 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.util;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.transport.DroneAnalyzerXMPPConnector;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.controller.DroneController;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import java.io.File;
public class DroneAnalyzerServiceUtils {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneAnalyzerServiceUtils.class);
public static void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state, DroneAnalyzerXMPPConnector droneXMPPConnector)
throws DeviceManagementException, TransportHandlerException {
String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppServerDomain.lastIndexOf(File.separator);
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), xmppServerDomain.length());
}
indexOfChar = xmppServerDomain.indexOf(":");
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring(0, indexOfChar);
}
String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner;
String message = resource.replace("/", "") + ":" + state;
droneXMPPConnector.publishDeviceData(clientToConnect, message, "CONTROL-REQUEST");
}
public static boolean sendControlCommand(DroneController controller, String deviceId, String action,
double speed, double duration)
throws DeviceManagementException {
boolean controlState = false;
try{
switch (action){
case DroneConstants.TAKE_OFF:
controlState = controller.takeoff();
break;
case DroneConstants.LAND:
controlState = controller.land();
break;
case DroneConstants.BACK:
controlState = controller.back(speed, duration);
break;
case DroneConstants.CLOCK_WISE:
controlState = controller.clockwise(speed, duration);
break;
case DroneConstants.COUNTER_CLOCKWISE:
controlState = controller.conterClockwise(speed, duration);
break;
case DroneConstants.DOWN:
controlState = controller.down(speed, duration);
break;
case DroneConstants.FRONT:
controlState = controller.back(speed, duration);
break;
case DroneConstants.FORWARD:
controlState = controller.clockwise(speed, duration);
break;
case DroneConstants.UP:
controlState = controller.up(speed, duration);
break;
default:
log.error("Invalid command");
break;
}
}catch(Exception e){
log.error(e.getMessage()+ "\n"+ e);
}
return controlState;
}
}

@ -26,64 +26,62 @@
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/*/download</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>POST</method>
<scope>drone_analyzer_user</scope>
</Permission>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get Devices</name>
<path>/device-mgt/user/devices</path>
<url>/devices</url>
<name>Get device</name>
<path>/device-mgt/drone/user</path>
<url>/device/*</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
<scope>drone_user</scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/drone/user</path>
<url>/device/*</url>
<method>DELETE</method>
<scope>drone_user</scope>
</Permission>
<Permission>
<name>Generate Link</name>
<path>/device-mgt/user/devices/generate_link</path>
<url>/devices/*/generate_link</url>
<name>Download device</name>
<path>/device-mgt/drone/user</path>
<url>/device/download</url>
<method>GET</method>
<scope>drone_analyzer_user</scope>
<scope>drone_user</scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/drone/user</path>
<url>/device/*</url>
<method>POST</method>
<scope>drone_user</scope>
</Permission>
<Permission>
<name>Get Devices</name>
<path>/device-mgt/drone/user</path>
<url>/device</url>
<method>GET</method>
<scope>drone_user</scope>
</Permission>
<Permission>
<name>Register Device</name>
<path>/device-mgt/user/device/register</path>
<url>/device/register/*/*/*</url>
<path>/device-mgt/drone/user</path>
<url>/device/register</url>
<method>POST</method>
<scope>drone_analyzer_device</scope>
<scope>drone_device</scope>
</Permission>
<Permission>
<name>Send Command</name>
<path>/device-mgt/user/device/send_command</path>
<url>/device/*/send_command</url>
<name>Control Sensor</name>
<path>/device-mgt/drone/user</path>
<url>/device/*/change-status</url>
<method>POST</method>
<scope>drone_analyzer_user</scope>
<scope>drone_user</scope>
</Permission>
</PermissionConfiguration>
<Permission>
<name>Get Stats</name>
<path>/device-mgt/drone/user</path>
<url>/device/stats/*</url>
<method>GET</method>
<scope>drone_device</scope>
</Permission>
</PermissionConfiguration>

@ -1,7 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~ 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
@ -13,32 +12,25 @@
~ 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
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
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 http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<jaxrs:server id="DroneAnalyzer" address="/">
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans>
<bean id="DroneControllerService"
class="org.homeautomation.droneanalyzer.api.DroneControllerServiceImpl">
<!--<property name="DroneXMPPConnector" ref="xmppConnectorBean"/>-->
</bean>
<bean id="DroneManagerService"
class="org.homeautomation.droneanalyzer.api.DroneManagerServiceImpl">
<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="drone" address="/">
<jaxrs:serviceBeans>
<bean id="DroneAnalyzerService"
class="org.homeautomation.droneanalyzer.api.DroneAnalyzerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -6,44 +6,41 @@
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>false</param-value>
</context-param>
<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>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/drone_analyzer/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>
<!--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>

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -16,23 +17,21 @@
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<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>droneanalyzer-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.droneanalyzer.plugin</artifactId>
<version>1.0.0</version>
<artifactId>${project-base-package}.plugin</artifactId>
<packaging>bundle</packaging>
<name>${groupId}.droneanalyzer.plugin for CDMF </name>
<name>${project-base-package}.plugin</name>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
@ -42,10 +41,11 @@
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>${maven-compiler-plugin.version}</version>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
@ -55,11 +55,11 @@
<extensions>true</extensions>
<configuration>
<instructions>
<Bundle-SymbolicName>${groupId}.droneanalyzer.plugin</Bundle-SymbolicName>
<Bundle-Name>${groupId}.droneanalyzer.plugin</Bundle-Name>
<Bundle-Version>2.1.0-SNAPSHOT</Bundle-Version>
<Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
<Bundle-Name>${project-base-package}.plugin</Bundle-Name>
<Bundle-Version>1.0.0</Bundle-Version>
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
<Private-Package>org.homeautomation.droneanalyzer.plugin.internal</Private-Package>
<Private-Package>${project-base-package}.plugin.internal</Private-Package>
<Import-Package>
org.osgi.framework,
org.osgi.service.component,
@ -70,19 +70,29 @@
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.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>
!org.homeautomation.droneanalyzer.plugin.internal,
org.homeautomation.droneanalyzer.plugin.*
!${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>
@ -99,22 +109,25 @@
<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-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<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.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<groupId>org.wso2.carbon.analytics-common</groupId>
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
</dependency>
</dependencies>
</project>

@ -0,0 +1,70 @@
/*
* 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.droneanalyzer.plugin.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
/**
* Device type specific constants which includes all transport protocols configurations,
* stream definition and device specific dome constants
*/
public class DroneAnalyzerConstants {
public final static String DEVICE_TYPE = "drone";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "drone_DEVICE_ID";
public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
//sensor events summerized table name
public static final String SENSOR_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_droneStats";
public static final String DATA_SOURCE_NAME = "jdbc/droneDM_DB";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants
public static final String MQTT_ADAPTER_NAME = "droneStats_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 SUBSCRIBED_TOPIC = "carbon.super/drone/+/publisher";
public static final String CONTENT_TRANSFORMATION = "contentTransformer";
public static final String CONTENT_VALIDATION = "contentValidator";
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 TOPIC = "topic";
public final static String SENSOR_STREAM_DEFINITION = "org.wso2.iot.devices.droneStats";
public final static String SENSOR_STREAM_DEFINITION_VERSION = "1.0.0";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* 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
@ -11,46 +11,49 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.exception;
package org.homeautomation.droneanalyzer.plugin.exception;
public class DroneAnalyzerDeviceMgtPluginException extends Exception{
/**
* Device type plugin exception handler
*/
public class DeviceMgtPluginException extends Exception {
private String errorMessage;
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public DroneAnalyzerDeviceMgtPluginException(String msg, Exception nestedEx) {
public DeviceMgtPluginException(String msg, Exception nestedEx) {
super(msg, nestedEx);
setErrorMessage(msg);
}
public DroneAnalyzerDeviceMgtPluginException(String message, Throwable cause) {
public DeviceMgtPluginException(String message, Throwable cause) {
super(message, cause);
setErrorMessage(message);
}
public DroneAnalyzerDeviceMgtPluginException(String msg) {
public DeviceMgtPluginException(String msg) {
super(msg);
setErrorMessage(msg);
}
public DroneAnalyzerDeviceMgtPluginException() {
public DeviceMgtPluginException() {
super();
}
public DroneAnalyzerDeviceMgtPluginException(Throwable cause) {
public DeviceMgtPluginException(Throwable cause) {
super(cause);
}
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* 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
@ -11,7 +11,7 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -20,8 +20,8 @@ package org.homeautomation.droneanalyzer.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.feature.DroneAnalyzerFeatureManager;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
@ -29,34 +29,34 @@ 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.configuration.mgt.PlatformConfiguration;
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 Drone Analyzer service implementation of DeviceManagerService.
* This represents the ggg implementation of DeviceManagerService.
*/
public class DroneAnalyzerManager implements DeviceManager {
private static final DroneAnalyzerDAO droneAnalyzerDAO = new DroneAnalyzerDAO();
private static final Log log = LogFactory.getLog(DroneAnalyzerManager.class);
private FeatureManager droneFeatureManager = new DroneAnalyzerFeatureManager();
private static final DroneAnalyzerDAO deviceTypeDAO = new DroneAnalyzerDAO();
private FeatureManager featureManager = new DroneAnalyzerFeatureManager();
@Override
public FeatureManager getFeatureManager() {
return droneFeatureManager;
return featureManager;
}
@Override
public boolean saveConfiguration(TenantConfiguration tenantConfiguration)
throws DeviceManagementException {
//TODO implement this
public boolean saveConfiguration(PlatformConfiguration platformConfiguration) throws DeviceManagementException {
return false;
}
@Override
public TenantConfiguration getConfiguration() throws DeviceManagementException {
//TODO implement this
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
return null;
}
@ -65,19 +65,18 @@ public class DroneAnalyzerManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Enrolling a new drone device : " + device.getDeviceIdentifier());
log.debug("Enrolling a new droneanalyzer device : " + device.getDeviceIdentifier());
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().addDevice(device);
status = deviceTypeDAO.getDroneAnalyzerDAO().addDevice(device);
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
} catch (DeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
String msg = "Error occurred while roll back the device enrol transaction :" + device.toString();
log.warn(msg, iotDAOEx);
} catch (DeviceMgtPluginException iotDAOEx) {
log.warn("Error occurred while roll back the device enrol transaction :" + device.toString(), iotDAOEx);
}
String msg = "Error while enrolling the drone device : " + device.getDeviceIdentifier();
String msg = "Error while enrolling the droneanalyzer device : " + device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -89,19 +88,19 @@ public class DroneAnalyzerManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Modifying the Virtual Firealarm device enrollment data");
log.debug("Modifying the droneanalyzer device enrollment data");
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().updateDevice(device);
status = deviceTypeDAO.getDroneAnalyzerDAO().updateDevice(device);
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
} catch (DeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
} 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 drone device : " +
String msg = "Error while updating the enrollment of the droneanalyzer device : " +
device.getDeviceIdentifier();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -114,19 +113,19 @@ public class DroneAnalyzerManager implements DeviceManager {
boolean status;
try {
if (log.isDebugEnabled()) {
log.debug("Dis-enrolling drone device : " + deviceId);
log.debug("Dis-enrolling droneanalyzer device : " + deviceId);
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().deleteIotDevice(deviceId.getId());
status = deviceTypeDAO.getDroneAnalyzerDAO().deleteDevice(deviceId.getId());
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
} catch (DeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
} 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 drone device : " + deviceId.getId();
String msg = "Error while removing the droneanalyzer device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -138,14 +137,15 @@ public class DroneAnalyzerManager implements DeviceManager {
boolean isEnrolled = false;
try {
if (log.isDebugEnabled()) {
log.debug("Checking the enrollment of Drone device : " + deviceId.getId());
log.debug("Checking the enrollment of droneanalyzer device : " + deviceId.getId());
}
Device iotDevice = droneAnalyzerDAO.getDeviceDAO().getDevice(deviceId.getId());
Device iotDevice =
deviceTypeDAO.getDroneAnalyzerDAO().getDevice(deviceId.getId());
if (iotDevice != null) {
isEnrolled = true;
}
} catch (DroneAnalyzerDeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of Drone device : " +
} catch (DeviceMgtPluginException e) {
String msg = "Error while checking the enrollment status of droneanalyzer device : " +
deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
@ -169,11 +169,11 @@ public class DroneAnalyzerManager implements DeviceManager {
Device device;
try {
if (log.isDebugEnabled()) {
log.debug("Getting the details of Drone device : " + deviceId.getId());
log.debug("Getting the details of droneanalyzer device : " + deviceId.getId());
}
device = droneAnalyzerDAO.getDeviceDAO().getDevice(deviceId.getId());
} catch (DroneAnalyzerDeviceMgtPluginException e) {
String msg = "Error while fetching the Drone device : " + deviceId.getId();
device = deviceTypeDAO.getDroneAnalyzerDAO().getDevice(deviceId.getId());
} catch (DeviceMgtPluginException e) {
String msg = "Error while fetching the droneanalyzer device : " + deviceId.getId();
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -206,26 +206,30 @@ public class DroneAnalyzerManager implements DeviceManager {
}
@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 Drone device : " + deviceIdentifier);
log.debug("updating the details of droneanalyzer device : " + deviceIdentifier);
}
DroneAnalyzerDAO.beginTransaction();
status = droneAnalyzerDAO.getDeviceDAO().updateDevice(device);
status = deviceTypeDAO.getDroneAnalyzerDAO().updateDevice(device);
DroneAnalyzerDAO.commitTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
} catch (DeviceMgtPluginException e) {
try {
DroneAnalyzerDAO.rollbackTransaction();
} catch (DroneAnalyzerDeviceMgtPluginException iotDAOEx) {
} 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 Drone device : " + deviceIdentifier;
"Error while updating the droneanalyzer device : " + deviceIdentifier;
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
@ -234,23 +238,17 @@ public class DroneAnalyzerManager implements DeviceManager {
@Override
public List<Device> getAllDevices() throws DeviceManagementException {
List<Device> devices = null;
List<Device> devices;
try {
if (log.isDebugEnabled()) {
log.debug("Fetching the details of all Drone devices");
log.debug("Fetching the details of all droneanalyzer devices");
}
devices = droneAnalyzerDAO.getDeviceDAO().getAllDevices();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
String msg = "Error while fetching all Drone devices.";
devices = deviceTypeDAO.getDroneAnalyzerDAO().getAllDevices();
} catch (DeviceMgtPluginException e) {
String msg = "Error while fetching all droneanalyzer devices.";
log.error(msg, e);
throw new DeviceManagementException(msg, e);
}
return devices;
}
@Override
public boolean requireDeviceAuthorization() {
return true;
}
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* 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
@ -11,30 +11,33 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
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.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DroneAnalyzerManagerService implements DeviceManagementService {
private DeviceManager deviceManager;
private final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
@Override
public String getType() {
return DroneConstants.DEVICE_TYPE;
return DroneAnalyzerConstants.DEVICE_TYPE;
}
@Override
@ -53,54 +56,13 @@ public class DroneAnalyzerManagerService implements DeviceManagementService {
}
@Override
public void notifyOperationToDevices(Operation operation, List<DeviceIdentifier> list)
throws DeviceManagementException {
}
@Override
public Application[] getApplications(String s, int i, int i1) throws ApplicationManagementException {
return new Application[0];
}
@Override
public void updateApplicationStatus(DeviceIdentifier deviceIdentifier, Application application, String s)
throws ApplicationManagementException {
public ProvisioningConfig getProvisioningConfig() {
return new ProvisioningConfig(DroneAnalyzerConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false);
}
@Override
public String getApplicationStatus(DeviceIdentifier deviceIdentifier, Application application)
throws ApplicationManagementException {
public PushNotificationConfig getPushNotificationConfig() {
return null;
}
@Override
public void installApplicationForDevices(Operation operation, List<DeviceIdentifier> list)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUsers(Operation operation, List<String> list)
throws ApplicationManagementException {
}
@Override
public void installApplicationForUserRoles(Operation operation, List<String> list)
throws ApplicationManagementException {
}
@Override
public String getProviderTenantDomain() {
return DEVICE_TYPE_PROVIDER_DOMAIN;
}
@Override
public boolean isSharedWithAllTenants() {
return true;
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* 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
@ -11,7 +11,7 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -20,9 +20,10 @@ package org.homeautomation.droneanalyzer.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.impl.DroneAnalyzerDeviceDAOImpl;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.impl.dao.impl.DroneAnalyzerDAOImpl;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import javax.naming.Context;
import javax.naming.InitialContext;
@ -31,12 +32,14 @@ import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* Database handler which is specified for gg type
*/
public class DroneAnalyzerDAO {
private static final Log log = LogFactory.getLog(DroneAnalyzerDAO.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
static DataSource dataSource; // package local variable
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
public DroneAnalyzerDAO() {
initDroneAnalyzerDAO();
@ -45,57 +48,55 @@ public class DroneAnalyzerDAO {
public static void initDroneAnalyzerDAO() {
try {
Context ctx = new InitialContext();
dataSource = (DataSource) ctx.lookup(DroneConstants.DATA_SOURCE_NAME);
dataSource = (DataSource) ctx.lookup(DroneAnalyzerConstants.DATA_SOURCE_NAME);
} catch (NamingException e) {
log.error("Error while looking up the data source: " + DroneConstants.DATA_SOURCE_NAME);
log.error("Error while looking up the data source: " +
DroneAnalyzerConstants.DATA_SOURCE_NAME);
}
}
public DroneAnalyzerDeviceDAOImpl getDeviceDAO() {
return new DroneAnalyzerDeviceDAOImpl();
}
public static void beginTransaction() throws DroneAnalyzerDeviceMgtPluginException {
public static void beginTransaction() throws DeviceMgtPluginException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
throw new DeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws DroneAnalyzerDeviceMgtPluginException {
if (currentConnection != null && currentConnection.get() == null) {
public static Connection getConnection() throws DeviceMgtPluginException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while retrieving data source connection", e);
throw new DeviceMgtPluginException("Error occurred while retrieving data source connection",
e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws DroneAnalyzerDeviceMgtPluginException {
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");
log.debug("Datasource connection associated with the current thread is null, hence commit " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while committing the transaction", e);
throw new DeviceMgtPluginException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws DroneAnalyzerDeviceMgtPluginException {
public static void closeConnection() throws DeviceMgtPluginException {
Connection con = currentConnection.get();
if (con != null) {
try {
@ -107,21 +108,25 @@ public class DroneAnalyzerDAO {
currentConnection.remove();
}
public static void rollbackTransaction() throws DroneAnalyzerDeviceMgtPluginException {
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");
log.debug("Datasource connection associated with the current thread is null, hence rollback " +
"has not been attempted");
}
}
} catch (SQLException e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while rollback the transaction", e);
throw new DeviceMgtPluginException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}
public DroneAnalyzerDAOImpl getDroneAnalyzerDAO() {
return new DroneAnalyzerDAOImpl();
}
}

@ -1,5 +1,5 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
* 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
@ -11,7 +11,7 @@
* 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
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
@ -20,67 +20,73 @@ package org.homeautomation.droneanalyzer.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
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.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements CRUD for drone analyzer.
* Implements IotDeviceDAO for gg Devices.
*/
public class DroneAnalyzerDeviceDAOImpl {
public class DroneAnalyzerDAOImpl {
private static final Log log = LogFactory.getLog(DroneAnalyzerDeviceDAOImpl.class);
private static final Log log = LogFactory.getLog(DroneAnalyzerDAOImpl.class);
public Device getDevice(String deviceId) throws DroneAnalyzerDeviceMgtPluginException {
public Device getDevice(String deviceId) throws DeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
Device device = null;
Device iotDevice = null;
ResultSet resultSet = null;
try {
conn = DroneAnalyzerDAO.getConnection();
if(conn == null){
log.error("Database connection hasn't been created");
}
String selectDBQuery =
"SELECT DRONE_DEVICE_ID, DEVICE_NAME FROM DRONE_DEVICE WHERE DRONE_DEVICE_ID = ?";
"SELECT drone_DEVICE_ID, DEVICE_NAME" +
" FROM drone_DEVICE WHERE drone_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, deviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
device = new Device();
iotDevice = new Device();
iotDevice.setName(resultSet.getString(
DroneAnalyzerConstants.DEVICE_PLUGIN_DEVICE_NAME));
if (log.isDebugEnabled()) {
log.debug("Drone device " + deviceId + " data has been fetched from " +
"Drone database.");
log.debug("drone device " + deviceId + " data has been fetched from " +
"drone database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching drone device : '" + deviceId + "'";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, resultSet);
DroneAnalyzerDAO.closeConnection();
}
return device;
return iotDevice;
}
public boolean addDevice(Device device) throws DroneAnalyzerDeviceMgtPluginException {
public boolean addDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String createDBQuery =
"INSERT INTO DRONE_DEVICE(DRONE_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
"INSERT INTO drone_DEVICE(drone_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, device.getDeviceIdentifier());
stmt.setString(2, device.getName());
@ -96,88 +102,93 @@ public class DroneAnalyzerDeviceDAOImpl {
String msg = "Error occurred while adding the drone device '" +
device.getDeviceIdentifier() + "' to the drone db.";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean updateDevice(Device device) throws DroneAnalyzerDeviceMgtPluginException {
public boolean updateDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
String updateDBQuery =
"UPDATE DRONE_DEVICE SET DEVICE_NAME = ? WHERE DRONE_DEVICE_ID = ?";
"UPDATE drone_DEVICE SET DEVICE_NAME = ? WHERE drone_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("Drone device " + device.getDeviceIdentifier() + " data has been" +
log.debug("drone device " + device.getDeviceIdentifier() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Drone device '" + device.getDeviceIdentifier() + "' data.";
String msg = "Error occurred while modifying the drone device '" +
device.getDeviceIdentifier() + "' data.";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, null);
}
return status;
}
public boolean deleteIotDevice(String iotDeviceId) throws DroneAnalyzerDeviceMgtPluginException {
public boolean deleteDevice(String deviceId) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
System.out.println("delete device ");
String deleteDBQuery =
"DELETE FROM DRONE_DEVICE WHERE DRONE_DEVICE_ID = ?";
"DELETE FROM drone_DEVICE WHERE drone_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
stmt.setString(1, deviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Drone device " + iotDeviceId + " data has deleted" +
log.debug("drone device " + deviceId + " data has deleted" +
" from the drone database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting drone device " + iotDeviceId;
String msg = "Error occurred while deleting drone device " + deviceId;
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, null);
}
return status;
}
public List<Device> getAllDevices() throws DroneAnalyzerDeviceMgtPluginException {
public List<Device> getAllDevices() throws DeviceMgtPluginException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device iotDevice;
List<Device> iotDevices = new ArrayList<Device>();
Device device;
List<Device> iotDevices = new ArrayList<>();
try {
conn = DroneAnalyzerDAO.getConnection();
String selectDBQuery =
"SELECT DRONE_DEVICE_ID, DEVICE_NAME " +
"FROM DRONE_DEVICE";
"SELECT drone_DEVICE_ID, DEVICE_NAME " +
"FROM drone_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
iotDevice = new Device();
iotDevice.setDeviceIdentifier(resultSet.getString(DroneConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setName(resultSet.getString(DroneConstants.DEVICE_PLUGIN_DEVICE_NAME));
device = new Device();
device.setDeviceIdentifier(resultSet.getString(DroneAnalyzerConstants.DEVICE_PLUGIN_DEVICE_ID));
device.setName(resultSet.getString(DroneAnalyzerConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<>();
device.setProperties(propertyList);
}
if (log.isDebugEnabled()) {
log.debug("All drone device details have fetched from drone database.");
@ -186,7 +197,7 @@ public class DroneAnalyzerDeviceDAOImpl {
} catch (SQLException e) {
String msg = "Error occurred while fetching all drone device data'";
log.error(msg, e);
throw new DroneAnalyzerDeviceMgtPluginException(msg, e);
throw new DeviceMgtPluginException(msg, e);
} finally {
DroneAnalyzerUtils.cleanupResources(stmt, resultSet);
DroneAnalyzerDAO.closeConnection();

@ -15,7 +15,7 @@
*/
package org.homeautomation.droneanalyzer.plugin.impl.feature;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.Feature;
import org.wso2.carbon.device.mgt.common.FeatureManager;
@ -23,6 +23,9 @@ import org.wso2.carbon.device.mgt.extensions.feature.mgt.GenericFeatureManager;
import java.util.List;
/**
* Device type specific feature management server
*/
public class DroneAnalyzerFeatureManager implements FeatureManager {
@Override
public boolean addFeature(Feature feature) throws DeviceManagementException {
@ -37,13 +40,13 @@ public class DroneAnalyzerFeatureManager implements FeatureManager {
@Override
public Feature getFeature(String name) throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeature(DroneConstants.DEVICE_TYPE, name);
return genericFeatureManager.getFeature(DroneAnalyzerConstants.DEVICE_TYPE, name);
}
@Override
public List<Feature> getFeatures() throws DeviceManagementException {
GenericFeatureManager genericFeatureManager = GenericFeatureManager.getInstance();
return genericFeatureManager.getFeatures(DroneConstants.DEVICE_TYPE);
return genericFeatureManager.getFeatures(DroneAnalyzerConstants.DEVICE_TYPE);
}
@Override

@ -15,7 +15,6 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.util;
import org.apache.commons.logging.Log;
@ -29,11 +28,11 @@ import java.io.File;
/**
* Provides methods for initializing the database script.
*/
public class DeviceSchemaInitializer extends DatabaseCreator {
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;
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
public DeviceSchemaInitializer(DataSource dataSource) {
super(dataSource);

@ -0,0 +1,46 @@
/*
* 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.droneanalyzer.plugin.impl.util;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;
import java.io.IOException;
/**
* When device type related plugin is depleting it will initiate mqtt connection with mqtt broker
*/
public class DroneAnalyzerStartupListener implements ServerStartupObserver {
private static final Log log = LogFactory.getLog(org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerStartupListener.class);
@Override
public void completingServerStartup() {
}
@Override
public void completedServerStartup() {
try {
DroneAnalyzerUtils.setupMqttOutputAdapter();
} catch (IOException e) {
log.error("Failed to initialize the drone output adapter", e);
}
}
}

@ -0,0 +1,190 @@
/*
* 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.droneanalyzer.plugin.impl.util;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.internal.DroneAnalyzerManagementDataHolder;
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.List;
import java.util.Map;
import java.util.Properties;
/**
* Contains utility methods used by gg plugin.
*/
public class DroneAnalyzerUtils {
private static Log log = LogFactory.getLog(org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils.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(DroneAnalyzerConstants.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: " + DroneAnalyzerConstants.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(!DroneAnalyzerConstants.MQTT_BROKER_HOST.startsWith("$")){
MQTT_BROKER_HOST = "\\$".concat(DroneAnalyzerConstants.MQTT_BROKER_HOST);
}
if(!DroneAnalyzerConstants.MQTT_PORT.startsWith("$")){
MQTT_PORT = "\\$".concat(DroneAnalyzerConstants.MQTT_PORT);
}
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_PORT, "" +
(DroneAnalyzerConstants.DEFAULT_MQTT_PORT + getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_BROKER_HOST,
System.getProperty(DroneAnalyzerConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
return urlWithPlaceholders;
}
private static int getPortOffset() {
ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
DroneAnalyzerConstants.CARBON_CONFIG_PORT_OFFSET));
try {
if ((portOffset != null)) {
return Integer.parseInt(portOffset.trim());
} else {
return DroneAnalyzerConstants.CARBON_DEFAULT_PORT_OFFSET;
}
} catch (NumberFormatException e) {
return DroneAnalyzerConstants.CARBON_DEFAULT_PORT_OFFSET;
}
}
public static void setupMqttOutputAdapter() throws IOException {
OutputEventAdapterConfiguration outputEventAdapterConfiguration =
createMqttOutputEventAdapterConfiguration(DroneAnalyzerConstants.MQTT_ADAPTER_NAME,
DroneAnalyzerConstants.MQTT_ADAPTER_TYPE, MessageType.TEXT);
try {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
DroneAnalyzerConstants.DEVICE_TYPE_PROVIDER_DOMAIN, true);
DroneAnalyzerManagementDataHolder.getInstance().getOutputEventAdapterService()
.create(outputEventAdapterConfiguration);
} catch (OutputEventAdapterException e) {
log.error("Unable to create Output Event Adapter : " + DroneAnalyzerConstants.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(DroneAnalyzerConstants.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(DroneAnalyzerConstants.USERNAME_PROPERTY_KEY, properties.getProperty(
DroneAnalyzerConstants.USERNAME_PROPERTY_KEY));
mqttAdapterProperties.put(DroneAnalyzerConstants.DCR_PROPERTY_KEY, Utils.replaceSystemProperty(
properties.getProperty(DroneAnalyzerConstants.DCR_PROPERTY_KEY)));
mqttAdapterProperties.put(DroneAnalyzerConstants.BROKER_URL_PROPERTY_KEY, replaceMqttProperty(
properties.getProperty(DroneAnalyzerConstants.BROKER_URL_PROPERTY_KEY)));
mqttAdapterProperties.put(DroneAnalyzerConstants.SCOPES_PROPERTY_KEY, properties.getProperty(
DroneAnalyzerConstants.SCOPES_PROPERTY_KEY));
mqttAdapterProperties.put(DroneAnalyzerConstants.CLEAR_SESSION_PROPERTY_KEY, properties.getProperty(
DroneAnalyzerConstants.CLEAR_SESSION_PROPERTY_KEY));
mqttAdapterProperties.put(DroneAnalyzerConstants.QOS_PROPERTY_KEY, properties.getProperty(
DroneAnalyzerConstants.QOS_PROPERTY_KEY));
mqttAdapterProperties.put(DroneAnalyzerConstants.CLIENT_ID_PROPERTY_KEY, "");
mqttAdapterProperties.put(DroneAnalyzerConstants.RESOURCE, "output-event");
outputEventAdapterConfiguration.setStaticProperties(mqttAdapterProperties);
}
return outputEventAdapterConfiguration;
}
}

@ -0,0 +1,47 @@
/*
* 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.droneanalyzer.plugin.internal;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
/**
* DataHolder class of gg plugins component.
*/
public class DroneAnalyzerManagementDataHolder {
private static DroneAnalyzerManagementDataHolder thisInstance = new DroneAnalyzerManagementDataHolder();
private OutputEventAdapterService outputEventAdapterService;
private DroneAnalyzerManagementDataHolder() {
}
public static DroneAnalyzerManagementDataHolder 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.droneanalyzer.plugin.internal;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerStartupListener;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.homeautomation.droneanalyzer.plugin.impl.DroneAnalyzerManagerService;
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="org.homeautomation.droneanalyzer.plugin.internal.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 {
DroneAnalyzerManagerService deviceTypeManagerService = new DroneAnalyzerManagerService();
BundleContext bundleContext = ctx.getBundleContext();
serviceRegistration =
bundleContext.registerService(DeviceManagementService.class.getName(),
deviceTypeManagerService, null);
bundleContext.registerService(ServerStartupObserver.class.getName(), new DroneAnalyzerStartupListener(),
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 {
DroneAnalyzerUtils.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) {
DroneAnalyzerManagementDataHolder.getInstance().setOutputEventAdapterService(outputEventAdapterService);
}
/**
* De-reference the Output EventAdapter Service dependency.
*/
protected void unsetOutputEventAdapterService(OutputEventAdapterService outputEventAdapterService) {
DroneAnalyzerManagementDataHolder.getInstance().setOutputEventAdapterService(null);
}
}

@ -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.droneanalyzer.plugin.mqtt;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* MQTT configurations
*/
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(DroneAnalyzerConstants.MQTT_CONFIG_LOCATION);
if (configFile.exists()) {
try {
InputStream propertyStream = configFile.toURI().toURL().openStream();
Properties properties = new Properties();
properties.load(propertyStream);
brokerEndpoint = DroneAnalyzerUtils.replaceMqttProperty(
properties.getProperty(DroneAnalyzerConstants.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;
}
}

@ -1,41 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.constants;
public class DroneConstants {
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "DRONE_DEVICE_ID";
public final static String MESSAGE_RESOURCE = "drone_current_status";
public static final String DEVICE_TYPE = "drone_analyzer";
public static final int MINIMUM_TIME_DURATION = 150;
public static final int MAXIMUM_BUFFERE_SIZE_OF_SHARED_QUEUE = 10;
public static final String DEVICE_ID = "drone_type1";
public final static String TAKE_OFF = "takeoff";
public final static String LAND = "land";
public final static String UP = "up";
public final static String DOWN = "down";
public final static String BACK = "back";
public final static String FORWARD = "forward";
public final static String FRONT = "front";
public final static String CLOCK_WISE = "clockwise";
public final static String COUNTER_CLOCKWISE = "counterClockwise";
public static final String DATA_SOURCE_NAME = "jdbc/DroneAnalyzerDM_DB";
}

@ -1,40 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.constants;
public class MessageConfig {
public static final String IN_QUATANNIM_VAL = "quatanium_val";
public static final String IN_DEVICE_TYPE = "device_type";
public static final String IN_IRIS_DRONE = "IRIS_DRONE";
public static final String IN_SIMULATOR = "SIMULATOR";
public static final String OUT_QUATANNIM_VAL = "quatanium_val";
public static final String IN_ACCELETOMETER_VAL = "accelerometer";
public static final String OUT_ACCELETOMETER_VAL = "accelerometer";
public static final String IN_GYROSCOPE_VAL = "gyroscope";
public static final String OUT_GYROSCOPE_VAL = "gyroscope";
public static final String IN_MAGNETOMETER_VAL = "magnetometer";
public static final String OUT_MAGNETOMETER_VAL = "magnetometer";
public static final String IN_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VAL = "basicParam";
public static final String OUT_BASIC_PARAM_VELOCITY = "velocity";
public static final String OUT_BASIC_PARAM_GLOBAL_LOCATION = "global_location";
public static final String OUT_BATTERY_LEVEL = "battery_level";
}

@ -1,34 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.controller;
public interface DroneController {
boolean takeoff();
boolean land();
boolean up(double speed, double duration);
boolean down(double speed, double duration);
boolean left(double speed, double duration);
boolean right(double speed, double duration);
boolean front(double speed, double duration);
boolean back(double speed, double duration);
boolean clockwise(double speed, double duration);
boolean conterClockwise(double speed, double duration);
}

@ -1,74 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.controller.impl;
import org.homeautomation.droneanalyzer.plugin.controller.DroneController;
public class DroneControllerImpl implements DroneController {
@Override
public boolean takeoff() {
return false;
}
@Override
public boolean land() {
return false;
}
@Override
public boolean up(double speed, double duration) {
return false;
}
@Override
public boolean down(double speed, double duration) {
return false;
}
@Override
public boolean left(double speed, double duration) {
return false;
}
@Override
public boolean right(double speed, double duration) {
return false;
}
@Override
public boolean front(double speed, double duration) {
return false;
}
@Override
public boolean back(double speed, double duration) {
return false;
}
@Override
public boolean clockwise(double speed, double duration) {
return false;
}
@Override
public boolean conterClockwise(double speed, double duration) {
return false;
}
}

@ -1,109 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.wso2.carbon.device.mgt.common.Device;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
/**
* Contains utility methods used by Drone Analyzer plugin.
*/
public class DroneAnalyzerUtils {
private static Log log = LogFactory.getLog(DroneAnalyzerUtils.class);
public static String getDeviceProperty(List<Device.Property> deviceProperties, String propertyKey) {
String deviceProperty = "";
for(Device.Property property :deviceProperties){
if(propertyKey.equals(property.getName())){
deviceProperty = property.getValue();
}
}
return deviceProperty;
}
public static Device.Property getProperty(String property, String value) {
if (property != null) {
Device.Property prop = new Device.Property();
prop.setName(property);
prop.setValue(value);
return prop;
}
return null;
}
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 DroneAnalyzerDeviceMgtPluginException {
try {
Context ctx = new InitialContext();
DataSource dataSource = (DataSource) ctx.lookup(DroneConstants.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: " + DroneConstants.DATA_SOURCE_NAME);
} catch (Exception e) {
throw new DroneAnalyzerDeviceMgtPluginException("Error occurred while initializing Iot Device " +
"Management database schema", e);
}
}
}

@ -1,89 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.plugin.internal;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.impl.DroneAnalyzerManagerService;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.homeautomation.droneanalyzer.plugin.exception.DroneAnalyzerDeviceMgtPluginException;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
/**
* @scr.component name="org.homeautomation.droneanalyzer.plugin.DroneAnalyzerManagementServiceComponent
* immediate="true"
*/
public class DroneAnalyzerManagementServiceComponent {
private ServiceRegistration firealarmServiceRegRef;
private static final Log log = LogFactory.getLog(
DroneAnalyzerManagementServiceComponent.class);
protected void activate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("Activating Drone Analyzer Management Service Component");
}
try {
BundleContext bundleContext = ctx.getBundleContext();
firealarmServiceRegRef =
bundleContext.registerService(DeviceManagementService.class.getName(),
new DroneAnalyzerManagerService(), 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 {
DroneAnalyzerUtils.setupDeviceManagementSchema();
} catch (DroneAnalyzerDeviceMgtPluginException e) {
log.error("Exception occurred while initializing device management database schema", e);
}
}
if (log.isDebugEnabled()) {
log.debug(
"Drone Analyzer Device Management Service Component has been successfully activated");
}
} catch (Throwable e) {
log.error("Error occurred while activating Drone Analyzer Device Management Service Component", e);
}
}
protected void deactivate(ComponentContext ctx) {
if (log.isDebugEnabled()) {
log.debug("De-activating Drone Analyzer Device Management Service Component");
}
try {
if (firealarmServiceRegRef != null) {
firealarmServiceRegRef.unregister();
}
if (log.isDebugEnabled()) {
log.debug("Drone Analyzer Device Management Service Component has been successfully de-activated");
}
} catch (Throwable e) {
log.error(
"Error occurred while de-activating Drone Analyzer Device Management bundle",e);
}
}
}

@ -1,34 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!--/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/--><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>droneanalyzer</artifactId>
<version>2.1.0-SNAPSHOT</version>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<version>1.0.0</version>
<artifactId>droneanalyzer-component</artifactId>
<name>WSO2 IoTS(Device Types) - Drone Analyzer Component</name>
<packaging>pom</packaging>
<build>
<pluginManagement>
@ -49,11 +45,10 @@
</plugins>
</pluginManagement>
</build>
<modules>
<module>plugin</module>
<module>api</module>
<module>ui</module>
</modules>
</project>
<modules>
<module>plugin</module>
<module>api</module>
<module>ui</module>
<module>analytics</module>
</modules>
</project>

@ -1,5 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
@ -17,32 +16,26 @@
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.homeautomation</groupId>
<artifactId>droneanalyzer-component</artifactId>
<version>2.1.0-SNAPSHOT</version>
<version>1.0.0</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<version>2.1.0-SNAPSHOT</version>
<artifactId>${groupId}.droneanalyzer.ui</artifactId>
<name>${groupId}.droneanalyzer.ui</name>
<artifactId>${project-base-package}.ui</artifactId>
<name>${project-base-package}.ui</name>
<packaging>pom</packaging>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>2.5.5</version>
<version>${maven-assembly-plugin.version}</version>
<configuration>
<finalName>${project.artifactId}-${carbon.device.mgt.version}</finalName>
<finalName>${project.artifactId}-1.0.0</finalName>
<appendAssemblyId>false</appendAssemblyId>
<descriptors>
<descriptor>src/assembly/src.xml</descriptor>
@ -60,5 +53,4 @@
</plugin>
</plugins>
</build>
</project>

@ -1,3 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~

@ -0,0 +1,55 @@
<span id="drone-details" data-devices="{{devices}}" data-devicename="{{device.name}}"
data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span>
<div id="drone-div-chart" data-backend-api-url= {{backendApiUrl}}>
<div class="chartWrapper" id="chartWrapper-battery">
<span id="span-title">Battery</span>
<div id="y_axis-battery" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-battery" title="Smoothing"></div>
<div id="legend-battery"></div>
</div>
<div id="chart-battery" class="custom_rickshaw_graph" ></div>
<div id="x_axis-battery" class="custom_x_axis"></div>
<div id="slider-battery" class="custom_slider"></div>
</div>
<div class="chartWrapper" id="chartWrapper-heading">
<span id="span-title">Heading</span>
<div id="y_axis-heading" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-heading" title="Smoothing"></div>
<div id="legend-heading"></div>
</div>
<div id="chart-heading" class="custom_rickshaw_graph" ></div>
<div id="x_axis-heading" class="custom_x_axis"></div>
<div id="slider-heading" class="custom_slider"></div>
</div>
<div class="chartWrapper" id="chartWrapper-bank">
<span id="span-title">Bank</span>
<div id="y_axis-bank" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-bank" title="Smoothing"></div>
<div id="legend-bank"></div>
</div>
<div id="chart-bank" class="custom_rickshaw_graph" ></div>
<div id="x_axis-bank" class="custom_x_axis"></div>
<div id="slider-bank" class="custom_slider"></div>
</div>
<div class="chartWrapper" id="chartWrapper-attitude">
<span id="span-title">Attitude</span>
<div id="y_axis-attitude" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother-attitude" title="Smoothing"></div>
<div id="legend-attitude"></div>
</div>
<div id="chart-attitude" class="custom_rickshaw_graph" ></div>
<div id="x_axis-attitude" class="custom_x_axis"></div>
<div id="slider-attitude" class="custom_slider"></div>
</div>
</div>
{{#zone "bottomJs"}}
{{js "js/drone.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),
"backendApiUrl": devicemgtProps["httpsURL"] + "/"+deviceType+"/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"] + "/"+deviceType+"/device/stats/" + deviceId
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
exit();
}
}
}

@ -0,0 +1,470 @@
/*
* 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.
*/
/* graph */
.rickshaw_graph {
position: relative;
}
.rickshaw_graph svg {
display: block;
overflow: hidden;
}
/* ticks */
.rickshaw_graph .x_tick {
position: absolute;
top: 0;
bottom: 0;
width: 0;
border-left: 1px dotted rgba(0, 0, 0, 0.2);
pointer-events: none;
}
.rickshaw_graph .x_tick .title {
position: absolute;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0.5;
white-space: nowrap;
margin-left: 3px;
bottom: -20px;
height: auto;
border-bottom: none;
}
/* annotations */
.rickshaw_annotation_timeline {
height: 1px;
border-top: 1px solid #e0e0e0;
margin-top: 10px;
position: relative;
}
.rickshaw_annotation_timeline .annotation {
position: absolute;
height: 6px;
width: 6px;
margin-left: -2px;
top: -3px;
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.25);
}
.rickshaw_graph .annotation_line {
position: absolute;
top: 0;
bottom: -6px;
width: 0;
border-left: 2px solid rgba(0, 0, 0, 0.3);
display: none;
}
.rickshaw_graph .annotation_line.active {
display: block;
}
.rickshaw_graph .annotation_range {
background: rgba(0, 0, 0, 0.1);
display: none;
position: absolute;
top: 0;
bottom: -6px;
}
.rickshaw_graph .annotation_range.active {
display: block;
}
.rickshaw_graph .annotation_range.active.offscreen {
display: none;
}
.rickshaw_annotation_timeline .annotation .content {
background: white;
color: black;
opacity: 0.9;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
border-radius: 3px;
position: relative;
z-index: 20;
font-size: 12px;
padding: 6px 8px 8px;
top: 18px;
left: -11px;
width: 160px;
display: none;
cursor: pointer;
}
.rickshaw_annotation_timeline .annotation .content:before {
content: "\25b2";
position: absolute;
top: -11px;
color: white;
text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.8);
}
.rickshaw_annotation_timeline .annotation.active,
.rickshaw_annotation_timeline .annotation:hover {
background-color: rgba(0, 0, 0, 0.8);
cursor: none;
}
.rickshaw_annotation_timeline .annotation .content:hover {
z-index: 50;
}
.rickshaw_annotation_timeline .annotation.active .content {
display: block;
}
.rickshaw_annotation_timeline .annotation:hover .content {
display: block;
z-index: 50;
}
.rickshaw_graph .y_axis,
.rickshaw_graph .x_axis_d3 {
fill: none;
}
.rickshaw_graph .y_ticks .tick line,
.rickshaw_graph .x_ticks_d3 .tick {
stroke: rgba(0, 0, 0, 0.16);
stroke-width: 2px;
shape-rendering: crisp-edges;
pointer-events: none;
}
.rickshaw_graph .y_grid .tick,
.rickshaw_graph .x_grid_d3 .tick {
z-index: -1;
stroke: rgba(0, 0, 0, 0.20);
stroke-width: 1px;
stroke-dasharray: 1 1;
}
.rickshaw_graph .y_grid .tick[data-y-value="0"] {
stroke-dasharray: 1 0;
}
.rickshaw_graph .y_grid path,
.rickshaw_graph .x_grid_d3 path {
fill: none;
stroke: none;
}
.rickshaw_graph .y_ticks path,
.rickshaw_graph .x_ticks_d3 path {
fill: none;
stroke: #808080;
}
.rickshaw_graph .y_ticks text,
.rickshaw_graph .x_ticks_d3 text {
opacity: 0.5;
font-size: 12px;
pointer-events: none;
}
.rickshaw_graph .x_tick.glow .title,
.rickshaw_graph .y_ticks.glow text {
fill: black;
color: black;
text-shadow: -1px 1px 0 rgba(255, 255, 255, 0.1),
1px -1px 0 rgba(255, 255, 255, 0.1),
1px 1px 0 rgba(255, 255, 255, 0.1),
0 1px 0 rgba(255, 255, 255, 0.1),
0 -1px 0 rgba(255, 255, 255, 0.1),
1px 0 0 rgba(255, 255, 255, 0.1),
-1px 0 0 rgba(255, 255, 255, 0.1),
-1px -1px 0 rgba(255, 255, 255, 0.1);
}
.rickshaw_graph .x_tick.inverse .title,
.rickshaw_graph .y_ticks.inverse text {
fill: white;
color: white;
text-shadow: -1px 1px 0 rgba(0, 0, 0, 0.8),
1px -1px 0 rgba(0, 0, 0, 0.8),
1px 1px 0 rgba(0, 0, 0, 0.8),
0 1px 0 rgba(0, 0, 0, 0.8),
0 -1px 0 rgba(0, 0, 0, 0.8),
1px 0 0 rgba(0, 0, 0, 0.8),
-1px 0 0 rgba(0, 0, 0, 0.8),
-1px -1px 0 rgba(0, 0, 0, 0.8);
}
.custom_rickshaw_graph {
position: relative;
left: 40px;
}
.custom_y_axis {
position: absolute;
width: 40px;
}
.custom_slider {
left: 40px;
}
.custom_x_axis {
position: relative;
left: 40px;
height: 30px;
width: 97%;
top: 20px;
text-align: right;
}
.chartWrapper {
padding-top: 50px;
}
/*detail*/
.rickshaw_graph .detail {
pointer-events: none;
position: absolute;
top: 0;
z-index: 2;
background: rgba(0, 0, 0, 0.1);
bottom: 0;
width: 1px;
transition: opacity 0.25s linear;
-moz-transition: opacity 0.25s linear;
-o-transition: opacity 0.25s linear;
-webkit-transition: opacity 0.25s linear;
}
.rickshaw_graph .detail.inactive {
opacity: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
}
.rickshaw_graph .detail .x_label {
font-family: Arial, sans-serif;
border-radius: 3px;
padding: 6px;
opacity: 0.5;
border: 1px solid #e0e0e0;
font-size: 12px;
position: absolute;
background: white;
white-space: nowrap;
}
.rickshaw_graph .detail .x_label.left {
left: 0;
}
.rickshaw_graph .detail .x_label.right {
right: 0;
}
.rickshaw_graph .detail .item {
position: absolute;
z-index: 2;
border-radius: 3px;
padding: 0.25em;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0;
background: rgba(0, 0, 0, 0.4);
color: white;
border: 1px solid rgba(0, 0, 0, 0.4);
margin-left: 1em;
margin-right: 1em;
margin-top: -1em;
white-space: nowrap;
}
.rickshaw_graph .detail .item.left {
left: 0;
}
.rickshaw_graph .detail .item.right {
right: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
background: rgba(0, 0, 0, 0.8);
}
.rickshaw_graph .detail .item:after {
position: absolute;
display: block;
width: 0;
height: 0;
content: "";
border: 5px solid transparent;
}
.rickshaw_graph .detail .item.left:after {
top: 1em;
left: -5px;
margin-top: -5px;
border-right-color: rgba(0, 0, 0, 0.8);
border-left-width: 0;
}
.rickshaw_graph .detail .item.right:after {
top: 1em;
right: -5px;
margin-top: -5px;
border-left-color: rgba(0, 0, 0, 0.8);
border-right-width: 0;
}
.rickshaw_graph .detail .dot {
width: 4px;
height: 4px;
margin-left: -3px;
margin-top: -3.5px;
border-radius: 5px;
position: absolute;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.6);
box-sizing: content-box;
-moz-box-sizing: content-box;
background: white;
border-width: 2px;
border-style: solid;
display: none;
background-clip: padding-box;
}
.rickshaw_graph .detail .dot.active {
display: block;
}
/*legend*/
.rickshaw_legend {
font-family: Arial;
font-size: 12px;
color: white;
background: #404040;
display: inline-block;
padding: 12px 5px;
border-radius: 2px;
position: relative;
float: right;
}
.rickshaw_legend:hover {
z-index: 10;
}
.rickshaw_legend .swatch {
width: 10px;
height: 10px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.rickshaw_legend .line {
clear: both;
line-height: 140%;
padding-right: 15px;
}
.rickshaw_legend .line .swatch {
display: inline-block;
margin-right: 3px;
border-radius: 2px;
}
.rickshaw_legend .label {
margin: 0;
white-space: nowrap;
display: inline;
font-size: inherit;
background-color: transparent;
color: inherit;
font-weight: normal;
line-height: normal;
padding: 0;
text-shadow: none;
}
.rickshaw_legend .action:hover {
opacity: 0.6;
}
.rickshaw_legend .action {
margin-right: 0.2em;
opacity: 0.2;
cursor: pointer;
font-size: 14px;
}
.rickshaw_legend .line.disabled {
opacity: 0.4;
}
.rickshaw_legend ul {
list-style-type: none;
padding: 0;
margin: 2px;
cursor: pointer;
}
.rickshaw_legend li {
padding: 0 0 0 2px;
min-width: 80px;
white-space: nowrap;
}
.rickshaw_legend li:hover {
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
.rickshaw_legend li:active {
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
}
.legend {
display: inline-block;
position: relative;
left: 8px;
}
.legend_container {
float: right;
padding-right: 10px;
width: 0;
z-index: 1;
position: relative;
opacity: 0.7;
}
.spaced {
margin-top: 20px !important;
}

@ -0,0 +1,265 @@
/*
* 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_drone(from, to) {
var devices = $("#drone-details").data("devices");
var tzOffset = new Date().getTimezoneOffset() * 60;
var streamIndex = 0;
var streams = ["battery", "heading", "bank", "attitude"];
populateGraph();
function populateGraph() {
if(streamIndex<4){
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, isMultilined) {
if (graphMap[type]) {
return graphMap[type];
}
var chartWrapperElmId = "#drone-div-chart";
var graphWidth = $(chartWrapperElmId).width() - 50;
console.log("document.getElementById("+ document.getElementById("chart-" + type)+ " ---"+ type);
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 {
if (isMultilined) {
graphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': "x"
},
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': "y"
},
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': "z"
}
);
} else {
graphConfig['series'].push(
{
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $("#drone-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) {
var graphObj = initGraph(type, false);
var graph = graphObj.graph;
var graphConfig = graphObj.config;
var deviceIndex = 0;
if (devices) {
getData();
} else {
var backendApiUrl = $("#drone-div-chart").data("backend-api-url") + "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data));
}
populateGraph();
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
populateGraph();
});
}
function getData() {
if (deviceIndex >= devices.length) {
return;
}
var backendApiUrl = $("#drone-div-chart").data("backend-api-url") + "?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.meta_time) - tzOffset,
y: parseInt(getFieldData(data[i], type))
}
);
}
graphConfig.series[deviceIndex].data = chartData;
graph.update();
}
}
function getFieldData(data, type) {
var columnData;
switch (type) {
case "battery" :
columnData = data.values.battery_level;
break;
case "heading" :
columnData = data.values.yaw;
break;
case "bank" :
columnData = data.values.roll;
break;
case "attitude" :
columnData = data.values.pitch;
break;
}
return columnData;
}
}

@ -1,28 +1,44 @@
{{#zone "topCss"}}
<style>
.thumbnail.icon:before {
padding-top: 0;
}
</style>
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/drone-icon.png"/>
{{/zone}}
{{#zone "device-opetations"}}
<div class="add-margin-top-4x">
{{unit "iot.unit.device.operation-bar" device=device}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<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 "iot.unit.device.droneanalyzer.statistics" device=device}}
<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.drone.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="#"

@ -15,20 +15,23 @@
* specific language governing permissions and limitations
* under the License.
*/
function onRequest(context) {
var log = new Log("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};
return {"device": device, "backendApiUri" : devicemgtProps["httpsURL"] + "/"+deviceType+"/", "autoCompleteParams" : autoCompleteParams};
} else {
response.sendError(404, "Device Id " + deviceId + "of type " + deviceType + " cannot be found!");
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
exit();
}
}
}
}

@ -0,0 +1,210 @@
{{#zone "topCss"}}
{{css "css/graph.css"}}
{{css "css/main-app.css" }}
{{/zone}}
<div id="div-chart" data-websocketurl="{{websocketEndpoint}}">
<div class="chartWrapper" id="chartWrapper">
<div class=" row">
<div class="box col-md-12">
<div>
<div class="col-md-0.5 col-sm-1 col-xs-2">
<p>Battery Level </p>
</div>
<div class="col-md-4 col-sm-2 col-xs-2">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0"
aria-valuemax="100" style="width: 0%;" id="batteryLevelPlaceholder">
<p id="batteryLevel">0%</p>
</div>
</div>
</div>
<div class="col-md-1 col-sm-1 col-xs-2">
<p>Battery Voltage </p>
</div>
<div class="col-md-4 col-sm-2 col-xs-2">
<div class="progress">
<div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0"
aria-valuemax="100" style="width: 0%;" id="batteryVoltagePlaceholder">
<p id="batteryVoltage">0%</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="box col-md-12">
<div class="box col-md-4">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2><i class="glyphicon glyphicon-list"></i> Angle of Rotation</h2>
<div class="box-icon" id="Rotation">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
</div>
</div>
<div class="box-content" style="position: relative;" id="objectHolder">
<div class="grayscale" border-radius="2" id="virtualDrone">
</div>
</div>
</div>
</div>
<div class="box col-md-2">
<div class="box-inner" style="max-height: 280px;">
<div class="box-header well" data-original-title="">
<div class="box-icon" id="AngleOfRotation">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div style="position: relative;">
<img class="grayscale" id="imageTop"
src="{{@unit.publicUri}}/images/drone_position_controller/direction_drone.png"
style="width: 100%;"/>
<img class="grayscale" id="imageBack"
src="{{@unit.publicUri}}/images/drone_position_controller/background_drone.png"
style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"/>
</div>
</div>
</div>
</div>
<div class="box col-md-2">
<div class="box-inner" style="max-height: 280px;">
<div class="box-header well" data-original-title="">
<div class="box-icon">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div style="position: relative;">
<img id="imageBackSecond"
src="{{@unit.publicUri}}/images/drone_position_controller/pitch_drone.png"
style="width: 100%;"/>
<img id="imageTopSecond"
src="{{@unit.publicUri}}/images/drone_position_controller/background_drone.png"
style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);"/>
</div>
</div>
</div>
</div>
<div class="box col-md-4">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2><i class="glyphicon glyphicon-list"></i>Live Video Stream</h2>
<div class="box-icon" id="LiveVideoStream">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<img class="grayscale" src="{{@unit.publicUri}}/images/no_video_preview.gif"
alt="video stream" style="display: block; height:225px; margin: auto;">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="box col-md-12">
<div class="box col-md-4">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2><i class="glyphicon glyphicon-list"></i>Sensor Readings</h2>
<div class="box-icon" id="SensorReadings">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
</div>
</div>
<div class="box-content" id="basicSensoReading">
<div>
<p>Location</br> latitude: <label id="locationLat"></label></br>
longitude: <label id="locationLog"></label></br>
altitudes: <label id="locationAlt"></label></p>
<p> Velocity:</br> x :<label id="velocityx"></label></br>
y : <label id="velocityy"></label></br>
z : <label id="velocityz"></label></p>
</div>
</div>
</div>
</div>
<div class="box col-md-8">
<div class="box-inner">
<div class="box-header well" data-original-title="">
<h2><i class="glyphicon glyphicon-list-alt"></i>Realtime Plotting</h2>
<div class="box-icon" id="RealtimePlotting">
<a href="#" class="btn btn-minimize btn-round btn-default"><i
class="glyphicon glyphicon-chevron-up"></i></a>
</div>
</div>
<div class="box-content">
<div class="row">
<div class="box col-md-4" id="plottingMetadata" style="margin-left: 5%">
<div>
Window size : <label id="windowSizeCurrentValue">30</label>
<div id="windowSize" style="width: 100%;"></div>
<br>
Update period : <label id="windowUpdateValue">300</label>
</div>
<div id="windowUpdate" style="width: 100%;"></div>
</br>
<div style="width:100%;">Y-axis: <label>Min: <input id="rangeMin" type="text"
value="-4" size="3"></label>
<label>Max: <input id="rangeMax" value="4" type="text" size="3"></label></div>
<div style="width:100%;"><select ng-model='discussionsSelect' class='form-control'
id="plottingAttribute">
<option value='heading' selected>Heading</option>
<option value='bank'>Bank</option>
<option value='attitude'>Attitude</option>
</select></div>
</br>
<div>
<button class="btn btn-primary" id="replotting">Replot</button>
</div>
</div>
<div class="box col-md-8" id="realtimeChart" style="width:20%; height: 250px;"></div>
</div>
</div>
</div>
</div>
</div>
</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/libs/d3.min.js"}}
{{js "js/libs/rickshaw.min.js"}}
{{js "js/libs/moment.min.js"}}
{{js "js/libs/socket.io.min.js"}}
{{js "/js/libs/three.min.js" }}
{{js "/js/libs/Coordinates.js" }}
{{js "/js/libs/OrbitAndPanControls.js" }}
{{js "/js/3DDroneController/controler.js" }}
{{js "/js/libs/jQueryRotate.js" }}
{{js "/js/config/config.js" }}
{{js "/js/common/ajaxHandler.js" }}
{{js "/js/modules/realtimePlotting.js" }}
{{js "/js/init.js" }}
{{js "/js/modules/controller.js" }}
{{js "/js/modules/flightDynamics.js" }}
{{js "/js/mainHandler.js" }}
{{/zone}}

@ -0,0 +1,33 @@
/*
* 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("stats.js");
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.devices.droneStats/1.0.0?" +
"token="+ token +"&deviceId=" + device.deviceIdentifier + "&deviceType=" + device.type;
return {"device": device, "websocketEndpoint" : websocketEndpoint};
}

@ -0,0 +1,471 @@
/*
* 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.
*/
/* graph */
.rickshaw_graph {
position: relative;
}
.rickshaw_graph svg {
display: block;
overflow: hidden;
}
/* ticks */
.rickshaw_graph .x_tick {
position: absolute;
top: 0;
bottom: 0;
width: 0;
border-left: 1px dotted rgba(0, 0, 0, 0.2);
pointer-events: none;
}
.rickshaw_graph .x_tick .title {
position: absolute;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0.5;
white-space: nowrap;
margin-left: 3px;
bottom: -20px;
height: auto;
border-bottom: none;
}
/* annotations */
.rickshaw_annotation_timeline {
height: 1px;
border-top: 1px solid #e0e0e0;
margin-top: 10px;
position: relative;
}
.rickshaw_annotation_timeline .annotation {
position: absolute;
height: 6px;
width: 6px;
margin-left: -2px;
top: -3px;
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.25);
}
.rickshaw_graph .annotation_line {
position: absolute;
top: 0;
bottom: -6px;
width: 0;
border-left: 2px solid rgba(0, 0, 0, 0.3);
display: none;
}
.rickshaw_graph .annotation_line.active {
display: block;
}
.rickshaw_graph .annotation_range {
background: rgba(0, 0, 0, 0.1);
display: none;
position: absolute;
top: 0;
bottom: -6px;
}
.rickshaw_graph .annotation_range.active {
display: block;
}
.rickshaw_graph .annotation_range.active.offscreen {
display: none;
}
.rickshaw_annotation_timeline .annotation .content {
background: white;
color: black;
opacity: 0.9;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.8);
border-radius: 3px;
position: relative;
z-index: 20;
font-size: 12px;
padding: 6px 8px 8px;
top: 18px;
left: -11px;
width: 160px;
display: none;
cursor: pointer;
}
.rickshaw_annotation_timeline .annotation .content:before {
content: "\25b2";
position: absolute;
top: -11px;
color: white;
text-shadow: 0 -1px 1px rgba(0, 0, 0, 0.8);
}
.rickshaw_annotation_timeline .annotation.active,
.rickshaw_annotation_timeline .annotation:hover {
background-color: rgba(0, 0, 0, 0.8);
cursor: none;
}
.rickshaw_annotation_timeline .annotation .content:hover {
z-index: 50;
}
.rickshaw_annotation_timeline .annotation.active .content {
display: block;
}
.rickshaw_annotation_timeline .annotation:hover .content {
display: block;
z-index: 50;
}
.rickshaw_graph .y_axis,
.rickshaw_graph .x_axis_d3 {
fill: none;
}
.rickshaw_graph .y_ticks .tick line,
.rickshaw_graph .x_ticks_d3 .tick {
stroke: rgba(0, 0, 0, 0.16);
stroke-width: 2px;
shape-rendering: crisp-edges;
pointer-events: none;
}
.rickshaw_graph .y_grid .tick,
.rickshaw_graph .x_grid_d3 .tick {
z-index: -1;
stroke: rgba(0, 0, 0, 0.20);
stroke-width: 1px;
stroke-dasharray: 1 1;
}
.rickshaw_graph .y_grid .tick[data-y-value="0"] {
stroke-dasharray: 1 0;
}
.rickshaw_graph .y_grid path,
.rickshaw_graph .x_grid_d3 path {
fill: none;
stroke: none;
}
.rickshaw_graph .y_ticks path,
.rickshaw_graph .x_ticks_d3 path {
fill: none;
stroke: #808080;
}
.rickshaw_graph .y_ticks text,
.rickshaw_graph .x_ticks_d3 text {
opacity: 0.5;
font-size: 12px;
pointer-events: none;
}
.rickshaw_graph .x_tick.glow .title,
.rickshaw_graph .y_ticks.glow text {
fill: black;
color: black;
text-shadow: -1px 1px 0 rgba(255, 255, 255, 0.1),
1px -1px 0 rgba(255, 255, 255, 0.1),
1px 1px 0 rgba(255, 255, 255, 0.1),
0 1px 0 rgba(255, 255, 255, 0.1),
0 -1px 0 rgba(255, 255, 255, 0.1),
1px 0 0 rgba(255, 255, 255, 0.1),
-1px 0 0 rgba(255, 255, 255, 0.1),
-1px -1px 0 rgba(255, 255, 255, 0.1);
}
.rickshaw_graph .x_tick.inverse .title,
.rickshaw_graph .y_ticks.inverse text {
fill: white;
color: white;
text-shadow: -1px 1px 0 rgba(0, 0, 0, 0.8),
1px -1px 0 rgba(0, 0, 0, 0.8),
1px 1px 0 rgba(0, 0, 0, 0.8),
0 1px 0 rgba(0, 0, 0, 0.8),
0 -1px 0 rgba(0, 0, 0, 0.8),
1px 0 0 rgba(0, 0, 0, 0.8),
-1px 0 0 rgba(0, 0, 0, 0.8),
-1px -1px 0 rgba(0, 0, 0, 0.8);
}
.custom_rickshaw_graph {
position: relative;
left: 40px;
}
.custom_y_axis {
position: absolute;
width: 40px;
margin-top: -20px;
}
.custom_slider {
left: 40px;
}
.custom_x_axis {
position: relative;
left: 40px;
height: 30px;
width: 97%;
top: 20px;
text-align: right;
}
.chartWrapper {
padding-top: 50px;
}
/*detail*/
.rickshaw_graph .detail {
pointer-events: none;
position: absolute;
top: 0;
z-index: 2;
background: rgba(0, 0, 0, 0.1);
bottom: 0;
width: 1px;
transition: opacity 0.25s linear;
-moz-transition: opacity 0.25s linear;
-o-transition: opacity 0.25s linear;
-webkit-transition: opacity 0.25s linear;
}
.rickshaw_graph .detail.inactive {
opacity: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
}
.rickshaw_graph .detail .x_label {
font-family: Arial, sans-serif;
border-radius: 3px;
padding: 6px;
opacity: 0.5;
border: 1px solid #e0e0e0;
font-size: 12px;
position: absolute;
background: white;
white-space: nowrap;
}
.rickshaw_graph .detail .x_label.left {
left: 0;
}
.rickshaw_graph .detail .x_label.right {
right: 0;
}
.rickshaw_graph .detail .item {
position: absolute;
z-index: 2;
border-radius: 3px;
padding: 0.25em;
font-size: 12px;
font-family: Arial, sans-serif;
opacity: 0;
background: rgba(0, 0, 0, 0.4);
color: white;
border: 1px solid rgba(0, 0, 0, 0.4);
margin-left: 1em;
margin-right: 1em;
margin-top: -1em;
white-space: nowrap;
}
.rickshaw_graph .detail .item.left {
left: 0;
}
.rickshaw_graph .detail .item.right {
right: 0;
}
.rickshaw_graph .detail .item.active {
opacity: 1;
background: rgba(0, 0, 0, 0.8);
}
.rickshaw_graph .detail .item:after {
position: absolute;
display: block;
width: 0;
height: 0;
content: "";
border: 5px solid transparent;
}
.rickshaw_graph .detail .item.left:after {
top: 1em;
left: -5px;
margin-top: -5px;
border-right-color: rgba(0, 0, 0, 0.8);
border-left-width: 0;
}
.rickshaw_graph .detail .item.right:after {
top: 1em;
right: -5px;
margin-top: -5px;
border-left-color: rgba(0, 0, 0, 0.8);
border-right-width: 0;
}
.rickshaw_graph .detail .dot {
width: 4px;
height: 4px;
margin-left: -3px;
margin-top: -3.5px;
border-radius: 5px;
position: absolute;
box-shadow: 0 0 2px rgba(0, 0, 0, 0.6);
box-sizing: content-box;
-moz-box-sizing: content-box;
background: white;
border-width: 2px;
border-style: solid;
display: none;
background-clip: padding-box;
}
.rickshaw_graph .detail .dot.active {
display: block;
}
/*legend*/
.rickshaw_legend {
font-family: Arial;
font-size: 12px;
color: white;
background: #404040;
display: inline-block;
padding: 12px 5px;
border-radius: 2px;
position: relative;
float: right;
}
.rickshaw_legend:hover {
z-index: 10;
}
.rickshaw_legend .swatch {
width: 10px;
height: 10px;
border: 1px solid rgba(0, 0, 0, 0.2);
}
.rickshaw_legend .line {
clear: both;
line-height: 140%;
padding-right: 15px;
}
.rickshaw_legend .line .swatch {
display: inline-block;
margin-right: 3px;
border-radius: 2px;
}
.rickshaw_legend .label {
margin: 0;
white-space: nowrap;
display: inline;
font-size: inherit;
background-color: transparent;
color: inherit;
font-weight: normal;
line-height: normal;
padding: 0;
text-shadow: none;
}
.rickshaw_legend .action:hover {
opacity: 0.6;
}
.rickshaw_legend .action {
margin-right: 0.2em;
opacity: 0.2;
cursor: pointer;
font-size: 14px;
}
.rickshaw_legend .line.disabled {
opacity: 0.4;
}
.rickshaw_legend ul {
list-style-type: none;
padding: 0;
margin: 2px;
cursor: pointer;
}
.rickshaw_legend li {
padding: 0 0 0 2px;
min-width: 80px;
white-space: nowrap;
}
.rickshaw_legend li:hover {
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
}
.rickshaw_legend li:active {
background: rgba(255, 255, 255, 0.2);
border-radius: 3px;
}
.legend {
display: inline-block;
position: relative;
left: 8px;
}
.legend_container {
float: right;
padding-right: 10px;
width: 0;
z-index: 1;
position: relative;
opacity: 0.7;
}
.spaced {
margin-top: 20px !important;
}

@ -0,0 +1,186 @@
/*
* 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 camera, scene, renderer;
var cameraControls;
var clock = new THREE.Clock();
var ground = true;
var circle1, plate1;
var droneRender = function () {
var api = this;
api.fillScene = function () {
scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x808080, 2000, 4000);
var ambientLight = new THREE.AmbientLight(0x222222);
var light = new THREE.DirectionalLight(0xFFFFFF, 1.0);
light.position.set(200, 400, 500);
var light2 = new THREE.DirectionalLight(0xFFFFFF, 1.0);
light2.position.set(-500, 250, -200);
scene.add(ambientLight);
scene.add(light);
scene.add(light2);
if (ground) {
Coordinates.drawGround({size: 10000});
}
var robotBaseMaterial = new THREE.MeshPhongMaterial({color: 0x6E23BB, specular: 0x6E23BB, shininess: 20});
var robotForearmMaterial = new THREE.MeshPhongMaterial({color: 0xF4C154, specular: 0xF4C154, shininess: 100});
circle1 = new THREE.Object3D();
var circleLength = 40;
api.addCircles(circle1, circleLength, robotBaseMaterial);
circle1.position.y = circleLength * 2;
scene.add(circle1);
plate1 = new THREE.Object3D();
var plateLength = 40;
api.addPlates(plate1, plateLength, robotForearmMaterial);
plate1.position.y = circleLength / 8;
circle1.add(plate1);
},
api.addPlates = function (part, plateLength, material) {
var cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.position.x = plateLength + 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.rotation.z = 90 * Math.PI / 180;
cylinder.position.x = plateLength + 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.position.x = -plateLength - 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.rotation.z = 90 * Math.PI / 180;
cylinder.position.x = -plateLength - 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.position.z = -plateLength - 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.rotation.z = 90 * Math.PI / 180;
cylinder.position.z = -plateLength - 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.position.z = plateLength + 15;
part.add(cylinder);
cylinder = new THREE.Mesh(
new THREE.CylinderGeometry(5, 5, 40, 32), material);
cylinder.rotation.x = 90 * Math.PI / 180;
cylinder.rotation.z = 90 * Math.PI / 180;
cylinder.position.z = plateLength + 15;
part.add(cylinder);
},
api.addCircles = function (part, circleLength, material) {
var circle = new THREE.Mesh(
new THREE.TorusGeometry(40, 10, 40, 20, 6.3), material);
circle.position.x = circleLength + 10;
circle.rotation.x = 90 * Math.PI / 180;
part.add(circle);
circle = new THREE.Mesh(
new THREE.TorusGeometry(40, 10, 40, 20, 6.3), material);
circle.position.x = -circleLength - 10;
circle.rotation.x = 90 * Math.PI / 180;
part.add(circle);
circle = new THREE.Mesh(
new THREE.TorusGeometry(40, 10, 40, 20, 6.3), material);
circle.position.z = -circleLength - 10;
circle.rotation.x = 90 * Math.PI / 180;
part.add(circle);
circle = new THREE.Mesh(
new THREE.TorusGeometry(40, 10, 40, 20, 6.3), material);
circle.position.z = circleLength + 10;
circle.rotation.x = 90 * Math.PI / 180;
part.add(circle);
},
api.init = function (holder, object_width, object_height) {
var canvasRatio = 1;
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.gammaInput = true;
renderer.gammaOutput = true;
renderer.setSize(object_width, object_height);
renderer.setClearColorHex(0xAAAAAA, 1.0);
$(holder).append(renderer.domElement);
camera = new THREE.PerspectiveCamera(30, canvasRatio, 1, 10000);
camera.position.set(-510, 240, 100);
cameraControls = new THREE.OrbitAndPanControls(camera, renderer.domElement);
cameraControls.target.set(0, 100, 0);
api.fillScene();
},
api.animate = function () {
window.requestAnimationFrame(api.animate);
api.render();
},
api.render = function () {
var delta = clock.getDelta();
cameraControls.update(delta);
circle1.rotation.z = config.effectController.uz;
circle1.rotation.y = config.effectController.uy; // yaw
circle1.rotation.x = config.effectController.ux; // roll
circle1.position.z = config.effectController.fz;
circle1.position.x = config.effectController.fx;
renderer.render(scene, camera);
},
api.getHeadingAttitudeAndBank = function (data) {
if (data.length < 4) {
return {"heading": data[0], "attitude": data[1], "bank": data[2]};
} else {
var heading = Math.atan2(2 * data[1] * data[3] - 2 * data[0] * data[1], 1 - 2 * data[1] * data[1]
- 2 * data[2] * data[2]);
var bank = Math.atan2(2 * data[0] * data[3] - 2 * data[1] * data[2], 1 - 2 * data[0] * data[0]
- 2 * data[2] * data[2]);
var attitude = Math.asin(2 * data[0] * data[1] + 2 * data[2] * data[3]);
return {
"heading": isNaN(heading) ? 0 : heading,
"bank": isNaN(bank) ? 0 : bank,
"attitude": isNaN(attitude) ? 0 : attitude
};
}
},
api.setHeadingAttitudeAndBank = function (data) {
config.effectController.uy = data.heading;
config.effectController.uz = data.attitude;
config.effectController.ux = data.bank;
},
api.setHeading = function (holder, heading) {
var r = (180 / Math.PI) * parseFloat(heading);
$(holder).rotate(r);
},
api.setBank = function (holder, bank) {
var r = (180 / Math.PI) * parseFloat(bank);
$(holder).rotate(r);
}
};

@ -0,0 +1,47 @@
/*
* 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 ajax_handler = function () {
var api = this;
api.response = "v";
api.ajaxRequest = function (url, type, data, dataType, callback) {
var response;
$.ajax({
url: url,
type: type,
dataType: dataType,
success: function (data, success) {
api.response = data;
callback(data, success);
},
error: function (jqxhr, textStatus, error) {
var err = textStatus + ', ' + error;
callback(data, error);
api.response = data;
},
data: data
});
return api.response;
};
api.makeJSONObject = function () {
var object = {};
for (var i = 0; i < arguments.length - 1; i = i + 2) {
object[arguments[i]] = arguments[i + 1];
}
return object;
}
};

@ -0,0 +1,34 @@
/*
* 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 config = function () {
var api = this;
api.configDronePlaceholder = "#virtualDrone";
api.realtimePlottingUpdateInterval = 30;
api.realtimePlottingTotalPoints = 30;
api.realtimePlottingDataWindow = {};
api.effectController = {uy: 70.0, uz: 15.0, ux: 10.0, fx: 2.0, fz: 15.0, Tmax: 1};
api.controlType = "POST";
api.dataType = "json";
api.modulesStatus = {
"realtimePlotting": false,
"sensorReadings": false,
"angleOfRotationv1": false,
"angleOfRotationv2": false
};
};

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save