diff --git a/modules/samples/pom.xml b/modules/samples/pom.xml index c379481d..52091079 100644 --- a/modules/samples/pom.xml +++ b/modules/samples/pom.xml @@ -42,6 +42,7 @@ digital_display/src raspberrypi/src sensebot/src + virtual_firealarm/src diff --git a/modules/samples/sample_pom.xml b/modules/samples/sample_pom.xml index 6c1a9ce0..76e1dc33 100644 --- a/modules/samples/sample_pom.xml +++ b/modules/samples/sample_pom.xml @@ -42,6 +42,7 @@ digital_display/src raspberrypi/src sensebot/src + virtual_firealarm/src diff --git a/modules/samples/virtual_firealarm/artifact/deviceType.json b/modules/samples/virtual_firealarm/artifact/deviceType.json new file mode 100644 index 00000000..a9f467af --- /dev/null +++ b/modules/samples/virtual_firealarm/artifact/deviceType.json @@ -0,0 +1,25 @@ +{ + "name": "virtual_firealarm", + "tags": "WSO2, IoT, Raspberry, Fire Alarm, Virtual", + "rate": 3, + "attributes": { + "overview_status": "PUBLISHED", + "overview_provider":"admin", + "overview_version":"1.0.0", + "overview_name":"virtual_firealarm", + "overview_url":"http://www.google.lk", + "setupGuide_guideImage":"undefined", + "overview_actionLabel":"Download", + "sketches_Sketches":"virtual_firealarm", + "ingredients_ingredients":[ + "Virtual Agent that simulates an actual firealarm" + ], + "overview_description":"Download our Virtual Agent and try-it out for close to real simulation of the FireAlarm Device-Type", + "setupGuide_description":"sfd", + "quickStartupSteps_stepDescription":["Download the Virtual Agent","Run the 'startservice.sh' script","Provide the push-interval and network-interface"], + "quickStartupSteps_stepLabel":["1","2","3"], + "images_thumbnail":"virtual_firealarm/virtual_firealarm_thumbnail.png", + "images_banner":"virtual_firealarm/virtual_firealarm_banner.png", + "overview_thumbnail": "images_thumbnail" + } +} \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/artifact/virtual_firealarm_banner.png b/modules/samples/virtual_firealarm/artifact/virtual_firealarm_banner.png new file mode 100644 index 00000000..aaf16925 Binary files /dev/null and b/modules/samples/virtual_firealarm/artifact/virtual_firealarm_banner.png differ diff --git a/modules/samples/virtual_firealarm/artifact/virtual_firealarm_thumbnail.png b/modules/samples/virtual_firealarm/artifact/virtual_firealarm_thumbnail.png new file mode 100644 index 00000000..bad3b1b6 Binary files /dev/null and b/modules/samples/virtual_firealarm/artifact/virtual_firealarm_thumbnail.png differ diff --git a/modules/samples/virtual_firealarm/build.xml b/modules/samples/virtual_firealarm/build.xml new file mode 100644 index 00000000..594a20d5 --- /dev/null +++ b/modules/samples/virtual_firealarm/build.xml @@ -0,0 +1,95 @@ + + + + + + + + + + + + + + + + + + + + + + + + jdbc/${data_source} + virtual_firealarm + + ]]> + + + + + + ${data_source} + The datasource used for the Virtual-Firealarm database + + jdbc/${data_source} + + + + jdbc:h2:repository/database/${data_source};DB_CLOSE_ON_EXIT=FALSE + wso2carbon + wso2carbon + org.h2.Driver + 50 + 60000 + true + SELECT 1 + 30000 + + + + ]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/dbscripts/h2_virtual_firealarm.sql b/modules/samples/virtual_firealarm/dbscripts/h2_virtual_firealarm.sql new file mode 100644 index 00000000..340ba6a7 --- /dev/null +++ b/modules/samples/virtual_firealarm/dbscripts/h2_virtual_firealarm.sql @@ -0,0 +1,11 @@ + +-- ----------------------------------------------------- +-- Table `FIREALARM_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `VIRTUAL_FIREALARM_DEVICE` ( + `VIRTUAL_FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`VIRTUAL_FIREALARM_DEVICE_ID`) ); + + + diff --git a/modules/samples/virtual_firealarm/dbscripts/mysql_virtual_firealarm.sql b/modules/samples/virtual_firealarm/dbscripts/mysql_virtual_firealarm.sql new file mode 100644 index 00000000..432ecbb0 --- /dev/null +++ b/modules/samples/virtual_firealarm/dbscripts/mysql_virtual_firealarm.sql @@ -0,0 +1,12 @@ +-- ----------------------------------------------------- +-- Table `FIREALARM_DEVICE` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS `VIRTUAL_FIREALARM_DEVICE` ( + `VIRTUAL_FIREALARM_DEVICE_ID` VARCHAR(45) NOT NULL , + `DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL, + PRIMARY KEY (`VIRTUAL_FIREALARM_DEVICE_ID`) ) +ENGINE = InnoDB; + + + + diff --git a/modules/samples/virtual_firealarm/page/virtual_firealarm.hbs b/modules/samples/virtual_firealarm/page/virtual_firealarm.hbs new file mode 100644 index 00000000..30fb2abd --- /dev/null +++ b/modules/samples/virtual_firealarm/page/virtual_firealarm.hbs @@ -0,0 +1,8 @@ +{{layout "fluid"}} +{{#zone "title"}} + WSO2 IoT Server | Virtual FireAlarm +{{/zone}} +{{#zone "body"}} + {{unit "appbar" link="dashboard" enableBack="true" title="Virtual FireAlarm"}} + {{unit "virtual_firealarm"}} +{{/zone}} \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/sketch/deviceConfig.properties b/modules/samples/virtual_firealarm/sketch/deviceConfig.properties new file mode 100644 index 00000000..4af8602c --- /dev/null +++ b/modules/samples/virtual_firealarm/sketch/deviceConfig.properties @@ -0,0 +1,32 @@ +# +# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# + +#[Device-Configurations] +owner=${DEVICE_OWNER} +deviceId=${DEVICE_ID} +server-ep=${SERVER_EP} +service-ep=${SERVICE_EP} +apim-ep=${APIM_EP} +mqtt-ep=${MQTT_EP} +xmpp-ep=${XMPP_EP} +auth-method=token +auth-token=${DEVICE_TOKEN} +refresh-token=${DEVICE_REFRESH_TOKEN} +network-interface=wlan0 +push-interval=15 + + diff --git a/modules/samples/virtual_firealarm/sketch/firealarm-virtual-agent-1.0-SNAPSHOT-jar-with-dependencies.jar.zip b/modules/samples/virtual_firealarm/sketch/firealarm-virtual-agent-1.0-SNAPSHOT-jar-with-dependencies.jar.zip new file mode 100644 index 00000000..f67e38e0 Binary files /dev/null and b/modules/samples/virtual_firealarm/sketch/firealarm-virtual-agent-1.0-SNAPSHOT-jar-with-dependencies.jar.zip differ diff --git a/modules/samples/virtual_firealarm/sketch/sketch.properties b/modules/samples/virtual_firealarm/sketch/sketch.properties new file mode 100644 index 00000000..2a2a2f91 --- /dev/null +++ b/modules/samples/virtual_firealarm/sketch/sketch.properties @@ -0,0 +1,2 @@ +templates=deviceConfig.properties +zipfilename=FireAlarmAgent.zip diff --git a/modules/samples/virtual_firealarm/sketch/startservice.sh b/modules/samples/virtual_firealarm/sketch/startservice.sh new file mode 100644 index 00000000..b324e9d0 --- /dev/null +++ b/modules/samples/virtual_firealarm/sketch/startservice.sh @@ -0,0 +1,201 @@ +#!/bin/bash + +echo "----------------------------------------------------------------" +echo "| WSO2 IOT Sample " +echo "| Virtual RaspiAlarm " +echo "| ---------------- " +echo "| ....initializing startup-script " +echo "----------------------------------------------------------------" + + +unzip firealarm-virtual-agent-1.0-SNAPSHOT-jar-with-dependencies.jar.zip + +while true; do + read -p "What is the network-interface of your PC that the Agent should use (find from ifconfig. ex: wlan0,en0,eth0..) > " interface + + if [ $interface -eq $interface 2>/dev/null ] + then + echo "Setting the network-interface to " $interface + sed s/^network-interface=.*/network-interface=$interface/ deviceConfig.properties > myTmp + mv -f myTmp deviceConfig.properties + rm myTmp + break; + else + echo "Please select an appropriate interface from those which are listed on ifconfig." + fi +done + +while true; do + read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-IoT-Server (ex: '60' indicates 1 minute) > " interval + + if [ $interval -eq $interval 2>/dev/null ] + then + echo "Setting data-push interval to " $interval " seconds." + sed s/^push-interval=.*/push-interval=$interval/ deviceConfig.properties > myTmp + mv -f myTmp deviceConfig.properties + rm myTmp + break; + else + echo "Input needs to be an integer indicating the number seconds between successive data-pushes." + fi +done + + +java -jar firealarm-virtual-agent-1.0-SNAPSHOT-jar-with-dependencies.jar + + +#while true; do +# read -p "Do you wish to run 'apt-get update' and continue? [Yes/No] " yn +# case $yn in +# [Yy]* ) sudo apt-get update; +# break;; +# [Nn]* ) echo "Continuing without apt-get update..."; +# break;; +# * ) echo "Please answer yes or no."; +# esac +#done +# +#if [ $? -ne 0 ]; then +# echo "apt-get update failed.... Some dependencies may not get installed" +# echo "If an already installed version of the package exists, try running:" +# echo "----------------------------------------------------------------" +# echo "sudo -i" +# echo "cd /var/lib/dpkg/info" +# echo "rm -rf wso2-raspi-alarm*" +# echo "dpkg --remove --force-remove-reinstreq wso2-raspi-alarm" +# echo "exit" +# echo "----------------------------------------------------------------" +# echo "Retry Installation...." +# break; +#fi +# +#echo "Installing 'gdebi' package..." +#sudo apt-get install gdebi # installation of gdebi +# +# +#if [ $? -ne 0 ]; then +# echo "gdebi installation failed.... dependencies will not be installed without gdebi" +# read -p "Do you wish to continue without gdebi? [Yes/No] " yn +# case $yn in +# [Yy]* ) echo "Continueing without gdebi.....";; +# [Nn]* ) echo "Try to resolve errors and re-run the script."; +# exit;; +# * ) exit;; +# esac +#fi +# +# +#for f in ./wso2-raspi-alarm_1.0_armhf.deb; do +# ## Check if the glob gets expanded to existing files. +# ## If not, f here will be exactly the pattern above +# ## and the exists test will evaluate to false. +# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit; +# if [ -e "$f" ]; then +# echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing now...." +# else +# echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path. \nExiting installation..."; +# exit; +# fi +# ## This is all we needed to know, so we can break after the first iteration +# break +#done +# +#echo "Installing the 'wso2-raspi-alarm deb package'" +#sudo gdebi wso2-raspi-alarm_1.0_armhf.deb +# +#if [ $? -ne 0 ]; then +# echo "Installation Failed...." +# exit; +#fi + +#sudo killall -9 python +# +#for f in ./RaspberryAgent.zip; do +# ## Check if the glob gets expanded to existing files. +# ## If not, f here will be exactly the pattern above +# ## and the exists test will evaluate to false. +# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit; +# if [ -e "$f" ]; then +# echo "Agent files found......" +# sudo rm -rf /usr/local/src/RaspberryAgent +# sudo unzip RaspberryAgent.zip -d /usr/local/src/ +# else +# echo "'RaspberryAgent.zip' file does not exist in current path. \nInstalling without upgrading agent..."; +# fi +# ## This is all we needed to know, so we can break after the first iteration +# break +#done +# +#for f in /usr/local/src/RaspberryAgent/rc.local; do +# ## Check if the glob gets expanded to existing files. +# ## If not, f here will be exactly the pattern above +# ## and the exists test will evaluate to false. +# if [ -e "$f" ]; then +# echo "Copying boot script" +# sudo mv /usr/local/src/RaspberryAgent/rc.local /etc/rc.local +# sudo chmod +x /etc/rc.local +# else +# echo "Unable to set agent statup on boot"; +# fi +# ## This is all we needed to know, so we can break after the first iteration +# break +#done +# +#for f in ./deviceConfigs.cfg; do +# ## Check if the glob gets expanded to existing files. +# ## If not, f here will be exactly the pattern above +# ## and the exists test will evaluate to false. +# if [ -e "$f" ]; then +# echo "Configuration file found......" +# else +# echo "'deviceConfigs.cfg' file does not exist in current path. \nExiting installation..."; +# exit; +# fi +# ## This is all we needed to know, so we can break after the first iteration +# break +#done +# +#echo "Altering Configuration file" +#sed -i 's|[/,]||g' deviceConfigs.cfg +# +#echo "Copying configurations file to /usr/local/src/RaspberryAgent" +#sudo cp ./deviceConfigs.cfg /usr/local/src/RaspberryAgent/ +# +#if [ $? -ne 0 ]; then +# echo "Copying configuration file failed...." +# exit; +#fi +# +#while true; do +# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute) > " input +# +# if [ $input -eq $input 2>/dev/null ] +# then +# echo "Setting data-push interval to $input seconds." +# echo $input > /usr/local/src/RaspberryAgent/time-interval +# break; +# else +# echo "Input needs to be an integer indicating the number seconds between successive data-pushes." +# fi +#done +# +#cd /usr/local/src/RaspberryAgent/ +#sudo chmod +x RaspberryStats.py +#sudo nohup ./RaspberryStats.py -i $input + + + + + + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm + org.wso2.carbon.device.mgt.iot.server.sample + ${carbon.iot.device.mgt.version} + ../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl + ${carbon.iot.device.mgt.version} + bundle + WSO2 Carbon - Virtual Firealarm Management Impl + WSO2 Carbon - Virtual Firealarm Management and Control Implementation + http://wso2.org + + + + + org.apache.felix + maven-scr-plugin + + + maven-compiler-plugin + + 1.7 + 1.7 + + 2.3.2 + + + org.apache.felix + maven-bundle-plugin + 1.4.0 + true + + + ${project.artifactId} + ${project.artifactId} + ${carbon.iot.device.mgt.version} + IoT Server Impl Bundle + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.internal + + org.osgi.framework, + org.osgi.service.component, + org.apache.commons.logging, + javax.xml.bind.*, + javax.naming, + javax.sql, + javax.xml.bind.annotation.*, + javax.xml.parsers, + javax.net, + javax.net.ssl, + org.w3c.dom, + org.wso2.carbon.device.mgt.common.*, + org.wso2.carbon.device.mgt.common, + org.wso2.carbon.context.*, + org.wso2.carbon.ndatasource.core, + org.wso2.carbon.device.mgt.iot.common.*, + + + + !org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.internal, + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.* + + + + + + + + + + org.eclipse.osgi + org.eclipse.osgi + + + org.eclipse.osgi + org.eclipse.osgi.services + + + + org.wso2.carbon + org.wso2.carbon.logging + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon + org.wso2.carbon.ndatasource.core + + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + + + + + + \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/constants/VirtualFireAlarmConstants.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/constants/VirtualFireAlarmConstants.java new file mode 100644 index 00000000..b7f0c43e --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/constants/VirtualFireAlarmConstants.java @@ -0,0 +1,25 @@ +/* +* Copyright (c) 2014, 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.device.mgt.iot.sample.virtual.firealarm.plugin.constants; + +public class VirtualFireAlarmConstants { + public final static String DEVICE_TYPE = "virtual_firealarm"; + public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME"; + public final static String DEVICE_PLUGIN_DEVICE_ID = "VIRTUAL_FIREALARM_DEVICE_ID"; + public final static String STATE_ON = "ON"; + public final static String STATE_OFF = "OFF"; +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/VirtualFireAlarmManager.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/VirtualFireAlarmManager.java new file mode 100644 index 00000000..4defa1b7 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/VirtualFireAlarmManager.java @@ -0,0 +1,279 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.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.TenantConfiguration; +import org.wso2.carbon.device.mgt.common.license.mgt.License; +import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.util.IotDeviceManagementUtil; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.dao.VirtualFireAlarmDAO; + +import java.util.ArrayList; +import java.util.List; + + +/** + * This represents the FireAlarm implementation of DeviceManagerService. + */ +public class VirtualFireAlarmManager implements DeviceManager { + + private static final IotDeviceManagementDAOFactory iotDeviceManagementDAOFactory = new VirtualFireAlarmDAO(); + private static final Log log = LogFactory.getLog(VirtualFireAlarmManager.class); + + + + @Override + public FeatureManager getFeatureManager() { + return null; + } + + @Override + public boolean saveConfiguration(TenantConfiguration tenantConfiguration) + throws DeviceManagementException { + //TODO implement this + return false; + } + + @Override + public TenantConfiguration getConfiguration() throws DeviceManagementException { + //TODO implement this + return null; + } + + @Override + public boolean enrollDevice(Device device) throws DeviceManagementException { + boolean status; + IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device); + try { + if (log.isDebugEnabled()) { + log.debug("Enrolling a new Virtual Firealarm device : " + device.getDeviceIdentifier()); + } + VirtualFireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO().addIotDevice( + iotDevice); + VirtualFireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + VirtualFireAlarmDAO.rollbackTransaction(); + } catch (IotDeviceManagementDAOException iotDAOEx) { + String msg = "Error occurred while roll back the device enrol transaction :" + device.toString(); + log.warn(msg, iotDAOEx); + } + String msg = "Error while enrolling the Virtual Firealarm device : " + device.getDeviceIdentifier(); + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public boolean modifyEnrollment(Device device) throws DeviceManagementException { + boolean status; + IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device); + try { + if (log.isDebugEnabled()) { + log.debug("Modifying the Virtual Firealarm device enrollment data"); + } + VirtualFireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + VirtualFireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + VirtualFireAlarmDAO.rollbackTransaction(); + } catch (IotDeviceManagementDAOException 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 Virtual Firealarm 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 Virtual Firealarm device : " + deviceId); + } + VirtualFireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .deleteIotDevice(deviceId.getId()); + VirtualFireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + VirtualFireAlarmDAO.rollbackTransaction(); + } catch (IotDeviceManagementDAOException 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 Virtual Firealarm 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 Virtual Firealarm device : " + deviceId.getId()); + } + IotDevice iotDevice = + iotDeviceManagementDAOFactory.getIotDeviceDAO().getIotDevice( + deviceId.getId()); + if (iotDevice != null) { + isEnrolled = true; + } + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while checking the enrollment status of Virtual Firealarm 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 Virtual Firealarm device : " + deviceId.getId()); + } + IotDevice iotDevice = iotDeviceManagementDAOFactory.getIotDeviceDAO(). + getIotDevice(deviceId.getId()); + device = IotDeviceManagementUtil.convertToDevice(iotDevice); + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching the Virtual Firealarm 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 updateDeviceInfo(DeviceIdentifier deviceIdentifier, Device device) throws DeviceManagementException { + boolean status; + IotDevice iotDevice = IotDeviceManagementUtil.convertToIotDevice(device); + try { + if (log.isDebugEnabled()) { + log.debug( + "updating the details of Virtual Firealarm device : " + deviceIdentifier); + } + VirtualFireAlarmDAO.beginTransaction(); + status = iotDeviceManagementDAOFactory.getIotDeviceDAO() + .updateIotDevice(iotDevice); + VirtualFireAlarmDAO.commitTransaction(); + } catch (IotDeviceManagementDAOException e) { + try { + VirtualFireAlarmDAO.rollbackTransaction(); + } catch (IotDeviceManagementDAOException 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 Virtual Firealarm device : " + deviceIdentifier; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return status; + } + + @Override + public List getAllDevices() throws DeviceManagementException { + List devices = null; + try { + if (log.isDebugEnabled()) { + log.debug("Fetching the details of all Virtual Firealarm devices"); + } + List iotDevices = + iotDeviceManagementDAOFactory.getIotDeviceDAO().getAllIotDevices(); + if (iotDevices != null) { + devices = new ArrayList(); + for (IotDevice iotDevice : iotDevices) { + devices.add(IotDeviceManagementUtil.convertToDevice(iotDevice)); + } + } + } catch (IotDeviceManagementDAOException e) { + String msg = "Error while fetching all Virtual Firealarm devices."; + log.error(msg, e); + throw new DeviceManagementException(msg, e); + } + return devices; + } + + + +} \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/VirtualFireAlarmManagerService.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/VirtualFireAlarmManagerService.java new file mode 100644 index 00000000..49dcf8f6 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/VirtualFireAlarmManagerService.java @@ -0,0 +1,77 @@ +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl; + +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.app.mgt.Application; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException; +import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager; +import org.wso2.carbon.device.mgt.common.operation.mgt.Operation; +import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants + .VirtualFireAlarmConstants; + +import java.util.List; + +public class VirtualFireAlarmManagerService implements DeviceManagementService{ + private DeviceManager deviceManager; + @Override + public String getType() { + return VirtualFireAlarmConstants.DEVICE_TYPE; + } + + + @Override + public String getProviderTenantDomain() { + return "carbon.super"; + } + + @Override + public boolean isSharedWithAllTenants() { + return true; + } + + @Override + public String[] getSharedTenantsDomain() { + return new String[0]; + } + + @Override + public void init() throws DeviceManagementException { + this.deviceManager=new VirtualFireAlarmManager(); + } + + @Override + public DeviceManager getDeviceManager() { + return deviceManager; + } + + @Override + public ApplicationManager getApplicationManager() { + return null; + } + + @Override + public Application[] getApplications(String domain, int pageNumber, int size) + throws ApplicationManagementException { + return new Application[0]; + } + + @Override + public void updateApplicationStatus(DeviceIdentifier deviceId, Application application, + String status) throws ApplicationManagementException { + + } + + @Override + public String getApplicationStatus(DeviceIdentifier deviceId, Application application) + throws ApplicationManagementException { + return null; + } + + @Override + public void installApplication(Operation operation, List deviceIdentifiers) + throws ApplicationManagementException { + + } +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/dao/VirtualFireAlarmDAO.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/dao/VirtualFireAlarmDAO.java new file mode 100644 index 00000000..e65f79df --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/dao/VirtualFireAlarmDAO.java @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. +*/ + +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.dao; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao + .IotDeviceManagementDAOFactoryInterface; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants + .VirtualFireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.dao.impl.VirtualFireAlarmDeviceDAOImpl; + + + +import javax.sql.DataSource; +import java.sql.Connection; +import java.sql.SQLException; + +public class VirtualFireAlarmDAO extends IotDeviceManagementDAOFactory implements IotDeviceManagementDAOFactoryInterface { + + private static final Log log = LogFactory.getLog(VirtualFireAlarmDAO.class); + static DataSource dataSource; + private static ThreadLocal currentConnection = new ThreadLocal(); + + public VirtualFireAlarmDAO() { + initFireAlarmDAO(); + } + + public static void initFireAlarmDAO() { + dataSource = getDataSourceMap().get(VirtualFireAlarmConstants.DEVICE_TYPE); + } + + @Override public IotDeviceDAO getIotDeviceDAO() { + return new VirtualFireAlarmDeviceDAOImpl(); + } + + public static void beginTransaction() throws IotDeviceManagementDAOException { + try { + Connection conn = dataSource.getConnection(); + conn.setAutoCommit(false); + currentConnection.set(conn); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving datasource connection", e); + } + } + + public static Connection getConnection() throws IotDeviceManagementDAOException { + if (currentConnection.get() == null) { + try { + currentConnection.set(dataSource.getConnection()); + } catch (SQLException e) { + throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e); + } + } + return currentConnection.get(); + } + + public static void commitTransaction() throws IotDeviceManagementDAOException { + 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 IotDeviceManagementDAOException("Error occurred while committing the transaction", e); + } finally { + closeConnection(); + } + } + + public static void closeConnection() throws IotDeviceManagementDAOException { + + 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 IotDeviceManagementDAOException { + 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 IotDeviceManagementDAOException("Error occurred while rollback the transaction", e); + } finally { + closeConnection(); + } + } +} \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/dao/impl/VirtualFireAlarmDeviceDAOImpl.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/dao/impl/VirtualFireAlarmDeviceDAOImpl.java new file mode 100644 index 00000000..c8254c04 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/dao/impl/VirtualFireAlarmDeviceDAOImpl.java @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.dao.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceDAO; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.IotDeviceManagementDAOException; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dao.util.IotDeviceManagementDAOUtil; +import org.wso2.carbon.device.mgt.iot.common.util.iotdevice.dto.IotDevice; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants + .VirtualFireAlarmConstants; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.dao.VirtualFireAlarmDAO; + +import java.sql.Connection; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Implements IotDeviceDAO for virtual firealarm Devices. + */ +public class VirtualFireAlarmDeviceDAOImpl implements IotDeviceDAO{ + + + private static final Log log = LogFactory.getLog(VirtualFireAlarmDeviceDAOImpl.class); + + @Override + public IotDevice getIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + Connection conn = null; + PreparedStatement stmt = null; + IotDevice iotDevice = null; + ResultSet resultSet = null; + try { + conn = VirtualFireAlarmDAO.getConnection(); + String selectDBQuery = + "SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME" + + " FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?"; + stmt = conn.prepareStatement(selectDBQuery); + stmt.setString(1, iotDeviceId); + resultSet = stmt.executeQuery(); + + if (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceName(resultSet.getString( + VirtualFireAlarmConstants.DEVICE_PLUGIN_DEVICE_NAME)); + Map propertyMap = new HashMap(); + + + + iotDevice.setDeviceProperties(propertyMap); + + if (log.isDebugEnabled()) { + log.debug("Virtual Firealarm device " + iotDeviceId + " data has been fetched from " + + "Virtual Firealarm database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while fetching Virtual Firealarm device : '" + iotDeviceId + "'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + VirtualFireAlarmDAO.closeConnection(); + } + + return iotDevice; + } + + @Override + public boolean addIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = VirtualFireAlarmDAO.getConnection(); + String createDBQuery = + "INSERT INTO VIRTUAL_FIREALARM_DEVICE(VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME) VALUES (?, ?)"; + + stmt = conn.prepareStatement(createDBQuery); + stmt.setString(1, iotDevice.getIotDeviceId()); + stmt.setString(2,iotDevice.getIotDeviceName()); + if (iotDevice.getDeviceProperties() == null) { + iotDevice.setDeviceProperties(new HashMap()); + } + + + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Virtual Firealarm device " + iotDevice.getIotDeviceId() + " data has been" + + " added to the Virtual Firealarm database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while adding the Virtual Firealarm device '" + + iotDevice.getIotDeviceId() + "' to the Virtual Firealarm db."; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean updateIotDevice(IotDevice iotDevice) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = VirtualFireAlarmDAO.getConnection(); + String updateDBQuery = + "UPDATE VIRTUAL_FIREALARM_DEVICE SET DEVICE_NAME = ? WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?"; + + stmt = conn.prepareStatement(updateDBQuery); + + if (iotDevice.getDeviceProperties() == null) { + iotDevice.setDeviceProperties(new HashMap()); + } + stmt.setString(1, iotDevice.getIotDeviceName()); + + stmt.setString(2, iotDevice.getIotDeviceId()); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Virtualm Firealarm device " + iotDevice.getIotDeviceId() + " data has been" + + " modified."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while modifying the Virtual Firealarm device '" + + iotDevice.getIotDeviceId() + "' data."; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public boolean deleteIotDevice(String iotDeviceId) + throws IotDeviceManagementDAOException { + boolean status = false; + Connection conn = null; + PreparedStatement stmt = null; + try { + conn = VirtualFireAlarmDAO.getConnection(); + String deleteDBQuery = + "DELETE FROM VIRTUAL_FIREALARM_DEVICE WHERE VIRTUAL_FIREALARM_DEVICE_ID = ?"; + stmt = conn.prepareStatement(deleteDBQuery); + stmt.setString(1, iotDeviceId); + int rows = stmt.executeUpdate(); + if (rows > 0) { + status = true; + if (log.isDebugEnabled()) { + log.debug("Virtual Firealarm device " + iotDeviceId + " data has deleted" + + " from the Virtual Firealarm database."); + } + } + } catch (SQLException e) { + String msg = "Error occurred while deleting Virtual Firealarm device " + iotDeviceId; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, null); + } + return status; + } + + @Override + public List getAllIotDevices() + throws IotDeviceManagementDAOException { + + Connection conn = null; + PreparedStatement stmt = null; + ResultSet resultSet = null; + IotDevice iotDevice; + List iotDevices = new ArrayList(); + + try { + conn = VirtualFireAlarmDAO.getConnection(); + String selectDBQuery = + "SELECT VIRTUAL_FIREALARM_DEVICE_ID, DEVICE_NAME " + + "FROM VIRTUAL_FIREALARM_DEVICE"; + stmt = conn.prepareStatement(selectDBQuery); + resultSet = stmt.executeQuery(); + while (resultSet.next()) { + iotDevice = new IotDevice(); + iotDevice.setIotDeviceId(resultSet.getString(VirtualFireAlarmConstants.DEVICE_PLUGIN_DEVICE_ID)); + iotDevice.setIotDeviceName(resultSet.getString(VirtualFireAlarmConstants.DEVICE_PLUGIN_DEVICE_NAME)); + + Map propertyMap = new HashMap(); + + iotDevice.setDeviceProperties(propertyMap); + iotDevices.add(iotDevice); + } + if (log.isDebugEnabled()) { + log.debug("All Virtual Firealarm device details have fetched from Firealarm database."); + } + return iotDevices; + } catch (SQLException e) { + String msg = "Error occurred while fetching all Virtual Firealarm device data'"; + log.error(msg, e); + throw new IotDeviceManagementDAOException(msg, e); + } finally { + IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet); + VirtualFireAlarmDAO.closeConnection(); + } + + } + + } \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/util/VirtualFireAlarmUtils.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/util/VirtualFireAlarmUtils.java new file mode 100644 index 00000000..43bfee74 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/impl/util/VirtualFireAlarmUtils.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.util; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Map; + +/** + * Contains utility methods used by FireAlarm plugin. + */ +public class VirtualFireAlarmUtils { + + private static Log log = LogFactory.getLog(VirtualFireAlarmUtils.class); + + public static String getDeviceProperty(Map deviceProperties, String property) { + + String deviceProperty = deviceProperties.get(property); + + if (deviceProperty == null) { + return ""; + } + + return deviceProperty; + } + + +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/internal/VirtualFirealarmManagementServiceComponent.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/internal/VirtualFirealarmManagementServiceComponent.java new file mode 100644 index 00000000..858f9df9 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/plugin/internal/VirtualFirealarmManagementServiceComponent.java @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * you may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.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.device.mgt.iot.common.service.DeviceTypeService; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl.VirtualFireAlarmManagerService; + + +/** + * @scr.component name="org.wso2.carbon.device.mgt.iot.firealarm.internal.VirtualFirealarmManagementServiceComponent" + * immediate="true" + * @scr.reference name="wso2.carbon.device.mgt.iot.common.DeviceTypeService" + * interface="org.wso2.carbon.device.mgt.iot.common.service.DeviceTypeService" + * cardinality="1..1" + * policy="dynamic" + * bind="setDeviceTypeService" + * unbind="unsetDeviceTypeService" + */ +public class VirtualFirealarmManagementServiceComponent { + + + private ServiceRegistration firealarmServiceRegRef; + + + + private static final Log log = LogFactory.getLog(VirtualFirealarmManagementServiceComponent.class); + protected void activate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("Activating Virtual Firealarm Device Management Service Component"); + } + try { + BundleContext bundleContext = ctx.getBundleContext(); + + + firealarmServiceRegRef = + bundleContext.registerService(DeviceManagementService.class.getName(), + new VirtualFireAlarmManagerService(), + null); + + + + if (log.isDebugEnabled()) { + log.debug("Virtual Firealarm Device Management Service Component has been successfully activated"); + } + } catch (Throwable e) { + log.error("Error occurred while activating Virtual Firealarm Device Management Service Component", e); + } + } + + protected void deactivate(ComponentContext ctx) { + if (log.isDebugEnabled()) { + log.debug("De-activating Virtual Firealarm Device Management Service Component"); + } + try { + if (firealarmServiceRegRef != null) { + firealarmServiceRegRef.unregister(); + } + + if (log.isDebugEnabled()) { + log.debug( + "Virtual Firealarm Device Management Service Component has been successfully de-activated"); + } + } catch (Throwable e) { + log.error("Error occurred while de-activating Virtual Firealarm Device Management bundle", e); + } + } + + protected void setDeviceTypeService(DeviceTypeService deviceTypeService) { + /* This is to avoid this component getting initialized before the + common registered */ + if (log.isDebugEnabled()) { + log.debug("Data source service set to mobile service component"); + } + } + + protected void unsetDeviceTypeService(DeviceTypeService deviceTypeService) { + //do nothing + } + + + +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml new file mode 100644 index 00000000..3db470bd --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/pom.xml @@ -0,0 +1,123 @@ + + + + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm + org.wso2.carbon.device.mgt.iot.server.sample + ${carbon.iot.device.mgt.version} + ../pom.xml + + 4.0.0 + + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl + ${carbon.iot.device.mgt.version} + + war + WSO2 Carbon - IoT Server API - Virtual Firealarm API + + + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.common + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.core + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + provided + + + org.apache.cxf + cxf-rt-frontend-jaxrs + provided + + + org.apache.cxf + cxf-rt-transports-http + provided + + + + org.eclipse.paho + mqtt-client + + + + + org.apache.httpcomponents + httpasyncclient + 4.1 + + + org.wso2.carbon.device.mgt.iot + org.wso2.carbon.device.mgt.iot.common + + + org.wso2.carbon.device.mgt.iot.server.sample + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl + 1.0.0-SNAPSHOT + provided + + + + org.codehaus.jackson + jackson-core-asl + + + org.codehaus.jackson + jackson-jaxrs + + + javax + javaee-web-api + provided + + + javax.ws.rs + jsr311-api + provided + + + commons-httpclient.wso2 + commons-httpclient + + + + org.wso2.carbon + org.wso2.carbon.utils + + + org.wso2.carbon.devicemgt + org.wso2.carbon.device.mgt.analytics + + + + + + + + + maven-compiler-plugin + + UTF-8 + ${wso2.maven.compiler.source} + ${wso2.maven.compiler.target} + + + + maven-war-plugin + + virtual_firealarm + + + + + + \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/log4j.properties b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/log4j.properties new file mode 100755 index 00000000..c271582f --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/log4j.properties @@ -0,0 +1,8 @@ +# Root logger option +log4j.rootLogger=INFO, stdout + +# Direct log messages to stdout +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.Target=System.out +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=%-5p %d{yyyy-MM-dd HH:mm:ss} %c{1}:%L - %m%n \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmControllerService.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmControllerService.java new file mode 100644 index 00000000..aa5f6b76 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmControllerService.java @@ -0,0 +1,756 @@ +/* + * Copyright (c) 2014, 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.device.mgt.iot.sample.virtual.firealarm.service.impl; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.http.HttpResponse; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.concurrent.FutureCallback; +import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.http.impl.nio.client.HttpAsyncClients; +import org.wso2.carbon.context.PrivilegedCarbonContext; +import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; +import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService; +import org.wso2.carbon.device.mgt.common.DeviceIdentifier; +import org.wso2.carbon.device.mgt.common.DeviceManagementException; +import org.wso2.carbon.device.mgt.iot.common.DeviceController; +import org.wso2.carbon.device.mgt.iot.common.DeviceValidator; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.DeviceJSON; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants + .VirtualFireAlarmConstants; +import org.wso2.carbon.utils.CarbonUtils; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.GET; +import javax.ws.rs.HeaderParam; +import javax.ws.rs.HttpMethod; +import javax.ws.rs.POST; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.Future; + +public class VirtualFireAlarmControllerService { + + private static Log log = LogFactory.getLog(VirtualFireAlarmControllerService.class); + //TODO; replace this tenant domain + private final String SUPER_TENANT = "carbon.super"; + @Context //injected response proxy supporting multiple thread + private HttpServletResponse response; + private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; + + private static final String URL_PREFIX = "http://"; + private static final String BULB_CONTEXT = "/BULB/"; + private static final String SONAR_CONTEXT = "/SONAR/"; + private static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/"; + + public static final String XMPP_PROTOCOL = "XMPP"; + public static final String HTTP_PROTOCOL = "HTTP"; + public static final String MQTT_PROTOCOL = "MQTT"; + + + private static ConcurrentHashMap deviceToIpMap = + new ConcurrentHashMap(); + + @Path("/register/{owner}/{deviceId}/{ip}") + @POST + public String registerDeviceIP(@PathParam("owner") String owner, + @PathParam("deviceId") String deviceId, + @PathParam("ip") String deviceIP, + @Context HttpServletResponse response) { + String result; + + log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + + " of owner: " + owner); + + deviceToIpMap.put(deviceId, deviceIP); + + result = "Device-IP Registered"; + response.setStatus(Response.Status.OK.getStatusCode()); + + if (log.isDebugEnabled()) { + log.debug(result); + } + + return result; + } + + + /* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb + Called by an external client intended to control the Virtual FireAlarm bulb */ + @Path("/bulb/{state}") + @POST + public void switchBulb(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @PathParam("state") String state, + @Context HttpServletResponse response) { + + try { + DeviceValidator deviceValidator = new DeviceValidator(); + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants.DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + return; + } + } catch (DeviceManagementException e) { + log.error("DeviceValidation Failed for deviceId: " + deviceId + " of user: " + owner); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return; + } + + String switchToState = state.toUpperCase(); + + if (!switchToState.equals(VirtualFireAlarmConstants.STATE_ON) && !switchToState.equals( + VirtualFireAlarmConstants.STATE_OFF)) { + log.error("The requested state change shoud be either - 'ON' or 'OFF'"); + response.setStatus(Response.Status.BAD_REQUEST.getStatusCode()); + return; + } + + String deviceIP = deviceToIpMap.get(deviceId); + if (deviceIP == null) { + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } + + String protocolString = protocol.toUpperCase(); + String callUrlPattern = BULB_CONTEXT + switchToState; + + log.info("Sending command: '" + callUrlPattern + "' to virtual-firealarm at: " + deviceIP + " " + + "via" + " " + protocolString); + + try { + switch (protocolString) { + case HTTP_PROTOCOL: + sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + break; + case MQTT_PROTOCOL: + sendCommandViaMQTT(owner, deviceId, BULB_CONTEXT.replace("/", ""), + switchToState); + break; + case XMPP_PROTOCOL: +// requestBulbChangeViaXMPP(switchToState, response); + sendCommandViaXMPP(owner, deviceId, BULB_CONTEXT, switchToState); + break; + default: + if (protocolString == null) { + sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + return; + } + break; + } + } catch (DeviceManagementException e) { + log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + + " " + protocol); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return; + } + + response.setStatus(Response.Status.OK.getStatusCode()); + } + + + @Path("/readsonar") + @GET + public String requestSonarReading(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @Context HttpServletResponse response) { + String replyMsg = ""; + + DeviceValidator deviceValidator = new DeviceValidator(); + try { + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants + .DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + return "Unauthorized Access"; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return replyMsg; + } + + String deviceIp = deviceToIpMap.get(deviceId); + + if (deviceIp == null) { + replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return replyMsg; + } + + try { + switch (protocol) { + case HTTP_PROTOCOL: + log.info("Sending request to read sonar value at : " + deviceIp + + " via " + HTTP_PROTOCOL); + + replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false); + break; + + case XMPP_PROTOCOL: + log.info("Sending request to read sonar value at : " + deviceIp + + " via " + + XMPP_PROTOCOL); + replyMsg = sendCommandViaXMPP(owner, deviceId, SONAR_CONTEXT, "."); + break; + + default: + if (protocol == null) { + log.info("Sending request to read sonar value at : " + deviceIp + + " via " + HTTP_PROTOCOL); + + replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false); + } else { + replyMsg = "Requested protocol '" + protocol + "' is not supported"; + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + return replyMsg; + } + break; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return replyMsg; + } + + response.setStatus(Response.Status.OK.getStatusCode()); + replyMsg = "The current sonar reading of the device is " + replyMsg; + return replyMsg; + } + + + @Path("/readtemperature") + @GET + public String requestTemperature(@HeaderParam("owner") String owner, + @HeaderParam("deviceId") String deviceId, + @HeaderParam("protocol") String protocol, + @Context HttpServletResponse response) { + String replyMsg = ""; + + DeviceValidator deviceValidator = new DeviceValidator(); + try { + if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, + VirtualFireAlarmConstants + .DEVICE_TYPE))) { + response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); + return "Unauthorized Access"; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return replyMsg; + } + + String deviceIp = deviceToIpMap.get(deviceId); + + if (deviceIp == null) { + replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return replyMsg; + } + + try { + switch (protocol) { + case HTTP_PROTOCOL: + log.info("Sending request to read virtual-firealarm-temperature at : " + deviceIp + + " via " + HTTP_PROTOCOL); + + replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); + break; + + case XMPP_PROTOCOL: + log.info("Sending request to read virtual-firealarm-temperature at : " + deviceIp + + " via " + + XMPP_PROTOCOL); + replyMsg = sendCommandViaXMPP(owner, deviceId, TEMPERATURE_CONTEXT, "."); +// replyMsg = requestTemperatureViaXMPP(response); + break; + + default: + if (protocol == null) { + log.info("Sending request to read virtual-firealarm-temperature at : " + deviceIp + + " via " + HTTP_PROTOCOL); + + replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); + } else { + replyMsg = "Requested protocol '" + protocol + "' is not supported"; + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + return replyMsg; + } + break; + } + } catch (DeviceManagementException e) { + replyMsg = e.getErrorMessage(); + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return replyMsg; + } + + response.setStatus(Response.Status.OK.getStatusCode()); + replyMsg = "The current temperature of the device is " + replyMsg; + return replyMsg; + } + + +// public String requestTemperatureViaXMPP(@Context HttpServletResponse response) { +// String replyMsg = ""; +// +// String sep = File.separator; +// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; +// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep +// + "xmpp_client.py -r Temperature"; +// String command = "python " + scriptPath; +// +// replyMsg = executeCommand(command); +// +// response.setStatus(HttpStatus.SC_OK); +// return replyMsg; +// } + + +// public String requestSonarViaXMPP(@Context HttpServletResponse response) { +// String replyMsg = ""; +// +// String sep = File.separator; +// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; +// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep +// + "xmpp_client.py -r Sonar"; +// String command = "python " + scriptPath; +// +// replyMsg = executeCommand(command); +// +// response.setStatus(HttpStatus.SC_OK); +// return replyMsg; +// } + + +// public String requestBulbChangeViaXMPP(String state, +// @Context HttpServletResponse response) { +// String replyMsg = ""; +// +// String sep = File.separator; +// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts"; +// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep +// + "xmpp_client.py -r Bulb -s " + state; +// String command = "python " + scriptPath; +// +// replyMsg = executeCommand(command); +// +// response.setStatus(HttpStatus.SC_OK); +// return replyMsg; +// } + + @Path("/push_temperature") + @POST + @Consumes(MediaType.APPLICATION_JSON) + public void pushTemperatureData( + final DeviceJSON dataMsg, @Context HttpServletResponse response) { + boolean result; + String deviceId = dataMsg.deviceId; + String deviceIp = dataMsg.reply; + float temperature = dataMsg.value; + + String registeredIp = deviceToIpMap.get(deviceId); + + if (registeredIp == null) { + log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + + deviceIp + " for device ID - " + deviceId); + response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); + return; + } else if (!registeredIp.equals(deviceIp)) { + log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + + deviceId + " is already registered under some other IP. Re-registration " + "required"); + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + return; + } + + PrivilegedCarbonContext.startTenantFlow(); + PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); + ctx.setTenantDomain(SUPER_TENANT, true); + DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx + .getOSGiService(DeviceAnalyticsService.class, null); + Object metdaData[] = {dataMsg.owner, VirtualFireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId, + System.currentTimeMillis()}; + Object payloadData[] = {temperature}; + try { + deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", + metdaData, new Object[0], payloadData); + } catch (DataPublisherConfigurationException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + + } finally { + PrivilegedCarbonContext.endTenantFlow(); + } + + + } + + + /* Service to push all the sensor data collected by the FireAlarm + Called by the FireAlarm device */ + +// @Path("/pushalarmdata") +// @POST +// @Consumes(MediaType.APPLICATION_JSON) +// public void pushAlarmData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { +// boolean result; +// String sensorValues = dataMsg.value; +// log.info("Recieved Sensor Data Values: " + sensorValues); +// +// String sensors[] = sensorValues.split(":"); +// try { +// if (sensors.length == 3) { +// String temperature = sensors[0]; +// String bulb = sensors[1]; +// String sonar = sensors[2]; + +// sensorValues = "Temperature:" + temperature + "C\tBulb Status:" + bulb + +// "\t\tSonar Status:" + sonar; +// log.info(sensorValues); +// DeviceController deviceController = new DeviceController(); +// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants +// .DEVICE_TYPE, +// dataMsg.deviceId, +// System.currentTimeMillis(), "DeviceData", +// temperature, "TEMPERATURE"); +// +// if (!result) { +// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); +// log.error("Error whilst pushing temperature: " + sensorValues); +// return; +// } +// +// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants +// .DEVICE_TYPE, +// dataMsg.deviceId, +// System.currentTimeMillis(), "DeviceData", +// bulb, +// "BULB"); +// +// if (!result) { +// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); +// log.error("Error whilst pushing Bulb data: " + sensorValues); +// return; +// } +// +// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants +// .DEVICE_TYPE, +// dataMsg.deviceId, +// System.currentTimeMillis(), "DeviceData", +// sonar, +// "SONAR"); +// +// if (!result) { +// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); +// log.error("Error whilst pushing Sonar data: " + sensorValues); +// } +// +// } else { +// DeviceController deviceController = new DeviceController(); +// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants +// .DEVICE_TYPE, +// dataMsg.deviceId, +// System.currentTimeMillis(), "DeviceData", +// dataMsg.value, dataMsg.reply); +// if (!result) { +// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); +// log.error("Error whilst pushing sensor data: " + sensorValues); +// } +// } +// +// } catch (UnauthorizedException e) { +// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); +// log.error("Data Push Attempt Failed at Publisher: " + e.getMessage()); +// } +// } + + + private String sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + String replyMsg = ""; + String scriptArguments = ""; + String command = ""; + + String seperator = File.separator; + String xmppServerURL = XmppConfig.getInstance().getXmppEndpoint(); + int indexOfChar = xmppServerURL.lastIndexOf(seperator); + if (indexOfChar != -1) { + xmppServerURL = xmppServerURL.substring((indexOfChar + 1), xmppServerURL.length()); + } + + indexOfChar = xmppServerURL.indexOf(":"); + if (indexOfChar != -1) { + xmppServerURL = xmppServerURL.substring(0, indexOfChar); + } + + String xmppAdminUName = XmppConfig.getInstance().getXmppUsername(); + String xmppAdminPass = XmppConfig.getInstance().getXmppPassword(); + + String xmppAdminUserLogin = xmppAdminUName + "@" + xmppServerURL + seperator + deviceOwner; + String clientToConnect = deviceId + "@" + xmppServerURL + seperator + deviceOwner; + + String scriptsFolder = "repository" + seperator + "resources" + seperator + "scripts"; + String scriptPath = CarbonUtils.getCarbonHome() + seperator + scriptsFolder + seperator + + "xmpp_client.py "; + + scriptArguments = + "-j " + xmppAdminUserLogin + " -p " + xmppAdminPass + " -c " + clientToConnect + + " -r " + resource + " -s " + state; + command = "python " + scriptPath + scriptArguments; + + if (log.isDebugEnabled()) { + log.debug("Connecting to XMPP Server via Admin credentials: " + xmppAdminUserLogin); + log.debug("Trying to contact xmpp device account: " + clientToConnect); + log.debug("Arguments used for the scripts: '" + scriptArguments + "'"); + log.debug("Command exceuted: '" + command + "'"); + } + +// switch (resource) { +// case BULB_CONTEXT: +// scriptArguments = "-r Bulb -s " + state; +// command = "python " + scriptPath + scriptArguments; +// break; +// case SONAR_CONTEXT: +// scriptArguments = "-r Sonar"; +// command = "python " + scriptPath + scriptArguments; +// break; +// case TEMPERATURE_CONTEXT: +// scriptArguments = "-r Temperature"; +// command = "python " + scriptPath + scriptArguments; +// break; +// } + + replyMsg = executeCommand(command); + return replyMsg; + } + + + private String executeCommand(String command) { + StringBuffer output = new StringBuffer(); + + Process p; + try { + p = Runtime.getRuntime().exec(command); + p.waitFor(); + BufferedReader reader = + new BufferedReader(new InputStreamReader(p.getInputStream())); + + String line = ""; + while ((line = reader.readLine()) != null) { + output.append(line + "\n"); + } + + } catch (Exception e) { + log.info(e.getMessage(), e); + } + + return output.toString(); + + } + + + private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, + String state) throws DeviceManagementException { + + boolean result = false; + DeviceController deviceController = new DeviceController(); + + try { + result = deviceController.publishMqttControl(deviceOwner, + VirtualFireAlarmConstants.DEVICE_TYPE, + deviceId, resource, state); + } catch (DeviceControllerException e) { + String errorMsg = "Error whilst trying to publish to MQTT Queue"; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + return result; + } + + + private String sendCommandViaHTTP(final String deviceIp, int deviceServerPort, + String callUrlPattern, + boolean fireAndForgot) + throws DeviceManagementException { + + if (deviceServerPort == 0) { + deviceServerPort = 80; + } + + String responseMsg = ""; + String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern; + + if (log.isDebugEnabled()) { + log.debug(urlString); + } + + if (!fireAndForgot) { + HttpURLConnection httpConnection = getHttpConnection(urlString); + + try { + httpConnection.setRequestMethod(HttpMethod.GET); + } catch (ProtocolException e) { + String errorMsg = + "Protocol specific error occurred when trying to set method to GET" + + " for:" + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + responseMsg = readResponseFromGetRequest(httpConnection); + + } else { + CloseableHttpAsyncClient httpclient = null; + try { + + httpclient = HttpAsyncClients.createDefault(); + httpclient.start(); + HttpGet request = new HttpGet(urlString); + final CountDownLatch latch = new CountDownLatch(1); + Future future = httpclient.execute( + request, new FutureCallback() { + @Override + public void completed(HttpResponse httpResponse) { + latch.countDown(); + } + + @Override + public void failed(Exception e) { + latch.countDown(); + } + + @Override + public void cancelled() { + latch.countDown(); + } + }); + + latch.await(); + + } catch (InterruptedException e) { + if (log.isDebugEnabled()) { + log.debug("Sync Interrupted"); + } + } finally { + try { + if (httpclient != null) { + httpclient.close(); + + } + } catch (IOException e) { + if (log.isDebugEnabled()) { + log.debug("Failed on close"); + } + } + } + + } + + return responseMsg; + } + + /* Utility methods relevant to creating and sending http requests */ + + /* This methods creates and returns a http connection object */ + + private HttpURLConnection getHttpConnection(String urlString) throws + DeviceManagementException { + + URL connectionUrl = null; + HttpURLConnection httpConnection = null; + + try { + connectionUrl = new URL(urlString); + httpConnection = (HttpURLConnection) connectionUrl.openConnection(); + } catch (MalformedURLException e) { + String errorMsg = + "Error occured whilst trying to form HTTP-URL from string: " + urlString; + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } catch (IOException e) { + String errorMsg = "Error occured whilst trying to open a connection to: " + + connectionUrl.toString(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + return httpConnection; + } + + /* This methods reads and returns the response from the connection */ + + private String readResponseFromGetRequest(HttpURLConnection httpConnection) + throws DeviceManagementException { + BufferedReader bufferedReader = null; + try { + bufferedReader = new BufferedReader(new InputStreamReader( + httpConnection.getInputStream())); + } catch (IOException e) { + String errorMsg = + "There is an issue with connecting the reader to the input stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + + String responseLine; + StringBuffer completeResponse = new StringBuffer(); + + try { + while ((responseLine = bufferedReader.readLine()) != null) { + completeResponse.append(responseLine); + } + } catch (IOException e) { + String errorMsg = + "Error occured whilst trying read from the connection stream at: " + + httpConnection.getURL(); + log.error(errorMsg); + throw new DeviceManagementException(errorMsg, e); + } + try { + bufferedReader.close(); + } catch (IOException e) { + log.error( + "Could not succesfully close the bufferedReader to the connection at: " + + httpConnection.getURL()); + } + + return completeResponse.toString(); + } + +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java new file mode 100644 index 00000000..48a1a1b5 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/VirtualFireAlarmManagerService.java @@ -0,0 +1,359 @@ +/* + * Copyright (c) 2014, 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.device.mgt.iot.sample.virtual.firealarm.service.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.EnrolmentInfo; +import org.wso2.carbon.device.mgt.iot.common.DeviceManagement; +import org.wso2.carbon.device.mgt.iot.common.apimgt.AccessTokenInfo; +import org.wso2.carbon.device.mgt.iot.common.apimgt.TokenClient; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppAccount; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; +import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; +import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; +import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; +import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; +import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; +import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants + .VirtualFireAlarmConstants; + +import javax.servlet.http.HttpServletResponse; +import javax.ws.rs.Consumes; +import javax.ws.rs.DELETE; +import javax.ws.rs.GET; +import javax.ws.rs.POST; +import javax.ws.rs.PUT; +import javax.ws.rs.Path; +import javax.ws.rs.PathParam; +import javax.ws.rs.Produces; +import javax.ws.rs.QueryParam; +import javax.ws.rs.core.Context; +import javax.ws.rs.core.Response; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +//@Path("/VirtualFireAlarmDeviceManager") +public class VirtualFireAlarmManagerService { + + private static Log log = LogFactory.getLog(VirtualFireAlarmManagerService.class); + + //TODO; replace this tenant domain + private final String SUPER_TENANT = "carbon.super"; + @Context //injected response proxy supporting multiple thread + private HttpServletResponse response; + + @Path("/device/register") + @PUT + public boolean register(@QueryParam("deviceId") String deviceId, + @QueryParam("name") String name, @QueryParam("owner") String owner) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + try { + if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) { + response.setStatus(Response.Status.CONFLICT.getStatusCode()); + 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(VirtualFireAlarmConstants.DEVICE_TYPE); + enrolmentInfo.setOwner(owner); + device.setEnrolmentInfo(enrolmentInfo); + boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device); + + if (added) { + response.setStatus(Response.Status.OK.getStatusCode()); + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + } + + return added; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + } + + @Path("/device/remove/{device_id}") + @DELETE + public void removeDevice(@PathParam("device_id") String deviceId, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + try { + boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice( + deviceIdentifier); + if (removed) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("/device/update/{device_id}") + @POST + public boolean updateDevice(@PathParam("device_id") String deviceId, + @QueryParam("name") String name, + @Context HttpServletResponse response) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + try { + Device device = deviceManagement.getDeviceManagementService().getDevice( + deviceIdentifier); + device.setDeviceIdentifier(deviceId); + + // device.setDeviceTypeId(deviceTypeId); + device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime()); + + device.setName(name); + device.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + + boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment( + device); + + if (updated) { + response.setStatus(Response.Status.OK.getStatusCode()); + + } else { + response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); + + } + return updated; + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return false; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("/device/{device_id}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device getDevice(@PathParam("device_id") String deviceId) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); + deviceIdentifier.setId(deviceId); + deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); + + try { + return deviceManagement.getDeviceManagementService().getDevice(deviceIdentifier); + + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("/devices/{username}") + @GET + @Consumes("application/json") + @Produces("application/json") + public Device[] getFirealarmDevices(@PathParam("username") String username) { + + DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); + + try { + List userDevices = + deviceManagement.getDeviceManagementService().getDevicesOfUser( + username); + ArrayList userDevicesforFirealarm = new ArrayList(); + for (Device device : userDevices) { + + if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) && + device.getEnrolmentInfo().getStatus().equals( + EnrolmentInfo.Status.ACTIVE)) { + userDevicesforFirealarm.add(device); + + } + } + + return userDevicesforFirealarm.toArray(new Device[]{}); + } catch (DeviceManagementException e) { + response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); + return null; + } finally { + deviceManagement.endTenantFlow(); + } + + } + + @Path("/device/{sketch_type}/download") + @GET + @Produces("application/octet-stream") + public Response downloadSketch(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile()); + rb.header("Content-Disposition", + "attachment; filename=\"" + zipFile.getFileName() + "\""); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + @Path("/device/{sketch_type}/generate_link") + @GET + public Response generateSketchLink(@QueryParam("owner") String owner, + @PathParam("sketch_type") String sketchType) { + + ZipArchive zipFile = null; + try { + zipFile = createDownloadFile(owner, sketchType); + Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId()); + return rb.build(); + } catch (IllegalArgumentException ex) { + return Response.status(400).entity(ex.getMessage()).build();//bad request + } catch (DeviceManagementException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (AccessTokenException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } catch (DeviceControllerException ex) { + return Response.status(500).entity(ex.getMessage()).build(); + } + + } + + private ZipArchive createDownloadFile(String owner, String sketchType) + throws DeviceManagementException, AccessTokenException, DeviceControllerException { + if (owner == null) { + throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!"); + } + + //create new device id + String deviceId = shortUUID(); + + TokenClient accessTokenClient = new TokenClient(VirtualFireAlarmConstants.DEVICE_TYPE); + AccessTokenInfo accessTokenInfo = null; + + accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); + + //create token + String accessToken = accessTokenInfo.getAccess_token(); + String refreshToken = accessTokenInfo.getRefresh_token(); + //adding registering data + + XmppAccount newXmppAccount = new XmppAccount(); + newXmppAccount.setAccountName(owner + "_" + deviceId); + newXmppAccount.setUsername(deviceId); + newXmppAccount.setPassword(accessToken); + + String xmppEndPoint = XmppConfig.getInstance().getXmppControlQueue().getServerURL(); + + int indexOfChar = xmppEndPoint.lastIndexOf('/'); + + if (indexOfChar != -1) { + xmppEndPoint = xmppEndPoint.substring((indexOfChar + 1), xmppEndPoint.length()); + } + + newXmppAccount.setEmail(deviceId + "@wso2.com"); + + XmppServerClient xmppServerClient = new XmppServerClient(); + xmppServerClient.initControlQueue(); + boolean status; + if(XmppConfig.getInstance().isEnabled()) { + status = xmppServerClient.createXMPPAccount(newXmppAccount); + + if (!status) { + String msg = + "XMPP Account was not created for device - " + deviceId + " of owner - " + + owner + + ". XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config.server.configs"; + log.warn(msg); + throw new DeviceManagementException(msg); + } + } + status = register(deviceId, owner + "s_" + sketchType + "_" + deviceId.substring(0, + 3), + owner); + 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 = null; + + zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, accessToken, refreshToken); + zipFile.setDeviceId(deviceId); + return zipFile; + } + + private static String shortUUID() { + UUID uuid = UUID.randomUUID(); + long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong(); + return Long.toString(l, Character.MAX_RADIX); + } + +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/DeviceJSON.java b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/DeviceJSON.java new file mode 100644 index 00000000..62ec64fa --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/java/org/wso2/carbon/device/mgt/iot/sample/virtual/firealarm/service/impl/util/DeviceJSON.java @@ -0,0 +1,18 @@ +package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util; + +import org.codehaus.jackson.annotate.JsonIgnoreProperties; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement + +@JsonIgnoreProperties(ignoreUnknown = true) +public class DeviceJSON { + @XmlElement(required = true) public String owner; + @XmlElement(required = true) public String deviceId; + @XmlElement(required = true) public String reply; + @XmlElement public Long time; + @XmlElement public String key; + @XmlElement public float value; +} diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/META-INF/webapp-classloading.xml b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/META-INF/webapp-classloading.xml new file mode 100644 index 00000000..fa446191 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/META-INF/webapp-classloading.xml @@ -0,0 +1,33 @@ + + + + + + + + + false + + + CXF,Carbon + diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml new file mode 100644 index 00000000..dc3ddaab --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/cxf-servlet.xml @@ -0,0 +1,53 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml new file mode 100755 index 00000000..ee946a86 --- /dev/null +++ b/modules/samples/virtual_firealarm/src/org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl/src/main/webapp/WEB-INF/web.xml @@ -0,0 +1,23 @@ + + + WSO2 IoT Server + WSO2 IoT Server + + + CXFServlet + org.apache.cxf.transport.servlet.CXFServlet + 1 + + + + + CXFServlet + /* + + + + diff --git a/modules/samples/virtual_firealarm/src/pom.xml b/modules/samples/virtual_firealarm/src/pom.xml new file mode 100644 index 00000000..d949f29c --- /dev/null +++ b/modules/samples/virtual_firealarm/src/pom.xml @@ -0,0 +1,23 @@ + + + iot-server-samples + org.wso2.carbon.device.mgt.iot.server.sample + ${carbon.iot.device.mgt.version} + ../../pom.xml + + + 4.0.0 + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm + pom + ${carbon.iot.device.mgt.version} + WSO2 Carbon - Virtual Firealarm Sample + http://wso2.org + WSO2 Carbon - IoT Server Sample + + + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.impl + org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl + + + \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/units/public/images/schematicsGuide.png b/modules/samples/virtual_firealarm/units/public/images/schematicsGuide.png new file mode 100644 index 00000000..b247bf65 Binary files /dev/null and b/modules/samples/virtual_firealarm/units/public/images/schematicsGuide.png differ diff --git a/modules/samples/virtual_firealarm/units/public/images/virtual_firealarm-thumb.png b/modules/samples/virtual_firealarm/units/public/images/virtual_firealarm-thumb.png new file mode 100644 index 00000000..aaf16925 Binary files /dev/null and b/modules/samples/virtual_firealarm/units/public/images/virtual_firealarm-thumb.png differ diff --git a/modules/samples/virtual_firealarm/units/public/images/virtual_firealarm.png b/modules/samples/virtual_firealarm/units/public/images/virtual_firealarm.png new file mode 100644 index 00000000..a735a75a Binary files /dev/null and b/modules/samples/virtual_firealarm/units/public/images/virtual_firealarm.png differ diff --git a/modules/samples/virtual_firealarm/units/public/js/virtual_firealarm.js b/modules/samples/virtual_firealarm/units/public/js/virtual_firealarm.js new file mode 100644 index 00000000..42f877d2 --- /dev/null +++ b/modules/samples/virtual_firealarm/units/public/js/virtual_firealarm.js @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. + * + * WSO2 Inc. licenses this file to you under the Apache License, + * Version 2.0 (the "License"); you may not use this file except + * in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +var modalPopup = ".wr-modalpopup"; +var modalPopupContainer = modalPopup + " .modalpopup-container"; +var modalPopupContent = modalPopup + " .modalpopup-content"; +var body = "body"; + +/* + * set popup maximum height function. + */ +function setPopupMaxHeight() { + $(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30))); + $(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2))); +} + +/* + * show popup function. + */ +function showPopup() { + $(modalPopup).show(); + setPopupMaxHeight(); +} + +/* + * hide popup function. + */ +function hidePopup() { + $(modalPopupContent).html(''); + $(modalPopup).hide(); +} + +/* + * DOM ready functions. + */ +$(document).ready(function () { + attachEvents(); +}); + +function attachEvents() { + /** + * Following click function would execute + * when a user clicks on "Download" link + * on Device Management page in WSO2 DC Console. + */ + $("a.download-link").click(function () { + var sketchType = $(this).data("sketchtype"); + var deviceType = $(this).data("devicetype"); + var downloadDeviceAPI = "/iotserver/api/device/sketch/generate_link"; + var payload = {"sketchType":sketchType, "deviceType":deviceType}; + console.log(payload); + $(modalPopupContent).html($('#download-device-modal-content').html()); + showPopup(); + + $("a#download-device-download-link").click(function () { + invokerUtil.post( + downloadDeviceAPI, + payload, + function (data, textStatus, jqxhr) { + if(jqxhr.status == 200) { + if(data == "403"){ + $(modalPopupContent).html($('#device-403-content').html()); + $("#device-403-link").click(function () { + window.location = "/iotserver/login"; + }); + showPopup(); + }else { + $(modalPopupContent).html($('#download-device-modal-content-links').html()); + $("#download-device-url").val(data); + $("#download-device-url").focus(function () { + $(this).select(); + }); + showPopup(); + } + }else{ + $(modalPopupContent).html($('#device-403-content').html()); + $("#device-403-link").click(function () { + window.location.reload(); + }); + showPopup(); + } + }, + function () { + $(modalPopupContent).html($('#device-unexpected-error-content').html()); + $("a#device-unexpected-error-link").click(function () { + hidePopup(); + }); + } + ); + }); + + $("a#download-device-cancel-link").click(function () { + hidePopup(); + }); + + }); +} diff --git a/modules/samples/virtual_firealarm/units/public/store.json b/modules/samples/virtual_firealarm/units/public/store.json new file mode 100644 index 00000000..793feca5 --- /dev/null +++ b/modules/samples/virtual_firealarm/units/public/store.json @@ -0,0 +1,4 @@ +{ + "title" : "Virtual Firealarm", + "description":"Connect and Test a Virtual Firealarm over the WSO2 IoT Server" +} \ No newline at end of file diff --git a/modules/samples/virtual_firealarm/units/virtual_firealarm.hbs b/modules/samples/virtual_firealarm/units/virtual_firealarm.hbs new file mode 100644 index 00000000..76d8a60a --- /dev/null +++ b/modules/samples/virtual_firealarm/units/virtual_firealarm.hbs @@ -0,0 +1,213 @@ +{{#zone "main"}} +
+
+
+
+

Fire Alarm

+
+

Connect your Fire Alarm device + to the WSO2 IoT server.

+
+
+ +
+
+

Ingredients

+
+

Hardware Requirements

+
+ + + + Raspberry Pi (Internet Enabled) +       + + + + DHT11 Temperature Sensor

+ + + + LED +                      +                      +           + + + + Buzzer(3v)

+ Download + +
+ +
+
+

Prepare


+

Get your device ready

+
+ 01 Set up your RaspberryPi device as shown in the schematic below and get the FireAlarm setup. +
+
+ 02 Connect a monitor to your RaspberryPi via the HDMI cable to get a UI view of the device. +
+
+ 03 Get the RaspberryPi to connect to the internet (via Ethernet or Wifi) and note its IP_ADDRESS +
+
+
+

Schematic Diagram


+

Click on the image to zoom

+
+ + + +
+
+
+
+
+

Connect (Quickstart)

+
+

Internet of Things Foundation Quickstart connection

+
+ 01 Click on the "Create DEB" button above to get the download link for the FireAlarm setup files
+
+
+
+ (The following commands can be issued by directly typing into the terminal of the device or by an "ssh" login from a remote PC) +
+
+ 02 Download the FireAlarm setup files using the following command: "curl -k <url_link_received_from_the_above_step> > Agent.zip"
+                 This will download a zip file named "Agent.zip" +
+
+ + 03 Run the following commands to successfuly install the package and get the service running:
+                cd <PATH_WHERE_THE_DOWNLOADED_"Agent.zip"_FILE_IS>
+              unzip Agent.zip -d Agent
+              cd Agent
+              sudo chmod 755 startservice.sh
+              sudo ./startservice.sh
+ +
+ + +
+ 04 Follow the installation instructions and complete installation. Upon completion the Agent would have started automatically
+
+
+
+
+ +
+
+
+
+

Please download the file from following link.

+
+
+
+ + + +    + +     Copy Link     + +    +
+
+
+
+
+
+ + + +
+
+
+
+

Exception at backend. Try Later.

+ +
+
+
+
+ +
+
+
+
+

Action not permitted.

+ +
+
+
+
+ +
+
+
+
+

Device Sketch does not exist.

+ +
+
+
+
+ +
+
+
+
+

Unexpected error.

+ +
+
+
+
+ +{{/zone}} +{{#zone "topCss"}} + + +{{/zone}} +{{#zone "bottomJs"}} + +{{/zone}} diff --git a/modules/samples/virtual_firealarm/units/virtual_firealarm.js b/modules/samples/virtual_firealarm/units/virtual_firealarm.js new file mode 100644 index 00000000..68606eea --- /dev/null +++ b/modules/samples/virtual_firealarm/units/virtual_firealarm.js @@ -0,0 +1,4 @@ +function onRequest(context){ + context.sketchPath = "../api/device/sketch/download"; + return context; +} diff --git a/modules/samples/virtual_firealarm/units/virtual_firealarm.json b/modules/samples/virtual_firealarm/units/virtual_firealarm.json new file mode 100644 index 00000000..3dbff381 --- /dev/null +++ b/modules/samples/virtual_firealarm/units/virtual_firealarm.json @@ -0,0 +1,3 @@ +{ + "predicate": "false" +} \ No newline at end of file