added changes to virtual fire alaram sample

dev
Amalka Subasinghe 2 years ago
parent 83bfaded86
commit 99337539e6

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>6.0.16-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-types</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Plugins</name>
<url>http://wso2.org</url>
<modules>
<module>virtual-fire-alarm-plugin</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -23,8 +23,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>4.1.21-SNAPSHOT</version> <version>6.0.16-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent> </parent>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl</artifactId> <artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl</artifactId>

@ -69,8 +69,9 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
Runnable connector = new Runnable() { Runnable connector = new Runnable() {
public void run() { public void run() {
while (!isConnected()) { while (!isConnected()) {
try { try { // uudi formay 8-4-4-4-12
connectToQueue(agentManager.getAgentConfigs().getAuthToken(), DEFAULT_PASSWORD); connectToQueue(agentManager.getAgentConfigs().getAuthToken().substring(0, 18),
agentManager.getAgentConfigs().getAuthToken().substring(19));
agentManager.updateAgentStatus("Connected to MQTT Queue"); agentManager.updateAgentStatus("Connected to MQTT Queue");
} catch (TransportHandlerException e) { } catch (TransportHandlerException e) {
log.warn(AgentConstants.LOG_APPENDER + "Connection to MQTT Broker at: " + mqttBrokerEndPoint + log.warn(AgentConstants.LOG_APPENDER + "Connection to MQTT Broker at: " + mqttBrokerEndPoint +
@ -138,6 +139,18 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
String replyMessage; String replyMessage;
String securePayLoad; String securePayLoad;
if (message.toString().contains("BULB:ON")) {
boolean stateToSwitch = true;
agentManager.changeAlarmStatus(stateToSwitch);
log.info(AgentConstants.LOG_APPENDER + "Bulb was switched to state: 'ON'");
return;
} else if (message.toString().contains("BULB:OFF")) {
boolean stateToSwitch = false;
agentManager.changeAlarmStatus(stateToSwitch);
log.info(AgentConstants.LOG_APPENDER + "Bulb was switched to state: 'OFF'");
return;
}
try { try {
receivedMessage = AgentUtilOperations.extractMessageFromPayload(message.toString()); receivedMessage = AgentUtilOperations.extractMessageFromPayload(message.toString());
log.info(AgentConstants.LOG_APPENDER + "Message [" + receivedMessage + "] was received"); log.info(AgentConstants.LOG_APPENDER + "Message [" + receivedMessage + "] was received");
@ -210,8 +223,8 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
int currentTemperature = agentManager.getTemperature(); int currentTemperature = agentManager.getTemperature();
String message = "{\"event\": {\"metaData\": {\"owner\": \"" + AgentManager String message = "{\"event\": {\"metaData\": {\"owner\": \"" + AgentManager
.getInstance().getAgentConfigs().getDeviceOwner() + "\",\"deviceId\": \"" + AgentManager .getInstance().getAgentConfigs().getDeviceOwner() + "\",\"deviceId\": \"" + AgentManager
.getInstance().getAgentConfigs().getDeviceId() + "\",\"time\": " + .getInstance().getAgentConfigs().getDeviceId() + "\",\"time\": \"" +
"0},\"payloadData\": { \"temperature\": " + currentTemperature + "} }}"; System.currentTimeMillis() + "\"},\"payloadData\": { \"temperature\": " + currentTemperature + "} }}";
try { try {
String payLoad = AgentUtilOperations.prepareSecurePayLoad(message); String payLoad = AgentUtilOperations.prepareSecurePayLoad(message);

@ -21,7 +21,7 @@
<parent> <parent>
<artifactId>virtual-fire-alarm-plugin</artifactId> <artifactId>virtual-fire-alarm-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId> <groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>4.1.21-SNAPSHOT</version> <version>6.0.16-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <relativePath>../pom.xml</relativePath>
</parent> </parent>
@ -32,6 +32,10 @@
<description>WSO2 Carbon - Virtual FireAlarm Service Management API Implementation</description> <description>WSO2 Carbon - Virtual FireAlarm Service Management API Implementation</description>
<url>http://wso2.org</url> <url>http://wso2.org</url>
<properties>
<cxf-bundle-package.version>2.7.18</cxf-bundle-package.version>
</properties>
<dependencies> <dependencies>
<!-- CDM --> <!-- CDM -->
<dependency> <dependency>
@ -208,11 +212,11 @@
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId> <artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <!-- <dependency>-->
<groupId>org.wso2.carbon.analytics</groupId> <!-- <groupId>org.wso2.carbon.analytics</groupId>-->
<artifactId>org.wso2.carbon.analytics.api</artifactId> <!-- <artifactId>org.wso2.carbon.analytics.api</artifactId>-->
<scope>provided</scope> <!-- <scope>provided</scope>-->
</dependency> <!-- </dependency>-->
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId> <artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
@ -223,6 +227,80 @@
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId> <artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle</artifactId>
<version>3.0.0-milestone2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-bundle-jaxrs</artifactId>
<scope>provided</scope>
<version>${cxf-bundle-package.version}</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-core</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-jaxrs</artifactId>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-jaxb-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.orbit.com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>javax.ws.rs-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
</dependencies> </dependencies>
<build> <build>
<plugins> <plugins>

@ -54,7 +54,8 @@ import javax.ws.rs.core.Response;
name = "Enroll device", name = "Enroll device",
description = "", description = "",
key = "perm:firealarm:enroll", key = "perm:firealarm:enroll",
permissions = {"/device-mgt/devices/enroll/firealarm"} permissions = {"/device-mgt/devices/enroll/firealarm"},
roles = {"Internal/devicemgt-user"}
) )
} }
) )

@ -18,24 +18,24 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl; package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.commons.SortType;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.*; import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.exceptions.InvalidDeviceException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants; import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException; import org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException;
import org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation;
import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation; import org.wso2.carbon.device.mgt.core.operation.mgt.ConfigOperation;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dao.DeviceEventsDAO;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dao.DeviceEventsDAOImpl;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipArchive;
@ -49,23 +49,11 @@ import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.Consumes; import javax.ws.rs.*;
import javax.ws.rs.FormParam;
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.Response; import javax.ws.rs.core.Response;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.*;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.UUID;
public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService { public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
@ -135,26 +123,16 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
@Produces("application/json") @Produces("application/json")
public Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, public Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) { @QueryParam("to") long to) {
String fromDate = String.valueOf(from*1000); // converting time to ms
String toDate = String.valueOf(to*1000); // converting time to ms
String query = "meta_deviceId:" + deviceId + " AND meta_deviceType:" +
VirtualFireAlarmConstants.DEVICE_TYPE + " AND meta_time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = VirtualFireAlarmConstants.TEMPERATURE_EVENT_TABLE;
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized( if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE), new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) { DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
List<SortByField> sortByFields = new ArrayList<>(); DeviceEventsDAO eventsDAO = new DeviceEventsDAOImpl();
SortByField sortByField = new SortByField("meta_time", SortType.ASC); SensorRecord sensorRecord = eventsDAO.getStats(deviceId, from, to);
sortByFields.add(sortByField); return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecord).build();
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) { } catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e); log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
@ -247,6 +225,8 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantAdminDomainName); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(tenantAdminDomainName);
PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(adminUsername); PrivilegedCarbonContext.getThreadLocalCarbonContext().setUsername(adminUsername);
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true, VirtualFireAlarmConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true,
@ -256,10 +236,21 @@ public class VirtualFireAlarmServiceImpl implements VirtualFireAlarmService {
} }
} }
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = " device_" + deviceId;
String deviceType = sketchType.replace(" ", "");
String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
StringBuilder scopes = new StringBuilder("device:" + deviceType + ":" + deviceId);
// add scopes for event publishing
scopes.append(" perm:topic:pub:" + tenantDomain + ":" + deviceType + ":" + deviceId + ":temperature");
// add scopes for retrieve operation topic /tenantDomain/deviceType/deviceId/operation/#
scopes.append(" perm:topic:sub:" + tenantDomain + ":" + deviceType + ":" + deviceId + ":operation");
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, apiApplicationKey.getConsumerSecret(), owner,
scopes); scopes.toString());
String accessToken = accessTokenInfo.getAccessToken(); String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken(); String refreshToken = accessTokenInfo.getRefreshToken();
XmppAccount newXmppAccount = new XmppAccount(); XmppAccount newXmppAccount = new XmppAccount();

@ -30,7 +30,7 @@ public class VirtualFireAlarmConstants {
public static final String POLICY_CONTEXT = "POLICY"; public static final String POLICY_CONTEXT = "POLICY";
//sensor events sumerized table name for temperature //sensor events sumerized table name for temperature
public static final String TEMPERATURE_EVENT_TABLE = "IOT_PER_DEVICE_STREAM_VIRTUALFIREALARM_TEMPERATURE"; // public static final String TEMPERATURE_EVENT_TABLE = "IOT_PER_DEVICE_STREAM_VIRTUALFIREALARM_TEMPERATURE";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super"; public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants //mqtt tranport related constants

@ -0,0 +1,27 @@
/*
* Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
*
* Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
*
* Licensed under the Entgra Commercial License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://entgra.io/licenses/entgra-commercial/1.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.virtualfirealarm.service.impl.dao;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
public interface DeviceEventsDAO {
SensorRecord getStats(String deviceId, long fromTime, long toTime);
}

@ -0,0 +1,120 @@
/*
* Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
*
* Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
*
* Licensed under the Entgra Commercial License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://entgra.io/licenses/entgra-commercial/1.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.virtualfirealarm.service.impl.dao;
import org.wso2.carbon.device.mgt.common.exceptions.*;
import org.wso2.carbon.device.mgt.core.dao.util.*;
public class DeviceEventsDAOFactory {
private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(DeviceEventsDAOFactory.class);
private static javax.sql.DataSource dataSource;
private static String databaseEngine;
private static final ThreadLocal<java.sql.Connection> currentConnection = new ThreadLocal<>();
public static void init(String jndiName) {
dataSource = DeviceManagementDAOUtil.lookupDataSource(jndiName, null);
try {
databaseEngine = dataSource.getConnection().getMetaData().getDatabaseProductName();
} catch (java.sql.SQLException e) {
log.error("Error occurred while retrieving config.datasource connection", e);
}
}
public static DeviceEventsDAO getDeviceEventDao() {
return new DeviceEventsDAOImpl();
}
public static void openDBConnection() throws DBConnectionException {
java.sql.Connection conn = currentConnection.get();
if (conn != null) {
throw new IllegalTransactionStateException("Database connection has already been obtained.");
}
try {
conn = dataSource.getConnection();
} catch (java.sql.SQLException e) {
throw new DBConnectionException("Failed to get a database connection.", e);
}
currentConnection.set(conn);
}
public static void beginTransaction() throws DBConnectionException {
try {
java.sql.Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (java.sql.SQLException e) {
throw new DBConnectionException("Error occurred while retrieving datasource connection", e);
}
}
public static java.sql.Connection getConnection() throws DBConnectionException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (java.sql.SQLException e) {
throw new DBConnectionException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws DBConnectionException {
try {
java.sql.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 (java.sql.SQLException e) {
throw new DBConnectionException("Error occurred while committing the transaction", e);
}
}
public static void closeConnection() {
java.sql.Connection conn = currentConnection.get();
try {
if (conn != null) {
conn.close();
}
} catch (java.sql.SQLException e) {
log.error("Error occurred while close the connection");
}
currentConnection.remove();
}
public static void rollbackTransaction() {
java.sql.Connection conn = currentConnection.get();
if (conn == null) {
throw new org.wso2.carbon.device.mgt.common.exceptions.IllegalTransactionStateException("Database connection is not active. Hence, rollback is "
+ "not attempted.");
}
try {
conn.rollback();
} catch (java.sql.SQLException e) {
log.warn("Error occurred while roll-backing the transaction", e);
}
}
}

@ -0,0 +1,77 @@
/*
* Copyright (C) 2018 - 2023 Entgra (Pvt) Ltd, Inc - All Rights Reserved.
*
* Unauthorised copying/redistribution of this file, via any medium is strictly prohibited.
*
* Licensed under the Entgra Commercial License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://entgra.io/licenses/entgra-commercial/1.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.virtualfirealarm.service.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.common.exceptions.*;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Implements MobileDeviceDAO for Android Devices.
*/
public class DeviceEventsDAOImpl implements DeviceEventsDAO {
private static final Log log = LogFactory.getLog(DeviceEventsDAOImpl.class);
@Override
public SensorRecord getStats(String deviceId, long fromTime, long toTime) {
String sql = "SELECT * FROM TABLE_VIRTUALFIREALARM_CARBONSUPER_RDBMS_PUBLISHER WHERE " +
"META_DEVICEID = ? AND " +
"META_TIME >= ? AND " +
"META_TIME <= ? " +
"ORDER BY META_TIME ASC";
Map<Long, Float> stats = new LinkedHashMap<>();
try {
DeviceEventsDAOFactory.init("jdbc/EVENT_DB");
Connection conn = DeviceEventsDAOFactory.getConnection();
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, deviceId);
stmt.setLong(2, fromTime);
stmt.setLong(3, toTime);
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
stats.put(rs.getLong("META_TIME"), rs.getFloat("TEMPERATURE"));
}
}
} catch (SQLException e) {
String msg = "Error occurred while retrieving device details";
log.error(msg);
}
} catch (DBConnectionException e) {
String msg = "Error occurred while obtaining DB connection to retrieve device details";
log.error(msg);
}
// stats.entrySet()
// .stream()
// .sorted(Map.Entry.<Long, Float>comparingByKey())
// .forEach(System.out::println);
return new SensorRecord(stats);
}
}

@ -11,58 +11,23 @@ import java.util.Map;
@XmlRootElement @XmlRootElement
/** /**
* This stores sensor event data for android sense. * This stores sensor event data for virtual fire alarm sense.
*/ */
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
public class SensorRecord { public class SensorRecord {
@XmlElementWrapper(required = true, name = "values") @XmlElementWrapper(required = true, name = "stats")
private Map<String, Object> values; private Map<Long, Float> stats;
/** The id. */ public Map<Long, Float> getStats() {
@XmlElement(required = false, name = "id") return stats;
private String id;
/**
* Gets the values.
* @return the values
*/
public Map<String, Object> getValues() {
return values;
}
/**
* Sets the values.
* @param values the values
*/
public void setValues(Map<String, Object> values) {
this.values = values;
}
/**
* Sets the id.
* @param id the new id
*/
public void setId(String id) {
this.id = id;
}
/**
* Gets the id.
* @return the id
*/
public String getId() {
return id;
} }
@Override public void setStats(Map<Long, Float> stats) {
public String toString(){ this.stats = stats;
List<String> valueList = new ArrayList<String>();
for (Map.Entry<String, Object> entry : values.entrySet()) {
valueList.add(entry.getKey() + ":" + entry.getValue());
} }
return valueList.toString();
public SensorRecord(Map<Long, Float> stats) {
this.stats = stats;
} }
} }

@ -2,27 +2,13 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.api.AnalyticsDataAPIUtil;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.Record;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.CarbonContext;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationService;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfigurationManagementService;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService; import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService; import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/** /**
* This class provides utility functions used by REST-API. * This class provides utility functions used by REST-API.
*/ */
@ -52,81 +38,6 @@ public class APIUtil {
return deviceManagementProviderService; return deviceManagementProviderService;
} }
public static AnalyticsDataAPI getAnalyticsDataAPI() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
AnalyticsDataAPI analyticsDataAPI =
(AnalyticsDataAPI) ctx.getOSGiService(AnalyticsDataAPI.class, null);
if (analyticsDataAPI == null) {
String msg = "Analytics api service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return analyticsDataAPI;
}
public static List<SensorRecord> getAllEventsForDevice(String tableName, String query,
List<SortByField> sortByFields) throws AnalyticsException {
int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
AnalyticsDataAPI analyticsDataAPI = getAnalyticsDataAPI();
int eventCount = analyticsDataAPI.searchCount(tenantId, tableName, query);
if (eventCount == 0) {
return null;
}
List<SearchResultEntry> resultEntries = analyticsDataAPI.search(tenantId, tableName, query, 0, eventCount,
sortByFields);
List<String> recordIds = getRecordIds(resultEntries);
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataAPIUtil.listRecords(
analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData;
}
private static List<String> getRecordIds(List<SearchResultEntry> searchResults) {
List<String> ids = new ArrayList<>();
for (SearchResultEntry searchResult : searchResults) {
ids.add(searchResult.getId());
}
return ids;
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
List<SearchResultEntry> searchResults) {
List<SensorRecord> sortedRecords = new ArrayList<>();
for (SearchResultEntry searchResultEntry : searchResults) {
sortedRecords.add(sensorDatas.get(searchResultEntry.getId()));
}
return sortedRecords;
}
/**
* Creates the SensorDatas from records.
*
* @param records the records
* @return the Map of SensorRecord <id, SensorRecord>
*/
public static Map<String, SensorRecord> createSensorData(List<Record> records) {
Map<String, SensorRecord> sensorDatas = new HashMap<>();
for (Record record : records) {
SensorRecord sensorData = createSensorData(record);
sensorDatas.put(sensorData.getId(), sensorData);
}
return sensorDatas;
}
/**
* Create a SensorRecord object out of a Record object
*
* @param record the record object
* @return SensorRecord object
*/
public static SensorRecord createSensorData(Record record) {
SensorRecord recordBean = new SensorRecord();
recordBean.setId(record.getId());
recordBean.setValues(record.getValues());
return recordBean;
}
public static APIManagementProviderService getAPIManagementProviderService() { public static APIManagementProviderService getAPIManagementProviderService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
APIManagementProviderService apiManagementProviderService = APIManagementProviderService apiManagementProviderService =

@ -25,7 +25,7 @@ import org.apache.commons.logging.LogFactory;
import org.json.JSONObject; import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants; import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import org.wso2.carbon.core.util.Utils; import org.wso2.carbon.core.util.Utils;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.exceptions.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationEntry;
import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException; import org.wso2.carbon.device.mgt.common.configuration.mgt.ConfigurationManagementException;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration; import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
@ -72,7 +72,7 @@ public class ZipUtil {
String iotServerIP; String iotServerIP;
try { try {
iotServerIP = getServerUrl(); iotServerIP = "127.0.0.1"; //getServerUrl();
String httpsServerEP = Utils.replaceSystemProperty(HTTPS_PROTOCOL_URL); String httpsServerEP = Utils.replaceSystemProperty(HTTPS_PROTOCOL_URL);
String httpServerEP = Utils.replaceSystemProperty(HTTP_PROTOCOL_URL); String httpServerEP = Utils.replaceSystemProperty(HTTP_PROTOCOL_URL);
String mqttEndpoint = Utils.replaceSystemProperty(DEFAULT_MQTT_ENDPOINT); String mqttEndpoint = Utils.replaceSystemProperty(DEFAULT_MQTT_ENDPOINT);

@ -29,5 +29,5 @@
Tomcat environment is the default and every webapps gets it even if they didn't specify it. Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF. e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
--> -->
<Environments>CXF,Carbon</Environments> <Environments>CXF3,Carbon</Environments>
</Classloading> </Classloading>

@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-types</artifactId>
<version>6.0.16-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>virtual-fire-alarm-plugin</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - Virtual Fire Alarm Plugin</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl</module>
<module>org.wso2.carbon.device.mgt.iot.virtualfirealarm.api</module>
</modules>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-scr-plugin</artifactId>
<version>1.7.2</version>
<executions>
<execution>
<id>generate-scr-scrdescriptor</id>
<goals>
<goal>scr</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>carbon-device-mgt-plugins-parent</artifactId>
<version>6.0.16-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>device-types-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - Device Management IoT Plugins Feature</name>
<url>http://wso2.org</url>
<modules>
<module>virtual-fire-alarm-plugin-feature</module>
</modules>
</project>

@ -0,0 +1,157 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>virtual-fire-alarm-plugin-feature</artifactId>
<version>6.0.16-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend.feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server VirtualFireAlarm Backend Feature</name>
<url>http://wso2.org</url>
<description>This feature contains the VirtualFireAlarm Device type specific backend implementations for the IoT Server
</description>
<!-- <properties>-->
<!-- <orbit.h2.version>1.4.199.wso2v1</orbit.h2.version>-->
<!-- </properties>-->
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.orbit.com.h2database</groupId>
<artifactId>h2</artifactId>
<version>${orbit.h2.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-jaxrs-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.api
</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/webapps/</outputDirectory>
<destFileName>virtual_firealarm.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-agent-jar</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl
</artifactId>
<overWrite>true</overWrite>
<outputDirectory>${project.build.directory}/maven-shared-archive-resources/agent/</outputDirectory>
<destFileName>wso2-firealarm-virtual-agent.jar</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<version>${carbon.p2.plugin.version}</version>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:true</propertyDef>
</properties>
</adviceFile>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,34 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
#[Device-Configurations]
tenantDomain=${TENANT_DOMAIN}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
application-key=${API_APPLICATION_KEY}
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15
xmpp-server-name=${SERVER_NAME}
server-jid=${SERVER_JID}

@ -0,0 +1,7 @@
@echo off
echo.
echo.WSO2 IOT Sample
echo.Virtual Fire Alarm
echo.initializing agent
echo.
java -jar wso2-firealarm-virtual-agent.jar

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

@ -0,0 +1,58 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<DeviceTypeConfiguration name="virtual_firealarm">
<Features>
<Feature code="buzz">
<Name>Control buzzer</Name>
<Description>Control buzzer on Virtual Firealarm</Description>
<Operation context="/virtual_firealarm/device/{deviceId}/buzz" method="POST">
</Operation>
</Feature>
</Features>
<ProvisioningConfig>
<SharedWithAllTenants>true</SharedWithAllTenants>
</ProvisioningConfig>
<PushNotificationProviderConfig type="MQTT">
<FileBasedProperties>true</FileBasedProperties>
</PushNotificationProviderConfig>
<!--<PushNotificationProviderConfig type="XMPP">-->
<!--<FileBasedProperties>true</FileBasedProperties>-->
<!--&lt;!&ndash;if file based properties is set to false then the configuration will be picked from platform configuration&ndash;&gt;-->
<!--<ConfigProperties>-->
<!--<Property Name="xmpp.adapter.name">virtualfirealarm.xmpp.adapter</Property>-->
<!--<Property Name="host">localhost</Property>-->
<!--<Property Name="port">5222</Property>-->
<!--<Property Name="username">admin</Property>-->
<!--<Property Name="password">admin</Property>-->
<!--<Property Name="jid">admin@localhost</Property>-->
<!--<Property Name="server.name">localhost</Property>-->
<!--</ConfigProperties>-->
<!--</PushNotificationProviderConfig>-->
<License>
<Language>en_US</Language>
<Version>1.0.0</Version>
<Text>This is license text</Text>
</License>
</DeviceTypeConfiguration>

@ -0,0 +1,16 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend_${feature.version}/webapps/,target:${installFolder}/../../../repository/deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/deployment/server/devicetypes/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend_${feature.version}/devicetypes/,target:${installFolder}/../../../repository/deployment/server/devicetypes/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend_${feature.version}/receiver/,target:${installFolder}/../../../repository/deployment/server/eventreceivers/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend_${feature.version}/streams/,target:${installFolder}/../../../repository/deployment/server/eventstreams/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend_${feature.version}/publisher/,target:${installFolder}/../../../repository/deployment/server/eventpublishers/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../../repository/resources/sketches/virtual_firealarm/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend_${feature.version}/agent/,target:${installFolder}/../../../repository/resources/sketches/virtual_firealarm/,overwrite:true);\
instructions.unconfigure = \
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/webapps/virtual_firealarm.war);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/webapps/virtual_firealarm);\
org.eclipse.equinox.p2.touchpoint.natives.remove(path:${installFolder}/../../../repository/deployment/server/devicetypes/virtual_firealarm.xml);\

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<eventPublisher name="virtual_firealarm_rdbms_publisher-carbon.super" processing="enable"
statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventpublisher">
<from streamName="iot.per.device.stream.virtualfirealarm" version="1.0.0"/>
<mapping customMapping="disable" type="map"/>
<to eventAdapterType="rdbms">
<property name="datasource.name">EVENT_DB</property>
<property name="table.name">table_virtualfirealarm_carbonsuper_rdbms_publisher</property>
<property name="execution.mode">insert</property>
</to>
</eventPublisher>

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<eventReceiver name="virtualfirealarm_receiver-carbon.super" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt">
<property name="contentTransformer"/>
<property name="topic">carbon.super/virtual_firealarm/+/temperature</property>
<property name="contentValidator">default</property>
<property name="cleanSession">true</property>
</from>
<mapping customMapping="disable" type="json"/>
<to streamName="iot.per.device.stream.virtualfirealarm" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,16 @@
{
"name": "iot.per.device.stream.virtualfirealarm",
"version": "1.0.0",
"nickName": "virtual_firealarm",
"description": "Temperature data received from the virtual_firealarm",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"TIMESTAMP"}
],
"payloadData": [
{
"name": "temperature","type": "FLOAT"
}
]
}

@ -0,0 +1,39 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>device-types-feature</artifactId>
<version>6.0.16-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>virtual-fire-alarm-plugin-feature</artifactId>
<packaging>pom</packaging>
<name>WSO2 Carbon - IoT Server VirtualFireAlarm Device Feature</name>
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.virtualfirealarm.backend.feature</module>
</modules>
</project>

@ -37,10 +37,12 @@
<modules> <modules>
<module>components/extensions</module> <module>components/extensions</module>
<module>components/mobile-plugins</module> <module>components/mobile-plugins</module>
<module>components/device-types</module>
<!--<module>components/test-coverage</module>--> <!--<module>components/test-coverage</module>-->
<module>features/analytics-feature</module> <module>features/analytics-feature</module>
<module>features/mobile-plugins-feature</module> <module>features/mobile-plugins-feature</module>
<module>features/extensions-feature</module> <module>features/extensions-feature</module>
<module>features/device-types-feature</module>
</modules> </modules>
<dependencyManagement> <dependencyManagement>
@ -491,6 +493,16 @@
<artifactId>org.wso2.carbon.device.mgt.mobile.android.api</artifactId> <artifactId>org.wso2.carbon.device.mgt.mobile.android.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version> <version>${carbon.devicemgt.plugins.version}</version>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.api</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.impl</artifactId>
<version>${carbon.devicemgt.plugins.version}</version>
</dependency>
<!-- AppM dependencies --> <!-- AppM dependencies -->
<dependency> <dependency>

Loading…
Cancel
Save