parent
7450910748
commit
273cb989d4
@ -0,0 +1,195 @@
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2</groupId>
|
||||
<artifactId>wso2</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
|
||||
<modules>
|
||||
<module>sampledevice</module>
|
||||
</modules>
|
||||
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<groupId>org.wso2.iot.devicemgt-plugins</groupId>
|
||||
<artifactId>iot-devicetype-samples</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>Creating custom distribution</name>
|
||||
<url>http://wso2.org</url>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.wso2.maven</groupId>
|
||||
<artifactId>carbon-p2-plugin</artifactId>
|
||||
<version>1.5.4</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>2-p2-repo-generation</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>p2-repo-gen</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<metadataRepository>file:${basedir}/p2-repo</metadataRepository>
|
||||
<artifactRepository>file:${basedir}/p2-repo</artifactRepository>
|
||||
<publishArtifacts>true</publishArtifacts>
|
||||
<publishArtifactRepository>true</publishArtifactRepository>
|
||||
<featureArtifacts>
|
||||
<featureArtifactDef>
|
||||
org.wso2.carbon:org.wso2.carbon.sampledevice.feature:1.0.0
|
||||
</featureArtifactDef>
|
||||
</featureArtifacts>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>default-feature-install</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>p2-profile-gen</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<profile>default</profile>
|
||||
<metadataRepository>file:${basedir}/p2-repo</metadataRepository>
|
||||
<artifactRepository>file:${basedir}/p2-repo</artifactRepository>
|
||||
<destination>${basedir}/../wso2/components</destination>
|
||||
<deleteOldProfileFiles>false</deleteOldProfileFiles>
|
||||
<features>
|
||||
<feature>
|
||||
<id>org.wso2.carbon.sampledevice.feature.group</id>
|
||||
<version>1.0.0</version>
|
||||
</feature>
|
||||
</features>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>1.1</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-feature-install</id>
|
||||
<phase>package</phase>
|
||||
<configuration>
|
||||
<tasks>
|
||||
<replace token="false" value="true"
|
||||
dir="../wso2/components/default/configuration/org.eclipse.equinox.simpleconfigurator">
|
||||
<include name="**/bundles.info"/>
|
||||
</replace>
|
||||
<copy todir="../wso2/analytics/repository/deployment/server/carbonapps">
|
||||
<fileset dir="../repository/deployment/server/carbonapps">
|
||||
<include name="*.car"/>
|
||||
</fileset>
|
||||
</copy>
|
||||
</tasks>
|
||||
</configuration>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>wso2.releases</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>wso2.snapshots</id>
|
||||
<name>Apache Snapshot Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
</snapshots>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>wso2-nexus</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
|
||||
<repositories>
|
||||
<!-- Before adding ANYTHING in here, please start a discussion on the dev list.
|
||||
Ideally the Axis2 build should only use Maven central (which is available
|
||||
by default) and nothing else. We had troubles with other repositories in
|
||||
the past. Therefore configuring additional repositories here should be
|
||||
considered very carefully. -->
|
||||
<repository>
|
||||
<id>wso2-nexus</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>wso2.releases</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>wso2.snapshots</id>
|
||||
<name>WSO2 Snapshot Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
</snapshots>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<carbon.device.mgt.plugin.version>4.0.34</carbon.device.mgt.plugin.version>
|
||||
</properties>
|
||||
</project>
|
@ -0,0 +1,36 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--/*
|
||||
* Copyright (c) 2017, 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="sensorType1_dir" value="sensor_temp"/>
|
||||
|
||||
<target name="clean">
|
||||
<delete dir="${target-dir}"/>
|
||||
</target>
|
||||
<target name="zip" depends="clean">
|
||||
<mkdir dir="${target-dir}"/>
|
||||
<zip destfile="${target-dir}/${sensorType1_dir}.car">
|
||||
<zipfileset dir="${src-dir}/${sensorType1_dir}"/>
|
||||
</zip>
|
||||
|
||||
</target>
|
||||
</project>
|
||||
|
@ -0,0 +1,88 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice-component</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>${groupId}.sampledevice.analytics</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>pom</packaging>
|
||||
<name>${groupId}.sampledevice.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,37 @@
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<assembly
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0
|
||||
http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
||||
<id>src</id>
|
||||
<formats>
|
||||
<format>zip</format>
|
||||
</formats>
|
||||
<includeBaseDirectory>false</includeBaseDirectory>
|
||||
<baseDirectory>${basedir}/src</baseDirectory>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>${basedir}/target/carbonapps</directory>
|
||||
<outputDirectory>/</outputDirectory>
|
||||
<useDefaultExcludes>true</useDefaultExcludes>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
</assembly>
|
@ -0,0 +1,33 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<artifacts>
|
||||
<artifact name="sensor_temp_CAPP" version="1.0.0" type="carbon/application">
|
||||
<dependency artifact="sensor_temp_stream" version="1.0.0" include="true"
|
||||
serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="sensor_temp_store" version="1.0.0" include="true"
|
||||
serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="sensor_temp_mqtt_receiver" version="1.0.0" include="true"
|
||||
serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="sensor_temp_publisher" version="1.0.0" include="true"
|
||||
serverRole="DataAnalyticsServer"/>
|
||||
<dependency artifact="sensor_temp_spark_script" version="1.0.0" include="true"
|
||||
serverRole="DataAnalyticsServer"/>
|
||||
</artifact>
|
||||
</artifacts>
|
@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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="sensor_temp_mqtt_receiver" version="1.0.0" type="event/receiver"
|
||||
serverRole="DataAnalyticsServer">
|
||||
<file>sensor_temp_mqtt_receiver.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,32 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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="sensor_temp-mqtt" statistics="disable" trace="disable"
|
||||
xmlns="http://wso2.org/carbon/eventreceiver">
|
||||
<from eventAdapterType="oauth-mqtt">
|
||||
<property name="topic">carbon.super/sampledevice/+/sensor_temp</property>
|
||||
<property name="username">admin</property>
|
||||
<property name="password">admin</property>
|
||||
<property name="contentValidator">
|
||||
org.wso2.carbon.device.mgt.input.adapter.mqtt.util.MQTTContentValidator
|
||||
</property>
|
||||
<property name="cleanSession">true</property>
|
||||
</from>
|
||||
<mapping customMapping="disable" type="json"/>
|
||||
<to streamName="org.wso2.iot.devices.sensor_temp" version="1.0.0"/>
|
||||
</eventReceiver>
|
@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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="sensor_temp_publisher" version="1.0.0" type="event/publisher"
|
||||
serverRole="DataAnalyticsServer">
|
||||
<file>sensor_temp_publisher.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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_sensor_temp" statistics="disable" trace="disable"
|
||||
xmlns="http://wso2.org/carbon/eventpublisher">
|
||||
<from streamName="org.wso2.iot.devices.sensor_temp" version="1.0.0"/>
|
||||
<mapping customMapping="disable" type="wso2event"/>
|
||||
<to eventAdapterType="secured-websocket"/>
|
||||
</eventPublisher>
|
||||
|
@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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="sensor_temp_spark_script" version="1.0.0" type="analytics/spark"
|
||||
serverRole="DataAnalyticsServer">
|
||||
<file>sensor_temp_spark_script.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,34 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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>sensor_temp_spark_script</Name>
|
||||
<Script>
|
||||
CREATE TEMPORARY TABLE Devicesensor_tempData USING CarbonAnalytics OPTIONS(tableName
|
||||
"ORG_WSO2_IOT_DEVICES_sensor_temp");
|
||||
CREATE TEMPORARY TABLE Devicesensor_tempSummaryData USING CarbonAnalytics OPTIONS (tableName
|
||||
"DEVICE_sensor_temp_SUMMARY", schema "sensor_temp FLOAT, deviceType STRING -i, deviceId
|
||||
STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
|
||||
insert overwrite table Devicesensor_tempSummaryData select sensor_temp, meta_deviceType as
|
||||
deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time as BIGINT)as time
|
||||
from Devicesensor_tempData group by sensor_temp, meta_deviceType, meta_deviceId, meta_owner,
|
||||
cast(meta_time as BIGINT);
|
||||
</Script>
|
||||
<CronExpression>0 * * * * ?</CronExpression>
|
||||
</Analytics>
|
@ -0,0 +1,23 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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="sensor_temp_store" version="1.0.0" type="analytics/eventstore"
|
||||
serverRole="DataAnalyticsServer">
|
||||
<file>org_wso2_iot_devices_sensor_temp.xml</file>
|
||||
</artifact>
|
@ -0,0 +1,62 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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.sensor_temp: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>sensor_temp</Name>
|
||||
<EnableIndexing>false</EnableIndexing>
|
||||
<IsPrimaryKey>false</IsPrimaryKey>
|
||||
<EnableScoreParam>false</EnableScoreParam>
|
||||
<Type>FLOAT</Type>
|
||||
</ColumnDefinition>
|
||||
</TableSchema>
|
||||
</EventStoreConfiguration>
|
@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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="sensor_temp_stream" version="1.0.0" type="event/stream"
|
||||
serverRole="DataAnalyticsServer">
|
||||
<file>org.wso2.iot.devices.sensor_temp_1.0.0.json</file>
|
||||
</artifact>
|
||||
|
@ -0,0 +1,33 @@
|
||||
{
|
||||
"name": "org.wso2.iot.devices.sensor_temp",
|
||||
"version": "1.0.0",
|
||||
"nickName": "sensor_temp",
|
||||
"description": "sensor_temp data received from the Device",
|
||||
"metaData": [
|
||||
{
|
||||
"name": "owner",
|
||||
"type": "STRING"
|
||||
},
|
||||
{
|
||||
"name": "deviceType",
|
||||
"type": "STRING"
|
||||
},
|
||||
{
|
||||
"name": "deviceId",
|
||||
"type": "STRING"
|
||||
},
|
||||
{
|
||||
"name": "time",
|
||||
"type": "LONG"
|
||||
}
|
||||
],
|
||||
"payloadData": [
|
||||
{
|
||||
"name": "sensor_temp",
|
||||
"type": "FLOAT"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
|
@ -0,0 +1,143 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice-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>
|
||||
<artifactId>axis2-client</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
|
||||
<!--CXF -->
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.plugin</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!--JAX-RS -->
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-core-asl</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-jaxrs</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-web-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,150 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api;
|
||||
|
||||
import io.swagger.annotations.ApiOperation;
|
||||
import io.swagger.annotations.Extension;
|
||||
import io.swagger.annotations.ExtensionProperty;
|
||||
import io.swagger.annotations.Info;
|
||||
import io.swagger.annotations.SwaggerDefinition;
|
||||
import io.swagger.annotations.Tag;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scope;
|
||||
import org.wso2.carbon.apimgt.annotations.api.Scopes;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
|
||||
/**
|
||||
* This is the API which is used to control and manage device type functionality.
|
||||
*/
|
||||
@SwaggerDefinition(
|
||||
info = @Info(
|
||||
version = "1.0.0",
|
||||
title = "",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = "name", value = "sampledevice"),
|
||||
@ExtensionProperty(name = "context", value = "/sampledevice"),
|
||||
})
|
||||
}
|
||||
),
|
||||
tags = {
|
||||
@Tag(name = "sampledevice,device_management", description = "")
|
||||
}
|
||||
)
|
||||
@Scopes(
|
||||
scopes = {
|
||||
@Scope(
|
||||
name = "Enroll device",
|
||||
description = "",
|
||||
key = "perm:sampledevice:enroll",
|
||||
permissions = {"/device-mgt/devices/enroll/sampledevice"}
|
||||
)
|
||||
}
|
||||
)
|
||||
@SuppressWarnings("NonJaxWsWebServices")
|
||||
public interface DeviceTypeService {
|
||||
String SCOPE = "scope";
|
||||
|
||||
/**
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param state change status of sensor: on/off
|
||||
*/
|
||||
@Path("device/{deviceId}/change-status")
|
||||
@POST
|
||||
@ApiOperation(
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "POST",
|
||||
value = "Switch Status",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "sampledevice",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = SCOPE, value = "perm:sampledevice:enroll")
|
||||
})
|
||||
}
|
||||
)
|
||||
Response changeStatus(@PathParam("deviceId") String deviceId,
|
||||
@QueryParam("state") String state,
|
||||
@Context HttpServletResponse response);
|
||||
|
||||
/**
|
||||
* 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")
|
||||
@ApiOperation(
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Sensor Stats",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "sampledevice",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = SCOPE, value = "perm:sampledevice:enroll")
|
||||
})
|
||||
}
|
||||
)
|
||||
Response getSensorStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
|
||||
@QueryParam("to") long to, @QueryParam("sensorType") String sensorType);
|
||||
|
||||
/**
|
||||
* 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")
|
||||
@ApiOperation(
|
||||
consumes = MediaType.APPLICATION_JSON,
|
||||
httpMethod = "GET",
|
||||
value = "Download",
|
||||
notes = "",
|
||||
response = Response.class,
|
||||
tags = "sampledevice",
|
||||
extensions = {
|
||||
@Extension(properties = {
|
||||
@ExtensionProperty(name = SCOPE, value = "perm:sampledevice:enroll")
|
||||
})
|
||||
}
|
||||
)
|
||||
Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType);
|
||||
}
|
@ -0,0 +1,323 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api;
|
||||
|
||||
|
||||
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.SortByField;
|
||||
import org.wso2.carbon.analytics.dataservice.commons.SortType;
|
||||
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
|
||||
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.InvalidDeviceException;
|
||||
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
|
||||
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
|
||||
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
|
||||
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.sampledevice.api.dto.DeviceJSON;
|
||||
import org.wso2.carbon.sampledevice.api.dto.SensorRecord;
|
||||
import org.wso2.carbon.sampledevice.api.util.APIUtil;
|
||||
import org.wso2.carbon.sampledevice.api.util.ZipArchive;
|
||||
import org.wso2.carbon.sampledevice.api.util.ZipUtil;
|
||||
import org.wso2.carbon.sampledevice.plugin.constants.DeviceTypeConstants;
|
||||
import org.wso2.carbon.user.api.UserStoreException;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.UUID;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import javax.ws.rs.Consumes;
|
||||
import javax.ws.rs.GET;
|
||||
import javax.ws.rs.POST;
|
||||
import javax.ws.rs.Path;
|
||||
import javax.ws.rs.PathParam;
|
||||
import javax.ws.rs.Produces;
|
||||
import javax.ws.rs.QueryParam;
|
||||
import javax.ws.rs.core.Context;
|
||||
import javax.ws.rs.core.MediaType;
|
||||
import javax.ws.rs.core.Response;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* This is the API which is used to control and manage device type functionality.
|
||||
*/
|
||||
public class DeviceTypeServiceImpl implements DeviceTypeService {
|
||||
|
||||
private static final String KEY_TYPE = "PRODUCTION";
|
||||
private static Log log = LogFactory.getLog(DeviceTypeService.class);
|
||||
private static ApiApplicationKey apiApplicationKey;
|
||||
|
||||
private 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)) {
|
||||
return Response.status(Response.Status.OK).build();
|
||||
}
|
||||
return Response.status(Response.Status.NOT_ACCEPTABLE).build();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param state change status of sensor: on/off
|
||||
*/
|
||||
@Path("device/{deviceId}/change-status")
|
||||
@POST
|
||||
public Response changeStatus(@PathParam("deviceId") String deviceId,
|
||||
@QueryParam("state") String state,
|
||||
@Context HttpServletResponse response) {
|
||||
try {
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
|
||||
DeviceTypeConstants.DEVICE_TYPE))) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
String sensorState = state.toUpperCase();
|
||||
if (!sensorState.equals(DeviceTypeConstants.STATE_ON) && !sensorState.equals(
|
||||
DeviceTypeConstants.STATE_OFF)) {
|
||||
log.error("The requested state change should be either - 'ON' or 'OFF'");
|
||||
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
|
||||
}
|
||||
Map<String, String> dynamicProperties = new HashMap<>();
|
||||
String publishTopic = APIUtil.getAuthenticatedUserTenantDomain()
|
||||
+ "/" + DeviceTypeConstants.DEVICE_TYPE + "/" + deviceId + "/command";
|
||||
|
||||
String actualMessage = DeviceTypeConstants.BULB_CONTEXT + ':' + sensorState;
|
||||
|
||||
dynamicProperties.put(DeviceTypeConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
|
||||
Operation commandOp = new CommandOperation();
|
||||
commandOp.setCode("change-status");
|
||||
commandOp.setType(Operation.Type.COMMAND);
|
||||
commandOp.setEnabled(true);
|
||||
commandOp.setPayLoad(actualMessage);
|
||||
|
||||
Properties props = new Properties();
|
||||
props.setProperty("mqtt.adapter.topic", publishTopic);
|
||||
commandOp.setProperties(props);
|
||||
|
||||
List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
|
||||
deviceIdentifiers.add(new DeviceIdentifier(deviceId, "sampledevice"));
|
||||
APIUtil.getDeviceManagementService().addOperation("sampledevice", commandOp,
|
||||
deviceIdentifiers);
|
||||
return Response.ok().build();
|
||||
} catch (DeviceAccessAuthorizationException e) {
|
||||
log.error(e.getErrorMessage(), e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (OperationManagementException e) {
|
||||
String msg = "Error occurred while executing command operation upon ringing the buzzer";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
|
||||
} catch (InvalidDeviceException e) {
|
||||
String msg = "Error occurred while executing command operation to send keywords";
|
||||
log.error(msg, e);
|
||||
return Response.status(Response.Status.BAD_REQUEST).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, @QueryParam("sensorType") String sensorType) {
|
||||
String fromDate = String.valueOf(from);
|
||||
String toDate = String.valueOf(to);
|
||||
String query = "meta_deviceId:" + deviceId + " AND meta_deviceType:" +
|
||||
DeviceTypeConstants.DEVICE_TYPE + " AND meta_time : [" + fromDate + " TO " + toDate + "]";
|
||||
String sensorTableName = null;
|
||||
if (sensorType.equals(DeviceTypeConstants.SENSOR_TYPE1)) {
|
||||
sensorTableName = DeviceTypeConstants.SENSOR_TYPE1_EVENT_TABLE;
|
||||
} else if (sensorType.equals(DeviceTypeConstants.SENSOR_TYPE2)) {
|
||||
sensorTableName = DeviceTypeConstants.SENSOR_TYPE2_EVENT_TABLE;
|
||||
}
|
||||
try {
|
||||
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
|
||||
DeviceTypeConstants.DEVICE_TYPE))) {
|
||||
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
|
||||
}
|
||||
if (sensorTableName != null) {
|
||||
List<SortByField> sortByFields = new ArrayList<>();
|
||||
SortByField sortByField = new SortByField("meta_time", SortType.ASC);
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
* To download device type agent source code as zip file.
|
||||
*
|
||||
* @param deviceName name for the device type instance
|
||||
* @param sketchType folder name where device type agent was installed into server
|
||||
* @return Agent source code as zip file
|
||||
*/
|
||||
@Path("/device/download")
|
||||
@GET
|
||||
@Produces("application/zip")
|
||||
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
|
||||
@QueryParam("sketchType") String sketchType) {
|
||||
try {
|
||||
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
|
||||
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
|
||||
response.status(Response.Status.OK);
|
||||
response.type("application/zip");
|
||||
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
|
||||
Response resp = response.build();
|
||||
zipFile.getZipFile().delete();
|
||||
return resp;
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return Response.status(400).entity(ex.getMessage()).build(); //bad request
|
||||
} catch (DeviceManagementException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (JWTClientException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (APIManagerException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (IOException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
} catch (UserStoreException ex) {
|
||||
log.error(ex.getMessage(), ex);
|
||||
return Response.status(500).entity(ex.getMessage()).build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register device into device management service.
|
||||
*
|
||||
* @param deviceId unique identifier for given device type instance
|
||||
* @param name name for the device type instance
|
||||
* @return check whether device is installed into cdmf
|
||||
*/
|
||||
private boolean register(String deviceId, String name) {
|
||||
try {
|
||||
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
|
||||
deviceIdentifier.setId(deviceId);
|
||||
deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
|
||||
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
|
||||
return false;
|
||||
}
|
||||
Device device = new Device();
|
||||
device.setDeviceIdentifier(deviceId);
|
||||
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
|
||||
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
|
||||
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
|
||||
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
|
||||
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
|
||||
device.setName(name);
|
||||
device.setType(DeviceTypeConstants.DEVICE_TYPE);
|
||||
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
|
||||
device.setEnrolmentInfo(enrolmentInfo);
|
||||
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
|
||||
return added;
|
||||
} catch (DeviceManagementException e) {
|
||||
log.error(e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
|
||||
throws DeviceManagementException, JWTClientException, APIManagerException,
|
||||
UserStoreException {
|
||||
//create new device id
|
||||
String deviceId = shortUUID();
|
||||
if (apiApplicationKey == null) {
|
||||
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext()
|
||||
.getUserRealm()
|
||||
.getRealmConfiguration().getAdminUserName();
|
||||
applicationUsername = applicationUsername + "@" +
|
||||
APIUtil.getAuthenticatedUserTenantDomain();
|
||||
APIManagementProviderService apiManagementProviderService =
|
||||
APIUtil.getAPIManagementProviderService();
|
||||
String[] tags = {DeviceTypeConstants.DEVICE_TYPE};
|
||||
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
|
||||
DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true,
|
||||
"3600");
|
||||
}
|
||||
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
|
||||
String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
|
||||
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
|
||||
apiApplicationKey.getConsumerSecret(), owner + "@" +
|
||||
APIUtil.getAuthenticatedUserTenantDomain(), scopes);
|
||||
|
||||
//create token
|
||||
String accessToken = accessTokenInfo.getAccessToken();
|
||||
String refreshToken = accessTokenInfo.getRefreshToken();
|
||||
boolean status = register(deviceId, deviceName);
|
||||
if (!status) {
|
||||
String msg = "Error occurred while registering the device with " + "id: " +
|
||||
deviceId + " owner:" + owner;
|
||||
throw new DeviceManagementException(msg);
|
||||
}
|
||||
ZipUtil ziputil = new ZipUtil();
|
||||
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
|
||||
sketchType, deviceId, deviceName, accessToken, refreshToken,
|
||||
apiApplicationKey.toString());
|
||||
return zipFile;
|
||||
}
|
||||
}
|
@ -0,0 +1,38 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.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,93 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api.dto;
|
||||
|
||||
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import javax.xml.bind.annotation.XmlElement;
|
||||
import javax.xml.bind.annotation.XmlElementWrapper;
|
||||
import javax.xml.bind.annotation.XmlRootElement;
|
||||
|
||||
|
||||
/**
|
||||
* This stores sensor event data for sampledevice.
|
||||
*/
|
||||
@XmlRootElement
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class SensorRecord {
|
||||
|
||||
@XmlElementWrapper(required = true, name = "values")
|
||||
private Map<String, Object> values;
|
||||
|
||||
/**
|
||||
* Unique identifier for each recode.
|
||||
*/
|
||||
@XmlElement(name = "id")
|
||||
private String id;
|
||||
|
||||
/**
|
||||
* Gets the values.
|
||||
*
|
||||
* @return the values
|
||||
*/
|
||||
public Map<String, Object> getValues() {
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the values.
|
||||
*
|
||||
* @param values sensorvalues
|
||||
*/
|
||||
public void setValues(Map<String, Object> values) {
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the id.
|
||||
*
|
||||
* @return the id
|
||||
*/
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the id.
|
||||
*
|
||||
* @param id set unique identifier
|
||||
*/
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
List<String> valueList = new ArrayList<>();
|
||||
for (Map.Entry<String, Object> entry : values.entrySet()) {
|
||||
valueList.add(entry.getKey() + ":" + entry.getValue());
|
||||
}
|
||||
return valueList.toString();
|
||||
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api.exception;
|
||||
|
||||
/**
|
||||
* Device specific exception handler.
|
||||
*/
|
||||
public class DeviceTypeException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 2736466230451105441L;
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public DeviceTypeException(String msg, DeviceTypeException nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public DeviceTypeException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public DeviceTypeException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public DeviceTypeException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public DeviceTypeException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
private void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
}
|
@ -0,0 +1,231 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api.util;
|
||||
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
|
||||
import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil;
|
||||
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.sampledevice.api.dto.SensorRecord;
|
||||
|
||||
import java.util.ArrayList;
|
||||
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);
|
||||
|
||||
/**
|
||||
* @return username of the current user
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Device management service of current context
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return api management service of current context
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return JWTClient manager of current context
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return tenant domain of the user
|
||||
*/
|
||||
public static String getTenantDomainOftheUser() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
return threadLocalCarbonContext.getTenantDomain();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return A Service to authorize device access requests
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get sensor data for a device.
|
||||
*
|
||||
* @param tableName table name of the data source
|
||||
* @param query query for the table
|
||||
* @param sortByFields list of fields to sort the data by
|
||||
* @return List of SensorRecords that is sorted by the fields provided
|
||||
* @throws AnalyticsException
|
||||
*/
|
||||
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(AnalyticsDataAPIUtil.listRecords(
|
||||
analyticsDataAPI, response));
|
||||
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
|
||||
return sortedSensorData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param sensorDatas Map that have the sensor data as key value pairs.
|
||||
* @param searchResults List of Search Results that has ids for sensor records.
|
||||
* @return List of Sensor Records.
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param searchResults List of SearchResultEntry
|
||||
* @return List of Ids from SearchResultEntry list
|
||||
*/
|
||||
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
|
||||
List<String> ids = new ArrayList<>();
|
||||
for (SearchResultEntry searchResult : searchResults) {
|
||||
ids.add(searchResult.getId());
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param records List of Records that to convert to SensorRecords
|
||||
* @return Map of Sensor records
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param record Record to convert to SensorRecord
|
||||
* @return SensorRecord
|
||||
*/
|
||||
public static SensorRecord createSensorData(Record record) {
|
||||
SensorRecord recordBean = new SensorRecord();
|
||||
recordBean.setId(record.getId());
|
||||
recordBean.setValues(record.getValues());
|
||||
return recordBean;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return AnalyticthsDataAPI for the context
|
||||
*/
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return TenantDomain
|
||||
*/
|
||||
public static String getAuthenticatedUserTenantDomain() {
|
||||
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
|
||||
return threadLocalCarbonContext.getTenantDomain();
|
||||
}
|
||||
}
|
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api.util;
|
||||
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* This is an utility class to hold zip files.
|
||||
*/
|
||||
public class ZipArchive {
|
||||
|
||||
private File zipFile = null;
|
||||
private String fileName = null;
|
||||
|
||||
public ZipArchive(String fileName, File zipFile) {
|
||||
this.fileName = fileName;
|
||||
this.zipFile = zipFile;
|
||||
}
|
||||
|
||||
public File getZipFile() {
|
||||
return zipFile;
|
||||
}
|
||||
|
||||
public String getFileName() {
|
||||
return fileName;
|
||||
}
|
||||
}
|
@ -0,0 +1,381 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.api.util;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.json.JSONObject;
|
||||
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.BufferedOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.SocketException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.zip.ZipEntry;
|
||||
import java.util.zip.ZipOutputStream;
|
||||
|
||||
/**
|
||||
* This is used to create a zip file that includes the necessary configuration required for the agent.
|
||||
*/
|
||||
public class ZipUtil {
|
||||
|
||||
public static final String HOST_NAME = "HostName";
|
||||
private static final String LOCALHOST = "localhost";
|
||||
private static final String HTTPS_PROTOCOL_URL = "https://${iot.gateway.host}:${iot.gateway.https.port}";
|
||||
private static final String HTTP_PROTOCOL_URL = "http://${iot.gateway.host}:${iot.gateway.http.port}";
|
||||
private static final String CONFIG_TYPE = "general";
|
||||
private static final String DEFAULT_MQTT_ENDPOINT = "tcp://${mqtt.broker.host}:${mqtt.broker.port}";
|
||||
|
||||
public static String getServerUrl() {
|
||||
try {
|
||||
return org.apache.axis2.util.Utils.getIpAddress();
|
||||
} catch (SocketException e) {
|
||||
return "localhost";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get agent sketch.
|
||||
*
|
||||
* @param archivesPath Path of the zip file to create.
|
||||
* @param templateSketchPath Path of the sketch.
|
||||
* @param contextParams Map of parameters to be included in the zip file.
|
||||
* @param zipFileName Name of the zip file.
|
||||
* @return Created zip archive.
|
||||
* @throws DeviceManagementException
|
||||
* @throws IOException
|
||||
*/
|
||||
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams
|
||||
, String zipFileName)
|
||||
throws DeviceManagementException, IOException {
|
||||
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
|
||||
FileUtils.deleteDirectory(new File(archivesPath)); //clear directory
|
||||
FileUtils.deleteDirectory(new File(archivesPath + ".zip")); //clear zip
|
||||
if (!new File(archivesPath).mkdirs()) { //new dir
|
||||
String message = "Could not create directory at path: " + archivesPath;
|
||||
throw new DeviceManagementException(message);
|
||||
}
|
||||
zipFileName = zipFileName + ".zip";
|
||||
try {
|
||||
Map<String, List<String>> properties = getProperties(sketchPath +
|
||||
File.separator + "sketch" + ".properties");
|
||||
List<String> templateFiles = properties.get("templates");
|
||||
|
||||
for (String templateFile : templateFiles) {
|
||||
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath
|
||||
+ File.separator + templateFile, contextParams);
|
||||
}
|
||||
|
||||
templateFiles.add("sketch.properties"); // ommit copying the props file
|
||||
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
|
||||
createZipArchive(archivesPath);
|
||||
FileUtils.deleteDirectory(new File(archivesPath));
|
||||
File zip = new File(archivesPath + ".zip");
|
||||
return new ZipArchive(zipFileName, zip);
|
||||
} catch (IOException ex) {
|
||||
throw new DeviceManagementException(
|
||||
"Error occurred when trying to read property " + "file sketch.properties", ex);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read Properties file.
|
||||
*
|
||||
* @param propertyFilePath Path of the properties file for the sketch
|
||||
* @return Map of properties
|
||||
* @throws IOException
|
||||
*/
|
||||
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
|
||||
Properties prop = new Properties();
|
||||
InputStream input = null;
|
||||
|
||||
try {
|
||||
|
||||
input = new FileInputStream(propertyFilePath);
|
||||
|
||||
// load a properties file
|
||||
prop.load(input);
|
||||
Map<String, List<String>> properties = new HashMap<String, List<String>>();
|
||||
|
||||
String templates = prop.getProperty("templates");
|
||||
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
|
||||
properties.put("templates", list);
|
||||
|
||||
final String filename = prop.getProperty("zipfilename");
|
||||
list = new ArrayList<String>() {{
|
||||
add(filename);
|
||||
}};
|
||||
properties.put("zipfilename", list);
|
||||
return properties;
|
||||
|
||||
} finally {
|
||||
if (input != null) {
|
||||
try {
|
||||
input.close();
|
||||
} catch (IOException e) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param srcFile Path of the template
|
||||
* @param dstFile Destination of the new file
|
||||
* @param contextParams Map of parameters
|
||||
* @throws IOException Error creating the file
|
||||
*/
|
||||
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
|
||||
//read from file
|
||||
FileInputStream inputStream = null;
|
||||
FileOutputStream outputStream = null;
|
||||
try {
|
||||
inputStream = new FileInputStream(srcFile);
|
||||
outputStream = new FileOutputStream(dstFile);
|
||||
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
|
||||
Iterator iterator = contextParams.entrySet().iterator();
|
||||
while (iterator.hasNext()) {
|
||||
Map.Entry mapEntry = (Map.Entry) iterator.next();
|
||||
content = content.replaceAll("\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
|
||||
}
|
||||
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
|
||||
} finally {
|
||||
if (inputStream != null) {
|
||||
inputStream.close();
|
||||
}
|
||||
if (outputStream != null) {
|
||||
outputStream.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy folders to the zip archive.
|
||||
*
|
||||
* @param src Path of source folder.
|
||||
* @param dest Path of destination folder.
|
||||
* @param excludeFileNames List of filenames to exclude form zip file.
|
||||
* @throws IOException Error copying the folders/files.
|
||||
*/
|
||||
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
|
||||
|
||||
if (src.isDirectory()) {
|
||||
//if directory not exists, create it
|
||||
if (!dest.exists() && !dest.mkdirs()) {
|
||||
String message = "Could not create directory at path: " + dest;
|
||||
throw new IOException(message);
|
||||
}
|
||||
//list all the directory contents
|
||||
String files[] = src.list();
|
||||
|
||||
if (files == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (String file : files) {
|
||||
//construct the src and dest file structure
|
||||
File srcFile = new File(src, file);
|
||||
File destFile = new File(dest, file);
|
||||
//recursive copy
|
||||
copyFolder(srcFile, destFile, excludeFileNames);
|
||||
}
|
||||
|
||||
} else {
|
||||
for (String fileName : excludeFileNames) {
|
||||
if (src.getName().equals(fileName)) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
//if file, then copy it
|
||||
//Use bytes stream to support all file types
|
||||
InputStream in = null;
|
||||
OutputStream out = null;
|
||||
|
||||
try {
|
||||
in = new FileInputStream(src);
|
||||
out = new FileOutputStream(dest);
|
||||
|
||||
byte[] buffer = new byte[1024];
|
||||
|
||||
int length;
|
||||
//copy the file content in bytes
|
||||
while ((length = in.read(buffer)) > 0) {
|
||||
out.write(buffer, 0, length);
|
||||
}
|
||||
} finally {
|
||||
if (in != null) {
|
||||
in.close();
|
||||
}
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the zip file.
|
||||
*
|
||||
* @param srcFolder Path of the source folder
|
||||
* @return zip distribution.
|
||||
* @throws IOException Error creating the zip file.
|
||||
*/
|
||||
private static boolean createZipArchive(String srcFolder) throws IOException {
|
||||
BufferedInputStream origin = null;
|
||||
ZipOutputStream out = null;
|
||||
|
||||
try {
|
||||
final int buffer = 2048;
|
||||
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
|
||||
out = new ZipOutputStream(new BufferedOutputStream(dest));
|
||||
byte data[] = new byte[buffer];
|
||||
File subDir = new File(srcFolder);
|
||||
String subdirList[] = subDir.list();
|
||||
if (subdirList == null) {
|
||||
return false;
|
||||
}
|
||||
for (String sd : subdirList) {
|
||||
// get a list of files from current directory
|
||||
File f = new File(srcFolder + "/" + sd);
|
||||
if (f.isDirectory()) {
|
||||
String files[] = f.list();
|
||||
|
||||
if (files == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
|
||||
origin = new BufferedInputStream(fi, buffer);
|
||||
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
|
||||
out.putNextEntry(entry);
|
||||
int count;
|
||||
while ((count = origin.read(data, 0, buffer)) != -1) {
|
||||
out.write(data, 0, count);
|
||||
out.flush();
|
||||
}
|
||||
|
||||
}
|
||||
} else { //it is just a file
|
||||
FileInputStream fi = new FileInputStream(f);
|
||||
origin = new BufferedInputStream(fi, buffer);
|
||||
ZipEntry entry = new ZipEntry(sd);
|
||||
out.putNextEntry(entry);
|
||||
int count;
|
||||
while ((count = origin.read(data, 0, buffer)) != -1) {
|
||||
out.write(data, 0, count);
|
||||
out.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
out.flush();
|
||||
} finally {
|
||||
if (origin != null) {
|
||||
origin.close();
|
||||
}
|
||||
if (out != null) {
|
||||
out.close();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create agent zip file.
|
||||
*
|
||||
* @param owner Owner of device.
|
||||
* @param tenantDomain Tenant of the device.
|
||||
* @param deviceType Device type.
|
||||
* @param deviceId Device ID.
|
||||
* @param deviceName Device Name
|
||||
* @param token Auth token to access the api.
|
||||
* @param refreshToken Refresh token to generate new auth token.
|
||||
* @param apiApplicationKey Application key.
|
||||
* @return Zip archive.
|
||||
* @throws DeviceManagementException Error creating zip archive.
|
||||
*/
|
||||
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
|
||||
String deviceId, String deviceName, String token,
|
||||
String refreshToken, String apiApplicationKey)
|
||||
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 = getServerUrl();
|
||||
String httpsServerEP = Utils.replaceSystemProperty(HTTPS_PROTOCOL_URL);
|
||||
String httpServerEP = Utils.replaceSystemProperty(HTTP_PROTOCOL_URL);
|
||||
String mqttEndpoint = Utils.replaceSystemProperty(DEFAULT_MQTT_ENDPOINT);
|
||||
if (mqttEndpoint.contains(LOCALHOST)) {
|
||||
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
|
||||
httpsServerEP = httpsServerEP.replace(LOCALHOST, iotServerIP);
|
||||
httpServerEP = httpServerEP.replace(LOCALHOST, iotServerIP);
|
||||
}
|
||||
String base64EncodedApplicationKey = getBase64EncodedAPIAppKey(apiApplicationKey).trim();
|
||||
|
||||
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", httpsServerEP);
|
||||
contextParams.put("MQTT_EP", mqttEndpoint);
|
||||
contextParams.put("DEVICE_TOKEN", token);
|
||||
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
|
||||
contextParams.put("API_APPLICATION_KEY", base64EncodedApplicationKey);
|
||||
|
||||
ZipArchive zipFile;
|
||||
zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
|
||||
return zipFile;
|
||||
} catch (IOException e) {
|
||||
throw new DeviceManagementException("Zip File Creation Failed", e);
|
||||
}
|
||||
}
|
||||
|
||||
private String getBase64EncodedAPIAppKey(String apiAppCredentialsAsJSONString) {
|
||||
|
||||
JSONObject jsonObject = new JSONObject(apiAppCredentialsAsJSONString);
|
||||
String consumerKey = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_ID).toString();
|
||||
String consumerSecret = jsonObject.get(ApiApplicationConstants.OAUTH_CLIENT_SECRET).toString();
|
||||
String stringToEncode = consumerKey + ":" + consumerSecret;
|
||||
return Base64.encodeBase64String(stringToEncode.getBytes());
|
||||
}
|
||||
}
|
@ -0,0 +1,86 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<!-- This file contains the list of permissions that are associated with URL end points
|
||||
of the web app. Each permission should contain the name, permission path ,API path
|
||||
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
|
||||
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
|
||||
NOTE: All the endpoints of the web app should be available in this file. Otherwise
|
||||
it will result 403 error at the runtime.
|
||||
-->
|
||||
<PermissionConfiguration>
|
||||
<APIVersion></APIVersion>
|
||||
<!-- Device related APIs -->
|
||||
<Permission>
|
||||
<name>Get device</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/*</url>
|
||||
<method>GET</method>
|
||||
<scope>sampledevice_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Remove device</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/*</url>
|
||||
<method>DELETE</method>
|
||||
<scope>sampledevice_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Download device</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/download</url>
|
||||
<method>GET</method>
|
||||
<scope>sampledevice_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Update device</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/*</url>
|
||||
<method>POST</method>
|
||||
<scope>sampledevice_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Get Devices</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device</url>
|
||||
<method>GET</method>
|
||||
<scope>sampledevice_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Register Device</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/register</url>
|
||||
<method>POST</method>
|
||||
<scope>sampledevice_device</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Control Sensor</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/*/change-status</url>
|
||||
<method>POST</method>
|
||||
<scope>sampledevice_user</scope>
|
||||
</Permission>
|
||||
<Permission>
|
||||
<name>Get Stats</name>
|
||||
<path>/device-mgt/sampledevice/user</path>
|
||||
<url>/device/stats/*</url>
|
||||
<method>GET</method>
|
||||
<scope>sampledevice_device</scope>
|
||||
</Permission>
|
||||
</PermissionConfiguration>
|
@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="ISO-8859-1"?>
|
||||
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<!--
|
||||
This file defines class loading policy of the whole container. But this behaviour can be
|
||||
overridden by individual webapps by putting this file into the META-INF/ directory.
|
||||
-->
|
||||
<Classloading xmlns="http://wso2.org/projects/as/classloading">
|
||||
|
||||
<!-- Parent-first or child-first. Default behaviour is child-first.-->
|
||||
<ParentFirst>false</ParentFirst>
|
||||
|
||||
<!--
|
||||
Default environments that contains provides to all the webapps. This can be overridden by
|
||||
individual webapps by specifing required environments
|
||||
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
|
||||
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
|
||||
-->
|
||||
<Environments>CXF,Carbon</Environments>
|
||||
</Classloading>
|
@ -0,0 +1,37 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
|
||||
xmlns="http://www.springframework.org/schema/beans"
|
||||
xsi:schemaLocation="
|
||||
http://www.springframework.org/schema/beans
|
||||
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
|
||||
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
|
||||
<jaxrs:server id="sampledevice" address="/">
|
||||
<jaxrs:serviceBeans>
|
||||
<bean id="DeviceTypeService"
|
||||
class="org.wso2.carbon.sampledevice.api.DeviceTypeServiceImpl">
|
||||
</bean>
|
||||
</jaxrs:serviceBeans>
|
||||
<jaxrs:providers>
|
||||
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
|
||||
</jaxrs:providers>
|
||||
</jaxrs:server>
|
||||
</beans>
|
@ -0,0 +1,52 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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.
|
||||
-->
|
||||
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
version="2.5"
|
||||
xmlns="http://java.sun.com/xml/ns/javaee"
|
||||
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
|
||||
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
|
||||
metadata-complete="true">
|
||||
<display-name>WSO2 IoT Server</display-name>
|
||||
<description>WSO2 IoT Server</description>
|
||||
|
||||
<servlet>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
|
||||
<load-on-startup>1</load-on-startup>
|
||||
</servlet>
|
||||
<servlet-mapping>
|
||||
<servlet-name>CXFServlet</servlet-name>
|
||||
<url-pattern>/*</url-pattern>
|
||||
</servlet-mapping>
|
||||
<context-param>
|
||||
<param-name>doAuthentication</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
<context-param>
|
||||
<param-name>isSharedWithAllTenants</param-name>
|
||||
<param-value>false</param-value>
|
||||
</context-param>
|
||||
|
||||
<!--publish to apim-->
|
||||
<context-param>
|
||||
<param-name>managed-api-enabled</param-name>
|
||||
<param-value>true</param-value>
|
||||
</context-param>
|
||||
|
||||
</web-app>
|
@ -0,0 +1,133 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice-component</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0</version>
|
||||
<artifactId>${project-base-package}.plugin</artifactId>
|
||||
<packaging>bundle</packaging>
|
||||
<name>${project-base-package}.plugin</name>
|
||||
<url>http://wso2.org</url>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>${maven-compiler-plugin.version}</version>
|
||||
<configuration>
|
||||
<encoding>UTF-8</encoding>
|
||||
<source>${maven.compiler.source}</source>
|
||||
<target>${maven.compiler.target}</target>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-bundle-plugin</artifactId>
|
||||
<version>${org.apache.felix.version}</version>
|
||||
<extensions>true</extensions>
|
||||
<configuration>
|
||||
<instructions>
|
||||
<Bundle-SymbolicName>${project-base-package}.plugin</Bundle-SymbolicName>
|
||||
<Bundle-Name>${project-base-package}.plugin</Bundle-Name>
|
||||
<Bundle-Version>1.0.0</Bundle-Version>
|
||||
<Bundle-Description>IoT Server Impl Bundle</Bundle-Description>
|
||||
<Private-Package>${project-base-package}.plugin.internal</Private-Package>
|
||||
<Import-Package>
|
||||
org.osgi.framework,
|
||||
org.osgi.service.component,
|
||||
org.apache.commons.logging,
|
||||
javax.naming;resolution:=optional,
|
||||
javax.sql;resolution:=optional,
|
||||
org.wso2.carbon.device.mgt.common.*,
|
||||
org.wso2.carbon.device.mgt.common,
|
||||
org.wso2.carbon.device.mgt.iot.*,
|
||||
org.wso2.carbon.device.mgt.extensions.feature.mgt.*,
|
||||
org.wso2.carbon.utils.*,
|
||||
org.wso2.carbon.event.output.adapter.core,
|
||||
org.wso2.carbon.event.output.adapter.core.exception,
|
||||
org.wso2.carbon.base,
|
||||
org.wso2.carbon.core.util,
|
||||
org.wso2.carbon.context,
|
||||
org.wso2.carbon.core,
|
||||
org.apache.commons.codec.binary
|
||||
</Import-Package>
|
||||
<Export-Package>
|
||||
!${project-base-package}.plugin.internal,
|
||||
${project-base-package}.plugin.*
|
||||
</Export-Package>
|
||||
</instructions>
|
||||
</configuration>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>commons-codec.wso2</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.constants;
|
||||
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* Sample Device constants.
|
||||
* Device type specific constants which includes all transport protocols configurations,
|
||||
* stream definition and device specific dome constants
|
||||
*/
|
||||
public class DeviceTypeConstants {
|
||||
public static final String DEVICE_TYPE = "sampledevice";
|
||||
public static final String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
|
||||
public static final String DEVICE_PLUGIN_DEVICE_ID = "sampledevice_DEVICE_ID";
|
||||
public static final String STATE_ON = "ON";
|
||||
public static final String STATE_OFF = "OFF";
|
||||
public static final String BULB_CONTEXT = "BULB";
|
||||
|
||||
//sensor events summerized table name
|
||||
public static final String SENSOR_TYPE1_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_sensor_temp";
|
||||
public static final String SENSOR_TYPE2_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_no_sensor1";
|
||||
public static final String DATA_SOURCE_NAME = "jdbc/sampledeviceDM_DB";
|
||||
public static final String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
|
||||
public static final String SENSOR_TYPE1 = "sensor_temp";
|
||||
public static final String SENSOR_TYPE2 = "no_sensor1";
|
||||
|
||||
//mqtt tranport related constants
|
||||
public static final String MQTT_ADAPTER_NAME = "sensor_temp_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/sampledevice/+/sensor_temp";
|
||||
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 static final String SENSOR_TYPE1_STREAM_DEFINITION = "org.wso2.iot.devices.sensor_temp";
|
||||
public static final String SENSOR_TYPE1_STREAM_DEFINITION_VERSION = "1.0.0";
|
||||
|
||||
|
||||
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() +
|
||||
File.separator + "mqtt.properties";
|
||||
}
|
||||
|
@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.exception;
|
||||
|
||||
/**
|
||||
* Device type plugin exception handler.
|
||||
*/
|
||||
public class DeviceMgtPluginException extends Exception {
|
||||
|
||||
private String errorMessage;
|
||||
|
||||
public DeviceMgtPluginException(String msg, Exception nestedEx) {
|
||||
super(msg, nestedEx);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public DeviceMgtPluginException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
setErrorMessage(message);
|
||||
}
|
||||
|
||||
public DeviceMgtPluginException(String msg) {
|
||||
super(msg);
|
||||
setErrorMessage(msg);
|
||||
}
|
||||
|
||||
public DeviceMgtPluginException() {
|
||||
super();
|
||||
}
|
||||
|
||||
public DeviceMgtPluginException(Throwable cause) {
|
||||
super(cause);
|
||||
}
|
||||
|
||||
public String getErrorMessage() {
|
||||
return errorMessage;
|
||||
}
|
||||
|
||||
public void setErrorMessage(String errorMessage) {
|
||||
this.errorMessage = errorMessage;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,262 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManager;
|
||||
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
|
||||
import org.wso2.carbon.device.mgt.common.FeatureManager;
|
||||
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
|
||||
import org.wso2.carbon.device.mgt.common.license.mgt.License;
|
||||
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;
|
||||
import org.wso2.carbon.sampledevice.plugin.exception.DeviceMgtPluginException;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.dao.DeviceTypeDAO;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.feature.DeviceTypeFeatureManager;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
|
||||
/**
|
||||
* This represents the sampledevice implementation of DeviceManagerService.
|
||||
*/
|
||||
public class DeviceTypeManager implements DeviceManager {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeManager.class);
|
||||
private static final DeviceTypeDAO deviceTypeDAO = new DeviceTypeDAO();
|
||||
private FeatureManager featureManager = new DeviceTypeFeatureManager();
|
||||
|
||||
@Override
|
||||
public FeatureManager getFeatureManager() {
|
||||
return featureManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean saveConfiguration(PlatformConfiguration platformConfiguration)
|
||||
throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PlatformConfiguration getConfiguration() throws DeviceManagementException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean enrollDevice(Device device) throws DeviceManagementException {
|
||||
boolean status;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Enrolling a new sampledevice device : " + device.getDeviceIdentifier());
|
||||
}
|
||||
DeviceTypeDAO.beginTransaction();
|
||||
status = deviceTypeDAO.getDeviceTypeDAO().addDevice(device);
|
||||
DeviceTypeDAO.commitTransaction();
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
try {
|
||||
DeviceTypeDAO.rollbackTransaction();
|
||||
} catch (DeviceMgtPluginException iotDAOEx) {
|
||||
log.warn("Error occurred while roll back the device enrol transaction :"
|
||||
+ device.toString(), iotDAOEx);
|
||||
}
|
||||
String msg = "Error while enrolling the sampledevice device : "
|
||||
+ device.getDeviceIdentifier();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean modifyEnrollment(Device device) throws DeviceManagementException {
|
||||
boolean status;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Modifying the sampledevice device enrollment data");
|
||||
}
|
||||
DeviceTypeDAO.beginTransaction();
|
||||
status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
|
||||
DeviceTypeDAO.commitTransaction();
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
try {
|
||||
DeviceTypeDAO.rollbackTransaction();
|
||||
} catch (DeviceMgtPluginException iotDAOEx) {
|
||||
String msg = "Error occurred while roll back the update device transaction :"
|
||||
+ device.toString();
|
||||
log.warn(msg, iotDAOEx);
|
||||
}
|
||||
String msg = "Error while updating the enrollment of the sampledevice device : " +
|
||||
device.getDeviceIdentifier();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean disenrollDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
boolean status;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Dis-enrolling sampledevice device : " + deviceId);
|
||||
}
|
||||
DeviceTypeDAO.beginTransaction();
|
||||
status = deviceTypeDAO.getDeviceTypeDAO().deleteDevice(deviceId.getId());
|
||||
DeviceTypeDAO.commitTransaction();
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
try {
|
||||
DeviceTypeDAO.rollbackTransaction();
|
||||
} catch (DeviceMgtPluginException iotDAOEx) {
|
||||
String msg = "Error occurred while roll back the device dis enrol transaction :"
|
||||
+ deviceId.toString();
|
||||
log.warn(msg, iotDAOEx);
|
||||
}
|
||||
String msg = "Error while removing the sampledevice device : " + deviceId.getId();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnrolled(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
boolean isEnrolled = false;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Checking the enrollment of sampledevice device : "
|
||||
+ deviceId.getId());
|
||||
}
|
||||
Device iotDevice =
|
||||
deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
|
||||
if (iotDevice != null) {
|
||||
isEnrolled = true;
|
||||
}
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
String msg = "Error while checking the enrollment status of sampledevice device : " +
|
||||
deviceId.getId();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return isEnrolled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isActive(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setActive(DeviceIdentifier deviceId, boolean status)
|
||||
throws DeviceManagementException {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Device getDevice(DeviceIdentifier deviceId) throws DeviceManagementException {
|
||||
Device device;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Getting the details of sampledevice device : " + deviceId.getId());
|
||||
}
|
||||
device = deviceTypeDAO.getDeviceTypeDAO().getDevice(deviceId.getId());
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
String msg = "Error while fetching the sampledevice device : " + deviceId.getId();
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return device;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setOwnership(DeviceIdentifier deviceId, String ownershipType)
|
||||
throws DeviceManagementException {
|
||||
return true;
|
||||
}
|
||||
|
||||
public boolean isClaimable(DeviceIdentifier deviceIdentifier) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean setStatus(DeviceIdentifier deviceId, String currentOwner,
|
||||
EnrolmentInfo.Status status) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public License getLicense(String s) throws LicenseManagementException {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addLicense(License license) throws LicenseManagementException {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean requireDeviceAuthorization() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device)
|
||||
throws DeviceManagementException {
|
||||
boolean status;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("updating the details of sampledevice device : " + deviceIdentifier);
|
||||
}
|
||||
DeviceTypeDAO.beginTransaction();
|
||||
status = deviceTypeDAO.getDeviceTypeDAO().updateDevice(device);
|
||||
DeviceTypeDAO.commitTransaction();
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
try {
|
||||
DeviceTypeDAO.rollbackTransaction();
|
||||
} catch (DeviceMgtPluginException iotDAOEx) {
|
||||
String msg = "Error occurred while roll back the update device info transaction :"
|
||||
+ device.toString();
|
||||
log.warn(msg, iotDAOEx);
|
||||
}
|
||||
String msg =
|
||||
"Error while updating the sampledevice device : " + deviceIdentifier;
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Device> getAllDevices() throws DeviceManagementException {
|
||||
List<Device> devices;
|
||||
try {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Fetching the details of all sampledevice devices");
|
||||
}
|
||||
devices = deviceTypeDAO.getDeviceTypeDAO().getAllDevices();
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
String msg = "Error while fetching all sampledevice devices.";
|
||||
log.error(msg, e);
|
||||
throw new DeviceManagementException(msg, e);
|
||||
}
|
||||
return devices;
|
||||
}
|
||||
}
|
@ -0,0 +1,117 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.impl;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManager;
|
||||
import org.wso2.carbon.device.mgt.common.DeviceStatusTaskPluginConfig;
|
||||
import org.wso2.carbon.device.mgt.common.InitialOperationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.OperationMonitoringTaskConfig;
|
||||
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
|
||||
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
|
||||
import org.wso2.carbon.device.mgt.common.policy.mgt.PolicyMonitoringManager;
|
||||
import org.wso2.carbon.device.mgt.common.pull.notification.PullNotificationSubscriber;
|
||||
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
|
||||
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.sampledevice.plugin.constants.DeviceTypeConstants;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* DeviceType Manager Service that defines device manager operations.
|
||||
*/
|
||||
public class DeviceTypeManagerService implements DeviceManagementService {
|
||||
private DeviceManager deviceManager;
|
||||
private OperationMonitoringTaskConfig operationMonitoringTaskConfig;
|
||||
|
||||
@Override
|
||||
public String getType() {
|
||||
return DeviceTypeConstants.DEVICE_TYPE;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void init() throws DeviceManagementException {
|
||||
this.deviceManager = new DeviceTypeManager();
|
||||
this.operationMonitoringTaskConfig = new OperationMonitoringTaskConfig();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public DeviceManager getDeviceManager() {
|
||||
return deviceManager;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ApplicationManager getApplicationManager() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProvisioningConfig getProvisioningConfig() {
|
||||
return new ProvisioningConfig(DeviceTypeConstants.DEVICE_TYPE_PROVIDER_DOMAIN, false);
|
||||
}
|
||||
|
||||
@Override
|
||||
public OperationMonitoringTaskConfig getOperationMonitoringConfig() {
|
||||
return operationMonitoringTaskConfig;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PushNotificationConfig getPushNotificationConfig() {
|
||||
// this needs to be retrieved from a config file.
|
||||
Map<String, String> properties = new HashMap<>();
|
||||
properties.put("mqttAdapterName", "sampledevice_mqtt");
|
||||
properties.put("username", "admin");
|
||||
properties.put("password", "admin");
|
||||
properties.put("qos", "0");
|
||||
properties.put("clearSession", "true");
|
||||
properties.put("scopes", "");
|
||||
return new PushNotificationConfig("MQTT", false, properties);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PolicyMonitoringManager getPolicyMonitoringManager() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public InitialOperationConfig getInitialOperationConfig() {
|
||||
|
||||
InitialOperationConfig config = new InitialOperationConfig();
|
||||
List<String> operations = new ArrayList<>();
|
||||
operations.add(DeviceTypeConstants.BULB_CONTEXT + ":ON");
|
||||
config.setOperations(operations);
|
||||
return config;
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public PullNotificationSubscriber getPullNotificationSubscriber() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public DeviceStatusTaskPluginConfig getDeviceStatusTaskPluginConfig() {
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,132 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.impl.dao;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.sampledevice.plugin.constants.DeviceTypeConstants;
|
||||
import org.wso2.carbon.sampledevice.plugin.exception.DeviceMgtPluginException;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.dao.impl.DeviceTypeDAOImpl;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.SQLException;
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
|
||||
/**
|
||||
* Database handler which is specified for sampledevice type.
|
||||
*/
|
||||
public class DeviceTypeDAO {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeDAO.class);
|
||||
static DataSource dataSource; // package local variable
|
||||
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<>();
|
||||
|
||||
public DeviceTypeDAO() {
|
||||
initDeviceTypeDAO();
|
||||
}
|
||||
|
||||
public static void initDeviceTypeDAO() {
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME);
|
||||
} catch (NamingException e) {
|
||||
log.error("Error while looking up the data source: " +
|
||||
DeviceTypeConstants.DATA_SOURCE_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
public static void beginTransaction() throws DeviceMgtPluginException {
|
||||
try {
|
||||
Connection conn = dataSource.getConnection();
|
||||
conn.setAutoCommit(false);
|
||||
currentConnection.set(conn);
|
||||
} catch (SQLException e) {
|
||||
throw new DeviceMgtPluginException("Error occurred while retrieving datasource connection", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static Connection getConnection() throws DeviceMgtPluginException {
|
||||
if (currentConnection.get() == null) {
|
||||
try {
|
||||
currentConnection.set(dataSource.getConnection());
|
||||
} catch (SQLException e) {
|
||||
throw new DeviceMgtPluginException("Error occurred while retrieving data source connection",
|
||||
e);
|
||||
}
|
||||
}
|
||||
return currentConnection.get();
|
||||
}
|
||||
|
||||
public static void commitTransaction() throws DeviceMgtPluginException {
|
||||
try {
|
||||
Connection conn = currentConnection.get();
|
||||
if (conn != null) {
|
||||
conn.commit();
|
||||
} else {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Datasource connection associated with the current thread is null," +
|
||||
" hence commit has not been attempted");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DeviceMgtPluginException("Error occurred while committing the transaction", e);
|
||||
} finally {
|
||||
closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
public static void closeConnection() throws DeviceMgtPluginException {
|
||||
|
||||
Connection con = currentConnection.get();
|
||||
if (con != null) {
|
||||
try {
|
||||
con.close();
|
||||
} catch (SQLException e) {
|
||||
log.error("Error occurred while close the connection");
|
||||
}
|
||||
}
|
||||
currentConnection.remove();
|
||||
}
|
||||
|
||||
public static void rollbackTransaction() throws DeviceMgtPluginException {
|
||||
try {
|
||||
Connection conn = currentConnection.get();
|
||||
if (conn != null) {
|
||||
conn.rollback();
|
||||
} else {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Datasource connection associated with the current thread is null, " +
|
||||
"hence rollback has not been attempted");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
throw new DeviceMgtPluginException("Error occurred while rollback the transaction", e);
|
||||
} finally {
|
||||
closeConnection();
|
||||
}
|
||||
}
|
||||
|
||||
public DeviceTypeDAOImpl getDeviceTypeDAO() {
|
||||
return new DeviceTypeDAOImpl();
|
||||
}
|
||||
}
|
@ -0,0 +1,201 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.impl.dao.impl;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.device.mgt.common.Device;
|
||||
import org.wso2.carbon.sampledevice.plugin.constants.DeviceTypeConstants;
|
||||
import org.wso2.carbon.sampledevice.plugin.exception.DeviceMgtPluginException;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.dao.DeviceTypeDAO;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.util.DeviceTypeUtils;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Implements IotDeviceDAO for sampledevice Devices.
|
||||
*/
|
||||
public class DeviceTypeDAOImpl {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceTypeDAOImpl.class);
|
||||
|
||||
public Device getDevice(String deviceId) throws DeviceMgtPluginException {
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
Device iotDevice = null;
|
||||
ResultSet resultSet = null;
|
||||
try {
|
||||
conn = DeviceTypeDAO.getConnection();
|
||||
String selectDBQuery =
|
||||
"SELECT sampledevice_DEVICE_ID, DEVICE_NAME" +
|
||||
" FROM sampledevice_DEVICE WHERE sampledevice_DEVICE_ID = ?";
|
||||
stmt = conn.prepareStatement(selectDBQuery);
|
||||
stmt.setString(1, deviceId);
|
||||
resultSet = stmt.executeQuery();
|
||||
|
||||
if (resultSet.next()) {
|
||||
iotDevice = new Device();
|
||||
iotDevice.setName(resultSet.getString(
|
||||
DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME));
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("sampledevice device " + deviceId + " data has been fetched from " +
|
||||
"sampledevice database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while fetching sampledevice device : '" + deviceId + "'";
|
||||
log.error(msg, e);
|
||||
throw new DeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
DeviceTypeUtils.cleanupResources(stmt, resultSet);
|
||||
DeviceTypeDAO.closeConnection();
|
||||
}
|
||||
return iotDevice;
|
||||
}
|
||||
|
||||
public boolean addDevice(Device device) throws DeviceMgtPluginException {
|
||||
boolean status = false;
|
||||
Connection conn;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = DeviceTypeDAO.getConnection();
|
||||
String createDBQuery =
|
||||
"INSERT INTO sampledevice_DEVICE(sampledevice_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)";
|
||||
stmt = conn.prepareStatement(createDBQuery);
|
||||
stmt.setString(1, device.getDeviceIdentifier());
|
||||
stmt.setString(2, device.getName());
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("sampledevice device " + device.getDeviceIdentifier() + " data has been" +
|
||||
" added to the sampledevice database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while adding the sampledevice device '" +
|
||||
device.getDeviceIdentifier() + "' to the sampledevice db.";
|
||||
log.error(msg, e);
|
||||
throw new DeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
DeviceTypeUtils.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
public boolean updateDevice(Device device) throws DeviceMgtPluginException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = DeviceTypeDAO.getConnection();
|
||||
String updateDBQuery =
|
||||
"UPDATE sampledevice_DEVICE SET DEVICE_NAME = ? WHERE sampledevice_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("sampledevice device " + device.getDeviceIdentifier() + " data has been" +
|
||||
" modified.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while modifying the sampledevice device '" +
|
||||
device.getDeviceIdentifier() + "' data.";
|
||||
log.error(msg, e);
|
||||
throw new DeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
DeviceTypeUtils.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
public boolean deleteDevice(String deviceId) throws DeviceMgtPluginException {
|
||||
boolean status = false;
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
try {
|
||||
conn = DeviceTypeDAO.getConnection();
|
||||
String deleteDBQuery =
|
||||
"DELETE FROM sampledevice_DEVICE WHERE sampledevice_DEVICE_ID = ?";
|
||||
stmt = conn.prepareStatement(deleteDBQuery);
|
||||
stmt.setString(1, deviceId);
|
||||
int rows = stmt.executeUpdate();
|
||||
if (rows > 0) {
|
||||
status = true;
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("sampledevice device " + deviceId + " data has deleted" +
|
||||
" from the sampledevice database.");
|
||||
}
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while deleting sampledevice device " + deviceId;
|
||||
log.error(msg, e);
|
||||
throw new DeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
DeviceTypeUtils.cleanupResources(stmt, null);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
public List<Device> getAllDevices() throws DeviceMgtPluginException {
|
||||
Connection conn = null;
|
||||
PreparedStatement stmt = null;
|
||||
ResultSet resultSet = null;
|
||||
Device device;
|
||||
List<Device> iotDevices = new ArrayList<>();
|
||||
try {
|
||||
conn = DeviceTypeDAO.getConnection();
|
||||
String selectDBQuery =
|
||||
"SELECT sampledevice_DEVICE_ID, DEVICE_NAME " +
|
||||
"FROM sampledevice_DEVICE";
|
||||
stmt = conn.prepareStatement(selectDBQuery);
|
||||
resultSet = stmt.executeQuery();
|
||||
while (resultSet.next()) {
|
||||
device = new Device();
|
||||
device.setDeviceIdentifier(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_ID));
|
||||
device.setName(resultSet.getString(DeviceTypeConstants.DEVICE_PLUGIN_DEVICE_NAME));
|
||||
List<Device.Property> propertyList = new ArrayList<>();
|
||||
device.setProperties(propertyList);
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("All sampledevice device details have fetched from sampledevice database.");
|
||||
}
|
||||
return iotDevices;
|
||||
} catch (SQLException e) {
|
||||
String msg = "Error occurred while fetching all sampledevice device data'";
|
||||
log.error(msg, e);
|
||||
throw new DeviceMgtPluginException(msg, e);
|
||||
} finally {
|
||||
DeviceTypeUtils.cleanupResources(stmt, resultSet);
|
||||
DeviceTypeDAO.closeConnection();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,95 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
package org.wso2.carbon.sampledevice.plugin.impl.feature;
|
||||
|
||||
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
|
||||
import org.wso2.carbon.device.mgt.common.Feature;
|
||||
import org.wso2.carbon.device.mgt.common.FeatureManager;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Device type specific feature management server.
|
||||
*/
|
||||
public class DeviceTypeFeatureManager implements FeatureManager {
|
||||
|
||||
private static final String METHOD = "method";
|
||||
private static final String URI = "uri";
|
||||
private static final String CONTENT_TYPE = "contentType";
|
||||
private static final String PATH_PARAMS = "pathParams";
|
||||
private static final String QUERY_PARAMS = "queryParams";
|
||||
private static final String FORM_PARAMS = "formParams";
|
||||
private static Feature feature = new Feature();
|
||||
|
||||
public DeviceTypeFeatureManager() {
|
||||
feature.setCode("change-status");
|
||||
feature.setName("Change status of sensor: on/off");
|
||||
feature.setDescription("Change status of sensor: on/off");
|
||||
|
||||
Map<String, Object> apiParams = new HashMap<>();
|
||||
apiParams.put(METHOD, "POST");
|
||||
apiParams.put(URI, "/sampledevice/device/{deviceId}/change-status");
|
||||
List<String> pathParams = new ArrayList<>();
|
||||
List<String> queryParams = new ArrayList<>();
|
||||
List<String> formParams = new ArrayList<>();
|
||||
pathParams.add("deviceId");
|
||||
apiParams.put(PATH_PARAMS, pathParams);
|
||||
queryParams.add("state");
|
||||
apiParams.put(QUERY_PARAMS, queryParams);
|
||||
apiParams.put(FORM_PARAMS, formParams);
|
||||
List<Feature.MetadataEntry> metadataEntries = new ArrayList<>();
|
||||
Feature.MetadataEntry metadataEntry = new Feature.MetadataEntry();
|
||||
metadataEntry.setId(-1);
|
||||
metadataEntry.setValue(apiParams);
|
||||
metadataEntries.add(metadataEntry);
|
||||
feature.setMetadataEntries(metadataEntries);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addFeature(Feature feature) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addFeatures(List<Feature> features) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Feature getFeature(String name) throws DeviceManagementException {
|
||||
return feature;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Feature> getFeatures() throws DeviceManagementException {
|
||||
List<Feature> features = new ArrayList<>();
|
||||
features.add(feature);
|
||||
return features;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean removeFeature(String name) throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean addSupportedFeaturesToDB() throws DeviceManagementException {
|
||||
return false;
|
||||
}
|
||||
}
|
@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.impl.util;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.utils.CarbonUtils;
|
||||
import org.wso2.carbon.utils.dbcreator.DatabaseCreator;
|
||||
|
||||
import java.io.File;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
|
||||
/**
|
||||
* Provides methods for initializing the database script.
|
||||
*/
|
||||
public class DeviceSchemaInitializer extends DatabaseCreator {
|
||||
|
||||
private static final Log log = LogFactory.getLog(DeviceSchemaInitializer.class);
|
||||
private static final String setupSQLScriptBaseLocation = CarbonUtils.getCarbonHome()
|
||||
+ File.separator + "dbscripts"
|
||||
+ File.separator + "cdm" + File.separator + "plugins" + File.separator;
|
||||
|
||||
public DeviceSchemaInitializer(DataSource dataSource) {
|
||||
super(dataSource);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String getDbScriptLocation(String databaseType) {
|
||||
String scriptName = databaseType + ".sql";
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Loading database script from :" + scriptName);
|
||||
}
|
||||
return setupSQLScriptBaseLocation.replaceFirst("DBTYPE", databaseType) + scriptName;
|
||||
}
|
||||
}
|
@ -0,0 +1,122 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* you may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.impl.util;
|
||||
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
import org.wso2.carbon.base.ServerConfiguration;
|
||||
import org.wso2.carbon.core.util.Utils;
|
||||
import org.wso2.carbon.sampledevice.plugin.constants.DeviceTypeConstants;
|
||||
import org.wso2.carbon.sampledevice.plugin.exception.DeviceMgtPluginException;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.PreparedStatement;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.SQLException;
|
||||
import javax.naming.Context;
|
||||
import javax.naming.InitialContext;
|
||||
import javax.naming.NamingException;
|
||||
import javax.sql.DataSource;
|
||||
|
||||
|
||||
/**
|
||||
* Contains utility methods used by sampledevice plugin.
|
||||
*/
|
||||
public class DeviceTypeUtils {
|
||||
|
||||
private static Log log = LogFactory.getLog(org.wso2.carbon.sampledevice.plugin.impl.util.DeviceTypeUtils.class);
|
||||
|
||||
public static void cleanupResources(Connection conn, PreparedStatement stmt, ResultSet rs) {
|
||||
if (rs != null) {
|
||||
try {
|
||||
rs.close();
|
||||
} catch (SQLException e) {
|
||||
log.warn("Error occurred while closing result set", e);
|
||||
}
|
||||
}
|
||||
if (stmt != null) {
|
||||
try {
|
||||
stmt.close();
|
||||
} catch (SQLException e) {
|
||||
log.warn("Error occurred while closing prepared statement", e);
|
||||
}
|
||||
}
|
||||
if (conn != null) {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (SQLException e) {
|
||||
log.warn("Error occurred while closing database connection", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void cleanupResources(PreparedStatement stmt, ResultSet rs) {
|
||||
cleanupResources(null, stmt, rs);
|
||||
}
|
||||
|
||||
public static void setupDeviceManagementSchema() throws DeviceMgtPluginException {
|
||||
try {
|
||||
Context ctx = new InitialContext();
|
||||
DataSource dataSource = (DataSource) ctx.lookup(DeviceTypeConstants.DATA_SOURCE_NAME);
|
||||
DeviceSchemaInitializer initializer =
|
||||
new DeviceSchemaInitializer(dataSource);
|
||||
log.info("Initializing device management repository database schema");
|
||||
initializer.createRegistryDatabase();
|
||||
} catch (NamingException e) {
|
||||
log.error("Error while looking up the data source: " + DeviceTypeConstants.DATA_SOURCE_NAME);
|
||||
} catch (Exception e) {
|
||||
throw new DeviceMgtPluginException("Error occurred while initializing Iot Device " +
|
||||
"Management database schema", e);
|
||||
}
|
||||
}
|
||||
|
||||
public static String replaceMqttProperty(String urlWithPlaceholders) {
|
||||
String mqttBrokerHost = null;
|
||||
String mqttPort = null;
|
||||
if (!DeviceTypeConstants.MQTT_BROKER_HOST.startsWith("$")) {
|
||||
mqttBrokerHost = "\\$".concat(DeviceTypeConstants.MQTT_BROKER_HOST);
|
||||
}
|
||||
if (!DeviceTypeConstants.MQTT_PORT.startsWith("$")) {
|
||||
mqttPort = "\\$".concat(DeviceTypeConstants.MQTT_PORT);
|
||||
}
|
||||
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
|
||||
urlWithPlaceholders = urlWithPlaceholders.replaceAll(mqttPort, "" +
|
||||
(DeviceTypeConstants.DEFAULT_MQTT_PORT + getPortOffset()));
|
||||
urlWithPlaceholders = urlWithPlaceholders.replaceAll(mqttBrokerHost,
|
||||
System.getProperty(DeviceTypeConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
|
||||
return urlWithPlaceholders;
|
||||
}
|
||||
|
||||
private static int getPortOffset() {
|
||||
ServerConfiguration carbonConfig = ServerConfiguration.getInstance();
|
||||
String portOffset = System.getProperty("portOffset", carbonConfig.getFirstProperty(
|
||||
DeviceTypeConstants.CARBON_CONFIG_PORT_OFFSET));
|
||||
try {
|
||||
if ((portOffset != null)) {
|
||||
return Integer.parseInt(portOffset.trim());
|
||||
} else {
|
||||
return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
return DeviceTypeConstants.CARBON_DEFAULT_PORT_OFFSET;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
package org.wso2.carbon.sampledevice.plugin.internal;
|
||||
|
||||
|
||||
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.device.mgt.common.spi.DeviceManagementService;
|
||||
import org.wso2.carbon.sampledevice.plugin.exception.DeviceMgtPluginException;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.DeviceTypeManagerService;
|
||||
import org.wso2.carbon.sampledevice.plugin.impl.util.DeviceTypeUtils;
|
||||
|
||||
/**
|
||||
* @scr.component name="org.wso2.carbon.sampledevice.plugin.internal.ServiceComponent"
|
||||
* immediate="true"
|
||||
*/
|
||||
|
||||
public class ServiceComponent {
|
||||
private static final Log log = LogFactory.getLog(ServiceComponent.class);
|
||||
private ServiceRegistration serviceRegistration;
|
||||
|
||||
protected void activate(ComponentContext ctx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Activating b Management Service Component");
|
||||
}
|
||||
try {
|
||||
DeviceTypeManagerService deviceTypeManagerService = new DeviceTypeManagerService();
|
||||
BundleContext bundleContext = ctx.getBundleContext();
|
||||
serviceRegistration =
|
||||
bundleContext.registerService(DeviceManagementService.class.getName(),
|
||||
deviceTypeManagerService, null);
|
||||
String setupOption = System.getProperty("setup");
|
||||
if (setupOption != null) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("-Dsetup is enabled. Iot Device management repository schema " +
|
||||
"initialization is about to begin");
|
||||
}
|
||||
try {
|
||||
DeviceTypeUtils.setupDeviceManagementSchema();
|
||||
} catch (DeviceMgtPluginException e) {
|
||||
log.error("Exception occurred while initializing device management database " +
|
||||
"schema", e);
|
||||
}
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("b Management Service Component has been successfully activated");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while activating Current Sensor Management Service " +
|
||||
"Component", e);
|
||||
}
|
||||
}
|
||||
|
||||
protected void deactivate(ComponentContext ctx) {
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("De-activating b Management Service Component");
|
||||
}
|
||||
try {
|
||||
if (serviceRegistration != null) {
|
||||
serviceRegistration.unregister();
|
||||
}
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("Current Sensor Management Service Component has been successfully " +
|
||||
"de-activated");
|
||||
}
|
||||
} catch (Throwable e) {
|
||||
log.error("Error occurred while de-activating Iot Device Management bundle", e);
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,57 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0</version>
|
||||
<artifactId>sampledevice-component</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<build>
|
||||
<pluginManagement>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.felix</groupId>
|
||||
<artifactId>maven-scr-plugin</artifactId>
|
||||
<version>${maven-scr-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>generate-scr-scrdescriptor</id>
|
||||
<goals>
|
||||
<goal>scr</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</pluginManagement>
|
||||
</build>
|
||||
<modules>
|
||||
<module>plugin</module>
|
||||
<module>api</module>
|
||||
<module>ui</module>
|
||||
<module>analytics</module>
|
||||
</modules>
|
||||
</project>
|
@ -0,0 +1,56 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice-component</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>${project-base-package}.ui</artifactId>
|
||||
<name>${project-base-package}.ui</name>
|
||||
<packaging>pom</packaging>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-assembly-plugin</artifactId>
|
||||
<version>${maven-assembly-plugin.version}</version>
|
||||
<configuration>
|
||||
<finalName>${project.artifactId}-1.0.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,38 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<assembly
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0
|
||||
http://maven.apache.org/xsd/assembly-1.1.0.xsd">
|
||||
<id>src</id>
|
||||
<formats>
|
||||
<format>zip</format>
|
||||
</formats>
|
||||
<includeBaseDirectory>false</includeBaseDirectory>
|
||||
<baseDirectory>${basedir}/src</baseDirectory>
|
||||
<fileSets>
|
||||
<fileSet>
|
||||
<directory>${basedir}/src/main/resources/jaggeryapps/devicemgt</directory>
|
||||
<outputDirectory>/</outputDirectory>
|
||||
<useDefaultExcludes>true</useDefaultExcludes>
|
||||
</fileSet>
|
||||
</fileSets>
|
||||
</assembly>
|
@ -0,0 +1,39 @@
|
||||
{{!
|
||||
Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
|
||||
WSO2 Inc. licenses this file to you under the Apache License,
|
||||
Version 2.0 (the "License"); you may not use this file except
|
||||
in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
}}
|
||||
<span id="devicetype-details" data-devices="{{devices}}" data-devicename="{{device.name}}"
|
||||
data-deviceid="{{device.deviceIdentifier}}"
|
||||
data-appcontext="{{@app.context}}"></span>
|
||||
<div id="chartDivSensorType1">
|
||||
<div class="chartWrapper" id="chartWrapper">
|
||||
<span id="sensorType1Title">sensor_temp</span>
|
||||
<div id="sensorType1yAxis" class="custom_y_axis"></div>
|
||||
<div class="legend_container">
|
||||
<div id="smoother" title="Smoothing"></div>
|
||||
<div id="sensorType1Legend"></div>
|
||||
</div>
|
||||
<div id="chartSensorType1" class="custom_rickshaw_graph"
|
||||
data-backend-api-url= {{backendApiUri}}></div>
|
||||
<div id="sensorType1xAxis" class="custom_x_axis"></div>
|
||||
<div id="sensorType1Slider" class="custom_slider"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{{#zone "bottomJs"}}
|
||||
{{js "js/devicetype-graph.js"}}
|
||||
{{/zone}}
|
@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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 devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
|
||||
var devices = context.unit.params.devices;
|
||||
var deviceType = context.uriParams.deviceType;
|
||||
var deviceId = request.getParameter("deviceId");
|
||||
|
||||
if (devices) {
|
||||
return {
|
||||
"devices": stringify(devices),
|
||||
"backendApiUri": "/" + deviceType + "/device/stats/"
|
||||
};
|
||||
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
|
||||
var deviceModule = require("/app/modules/business-controllers/device.js")["deviceModule"];
|
||||
var device = deviceModule.viewDevice(deviceType, deviceId);
|
||||
if (device && device.status != "error") {
|
||||
return {
|
||||
"device": device.content,
|
||||
"backendApiUri": "/" + deviceType +"/device/stats/" + deviceId
|
||||
};
|
||||
} else {
|
||||
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "1.0.0"
|
||||
}
|
@ -0,0 +1,208 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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 sensorType1 = "sensor_temp";
|
||||
|
||||
var sensorType1Graph;
|
||||
|
||||
|
||||
function drawGraph_sampledevice(from, to)
|
||||
{
|
||||
//clear the graph before reloading
|
||||
$("#sensorType1yAxis").html("");
|
||||
$("#smoother").html("");
|
||||
$("#sensorType1Legend").html("");
|
||||
$("#chartSensorType1").html("");
|
||||
$("#sensorType1xAxis").html("");
|
||||
$("#sensorType1Slider").html("");
|
||||
|
||||
|
||||
|
||||
var devices = $("#details").data("devices");
|
||||
var tzOffset = new Date().getTimezoneOffset() * 60;
|
||||
var chartWrapperElmId = "#chartDivSensorType1";
|
||||
var graphWidth = $(chartWrapperElmId).width() - 50;
|
||||
var graphConfigSensorType1 = getGraphConfig("chartSensorType1");
|
||||
var graphConfigSensorType2 = getGraphConfig("chartSensorType2");
|
||||
|
||||
function getGraphConfig(placeHolder) {
|
||||
return {
|
||||
element: document.getElementById(placeHolder),
|
||||
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++) {
|
||||
graphConfigSensorType1['series'].push(
|
||||
{
|
||||
'color': palette.color(),
|
||||
'data': [{
|
||||
x: parseInt(new Date().getTime() / 1000),
|
||||
y: 0
|
||||
}],
|
||||
'name': devices[i].name
|
||||
});
|
||||
|
||||
graphConfigSensorType2['series'].push(
|
||||
{
|
||||
'color': palette.color(),
|
||||
'data': [{
|
||||
x: parseInt(new Date().getTime() / 1000),
|
||||
y: 0
|
||||
}],
|
||||
'name': devices[i].name
|
||||
});
|
||||
}
|
||||
} else {
|
||||
graphConfigSensorType1['series'].push(
|
||||
{
|
||||
'color': palette.color(),
|
||||
'data': [{
|
||||
x: parseInt(new Date().getTime() / 1000),
|
||||
y: 0
|
||||
}],
|
||||
'name': $("#details").data("devicename")
|
||||
});
|
||||
graphConfigSensorType2['series'].push(
|
||||
{
|
||||
'color': palette.color(),
|
||||
'data': [{
|
||||
x: parseInt(new Date().getTime() / 1000),
|
||||
y: 0
|
||||
}],
|
||||
'name': $("#details").data("devicename")
|
||||
});
|
||||
}
|
||||
|
||||
sensorType1Graph = new Rickshaw.Graph(graphConfigSensorType1);
|
||||
|
||||
drawGraph(sensorType1Graph, "sensorType1yAxis", "sensorType1Slider", "sensorType1Legend", sensorType1
|
||||
, graphConfigSensorType1, "chartSensorType1");
|
||||
|
||||
function drawGraph(graph, yAxis, slider, legend, sensorType, graphConfig, chart) {
|
||||
console.log("1");
|
||||
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(yAxis),
|
||||
width: 40,
|
||||
height: 410
|
||||
});
|
||||
yAxis.render();
|
||||
var slider = new Rickshaw.Graph.RangeSlider.Preview({
|
||||
graph: graph,
|
||||
element: document.getElementById(slider)
|
||||
});
|
||||
var legend = new Rickshaw.Graph.Legend({
|
||||
graph: graph,
|
||||
element: document.getElementById(legend)
|
||||
});
|
||||
var hoverDetail = new Rickshaw.Graph.HoverDetail({
|
||||
graph: graph,
|
||||
formatter: function (series, x, y) {
|
||||
var date = '<span class="date">' +
|
||||
moment.unix((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
|
||||
});
|
||||
var deviceIndex = 0;
|
||||
console.log("1");
|
||||
if (devices) {
|
||||
getData(chat, deviceIndex, sensorType);
|
||||
} else {
|
||||
var backendApiUrl = $("#" + chart + "").data("backend-api-url") + "?from=" + from + "&to=" + to
|
||||
+ "&sensorType=" + sensorType;
|
||||
var successCallback = function (data) {
|
||||
if (data) {
|
||||
drawLineGraph(JSON.parse(data), sensorType, deviceIndex, graphConfig, graph);
|
||||
}
|
||||
};
|
||||
invokerUtil.get(backendApiUrl, successCallback, function (message) {
|
||||
console.log(message);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function getData(placeHolder, deviceIndex, sensorType, graphConfig, graph) {
|
||||
if (deviceIndex >= devices.length) {
|
||||
return;
|
||||
}
|
||||
var backendApiUrl = $("#" + placeHolder + "").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
|
||||
+ "?from=" + from + "&to=" + to + "&sensorType=" + sensorType;
|
||||
var successCallback = function (data) {
|
||||
if (data) {
|
||||
console.log("----" + data);
|
||||
drawLineGraph(JSON.parse(data), sensorType, deviceIndex, graphConfig, graph);
|
||||
}
|
||||
deviceIndex++;
|
||||
getData(placeHolder, deviceIndex, sensorType);
|
||||
};
|
||||
invokerUtil.get(backendApiUrl, successCallback, function (message) {
|
||||
console.log(message);
|
||||
deviceIndex++;
|
||||
getData(placeHolder, deviceIndex, sensorType);
|
||||
});
|
||||
}
|
||||
|
||||
function drawLineGraph(data, sensorType, deviceIndex, graphConfig, graph) {
|
||||
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(data[i].values[sensorType])
|
||||
}
|
||||
);
|
||||
}
|
||||
graphConfig.series[deviceIndex].data = chartData;
|
||||
graph.update();
|
||||
}
|
||||
}
|
@ -0,0 +1,56 @@
|
||||
{{!
|
||||
Copyright (c) 2017, 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.
|
||||
}}
|
||||
{{#zone "topCss"}}
|
||||
<style>
|
||||
.thumbnail.icon:before {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
</style>
|
||||
{{/zone}}
|
||||
|
||||
{{#zone "device-thumbnail"}}
|
||||
<img src="{{@unit.publicUri}}/images/deviceType.png"/>
|
||||
{{/zone}}
|
||||
|
||||
{{#zone "device-opetations"}}
|
||||
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
|
||||
Operations
|
||||
</div>
|
||||
<div class="add-margin-top-4x">
|
||||
{{unit "cdmf.unit.device.operation-bar" device=device autoCompleteParams=autoCompleteParams
|
||||
encodedFeaturePayloads=encodedFeaturePayloads}}
|
||||
</div>
|
||||
{{/zone}}
|
||||
|
||||
{{#zone "device-view-tabs"}}
|
||||
<li class="active"><a class="list-group-item" href="#device_statistics" role="tab"
|
||||
data-toggle="tab" aria-controls="device_statistics">Device
|
||||
Statistics</a>
|
||||
</li>
|
||||
|
||||
{{/zone}}
|
||||
|
||||
{{#zone "device-view-tab-contents"}}
|
||||
<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.sampledevice.realtime.analytics-view" device=device}}
|
||||
</div>
|
||||
|
||||
{{/zone}}
|
@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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("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/business-controllers/device.js")["deviceModule"];
|
||||
var device = deviceModule.viewDevice(deviceType, deviceId);
|
||||
if (device && device.status != "error") {
|
||||
return {"device": device.content, "autoCompleteParams" : autoCompleteParams, "encodedFeaturePayloads": ""};
|
||||
} else {
|
||||
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");
|
||||
exit();
|
||||
}
|
||||
}
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "1.0.0"
|
||||
}
|
After Width: | Height: | Size: 10 KiB |
@ -0,0 +1,45 @@
|
||||
{{!
|
||||
Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
|
||||
WSO2 Inc. licenses this file to you under the Apache License,
|
||||
Version 2.0 (the "License"); you may not use this file except
|
||||
in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing,
|
||||
software distributed under the License is distributed on an
|
||||
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
KIND, either express or implied. See the License for the
|
||||
specific language governing permissions and limitations
|
||||
under the License.
|
||||
}}
|
||||
|
||||
{{unit "cdmf.unit.lib.rickshaw-graph"}}
|
||||
|
||||
<div id="div-chart-sensorType1" data-websocketurlStream="{{websocketEndpointForStream1}}">
|
||||
<div class="chartWrapper" id="chartWrapper">
|
||||
<div id="yAxisSensorType1" class="custom_y_axis">sensor_temp</div>
|
||||
<div class="legend_container">
|
||||
<div id="smoother" title="Smoothing"></div>
|
||||
<div id="legend"></div>
|
||||
</div>
|
||||
<div id="chartSensorType1" class="custom_rickshaw_graph"></div>
|
||||
<div class="custom_x_axis">Time</div>
|
||||
</div>
|
||||
</div>
|
||||
<a class="padding-left"
|
||||
href="{{@app.context}}/device/{{device.type}}/analytics?deviceId={{device.deviceIdentifier}}
|
||||
&deviceName={{device.name}}">
|
||||
<span class="fw-stack">
|
||||
<i class="fw fw-ring fw-stack-2x"></i>
|
||||
<i class="fw fw-statistics fw-stack-1x"></i>
|
||||
</span> View Device Analytics
|
||||
</a>
|
||||
<!-- /statistics -->
|
||||
{{#zone "bottomJs"}}
|
||||
{{js "js/moment.min.js"}}
|
||||
{{js "js/socket.io.min.js"}}
|
||||
{{js "js/device-stats.js"}}
|
||||
{{/zone}}
|
@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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 carbonServer = require("carbon").server;
|
||||
var device = context.unit.params.device;
|
||||
var devicemgtProps = require("/app/modules/conf-reader/main.js")["conf"];
|
||||
var constants = require("/app/modules/constants.js");
|
||||
var websocketEndpoint = devicemgtProps["wssURL"].replace("https", "wss");
|
||||
var jwtService = carbonServer.osgiService(
|
||||
'org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService');
|
||||
var jwtClient = jwtService.getJWTClient();
|
||||
var encodedClientKeys = session.get(constants["ENCODED_TENANT_BASED_WEB_SOCKET_CLIENT_CREDENTIALS"]);
|
||||
var token = "";
|
||||
if (encodedClientKeys) {
|
||||
var tokenUtil = require("/app/modules/oauth/token-handler-utils.js")["utils"];
|
||||
var resp = tokenUtil.decode(encodedClientKeys).split(":");
|
||||
var tokenPair = jwtClient.getAccessToken(resp[0], resp[1], context.user.username,"default", {});
|
||||
if (tokenPair) {
|
||||
token = tokenPair.accessToken;
|
||||
}
|
||||
var websocketToken= {'name':'websocket-token','value': token, 'path':'/', "maxAge":18000};
|
||||
response.addCookie(websocketToken);
|
||||
}
|
||||
var websocketEndpointForStream1 = websocketEndpoint + "/secured-websocket/org.wso2.iot.devices.sensor_temp/1.0.0?deviceId="
|
||||
+ device.deviceIdentifier + "&deviceType=" + device.type + "&websocketToken=" + token;
|
||||
|
||||
return {
|
||||
"device": device,
|
||||
"websocketEndpointForStream1": websocketEndpointForStream1
|
||||
|
||||
};
|
||||
}
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "1.0.0"
|
||||
}
|
@ -0,0 +1,115 @@
|
||||
/*
|
||||
* Copyright (c) 2017, 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 wsConnection1;
|
||||
var wsConnection2;
|
||||
var graphForSensorType1;
|
||||
var graphForSensorType2;
|
||||
var chartDataSensorType1 = [];
|
||||
var chartDataSensorType2 = [];
|
||||
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
|
||||
function drawGraph(wsConnection, placeHolder, yAxis, chat, chartData, graph) {
|
||||
var tNow = new Date().getTime() / 1000;
|
||||
for (var i = 0; i < 30; i++) {
|
||||
chartData.push({
|
||||
x: tNow - (30 - i) * 15,
|
||||
y: parseFloat(0)
|
||||
});
|
||||
}
|
||||
|
||||
graph = new Rickshaw.Graph({
|
||||
element: document.getElementById(chat),
|
||||
width: $(placeHolder).width() - 50,
|
||||
height: 300,
|
||||
renderer: "line",
|
||||
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
|
||||
xScale: d3.time.scale(),
|
||||
series: [{
|
||||
'color': palette.color(),
|
||||
'data': chartData,
|
||||
'name': "SensorValue"
|
||||
}]
|
||||
});
|
||||
|
||||
graph.render();
|
||||
|
||||
var xAxis = new Rickshaw.Graph.Axis.Time({
|
||||
graph: graph
|
||||
});
|
||||
|
||||
xAxis.render();
|
||||
|
||||
new Rickshaw.Graph.Axis.Y({
|
||||
graph: graph,
|
||||
orientation: 'left',
|
||||
height: 300,
|
||||
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
|
||||
element: document.getElementById(yAxis)
|
||||
});
|
||||
|
||||
new Rickshaw.Graph.HoverDetail({
|
||||
graph: graph,
|
||||
formatter: function (series, x, y) {
|
||||
var date = '<span class="date">' + moment.unix(x * 1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
|
||||
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
|
||||
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
|
||||
}
|
||||
});
|
||||
var websocketurlStream = $(placeHolder).attr("data-websocketurlStream");
|
||||
connect(wsConnection, websocketurlStream, chartData, graph);
|
||||
}
|
||||
|
||||
$(window).load(function () {
|
||||
drawGraph(wsConnection1, "#div-chart-sensorType1", "yAxisSensorType1", "chartSensorType1", chartDataSensorType1
|
||||
, graphForSensorType1);
|
||||
|
||||
});
|
||||
|
||||
$(window).unload(function () {
|
||||
disconnect(wsConnection1);
|
||||
disconnect(wsConnection2);
|
||||
});
|
||||
|
||||
//websocket connection
|
||||
function connect(wsConnection, target, chartData, graph) {
|
||||
if ('WebSocket' in window) {
|
||||
wsConnection = new WebSocket(target);
|
||||
} else if ('MozWebSocket' in window) {
|
||||
wsConnection = new MozWebSocket(target);
|
||||
} else {
|
||||
console.log('WebSocket is not supported by this browser.');
|
||||
}
|
||||
if (wsConnection) {
|
||||
wsConnection.onmessage = function (event) {
|
||||
var dataPoint = JSON.parse(event.data);
|
||||
chartData.push({
|
||||
x: parseInt(dataPoint[4]) / 1000,
|
||||
y: parseFloat(dataPoint[5])
|
||||
});
|
||||
chartData.shift();
|
||||
graph.update();
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function disconnect(wsConnection) {
|
||||
if (wsConnection != null) {
|
||||
wsConnection.close();
|
||||
wsConnection = null;
|
||||
}
|
||||
}
|
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@ -0,0 +1,10 @@
|
||||
{
|
||||
"deviceType": {
|
||||
"label": "sampledevice",
|
||||
"category": "iot",
|
||||
"downloadAgentUri": "sampledevice/device/download",
|
||||
"scopes": [
|
||||
"perm:sampledevice:enroll"
|
||||
]
|
||||
}
|
||||
}
|
@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
.circle {
|
||||
background: none repeat scroll 0 0 #191919;
|
||||
border-radius: 50px;
|
||||
height: 50px;
|
||||
padding: 10px;
|
||||
width: 50px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.padding-top-double {
|
||||
padding-top: 20px;
|
||||
}
|
||||
|
||||
.padding-double {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.grey {
|
||||
color: #333;
|
||||
}
|
||||
|
||||
hr {
|
||||
display: block;
|
||||
height: 1px;
|
||||
border: 0;
|
||||
border-top: 1px solid #7f7f7f;
|
||||
margin: 1em 0;
|
||||
padding: 0;
|
||||
opacity: 0.2;
|
||||
}
|
||||
|
||||
.light-grey {
|
||||
color: #7c7c7c;
|
||||
}
|
||||
|
||||
.uppercase {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.grey-bg {
|
||||
background-color: #f6f4f4;
|
||||
}
|
||||
|
||||
.doc-link{
|
||||
background: none;
|
||||
color: #000;
|
||||
padding: 10px 0px;
|
||||
}
|
||||
|
||||
.doc-link a {
|
||||
color: #006eff;
|
||||
}
|
After Width: | Height: | Size: 10 KiB |
After Width: | Height: | Size: 126 KiB |
After Width: | Height: | Size: 10 KiB |
@ -0,0 +1,135 @@
|
||||
/*
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
*/
|
||||
|
||||
var modalPopup = ".modal";
|
||||
var modalPopupContainer = modalPopup + " .modal-content";
|
||||
var modalPopupContent = modalPopup + " .modal-content";
|
||||
var body = "body";
|
||||
|
||||
/*
|
||||
* Set popup maximum height function.
|
||||
*/
|
||||
function setPopupMaxHeight() {
|
||||
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
|
||||
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
|
||||
}
|
||||
|
||||
/*
|
||||
* Shows agent download popup.
|
||||
*/
|
||||
function showAgentDownloadPopup() {
|
||||
$(modalPopup).modal('show');
|
||||
setPopupMaxHeight();
|
||||
var deviceType = "";
|
||||
$('.deviceType').each(function () {
|
||||
if (this.value != "") {
|
||||
deviceType = this.value;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
* Hides agent download popup.
|
||||
*/
|
||||
function hideAgentDownloadPopup() {
|
||||
$('label[for=deviceName]').remove();
|
||||
$('.control-group').removeClass('success').removeClass('error');
|
||||
$(modalPopupContent).html('');
|
||||
$(modalPopup).modal('hide');
|
||||
}
|
||||
|
||||
/*
|
||||
* DOM ready functions.
|
||||
*/
|
||||
$(document).ready(function () {
|
||||
attachEvents();
|
||||
});
|
||||
|
||||
function attachEvents() {
|
||||
/**
|
||||
* Following click function would execute
|
||||
* when a user clicks on "Download" link
|
||||
* on Device Management page in WSO2 DC Console.
|
||||
*/
|
||||
$("a.download-link").click(function () {
|
||||
var sketchType = $(this).data("sketchtype");
|
||||
var deviceType = $(this).data("devicetype");
|
||||
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
|
||||
var payload = {"sketchType": sketchType, "deviceType": deviceType};
|
||||
$(modalPopupContent).html($('#download-device-modal-content').html());
|
||||
showAgentDownloadPopup();
|
||||
});
|
||||
}
|
||||
|
||||
function downloadAgent() {
|
||||
var deviceName;
|
||||
$('.new-device-name').each(function () {
|
||||
if (this.value != "") {
|
||||
deviceName = this.value;
|
||||
}
|
||||
});
|
||||
var deviceNameFormat = /^[^~?!#$:;%^*`+={}\[\]\\()|<>,'"]{1,30}$/;
|
||||
if (deviceName && deviceName.length < 4) {
|
||||
$("#invalid-username-error-msg span").text("Device name should be more than 3 letters!");
|
||||
$("#invalid-username-error-msg").removeClass("hidden");
|
||||
} else if (deviceName && deviceNameFormat.test(deviceName)) {
|
||||
$('#downloadForm').submit();
|
||||
hidePopup();
|
||||
$(modalPopupContent).html($('#device-agent-downloading-content').html());
|
||||
showPopup();
|
||||
setTimeout(function () {
|
||||
hidePopup();
|
||||
}, 1000);
|
||||
}else {
|
||||
$("#invalid-username-error-msg span").text("Invalid device name");
|
||||
$("#invalid-username-error-msg").removeClass("hidden");
|
||||
}
|
||||
}
|
||||
|
||||
function doAction(data) {
|
||||
//if it is saml redirection response
|
||||
if (data.status == null) {
|
||||
document.write(data);
|
||||
}
|
||||
|
||||
if (data.status == "200") {
|
||||
$(modalPopupContent).html($('#download-device-modal-content-links').html());
|
||||
$("input#download-device-url").val(data.responseText);
|
||||
$("input#download-device-url").focus(function () {
|
||||
$(this).select();
|
||||
});
|
||||
showAgentDownloadPopup();
|
||||
} else if (data.status == "401") {
|
||||
$(modalPopupContent).html($('#device-401-content').html());
|
||||
$("#device-401-link").click(function () {
|
||||
window.location = "/devicemgt/login";
|
||||
});
|
||||
showAgentDownloadPopup();
|
||||
} else if (data == "403") {
|
||||
$(modalPopupContent).html($('#device-403-content').html());
|
||||
$("#device-403-link").click(function () {
|
||||
window.location = "/devicemgt/login";
|
||||
});
|
||||
showAgentDownloadPopup();
|
||||
} else {
|
||||
$(modalPopupContent).html($('#device-unexpected-error-content').html());
|
||||
$("a#device-unexpected-error-link").click(function () {
|
||||
hideAgentDownloadPopup();
|
||||
});
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
@ -0,0 +1,225 @@
|
||||
{{!
|
||||
Copyright (c) 2017, 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.
|
||||
}}
|
||||
|
||||
<div class="col-lg-12 margin-top-double">
|
||||
<h1 class="grey "></h1>
|
||||
<hr>
|
||||
</div>
|
||||
|
||||
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 padding-top">
|
||||
<img src="{{@unit.publicUri}}/images/deviceType.png" class="img-responsive">
|
||||
</div>
|
||||
|
||||
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
|
||||
|
||||
</div>
|
||||
|
||||
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
|
||||
<h3 class="uppercase">What it Does</h3>
|
||||
<hr>
|
||||
<p class="grey margin-top">Connect a sampledevice to WSO2 IoT Server and manage it.</p>
|
||||
<p>Add brief description what this device type does</p>
|
||||
<h3 class="uppercase">What You Need</h3>
|
||||
<p>Add hardware requirement which will be required to make this device type </p>
|
||||
<br>
|
||||
<hr>
|
||||
<br>
|
||||
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
|
||||
class="btn-operations"
|
||||
target="_blank"><i class="fw fw-api add-margin-1x"></i> View API</i>
|
||||
</a>
|
||||
<a href="#" class="download-link btn-operations">
|
||||
<i class="fw fw-download add-margin-1x"></i>Download Agent
|
||||
</a>
|
||||
<div id="download-device-modal-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 center-container">
|
||||
<h3>Name your device and download the agent from following link.</h3>
|
||||
<br/>
|
||||
<form id="downloadForm" method="GET"
|
||||
action="{{@app.context}}/api/devices/sketch/download">
|
||||
<div id="invalid-username-error-msg" class="alert alert-danger hidden"
|
||||
role="alert">
|
||||
<i class="icon fw fw-error"></i><span></span>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<div class="controls">
|
||||
<input class="new-device-name" style="color:#3f3f3f;padding:5px"
|
||||
type="text"
|
||||
placeholder="Ex. Lobby_Device"
|
||||
name="deviceName" size="60" required>
|
||||
<br/>
|
||||
<input type="hidden" class="deviceType" name="deviceType"
|
||||
value="sampledevice"/>
|
||||
<input type="hidden" class="sketchType" name="sketchType"
|
||||
value="sampledevice"/>
|
||||
</div>
|
||||
</div>
|
||||
<div class="buttons" style="padding-bottom: 0px">
|
||||
<a class="btn btn-operations" onclick="downloadAgent()">Download Now</a>
|
||||
|
||||
<a href="#" id="download-device-download-link"
|
||||
class="btn btn-operations"> Copy Link
|
||||
</a>
|
||||
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="device-agent-downloading-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 col-centered center-container">
|
||||
<h3>Device Agent will downloading shortly.</h3>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="device-400-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 col-centered center-container">
|
||||
<h3>Exception at backend. Try Later.</h3>
|
||||
<div class="buttons">
|
||||
<a href="#" id="device-400-link" class="btn-operations">
|
||||
OK
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="device-401-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 col-centered center-container">
|
||||
<h3>You have to log in first.</h3><br/>
|
||||
<div class="buttons">
|
||||
<a href="#" id="device-401-link" class="blue-button">
|
||||
Goto Login Page
|
||||
</a>
|
||||
<a href="#" onclick="hidePopup();" class="btn-operations">
|
||||
Cancel
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="device-403-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 col-centered center-container">
|
||||
<h3>Action not permitted.</h3><br/>
|
||||
|
||||
<div class="buttons">
|
||||
<a href="#" id="device-403-link" class="btn-operations">
|
||||
OK
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="device-409-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 col-centered center-container">
|
||||
<h3>Device Sketch does not exist.</h3><br/>
|
||||
<div class="buttons">
|
||||
<a href="#" id="device-409-link" class="btn-operations">
|
||||
OK
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="device-unexpected-error-content" class="hide">
|
||||
<div class="modal-content">
|
||||
<div class="row">
|
||||
<div class="col-md-7 col-centered center-container">
|
||||
<h3>Unexpected error.</h3><br/>
|
||||
<div class="buttons">
|
||||
<a href="#" id="device-unexpected-error-link" class="btn-operations">
|
||||
OK
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<br/><br/>
|
||||
</div>
|
||||
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding-double grey-bg">
|
||||
<h3 class="uppercase">Prepare</h3>
|
||||
<hr>
|
||||
<ul class="list-unstyled">
|
||||
<li class="padding-top-double"><span class="circle">01</span> Add how you
|
||||
are goining to
|
||||
prepare your device
|
||||
</li>
|
||||
</ul>
|
||||
<br>
|
||||
<br>
|
||||
</div>
|
||||
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
|
||||
<h3 class="uppercase">Schematic Diagram</h3>
|
||||
<hr>
|
||||
<p class="grey margin-top">Click on the image to zoom</p>
|
||||
<center>
|
||||
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
|
||||
<img src="{{@unit.publicUri}}/images/schematicsGuide.png" class="img-responsive">
|
||||
</a>
|
||||
</center>
|
||||
<br/>
|
||||
</div>
|
||||
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
|
||||
<h3 class="uppercase">Try Out</h3>
|
||||
<hr>
|
||||
<ul class="list-unstyled">
|
||||
<li class="padding-top-double">
|
||||
<span class="circle">01</span>
|
||||
You can view all your connected devices at
|
||||
<a href="{{@app.context}}/devices">[Device Management]</a> page.
|
||||
</li>
|
||||
<li class="padding-top-double">
|
||||
<span class="circle">02</span>
|
||||
Select one of connected devices and check for available control
|
||||
operations and monitor Real-Time data.
|
||||
</li>
|
||||
<li class="padding-top-double">
|
||||
<span class="circle">03</span>
|
||||
You can also view analytics of the data published to IoT-Server by
|
||||
navigating to Device Analytics page.
|
||||
</li>
|
||||
</ul>
|
||||
<br/>
|
||||
</div>
|
||||
|
||||
{{#zone "topCss"}}
|
||||
{{css "css/styles.css"}}
|
||||
{{/zone}}
|
||||
|
||||
{{#zone "bottomJs"}}
|
||||
{{js "/js/download.js"}}
|
||||
{{js "/js/jquery.validate.js"}}
|
||||
{{/zone}}
|
@ -0,0 +1,3 @@
|
||||
{
|
||||
"version": "1.0.0"
|
||||
}
|
@ -0,0 +1,213 @@
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice-feature</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<version>1.0.0</version>
|
||||
<artifactId>${project-base-package}.feature</artifactId>
|
||||
<packaging>pom</packaging>
|
||||
<name>${project-base-package}.feature</name>
|
||||
<url>http://wso2.org</url>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.plugin</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.api</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<type>war</type>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database.wso2</groupId>
|
||||
<artifactId>h2-database-engine</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<artifactId>maven-resources-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>copy-resources</id>
|
||||
<phase>generate-resources</phase>
|
||||
<goals>
|
||||
<goal>copy-resources</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<outputDirectory>src/main/resources</outputDirectory>
|
||||
<resources>
|
||||
<resource>
|
||||
<directory>resources</directory>
|
||||
<includes>
|
||||
<include>build.properties</include>
|
||||
<include>p2.inf</include>
|
||||
</includes>
|
||||
</resource>
|
||||
</resources>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-dependency-plugin</artifactId>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>unpack</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>unpack</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.analytics</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<type>zip</type>
|
||||
<overWrite>true</overWrite>
|
||||
<outputDirectory>
|
||||
${project.build.directory}/maven-shared-archive-resources/carbonapps
|
||||
</outputDirectory>
|
||||
<includes>**/*</includes>
|
||||
</artifactItem>
|
||||
<artifactItem>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.ui
|
||||
</artifactId>
|
||||
<version>${project.version}</version>
|
||||
<type>zip</type>
|
||||
<overWrite>true</overWrite>
|
||||
<outputDirectory>
|
||||
${project.build.directory}/maven-shared-archive-resources/jaggeryapps/devicemgt
|
||||
</outputDirectory>
|
||||
<includes>**/*</includes>
|
||||
</artifactItem>
|
||||
</artifactItems>
|
||||
</configuration>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>copy-jaxrs-war</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>copy</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<artifactItems>
|
||||
<artifactItem>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.api</artifactId>
|
||||
<type>war</type>
|
||||
<overWrite>true</overWrite>
|
||||
<outputDirectory>
|
||||
${project.build.directory}/maven-shared-archive-resources/webapps/
|
||||
</outputDirectory>
|
||||
<destFileName>sampledevice.war</destFileName>
|
||||
</artifactItem>
|
||||
</artifactItems>
|
||||
</configuration>
|
||||
</execution>
|
||||
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-antrun-plugin</artifactId>
|
||||
<version>${maven-antrun-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>create-sampledevice-plugin-mgt-schema</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>run</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<tasks>
|
||||
<property name="db.dir"
|
||||
value="target/maven-shared-archive-resources/database"/>
|
||||
<property name="userid" value="wso2carbon"/>
|
||||
<property name="password" value="wso2carbon"/>
|
||||
<property name="dbURL"
|
||||
value="jdbc:h2:file:${basedir}/${db.dir}/sampledeviceDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
|
||||
<mkdir dir="${basedir}/${db.dir}"/>
|
||||
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
|
||||
password="${password}"
|
||||
autocommit="true" onerror="continue">
|
||||
<classpath refid="maven.dependency.classpath"/>
|
||||
<classpath refid="maven.compile.classpath"/>
|
||||
<classpath refid="maven.runtime.classpath"/>
|
||||
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
|
||||
</sql>
|
||||
</tasks>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.wso2.maven</groupId>
|
||||
<artifactId>carbon-p2-plugin</artifactId>
|
||||
<version>${carbon-p2-plugin.version}</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>p2-feature-generation</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>p2-feature-gen</goal>
|
||||
</goals>
|
||||
<configuration>
|
||||
<id>${project-base-package}</id>
|
||||
<propertiesFile>../../../features/etc/feature.properties
|
||||
</propertiesFile>
|
||||
<adviceFile>
|
||||
<properties>
|
||||
<propertyDef>org.wso2.carbon.p2.category.type:server
|
||||
</propertyDef>
|
||||
<propertyDef>org.eclipse.equinox.p2.type.group:true
|
||||
</propertyDef>
|
||||
</properties>
|
||||
</adviceFile>
|
||||
<bundles>
|
||||
<bundleDef>
|
||||
org.wso2.carbon:${project-base-package}.plugin:1.0.0
|
||||
</bundleDef>
|
||||
</bundles>
|
||||
<importFeatures>
|
||||
<importFeatureDef>
|
||||
org.wso2.carbon.core.server:${carbon.kernel.version}
|
||||
</importFeatureDef>
|
||||
<importFeatureDef>
|
||||
org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
|
||||
</importFeatureDef>
|
||||
</importFeatures>
|
||||
</configuration>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
@ -0,0 +1,34 @@
|
||||
#
|
||||
# Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
#
|
||||
#
|
||||
[Device-Configurations]
|
||||
owner={DEVICE_OWNER}
|
||||
deviceId={DEVICE_ID}
|
||||
device-name={DEVICE_NAME}
|
||||
server-name={SERVER_NAME}
|
||||
controller-context=/sampledevice
|
||||
device-type=sampledevice
|
||||
mqtt-ep={MQTT_EP}
|
||||
https-ep={HTTPS_EP}
|
||||
http-ep={HTTP_EP}
|
||||
apim-ep={APIM_EP}
|
||||
auth-method=token
|
||||
auth-token={DEVICE_TOKEN}
|
||||
refresh-token={DEVICE_REFRESH_TOKEN}
|
||||
push-interval=15
|
||||
application-key={API_APPLICATION_KEY}
|
||||
|
||||
|
After Width: | Height: | Size: 10 KiB |
@ -0,0 +1,16 @@
|
||||
#/*
|
||||
# * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
# * WSO2 Inc. licenses this file to you under the Apache License,
|
||||
# * Version 2.0 (the "License"); you may not use this file except
|
||||
# * in compliance with the License.
|
||||
# * You may obtain a copy of the License at
|
||||
# * http://www.apache.org/licenses/LICENSE-2.0
|
||||
# * Unless required by applicable law or agreed to in writing,
|
||||
# * software distributed under the License is distributed on an
|
||||
# * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# * KIND, either express or implied. See the License for the
|
||||
# * specific language governing permissions and limitations
|
||||
# * under the License.
|
||||
# */
|
||||
templates=deviceConfig.properties
|
||||
zipfilename=sampledevice.zip
|
@ -0,0 +1,271 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
/**
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
**/
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import calendar
|
||||
import logging
|
||||
import logging.handlers
|
||||
import signal
|
||||
import ssl
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
import iotUtils
|
||||
import mqttHandler
|
||||
import running_mode
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Overriding the default SSL version used in some of the Python (2.7.x) versions
|
||||
# This is a known issue in earlier Python releases
|
||||
# But was fixed in later versions. Ex-2.7.11
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def sslwrap(func):
|
||||
@wraps(func)
|
||||
def bar(*args, **kw):
|
||||
kw['ssl_version'] = ssl.PROTOCOL_TLSv1
|
||||
return func(*args, **kw)
|
||||
|
||||
return bar
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
PUSH_INTERVAL = 2 # time interval between successive data pushes in seconds
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Logger defaults
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
LOG_FILENAME = "agent.log"
|
||||
logging_enabled = False
|
||||
LOG_LEVEL = logging.INFO # Could be e.g. "DEBUG" or "WARNING"
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Python version
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
if sys.version_info < (2, 6, 0):
|
||||
sys.stderr.write("You need python 2.6.0 or later to run this script\n")
|
||||
exit(1)
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Define and parse command line arguments
|
||||
# If the log file is specified on the command line then override the default
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
parser = argparse.ArgumentParser(description="Python service to push RPi info to the Device Cloud")
|
||||
parser.add_argument("-l", "--log", help="file to write log to (default '" + LOG_FILENAME + "')")
|
||||
|
||||
help_string_for_data_push_interval = "time interval between successive locker status push to server(default '" + \
|
||||
str(PUSH_INTERVAL) + "')"
|
||||
help_string_for_running_mode = "whether it is going to run on the real device or not"
|
||||
|
||||
parser.add_argument("-i", "--interval", type=int, help=help_string_for_data_push_interval)
|
||||
|
||||
parser.add_argument("-m", "--mode", type=str, help=help_string_for_running_mode)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.log:
|
||||
LOG_FILENAME = args.log
|
||||
|
||||
if args.interval:
|
||||
PUSH_INTERVAL = args.interval
|
||||
|
||||
if args.mode:
|
||||
running_mode.RUNNING_MODE = args.mode
|
||||
iotUtils = __import__('iotUtils')
|
||||
mqttConnector = __import__('mqttHandler')
|
||||
|
||||
if running_mode.RUNNING_MODE == 'N':
|
||||
Adafruit_DHT = __import__('Adafruit_DHT')
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Endpoint specific settings to connect with the IoT Server
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
SERVER_ENDPOINT = iotUtils.HTTPS_EP.split(":")
|
||||
SERVER_IP = SERVER_ENDPOINT[1].replace('//', '')
|
||||
SERVER_PORT = int(SERVER_ENDPOINT[2])
|
||||
API_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT
|
||||
PUSH_SENSOR_VALUE_ENDPOINT = str(API_ENDPOINT_CONTEXT) + '/push-sensor-value'
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# A class we can use to capture stdout and sterr in the log
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
class IOTLogger(object):
|
||||
def __init__(self, logger, level):
|
||||
"""Needs a logger and a logger level."""
|
||||
self.logger = logger
|
||||
self.level = level
|
||||
|
||||
def write(self, message):
|
||||
if message.rstrip() != "": # Only log if there is a message (not just a new line)
|
||||
self.logger.log(self.level, message.rstrip())
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Configure logging to log to a file,
|
||||
# making a new file at midnight and keeping the last 3 day's data
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def configureLogger(loggerName):
|
||||
logger = logging.getLogger(loggerName)
|
||||
logger.setLevel(LOG_LEVEL) # Set the log level to LOG_LEVEL
|
||||
handler = logging.handlers.TimedRotatingFileHandler(LOG_FILENAME, when="midnight",
|
||||
backupCount=3) # Handler that writes to a file,
|
||||
# ~~~make new file at midnight and keep 3 backups
|
||||
formatter = logging.Formatter(
|
||||
'%(asctime)s %(levelname)-8s %(message)s') # Format each log message like this
|
||||
handler.setFormatter(formatter) # Attach the formatter to the handler
|
||||
logger.addHandler(handler) # Attach the handler to the logger
|
||||
|
||||
if (logging_enabled):
|
||||
sys.stdout = IOTLogger(logger,
|
||||
logging.INFO) # Replace stdout with logging to file at INFO level
|
||||
sys.stderr = IOTLogger(logger,
|
||||
logging.ERROR) # Replace stderr with logging to file at ERROR level
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# This is a Thread object for listening for MQTT Messages
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
class ListenMQTTThread(object):
|
||||
def __init__(self):
|
||||
thread = threading.Thread(target=self.run, args=())
|
||||
thread.daemon = True # Daemonize thread
|
||||
thread.start() # Start the execution
|
||||
|
||||
def run(self):
|
||||
mqttHandler.main()
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# When sysvinit sends the TERM signal, cleanup before exiting
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def sigterm_handler(_signo, _stack_frame):
|
||||
print("[] received signal {}, exiting...".format(_signo))
|
||||
sys.exit(0)
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# This is a Thread object for reading temperature continuously
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
class TemperatureReaderThread(object):
|
||||
def __init__(self):
|
||||
if running_mode.RUNNING_MODE == 'N':
|
||||
self.interval = iotUtils.TEMPERATURE_READING_INTERVAL_REAL_MODE
|
||||
else:
|
||||
self.interval = iotUtils.TEMPERATURE_READING_INTERVAL_VIRTUAL_MODE
|
||||
thread = threading.Thread(target=self.run, args=())
|
||||
thread.daemon = True # Daemonize thread
|
||||
thread.start() # Start the execution
|
||||
|
||||
def run(self):
|
||||
|
||||
# Try to grab a sensor reading. Use the read_retry method which will retry up
|
||||
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
|
||||
while True:
|
||||
try:
|
||||
if running_mode.RUNNING_MODE == 'N':
|
||||
humidity, temperature = Adafruit_DHT.read_retry(iotUtils.TEMP_SENSOR_TYPE,
|
||||
iotUtils.TEMP_PIN)
|
||||
else:
|
||||
humidity, temperature = iotUtils.generateRandomSensorValues()
|
||||
|
||||
if temperature != iotUtils.LAST_TEMP:
|
||||
time.sleep(PUSH_INTERVAL)
|
||||
iotUtils.LAST_TEMP = temperature
|
||||
# connectAndPushData()
|
||||
|
||||
iotUtils.LAST_TEMP = temperature
|
||||
print 'RASPBERRY_STATS: Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature,
|
||||
humidity)
|
||||
|
||||
except Exception, e:
|
||||
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
|
||||
print "RASPBERRY_STATS: Exception in TempReaderThread: Could not successfully " \
|
||||
"read Temperature"
|
||||
print ("RASPBERRY_STATS: " + str(e))
|
||||
pass
|
||||
time.sleep(self.interval)
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# This method connects to the Device-Cloud and pushes data
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
def connectAndPushData():
|
||||
currentTime = calendar.timegm(time.gmtime())
|
||||
rPiTemperature = iotUtils.LAST_TEMP # Push the last read temperature value
|
||||
PUSH_DATA = iotUtils.DEVICE_INFO.format(currentTime, rPiTemperature)
|
||||
|
||||
mqttConnector.publish(PUSH_DATA)
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# generate random sensor value
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def getSensorValue():
|
||||
return iotUtils.LAST_TEMP
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
signal.signal(signal.SIGTERM, sigterm_handler)
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# The Main method of the Agent
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def main():
|
||||
configureLogger("agent")
|
||||
ListenMQTTThread()
|
||||
TemperatureReaderThread()
|
||||
while True:
|
||||
try:
|
||||
|
||||
currentTime = calendar.timegm(time.gmtime())
|
||||
sensorValue = getSensorValue()
|
||||
PUSH_DATA_TO_STREAM_1 = iotUtils.SENSOR_STATS_SENSOR1.format(currentTime, sensorValue)
|
||||
|
||||
mqttHandler.sendSensorValue(PUSH_DATA_TO_STREAM_1)
|
||||
print '~~~~~~~~~~~~~~~~~~~~~~~~ Publishing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~'
|
||||
print ('PUBLISHED DATA STREAM 1: ' + PUSH_DATA_TO_STREAM_1)
|
||||
|
||||
time.sleep(PUSH_INTERVAL)
|
||||
except (KeyboardInterrupt, Exception) as e:
|
||||
print "agentStats: Exception in AgentThread (either KeyboardInterrupt or Other)"
|
||||
print ("agentStats: " + str(e))
|
||||
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
|
||||
pass
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -0,0 +1,105 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
/**
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
**/
|
||||
"""
|
||||
|
||||
import ConfigParser
|
||||
import os
|
||||
import random
|
||||
|
||||
import running_mode
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Device specific info when pushing data to server
|
||||
# Read from a file "deviceConfig.properties" in the same folder level
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
configParser = ConfigParser.RawConfigParser()
|
||||
configFilePath = os.path.join(os.path.dirname(__file__), './deviceConfig.properties')
|
||||
configParser.read(configFilePath)
|
||||
|
||||
DEVICE_OWNER = configParser.get('Device-Configurations', 'owner')
|
||||
DEVICE_ID = configParser.get('Device-Configurations', 'deviceId')
|
||||
DEVICE_NAME = configParser.get('Device-Configurations', 'device-name')
|
||||
DEVICE_TYPE = configParser.get('Device-Configurations', 'device-type')
|
||||
SERVER_NAME = configParser.get('Device-Configurations', 'server-name')
|
||||
MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
|
||||
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
|
||||
REFRESH_TOKEN = configParser.get('Device-Configurations', 'refresh-token')
|
||||
APPLICATION_KEY = configParser.get('Device-Configurations', 'application-key')
|
||||
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
|
||||
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '",'
|
||||
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
|
||||
HTTP_EP = configParser.get('Device-Configurations', 'http-ep')
|
||||
APIM_EP = configParser.get('Device-Configurations', 'apim-ep')
|
||||
DEVICE_DATA = '"sensorValue":"{sensorValue}"'
|
||||
SENSOR_STATS_SENSOR1 = '{{"event":{{"metaData":{{"owner":"' + DEVICE_OWNER + '","deviceType":"' + DEVICE_TYPE \
|
||||
+ '","deviceId":"' + DEVICE_ID + '","time":{}}},"payloadData":{{"sensor_temp":{:.2f}}}}}}}'
|
||||
|
||||
global LAST_TEMP
|
||||
LAST_TEMP = 25
|
||||
|
||||
TEMPERATURE_READING_INTERVAL_REAL_MODE = 3
|
||||
TEMPERATURE_READING_INTERVAL_VIRTUAL_MODE = 60
|
||||
TEMP_PIN = 4
|
||||
TEMP_SENSOR_TYPE = 11
|
||||
BULB_PIN = 18
|
||||
|
||||
|
||||
def isEmpty(string):
|
||||
if string and string.strip():
|
||||
# string is not None AND string is not empty or blank
|
||||
return False
|
||||
# string is None OR string is empty or blank
|
||||
return True
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# Performs the state changing operation of the LED
|
||||
#
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def switchBulb(state):
|
||||
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
|
||||
print "Requested Switch State: " + state
|
||||
|
||||
if running_mode == "N":
|
||||
|
||||
import RPi.GPIO as GPIO
|
||||
|
||||
if state == "ON":
|
||||
GPIO.output(BULB_PIN, True)
|
||||
print "BULB Switched ON"
|
||||
elif state == "OFF":
|
||||
GPIO.output(BULB_PIN, False)
|
||||
print "BULB Switched OFF"
|
||||
|
||||
else:
|
||||
|
||||
if state == "ON":
|
||||
print "BULB Switched ON"
|
||||
elif state == "OFF":
|
||||
print "BULB Switched OFF"
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# This method generate a random sensor value between 15 and 40
|
||||
#
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def generateRandomSensorValues():
|
||||
return random.randint(15, 40), random.randint(15, 40)
|
@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
/**
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
**/
|
||||
"""
|
||||
|
||||
import paho.mqtt.client as mqtt
|
||||
import time
|
||||
|
||||
import iotUtils
|
||||
from token_updater import RefreshToken
|
||||
|
||||
global mqttClient
|
||||
mqttClient = mqtt.Client(client_id='sampledevice-client')
|
||||
agent_connected = False
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# The callback for when the client receives a CONNACK response from the server.
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def on_connect(mqttClient, userdata, flags, rc):
|
||||
if rc == 0:
|
||||
global agent_connected
|
||||
agent_connected = True
|
||||
# Subscribing in on_connect() means that if we lose the connection and
|
||||
# reconnect then subscriptions will be renewed.
|
||||
print ("MQTT_LISTENER: Subscribing with topic " + TOPIC_TO_SUBSCRIBE)
|
||||
mqttClient.subscribe(TOPIC_TO_SUBSCRIBE)
|
||||
|
||||
elif rc == 4:
|
||||
token = RefreshToken()
|
||||
response = token.updateTokens()
|
||||
newAccessToken = response['access_token']
|
||||
mqttClient.username_pw_set(newAccessToken, password="")
|
||||
else:
|
||||
|
||||
global agent_connected
|
||||
agent_connected = False
|
||||
|
||||
print("MQTT_LISTENER: Connected with result code " + str(rc))
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# The callback for when a PUBLISH message is received from the server.
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def on_message(mqttClient, userdata, msg):
|
||||
print("MQTT_LISTENER: " + msg.topic + " " + str(msg.payload))
|
||||
|
||||
print 'MQTT_LISTENER: Message Received by Device'
|
||||
print("MQTT_LISTENER: " + msg.topic + " --> " + str(msg.payload))
|
||||
|
||||
request = str(msg.payload)
|
||||
|
||||
resource = request.split(":")[0].upper()
|
||||
state = request.split(":")[1].upper()
|
||||
|
||||
print "MQTT_LISTENER: Resource- " + resource
|
||||
print "MQTT_LISTENER: State- " + state
|
||||
|
||||
if resource == "BULB":
|
||||
iotUtils.switchBulb(state=state)
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# The callback for when a PUBLISH message to the server
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def on_publish(mqttClient, stream1PlayLoad):
|
||||
mqttClient.publish(TOPIC_TO_PUBLISH_STREAM1, stream1PlayLoad)
|
||||
|
||||
|
||||
def sendSensorValue(stream1PlayLoad):
|
||||
global mqttClient
|
||||
on_publish(mqttClient, stream1PlayLoad)
|
||||
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
# The Main method of the server script
|
||||
# This method is invoked from Agent.py on a new thread
|
||||
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
def main():
|
||||
MQTT_ENDPOINT = iotUtils.MQTT_EP.split(":")
|
||||
MQTT_IP = MQTT_ENDPOINT[1].replace('//', '')
|
||||
MQTT_PORT = int(MQTT_ENDPOINT[2])
|
||||
|
||||
DEV_OWNER = iotUtils.DEVICE_OWNER
|
||||
DEV_ID = iotUtils.DEVICE_ID
|
||||
DEV_TYPE = iotUtils.DEVICE_TYPE
|
||||
TANENT_DOMAIN = iotUtils.SERVER_NAME
|
||||
global TOPIC_TO_SUBSCRIBE
|
||||
TOPIC_TO_SUBSCRIBE = TANENT_DOMAIN + "/" + DEV_TYPE + "/" + DEV_ID + "/command"
|
||||
global TOPIC_TO_PUBLISH_STREAM1
|
||||
TOPIC_TO_PUBLISH_STREAM1 = TANENT_DOMAIN + "/" + DEV_TYPE + "/" + DEV_ID + "/sensor_temp"
|
||||
|
||||
print ("MQTT_LISTENER: MQTT_ENDPOINT is " + str(MQTT_ENDPOINT))
|
||||
print ("MQTT_LISTENER: MQTT_TOPIC is " + TOPIC_TO_SUBSCRIBE)
|
||||
global mqttClient
|
||||
mqttClient.username_pw_set(iotUtils.AUTH_TOKEN, password="")
|
||||
mqttClient.on_connect = on_connect
|
||||
mqttClient.on_message = on_message
|
||||
|
||||
while True:
|
||||
try:
|
||||
print "MQTT CONNECT CALLED"
|
||||
mqttClient.connect(MQTT_IP, MQTT_PORT, 180)
|
||||
print "MQTT_LISTENER: " + time.asctime(), "Connected to MQTT Broker - %s:%s" % (
|
||||
MQTT_IP, MQTT_PORT)
|
||||
mqttClient.loop_forever()
|
||||
|
||||
except (KeyboardInterrupt, Exception) as e:
|
||||
print "MQTT_LISTENER: Exception in MQTTServerThread (either KeyboardInterrupt or Other)"
|
||||
print ("MQTT_LISTENER: " + str(e))
|
||||
|
||||
mqttClient.disconnect()
|
||||
print "MQTT_LISTENER: " + time.asctime(), "Connection to Broker closed - %s:%s" % (
|
||||
MQTT_IP, MQTT_PORT)
|
||||
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
/**
|
||||
* Copyright (c) 2017, 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.
|
||||
**/
|
||||
"""
|
||||
|
||||
global RUNNING_MODE
|
||||
RUNNING_MODE = 'N'
|
@ -0,0 +1,78 @@
|
||||
#!/usr/bin/env python
|
||||
|
||||
"""
|
||||
/**
|
||||
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
*
|
||||
* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
* Version 2.0 (the "License"); you may not use this file except
|
||||
* in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing,
|
||||
* software distributed under the License is distributed on an
|
||||
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
* KIND, either express or implied. See the License for the
|
||||
* specific language governing permissions and limitations
|
||||
* under the License.
|
||||
**/
|
||||
"""
|
||||
|
||||
import json
|
||||
import requests
|
||||
import urllib
|
||||
import iotUtils
|
||||
|
||||
applicationKey = None
|
||||
refreshToken = None
|
||||
filename = "deviceConfig.properties"
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------------------------
|
||||
#
|
||||
# Responsible for generating an access token form the Refresh token.
|
||||
# -----------------------------------------------------------------------------------------------
|
||||
class RefreshToken():
|
||||
def post(self, url, payload, appKey):
|
||||
headers = {'Authorization': 'Basic ' + appKey,
|
||||
'Content-Type': 'application/x-www-form-urlencoded'}
|
||||
baseUrl = iotUtils.HTTP_EP + url
|
||||
baseUrl = baseUrl.replace('$', '')
|
||||
response = requests.post(baseUrl, params=payload, headers=headers)
|
||||
return response
|
||||
|
||||
def read_server_conf(self):
|
||||
with open(filename, 'r') as outfile:
|
||||
conf_file = outfile.readlines()
|
||||
|
||||
return conf_file
|
||||
|
||||
def updateFile(self, response):
|
||||
newRefreshToken = response['refresh_token']
|
||||
newAccessToken = response['access_token']
|
||||
|
||||
with open(filename, 'r+') as f:
|
||||
lines = f.readlines()
|
||||
f.seek(0)
|
||||
f.truncate()
|
||||
for line in lines:
|
||||
if line.__contains__("auth-token="):
|
||||
line = "auth-token=" + newAccessToken + "\n"
|
||||
if line.__contains__("refresh-token="):
|
||||
line = "refresh-token=" + newRefreshToken + "\n"
|
||||
f.write(line)
|
||||
|
||||
def updateTokens(self, ):
|
||||
global applicationKey
|
||||
global refreshToken
|
||||
refreshToken = iotUtils.REFRESH_TOKEN
|
||||
applicationKey = iotUtils.APPLICATION_KEY
|
||||
|
||||
params = urllib.urlencode({"grant_type": "refresh_token", "refresh_token": refreshToken,
|
||||
"scope": "Enroll device"})
|
||||
data = self.post("/token", params, applicationKey)
|
||||
response = json.loads(data.content)
|
||||
self.updateFile(response)
|
||||
return response
|
@ -0,0 +1,106 @@
|
||||
#"""
|
||||
#/**
|
||||
#* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
#*
|
||||
#* WSO2 Inc. licenses this file to you under the Apache License,
|
||||
#* Version 2.0 (the "License"); you may not use this file except
|
||||
#* in compliance with the License.
|
||||
#* You may obtain a copy of the License at
|
||||
#*
|
||||
#* http://www.apache.org/licenses/LICENSE-2.0
|
||||
#*
|
||||
#* Unless required by applicable law or agreed to in writing,
|
||||
#* software distributed under the License is distributed on an
|
||||
#* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
#* KIND, either express or implied. See the License for the
|
||||
#* specific language governing permissions and limitations
|
||||
#* under the License.
|
||||
#**/
|
||||
#"""
|
||||
|
||||
#!/bin/bash
|
||||
|
||||
echo "----------------------------------------------------------------"
|
||||
echo "| WSO2 IOT Sample "
|
||||
echo "| Agent "
|
||||
echo "| ---------------- "
|
||||
echo "| ....initializing startup-script "
|
||||
echo "----------------------------------------------------------------"
|
||||
|
||||
currentDir=$PWD
|
||||
|
||||
for f in ./deviceConfig.properties; do
|
||||
## Check if the glob gets expanded to existing files.
|
||||
## If not, f here will be exactly the pattern above
|
||||
## and the exists test will evaluate to false.
|
||||
if [ -e "$f" ]; then
|
||||
echo "Configuration file found......"
|
||||
else
|
||||
echo "'deviceConfig.properties' file does not exist in current path. \nExiting installation...";
|
||||
exit;
|
||||
fi
|
||||
## This is all we needed to know, so we can break after the first iteration
|
||||
break
|
||||
done
|
||||
|
||||
#install mqtt dependency
|
||||
git clone https://github.com/eclipse/paho.mqtt.python.git
|
||||
cd ./paho.mqtt.python
|
||||
sudo python setup.py install
|
||||
|
||||
cd $currentDir
|
||||
|
||||
|
||||
read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute) > " input
|
||||
if [ $input -eq $input 2>/dev/null ]
|
||||
then
|
||||
echo "Setting data-push interval to $input seconds."
|
||||
else
|
||||
echo "Input needs to be an integer indicating the number seconds between successive data-pushes. 15 will be taken as default value"
|
||||
$input=15
|
||||
fi
|
||||
|
||||
read -p "Are you want to run this as a virtual agent? (Yes/No) " mode
|
||||
|
||||
case $mode in
|
||||
[Yy]* ) mode="Y"
|
||||
echo "----------------------------------------------------------"
|
||||
echo " This will run as a virtual agent "
|
||||
echo "----------------------------------------------------------"
|
||||
break;;
|
||||
[Nn]* ) mode="N"
|
||||
echo "----------------------------------------------------------"
|
||||
echo " This will run as a real agent "
|
||||
echo "----------------------------------------------------------"
|
||||
break;;
|
||||
* ) echo "Please answer yes or no.";
|
||||
|
||||
esac
|
||||
|
||||
cp deviceConfig.properties ./src
|
||||
|
||||
if [ "$mode" = "N" ]; then
|
||||
# Install RPi.GPIO Library for Accessing RPi GPIO Pins
|
||||
sudo apt-get install rpi.gpio
|
||||
# -----------------------------------------------------
|
||||
# Install Adafruit_Python_DHT Library for reading DHT Sensor
|
||||
git clone https://github.com/adafruit/Adafruit_Python_DHT.git
|
||||
sudo apt-get install build-essential python-dev python-openssl
|
||||
cd ./Adafruit_Python_DHT
|
||||
sudo python setup.py install
|
||||
cd ..
|
||||
# -----------------------------------------------------
|
||||
fi
|
||||
|
||||
|
||||
chmod +x ./src/agent.py
|
||||
./src/agent.py -i $input -m $mode
|
||||
|
||||
if [ $? -ne 0 ]; then
|
||||
echo "Could not start the service..."
|
||||
exit;
|
||||
fi
|
||||
|
||||
echo "--------------------------------------------------------------------------"
|
||||
echo "| Successfully Started |"
|
||||
echo "| -------------------------- |"
|
@ -0,0 +1,18 @@
|
||||
#<!--
|
||||
# ~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
# ~
|
||||
# ~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
# ~ Version 2.0 (the "License"); you may not use this file except
|
||||
# ~ in compliance with the License.
|
||||
# ~ You may obtain a copy of the License at
|
||||
# ~
|
||||
# ~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
# ~
|
||||
# ~ Unless required by applicable law or agreed to in writing,
|
||||
# ~ software distributed under the License is distributed on an
|
||||
# ~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
# ~ KIND, either express or implied. See the License for the
|
||||
# ~ specific language governing permissions and limitations
|
||||
# ~ under the License.
|
||||
# -->
|
||||
custom=true
|
@ -0,0 +1,47 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
|
||||
<datasources-configuration>
|
||||
<providers>
|
||||
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
|
||||
</providers>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<name>sampledeviceDM_DB</name>
|
||||
<description>The datasource used for the this device type</description>
|
||||
<jndiConfig>
|
||||
<name>jdbc/sampledeviceDM_DB</name>
|
||||
</jndiConfig>
|
||||
<definition type="RDBMS">
|
||||
<configuration>
|
||||
<url>jdbc:h2:repository/database/sampledeviceDM_DB;DB_CLOSE_ON_EXIT=FALSE
|
||||
</url>
|
||||
<username>wso2carbon</username>
|
||||
<password>wso2carbon</password>
|
||||
<driverClassName>org.h2.Driver</driverClassName>
|
||||
<maxActive>50</maxActive>
|
||||
<maxWait>60000</maxWait>
|
||||
<testOnBorrow>true</testOnBorrow>
|
||||
<validationQuery>SELECT 1</validationQuery>
|
||||
<validationInterval>30000</validationInterval>
|
||||
</configuration>
|
||||
</definition>
|
||||
</datasource>
|
||||
</datasources>
|
||||
</datasources-configuration>
|
@ -0,0 +1,11 @@
|
||||
|
||||
-- -----------------------------------------------------
|
||||
-- Agent Database
|
||||
-- -----------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `sampledevice_DEVICE` (
|
||||
`sampledevice_DEVICE_ID` VARCHAR(45) NOT NULL ,
|
||||
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`sampledevice_DEVICE_ID`) );
|
||||
|
||||
|
||||
|
@ -0,0 +1,9 @@
|
||||
|
||||
-- -----------------------------------------------------
|
||||
-- Table `sampledevice_DEVICE`
|
||||
-- -----------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS sampledevice_DEVICE (
|
||||
sampledevice_DEVICE_ID VARCHAR(45) NOT NULL ,
|
||||
DEVICE_NAME VARCHAR(100) NULL DEFAULT NULL,
|
||||
PRIMARY KEY (sampledevice_DEVICE_ID) );
|
||||
|
@ -0,0 +1,10 @@
|
||||
|
||||
CREATE TABLE IF NOT EXISTS `sampledevice_DEVICE` (
|
||||
`sampledevice_DEVICE_ID` VARCHAR(45) NOT NULL ,
|
||||
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
|
||||
PRIMARY KEY (`sampledevice_DEVICE_ID`) )
|
||||
ENGINE = InnoDB;
|
||||
|
||||
|
||||
|
||||
|
@ -0,0 +1,9 @@
|
||||
|
||||
-- -----------------------------------------------------
|
||||
-- Table `sampledevice_DEVICE`
|
||||
-- -----------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS sampledevice_DEVICE (
|
||||
sampledevice_DEVICE_ID VARCHAR(45) NOT NULL ,
|
||||
DEVICE_NAME VARCHAR(100) NULL DEFAULT NULL,
|
||||
PRIMARY KEY (sampledevice_DEVICE_ID) );
|
||||
|
@ -0,0 +1,48 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
|
||||
<!--
|
||||
~ Copyright (c) 2017, 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.
|
||||
-->
|
||||
<DeviceTypeConfiguration name="sampledevice">
|
||||
<Features>
|
||||
<Feature code="bulb">
|
||||
<Name>Control Bulb</Name>
|
||||
<Description>Control Bulb on sampledevice</Description>
|
||||
<Operation context="/sampledevice/device/{deviceId}/bulb" method="POST">
|
||||
<QueryParameters>
|
||||
<Parameter>state</Parameter>
|
||||
</QueryParameters>
|
||||
</Operation>
|
||||
</Feature>
|
||||
</Features>
|
||||
|
||||
<ProvisioningConfig>
|
||||
<SharedWithAllTenants>true</SharedWithAllTenants>
|
||||
</ProvisioningConfig>
|
||||
|
||||
<PushNotificationProviderConfig type="MQTT">
|
||||
<FileBasedProperties>true</FileBasedProperties>
|
||||
</PushNotificationProviderConfig>
|
||||
|
||||
<License>
|
||||
<Language>en_US</Language>
|
||||
<Version>1.0.0</Version>
|
||||
<Text>This is license text</Text>
|
||||
</License>
|
||||
|
||||
</DeviceTypeConfiguration>
|
||||
|
@ -0,0 +1,30 @@
|
||||
instructions.configure = \
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/deployment/server/webapps/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/webapps/,target:${installFolder}/../../../repository/deployment/server/webapps/,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../resources/sketches/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../resources/sketches/sampledevice/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/agent/,target:${installFolder}/../../../repository/resources/sketches/sampledevice/,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/sampledevice,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/datasources/,target:${installFolder}/../../../conf/datasources/,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/deployment/server/jaggeryapps/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/jaggeryapps/,target:${installFolder}/../../../repository/deployment/server/jaggeryapps/,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/database/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/database/,target:${installFolder}/../../../repository/database/,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/deployment/server/carbonapps/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/carbonapps/,target:${installFolder}/../../../repository/deployment/server/carbonapps/,overwrite:true);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/deployment/server/devicetypes/);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.sampledevice_${feature.version}/devicetypes/,target:${installFolder}/../../../repository/deployment/server/devicetypes/,overwrite:true);\
|
||||
|
||||
|
||||
|
||||
instructions.unconfigure = \
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/webapps/sampledevice.war);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/webapps/sampledevice);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../dbscripts/cdm/plugins/sampledevice);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../conf/datasources/sampledevice-datasources.xml);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/database/sampledeviceDM_DB.h2.db);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/devicetypes/sampledevice.xml);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.sampledevice.device-view);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.sampledevice.type-view);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.sampledevice.realtime.analytics-view);\
|
||||
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/jaggeryapps/devicemgt/app/units/cdmf.unit.device.type.sampledevice.analytics-view);\
|
@ -0,0 +1,35 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<relativePath>../pom.xml</relativePath>
|
||||
</parent>
|
||||
<artifactId>sampledevice-feature</artifactId>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<packaging>pom</packaging>
|
||||
<version>1.0.0</version>
|
||||
<modules>
|
||||
<module>feature</module>
|
||||
</modules>
|
||||
</project>
|
@ -0,0 +1,415 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!--
|
||||
~ Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
|
||||
~
|
||||
~ WSO2 Inc. licenses this file to you under the Apache License,
|
||||
~ Version 2.0 (the "License"); you may not use this file except
|
||||
~ in compliance with the License.
|
||||
~ You may obtain a copy of the License at
|
||||
~
|
||||
~ http://www.apache.org/licenses/LICENSE-2.0
|
||||
~
|
||||
~ Unless required by applicable law or agreed to in writing,
|
||||
~ software distributed under the License is distributed on an
|
||||
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
||||
~ KIND, either express or implied. See the License for the
|
||||
~ specific language governing permissions and limitations
|
||||
~ under the License.
|
||||
-->
|
||||
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>org.wso2</groupId>
|
||||
<artifactId>wso2</artifactId>
|
||||
<version>1</version>
|
||||
</parent>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>sampledevice</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>pom</packaging>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<url>http://wso2.com</url>
|
||||
<modules>
|
||||
<module>component</module>
|
||||
<module>feature</module>
|
||||
</modules>
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi</artifactId>
|
||||
<version>${eclipse.osgi.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.equinox</groupId>
|
||||
<artifactId>org.eclipse.equinox.common</artifactId>
|
||||
<version>${eclipse.equinox.common.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.osgi</groupId>
|
||||
<artifactId>org.eclipse.osgi.services</artifactId>
|
||||
<version>3.3.100.v20120522-1822</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.logging</artifactId>
|
||||
<version>${carbon.kernel.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.apache.log4j.wso2</groupId>
|
||||
<artifactId>log4j</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-logging</groupId>
|
||||
<artifactId>commons-logging</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.bootstrap</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<!-- CXF dependencies -->
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxws</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.cxf</groupId>
|
||||
<artifactId>cxf-rt-transports-http</artifactId>
|
||||
<version>${cxf.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.eclipse.paho</groupId>
|
||||
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
|
||||
<version>${paho.mqtt.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-core-asl</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.codehaus.jackson</groupId>
|
||||
<artifactId>jackson-jaxrs</artifactId>
|
||||
<version>${jackson.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax</groupId>
|
||||
<artifactId>javaee-web-api</artifactId>
|
||||
<version>6.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>javax.ws.rs</groupId>
|
||||
<artifactId>jsr311-api</artifactId>
|
||||
<version>${javax.ws.rs.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.apache.httpcomponents</groupId>
|
||||
<artifactId>httpasyncclient</artifactId>
|
||||
<version>${org.apache.httpcomponents.version}</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>${project-base-package}.plugin</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.ndatasource.core</artifactId>
|
||||
<version>${carbon.kernel.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
|
||||
<version>${carbon.device.mgt.plugin.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.api</artifactId>
|
||||
<version>${carbon.analytics.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.datasource.commons</artifactId>
|
||||
<version>${carbon.analytics.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.dataservice.commons</artifactId>
|
||||
<version>${carbon.analytics.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics</groupId>
|
||||
<artifactId>org.wso2.carbon.analytics.dataservice.core</artifactId>
|
||||
<version>${carbon.analytics.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
<version>${commons-httpclient.orbit.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.utils</artifactId>
|
||||
<version>${carbon.kernel.version}</version>
|
||||
<exclusions>
|
||||
<exclusion>
|
||||
<groupId>org.bouncycastle.wso2</groupId>
|
||||
<artifactId>bcprov-jdk15on</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.user.api</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.queuing</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.base</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.axis2.wso2</groupId>
|
||||
<artifactId>axis2</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>jaxen</groupId>
|
||||
<artifactId>jaxen</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-fileupload.wso2</groupId>
|
||||
<artifactId>commons-fileupload</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.apache.ant.wso2</groupId>
|
||||
<artifactId>ant</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>commons-httpclient.wso2</groupId>
|
||||
<artifactId>commons-httpclient</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.eclipse.equinox</groupId>
|
||||
<artifactId>javax.servlet</artifactId>
|
||||
</exclusion>
|
||||
<exclusion>
|
||||
<groupId>org.wso2.carbon</groupId>
|
||||
<artifactId>org.wso2.carbon.registry.api</artifactId>
|
||||
</exclusion>
|
||||
</exclusions>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smack</artifactId>
|
||||
<version>${smack.wso2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.igniterealtime.smack.wso2</groupId>
|
||||
<artifactId>smackx</artifactId>
|
||||
<version>${smackx.wso2.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.json.wso2</groupId>
|
||||
<artifactId>json</artifactId>
|
||||
<version>${commons-json.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.h2database.wso2</groupId>
|
||||
<artifactId>h2-database-engine</artifactId>
|
||||
<version>1.2.140.wso2v3</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.analytics-common</groupId>
|
||||
<artifactId>org.wso2.carbon.event.output.adapter.core</artifactId>
|
||||
<version>${carbon.analytics.common.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.wso2.carbon.devicemgt</groupId>
|
||||
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
|
||||
<version>${carbon.device.mgt.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>commons-codec.wso2</groupId>
|
||||
<artifactId>commons-codec</artifactId>
|
||||
<version>${commons-codec.wso2.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<pluginRepositories>
|
||||
<pluginRepository>
|
||||
<id>wso2.releases</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
|
||||
<pluginRepository>
|
||||
<id>wso2.snapshots</id>
|
||||
<name>Apache Snapshot Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/snapshots/</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
</snapshots>
|
||||
<releases>
|
||||
<enabled>false</enabled>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
<pluginRepository>
|
||||
<id>wso2-nexus</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</pluginRepository>
|
||||
</pluginRepositories>
|
||||
|
||||
<repositories>
|
||||
<!-- Before adding ANYTHING in here, please start a discussion on the dev list.
|
||||
Ideally the Axis2 build should only use Maven central (which is available
|
||||
by default) and nothing else. We had troubles with other repositories in
|
||||
the past. Therefore configuring additional repositories here should be
|
||||
considered very carefully. -->
|
||||
<repository>
|
||||
<id>wso2-nexus</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</repository>
|
||||
<repository>
|
||||
<id>wso2.releases</id>
|
||||
<name>WSO2 internal Repository</name>
|
||||
<url>http://maven.wso2.org/nexus/content/repositories/releases/</url>
|
||||
<releases>
|
||||
<enabled>true</enabled>
|
||||
<updatePolicy>daily</updatePolicy>
|
||||
<checksumPolicy>ignore</checksumPolicy>
|
||||
</releases>
|
||||
</repository>
|
||||
</repositories>
|
||||
<properties>
|
||||
<carbon.kernel.version>4.4.11</carbon.kernel.version>
|
||||
|
||||
<!-- Carbon Device Management -->
|
||||
<carbon.device.mgt.version>3.0.37</carbon.device.mgt.version>
|
||||
<carbon.device.mgt.plugin.version>4.0.34</carbon.device.mgt.plugin.version>
|
||||
|
||||
|
||||
<project-base-package>${project.groupId}.sampledevice</project-base-package>
|
||||
|
||||
<maven.compiler.source>1.7</maven.compiler.source>
|
||||
<maven.compiler.target>1.7</maven.compiler.target>
|
||||
<maven-clean-plugin.version>2.4.1</maven-clean-plugin.version>
|
||||
<maven-compiler-plugin.version>2.3.2</maven-compiler-plugin.version>
|
||||
<maven-war-plugin.version>2.6</maven-war-plugin.version>
|
||||
<maven-antrun-plugin.version>1.8</maven-antrun-plugin.version>
|
||||
<maven-scr-plugin.version>1.7.2</maven-scr-plugin.version>
|
||||
<maven-assembly-plugin.version>2.5.5</maven-assembly-plugin.version>
|
||||
|
||||
<paho.mqtt.version>1.0.2</paho.mqtt.version>
|
||||
<commons-json.version>3.0.0.wso2v1</commons-json.version>
|
||||
<eclipse.osgi.version>3.8.1.v20120830-144521</eclipse.osgi.version>
|
||||
<javax.ws.rs.version>1.1.1</javax.ws.rs.version>
|
||||
|
||||
<!--XMPP/MQTT Version-->
|
||||
<smack.wso2.version>3.0.4.wso2v1</smack.wso2.version>
|
||||
<smackx.wso2.version>3.0.4.wso2v1</smackx.wso2.version>
|
||||
<cxf.version>2.6.1</cxf.version>
|
||||
<jackson.version>1.9.0</jackson.version>
|
||||
<commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.version>
|
||||
<commons-json.version>3.0.0.wso2v1</commons-json.version>
|
||||
<eclipse.equinox.common.version>3.6.100.v20120522-1841</eclipse.equinox.common.version>
|
||||
<analytics.version>1.3.0</analytics.version>
|
||||
<carbon.analytics.version>1.3.0</carbon.analytics.version>
|
||||
<org.apache.felix.version>1.4.0</org.apache.felix.version>
|
||||
<commons-codec.wso2.version>1.4.0.wso2v1</commons-codec.wso2.version>
|
||||
<carbon.analytics.common.version>5.1.5</carbon.analytics.common.version>
|
||||
<carbon-p2-plugin.version>1.5.3</carbon-p2-plugin.version>
|
||||
</properties>
|
||||
</project>
|
Loading…
Reference in new issue