few fixes after testing the device types with the refactoring

revert-dabc3590
ayyoob 9 years ago
parent c7effff3ce
commit 64cdb33d67

@ -52,8 +52,6 @@ public class DataPublisherService extends Service {
private static String VALUE_TAG = "value";
public static Context context;
LocationData gps;
@Nullable
@Override
public IBinder onBind(Intent intent) {
@ -114,16 +112,13 @@ public class DataPublisherService extends Service {
//retrieve batter data.
List<BatteryData> batteryDataMap = SenseDataHolder.getBatteryDataHolder();
if (!batteryDataMap.isEmpty()) {
for (BatteryData batteryData : batteryDataMap) {
Event event = new Event();
event.setTimestamp(batteryData.getTimestamp());
event.setBattery(batteryData.getLevel());
events.add(event);
}
}
SenseDataHolder.resetBatteryDataHolder();
//retrieve location data.

@ -2,9 +2,6 @@ package org.wso2.carbon.iot.android.sense.data.publisher;
import org.json.JSONException;
import org.json.JSONObject;
import org.wso2.carbon.iot.android.sense.event.streams.Location.LocationData;
import android.util.Log;
/**
* This hold the definition of the stream that android sense is publishing to.
@ -29,11 +26,8 @@ public class Event {
private String wordStatus;
private long timestamp;
private static final String TAG = Event.class.getName();
LocationData gpsLoc;
private int getBattery() {
return this.battery;
return battery;
}
public void setBattery(int battery) {
@ -42,8 +36,7 @@ public class Event {
}
private double[] getGps() {
return gps != null ? this.gps : new double[]{gps[0],gps[1]};
return gps != null ? gps : new double[]{0, 0};
}
public void setGps(double[] gps) {
@ -52,7 +45,7 @@ public class Event {
}
private float[] getAccelerometer() {
return this.accelerometer != null ? this.accelerometer : new float[]{0, 0, 0};
return accelerometer != null ? accelerometer : new float[]{0, 0, 0};
}
public void setAccelerometer(float[] accelerometer) {
@ -61,7 +54,7 @@ public class Event {
}
private float[] getMagnetic() {
return this.magnetic != null ? this.magnetic : new float[]{0, 0, 0};
return magnetic != null ? magnetic : new float[]{0, 0, 0};
}
public void setMagnetic(float[] magnetic) {
@ -70,7 +63,7 @@ public class Event {
}
private float[] getGyroscope() {
return this.gyroscope != null ? this.gyroscope : new float[]{0, 0, 0};
return gyroscope != null ? gyroscope : new float[]{0, 0, 0};
}
public void setGyroscope(float[] gyroscope) {
@ -79,7 +72,7 @@ public class Event {
}
public float getLight() {
return this.light;
return light;
}
public void setLight(float light) {
@ -88,7 +81,7 @@ public class Event {
}
public float getPressure() {
return this.pressure;
return pressure;
}
public void setPressure(float pressure) {
@ -97,7 +90,7 @@ public class Event {
}
public float getProximity() {
return this.proximity;
return proximity;
}
public void setProximity(float proximity) {
@ -106,7 +99,7 @@ public class Event {
}
private float[] getGravity() {
return this.gravity != null ? this.gravity : new float[]{0, 0, 0};
return gravity != null ? gravity : new float[]{0, 0, 0};
}
public void setGravity(float gravity[]) {
@ -115,7 +108,7 @@ public class Event {
}
private float[] getRotation() {
return this.rotation != null ? this.rotation : new float[]{0, 0, 0};
return rotation != null ? rotation : new float[]{0, 0, 0};
}
public void setRotation(float rotation[]) {
@ -132,7 +125,7 @@ public class Event {
}
private String getWord() {
return this.word != null ? this.word : "";
return word != null ? word : "";
}
public void setWord(String word) {
@ -183,60 +176,44 @@ public class Event {
JSONObject jsonPayloadData = new JSONObject();
jsonPayloadData.put("battery", getBattery());
//gps & accelerometer
if (gps !=null && accelerometer !=null) {
jsonPayloadData.put("gps_lat", gps[0]);
jsonPayloadData.put("gps_long", gps[1]);
jsonPayloadData.put("accelerometer_x", accelerometer[0]);
jsonPayloadData.put("accelerometer_y", accelerometer[1]);
jsonPayloadData.put("accelerometer_z", accelerometer[2]);
}
//gps
double gpsEvents[] = getGps();
jsonPayloadData.put("gps_lat", gpsEvents[0]);
jsonPayloadData.put("gps_long", gpsEvents[1]);
//acceleromter
float events[] = getAccelerometer();
jsonPayloadData.put("accelerometer_x", events[0]);
jsonPayloadData.put("accelerometer_y", events[1]);
jsonPayloadData.put("accelerometer_z", events[2]);
//magnetic
//events = getMagnetic();
if (magnetic !=null) {
jsonPayloadData.put("magnetic_x", magnetic[0]);
jsonPayloadData.put("magnetic_y", magnetic[1]);
jsonPayloadData.put("magnetic_z", magnetic[2]);
}
events = getMagnetic();
jsonPayloadData.put("magnetic_x", events[0]);
jsonPayloadData.put("magnetic_y", events[1]);
jsonPayloadData.put("magnetic_z", events[2]);
//gyroscope
//events = getGyroscope();
if (gyroscope != null) {
jsonPayloadData.put("gyroscope_x", gyroscope[0]);
jsonPayloadData.put("gyroscope_y", gyroscope[1]);
jsonPayloadData.put("gyroscope_z", gyroscope[2]);
}
events = getGyroscope();
jsonPayloadData.put("gyroscope_x", events[0]);
jsonPayloadData.put("gyroscope_y", events[1]);
jsonPayloadData.put("gyroscope_z", events[2]);
jsonPayloadData.put("light", getLight());
jsonPayloadData.put("pressure", getPressure());
jsonPayloadData.put("proximity", getProximity());
//gravity
//events = getGravity();
if (gravity!=null) {
jsonPayloadData.put("gravity_x", gravity[0]);
jsonPayloadData.put("gravity_y", gravity[1]);
jsonPayloadData.put("gravity_z", gravity[2]);
}
events = getGravity();
jsonPayloadData.put("gravity_x", events[0]);
jsonPayloadData.put("gravity_y", events[1]);
jsonPayloadData.put("gravity_z", events[2]);
//rotation
//events = getRotation();
if (rotation!=null) {
jsonPayloadData.put("rotation_x", rotation[0]);
jsonPayloadData.put("rotation_y", rotation[1]);
jsonPayloadData.put("rotation_z", rotation[2]);
}
events = getRotation();
jsonPayloadData.put("rotation_x", events[0]);
jsonPayloadData.put("rotation_y", events[1]);
jsonPayloadData.put("rotation_z", events[2]);
//word
jsonPayloadData.put("word", getWord());
jsonPayloadData.put("word_sessionId", getWordSessionId());
jsonPayloadData.put("word_status", getWordStatus());
jsonEvent.put("payloadData", jsonPayloadData);
return jsonEvent;

@ -23,9 +23,6 @@ import org.wso2.carbon.iot.android.sense.event.streams.DataReader;
import org.wso2.carbon.iot.android.sense.util.SenseDataHolder;
import java.util.concurrent.TimeUnit;
/**
* This is used to retrieve the location data using GPS and used Network connection to increase the accuracy.
*/
@ -115,7 +112,7 @@ public class LocationDataReader extends DataReader implements LocationListener {
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Failed to capture location data.");
}
return location;
@ -182,14 +179,9 @@ public class LocationDataReader extends DataReader implements LocationListener {
TimeUnit.MILLISECONDS.sleep(10000);
double lat = getLatitude();
double longit = getLongitude();
if (lat != 0 && longit != 0) {
Log.d(TAG, "YYY " + getLatitude() + ", XXX " + getLongitude());
gps = new LocationData(getLatitude(), getLongitude());
SenseDataHolder.getLocationDataHolder().add(gps);
}

@ -30,5 +30,5 @@ CREATE TEMPORARY TABLE WordcountSummaryData USING CarbonAnalytics OPTIONS (table
insert into table WordcountSummaryData select sessionId, word, count(*) as occurence, meta_deviceType as deviceType,
meta_deviceId as deviceId, meta_owner as owner from WordCountData group by sessionId, word, meta_deviceType, meta_deviceId, meta_owner;
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -31,8 +31,7 @@ import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.AndroidConfiguration;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.Constants;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.device.mgt.iot.util.IoTUtil;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@ -63,7 +62,7 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, IoTUtil.getHostName());
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getHostName());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(androidConfiguration.toString())
@ -86,7 +85,7 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getBrokerEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, IoTUtil.getHostName());
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, Utils.getHostName());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.ok(androidConfiguration.toString()).build();
@ -96,9 +95,6 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build();
} catch (IoTException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build();
}
}

@ -18,7 +18,7 @@
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
function drawGraph(from, to) {
function drawGraph_android_sense(from, to) {
retrieveDataAndDrawLineGraph("battery", from, to);
retrieveDataAndDrawLineGraph("light", from, to);
retrieveDataAndDrawLineGraph("pressure", from, to);

@ -188,9 +188,8 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
}
//create new device id
String deviceId = shortUUID();
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm()
.getRealmConfiguration().getAdminUserName();
if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {ArduinoConstants.DEVICE_TYPE};
@ -213,7 +212,6 @@ public class ArduinoManagerServiceImpl implements ArduinoManagerService {
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
ArduinoConstants.DEVICE_TYPE, deviceId, deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}

@ -18,10 +18,9 @@
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.device.mgt.iot.util.IoTUtil;
import org.wso2.carbon.device.mgt.iot.util.IotDeviceManagementUtil;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
@ -35,13 +34,8 @@ import java.util.Map;
*/
public class ZipUtil {
private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String LOCALHOST = "localhost";
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
String deviceId, String deviceName, String token,
String refreshToken) throws DeviceManagementException {
@ -53,29 +47,27 @@ public class ZipUtil {
String iotServerIP;
try {
iotServerIP = IoTUtil.getHostName();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
iotServerIP = Utils.getHostName();
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String apimEndpoint = httpsServerEP;
Map<String, String> contextParams = new HashMap<>();
contextParams.put("TENANT_DOMAIN", APIUtil.getTenantDomainOftheUser());
if (APIUtil.getTenantDomainOftheUser().equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) {
contextParams.put("TENANT_DOMAIN", "");
} else {
contextParams.put("TENANT_DOMAIN", "/t/" + tenantDomain);
}
contextParams.put("DEVICE_OWNER", owner);
contextParams.put("DEVICE_ID", deviceId);
contextParams.put("DEVICE_NAME", deviceName);
contextParams.put("HTTPS_EP", httpsServerEP);
contextParams.put("HTTP_EP", httpServerEP);
contextParams.put("APIM_EP", apimEndpoint);
contextParams.put("SERVER_EP_IP", iotServerIP.replace('.', ','));
contextParams.put("SERVER_EP_PORT", httpServerPort);
contextParams.put("DEVICE_TOKEN", token);
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile;
zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, contextParams);
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile;
} catch (IoTException e) {
throw new DeviceManagementException(e.getMessage());
} catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e);
}

@ -1,11 +1,8 @@
{{#zone "topCss"}}
{{css "css/graph.css"}}
{{/zone}}
<span id="details" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}"
<span id="details" data-devices="{{devices}}" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span>
<div id="div-chart">
<div class="chartWrapper" id="chartWrapper">
<span id="span-title">Temperature</span>
<h3 id="span-title">Temperature</h3>
<div id="y_axis" class="custom_y_axis"></div>
<div class="legend_container">
<div id="smoother" title="Smoothing"></div>
@ -18,8 +15,5 @@
</div>
{{#zone "bottomJs"}}
{{js "js/d3.min.js"}}
{{js "js/rickshaw.min.js"}}
{{js "js/moment.min.js"}}
{{js "js/devicetype-graph.js"}}
{{/zone}}

@ -17,10 +17,16 @@
*/
function onRequest(context) {
var devices = context.unit.params.devices;
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("deviceId");
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
if (devices) {
return {
"devices": stringify(devices),
"backendApiUri": devicemgtProps["httpsURL"] + "/arduino/device/stats/"
};
} else if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {

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

@ -18,27 +18,20 @@
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
function drawGraph(from, to) {
var backendApiUrl = $("#chart").data("backend-api-url") + "?from=" + from + "&to=" + to;
function drawGraph_arduino(from, to) {
$("#y_axis").html("");
$("#smoother").html("");
$("#legend").html("");
$("#chart").html("");
$("#x_axis").html("");
$("#slider").html("");
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data));
}
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
});
}
var devices = $("#details").data("devices");
var tzOffset = new Date().getTimezoneOffset() * 60;
function drawLineGraph(data) {
var chartWrapperElmId = "#div-chart";
var graphWidth = $(chartWrapperElmId).width() - 50;
if (data.length == 0 || data.length == undefined) {
$("#chart").html("<br/>No data available...");
return;
}
$("#chart").empty();
var graphConfig = {
element: document.getElementById("chart"),
width: graphWidth,
@ -53,47 +46,28 @@ function drawLineGraph(data) {
series: []
};
var tzOffset = new Date().getTimezoneOffset() * 60;
var min = Number.MAX_VALUE;
var max = Number.MIN_VALUE;
var range_min = 99999, range_max = 0;
var max_val = parseInt(data[0].values.temperature);
var min_val = max_val;
var chartData = [];
for (var i = 0; i < data.length; i++) {
var y_val = parseInt(data[i].values.temperature);
if (y_val > max_val) {
max_val = y_val;
} else if (y_val < min_val) {
min_val = y_val;
}
chartData.push(
if (devices) {
for (var i = 0; i < devices.length; i++) {
graphConfig['series'].push(
{
x: parseInt(data[i].values.time) - tzOffset,
y: y_val
}
);
}
if (range_max < max_val) {
range_max = max_val;
}
if (range_min > min_val) {
range_min = min_val;
'color': palette.color(),
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': devices[i].name
});
}
} else {
graphConfig['series'].push(
{
'color': palette.color(),
'data': chartData,
'name': $("#details").data("devicename"),
'scale': d3.scale.linear().domain([Math.min(min, min_val), Math.max(max, max_val)])
.nice()
}
);
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
'data': [{
x: parseInt(new Date().getTime() / 1000),
y: 0
}],
'name': $("#details").data("devicename")
});
}
var graph = new Rickshaw.Graph(graphConfig);
@ -106,13 +80,12 @@ function drawLineGraph(data) {
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y.Scaled({
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
element: document.getElementById("y_axis"),
width: 40,
height: 410,
'scale': d3.scale.linear().domain([Math.min(min, range_min), Math.max(max, range_max)]).nice()
height: 410
});
yAxis.render();
@ -152,4 +125,59 @@ function drawLineGraph(data) {
graph: graph,
legend: legend
});
var deviceIndex = 0;
if (devices) {
getData();
} else {
var backendApiUrl = $("#chart").data("backend-api-url") + "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data));
}
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
});
}
function getData() {
if (deviceIndex >= devices.length) {
return;
}
var backendApiUrl = $("#chart").data("backend-api-url") + devices[deviceIndex].deviceIdentifier
+ "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data));
}
deviceIndex++;
getData();
};
invokerUtil.get(backendApiUrl, successCallback, function (message) {
console.log(message);
deviceIndex++;
getData();
});
}
function drawLineGraph(data) {
if (data.length === 0 || data.length === undefined) {
return;
}
var chartData = [];
for (var i = 0; i < data.length; i++) {
chartData.push(
{
x: parseInt(data[i].values.time) - tzOffset,
y: parseInt(data[i].values.temperature)
}
);
}
graphConfig.series[deviceIndex].data = chartData;
graph.update();
}
}

@ -26,5 +26,5 @@ CREATE TEMPORARY TABLE DeviceAccelerometerSummaryData USING CarbonAnalytics OPTI
insert into table DeviceAccelerometerSummaryData select x, y, z, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceAccelerometerData group by x, y, z, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceBatterySummaryData select level, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceBatteryData group by level, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceGPSSummaryData select latitude, longitude, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceGPSData group by latitude, longitude, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceGRAVITYSummaryData select x, y, z, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceGRAVITYData group by x, y, z, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceGYROSCOPESummaryData select x, y, z, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceGYROSCOPEData group by x, y, z, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceLightSummaryData select light, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceLightData group by light, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceMagneticSummaryData select x, y , z, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceMagneticData group by x, y, z, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DevicePRESSURESummaryData select pressure, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicePRESSUREData group by pressure, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DevicePROXIMITYSummaryData select proximity, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DevicePROXIMITYData group by proximity, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceROTATIONSummaryData select x, y, z, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceROTATIONData group by x, y, z, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -26,5 +26,5 @@
insert into table DeviceTemperatureSummaryData select temperature, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceTemperatureData group by temperature, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
<CronExpression>0 0/5 * * * ?</CronExpression>
</Analytics>

@ -49,8 +49,6 @@ public class HTTPMessageServlet extends HttpServlet {
private static final String AUTH_MESSAGE_STORE_AUTHENTICATION_INFO = "AUTH_MESSAGE_STORE_AUTHENTICATION_INFO";
private static final String AUTH_FAILURE_RESPONSE = "_AUTH_FAILURE_";
private static Log log = LogFactory.getLog(HTTPMessageServlet.class);
private static Map<String, String> contentValidationProperties;

@ -1,43 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.exception;
public class IoTException extends Exception {
public IoTException() {
super();
}
public IoTException(String message) {
super(message);
}
public IoTException(String message, Throwable cause) {
super(message, cause);
}
public IoTException(Throwable cause) {
super(cause);
}
protected IoTException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}

@ -1,45 +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.wso2.carbon.device.mgt.iot.util;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.utils.NetworkUtils;
import java.net.SocketException;
public class IoTUtil {
public static final String HOST_NAME = "HostName";
public static String getHostName() throws IoTException {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
throw new IoTException("Error while trying to read hostname.", e);
}
return hostName;
}
}

@ -1,319 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* you may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Provides utility methods required by the iot device management bundle.
*/
public class IotDeviceManagementUtil {
private static final Log log = LogFactory.getLog(IotDeviceManagementUtil.class.getName());
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams)
throws DeviceManagementException, IOException {
String sep = File.separator;
String sketchPath = CarbonUtils.getCarbonHome() + sep + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
String zipFileName = "zipFile.zip";
try {
Map<String, List<String>> properties = getProperties(sketchPath + sep + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates");
// zipFileName = properties.get("zipfilename").get(0);
zipFileName = contextParams.get("DEVICE_NAME") + ".zip";
for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + sep + templateFile, archivesPath + sep + templateFile,
contextParams);
}
templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
} catch (IOException ex) {
throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex);
}
try {
createZipArchive(archivesPath);
} catch (IOException e) {
String message = "Zip file for the specific device agent not found at path: " + archivesPath;
log.error(message);
log.error(e);
throw new DeviceManagementException(message, e);
}
FileUtils.deleteDirectory(new File(archivesPath));//clear folder
/* now get the zip file */
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip);
}
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertyFilePath);
// load a properties file
prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>();
String templates = prop.getProperty("templates");
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
properties.put("templates", list);
final String filename = prop.getProperty("zipfilename");
list = new ArrayList<String>() {{
add(filename);
}};
properties.put("zipfilename", list);
return properties;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
//TODO add velocity 1.7, currently commented
//TODO conflicting when calling in CXF environment with the opensaml orbit
// /* create a context and add data */
// VelocityContext context = new VelocityContext(contextParams);
//
// /* first, get and initialize an engine */
// VelocityEngine ve = new VelocityEngine();
// ve.setProperty( RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS,
// "org.apache.velocity.runtime.log.Log4JLogChute" );
// ve.setProperty("runtime.log.logsystem.log4j.logger", IotDeviceManagementUtil.class.getName());
// ve.init();
//
// String sep = File.separator;
// Template t = ve.getTemplate(srcFile);
// FileWriter writer = null;
// try {
// writer = new FileWriter(dstFile);
// t.merge(context, writer);
// } finally {
// if (writer != null) {
// writer.flush();
// writer.close();
// }
// }
//read from file
FileInputStream inputStream = new FileInputStream(srcFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
}
if (inputStream != null) {
inputStream.close();
}
//write to file
FileOutputStream outputStream = new FileOutputStream(dstFile);
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
if (outputStream != null) {
outputStream.close();
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
silentClose(in);
silentClose(out);
}
}
}
private static void silentClose(InputStream is) {
if (is == null) {
return;
}
try {
is.close();
} catch (IOException e) {
// do nothing
}
}
private static void silentClose(OutputStream os) {
if (os == null) {
return;
}
try {
os.close();
} catch (IOException e) {
// do nothing
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
final int BUFFER = 2048;
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder);
String subdirList[] = subDir.list();
if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false;
}
for (String sd : subdirList) {
// get a list of files from current directory
File f = new File(srcFolder + "/" + sd);
if (f.isDirectory()) {
String files[] = f.list();
if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false;
}
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
} else //it is just a file
{
FileInputStream fi = new FileInputStream(f);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
}
out.flush();
} finally {
silentClose(origin);
silentClose(out);
}
return true;
}
}

@ -0,0 +1,304 @@
/*
* 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.wso2.carbon.device.mgt.iot.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.base.ServerConfiguration;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.utils.CarbonUtils;
import org.wso2.carbon.utils.NetworkUtils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Provides utility methods required by the device type plugins.
*/
public class Utils {
public static final String HOST_NAME = "HostName";
private static final Log log = LogFactory.getLog(Utils.class);
public static String getHostName() {
String hostName = ServerConfiguration.getInstance().getFirstProperty(HOST_NAME);
try {
if (hostName == null) {
hostName = NetworkUtils.getLocalHostname();
}
} catch (SocketException e) {
hostName = "localhost";
}
return hostName;
}
public static ZipArchive getSketchArchive(String archivesPath, String templateSketchPath, Map contextParams,
String zipFileName)
throws DeviceManagementException, IOException {
String sketchPath = CarbonUtils.getCarbonHome() + File.separator + templateSketchPath;
FileUtils.deleteDirectory(new File(archivesPath));//clear directory
FileUtils.deleteDirectory(new File(archivesPath + ".zip"));//clear zip
if (!new File(archivesPath).mkdirs()) { //new dir
String message = "Could not create directory at path: " + archivesPath;
log.error(message);
throw new DeviceManagementException(message);
}
zipFileName = zipFileName + ".zip";
try {
Map<String, List<String>> properties = getProperties(sketchPath + File.separator + "sketch" + ".properties");
List<String> templateFiles = properties.get("templates");
for (String templateFile : templateFiles) {
parseTemplate(templateSketchPath + File.separator + templateFile, archivesPath + File.separator + templateFile,
contextParams);
}
templateFiles.add("sketch.properties"); // ommit copying the props file
copyFolder(new File(sketchPath), new File(archivesPath), templateFiles);
} catch (IOException ex) {
throw new DeviceManagementException(
"Error occurred when trying to read property " + "file sketch.properties", ex);
}
try {
createZipArchive(archivesPath);
} catch (IOException e) {
String message = "Zip file for the specific device agent not found at path: " + archivesPath;
log.error(message);
log.error(e);
throw new DeviceManagementException(message, e);
}
FileUtils.deleteDirectory(new File(archivesPath));//clear folder
/* now get the zip file */
File zip = new File(archivesPath + ".zip");
return new ZipArchive(zipFileName, zip);
}
private static Map<String, List<String>> getProperties(String propertyFilePath) throws IOException {
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream(propertyFilePath);
// load a properties file
prop.load(input);
Map<String, List<String>> properties = new HashMap<String, List<String>>();
String templates = prop.getProperty("templates");
List<String> list = new ArrayList<String>(Arrays.asList(templates.split(",")));
properties.put("templates", list);
final String filename = prop.getProperty("zipfilename");
list = new ArrayList<String>() {{
add(filename);
}};
properties.put("zipfilename", list);
return properties;
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static void parseTemplate(String srcFile, String dstFile, Map contextParams) throws IOException {
//read from file
FileInputStream inputStream = new FileInputStream(srcFile);
String content = IOUtils.toString(inputStream, StandardCharsets.UTF_8.toString());
Iterator iterator = contextParams.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
content = content.replaceAll("\\$\\{" + mapEntry.getKey() + "\\}", mapEntry.getValue().toString());
}
if (inputStream != null) {
inputStream.close();
}
//write to file
FileOutputStream outputStream = new FileOutputStream(dstFile);
IOUtils.write(content, outputStream, StandardCharsets.UTF_8.toString());
if (outputStream != null) {
outputStream.close();
}
}
private static void copyFolder(File src, File dest, List<String> excludeFileNames) throws IOException {
if (src.isDirectory()) {
//if directory not exists, create it
if (!dest.exists() && !dest.mkdirs()) {
String message = "Could not create directory at path: " + dest;
log.error(message);
throw new IOException(message);
}
//list all the directory contents
String files[] = src.list();
if (files == null) {
log.warn("There are no files insides the directory " + src.getAbsolutePath());
return;
}
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile, destFile, excludeFileNames);
}
} else {
for (String fileName : excludeFileNames) {
if (src.getName().equals(fileName)) {
return;
}
}
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(src);
out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
} finally {
silentClose(in);
silentClose(out);
}
}
}
private static void silentClose(InputStream is) {
if (is == null) {
return;
}
try {
is.close();
} catch (IOException e) {
// do nothing
}
}
private static void silentClose(OutputStream os) {
if (os == null) {
return;
}
try {
os.close();
} catch (IOException e) {
// do nothing
}
}
private static boolean createZipArchive(String srcFolder) throws IOException {
BufferedInputStream origin = null;
ZipOutputStream out = null;
try {
final int BUFFER = 2048;
FileOutputStream dest = new FileOutputStream(new File(srcFolder + ".zip"));
out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File subDir = new File(srcFolder);
String subdirList[] = subDir.list();
if (subdirList == null) {
log.warn("The sub directory " + subDir.getAbsolutePath() + " is empty");
return false;
}
for (String sd : subdirList) {
// get a list of files from current directory
File f = new File(srcFolder + "/" + sd);
if (f.isDirectory()) {
String files[] = f.list();
if (files == null) {
log.warn("The current directory " + f.getAbsolutePath() + " is empty. Has no files");
return false;
}
for (int i = 0; i < files.length; i++) {
FileInputStream fi = new FileInputStream(srcFolder + "/" + sd + "/" + files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd + "/" + files[i]);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
} else //it is just a file
{
FileInputStream fi = new FileInputStream(f);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(sd);
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
out.flush();
}
}
}
out.flush();
} finally {
silentClose(origin);
silentClose(out);
}
return true;
}
}

@ -20,25 +20,19 @@ package org.wso2.carbon.device.mgt.iot.util;
import java.io.File;
/**
* This is an utility class to hold zip files.
*/
public class ZipArchive {
private File zipFile = null;
private String fileName = null;
private String deviceId = null;
public ZipArchive(String fileName, File zipFile) {
this.fileName = fileName;
this.zipFile = zipFile;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public File getZipFile() {
return zipFile;
}

@ -236,7 +236,6 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType,
deviceId, deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}

@ -19,10 +19,8 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.util.IoTUtil;
import org.wso2.carbon.device.mgt.iot.util.IotDeviceManagementUtil;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
@ -54,7 +52,7 @@ public class ZipUtil {
String iotServerIP;
try {
iotServerIP = IoTUtil.getHostName();
iotServerIP = Utils.getHostName();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
@ -78,10 +76,8 @@ public class ZipUtil {
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile;
zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, contextParams);
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile;
} catch (IoTException e) {
throw new DeviceManagementException(e.getMessage());
} catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e);
}

@ -18,7 +18,7 @@
var palette = new Rickshaw.Color.Palette({scheme: "classic9"});
function drawGraph(from, to) {
function drawGraph_raspberrypi(from, to) {
var backendApiUrl = $("#chart").data("backend-api-url") + "?from=" + from + "&to=" + to;
var successCallback = function (data) {

@ -282,7 +282,6 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}

@ -19,9 +19,7 @@
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.device.mgt.iot.util.IoTUtil;
import org.wso2.carbon.device.mgt.iot.util.IotDeviceManagementUtil;
import org.wso2.carbon.device.mgt.iot.util.Utils;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.xmpp.XmppConfig;
@ -55,7 +53,7 @@ public class ZipUtil {
String iotServerIP;
try {
iotServerIP = IoTUtil.getHostName();
iotServerIP = Utils.getHostName();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
@ -84,10 +82,8 @@ public class ZipUtil {
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile;
zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, contextParams);
zipFile = Utils.getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
return zipFile;
} catch (IoTException e) {
throw new DeviceManagementException(e.getMessage());
} catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e);
}

@ -34,7 +34,6 @@
// Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
#define IDLE_TIMEOUT_MS 3000
#define TENANT_DOMAIN "${TENANT_DOMAIN}"
#define DEVICE_OWNER "${DEVICE_OWNER}"
#define DEVICE_ID "${DEVICE_ID}"
#define DEVICE_TOKEN "${DEVICE_TOKEN}"
@ -43,8 +42,7 @@
#define TIME 0
#define SUPER_TENANT "carbon.super"
#define DAS_SERVICE_EPOINT "/endpoints/temperature-http?deviceId=${DEVICE_ID}"
#define DAS_SERVICE_TEPOINT "/endpoints/t/${TENANT_DOMAIN}/temperature-http?deviceId=${DEVICE_ID}"
#define DAS_SERVICE_EPOINT "/endpoints${TENANT_DOMAIN}/arduino_receiver?deviceId=${DEVICE_ID}"
#define IOT_SERVICE_EPOINT "/arduino/device/${DEVICE_ID}/controls"
@ -53,15 +51,17 @@
#define DEBUG true
#define CON_DEBUG true
#define SERVICE_PORT 9763 //http port of iot server
#define SERVICE_PORT ${SERVER_EP_PORT} //http port of iot server
byte server[4] = {192,168,1,10}; //Ip address of iot server
byte deviceIP[4] = { 192, 168, 1,110 }; //Ststic ip address of arduino
byte server[4] = {${SERVER_EP_IP}}; //Ip address of iot server
//set static Ip
/**
byte deviceIP[4] = { 192, 168, 1,110 }; //Ststic ip address of arduino
byte dns2[] = { 8, 8, 8, 8 }; //Ststic dns of arduino
byte subnet[] = { 255, 255, 255, 0 }; //Ststic subnet of arduino
byte gateway[] = { 192, 168, 1, 1 }; //Ststic gateway of arduino
*/
String host, jsonPayLoad, replyMsg;
String responseMsg, subStrn;

@ -38,11 +38,14 @@ void connectHttp() {
Only required if using static IP for the WifiSheild
***********************************************************************************************/
/**
ip = cc3000.IP2U32(deviceIP[0], deviceIP[1], deviceIP[2], deviceIP[3]);
ddns = cc3000.IP2U32(dns2[0], dns2[1], dns2[2], dns2[3]);
ssubnet = cc3000.IP2U32(subnet[0], subnet[1], subnet[2], subnet[3]);
ggateway = cc3000.IP2U32(gateway[0], gateway[1], gateway[2], gateway[3]);
cc3000.setStaticIPAddress(ip, ssubnet, ggateway, ddns); // required for setting static IP
cc3000.setStaticIPAddress(ip, ssubnet, ggateway, ddns);
*/
// required for setting static IP
/***********************************************************************************************/

@ -31,11 +31,7 @@ void pushData(){
payLoad += "}}}";
client.fastrprint(F("POST "));
if (strcmp(TENANT_DOMAIN, SUPER_TENANT) == 0) {
client.fastrprint(DAS_SERVICE_EPOINT);
} else {
client.fastrprint(DAS_SERVICE_TEPOINT);
}
client.fastrprint(F(" HTTP/1.1")); client.fastrprint(F("\n"));
client.fastrprint(host.c_str()); client.fastrprint(F("\n"));
client.fastrprint(F("Authorization: Bearer ")); client.fastrprint(F(DEVICE_TOKEN)); client.fastrprint(F("\n"));
@ -50,11 +46,7 @@ void pushData(){
if(DEBUG) {
Serial.print("POST ");
if (strcmp(TENANT_DOMAIN, SUPER_TENANT) == 0) {
Serial.print(DAS_SERVICE_EPOINT);
} else {
Serial.print(DAS_SERVICE_TEPOINT);
}
Serial.print(" HTTP/1.1"); Serial.println();
Serial.print(host); Serial.println();
Serial.print("Content-Type: application/json"); Serial.println();

Loading…
Cancel
Save