code refactoring

application-manager-new
GPrathap 9 years ago
parent d712d07c80
commit 4a7beac606

@ -19,23 +19,19 @@
package org.homeautomation.droneanalyzer.api;
import org.homeautomation.droneanalyzer.api.dto.DeviceJSON;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.DELETE;
import javax.ws.rs.QueryParam;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@ -95,7 +91,7 @@ public interface DroneAnalyzerService {
/**
* To get device information
* @param deviceId unique identifier for given device type instance
* @return
* @return return Device object which carries all information related to a managed device
*/
@Path("/device/{device_id}")
@GET

@ -18,16 +18,14 @@
package org.homeautomation.droneanalyzer.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.dto.DeviceJSON;
import org.homeautomation.droneanalyzer.api.dto.SensorRecord;
import org.homeautomation.droneanalyzer.api.util.APIUtil;
import org.homeautomation.droneanalyzer.api.util.ZipUtil;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.api.DroneAnalyzerService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.analytics.dataservice.commons.SORT;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
@ -42,36 +40,31 @@ import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Path;
import javax.ws.rs.Consumes;
import javax.ws.rs.PathParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Consumes;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;
import javax.ws.rs.Path;
import javax.ws.rs.DELETE;
import javax.ws.rs.QueryParam;
import javax.ws.rs.PUT;
import javax.ws.rs.DELETE;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@ -85,7 +78,7 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
private static final String KEY_TYPE = "PRODUCTION";
private static Log log = LogFactory.getLog(DroneAnalyzerService.class);
private static ApiApplicationKey apiApplicationKey;
private static volatile ApiApplicationKey apiApplicationKey;
private ConcurrentHashMap<String, DeviceJSON> deviceToIpMap = new ConcurrentHashMap<>();
private static String shortUUID() {
@ -112,10 +105,11 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
/**
* Retrieve Sensor data for the given time period
*
* @param deviceId unique identifier for given device type instance
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
* @param from starting time
* @param to ending time
* @return response with List<SensorRecord> object which includes sensor data which is requested
*/
@Path("device/stats/{deviceId}")
@GET
@ -125,21 +119,20 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
@QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String query = "meta_deviceId:" + deviceId + " AND meta_deviceType:" +
DroneAnalyzerConstants.DEVICE_TYPE + " AND meta_time : [" + fromDate + " TO " + toDate + "]";
String query = DroneAnalyzerConstants.DEVICE_META_INFO_DEVICE_ID + deviceId + " AND "
+ DroneAnalyzerConstants.DEVICE_META_INFO_DEVICE_TYPE + DroneAnalyzerConstants.DEVICE_TYPE + " AND "
+ DroneAnalyzerConstants.DEVICE_META_INFO_TIME + ":[" + fromDate + " TO " + toDate + "]";
String sensorTableName = DroneAnalyzerConstants.SENSOR_EVENT_TABLE;
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
DroneAnalyzerConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
if (sensorTableName != null) {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("meta_time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
}
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField(DroneAnalyzerConstants.DEVICE_META_INFO_TIME, SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
@ -148,12 +141,12 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
return Response.status(Response.Status.BAD_REQUEST).build();
}
/**
* Remove device type instance using device id
* @param deviceId unique identifier for given device type instance
*
* @param deviceId unique identifier for given device type instance
*/
@Path("/device/{device_id}")
@DELETE
@ -183,8 +176,9 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
/**
* Update device instance name
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
*
* @param deviceId unique identifier for given device type instance
* @param name new name for the device type instance
*/
@Path("/device/{device_id}")
@PUT
@ -218,8 +212,9 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
/**
* To get device information
* @param deviceId unique identifier for given device type instance
* @return
*
* @param deviceId unique identifier for given device type instance
* @return return Device object which carries all information related to a managed device
*/
@Path("/device/{device_id}")
@GET
@ -246,7 +241,8 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
/**
* Get all device type instance which belongs to user
* @return Array of devices which includes device's information
*
* @return Array of devices which includes device's information
*/
@Path("/devices")
@GET
@ -256,14 +252,14 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
try {
List<Device> userDevices =
APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforFirealarm = new ArrayList<>();
ArrayList<Device> userDevicesforDrone = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DroneAnalyzerConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforFirealarm.add(device);
userDevicesforDrone.add(device);
}
}
Device[] devices = userDevicesforFirealarm.toArray(new Device[]{});
Device[] devices = userDevicesforDrone.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
@ -273,9 +269,10 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
/**
* To download device type agent source code as zip file
* @param deviceName name for the device type instance
* @param sketchType folder name where device type agent was installed into server
* @return Agent source code as zip file
*
* @param deviceName name for the device type instance
* @param sketchType folder name where device type agent was installed into server
* @return Agent source code as zip file
*/
@Path("/device/download")
@GET
@ -288,33 +285,39 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
response.status(Response.Status.OK);
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
Response resp = response.build();
zipFile.getZipFile().delete();
return resp;
Response requestedFile = response.build();
File file = zipFile.getZipFile();
if (!file.delete()) {
String message = file.exists() ? "is in use by another process" : "does not exist";
throw new IOException("Cannot delete file, because file " + message + ".");
} else {
return requestedFile;
}
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (IOException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
log.error(ex.getMessage(), ex);
return Response.status(500).entity(ex.getMessage()).build();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
}
}
/**
* Register device into device management service
*
* @param deviceId unique identifier for given device type instance
* @param name name for the device type instance
* @param name name for the device type instance
* @return check whether device is installed into cdmf
*/
private boolean register(String deviceId, String name) {
@ -362,9 +365,11 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
DroneAnalyzerConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + DroneAnalyzerConstants.DEVICE_TYPE + " device_" + deviceId;
String scopes = DroneAnalyzerConstants.DEVICE_SCOPE_INFO_DEVICE_TYPE + DroneAnalyzerConstants.DEVICE_TYPE
+ DroneAnalyzerConstants.DEVICE_SCOPE_INFO_DEVICE_ID + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain()
, scopes);
//create token
String accessToken = accessTokenInfo.getAccessToken();
@ -375,8 +380,7 @@ public class DroneAnalyzerServiceImpl implements DroneAnalyzerService {
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
return ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);
return zipFile;
}
}

@ -19,6 +19,7 @@
package org.homeautomation.droneanalyzer.api.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@ -32,6 +33,4 @@ public class DeviceJSON {
public String owner;
@XmlElement(required = true)
public String deviceId;
@XmlElement(required = true)
public Float sensorValue;
}

@ -45,6 +45,7 @@ public class SensorRecord {
/**
* Gets the values.
*
* @return the values
*/
public Map<String, Object> getValues() {
@ -53,6 +54,7 @@ public class SensorRecord {
/**
* Sets the values.
*
* @param values the values
*/
public void setValues(Map<String, Object> values) {
@ -61,6 +63,7 @@ public class SensorRecord {
/**
* Gets the id.
*
* @return the id
*/
public String getId() {
@ -69,6 +72,7 @@ public class SensorRecord {
/**
* Sets the id.
*
* @param id the new id
*/
public void setId(String id) {

@ -1,13 +1,13 @@
package org.homeautomation.droneanalyzer.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.api.dto.SensorRecord;
import org.wso2.carbon.event.output.adapter.core.OutputEventAdapterService;
import org.wso2.carbon.analytics.api.AnalyticsDataAPI;
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
import org.wso2.carbon.analytics.dataservice.commons.AnalyticsDataResponse;
import org.wso2.carbon.analytics.dataservice.commons.SearchResultEntry;
import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.dataservice.core.AnalyticsDataServiceUtils;
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;
@ -18,15 +18,13 @@ import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.identity.jwt.client.extension.service.JWTClientManagerService;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.user.core.Permission;
import org.wso2.carbon.user.core.service.RealmService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;
/**
* This class provides utility functions used by REST-API.
@ -108,17 +106,15 @@ public class APIUtil {
}
public static void registerApiAccessRoles(String user) {
UserStoreManager userStoreManager = null;
UserStoreManager userStoreManager;
try {
userStoreManager = getUserStoreManager();
String[] userList = new String[]{user};
if (userStoreManager != null) {
String rolesOfUser[] = userStoreManager.getRoleListOfUser(user);
if (!userStoreManager.isExistingRole(Constants.DEFAULT_ROLE_NAME)) {
userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, Constants.DEFAULT_PERMISSION);
} else if (rolesOfUser != null && Arrays.asList(rolesOfUser).contains(Constants.DEFAULT_ROLE_NAME)) {
return;
} else {
userStoreManager.addRole(Constants.DEFAULT_ROLE_NAME, userList, getDefaultPermissions());
} else if (rolesOfUser == null) {
userStoreManager.updateUserListOfRole(Constants.DEFAULT_ROLE_NAME, new String[0], userList);
}
}
@ -153,8 +149,7 @@ public class APIUtil {
AnalyticsDataResponse response = analyticsDataAPI.get(tenantId, tableName, 1, null, recordIds);
Map<String, SensorRecord> sensorDatas = createSensorData(AnalyticsDataServiceUtils.listRecords(
analyticsDataAPI, response));
List<SensorRecord> sortedSensorData = getSortedSensorData(sensorDatas, resultEntries);
return sortedSensorData;
return getSortedSensorData(sensorDatas, resultEntries);
}
public static List<SensorRecord> getSortedSensorData(Map<String, SensorRecord> sensorDatas,
@ -207,15 +202,8 @@ public class APIUtil {
return threadLocalCarbonContext.getTenantDomain();
}
public static OutputEventAdapterService getOutputEventAdapterService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
OutputEventAdapterService outputEventAdapterService =
(OutputEventAdapterService) ctx.getOSGiService(OutputEventAdapterService.class, null);
if (outputEventAdapterService == null) {
String msg = "Device Authorization service has not initialized.";
log.error(msg);
throw new IllegalStateException(msg);
}
return outputEventAdapterService;
public static Permission[] getDefaultPermissions() {
return new Permission[]{new org.wso2.carbon.user.core
.Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
}
}

@ -18,8 +18,6 @@
package org.homeautomation.droneanalyzer.api.util;
import org.wso2.carbon.user.core.Permission;
/**
* This hold the constants related to the device type.
*/
@ -27,6 +25,4 @@ public class Constants {
public static final String DEFAULT_PERMISSION_RESOURCE = "/permission/admin/device-mgt/drone/user";
public static final String DEFAULT_ROLE_NAME = "drone_user";
public static final Permission DEFAULT_PERMISSION[]
= new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE, "ui.execute")};
}

@ -1,108 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.util;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class ResponsePayload {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public static ResponsePayloadBuilder statusCode(int statusCode) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().statusCode(statusCode);
}
public static ResponsePayloadBuilder messageFromServer(
String messageFromServer) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().messageFromServer(messageFromServer);
}
public static ResponsePayloadBuilder responseContent(String responseContent) {
ResponsePayload message = new ResponsePayload();
return message.getBuilder().responseContent(responseContent);
}
@XmlElement
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@XmlElement
public String getMessageFromServer() {
return messageFromServer;
}
public void setMessageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
}
@XmlElement
public Object getResponseContent() {
return responseContent;
}
public void setResponseContent(Object responseContent) {
this.responseContent = responseContent;
}
private ResponsePayloadBuilder getBuilder() {
return new ResponsePayloadBuilder();
}
public class ResponsePayloadBuilder {
private int statusCode;
private String messageFromServer;
private Object responseContent;
public ResponsePayloadBuilder statusCode(int statusCode) {
this.statusCode = statusCode;
return this;
}
public ResponsePayloadBuilder messageFromServer(String messageFromServer) {
this.messageFromServer = messageFromServer;
return this;
}
public ResponsePayloadBuilder responseContent(String responseContent) {
this.responseContent = responseContent;
return this;
}
public ResponsePayload build() {
ResponsePayload payload = new ResponsePayload();
payload.setStatusCode(statusCode);
payload.setMessageFromServer(messageFromServer);
payload.setResponseContent(responseContent);
return payload;
}
}
}

@ -1,58 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.homeautomation.droneanalyzer.api.util;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.EventsPublisherService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
/**
* This can be used to publish data to DAS for given stream definition
*/
public class ServiceUtils {
private static final Log log = LogFactory.getLog(ServiceUtils.class);
/**
* Sensor data are published to DAS
*
* @param deviceId unique identifier of the device
* @param sensorValue current value of sensor which is set at agent side
* @return
*/
public static boolean publishToDAS(String deviceId, float sensorValue) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
EventsPublisherService deviceAnalyticsService = (EventsPublisherService) ctx.getOSGiService(
EventsPublisherService.class, null);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
Object metdaData[] = {owner, DroneAnalyzerConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadData[] = {sensorValue};
try {
deviceAnalyticsService.publishEvent(DroneAnalyzerConstants.SENSOR_STREAM_DEFINITION,
DroneAnalyzerConstants.SENSOR_STREAM_DEFINITION_VERSION, metdaData, new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
}
return true;
}
}

@ -19,7 +19,6 @@
package org.homeautomation.droneanalyzer.api.util;
import org.homeautomation.droneanalyzer.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
@ -58,12 +57,10 @@ public class ZipUtil {
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String apimEndpoint = httpsServerEP;
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
}
Map<String, String> contextParams = new HashMap<>();
contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser());
contextParams.put("DEVICE_OWNER", owner);
@ -71,7 +68,7 @@ public class ZipUtil {
contextParams.put("DEVICE_NAME", deviceName);
contextParams.put("HTTPS_EP", httpsServerEP);
contextParams.put("HTTP_EP", httpServerEP);
contextParams.put("APIM_EP", apimEndpoint);
contextParams.put("APIM_EP", httpsServerEP);
contextParams.put("MQTT_EP", mqttEndpoint);
contextParams.put("DEVICE_TOKEN", token);
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);

@ -19,6 +19,7 @@
package org.homeautomation.droneanalyzer.plugin.constants;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
/**
@ -29,29 +30,30 @@ public class DroneAnalyzerConstants {
public final static String DEVICE_TYPE = "drone";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "drone_DEVICE_ID";
public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF";
public final static String DEVICE_META_INFO_DEVICE_ID = "meta_deviceId:";
public final static String DEVICE_META_INFO_DEVICE_TYPE = "meta_deviceType:";
public final static String DEVICE_META_INFO_TIME = "meta_time";
public final static String DEVICE_SCOPE_INFO_DEVICE_TYPE = "device_type_";
public final static String DEVICE_SCOPE_INFO_DEVICE_ID = "device_";
//sensor events summerized table name
public static final String SENSOR_EVENT_TABLE = "ORG_WSO2_IOT_DEVICES_droneStats";
public static final String DATA_SOURCE_NAME = "jdbc/droneDM_DB";
public final static String DEVICE_TYPE_PROVIDER_DOMAIN = "carbon.super";
//mqtt tranport related constants
//mqtt transport related constants
public static final String MQTT_ADAPTER_NAME = "droneStats_mqtt";
public static final String MQTT_ADAPTER_TYPE = "oauth-mqtt";
public static final String ADAPTER_TOPIC_PROPERTY = "topic";
public static final String MQTT_PORT = "\\{mqtt.broker.port\\}";
public static final String MQTT_BROKER_HOST = "\\{mqtt.broker.host\\}";
public static final String CARBON_CONFIG_PORT_OFFSET = "Ports.Offset";
public static final String DEFAULT_CARBON_LOCAL_IP_PROPERTY = "carbon.local.ip";
public static final int CARBON_DEFAULT_PORT_OFFSET = 0;
public static final int DEFAULT_MQTT_PORT = 1883;
public static final String SUBSCRIBED_TOPIC = "carbon.super/drone/+/publisher";
public static final String CONTENT_TRANSFORMATION = "contentTransformer";
public static final String CONTENT_VALIDATION = "contentValidator";
public static final String RESOURCE = "resource";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
//dcr configuration properties
public static final String USERNAME_PROPERTY_KEY = "username";
public static final String DCR_PROPERTY_KEY = "dcrUrl";
public static final String BROKER_URL_PROPERTY_KEY = "url";
@ -59,12 +61,5 @@ public class DroneAnalyzerConstants {
public static final String QOS_PROPERTY_KEY = "qos";
public static final String CLIENT_ID_PROPERTY_KEY = "qos";
public static final String CLEAR_SESSION_PROPERTY_KEY = "clearSession";
public static final String TOPIC = "topic";
public final static String SENSOR_STREAM_DEFINITION = "org.wso2.iot.devices.droneStats";
public final static String SENSOR_STREAM_DEFINITION_VERSION = "1.0.0";
public static final String MQTT_CONFIG_LOCATION = CarbonUtils.getEtcCarbonConfigDirPath() + File.separator
+ "mqtt.properties";
}

@ -20,15 +20,10 @@ package org.homeautomation.droneanalyzer.plugin.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.impl.feature.DroneAnalyzerFeatureManager;
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.*;
import org.wso2.carbon.device.mgt.common.configuration.mgt.PlatformConfiguration;
import org.wso2.carbon.device.mgt.common.license.mgt.License;
import org.wso2.carbon.device.mgt.common.license.mgt.LicenseManagementException;

@ -19,19 +19,13 @@
package org.homeautomation.droneanalyzer.plugin.impl;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.DeviceManager;
import org.wso2.carbon.device.mgt.common.app.mgt.Application;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManagementException;
import org.wso2.carbon.device.mgt.common.ProvisioningConfig;
import org.wso2.carbon.device.mgt.common.app.mgt.ApplicationManager;
import org.wso2.carbon.device.mgt.common.operation.mgt.Operation;
import org.wso2.carbon.device.mgt.common.push.notification.PushNotificationConfig;
import org.wso2.carbon.device.mgt.common.spi.DeviceManagementService;
import java.util.List;
public class DroneAnalyzerManagerService implements DeviceManagementService {
private DeviceManager deviceManager;

@ -20,10 +20,9 @@ package org.homeautomation.droneanalyzer.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.impl.dao.impl.DroneAnalyzerDAOImpl;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.impl.DroneAnalyzerDAOImpl;
import javax.naming.Context;
import javax.naming.InitialContext;

@ -20,12 +20,10 @@ package org.homeautomation.droneanalyzer.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.dao.DroneAnalyzerDAO;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.wso2.carbon.device.mgt.common.Device;
import java.sql.Connection;
@ -33,9 +31,7 @@ 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 gg Devices.
@ -46,7 +42,7 @@ public class DroneAnalyzerDAOImpl {
private static final Log log = LogFactory.getLog(DroneAnalyzerDAOImpl.class);
public Device getDevice(String deviceId) throws DeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
Device iotDevice = null;
ResultSet resultSet = null;
@ -111,7 +107,7 @@ public class DroneAnalyzerDAOImpl {
public boolean updateDevice(Device device) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
@ -144,7 +140,7 @@ public class DroneAnalyzerDAOImpl {
public boolean deleteDevice(String deviceId) throws DeviceMgtPluginException {
boolean status = false;
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
try {
conn = DroneAnalyzerDAO.getConnection();
@ -171,11 +167,11 @@ public class DroneAnalyzerDAOImpl {
}
public List<Device> getAllDevices() throws DeviceMgtPluginException {
Connection conn = null;
Connection conn;
PreparedStatement stmt = null;
ResultSet resultSet = null;
Device device;
List<Device> iotDevices = new ArrayList<>();
List<Device> devices = new ArrayList<>();
try {
conn = DroneAnalyzerDAO.getConnection();
String selectDBQuery =
@ -189,11 +185,12 @@ public class DroneAnalyzerDAOImpl {
device.setName(resultSet.getString(DroneAnalyzerConstants.DEVICE_PLUGIN_DEVICE_NAME));
List<Device.Property> propertyList = new ArrayList<>();
device.setProperties(propertyList);
devices.add(device);
}
if (log.isDebugEnabled()) {
log.debug("All drone device details have fetched from drone database.");
}
return iotDevices;
return devices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all drone device data'";
log.error(msg, e);

@ -18,7 +18,6 @@
package org.homeautomation.droneanalyzer.plugin.impl.util;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.core.ServerStartupObserver;

@ -18,11 +18,11 @@
package org.homeautomation.droneanalyzer.plugin.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.constants.DroneAnalyzerConstants;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.internal.DroneAnalyzerManagementDataHolder;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.Utils;
@ -42,7 +42,6 @@ import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
@ -110,10 +109,15 @@ public class DroneAnalyzerUtils {
MQTT_PORT = "\\$".concat(DroneAnalyzerConstants.MQTT_PORT);
}
urlWithPlaceholders = Utils.replaceSystemProperty(urlWithPlaceholders);
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_PORT, "" +
(DroneAnalyzerConstants.DEFAULT_MQTT_PORT + getPortOffset()));
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_BROKER_HOST,
System.getProperty(DroneAnalyzerConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
if(MQTT_PORT != null ){
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_PORT, "" +
(DroneAnalyzerConstants.DEFAULT_MQTT_PORT + getPortOffset()));
}
if(MQTT_BROKER_HOST != null ){
urlWithPlaceholders = urlWithPlaceholders.replaceAll(MQTT_BROKER_HOST,
System.getProperty(DroneAnalyzerConstants.DEFAULT_CARBON_LOCAL_IP_PROPERTY, "localhost"));
}
return urlWithPlaceholders;
}

@ -18,13 +18,12 @@
package org.homeautomation.droneanalyzer.plugin.internal;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerStartupListener;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.homeautomation.droneanalyzer.plugin.impl.DroneAnalyzerManagerService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.homeautomation.droneanalyzer.plugin.exception.DeviceMgtPluginException;
import org.homeautomation.droneanalyzer.plugin.impl.DroneAnalyzerManagerService;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerStartupListener;
import org.homeautomation.droneanalyzer.plugin.impl.util.DroneAnalyzerUtils;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.component.ComponentContext;

@ -29,7 +29,7 @@ function drawGraph_drone(from, to) {
populateGraph();
function populateGraph() {
if(streamIndex<4){
if (streamIndex < 4) {
retrieveDataAndDrawLineGraph(streams[streamIndex], from, to);
}
streamIndex++;
@ -48,11 +48,8 @@ function drawGraph_drone(from, to) {
if (graphMap[type]) {
return graphMap[type];
}
var chartWrapperElmId = "#drone-div-chart";
var graphWidth = $(chartWrapperElmId).width() - 50;
console.log("document.getElementById("+ document.getElementById("chart-" + type)+ " ---"+ type);
var graphConfig = {
element: document.getElementById("chart-" + type),
width: graphWidth,
@ -66,7 +63,6 @@ function drawGraph_drone(from, to) {
padding: {top: 0.2, left: 0.02, right: 0.02, bottom: 0.2},
series: []
};
if (devices) {
for (var i = 0; i < devices.length; i++) {
graphConfig['series'].push(
@ -119,15 +115,12 @@ function drawGraph_drone(from, to) {
});
}
}
var graph = new Rickshaw.Graph(graphConfig);
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
@ -136,17 +129,14 @@ function drawGraph_drone(from, to) {
height: 410
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById("slider-" + type)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById("legend-" + type)
});
var hoverDetail = new Rickshaw.Graph.HoverDetail({
graph: graph,
formatter: function (series, x, y) {
@ -157,22 +147,18 @@ function drawGraph_drone(from, to) {
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
}
});
var shelving = new Rickshaw.Graph.Behavior.Series.Toggle({
graph: graph,
legend: legend
});
var order = new Rickshaw.Graph.Behavior.Series.Order({
graph: graph,
legend: legend
});
var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight({
graph: graph,
legend: legend
});
graphMap[type] = {};
graphMap[type].graph = graph;
graphMap[type].config = graphConfig;

@ -11,12 +11,7 @@
{{/zone}}
{{#zone "device-opetations"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<div class="add-margin-top-4x">
{{unit "iot.unit.device.operation-bar" device=device backendApiUri=backendApiUri autoCompleteParams=autoCompleteParams}}
</div>
{{/zone}}
{{#zone "device-detail-properties"}}
@ -27,8 +22,6 @@
data-toggle="tab" aria-controls="device_statistics">Device
Statistics</a>
</li>
<li><a class="list-group-item" href="#event_log" role="tab" data-toggle="tab"
aria-controls="event_log">Operations Log</a></li>
</ul>
</div>
<div class="media-body add-padding-left-5x remove-padding-xs tab-content">
@ -39,29 +32,6 @@
<div class="panel-heading">Device Statistics</div>
{{unit "cdmf.unit.device.type.drone.realtime.analytics-view" device=device}}
</div>
<div class="panel panel-default tab-pane" id="event_log" role="tabpanel"
aria-labelledby="event_log">
<div class="panel-heading">Operations Log <span><a href="#"
id="refresh-operations"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="operations-spinner" class="wr-advance-operations-init hidden">
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<i class="fw fw-settings fw-spin fw-2x"></i>
&nbsp;&nbsp;&nbsp;
Loading Operations Log . . .
<br>
<br>
</div>
<div id="operations-log-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
</div>
</div>
</div>

@ -1,110 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var ws;
var graph;
var chartData = [];
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
$(window).load(function () {
var tNow = new Date().getTime() / 1000;
for (var i = 0; i < 30; i++) {
chartData.push({
x: tNow - (30 - i) * 15,
y: parseFloat(0)
});
}
graph = new Rickshaw.Graph({
element: document.getElementById("chart"),
width: $("#div-chart").width() - 50,
height: 300,
renderer: "line",
padding: {top: 0.2, left: 0.0, right: 0.0, bottom: 0.2},
xScale: d3.time.scale(),
series: [{
'color': palette.color(),
'data': chartData,
'name': "Temperature"
}]
});
graph.render();
var xAxis = new Rickshaw.Graph.Axis.Time({
graph: graph
});
xAxis.render();
new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
height: 300,
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis')
});
new Rickshaw.Graph.HoverDetail({
graph: graph,
formatter: function (series, x, y) {
var date = '<span class="date">' + moment.unix(x*1000).format('Do MMM YYYY h:mm:ss a') + '</span>';
var swatch = '<span class="detail_swatch" style="background-color: ' + series.color + '"></span>';
return swatch + series.name + ": " + parseInt(y) + '<br>' + date;
}
});
var websocketUrl = $("#div-chart").data("websocketurl");
connect(websocketUrl)
});
$(window).unload(function () {
disconnect();
});
//websocket connection
function connect(target) {
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
console.log('WebSocket is not supported by this browser.');
}
if (ws) {
ws.onmessage = function (event) {
var dataPoint = JSON.parse(event.data);
/*var dataPoint = JSON.parse(event.data);
chartData.push({
x: parseInt(dataPoint[4]) / 1000,
y: parseFloat(dataPoint[5])
});
chartData.shift();
graph.update();*/
};
}
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
}

@ -1,21 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var ajax_handler = new ajax_handler();
var config_api = new config_api();
var plotting = new plotting();
var object_maker = new object_maker();

@ -1,357 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
// VERSION: 2.3 LAST UPDATE: 11.07.2013
/*
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*
* Made by Wilq32, wilq32@gmail.com, Wroclaw, Poland, 01.2009
* Website: http://jqueryrotate.com
*/
(function($) {
var supportedCSS,supportedCSSOrigin, styles=document.getElementsByTagName("head")[0].style,toCheck="transformProperty WebkitTransform OTransform msTransform MozTransform".split(" ");
for (var a = 0; a < toCheck.length; a++) if (styles[toCheck[a]] !== undefined) { supportedCSS = toCheck[a]; }
if (supportedCSS) {
supportedCSSOrigin = supportedCSS.replace(/[tT]ransform/,"TransformOrigin");
if (supportedCSSOrigin[0] == "T") supportedCSSOrigin[0] = "t";
}
// Bad eval to preven google closure to remove it from code o_O
eval('IE = "v"=="\v"');
jQuery.fn.extend({
rotate:function(parameters)
{
if (this.length===0||typeof parameters=="undefined") return;
if (typeof parameters=="number") parameters={angle:parameters};
var returned=[];
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (!element.Wilq32 || !element.Wilq32.PhotoEffect) {
var paramClone = $.extend(true, {}, parameters);
var newRotObject = new Wilq32.PhotoEffect(element,paramClone)._rootObj;
returned.push($(newRotObject));
}
else {
element.Wilq32.PhotoEffect._handleRotation(parameters);
}
}
return returned;
},
getRotateAngle: function(){
var ret = [];
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (element.Wilq32 && element.Wilq32.PhotoEffect) {
ret[i] = element.Wilq32.PhotoEffect._angle;
}
}
return ret;
},
stopRotate: function(){
for (var i=0,i0=this.length;i<i0;i++)
{
var element=this.get(i);
if (element.Wilq32 && element.Wilq32.PhotoEffect) {
clearTimeout(element.Wilq32.PhotoEffect._timer);
}
}
}
});
// Library agnostic interface
Wilq32=window.Wilq32||{};
Wilq32.PhotoEffect=(function(){
if (supportedCSS) {
return function(img,parameters){
img.Wilq32 = {
PhotoEffect: this
};
this._img = this._rootObj = this._eventObj = img;
this._handleRotation(parameters);
}
} else {
return function(img,parameters) {
this._img = img;
this._onLoadDelegate = [parameters];
this._rootObj=document.createElement('span');
this._rootObj.style.display="inline-block";
this._rootObj.Wilq32 =
{
PhotoEffect: this
};
img.parentNode.insertBefore(this._rootObj,img);
if (img.complete) {
this._Loader();
} else {
var self=this;
// TODO: Remove jQuery dependency
jQuery(this._img).bind("load", function(){ self._Loader(); });
}
}
}
})();
Wilq32.PhotoEffect.prototype = {
_setupParameters : function (parameters){
this._parameters = this._parameters || {};
if (typeof this._angle !== "number") { this._angle = 0 ; }
if (typeof parameters.angle==="number") { this._angle = parameters.angle; }
this._parameters.animateTo = (typeof parameters.animateTo === "number") ? (parameters.animateTo) : (this._angle);
this._parameters.step = parameters.step || this._parameters.step || null;
this._parameters.easing = parameters.easing || this._parameters.easing || this._defaultEasing;
this._parameters.duration = 'duration' in parameters ? parameters.duration : parameters.duration || this._parameters.duration || 1000;
this._parameters.callback = parameters.callback || this._parameters.callback || this._emptyFunction;
this._parameters.center = parameters.center || this._parameters.center || ["50%","50%"];
if (typeof this._parameters.center[0] == "string") {
this._rotationCenterX = (parseInt(this._parameters.center[0],10) / 100) * this._imgWidth * this._aspectW;
} else {
this._rotationCenterX = this._parameters.center[0];
}
if (typeof this._parameters.center[1] == "string") {
this._rotationCenterY = (parseInt(this._parameters.center[1],10) / 100) * this._imgHeight * this._aspectH;
} else {
this._rotationCenterY = this._parameters.center[1];
}
if (parameters.bind && parameters.bind != this._parameters.bind) { this._BindEvents(parameters.bind); }
},
_emptyFunction: function(){},
_defaultEasing: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b },
_handleRotation : function(parameters, dontcheck){
if (!supportedCSS && !this._img.complete && !dontcheck) {
this._onLoadDelegate.push(parameters);
return;
}
this._setupParameters(parameters);
if (this._angle==this._parameters.animateTo) {
this._rotate(this._angle);
}
else {
this._animateStart();
}
},
_BindEvents:function(events){
if (events && this._eventObj)
{
// Unbinding previous Events
if (this._parameters.bind){
var oldEvents = this._parameters.bind;
for (var a in oldEvents) if (oldEvents.hasOwnProperty(a))
// TODO: Remove jQuery dependency
jQuery(this._eventObj).unbind(a,oldEvents[a]);
}
this._parameters.bind = events;
for (var a in events) if (events.hasOwnProperty(a))
// TODO: Remove jQuery dependency
jQuery(this._eventObj).bind(a,events[a]);
}
},
_Loader:(function()
{
if (IE)
return function() {
var width=this._img.width;
var height=this._img.height;
this._imgWidth = width;
this._imgHeight = height;
this._img.parentNode.removeChild(this._img);
this._vimage = this.createVMLNode('image');
this._vimage.src=this._img.src;
this._vimage.style.height=height+"px";
this._vimage.style.width=width+"px";
this._vimage.style.position="absolute"; // FIXES IE PROBLEM - its only rendered if its on absolute position!
this._vimage.style.top = "0px";
this._vimage.style.left = "0px";
this._aspectW = this._aspectH = 1;
/* Group minifying a small 1px precision problem when rotating object */
this._container = this.createVMLNode('group');
this._container.style.width=width;
this._container.style.height=height;
this._container.style.position="absolute";
this._container.style.top="0px";
this._container.style.left="0px";
this._container.setAttribute('coordsize',width-1+','+(height-1)); // This -1, -1 trying to fix ugly problem with small displacement on IE
this._container.appendChild(this._vimage);
this._rootObj.appendChild(this._container);
this._rootObj.style.position="relative"; // FIXES IE PROBLEM
this._rootObj.style.width=width+"px";
this._rootObj.style.height=height+"px";
this._rootObj.setAttribute('id',this._img.getAttribute('id'));
this._rootObj.className=this._img.className;
this._eventObj = this._rootObj;
var parameters;
while (parameters = this._onLoadDelegate.shift()) {
this._handleRotation(parameters, true);
}
}
else return function () {
this._rootObj.setAttribute('id',this._img.getAttribute('id'));
this._rootObj.className=this._img.className;
this._imgWidth=this._img.naturalWidth;
this._imgHeight=this._img.naturalHeight;
var _widthMax=Math.sqrt((this._imgHeight)*(this._imgHeight) + (this._imgWidth) * (this._imgWidth));
this._width = _widthMax * 3;
this._height = _widthMax * 3;
this._aspectW = this._img.offsetWidth/this._img.naturalWidth;
this._aspectH = this._img.offsetHeight/this._img.naturalHeight;
this._img.parentNode.removeChild(this._img);
this._canvas=document.createElement('canvas');
this._canvas.setAttribute('width',this._width);
this._canvas.style.position="relative";
this._canvas.style.left = -this._img.height * this._aspectW + "px";
this._canvas.style.top = -this._img.width * this._aspectH + "px";
this._canvas.Wilq32 = this._rootObj.Wilq32;
this._rootObj.appendChild(this._canvas);
this._rootObj.style.width=this._img.width*this._aspectW+"px";
this._rootObj.style.height=this._img.height*this._aspectH+"px";
this._eventObj = this._canvas;
this._cnv=this._canvas.getContext('2d');
var parameters;
while (parameters = this._onLoadDelegate.shift()) {
this._handleRotation(parameters, true);
}
}
})(),
_animateStart:function()
{
if (this._timer) {
clearTimeout(this._timer);
}
this._animateStartTime = +new Date;
this._animateStartAngle = this._angle;
this._animate();
},
_animate:function()
{
var actualTime = +new Date;
var checkEnd = actualTime - this._animateStartTime > this._parameters.duration;
// TODO: Bug for animatedGif for static rotation ? (to test)
if (checkEnd && !this._parameters.animatedGif)
{
clearTimeout(this._timer);
}
else
{
if (this._canvas||this._vimage||this._img) {
var angle = this._parameters.easing(0, actualTime - this._animateStartTime, this._animateStartAngle, this._parameters.animateTo - this._animateStartAngle, this._parameters.duration);
this._rotate((~~(angle*10))/10);
}
if (this._parameters.step) {
this._parameters.step(this._angle);
}
var self = this;
this._timer = setTimeout(function()
{
self._animate.call(self);
}, 10);
}
// To fix Bug that prevents using recursive function in callback I moved this function to back
if (this._parameters.callback && checkEnd){
this._angle = this._parameters.animateTo;
this._rotate(this._angle);
this._parameters.callback.call(this._rootObj);
}
},
_rotate : (function()
{
var rad = Math.PI/180;
if (IE)
return function(angle)
{
this._angle = angle;
this._container.style.rotation=(angle%360)+"deg";
this._vimage.style.top = -(this._rotationCenterY - this._imgHeight/2) + "px";
this._vimage.style.left = -(this._rotationCenterX - this._imgWidth/2) + "px";
this._container.style.top = this._rotationCenterY - this._imgHeight/2 + "px";
this._container.style.left = this._rotationCenterX - this._imgWidth/2 + "px";
}
else if (supportedCSS)
return function(angle){
this._angle = angle;
this._img.style[supportedCSS]="rotate("+(angle%360)+"deg)";
this._img.style[supportedCSSOrigin]=this._parameters.center.join(" ");
}
else
return function(angle)
{
this._angle = angle;
angle=(angle%360)* rad;
// clear canvas
this._canvas.width = this._width;//+this._widthAdd;
this._canvas.height = this._height;//+this._heightAdd;
// REMEMBER: all drawings are read from backwards.. so first function is translate, then rotate, then translate, translate..
this._cnv.translate(this._imgWidth*this._aspectW,this._imgHeight*this._aspectH); // at least center image on screen
this._cnv.translate(this._rotationCenterX,this._rotationCenterY); // we move image back to its orginal
this._cnv.rotate(angle); // rotate image
this._cnv.translate(-this._rotationCenterX,-this._rotationCenterY); // move image to its center, so we can rotate around its center
this._cnv.scale(this._aspectW,this._aspectH); // SCALE - if needed ;)
this._cnv.drawImage(this._img, 0, 0); // First - we draw image
}
})()
}
if (IE)
{
Wilq32.PhotoEffect.prototype.createVMLNode=(function(){
document.createStyleSheet().addRule(".rvml", "behavior:url(#default#VML)");
try {
!document.namespaces.rvml && document.namespaces.add("rvml", "urn:schemas-microsoft-com:vml");
return function (tagName) {
return document.createElement('<rvml:' + tagName + ' class="rvml">');
};
} catch (e) {
return function (tagName) {
return document.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">');
};
}
})();
}
})(jQuery);

@ -242,7 +242,7 @@ $.extend($.validator, {
},
onkeyup: function( element, event ) {
if ( event.which === 9 && this.elementValue(element) === "" ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element(element);
}

@ -216,7 +216,7 @@
while (parameters = this._onLoadDelegate.shift()) {
this._handleRotation(parameters, true);
}
}
};
else return function () {
this._rootObj.setAttribute('id',this._img.getAttribute('id'));
this._rootObj.className=this._img.className;
@ -309,13 +309,13 @@
this._container.style.top = this._rotationCenterY - this._imgHeight/2 + "px";
this._container.style.left = this._rotationCenterX - this._imgWidth/2 + "px";
}
};
else if (supportedCSS)
return function(angle){
this._angle = angle;
this._img.style[supportedCSS]="rotate("+(angle%360)+"deg)";
this._img.style[supportedCSSOrigin]=this._parameters.center.join(" ");
}
};
else
return function(angle)
{
@ -335,7 +335,7 @@
}
})()
}
};
if (IE)
{

@ -1,132 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
object_maker.init(config_api.config_3dobject_holder, $("#objectHolder").width(), $("#objectHolder").width()/1.5);
object_maker.animate();
var ws;
var graph;
var chartData = [];
var flight_dynamics = new flight_dynamics();
$("#window_size").slider({
range: "min",
value: 37,
min: 10,
max: 300,
slide: function (event, ui) {
$("#window_size_current_value").html($("#window_size").slider("value"));
}
});
$("#window_update").slider({
range: "min",
value: 234,
min: 100,
max: 1000,
slide: function (event, ui) {
$("#window_update_value").html($("#window_update").slider("value"));
}
});
$("#replotting").click(function () {
plotting.finishPlotting(function (status) {
if (status) {
plotting.initPlotting(function (status) {
d3.select("#realtimechart").select("svg").remove();
plotting.realtime_plotting("#realtimechart", "#range_min", "#range_max", "#window_update_value",
600, $("#realtimechart").height(), "#window_size_current_value",
'#plotting_attribute');
});
} else {
$("#realtimechart").html("There is no data to plot");
}
});
});
$('.btn-minimize').click(function (e) {
e.preventDefault();
var $target = $(this).parent().parent().next('.box-content');
if ($target.is(':visible')) {
if ($(this).parent().attr('id') === "RealtimePlotting") {
plotting.forceToRedraw(function (status) {
d3.select("#realtimechart").select("svg").remove();
plotting.realtime_plotting("#realtimechart", "#range_min", "#range_max", "#window_update_value",
600, $("#realtimechart").height(), "#window_size_current_value",
'#plotting_attribute');
});
}
} else {
}
});
$('.btn-minimize').parent().parent().next('.box-content').hide();
var webSocket;
config_api.realtime_plotting_data_window["attitude"] = new Queue();
var current_status = {};
$(window).load(function () {
var websocketUrl = $("#div-chart").data("websocketurl");
connect(websocketUrl);
});
$(window).unload(function () {
disconnect();
});
//websocket connection
function connect(target) {
if ('WebSocket' in window) {
ws = new WebSocket(target);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(target);
} else {
console.log('WebSocket is not supported by this browser.');
}
if (ws) {
ws.onmessage = function (event) {
var sender_message = event.data;
sender_message = isJSON(sender_message);
if (sender_message != null) {
var droneStats = mapDroneStats(sender_message);
flight_dynamics.processingMessage(droneStats);
} else {
console.log("Message has been corrupted.");
}
};
}
}
function disconnect() {
if (ws != null) {
ws.close();
ws = null;
}
}
function mapDroneStats(sender_message){
var responseMessage = {
"quatanium_val":[sender_message[5],sender_message[6],sender_message[7],sender_message[8]],
"basicParam":{
"velocity":[sender_message[9],sender_message[10],sender_message[11]],
"global_location":[sender_message[12],sender_message[13],sender_message[14]],
"battery_level":sender_message[15],
"device_type":"drone",
"battery_voltage": sender_message[16]
}
};
return responseMessage;
}

@ -39,7 +39,7 @@ var plotting = function () {
$(placeholder).html();
var initWindow = function () {
return 0;
}
};
api.data = d3.range(parseInt($(placeholderWindowSize).html())).map(initWindow);
var margin = {top: 20, right: 20, bottom: 20, left: 40},
width = placeholderWidth - margin.left - margin.right,
@ -123,7 +123,7 @@ var plotting = function () {
}
function rescale() {
y.domain([parseInt($(placeholderYMin).val()), parseInt($(placeholderYMax).val())])
y.domain([parseInt($(placeholderYMin).val()), parseInt($(placeholderYMax).val())]);
svg.select(".title_label")
.text($(title).val() + " variation within last " + $(placeholderWindowSize).html() + " frames");
svg.select(".yaxis_label")
@ -134,5 +134,5 @@ var plotting = function () {
rescale();
});
}
}
};

@ -39,7 +39,7 @@ var plotting = function () {
$(holder).html();
var init_window = function () {
return 0;
}
};
api.data = d3.range(parseInt($(window_size_holder).html())).map(init_window);
var margin = {top: 20, right: 20, bottom: 20, left: 40},
width = holder_width - margin.left - margin.right,
@ -124,7 +124,7 @@ var plotting = function () {
}
function rescale() {
y.domain([parseInt($(y_min_hollder).val()), parseInt($(y_max_holder).val())])
y.domain([parseInt($(y_min_hollder).val()), parseInt($(y_max_holder).val())]);
svg.select(".title_label")
.text($(title).val() + " variation within last " + $(window_size_holder).html() + " frames");
@ -134,7 +134,7 @@ var plotting = function () {
}
function rescale_x() {
x.domain([1, parseInt($(window_size_holder).html()) - 2]).range([0, width])
x.domain([1, parseInt($(window_size_holder).html()) - 2]).range([0, width]);
svg.select(".x_axis").transition().call(axis_x);
}
@ -143,5 +143,5 @@ var plotting = function () {
});
}
}
};

@ -242,7 +242,7 @@ $.extend($.validator, {
},
onkeyup: function( element, event ) {
if ( event.which === 9 && this.elementValue(element) === "" ) {
return;
} else if ( element.name in this.submitted || element === this.lastElement ) {
this.element(element);
}

@ -0,0 +1,331 @@
<div class="col-lg-12 margin-top-double">
<h1 class="grey ">Drone Analyzer</h1>
<hr>
</div>
<div class="col-xs-12 col-sm-4 col-md-4 col-lg-4 padding-top">
<img src="{{@unit.publicUri}}/images/drone-icon.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<h4 class="doc-link">Click <a href="https://docs.wso2.com/pages/viewpage.action?pageId=48289181"
target="_blank">[ here ]</a> for latest instructions and
troubleshooting.</h4>
</div>
<div class="col-xs-12 col-sm-8 col-md-8 col-lg-8 padding-top">
<h3 class="uppercase">What it Does</h3>
<hr>
<p class="grey margin-top">Connect an
<a href="https://store.3drobotics.com/products/iris" target="_blank">[IRIS+]</a> Drone to
WSO2 IoT Server and visualize statistics or just run this as a simulator.
</p>
<br>
<h3 class="uppercase">What You Need </h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">ITEM 01</span>
&nbsp;&nbsp;&nbsp;IRIS+ Drone.
</li>
<li class="padding-top-double">
<span class="circle">ITEM 02</span>
&nbsp;&nbsp;&nbsp;USB to Micro USB cable or Telemetry Radio receiver.
</li>
<li class="padding-top-double">
<span class="circle">STEP 03</span>
&nbsp;&nbsp;&nbsp;If you don't have IRIS+ Drone then don't worry you can simulate without any additional
requirements. If you have a IRIS+ drone then Proceed to [Prepare] section.
</ul>
<br>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
class="btn-operations"
target="_blank"><i class="fw fw-api"></i> View API</i> &nbsp;
</a>
<a href="#" class="download-link btn-operations">
<i class="fw fw-download"></i>Download Agent
</a>
<div id="download-device-modal-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 center-container">
<h3>Name your device and download the agent from following link.</h3>
<br/>
<form id="downloadForm" method="GET"
action="{{@app.context}}/api/devices/sketch/download">
<div id="invalid-username-error-msg" class="alert alert-danger hidden"
role="alert">
<i class="icon fw fw-error"></i><span></span>
</div>
<div class="control-group">
<div class="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px"
type="text"
placeholder="Ex. drone"
name="deviceName" size="60" required>
<br/>
<input type="hidden" class="deviceType" name="deviceType"
value="drone"/>
<input type="hidden" class="sketchType" name="sketchType"
value="drone"/>
</div>
</div>
<div class="buttons" style="padding-bottom: 0px">
<a class="btn btn-operations" onclick="downloadAgent()">Download Now</a>
&nbsp;&nbsp;
</div>
</form>
</div>
</div>
</div>
</div>
<div id="device-agent-downloading-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Agent will downloading shortly.</h3>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-401-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>You have to log in first.</h3><br/>
<div class="buttons">
<a href="#" id="device-401-link" class="blue-button">
Goto Login Page
</a>&nbsp;&nbsp;
<a href="#" onclick="hidePopup();" class="btn-operations">
Cancel
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Action not permitted.</h3><br/>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Sketch does not exist.</h3><br/>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Unexpected error.</h3><br/>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
OK
</a>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12 padding-double grey-bg">
<h3 class="uppercase">Prepare</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">01</span>
&nbsp;&nbsp;&nbsp;Connect your IRIS+ Drone to your computer using either USB to Micro
USB cable or Telemetry Radio receiver.
</li>
<li class="padding-top-double">
<span class="circle">02</span>
&nbsp;&nbsp;&nbsp;Click on [Download Agent] button above to get IRIS+ Drone agent.
</li>
<li class="padding-top-double">
<span class="circle">03</span>
&nbsp;&nbsp;&nbsp;Once you have downloaded the agent please run
<i>"[startService.sh]"</i> script with root privileges.
</li>
<li class="padding-top-double">
<span class="circle">04</span>
&nbsp;&nbsp;&nbsp;Then you will be prompted to enter time interval (in seconds) between
successive Data-Pushes to the XMPP server, connection target and communication speed. So
below table will help you to find what is the correct connection target and
communication speed.
</li>
<div class="padding-top-double">
<table class="table table-bordered ">
<thead>
<tr>
<th>
<center><i>CONNECTION-TYPE</i></center>
</th>
<th>
<center><i>CONNECTION-STRING</i></center>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>Linux computer connected to the vehicle via USB</td>
<td> e.g. /dev/ttyUSB0</td>
</tr>
<tr>
<td>Linux computer connected to the drone via Serial port</td>
<td> e.g. /dev/ttyAMA0 <i>(also set baud=57600)</i></td>
</tr>
<tr>
<td>OSX computer connected to the drone via USB</td>
<td>e.g. dev/cu.usbmodem1</td>
</tr>
<tr>
<td>Windows computer connected to the drone via USB (in this case on COM14)</td>
<td>e.g. com14</td>
</tr>
<tr>
<td>Windows computer connected to the drone using a 3DR Telemetry Radio on
COM14
</td>
<td>e.g. com14 <i>(also set baud=57600)</i></td>
</tr>
</tbody>
</table>
</div>
</ul>
<br>
<br>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">IRIS+ Drone Connected to a computer</h3>
<hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
<img src="{{@unit.publicUri}}/images/schematicsGuide.png" class="img-responsive">
</a>
</center>
<br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-lg-6 padding-double">
<h3 class="uppercase">Try Out</h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
<span class="circle">01</span>
&nbsp;&nbsp;&nbsp;You can view all your connected devices at
<a href="{{@app.context}}/devices">[Device Management]</a> page.
</li>
<li class="padding-top-double">
<span class="circle">02</span>
&nbsp;&nbsp;&nbsp;Select one of connected devices and view stats which are published by
the device.
</li>
</ul>
<br/>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/devices_analytics.png" target="_blank">
<img src="{{@unit.publicUri}}/images/devices_analytics.png" class="img-responsive">
</a>
</center>
</div>
{{#zone "topCss"}}
<style type="text/css">
.circle {
background: none repeat scroll 0 0 #191919;
border-radius: 50px;
height: 50px;
padding: 10px;
width: 50px;
color: #fff;
}
.padding-top-double {
padding-top: 20px;
}
.padding-double {
padding: 20px;
}
.grey {
color: #333;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #7f7f7f;
margin: 1em 0;
padding: 0;
opacity: 0.2;
}
.light-grey {
color: #7c7c7c;
}
.uppercase {
text-transform: uppercase;
}
.grey-bg {
background-color: #f6f4f4;
}
.doc-link {
background: #11375B;
padding: 20px;
color: white;
margin-top: 0;
}
.doc-link a {
color: white;
}
</style>
{{/zone}}
{{#zone "bottomJs"}}
{{js "/js/download.js"}}
{{js "/js/jquery.validate.js"}}
{{/zone}}

@ -18,11 +18,11 @@
<hr>
<p class="grey margin-top">Connect an
<a href="https://store.3drobotics.com/products/iris" target="_blank">[IRIS+]</a> Drone to
WSO2 IoT Server and visualize statistics.
WSO2 IoT Server and visualize statistics or just run this as a simulator.
</p>
<br>
<h3 class="uppercase">What You Need</h3>
<h3 class="uppercase">What You Need </h3>
<hr>
<ul class="list-unstyled">
<li class="padding-top-double">
@ -35,8 +35,10 @@
</li>
<li class="padding-top-double">
<span class="circle">STEP 03</span>
&nbsp;&nbsp;&nbsp;Proceed to [Prepare] section.
&nbsp;&nbsp;&nbsp;If you don't have a IRIS+ Drone then don't worry you can simulate this without
any additional requirements. If you have a IRIS+ drone then proceed to [Prepare] section.
</ul>
<br>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
class="btn-operations"

@ -19,21 +19,22 @@
**/
"""
import argparse
import calendar
import httplib
import logging
import logging.handlers
import random
import signal
import ssl
import sys
import threading
import time, calendar
import time
from dronekit import connect
from functools import wraps
import random
import mqttHandler
import iotUtils
import argparse
import math
from dronekit import connect, VehicleMode
import mqttHandler
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -144,8 +145,7 @@ def registerAgent():
, context=ssl._create_unverified_context())
dcConncection.set_debuglevel(1)
dcConncection.connect()
PUSH_DATA = iotUtils.DEVICE_INFO + iotUtils.DEVICE_DATA.format(sensorValue=0.0)
PUSH_DATA += '}'
PUSH_DATA = iotUtils.DEVICE_INFO
print PUSH_DATA
registerURL = str(REGISTER_ENDPOINT)
dcConncection.putrequest('POST', registerURL)

@ -19,21 +19,21 @@
**/
"""
import argparse
import calendar
import httplib
import logging
import logging.handlers
import random
import signal
import ssl
import sys
import threading
import time, calendar
import time
from functools import wraps
import random
import mqttHandler
import iotUtils
import argparse
import math
from dronekit import connect, VehicleMode
import mqttHandler
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -136,8 +136,7 @@ def registerAgent():
, context=ssl._create_unverified_context())
dcConncection.set_debuglevel(1)
dcConncection.connect()
PUSH_DATA = iotUtils.DEVICE_INFO + iotUtils.DEVICE_DATA.format(sensorValue=0.0)
PUSH_DATA += '}'
PUSH_DATA = iotUtils.DEVICE_INFO
print PUSH_DATA
registerURL = str(REGISTER_ENDPOINT)
dcConncection.putrequest('POST', registerURL)
@ -151,10 +150,10 @@ def registerAgent():
iotUtils.IS_REGISTERED = True
print "Your device has been registered with IoT Server"
else:
iotUtils.IS_REGISTERED = False
print "Your device hasn't been registered with IoT Server"
print ('agentStats: ' + str(dcResponse.status))
print ('agentStats: ' + str(dcResponse.reason))
iotUtils.IS_REGISTERED = False
print "Your device hasn't been registered with IoT Server"
print ('agentStats: ' + str(dcResponse.status))
print ('agentStats: ' + str(dcResponse.reason))
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('agentStats: ' + str(registerURL))
print ('agentStats: Response Message')
@ -214,14 +213,14 @@ def main():
randomLatitudeLongitudeValue = generateLatitudeLongitudeValue(INIT_LATITUDE, INIT_LONGITUDE, 5)
print randomLatitudeLongitudeValue[1]
PUSH_DATA = iotUtils.SENSOR_STATS + '"time":'+str(currentTime)+'},"payloadData":{"quatanium_val_q1":34,' \
'"quatanium_val_q2":'+str(random.randint(15, 40))+',"quatanium_val_q3":'\
+str(random.randint(15, 40))+',"quatanium_val_q4":'+str(random.randint(15, 40))+',"velocity_x":'\
+str(random.randint(15, 40))+',"velocity_y":'+str(random.randint(15, 40))+',"velocity_z":678,' \
'"global_location_lat":'+str(randomLatitudeLongitudeValue[0])+',"global_location_alt":45,' \
'"global_location_lon":'+str(randomLatitudeLongitudeValue[1])+',"battery_level":'\
+str(random.randint(15, 100))+',"battery_voltage":'+str(random.randint(15, 100))+',"pitch":'\
+str(random.randint(15, 40))+',"roll":'+str(random.randint(15, 40))+',"yaw":'\
+str(random.randint(15, 40))+'}}}';
'"quatanium_val_q2":'+str(random.randint(15, 40))+',"quatanium_val_q3":' \
+str(random.randint(15, 40))+',"quatanium_val_q4":'+str(random.randint(5, 40))+',"velocity_x":' \
+str(random.randint(1, 5))+',"velocity_y":'+str(random.randint(1, 5))+',"velocity_z":' \
+str(random.randint(1, 5))+',"global_location_lat":'+str(randomLatitudeLongitudeValue[0]) \
+',"global_location_alt":45,"global_location_lon":'+str(randomLatitudeLongitudeValue[1]) \
+',"battery_level":'+ str(random.randint(15, 100))+',"battery_voltage":' \
+str(random.randint(15, 100))+',"pitch":'+str(random.randint(15, 40))+',"roll":' \
+str(random.randint(15, 40))+',"yaw":'+str(random.randint(15, 40))+'}}}';
mqttHandler.sendSensorValue(PUSH_DATA)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Publishing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('PUBLISHED DATA: ' + PUSH_DATA)

@ -21,10 +21,10 @@
"""
import ConfigParser
import calendar
import os
import random
import time, calendar
import time
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Device specific info when pushing data to server
@ -42,7 +42,7 @@ SERVER_NAME = configParser.get('Device-Configurations', 'server-name')
MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '",'
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '"}'
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
DEVICE_DATA = '"sensorValue":"{sensorValue}"'

@ -20,8 +20,9 @@
**/
"""
import time
import paho.mqtt.client as mqtt
import time
import iotUtils
global mqttClient

@ -17,7 +17,7 @@
~ under the License.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<datasources-configuration>
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>

Loading…
Cancel
Save