Move device type plugins to iot-plugins

This commit is contained in:
NuwanSameera 2016-03-30 16:14:42 +05:30
parent df35ec5aaf
commit 8656f84ac6
133 changed files with 4018 additions and 5791 deletions

View File

@ -1,667 +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.androidsense.controller.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.common.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
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.androidsense.controller.service.impl.transport.AndroidSenseMQTTConnector;
import org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.util.DeviceData;
import org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.util.SensorData;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The api for
*/
@DeviceType(value = "android_sense")
@API(name = "android_sense", version = "1.0.0", context = "/android_sense", tags = {"android_sense"})
public class AndroidSenseControllerService {
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private static Log log = LogFactory.getLog(AndroidSenseControllerService.class);
private static AndroidSenseMQTTConnector androidSenseMQTTConnector;
/**
* Fetches the `AndroidSenseMQTTConnector` specific to this Android Sense controller service.
*
* @return the 'AndroidSenseMQTTConnector' instance bound to the 'AndroidSenseMQTTConnector' variable of
* this service.
*/
@SuppressWarnings("Unused")
public AndroidSenseMQTTConnector getAndroidSenseMQTTConnector() {
return androidSenseMQTTConnector;
}
/**
* Sets the `AndroidSenseMQTTConnector` variable of this Android Sense controller service.
*
* @param androidSenseMQTTConnector a 'AndroidSenseMQTTConnector' object that handles all MQTT related
* communications of any connected Android Sense device-type
*/
@SuppressWarnings("Unused")
public void setAndroidSenseMQTTConnector(final AndroidSenseMQTTConnector androidSenseMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
AndroidSenseControllerService.androidSenseMQTTConnector = androidSenseMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
androidSenseMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
/**
* Service to push all the sensor data collected by the Android. Called by the Android device
*
* @param dataMsg The json string containing sensor readings
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API
*/
@Path("controller/sensors")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void addSensorData(DeviceData dataMsg, @Context HttpServletResponse response) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
SensorData[] sensorData = dataMsg.values;
String streamDef = null;
Object payloadData[] = null;
String sensorName = null;
for (SensorData sensor : sensorData) {
switch (sensor.key) {
case "battery" :
streamDef = AndroidSenseConstants.BATTERY_STREAM_DEFINITION;
payloadData = new Float[]{Float.parseFloat(sensor.value)};
sensorName = AndroidSenseConstants.SENSOR_BATTERY;
break;
case "GPS" :
streamDef = AndroidSenseConstants.GPS_STREAM_DEFINITION;
String gpsValue = sensor.value;
String gpsValuesString[] = gpsValue.split(",");
Float gpsValues[] = new Float[2];
gpsValues[0] = Float.parseFloat(gpsValuesString[0]);
gpsValues[1] = Float.parseFloat(gpsValuesString[0]);
payloadData = gpsValues;
sensorName = AndroidSenseConstants.SENSOR_GPS;
break;
default :
try {
int androidSensorId = Integer.parseInt(sensor.key);
String value = sensor.value;
String sensorValueString[] = value.split(",");
Float sensorValues[] = new Float[1];
switch (androidSensorId) {
case 1:
streamDef = AndroidSenseConstants.ACCELEROMETER_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_ACCELEROMETER;
break;
case 2:
streamDef = AndroidSenseConstants.MAGNETIC_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_MAGNETIC;
break;
case 4:
streamDef = AndroidSenseConstants.GYROSCOPE_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_GYROSCOPE;
break;
case 5:
streamDef = AndroidSenseConstants.LIGHT_STREAM_DEFINITION;
sensorName = AndroidSenseConstants.SENSOR_LIGHT;
payloadData = new Float[]{Float.parseFloat(sensorValueString[0])};
break;
case 6:
streamDef = AndroidSenseConstants.PRESSURE_STREAM_DEFINITION;
sensorName = AndroidSenseConstants.SENSOR_PRESSURE;
payloadData = new Float[]{Float.parseFloat(sensorValueString[0])};
break;
case 8:
streamDef = AndroidSenseConstants.PROXIMITY_STREAM_DEFINITION;
sensorName = AndroidSenseConstants.SENSOR_PROXIMITY;
payloadData = new Float[]{Float.parseFloat(sensorValueString[0])};
break;
case 9:
streamDef = AndroidSenseConstants.GRAVITY_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_GRAVITY;
break;
case 11:
streamDef = AndroidSenseConstants.ROTATION_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_ROTATION;
break;
}
} catch (NumberFormatException e) {
log.error("Invalid sensor value is sent from the device");
continue;
}
}
Object metaData[] = {dataMsg.owner, AndroidSenseConstants.DEVICE_TYPE, dataMsg.deviceId, sensor.time};
if (streamDef != null && payloadData != null && payloadData.length > 0) {
try {
SensorDataManager.getInstance()
.setSensorRecord(dataMsg.deviceId, sensorName, sensor.value, sensor.time);
deviceAnalyticsService.publishEvent(streamDef, "1.0.0", metaData, new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
response.setStatus(Response.Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode());
}
}
}
}
/**
* End point which is called by Front-end js to get Light sensor readings from the server.
*
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/light")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "light", name = "Light", description = "Read Light data from the device", type = "monitor")
public SensorRecord getLightData(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants.SENSOR_LIGHT);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Battery data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/battery")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "battery", name = "Battery", description = "Read Battery data from the device", type = "monitor")
public SensorRecord getBattery(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants.SENSOR_BATTERY);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get GPS data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/gps")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "gps", name = "gps", description = "Read GPS data from the device", type = "monitor")
public SensorRecord getGPS(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants.SENSOR_GPS);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Magnetic data readings from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/magnetic")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "magnetic", name = "Magnetic", description = "Read Magnetic data from the device", type = "monitor")
public SensorRecord readMagnetic(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants.SENSOR_MAGNETIC);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Accelerometer data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/accelerometer")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "accelerometer", name = "Accelerometer", description = "Read Accelerometer data from the device",
type = "monitor")
public SensorRecord readAccelerometer(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_ACCELEROMETER);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Rotation data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/rotation")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "rotation", name = "Rotation", description = "Read Rotational Vector data from the device",
type = "monitor")
public SensorRecord readRotation(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_ROTATION);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Proximity data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/proximity")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "proximity", name = "Proximity", description = "Read Proximity data from the device",
type = "monitor")
public SensorRecord readProximity(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_PROXIMITY);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Gyroscope data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/gyroscope")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "gyroscope", name = "Gyroscope", description = "Read Gyroscope data from the device",
type = "monitor")
public SensorRecord readGyroscope(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_GYROSCOPE);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Pressure data from the server.
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/pressure")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "pressure", name = "Pressure", description = "Read Pressure data from the device", type = "monitor")
public SensorRecord readPressure(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_PRESSURE);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point which is called by Front-end js to get Gravity data from the server.
*
* @param deviceId The registered device id
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("controller/device/{deviceId}/sensors/gravity")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "gravity", name = "Gravity",
description = "Read Gravity data from the device", type = "monitor")
public SensorRecord readGravity(@PathParam("deviceId") String deviceId, @Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_GRAVITY);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
@Path("controller/device/{deviceId}/sensors/words")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "words", name = "Words", description = "Get the key words and occurrences",
type = "monitor")
public SensorRecord getWords(@PathParam("deviceId") String deviceId, @QueryParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_WORDCOUNT);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
return sensorRecord;
}
/**
* End point to send the key words to the device
* @param deviceId The registered device Id.
* @param keywords The key words to be sent. (Comma separated values)
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API
*/
@Path("controller/device/{deviceId}/sensors/words")
@POST
@Feature(code = "keywords", name = "Add Keywords", description = "Send keywords to the device",
type = "operation")
public void sendKeyWords(@PathParam("deviceId") String deviceId, @FormParam("keywords") String keywords,
@Context HttpServletResponse response) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "add", keywords);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (TransportHandlerException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
}
/**
* End point to send the key words to the device
*
* @param deviceId The registered device Id.
* @param threshold The key words to be sent. (Comma separated values)
* @param response the HTTP servlet response object received by default as part of the HTTP
* call to this API
*/
@Path("controller/device/{deviceId}/sensors/words/threshold")
@POST
@Feature(code = "threshold", name = "Add a Threshold", description = "Set a threshold for word in the device",
type = "operation")
public void sendThreshold(@PathParam("deviceId") String deviceId, @FormParam("threshold") String threshold,
@Context HttpServletResponse response) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "threshold", threshold);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (TransportHandlerException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
}
@Path("controller/device/{deviceId}/sensors/words")
@DELETE
@Feature(code = "remove", name = "Remove Keywords", description = "Remove the keywords",
type = "operation")
public void removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words,
@Context HttpServletResponse response) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "remove", words);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (TransportHandlerException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
}
/**
* Retrieve Sensor data for the device type
*
*/
@Path("controller/stats/device/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
public SensorData[] getAndroidSenseDeviceStats(@PathParam("deviceId") String deviceId,
@PathParam("sensorName") String sensor,
@QueryParam("from") long from,
@QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String user = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
List<SensorData> sensorDatas = new ArrayList<>();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
String query = "owner:" + user + " AND deviceId:" + deviceId + " AND deviceType:" +
AndroidSenseConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) {
query = "owner:" + user + " AND deviceId:" + deviceId;
}
String sensorTableName = getSensorEventTableName(sensor);
try {
List<AnalyticsDataRecord> records = deviceAnalyticsService.getAllEventsForDevice(sensorTableName, query);
if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) {
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setKey((String)record.getValue("word"));
sensorData.setTime((long) record.getValue("occurence"));
sensorData.setValue((String) record.getValue("sessionId"));
sensorDatas.add(sensorData);
}
} else {
Collections.sort(records, new Comparator<AnalyticsDataRecord>() {
@Override
public int compare(AnalyticsDataRecord o1, AnalyticsDataRecord o2) {
long t1 = (Long) o1.getValue("time");
long t2 = (Long) o2.getValue("time");
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
return 0;
}
}
});
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setTime((long) record.getValue("time"));
sensorData.setValue("" + (float) record.getValue(sensor));
sensorDatas.add(sensorData);
}
}
return sensorDatas.toArray(new SensorData[sensorDatas.size()]);
} catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return sensorDatas.toArray(new SensorData[sensorDatas.size()]);
}
}
/**
* get the event table from the sensor name.
*/
private String getSensorEventTableName(String sensorName) {
String sensorEventTableName;
switch (sensorName) {
case AndroidSenseConstants.SENSOR_ACCELEROMETER:
sensorEventTableName = "DEVICE_ACCELEROMETER_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_BATTERY:
sensorEventTableName = "DEVICE_BATTERY_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_GPS:
sensorEventTableName = "DEVICE_GPS_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_GRAVITY:
sensorEventTableName = "DEVICE_GRAVITY_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_GYROSCOPE:
sensorEventTableName = "DEVICE_GYROSCOPE_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_LIGHT:
sensorEventTableName = "DEVICE_LIGHT_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_MAGNETIC:
sensorEventTableName = "DEVICE_MAGNETIC_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_PRESSURE:
sensorEventTableName = "DEVICE_PRESSURE_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_PROXIMITY:
sensorEventTableName = "DevicePROXIMITYSummaryData";
break;
case AndroidSenseConstants.SENSOR_ROTATION:
sensorEventTableName = "DEVICE_ROTATION_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_WORDCOUNT:
sensorEventTableName = "WORD_COUNT_SUMMARY";
break;
default:
sensorEventTableName = "";
}
return sensorEventTableName;
}
}

View File

@ -1,41 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<jaxrs:server id="AndroidSenseManager" address="/">
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans>
<bean id="AndroidSenseManagerService"
class="org.wso2.carbon.device.mgt.iot.androidsense.manager.service.impl.AndroidSenseManagerService"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
</beans>

View File

@ -1,49 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>Android Sense</display-name>
<description>Android Sense</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/android_sense_mgt/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>android_sense</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>false</param-value>
</context-param>
</web-app>

View File

@ -3,20 +3,20 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>androidsense-plugin</artifactId>
<artifactId>device-mgt-iot-androidsense</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.manager.api</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.service.impl</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - Android Sense Management API</name>
<description>WSO2 Carbon - Android Sense Management Service-API Implementation</description>
<name>WSO2 Carbon - Android Sense API</name>
<description>WSO2 Carbon - Android Sense Service-API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
@ -97,7 +97,8 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>1.1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
@ -196,7 +197,7 @@
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>android_sense_mgt</warName>
<warName>android_sense</warName>
</configuration>
</plugin>
</plugins>

View File

@ -0,0 +1,235 @@
/*
* 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.androidsense.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
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.androidsense.service.impl.util.DeviceData;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@DeviceType(value = "android_sense")
@API(name = "android_sense", version = "1.0.0", context = "/android_sense", tags = {"android_sense"})
public interface AndroidSenseControllerService {
/**
* Service to push all the sensor data collected by the Android. Called by the Android device
*
* @param dataMsg The json string containing sensor readings
*/
@Path("device/sensors")
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response addSensorData(DeviceData dataMsg);
/**
* End point which is called by Front-end js to get Light sensor readings from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/light")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "light", name = "Light", description = "Read Light data from the device", type = "monitor")
Response getLightData(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Battery data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/battery")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "battery", name = "Battery", description = "Read Battery data from the device", type = "monitor")
Response getBattery(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get GPS data from the server.
*
* @param deviceId The registered device id call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/gps")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "gps", name = "gps", description = "Read GPS data from the device", type = "monitor")
Response getGPS(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Magnetic data readings from the server.
*
* @param deviceId The registered device id
* call to this API.
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/magnetic")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "magnetic", name = "Magnetic", description = "Read Magnetic data from the device", type = "monitor")
Response readMagnetic(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Accelerometer data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/accelerometer")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "accelerometer", name = "Accelerometer", description = "Read Accelerometer data from the device",
type = "monitor")
Response readAccelerometer(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Rotation data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/rotation")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "rotation", name = "Rotation", description = "Read Rotational Vector data from the device",
type = "monitor")
Response readRotation(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Proximity data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/proximity")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "proximity", name = "Proximity", description = "Read Proximity data from the device",
type = "monitor")
Response readProximity(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Gyroscope data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/gyroscope")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "gyroscope", name = "Gyroscope", description = "Read Gyroscope data from the device",
type = "monitor")
Response readGyroscope(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Pressure data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/pressure")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "pressure", name = "Pressure", description = "Read Pressure data from the device", type = "monitor")
Response readPressure(@PathParam("deviceId") String deviceId);
/**
* End point which is called by Front-end js to get Gravity data from the server.
*
* @param deviceId The registered device id
* @return This method returns a SensorRecord object.
*/
@Path("device/{deviceId}/sensors/gravity")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "gravity", name = "Gravity",
description = "Read Gravity data from the device", type = "monitor")
Response readGravity(@PathParam("deviceId") String deviceId);
@Path("device/{deviceId}/sensors/words")
@GET
@Consumes("application/json")
@Produces("application/json")
@Feature(code = "words", name = "Words", description = "Get the key words and occurrences",
type = "monitor")
Response getWords(@PathParam("deviceId") String deviceId, @QueryParam("sessionId") String sessionId);
/**
* End point to send the key words to the device
*
* @param deviceId The registered device Id.
* @param keywords The key words to be sent. (Comma separated values)
*/
@Path("device/{deviceId}/sensors/words")
@POST
@Feature(code = "keywords", name = "Add Keywords", description = "Send keywords to the device",
type = "operation")
Response sendKeyWords(@PathParam("deviceId") String deviceId, @FormParam("keywords") String keywords);
/**
* End point to send the key words to the device
*
* @param deviceId The registered device Id.
* @param threshold The key words to be sent. (Comma separated values)
*/
@Path("device/{deviceId}/sensors/words/threshold")
@POST
@Feature(code = "threshold", name = "Add a Threshold", description = "Set a threshold for word in the device",
type = "operation")
Response sendThreshold(@PathParam("deviceId") String deviceId, @FormParam("threshold") String threshold);
@Path("device/{deviceId}/sensors/words")
@DELETE
@Feature(code = "remove", name = "Remove Keywords", description = "Remove the keywords",
type = "operation")
Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words);
/**
* Retrieve Sensor data for the device type
*/
@Path("stats/device/{deviceId}/sensors/{sensorName}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getAndroidSenseDeviceStats(@PathParam("deviceId") String deviceId, @PathParam("sensorName") String sensor,
@QueryParam("from") long from, @QueryParam("to") long to);
}

View File

@ -0,0 +1,443 @@
/*
* 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.androidsense.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.DeviceData;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorData;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* The api for
*/
public class AndroidSenseControllerServiceImpl implements AndroidSenseControllerService {
private static Log log = LogFactory.getLog(AndroidSenseControllerServiceImpl.class);
private static AndroidSenseMQTTConnector androidSenseMQTTConnector;
/**
* Fetches the `AndroidSenseMQTTConnector` specific to this Android Sense controller service.
*
* @return the 'AndroidSenseMQTTConnector' instance bound to the 'AndroidSenseMQTTConnector' variable of
* this service.
*/
@SuppressWarnings("Unused")
public AndroidSenseMQTTConnector getAndroidSenseMQTTConnector() {
return androidSenseMQTTConnector;
}
/**
* Sets the `AndroidSenseMQTTConnector` variable of this Android Sense controller service.
*
* @param androidSenseMQTTConnector a 'AndroidSenseMQTTConnector' object that handles all MQTT related
* communications of any connected Android Sense device-type
*/
@SuppressWarnings("Unused")
public void setAndroidSenseMQTTConnector(final AndroidSenseMQTTConnector androidSenseMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
AndroidSenseControllerServiceImpl.androidSenseMQTTConnector = androidSenseMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
androidSenseMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public Response addSensorData(DeviceData dataMsg) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
SensorData[] sensorData = dataMsg.values;
String streamDef = null;
Object payloadData[] = null;
String sensorName = null;
for (SensorData sensor : sensorData) {
switch (sensor.key) {
case "battery":
streamDef = AndroidSenseConstants.BATTERY_STREAM_DEFINITION;
payloadData = new Float[]{Float.parseFloat(sensor.value)};
sensorName = AndroidSenseConstants.SENSOR_BATTERY;
break;
case "GPS":
streamDef = AndroidSenseConstants.GPS_STREAM_DEFINITION;
String gpsValue = sensor.value;
String gpsValuesString[] = gpsValue.split(",");
Float gpsValues[] = new Float[2];
gpsValues[0] = Float.parseFloat(gpsValuesString[0]);
gpsValues[1] = Float.parseFloat(gpsValuesString[0]);
payloadData = gpsValues;
sensorName = AndroidSenseConstants.SENSOR_GPS;
break;
default:
try {
int androidSensorId = Integer.parseInt(sensor.key);
String value = sensor.value;
String sensorValueString[] = value.split(",");
Float sensorValues[] = new Float[1];
switch (androidSensorId) {
case 1:
streamDef = AndroidSenseConstants.ACCELEROMETER_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_ACCELEROMETER;
break;
case 2:
streamDef = AndroidSenseConstants.MAGNETIC_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_MAGNETIC;
break;
case 4:
streamDef = AndroidSenseConstants.GYROSCOPE_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_GYROSCOPE;
break;
case 5:
streamDef = AndroidSenseConstants.LIGHT_STREAM_DEFINITION;
sensorName = AndroidSenseConstants.SENSOR_LIGHT;
payloadData = new Float[]{Float.parseFloat(sensorValueString[0])};
break;
case 6:
streamDef = AndroidSenseConstants.PRESSURE_STREAM_DEFINITION;
sensorName = AndroidSenseConstants.SENSOR_PRESSURE;
payloadData = new Float[]{Float.parseFloat(sensorValueString[0])};
break;
case 8:
streamDef = AndroidSenseConstants.PROXIMITY_STREAM_DEFINITION;
sensorName = AndroidSenseConstants.SENSOR_PROXIMITY;
payloadData = new Float[]{Float.parseFloat(sensorValueString[0])};
break;
case 9:
streamDef = AndroidSenseConstants.GRAVITY_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_GRAVITY;
break;
case 11:
streamDef = AndroidSenseConstants.ROTATION_STREAM_DEFINITION;
sensorValues[0] = Float.parseFloat(sensorValueString[0]) *
Float.parseFloat(sensorValueString[0]) * Float.parseFloat(sensorValueString[0]);
payloadData = sensorValues;
sensorName = AndroidSenseConstants.SENSOR_ROTATION;
break;
}
} catch (NumberFormatException e) {
log.error("Invalid sensor value is sent from the device");
continue;
}
}
Object metaData[] = {dataMsg.owner, AndroidSenseConstants.DEVICE_TYPE, dataMsg.deviceId, sensor.time};
if (streamDef != null && payloadData != null && payloadData.length > 0) {
try {
SensorDataManager.getInstance()
.setSensorRecord(dataMsg.deviceId, sensorName, sensor.value, sensor.time);
deviceAnalyticsService.publishEvent(streamDef, "1.0.0", metaData, new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return Response.status(Response.Status.UNSUPPORTED_MEDIA_TYPE.getStatusCode()).build();
}
}
}
return Response.ok().build();
}
public Response getLightData(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants
.SENSOR_LIGHT);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getBattery(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants
.SENSOR_BATTERY);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getGPS(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants
.SENSOR_GPS);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readMagnetic(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, AndroidSenseConstants
.SENSOR_MAGNETIC);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readAccelerometer(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_ACCELEROMETER);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readRotation(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_ROTATION);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readProximity(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_PROXIMITY);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readGyroscope(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_GYROSCOPE);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readPressure(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_PRESSURE);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response readGravity(String deviceId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_GRAVITY);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getWords(String deviceId, String sessionId) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
AndroidSenseConstants.SENSOR_WORDCOUNT);
return Response.ok().entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response sendKeyWords(String deviceId, String keywords) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "add", keywords);
return Response.ok().build();
} catch (TransportHandlerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response sendThreshold(String deviceId, String threshold) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "threshold", threshold);
return Response.ok().build();
} catch (TransportHandlerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response removeKeyWords(String deviceId, String words) {
try {
String username = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
androidSenseMQTTConnector.publishDeviceData(username, deviceId, "remove", words);
return Response.ok().build();
} catch (TransportHandlerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getAndroidSenseDeviceStats(String deviceId, String sensor, long from, long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
String user = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
List<SensorData> sensorDatas = new ArrayList<>();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
String query = "owner:" + user + " AND deviceId:" + deviceId + " AND deviceType:" +
AndroidSenseConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) {
query = "owner:" + user + " AND deviceId:" + deviceId;
}
String sensorTableName = getSensorEventTableName(sensor);
try {
List<AnalyticsDataRecord> records = deviceAnalyticsService.getAllEventsForDevice(sensorTableName, query);
if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) {
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setKey((String) record.getValue("word"));
sensorData.setTime((long) record.getValue("occurence"));
sensorData.setValue((String) record.getValue("sessionId"));
sensorDatas.add(sensorData);
}
} else {
Collections.sort(records, new Comparator<AnalyticsDataRecord>() {
@Override
public int compare(AnalyticsDataRecord o1, AnalyticsDataRecord o2) {
long t1 = (Long) o1.getValue("time");
long t2 = (Long) o2.getValue("time");
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
return 0;
}
}
});
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setTime((long) record.getValue("time"));
sensorData.setValue("" + (float) record.getValue(sensor));
sensorDatas.add(sensorData);
}
}
SensorData[] sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.ok().entity(sensorDetails).build();
} catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
SensorData[] senserDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(senserDetails).build();
}
}
/**
* get the event table from the sensor name.
*/
private String getSensorEventTableName(String sensorName) {
String sensorEventTableName;
switch (sensorName) {
case AndroidSenseConstants.SENSOR_ACCELEROMETER:
sensorEventTableName = "DEVICE_ACCELEROMETER_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_BATTERY:
sensorEventTableName = "DEVICE_BATTERY_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_GPS:
sensorEventTableName = "DEVICE_GPS_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_GRAVITY:
sensorEventTableName = "DEVICE_GRAVITY_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_GYROSCOPE:
sensorEventTableName = "DEVICE_GYROSCOPE_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_LIGHT:
sensorEventTableName = "DEVICE_LIGHT_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_MAGNETIC:
sensorEventTableName = "DEVICE_MAGNETIC_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_PRESSURE:
sensorEventTableName = "DEVICE_PRESSURE_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_PROXIMITY:
sensorEventTableName = "DevicePROXIMITYSummaryData";
break;
case AndroidSenseConstants.SENSOR_ROTATION:
sensorEventTableName = "DEVICE_ROTATION_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_WORDCOUNT:
sensorEventTableName = "WORD_COUNT_SUMMARY";
break;
default:
sensorEventTableName = "";
}
return sensorEventTableName;
}
}

View File

@ -0,0 +1,62 @@
/*
* 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.androidsense.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@DeviceType(value = "android_sense")
@API(name = "android_sense_mgt", version = "1.0.0", context = "/android_sense_mgt", tags = {"android_sense"})
public interface AndroidSenseManagerService {
@Path("device/{device_id}")
@POST
Response register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@PathParam("sketch_type") String sketchType);
}

View File

@ -16,51 +16,32 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.manager.service.impl;
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.androidsense.manager.service.impl.util.APIUtil;
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.utils.CarbonUtils;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.io.File;
import java.util.Date;
public class AndroidSenseManagerService {
public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerService {
private static Log log = LogFactory.getLog(AndroidSenseManagerService.class);
private static Log log = LogFactory.getLog(AndroidSenseManagerServiceImpl.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
@Path("manager/device")
@POST
public boolean register(@QueryParam("deviceId") String deviceId, @QueryParam("deviceName") String deviceName) {
public Response register(String deviceId, String deviceName) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return true;
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
}
Device device = new Device();
@ -75,41 +56,32 @@ public class AndroidSenseManagerService {
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
return Response.ok().build();
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
public Response removeDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
return Response.ok().build();
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{device_id}")
@PUT
public boolean updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name,
@Context HttpServletResponse response) {
public Response updateDevice(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
@ -121,46 +93,38 @@ public class AndroidSenseManagerService {
device.setType(AndroidSenseConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
return Response.ok().build();
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) {
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch(@PathParam("sketch_type") String sketchType) {
public Response downloadSketch(String sketchType) {
try {
String sep = File.separator;
String sketchFolder = "repository" + sep + "resources" + sep + "sketches" + sep + "android_sense" + sep;
String archivesPath = CarbonUtils.getCarbonHome() + sep + sketchFolder;
Response.ResponseBuilder rb = Response.ok(new File(archivesPath+sep+"androidsense.apk"));
Response.ResponseBuilder rb = Response.ok(new File(archivesPath + sep + "androidsense.apk"));
rb.header("Content-Disposition", "attachment; filename=\"" + "androidsense.apk" + "\"");
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
return Response.status(Response.Status.BAD_REQUEST).entity(ex.getMessage()).build();
}
}
}

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.transport;
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
@ -25,16 +25,15 @@ import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
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.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.util.DeviceData;
import org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.util.SensorData;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.DeviceData;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorData;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.androidsense.manager.service.impl.util;
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

View File

@ -31,113 +31,150 @@
<Permission>
<name>add sensor information</name>
<path>/login</path>
<url>/controller/sensors</url>
<url>/device/sensors</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>Get light information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/light</url>
<url>/device/*/sensors/light</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get battery information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/battery</url>
<url>/device/*/sensors/battery</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get gps information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/gps</url>
<url>/device/*/sensors/gps</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get magnetic information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/magnetic</url>
<url>/device/*/sensors/magnetic</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get accelerometer information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/accelerometer</url>
<url>/device/*/sensors/accelerometer</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get rotation information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/rotation</url>
<url>/device/*/sensors/rotation</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get proximity information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/proximity</url>
<url>/device/*/sensors/proximity</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get gyroscope information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/gyroscope</url>
<url>/device/*/sensors/gyroscope</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get pressure information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/pressure</url>
<url>/device/*/sensors/pressure</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get gravity information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/gravity</url>
<url>/device/*/sensors/gravity</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get words information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/words</url>
<url>/device/*/sensors/words</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get words information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/words</url>
<url>/device/*/sensors/words</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>set word threshold information</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/words/threshold</url>
<url>/device/*/sensors/words/threshold</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>delete words</name>
<path>/login</path>
<url>/controller/device/{deviceId}/sensors/words</url>
<url>/device/*/sensors/words</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>get device stats</name>
<path>/login</path>
<url>/controller/stats/device/{deviceId}/sensors/{sensorName}</url>
<url>/stats/device/*/sensors/*</url>
<method>GET</method>
<scope></scope>
</Permission>
</PermissionConfiguration>
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/register</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/*/download</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>POST</method>
<scope></scope>
</Permission>
</PermissionConfiguration>

View File

@ -22,12 +22,14 @@
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="AndroidSenseController" address="/">
<jaxrs:server id="AndroidSense" address="/">
<jaxrs:serviceBeans>
<bean id="AndroidSenseControllerService"
class="org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.AndroidSenseControllerService">
class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.AndroidSenseControllerServiceImpl">
<property name="androidSenseMQTTConnector" ref="mqttConnectorBean"/>
</bean>
<bean id="AndroidSenseManagerService"
class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.AndroidSenseManagerServiceImpl"/>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
@ -35,7 +37,7 @@
</jaxrs:server>
<bean id="mqttConnectorBean"
class="org.wso2.carbon.device.mgt.iot.androidsense.controller.service.impl.transport.AndroidSenseMQTTConnector">
class="org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector">
</bean>
</beans>

View File

@ -34,8 +34,7 @@
<modules>
<module>org.wso2.carbon.device.mgt.iot.androidsense.analytics</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.controller.api</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.manager.api</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.plugin</module>
<module>org.wso2.carbon.device.mgt.iot.androidsense.ui</module>
</modules>

View File

@ -1,170 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>arduino-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server Arduino Controller API</name>
<description>WSO2 Carbon - Arduino Service Controller API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
</dependency>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>arduino</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,300 +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.arduino.controller.service.impl;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.common.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
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.arduino.controller.service.impl.dto.DeviceData;
import org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.dto.SensorData;
import org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.transport.ArduinoMQTTConnector;
import org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.util.ArduinoServiceUtils;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
@API( name="arduino", version="1.0.0", context="/arduino", tags = {"arduino"})
@DeviceType( value = "arduino")
public class ArduinoControllerService {
private static Log log = LogFactory.getLog(ArduinoControllerService.class);
private static Map<String, LinkedList<String>> replyMsgQueue = new HashMap<>();
private static Map<String, LinkedList<String>> internalControlsQueue = new HashMap<>();
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private ArduinoMQTTConnector arduinoMQTTConnector;
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
/**
* @return the queue containing all the MQTT reply messages from all Arduinos communicating to this service
*/
public static Map<String, LinkedList<String>> getReplyMsgQueue() {
return replyMsgQueue;
}
/**
* @return the queue containing all the MQTT controls received to be sent to any Arduinos connected to this server
*/
public static Map<String, LinkedList<String>> getInternalControlsQueue() {
return internalControlsQueue;
}
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
/**
* @return the "ArduinoMQTTConnector" object of this ArduinoControllerService instance
*/
@SuppressWarnings("unused")
public ArduinoMQTTConnector getArduinoMQTTConnector() {
return arduinoMQTTConnector;
}
/**
* @param arduinoMQTTConnector an object of type "ArduinoMQTTConnector" specific for this ArduinoControllerService
*/
@SuppressWarnings("unused")
public void setArduinoMQTTConnector(final ArduinoMQTTConnector arduinoMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
ArduinoControllerService.this.arduinoMQTTConnector = arduinoMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
arduinoMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, ArduinoMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Path("controller/register/device/{deviceId}/{ip}/{port}")
@POST
public String registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletResponse response,
@Context HttpServletRequest request) {
String result;
if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: ");
}
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) {
log.debug(result);
}
return result;
}
@Path("controller/device/{deviceId}/bulb")
@POST
@Feature(code = "bulb", name = "Control Bulb", type = "operation", description = "Control Bulb on Arduino Uno")
public void switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("state") String state, @Context HttpServletResponse response) {
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String operation = "BULB:" + state.toUpperCase();
log.info(operation);
if (deviceControlList == null) {
deviceControlList = new LinkedList<>();
deviceControlList.add(operation);
internalControlsQueue.put(deviceId, deviceControlList);
} else {
deviceControlList.add(operation);
}
response.setStatus(Response.Status.OK.getStatusCode());
}
@Path("controller/device/{deviceId}/temperature")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature( code="temperature", name="Temperature", type="monitor", description="Request temperature reading from Arduino agent")
public SensorRecord requestTemperature(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
try {
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ArduinoConstants.SENSOR_TEMPERATURE);
} catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
@Path("controller/sensor")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void pushData(DeviceData dataMsg, @Context HttpServletResponse response) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String deviceId = dataMsg.deviceId;
float pinData = dataMsg.value;
SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
String.valueOf(pinData),
Calendar.getInstance().getTimeInMillis());
if (!ArduinoServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish pin data of Arduino with ID [" +
deviceId + "] of owner [" + owner + "]");
}
}
@Path("controller/device/{deviceId}/controls")
@GET
public String readControls(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@Context HttpServletResponse response) {
String result;
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (deviceControlList == null) {
result = "No controls have been set for device " + deviceId + " of owner " + owner;
response.setStatus(HttpStatus.SC_NO_CONTENT);
} else {
try {
result = deviceControlList.remove();
response.setStatus(HttpStatus.SC_ACCEPTED);
} catch (NoSuchElementException ex) {
result = "There are no more controls for device " + deviceId + " of owner " + owner;
response.setStatus(HttpStatus.SC_NO_CONTENT);
}
}
if (log.isDebugEnabled()) {
log.debug(result);
}
return result;
}
@Path("controller/temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData(final DeviceData dataMsg, @Context HttpServletResponse response,
@Context HttpServletRequest request) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String deviceId = dataMsg.deviceId;
float temperature = dataMsg.value;
SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis());
if (!ArduinoServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish temperature data of Arduino with ID [" + deviceId +
"] of owner [" + owner + "]");
}
}
/**
* Retreive Sensor data for the device type
*/
@Path("controller/stats/device/{deviceId}/sensors/temperature")
@GET
@Consumes("application/json")
@Produces("application/json")
public SensorData[] getArduinoTemperatureStats(@PathParam("deviceId") String deviceId,
@QueryParam("from") long from,
@QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
List<SensorData> sensorDatas = new ArrayList<>();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
String query = "deviceId:" + deviceId + " AND deviceType:" +
ArduinoConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = ArduinoConstants.TEMPERATURE_EVENT_TABLE;
try {
List<AnalyticsDataRecord> records = deviceAnalyticsService.getAllEventsForDevice(sensorTableName, query);
Collections.sort(records, new Comparator<AnalyticsDataRecord>() {
@Override
public int compare(AnalyticsDataRecord o1, AnalyticsDataRecord o2) {
long t1 = (Long) o1.getValue("time");
long t2 = (Long) o2.getValue("time");
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
return 0;
}
}
});
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setTime((long) record.getValue("time"));
sensorData.setValue("" + (float) record.getValue(ArduinoConstants.SENSOR_TEMPERATURE));
sensorDatas.add(sensorData);
}
return sensorDatas.toArray(new SensorData[sensorDatas.size()]);
} catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return sensorDatas.toArray(new SensorData[sensorDatas.size()]);
}
}
}

View File

@ -1,193 +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.arduino.controller.service.impl.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.ArduinoControllerService;
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import java.io.File;
import java.util.LinkedList;
import java.util.UUID;
public class ArduinoMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(ArduinoMQTTConnector.class);
private static final String subscribeTopic = "wso2/" + ArduinoConstants.DEVICE_TYPE + "/#";
private static final String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private static final String MESSAGE_TO_SEND = "IN";
private static final String MESSAGE_RECEIVED = "OUT";
private ArduinoMQTTConnector() {
super(iotServerSubscriber, ArduinoConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
}
@Override
public void connect() {
Runnable connector = new Runnable() {
public void run() {
while (!isConnected()) {
try {
String brokerUsername = MqttConfig.getInstance().getMqttQueueUsername();
String brokerPassword = MqttConfig.getInstance().getMqttQueuePassword();
setUsernameAndPassword(brokerUsername, brokerPassword);
connectToQueue();
} catch (TransportHandlerException e) {
log.error("Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Connector: Thread Sleep Interrupt Exception.", ex);
}
}
try {
subscribeToQueue();
} catch (TransportHandlerException e) {
log.warn("Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) throws TransportHandlerException {
if(messageParams.length != 0) {
// owner and the deviceId are extracted from the MQTT topic to which the message was received.
// <Topic> = [ServerName/Owner/DeviceType/DeviceId]
String topic = messageParams[0];
String[] topicParams = topic.split("/");
String deviceId = topicParams[3];
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [DEVICE.ID-" + deviceId + "]");
}
int lastIndex = message.toString().lastIndexOf(":");
String msgContext = message.toString().substring(lastIndex + 1);
LinkedList<String> deviceControlList;
LinkedList<String> replyMessageList;
if (msgContext.equals(MESSAGE_TO_SEND) || msgContext.equals(ArduinoConstants.STATE_ON) || msgContext.equals(
ArduinoConstants.STATE_OFF)) {
if (log.isDebugEnabled()) {
log.debug("Received a control message: ");
log.debug("Control message topic: " + topic);
log.debug("Control message: " + message.toString());
}
synchronized (ArduinoControllerService.getInternalControlsQueue()) {
deviceControlList = ArduinoControllerService.getInternalControlsQueue().get(deviceId);
if (deviceControlList == null) {
ArduinoControllerService.getInternalControlsQueue()
.put(deviceId, deviceControlList = new LinkedList<String>());
}
}
deviceControlList.add(message.toString());
} else if (msgContext.equals(MESSAGE_RECEIVED)) {
if (log.isDebugEnabled()) {
log.debug("Received reply from a device: ");
log.debug("Reply message topic: " + topic);
log.debug("Reply message: " + message.toString().substring(0, lastIndex));
}
synchronized (ArduinoControllerService.getReplyMsgQueue()) {
replyMessageList = ArduinoControllerService.getReplyMsgQueue().get(deviceId);
if (replyMessageList == null) {
ArduinoControllerService.getReplyMsgQueue()
.put(deviceId, replyMessageList = new LinkedList<>());
}
}
replyMessageList.add(message.toString());
}
}
}
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
try {
closeConnection();
} catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
+ " for device-type - " + ArduinoConstants.DEVICE_TYPE, e);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception at device-type - " +
ArduinoConstants.DEVICE_TYPE, e1);
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void processIncomingMessage() throws TransportHandlerException {
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
}
}

View File

@ -1,48 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="ArduinoController" address="/">
<jaxrs:serviceBeans>
<bean id="ArduinoControllerService"
class="org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.ArduinoControllerService">
<property name="arduinoMQTTConnector" ref="arduinoMQTTConnector"/>
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
<bean id="arduinoMQTTConnector"
class="org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.transport.ArduinoMQTTConnector">
</bean>
</beans>

View File

@ -1,180 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>arduino-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server Arduino ManagerService API</name>
<description>WSO2 Carbon - Arduino ManagerService API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
</dependency>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>arduino_mgt</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,274 +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.arduino.manager.service.impl;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClient;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
public class ArduinoManagerService {
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
@Path("manager/device/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
}
@Path("manager/device/{device_id}")
@PUT
public boolean updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(ArduinoConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
}
}
@Path("manager/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device[] getArduinoDevices() {
try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(
APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforArduino = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(ArduinoConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforArduino.add(device);
}
}
return userDevicesforArduino.toArray(new Device[]{});
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
}
}
@Path("manager/device/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("deviceName") String customDeviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), customDeviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
@Path("manager/device/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {ArduinoConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
ArduinoConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + ArduinoConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//Register the device with CDMF
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
ArduinoConstants.DEVICE_TYPE, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
private boolean register(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(ArduinoConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
}
}
}

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="ArduinoManager" address="/">
<jaxrs:serviceBeans>
<bean id="ArduinoManagerService"
class="org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl.ArduinoManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

View File

@ -1,51 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>Arduino</display-name>
<description>Arduino</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/arduino/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>arduino</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

View File

@ -1,23 +1,74 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>androidsense-plugin</artifactId>
<artifactId>device-mgt-iot-arduino</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.controller.api</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.service.impl</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - Android Sense Controller API</name>
<description>WSO2 Carbon - Android Sense Service Controller API Implementation</description>
<name>WSO2 Carbon - IoT Server Arduino Service API</name>
<description>WSO2 Carbon - Arduino Service API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>1.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
@ -36,6 +87,20 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>1.1.0-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
@ -52,6 +117,7 @@
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
@ -73,9 +139,10 @@
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.androidsense.plugin</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.arduino.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
@ -95,82 +162,6 @@
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
@ -178,11 +169,12 @@
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
@ -196,10 +188,10 @@
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>android_sense</warName>
<warName>arduino</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>
</project>

View File

@ -0,0 +1,85 @@
/*
* 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.arduino.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
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.arduino.service.impl.dto.DeviceData;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "arduino", version = "1.0.0", context = "/arduino", tags = {"arduino"})
@DeviceType(value = "arduino")
public interface ArduinoControllerService {
@Path("register/device/{deviceId}/{ip}/{port}")
@POST
Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletRequest request);
@Path("device/{deviceId}/bulb")
@POST
@Feature(code = "bulb", name = "Control Bulb", type = "operation", description = "Control Bulb on Arduino Uno")
Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("state") String state);
@Path("device/{deviceId}/temperature")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "temperature", name = "Temperature", type = "monitor", description = "Request temperature reading " +
"from Arduino agent")
Response requestTemperature(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol);
@Path("sensor")
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response pushData(DeviceData dataMsg);
@Path("{deviceId}/controls")
@GET
Response readControls(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol);
@Path("temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response pushTemperatureData(final DeviceData dataMsg, @Context HttpServletRequest request);
/**
* Retreive Sensor data for the device type
*/
@Path("stats/device/{deviceId}/sensors/temperature")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to);
}

View File

@ -0,0 +1,200 @@
/*
* 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.arduino.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.DeviceData;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorData;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.ArduinoServiceUtils;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.concurrent.ConcurrentHashMap;
public class ArduinoControllerServiceImpl implements ArduinoControllerService {
private static Log log = LogFactory.getLog(ArduinoControllerServiceImpl.class);
private static Map<String, LinkedList<String>> internalControlsQueue = new HashMap<>();
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
@Override
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort, HttpServletRequest request) {
String result;
if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + " of owner: ");
}
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok(result).build();
}
@Override
public Response switchBulb(String deviceId, String protocol, String state) {
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String operation = "BULB:" + state.toUpperCase();
log.info(operation);
if (deviceControlList == null) {
deviceControlList = new LinkedList<>();
deviceControlList.add(operation);
internalControlsQueue.put(deviceId, deviceControlList);
} else {
deviceControlList.add(operation);
}
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@Override
public Response requestTemperature(String deviceId, String protocol) {
try {
SensorRecord sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ArduinoConstants.SENSOR_TEMPERATURE);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecord).build();
} catch (DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Override
public Response pushData(DeviceData dataMsg) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String deviceId = dataMsg.deviceId;
float pinData = dataMsg.value;
SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
String.valueOf(pinData),
Calendar.getInstance().getTimeInMillis());
if (!ArduinoServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
log.warn("An error occured whilst trying to publish pin data of Arduino with ID [" +
deviceId + "] of owner [" + owner + "]");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@Override
public Response readControls(String deviceId, String protocol) {
String result;
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
if (deviceControlList == null) {
result = "No controls have been set for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.CONFLICT.getStatusCode()).entity(result).build();
} else {
try {
result = deviceControlList.remove();
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(result).build();
} catch (NoSuchElementException ex) {
result = "There are no more controls for device " + deviceId + " of owner " + owner;
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.status(Response.Status.NO_CONTENT.getStatusCode()).entity(result).build();
}
}
}
@Override
public Response pushTemperatureData(final DeviceData dataMsg, HttpServletRequest request) {
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String deviceId = dataMsg.deviceId;
float temperature = dataMsg.value;
SensorDataManager.getInstance().setSensorRecord(deviceId, ArduinoConstants.SENSOR_TEMPERATURE,
String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis());
if (!ArduinoServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
log.warn("An error occured whilst trying to publish temperature data of Arduino with ID [" + deviceId +
"] of owner [" + owner + "]");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.status(Response.Status.OK.getStatusCode()).build();
}
@Override
public Response getArduinoTemperatureStats(String deviceId, long from, long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
List<SensorData> sensorDatas = new ArrayList<>();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
String query = "deviceId:" + deviceId + " AND deviceType:" +
ArduinoConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = ArduinoConstants.TEMPERATURE_EVENT_TABLE;
SensorData[] sensorDetails;
try {
List<AnalyticsDataRecord> records = deviceAnalyticsService.getAllEventsForDevice(sensorTableName, query);
Collections.sort(records, new Comparator<AnalyticsDataRecord>() {
@Override
public int compare(AnalyticsDataRecord o1, AnalyticsDataRecord o2) {
long t1 = (Long) o1.getValue("time");
long t2 = (Long) o2.getValue("time");
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
return 0;
}
}
});
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setTime((long) record.getValue("time"));
sensorData.setValue("" + (float) record.getValue(ArduinoConstants.SENSOR_TEMPERATURE));
sensorDatas.add(sensorData);
}
sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorDetails).build();
} catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(sensorDetails).build();
}
}
}

View File

@ -0,0 +1,68 @@
/*
* 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.arduino.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"})
@DeviceType(value = "arduino")
public interface ArduinoManagerService {
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getArduinoDevices();
@Path("devices/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String customDeviceName);
@Path("devices/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName);
}

View File

@ -0,0 +1,240 @@
/*
* 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.arduino.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClient;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@API(name = "arduino_mgt", version = "1.0.0", context = "/arduino_mgt", tags = {"arduino"})
@DeviceType(value = "arduino")
public class ArduinoManagerServiceImpl implements ArduinoManagerService {
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
@Override
public Response removeDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
return Response.status(Response.Status.OK.getStatusCode()).entity(true).build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Override
public Response updateDevice(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(ArduinoConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.status(Response.Status.OK.getStatusCode()).entity(true).build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Override
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.status(Response.Status.OK.getStatusCode()).entity(device).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Override
public Response getArduinoDevices() {
try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(
APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforArduino = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(ArduinoConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforArduino.add(device);
}
}
Device[] devices = userDevicesforArduino.toArray(new Device[]{});
return Response.status(Response.Status.OK.getStatusCode()).entity(devices).build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(true).build();
}
}
@Override
public Response downloadSketch(String customDeviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), customDeviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
@Override
public Response generateSketchLink(String deviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
return rb.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
if (apiApplicationKey == null) {
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {ArduinoConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
ArduinoConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + ArduinoConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner,
scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//Register the device with CDMF
boolean status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
ArduinoConstants.DEVICE_TYPE, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
private boolean register(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ArduinoConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(ArduinoConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
return APIUtil.getDeviceManagementService().enrollDevice(device);
} catch (DeviceManagementException e) {
return false;
}
}
}

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.dto;
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.exception;
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.exception;
public class ArduinoException extends Exception {
private static final long serialVersionUID = 118512086957330189L;

View File

@ -1,10 +1,11 @@
package org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api.util;
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
/**
* This class provides utility functions used by REST-API.
*/

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl.util;
package org.wso2.carbon.device.mgt.iot.arduino.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -26,16 +26,10 @@ import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import javax.ws.rs.HttpMethod;
import java.io.BufferedReader;
import java.io.IOException;
@ -50,8 +44,6 @@ import java.util.concurrent.Future;
public class ArduinoServiceUtils {
private static final Log log = LogFactory.getLog(ArduinoServiceUtils.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,

View File

@ -31,57 +31,85 @@
<Permission>
<name>Register Device</name>
<path>/login</path>
<url>/controller/register/device/{deviceId}/{ip}/{port}</url>
<url>/register/device/*/*/*</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>get device bulb statjs</name>
<path>/login</path>
<url>/controller/device/{deviceId}/bulb</url>
<url>/device/*/bulb</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>get device temperature</name>
<path>/login</path>
<url>/controller/device/{deviceId}/temperature</url>
<url>/device/*/temperature</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>get device temperature</name>
<path>/login</path>
<url>/controller/device/{deviceId}/temperature</url>
<url>/device/*/temperature</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>get device temperature</name>
<path>/login</path>
<url>/controller/sensor</url>
<url>/sensor</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>get controls</name>
<path>/login</path>
<url>/controller/device/{deviceId}/controls</url>
<url>/device/*/controls</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>push temperature</name>
<path>/login</path>
<url>/controller/temperature</url>
<url>/temperature</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>get temperature</name>
<path>/login</path>
<url>/controller/stats/device/{deviceId}/sensors/temperature</url>
<url>/stats/device/*/sensors/temperature</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/download</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>PUT</method>
<scope></scope>
</Permission>
</PermissionConfiguration>

View File

@ -23,10 +23,13 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="DigitalDisplayManager" address="/">
<jaxrs:server id="Arduino" address="/">
<jaxrs:serviceBeans>
<bean id="DigitalDisplayManagerService"
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api.DigitalDisplayManagerService">
<bean id="ArduinoManagerService"
class="org.wso2.carbon.device.mgt.iot.arduino.service.impl.ArduinoManagerServiceImpl">
</bean>
<bean id="ArduinoControllerService"
class="org.wso2.carbon.device.mgt.iot.arduino.service.impl.ArduinoControllerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
@ -35,4 +38,3 @@
</jaxrs:server>
</beans>

View File

@ -35,8 +35,7 @@
<modules>
<module>org.wso2.carbon.device.mgt.iot.arduino.analytics</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.controller.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.plugin.impl</module>
<module>org.wso2.carbon.device.mgt.iot.arduino.ui</module>
</modules>

View File

@ -1,243 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>digital-display-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server DigitalDisplay API</name>
<description>WSO2 Carbon - Digital Display Service API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>digital_display</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,432 +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.digitaldisplay.controller.api;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
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.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.exception.DigitalDisplayException;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.util.DigitalDisplayMQTTConnector;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
@API(name = "digital_display", version = "1.0.0", context = "/digital_display", tags = {"digital_display"})
@DeviceType(value = "digital_display")
public class DigitalDisplayControllerService {
private static Log log = LogFactory.getLog(DigitalDisplayControllerService.class);
private static DigitalDisplayMQTTConnector digitalDisplayMQTTConnector;
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DigitalDisplayMQTTConnector getDigitalDisplayMQTTConnector() {
return DigitalDisplayControllerService.digitalDisplayMQTTConnector;
}
public void setDigitalDisplayMQTTConnector(final
DigitalDisplayMQTTConnector digitalDisplayMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DigitalDisplayControllerService.digitalDisplayMQTTConnector = digitalDisplayMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
digitalDisplayMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, DigitalDisplayMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
/**
* Restart the running browser in the given digital display.
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/restart-browser")
@POST
@Feature(code = "restart-browser", name = "Restart Browser", type = "operation",
description = "Restart Browser in Digital Display")
public void restartBrowser(@PathParam("deviceId") String deviceId,
@HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_BROWSER_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Terminate all running processes. If this execute we have to reboot digital display manually.
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/terminate-display")
@POST
@Feature(code = "terminate-display", name = "Terminate Display", type = "operation",
description = "Terminate all running process in Digital Display")
public void terminateDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.TERMINATE_DISPLAY_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Reboot running digital display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/restart-display")
@POST
@Feature(code = "restart-display", name = "Restart Display", type = "operation",
description = "Restart Digital Display")
public void restartDisplay(@PathParam("deviceId") String deviceId,
@HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_DISPLAY_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Search through the sequence and edit requested resource
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
* @param name name of page need to change
* @param attribute this can be path,time or type
* @param newValue page is used to replace path
*/
@Path("device/{deviceId}/edit-sequence")
@POST
@Feature(code = "edit-sequence", name = "Edit Sequence", type = "operation",
description = "Search through the sequence and edit requested resource in Digital Display")
public void editSequence(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@FormParam("attribute") String attribute, @FormParam("new-value") String newValue,
@HeaderParam("sessionId") String sessionId, @Context HttpServletResponse response) {
try {
String params = name + "|" + attribute + "|" + newValue;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.EDIT_SEQUENCE_CONSTANT + "::", params);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("device/{deviceId}/upload-content")
@POST
@Feature(code = "upload-content", name = "Upload Content", type = "operation",
description = "Search through the sequence and edit requested resource in Digital Display")
public void uploadContent(@PathParam("deviceId") String deviceId, @FormParam("remote-path") String remotePath,
@FormParam("screen-name") String screenName, @HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
String params = remotePath + "|" + screenName;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.UPLOAD_CONTENT_CONSTANT + "::",
params);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Add new resource end to the existing sequence
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
* @param type type of new resource
* @param time new resource visible time
* @param path URL of the new resource
*/
@Path("device/{deviceId}/add-resource")
@POST
@Feature(code = "add-resource", name = "Add Resource", type = "operation",
description = "Add new resource end to the existing sequence in Digital Display")
public void addNewResource(@PathParam("deviceId") String deviceId,
@FormParam("type") String type,
@FormParam("time") String time,
@FormParam("path") String path,
@FormParam("name") String name,
@FormParam("position") String position,
@HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
String params;
try {
if (position.isEmpty()) {
params = type + "|" + time + "|" + path + "|" + name;
} else {
params = type + "|" + time + "|" + path + "|" + name +
"|" + "after=" + position;
}
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.ADD_NEW_RESOURCE_CONSTANT + "::", params);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Delete a resource in sequence
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
* @param name name of the page no need to delete
*/
@Path("device/{deviceId}/remove-resource")
@POST
@Feature(code = "remove-resource", name = "Remove Resource", type = "operation",
description = "Delete a resource from sequence in Digital Display")
public void removeResource(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@HeaderParam("sessionId") String sessionId, @Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.REMOVE_RESOURCE_CONSTANT + "::", name);
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Restart HTTP in running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/restart-server")
@POST
@Feature(code = "restart-server", name = "Restart Server", type = "operation",
description = "Stop HTTP Server running in Digital Display")
public void restartServer(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_SERVER_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Get screenshot of running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/screenshot")
@POST
@Feature(code = "screenshot", name = "Take Screenshot", type = "operation",
description = "Show current view in Digital Display")
public void showScreenshot(@PathParam("deviceId") String deviceId,
@HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.SCREENSHOT_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Get statistics of running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/get-device-status")
@POST
@Feature(code = "get-device-status", name = "Get Device Statistics", type = "operation",
description = "Current status in Digital Display")
public void getDevicestatus(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_DEVICE_STATUS_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Stop specific display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param response response type of the method
*/
@Path("device/{deviceId}/get-content-list")
@POST
@Feature(code = "get-content-list", name = "Get Content List", type = "operation",
description = "Content List in Digital Display")
public void getResources(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId,
@Context HttpServletResponse response) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_CONTENTLIST_CONSTANT + "::", "");
response.setStatus(Response.Status.OK.getStatusCode());
} catch (DeviceManagementException e) {
log.error(e);
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} catch (DigitalDisplayException e) {
log.error(e);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Send message via MQTT protocol
*
* @param deviceId id of the target digital display
* @param operation operation need to execute
* @param param parameters need to given operation
* @throws DeviceManagementException
* @throws DigitalDisplayException
*/
private void sendCommandViaMQTT(String deviceId, String operation, String param)
throws DeviceManagementException, DigitalDisplayException {
String topic = String.format(DigitalDisplayConstants.PUBLISH_TOPIC, deviceId);
String payload = operation + param;
try {
digitalDisplayMQTTConnector.publishToDigitalDisplay(topic, payload, 2, false);
} catch (TransportHandlerException e) {
String errorMessage = "Error publishing data to device with ID " + deviceId;
throw new DigitalDisplayException(errorMessage, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}

View File

@ -1,243 +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.digitaldisplay.manager.api;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClient;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
public class DigitalDisplayManagerService {
private static Log log = LogFactory.getLog(DigitalDisplayManagerService.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
@Path("manager/device")
@POST
public boolean register(@QueryParam("deviceId") String deviceId, @QueryParam("name") String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@PUT
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String
sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DigitalDisplayConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DigitalDisplayConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + DigitalDisplayConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
boolean status;
//Register the device with CDMF
status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

View File

@ -1,68 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Digital-Display-Agent-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS MDM Android Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/digital_display/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>digital_display</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

View File

@ -4,14 +4,15 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>digital-display-plugin</artifactId>
<artifactId>device-mgt-iot-digitaldisplay</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server DigitalDisplay API</name>
<description>WSO2 Carbon - Digital Display Service API Implementation</description>
@ -36,6 +37,32 @@
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>1.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.jwt.client.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
@ -237,7 +264,7 @@
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>digital_display_mgt</warName>
<warName>digital_display</warName>
</configuration>
</plugin>
</plugins>

View File

@ -0,0 +1,175 @@
/*
* 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.digitaldisplay.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import javax.websocket.server.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Response;
@API(name = "digital_display", version = "1.0.0", context = "/digital_display", tags = {"digital_display"})
@DeviceType(value = "digital_display")
public interface DigitalDisplayControllerService {
/**
* Restart the running browser in the given digital display.
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/restart-browser")
@POST
@Feature(code = "restart-browser", name = "Restart Browser", type = "operation",
description = "Restart Browser in Digital Display")
Response restartBrowser(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Terminate all running processes. If this execute we have to reboot digital display manually.
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/terminate-display")
@POST
@Feature(code = "terminate-display", name = "Terminate Display", type = "operation",
description = "Terminate all running process in Digital Display")
Response terminateDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Reboot running digital display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/restart-display")
@POST
@Feature(code = "restart-display", name = "Restart Display", type = "operation",
description = "Restart Digital Display")
Response restartDisplay(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Search through the sequence and edit requested resource
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param name name of page need to change
* @param attribute this can be path,time or type
* @param newValue page is used to replace path
*/
@Path("device/{deviceId}/edit-sequence")
@POST
@Feature(code = "edit-sequence", name = "Edit Sequence", type = "operation",
description = "Search through the sequence and edit requested resource in Digital Display")
Response editSequence(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@FormParam("attribute") String attribute, @FormParam("new-value") String newValue,
@HeaderParam("sessionId") String sessionId);
@Path("device/{deviceId}/upload-content")
@POST
@Feature(code = "upload-content", name = "Upload Content", type = "operation",
description = "Search through the sequence and edit requested resource in Digital Display")
Response uploadContent(@PathParam("deviceId") String deviceId, @FormParam("remote-path") String remotePath,
@FormParam("screen-name") String screenName, @HeaderParam("sessionId") String sessionId);
/**
* Add new resource end to the existing sequence
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param type type of new resource
* @param time new resource visible time
* @param path URL of the new resource
*/
@Path("device/{deviceId}/add-resource")
@POST
@Feature(code = "add-resource", name = "Add Resource", type = "operation",
description = "Add new resource end to the existing sequence in Digital Display")
Response addNewResource(@PathParam("deviceId") String deviceId, @FormParam("type") String type,
@FormParam("time") String time, @FormParam("path") String path,
@FormParam("name") String name, @FormParam("position") String position,
@HeaderParam("sessionId") String sessionId);
/**
* Delete a resource in sequence
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
* @param name name of the page no need to delete
*/
@Path("device/{deviceId}/remove-resource")
@POST
@Feature(code = "remove-resource", name = "Remove Resource", type = "operation",
description = "Delete a resource from sequence in Digital Display")
Response removeResource(@PathParam("deviceId") String deviceId, @FormParam("name") String name,
@HeaderParam("sessionId") String sessionId);
/**
* Restart HTTP in running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/restart-server")
@POST
@Feature(code = "restart-server", name = "Restart Server", type = "operation",
description = "Stop HTTP Server running in Digital Display")
Response restartServer(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Get screenshot of running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/screenshot")
@POST
@Feature(code = "screenshot", name = "Take Screenshot", type = "operation",
description = "Show current view in Digital Display")
Response showScreenshot(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Get statistics of running display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/get-device-status")
@POST
@Feature(code = "get-device-status", name = "Get Device Statistics", type = "operation",
description = "Current status in Digital Display")
Response getDevicestatus(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
/**
* Stop specific display
*
* @param deviceId id of the controlling digital display
* @param sessionId web socket id of the method invoke client
*/
@Path("device/{deviceId}/get-content-list")
@POST
@Feature(code = "get-content-list", name = "Get Content List", type = "operation",
description = "Content List in Digital Display")
Response getResources(@PathParam("deviceId") String deviceId, @HeaderParam("sessionId") String sessionId);
}

View File

@ -0,0 +1,242 @@
/*
* 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.digitaldisplay.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
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.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.exception.DigitalDisplayException;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.util.DigitalDisplayMQTTConnector;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import javax.ws.rs.FormParam;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
public class DigitalDisplayControllerServiceImpl implements DigitalDisplayControllerService {
private static Log log = LogFactory.getLog(DigitalDisplayControllerServiceImpl.class);
private static DigitalDisplayMQTTConnector digitalDisplayMQTTConnector;
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public DigitalDisplayMQTTConnector getDigitalDisplayMQTTConnector() {
return DigitalDisplayControllerServiceImpl.digitalDisplayMQTTConnector;
}
public void setDigitalDisplayMQTTConnector(final
DigitalDisplayMQTTConnector digitalDisplayMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
DigitalDisplayControllerServiceImpl.digitalDisplayMQTTConnector = digitalDisplayMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
digitalDisplayMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, DigitalDisplayMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
public Response restartBrowser(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_BROWSER_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response terminateDisplay(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.TERMINATE_DISPLAY_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response restartDisplay(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_DISPLAY_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response editSequence(String deviceId, String name, String attribute, String newValue, String sessionId) {
try {
String params = name + "|" + attribute + "|" + newValue;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.EDIT_SEQUENCE_CONSTANT + "::", params);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response uploadContent(String deviceId, String remotePath, String screenName, String sessionId) {
try {
String params = remotePath + "|" + screenName;
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.UPLOAD_CONTENT_CONSTANT + "::",
params);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response addNewResource(String deviceId, String type, String time, String path, String name, String position,
String sessionId) {
String params;
try {
if (position.isEmpty()) {
params = type + "|" + time + "|" + path + "|" + name;
} else {
params = type + "|" + time + "|" + path + "|" + name +
"|" + "after=" + position;
}
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.ADD_NEW_RESOURCE_CONSTANT + "::", params);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response removeResource(String deviceId, String name, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.REMOVE_RESOURCE_CONSTANT + "::", name);
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response restartServer(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.RESTART_SERVER_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response showScreenshot(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.SCREENSHOT_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevicestatus(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_DEVICE_STATUS_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getResources(String deviceId, String sessionId) {
try {
sendCommandViaMQTT(deviceId, sessionId + "::" + DigitalDisplayConstants.GET_CONTENTLIST_CONSTANT + "::", "");
return Response.ok().build();
} catch (DeviceManagementException e) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} catch (DigitalDisplayException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
/**
* Send message via MQTT protocol
*
* @param deviceId id of the target digital display
* @param operation operation need to execute
* @param param parameters need to given operation
* @throws DeviceManagementException
* @throws DigitalDisplayException
*/
private void sendCommandViaMQTT(String deviceId, String operation, String param)
throws DeviceManagementException, DigitalDisplayException {
String topic = String.format(DigitalDisplayConstants.PUBLISH_TOPIC, deviceId);
String payload = operation + param;
try {
digitalDisplayMQTTConnector.publishToDigitalDisplay(topic, payload, 2, false);
} catch (TransportHandlerException e) {
String errorMessage = "Error publishing data to device with ID " + deviceId;
throw new DigitalDisplayException(errorMessage, e);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}

View File

@ -0,0 +1,59 @@
/*
* 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.digitaldisplay.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "digital_display_mgt", version = "1.0.0", context = "/digital_display_mgt", tags = {"digital_display"})
@DeviceType(value = "digital_display")
public interface DigitalDisplayManagerService {
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String customDeviceName);
}

View File

@ -0,0 +1,201 @@
/*
* 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.digitaldisplay.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClient;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.UUID;
public class DigitalDisplayManagerServiceImpl implements DigitalDisplayManagerService {
private static Log log = LogFactory.getLog(DigitalDisplayManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
private boolean register(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
return added;
} catch (DeviceManagementException e) {
return false;
}
}
public Response removeDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response updateDevice(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(DigitalDisplayConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DigitalDisplayConstants.DEVICE_TYPE);
try {
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response downloadSketch(String deviceName) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
response.type("application/zip");
response.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return response.build();
} catch (IllegalArgumentException ex) {
return Response.status(400).entity(ex.getMessage()).build();//bad request
} catch (DeviceManagementException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (JWTClientException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (IOException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String owner, String deviceName)
throws DeviceManagementException, JWTClientException, DeviceControllerException, APIManagerException,
UserStoreException {
if (owner == null) {
throw new IllegalArgumentException("Error on createDownloadFile() Owner is null!");
}
//create new device id
String deviceId = shortUUID();
if (apiApplicationKey == null) {
String applicationUsername =
PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {DigitalDisplayConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
DigitalDisplayConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String scopes = "device_type_" + DigitalDisplayConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
boolean status;
//Register the device with CDMF
status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(),
DigitalDisplayConstants.DEVICE_TYPE, deviceId,
deviceName, accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.arduino.manager.service.impl.util;
package org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.util;
package org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -6,13 +6,12 @@ import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONObject;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.model.ScreenShotModel;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.websocket.DigitalDisplayWebSocketServerEndPoint;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.model.ScreenShotModel;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.websocket.DigitalDisplayWebSocketServerEndPoint;
import org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin.constants.DigitalDisplayConstants;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

View File

@ -0,0 +1,137 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!-- This file contains the list of permissions that are associated with URL end points
of the web app. Each permission should contain the name, permission path ,API path
(URL) , HTTP method and OAUTH2 authorization scope (not-required).
When defining dynamic paths for APIs, path variables are denoted by '*' notation.
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<PermissionConfiguration>
<APIVersion></APIVersion>
<!-- Device related APIs -->
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/devices/*</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/devices/*</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/devices/*/download</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/devices/*</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/restart-browser</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/terminate-display</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/restart-display</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/edit-sequence</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/upload-content</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/add-resource</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/remove-resource</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/restart-server</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/screenshot</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/get-device-status</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/get-content-list</url>
<method>POST</method>
<scope></scope>
</Permission>
</PermissionConfiguration>

View File

@ -27,9 +27,12 @@
<jaxrs:server id="DigitalDisplayController" address="/controller">
<jaxrs:serviceBeans>
<bean id="DigitalDisplayManagerControllerService"
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.DigitalDisplayControllerService">
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.DigitalDisplayControllerServiceImpl">
<property name="digitalDisplayMQTTConnector" ref="communicationHandler"/>
</bean>
<bean id="DigitalDisplayManagerService"
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.DigitalDisplayManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
@ -37,7 +40,7 @@
</jaxrs:server>
<bean id="communicationHandler"
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api.util.DigitalDisplayMQTTConnector" >
class="org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl.util.DigitalDisplayMQTTConnector" >
</bean>
</beans>

View File

@ -33,8 +33,7 @@
<url>http://wso2.org</url>
<modules>
<module>org.wso2.carbon.device.mgt.iot.digitaldisplay.controller.api</module>
<module>org.wso2.carbon.device.mgt.iot.digitaldisplay.manager.api</module>
<module>org.wso2.carbon.device.mgt.iot.digitaldisplay.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.digitaldisplay.plugin</module>
<module>org.wso2.carbon.device.mgt.iot.digitaldisplay.ui</module>
</modules>

View File

@ -1,254 +0,0 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>drone-analyzer-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server Drone Analyzer Controller API</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.0</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<warName>drone_analyzer</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

View File

@ -1,40 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs" xmlns:cxf="http://cxf.apache.org/core"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd">
<jaxrs:server id="DroneAnalyzerManager" address="/">
<jaxrs:features>
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans>
<bean id="DroneManagerService" class="org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api.impl.DroneManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

View File

@ -1,62 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>WSO2 IoT Server</display-name>
<description>WSO2 IoT Server</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/drone_analyzer/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>drone_analyzer</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
<!-- Below configuration is used to redirect http requests to https -->
<!--<security-constraint>-->
<!--<web-resource-collection>-->
<!--<web-resource-name>IoT</web-resource-name>-->
<!--<url-pattern>/*</url-pattern>-->
<!--</web-resource-collection>-->
<!--<user-data-constraint>-->
<!--<transport-guarantee>CONFIDENTIAL</transport-guarantee>-->
<!--</user-data-constraint>-->
<!--</security-constraint>-->
</web-app>

View File

@ -1,17 +1,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<artifactId>drone-analyzer-plugin</artifactId>
<artifactId>device-mgt-iot-droneanalyzer</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server Drone Analyzer Manager API</name>
<name>WSO2 Carbon - IoT Server Drone Analyzer API</name>
<url>http://maven.apache.org</url>
<dependencies>
@ -35,7 +34,8 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>1.1.0-SNAPSHOT</version>
<scope>provided</scope>
<exclusions>
<exclusion>
@ -56,8 +56,6 @@
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
@ -226,6 +224,16 @@
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.application.extension</artifactId>
<version>1.1.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.jwt.client.extension</artifactId>
@ -253,7 +261,7 @@
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
<warName>drone_analyzer_mgt</warName>
<warName>drone_analyzer</warName>
</configuration>
</plugin>
</plugins>

View File

@ -0,0 +1,46 @@
/*
* 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.droneanalyzer.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.FormParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
@API(name = "drone_analyzer", version = "1.0.0", context = "/drone_analyzer", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer")
public interface DroneControllerService {
@Path("device/register/{deviceId}/{ip}/{port}")
@POST
Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort);
@Path("device/{deviceId}/send_command")
@POST
/*@Feature( code="send_command", name="Send Command", type="operation",
description="Send Commands to Drone")*/
Response droneController(@PathParam("deviceId") String deviceId, @FormParam("action") String action,
@FormParam("duration") String duration, @FormParam("speed") String speed);
}

View File

@ -15,68 +15,48 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.util.DroneAnalyzerServiceUtils;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.util.DroneAnalyzerServiceUtils;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.DroneController;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.impl.DroneControllerImpl;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.util.concurrent.ConcurrentHashMap;
@API( name="drone_analyzer", version="1.0.0", context="/drone_analyzer", tags = {"drone_analyzer"})
@DeviceType( value = "drone_analyzer")
public class DroneControllerService {
public class DroneControllerServiceImpl implements DroneControllerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneControllerService.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneControllerServiceImpl.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private DroneController droneController = new DroneControllerImpl();
@Path("controller/register/{deviceId}/{ip}/{port}")
@POST
public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletResponse response) {
try {
String result;
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok(Response.Status.OK.getStatusCode()).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort) {
String result;
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok(Response.Status.OK.getStatusCode()).build();
}
@Path("controller/device/{deviceId}/send_command")
@POST
/*@Feature( code="send_command", name="Send Command", type="operation",
description="Send Commands to Drone")*/
public Response droneController(@PathParam("deviceId") String deviceId,
@FormParam("action") String action, @FormParam("duration") String duration,
@FormParam("speed") String speed){
public Response droneController(String deviceId, String action, String duration, String speed) {
try {
DroneAnalyzerServiceUtils.sendControlCommand(droneController, deviceId, action, Double.valueOf(speed),
Double.valueOf(duration));
Double.valueOf(duration));
return Response.status(Response.Status.ACCEPTED).build();
} catch (DeviceManagementException e) {
log.error("Drone command didn't success. Try again, \n"+ e);
log.error("Drone command didn't success. Try again, \n" + e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}

View File

@ -0,0 +1,69 @@
/*
* 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.droneanalyzer.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
@API(name = "drone_analyzer_mgt", version = "1.0.0", context = "/drone_analyzer_mgt", tags = {"drone_analyzer"})
@DeviceType(value = "drone_analyzer")
public interface DroneManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getDroneDevices();
@Path("devices/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String sketchType);
@Path("devices/{sketch_type}/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType);
}

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api.impl;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
@ -30,7 +30,7 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
@ -40,18 +40,6 @@ import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClientManager;
import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
@ -60,23 +48,18 @@ import java.util.Date;
import java.util.List;
import java.util.UUID;
public class DroneManagerService {
public class DroneManagerServiceImpl implements DroneManagerService {
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneManagerService.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private static org.apache.commons.logging.Log log = LogFactory.getLog(DroneManagerServiceImpl.class);
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
@Path("manager/device/register")
@POST
public boolean register(@QueryParam("deviceId") String deviceId, @QueryParam("name") String name) {
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
@ -91,49 +74,33 @@ public class DroneManagerService {
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
@Path("manager/device/{device_id}")
@PUT
public boolean updateDevice(@PathParam("device_id") String deviceId, @QueryParam("name") String name,
@Context HttpServletResponse response) {
public Response removeDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
if (removed) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response updateDevice(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
device.setDeviceIdentifier(deviceId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
@ -141,102 +108,75 @@ public class DroneManagerService {
device.setType(DroneConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
return Response.ok().build();
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) {
public Response getDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(DroneConstants.DEVICE_TYPE);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/devices")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device[] getDroneDevices() {
public Response getDroneDevices() {
try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(APIUtil.getAuthenticatedUser());
ArrayList<Device> userDevicesforDrone = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(DroneConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(
EnrolmentInfo.Status.ACTIVE)) {
device.getEnrolmentInfo().getStatus().equals(
EnrolmentInfo.Status.ACTIVE)) {
userDevicesforDrone.add(device);
}
}
return userDevicesforDrone.toArray(new Device[]{});
Device[] devices = userDevicesforDrone.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
public Response downloadSketch(String deviceName, String sketchType) {
//create new device id
String deviceId = shortUUID();
//create token
String token = UUID.randomUUID().toString();
String refreshToken = UUID.randomUUID().toString();
//adding registering data
boolean status = register(deviceId, deviceName);
if (!status) {
return Response.status(500).entity(
"Error occurred while registering the device with " + "id: " + deviceId + " owner:" +
APIUtil.getAuthenticatedUser()).build();
@Path("manager/device/{sketch_type}/download")
@GET
@Produces("application/octet-stream")
public Response downloadSketch(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile;
try {
//create new device id
String deviceId = shortUUID();
//create token
String token = UUID.randomUUID().toString();
String refreshToken = UUID.randomUUID().toString();
//adding registering data
boolean status = register(deviceId, deviceName);
if (!status) {
return Response.status(500).entity(
"Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + APIUtil.getAuthenticatedUser()).build();
zipFile = ziputil.createZipFile(APIUtil.getAuthenticatedUser(), APIUtil.getTenantDomainOftheUser(),
sketchType, deviceId, deviceName, token, refreshToken);
} catch (DeviceManagementException ex) {
return Response.status(500).entity("Error occurred while creating zip file").build();
}
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
}
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile;
try {
zipFile = ziputil.createZipFile(APIUtil.getAuthenticatedUser(), APIUtil.getTenantDomainOftheUser(),
sketchType, deviceId, deviceName, token, refreshToken);
} catch (DeviceManagementException ex) {
return Response.status(500).entity("Error occurred while creating zip file").build();
}
Response.ResponseBuilder rb = Response.ok(zipFile.getZipFile());
rb.header("Content-Disposition", "attachment; filename=\"" + zipFile.getFileName() + "\"");
return rb.build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}
@Path("manager/device/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
public Response generateSketchLink(String deviceName, String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(deviceName, sketchType);
Response.ResponseBuilder rb = Response.ok(zipFile.getDeviceId());
@ -250,13 +190,11 @@ public class DroneManagerService {
} catch (DeviceControllerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (APIManagerException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
}
}
private ZipArchive createDownloadFile(String deviceName, String sketchType)
throws DeviceManagementException, JWTClientException, APIManagerException, DeviceControllerException,
@ -272,7 +210,7 @@ public class DroneManagerService {
DroneConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true);
}
JWTClient jwtClient = JWTClientManager.getInstance().getJWTClient();
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String owner = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUsername();
String scopes = "device_type_" + DroneConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes);
@ -292,7 +230,8 @@ public class DroneManagerService {
status = xmppServerClient.createXMPPAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " +
APIUtil.getAuthenticatedUser() + ".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config.server.configs";
APIUtil.getAuthenticatedUser() + ".XMPP might have been disabled in " +
"org.wso2.carbon.device.mgt.iot.common.config.server.configs";
log.warn(msg);
throw new DeviceManagementException(msg);
}
@ -301,7 +240,7 @@ public class DroneManagerService {
status = register(deviceId, deviceName);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + APIUtil.getAuthenticatedUser();
+ " owner:" + APIUtil.getAuthenticatedUser();
throw new DeviceManagementException(msg);
}
ZipUtil ziputil = new ZipUtil();

View File

@ -15,13 +15,13 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.transport.DroneAnalyzerXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.trasformer.MessageTransformer;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.transport.DroneAnalyzerXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.trasformer.MessageTransformer;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import javax.websocket.OnClose;

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.exception;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.exception;
public class DroneAnalyzerException extends Exception {
private static final long serialVersionUID = 118512086958330189L;

View File

@ -16,13 +16,13 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.transport;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.trasformer.MessageTransformer;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.trasformer.MessageTransformer;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.xmpp.XMPPTransportHandler;

View File

@ -15,7 +15,7 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.trasformer;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.trasformer;
import org.apache.commons.collections4.queue.CircularFifoQueue;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api.impl.util;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

View File

@ -16,12 +16,12 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.util;
package org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.util;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.transport.DroneAnalyzerXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.transport.DroneAnalyzerXMPPConnector;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.constants.DroneConstants;
import org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin.controller.DroneController;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;

View File

@ -31,36 +31,57 @@
<Permission>
<name>Get device</name>
<path>/device-mgt/user/devices/list</path>
<url>/manager/device/{device_id}</url>
<url>/devices/*</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Add device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name>Remove device</name>
<path>/device-mgt/user/devices/remove</path>
<url>/manager/device/{device_id}</url>
<url>/devices/*</url>
<method>DELETE</method>
<scope></scope>
</Permission>
<Permission>
<name>Download device</name>
<path>/device-mgt/user/devices/add</path>
<url>/manager/device/{sketch_type}/download</url>
<url>/devices/*/download</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name>Update device</name>
<path>/device-mgt/user/devices/update</path>
<url>/manager/device/{device_id}</url>
<url>/devices/*</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/devices</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/devices/*/generate_link</url>
<method>GET</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/register/*/*/*</url>
<method>POST</method>
<scope></scope>
</Permission>
<Permission>
<name></name>
<path></path>
<url>/device/*/send_command</url>
<method>POST</method>
<scope></scope>
</Permission>
</PermissionConfiguration>

View File

@ -28,11 +28,15 @@
<cxf:logging/>
</jaxrs:features>
<jaxrs:serviceBeans>
<bean id="DroneControllerService" class="org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api.impl.DroneControllerService">
<bean id="DroneControllerService"
class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.DroneControllerServiceImpl">
<!--<property name="DroneXMPPConnector" ref="xmppConnectorBean"/>-->
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean id="DroneManagerService"
class="org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl.DroneManagerServiceImpl">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>

View File

@ -34,8 +34,7 @@
<modules>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.ui</module>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.controller.api</module>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.manager.api</module>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.droneanalyzer.plugin</module>
</modules>

View File

@ -103,7 +103,7 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<scope>provided</scope>
</dependency>

View File

@ -191,7 +191,7 @@
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
</dependency>
<!--Dependencies on XMPP Client Library-->
<dependency>

View File

@ -33,12 +33,12 @@
<url>http://wso2.org</url>
<modules>
<!--<module>androidsense-plugin</module>-->
<!--<module>arduino-plugin</module>-->
<!--<module>digital-display-plugin</module>-->
<!--<module>drone-analyzer-plugin</module>-->
<!--<module>raspberrypi-plugin</module>-->
<!--<module>virtual-fire-alarm-plugin</module>-->
<module>androidsense-plugin</module>
<module>arduino-plugin</module>
<module>digital-display-plugin</module>
<module>drone-analyzer-plugin</module>
<module>raspberrypi-plugin</module>
<module>virtual-fire-alarm-plugin</module>
<module>iot-base-plugin</module>
</modules>

View File

@ -1,158 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>raspberrypi-plugin</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl</artifactId>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi Controller API</name>
<description>WSO2 Carbon - RaspberryPi Controller Service API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<scope>provided</scope>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<scope>provided</scope>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.extensions</artifactId>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>raspberrypi</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

View File

@ -1,295 +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.raspberrypi.controller.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.common.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
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.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.dto.DeviceData;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.dto.SensorData;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.transport.RaspberryPiMQTTConnector;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
@API(name = "raspberrypi", version = "1.0.0", context = "/raspberrypi", tags = {"raspberrypi"})
@DeviceType(value = "raspberrypi")
public class RaspberryPiControllerService {
private static Log log = LogFactory.getLog(RaspberryPiControllerService.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private RaspberryPiMQTTConnector raspberryPiMQTTConnector;
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public RaspberryPiMQTTConnector getRaspberryPiMQTTConnector() {
return raspberryPiMQTTConnector;
}
public void setRaspberryPiMQTTConnector(
final RaspberryPiMQTTConnector raspberryPiMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
RaspberryPiControllerService.this.raspberryPiMQTTConnector = raspberryPiMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
raspberryPiMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, RaspberryPiMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Path("controller/register/{deviceId}/{ip}/{port}")
@POST
public String registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletResponse response,
@Context HttpServletRequest request) {
try {
String result;
if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId);
}
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode());
if (log.isDebugEnabled()) {
log.debug(result);
}
return result;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("controller/device/{deviceId}/bulb")
@POST
@Feature(code = "bulb", name = "Bulb On / Off", type = "operation",
description = "Switch on/off Raspberry Pi agent's bulb. (On / Off)")
public void switchBulb(@PathParam("deviceId") String deviceId, @FormParam("state") String state,
@Context HttpServletResponse response) {
try {
String switchToState = state.toUpperCase();
if (!switchToState.equals(RaspberrypiConstants.STATE_ON) && !switchToState.equals(
RaspberrypiConstants.STATE_OFF)) {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
response.setStatus(Response.Status.BAD_REQUEST.getStatusCode());
return;
}
String callUrlPattern = RaspberrypiConstants.BULB_CONTEXT + switchToState;
try {
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
RaspberrypiServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
} catch (DeviceManagementException e) {
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via ");
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return;
}
response.setStatus(Response.Status.OK.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("controller/device/{deviceId}/readtemperature")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "readtemperature", name = "Temperature", type = "monitor",
description = "Request temperature reading from Raspberry Pi agent")
public SensorRecord requestTemperature(@PathParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
try {
SensorRecord sensorRecord = null;
if (log.isDebugEnabled()) {
log.debug("Sending request to read raspberrypi-temperature of device [" + deviceId + "] via ");
}
try {
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
}
String temperatureValue = RaspberrypiServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint,
RaspberrypiConstants
.TEMPERATURE_CONTEXT,
false);
SensorDataManager.getInstance().setSensorRecord(deviceId, RaspberrypiConstants.SENSOR_TEMPERATURE,
temperatureValue, Calendar.getInstance()
.getTimeInMillis
());
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
RaspberrypiConstants
.SENSOR_TEMPERATURE);
} catch (DeviceManagementException | DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("controller/push_temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData(final DeviceData dataMsg, @Context HttpServletResponse response,
@Context HttpServletRequest request) {
try {
String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply;
float temperature = dataMsg.value;
String registeredIp = deviceToIpMap.get(deviceId);
if (registeredIp == null) {
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
" for device ID - " + deviceId);
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
} else if (!registeredIp.equals(deviceIp)) {
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
" is already registered under some other IP. Re-registration required");
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return;
}
if (log.isDebugEnabled()) {
log.debug("Received Pin Data Value: " + temperature + " degrees C");
}
SensorDataManager.getInstance().setSensorRecord(deviceId, RaspberrypiConstants.SENSOR_TEMPERATURE,
String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis());
if (!RaspberrypiServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
log.warn("An error occured whilst trying to publish temperature data of raspberrypi with ID [" +
deviceId + "] of owner [" + owner + "]");
}
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/**
* Retreive Sensor data for the device type
*/
@Path("controller/stats/device/{deviceId}/sensors/temperature")
@GET
@Consumes("application/json")
@Produces("application/json")
public SensorData[] getArduinoTemperatureStats(@PathParam("deviceId") String deviceId,
@QueryParam("username") String user,
@QueryParam("from") long from,
@QueryParam("to") long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
List<SensorData> sensorDatas = new ArrayList<>();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
String query = "owner:" + user + " AND deviceId:" + deviceId + " AND deviceType:" +
RaspberrypiConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = RaspberrypiConstants.TEMPERATURE_EVENT_TABLE;
try {
List<AnalyticsDataRecord> records = deviceAnalyticsService.getAllEventsForDevice(sensorTableName, query);
Collections.sort(records, new Comparator<AnalyticsDataRecord>() {
@Override
public int compare(AnalyticsDataRecord o1, AnalyticsDataRecord o2) {
long t1 = (Long) o1.getValue("time");
long t2 = (Long) o2.getValue("time");
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
return 0;
}
}
});
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setTime((long) record.getValue("time"));
sensorData.setValue("" + (float) record.getValue(RaspberrypiConstants.SENSOR_TEMPERATURE));
sensorDatas.add(sensorData);
}
return sensorDatas.toArray(new SensorData[sensorDatas.size()]);
} catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return sensorDatas.toArray(new SensorData[sensorDatas.size()]);
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
}

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

View File

@ -1,33 +0,0 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright 2005-2013 WSO2, Inc. (http://wso2.com)
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

View File

@ -1,43 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ 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.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="RaspberryPiManager" address="/">
<jaxrs:serviceBeans>
<bean id="RaspberryPiManagerService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl.RaspberryPiManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider"/>
</jaxrs:providers>
</jaxrs:server>
</beans>

View File

@ -1,50 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true">
<display-name>RaspberryPi</display-name>
<description>RaspberryPi</description>
<servlet>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>true</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/raspberrypi/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>raspberrypi</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

View File

@ -20,19 +20,20 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>raspberrypi-plugin</artifactId>
<parent>
<artifactId>device-mgt-iot-raspberrypi</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>2.1.0-SNAPSHOT</version>
<version>2.0.4-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl</artifactId>
<version>2.0.4-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi Manager API</name>
<description>WSO2 Carbon - RaspberryPi Manager Service API Implementation</description>
<name>WSO2 Carbon - IoT Server RaspberryPi API</name>
<description>WSO2 Carbon - RaspberryPi Service API Implementation</description>
<url>http://wso2.org</url>
<dependencies>
@ -118,7 +119,8 @@
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<artifactId>org.wso2.carbon.device.mgt.analytics.data.publisher</artifactId>
<version>1.1.0-SNAPSHOT</version>
<scope>provided</scope>
</dependency>
<dependency>
@ -157,7 +159,7 @@
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>raspberrypi_mgt</warName>
<warName>raspberrypi</warName>
</configuration>
</plugin>
</plugins>

View File

@ -0,0 +1,77 @@
/*
* 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.raspberrypi.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
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.raspberrypi.service.impl.dto.DeviceData;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "raspberrypi", version = "1.0.0", context = "/raspberrypi", tags = {"raspberrypi"})
@DeviceType(value = "raspberrypi")
public interface RaspberryPiControllerService {
@Path("device/register/{deviceId}/{ip}/{port}")
@POST
Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@PathParam("port") String devicePort, @Context HttpServletRequest request);
@Path("device/{deviceId}/bulb")
@POST
@Feature(code = "bulb", name = "Bulb On / Off", type = "operation",
description = "Switch on/off Raspberry Pi agent's bulb. (On / Off)")
Response switchBulb(@PathParam("deviceId") String deviceId, @FormParam("state") String state);
@Path("device/{deviceId}/readtemperature")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
@Feature(code = "readtemperature", name = "Temperature", type = "monitor",
description = "Request temperature reading from Raspberry Pi agent")
Response requestTemperature(@PathParam("deviceId") String deviceId);
@Path("device/push_temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
Response pushTemperatureData(final DeviceData dataMsg, @Context HttpServletRequest request);
/**
* Retreive Sensor data for the device type
*/
@Path("device/stats/{deviceId}/sensors/temperature")
@GET
@Consumes("application/json")
@Produces("application/json")
Response getArduinoTemperatureStats(@PathParam("deviceId") String deviceId, @QueryParam("username") String user,
@QueryParam("from") long from, @QueryParam("to") long to);
}

View File

@ -0,0 +1,221 @@
/*
* 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.raspberrypi.service.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.data.publisher.AnalyticsDataRecord;
import org.wso2.carbon.device.mgt.analytics.data.publisher.exception.DeviceManagementAnalyticsException;
import org.wso2.carbon.device.mgt.analytics.data.publisher.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.DeviceData;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorData;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.transport.RaspberryPiMQTTConnector;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerService {
private static Log log = LogFactory.getLog(RaspberryPiControllerServiceImpl.class);
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private RaspberryPiMQTTConnector raspberryPiMQTTConnector;
private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
return true;
}
}
return false;
}
public RaspberryPiMQTTConnector getRaspberryPiMQTTConnector() {
return raspberryPiMQTTConnector;
}
public void setRaspberryPiMQTTConnector(
final RaspberryPiMQTTConnector raspberryPiMQTTConnector) {
Runnable connector = new Runnable() {
public void run() {
if (waitForServerStartup()) {
return;
}
RaspberryPiControllerServiceImpl.this.raspberryPiMQTTConnector = raspberryPiMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
raspberryPiMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, RaspberryPiMQTTConnector not started.");
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
public Response registerDeviceIP(String deviceId, String deviceIP, String devicePort, HttpServletRequest request) {
String result;
if (log.isDebugEnabled()) {
log.debug("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId);
}
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
if (log.isDebugEnabled()) {
log.debug(result);
}
return Response.ok().entity(result).build();
}
public Response switchBulb(String deviceId, String state) {
String switchToState = state.toUpperCase();
if (!switchToState.equals(RaspberrypiConstants.STATE_ON) && !switchToState.equals(
RaspberrypiConstants.STATE_OFF)) {
log.error("The requested state change shoud be either - 'ON' or 'OFF'");
return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
}
String callUrlPattern = RaspberrypiConstants.BULB_CONTEXT + switchToState;
try {
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
return Response.status(Response.Status.PRECONDITION_FAILED.getStatusCode()).build();
}
RaspberrypiServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
} catch (DeviceManagementException e) {
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via ");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().build();
}
public Response requestTemperature(@PathParam("deviceId") String deviceId) {
SensorRecord sensorRecord = null;
if (log.isDebugEnabled()) {
log.debug("Sending request to read raspberrypi-temperature of device [" + deviceId + "] via ");
}
try {
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
return Response.status(Response.Status.PRECONDITION_FAILED.getStatusCode()).build();
}
String temperatureValue = RaspberrypiServiceUtils.sendCommandViaHTTP(deviceHTTPEndpoint,
RaspberrypiConstants
.TEMPERATURE_CONTEXT,
false);
SensorDataManager.getInstance().setSensorRecord(deviceId, RaspberrypiConstants.SENSOR_TEMPERATURE,
temperatureValue, Calendar.getInstance()
.getTimeInMillis());
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
RaspberrypiConstants.SENSOR_TEMPERATURE);
} catch (DeviceManagementException | DeviceControllerException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().entity(sensorRecord).build();
}
public Response pushTemperatureData(final DeviceData dataMsg, HttpServletRequest request) {
String owner = dataMsg.owner;
String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply;
float temperature = dataMsg.value;
String registeredIp = deviceToIpMap.get(deviceId);
if (registeredIp == null) {
log.warn("Unregistered IP: Temperature Data Received from an un-registered IP " + deviceIp +
" for device ID - " + deviceId);
return Response.status(Response.Status.PRECONDITION_FAILED.getStatusCode()).build();
} else if (!registeredIp.equals(deviceIp)) {
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + deviceId +
" is already registered under some other IP. Re-registration required");
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
}
if (log.isDebugEnabled()) {
log.debug("Received Pin Data Value: " + temperature + " degrees C");
}
SensorDataManager.getInstance().setSensorRecord(deviceId, RaspberrypiConstants.SENSOR_TEMPERATURE,
String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis());
if (!RaspberrypiServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
log.warn("An error occured whilst trying to publish temperature data of raspberrypi with ID [" +
deviceId + "] of owner [" + owner + "]");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
return Response.ok().build();
}
public Response getArduinoTemperatureStats(String deviceId, String user, long from, long to) {
String fromDate = String.valueOf(from);
String toDate = String.valueOf(to);
List<SensorData> sensorDatas = new ArrayList<>();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
String query = "owner:" + user + " AND deviceId:" + deviceId + " AND deviceType:" +
RaspberrypiConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = RaspberrypiConstants.TEMPERATURE_EVENT_TABLE;
try {
List<AnalyticsDataRecord> records = deviceAnalyticsService.getAllEventsForDevice(sensorTableName, query);
Collections.sort(records, new Comparator<AnalyticsDataRecord>() {
@Override
public int compare(AnalyticsDataRecord o1, AnalyticsDataRecord o2) {
long t1 = (Long) o1.getValue("time");
long t2 = (Long) o2.getValue("time");
if (t1 < t2) {
return -1;
} else if (t1 > t2) {
return 1;
} else {
return 0;
}
}
});
for (AnalyticsDataRecord record : records) {
SensorData sensorData = new SensorData();
sensorData.setTime((long) record.getValue("time"));
sensorData.setValue("" + (float) record.getValue(RaspberrypiConstants.SENSOR_TEMPERATURE));
sensorDatas.add(sensorData);
}
SensorData[] sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.ok().entity(sensorDetails).build();
} catch (DeviceManagementAnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
SensorData[] sensorDetails = sensorDatas.toArray(new SensorData[sensorDatas.size()]);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(sensorDetails).build();
}
}
}

View File

@ -0,0 +1,72 @@
/*
* 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.raspberrypi.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@API(name = "raspberrypi_mgt", version = "1.0.0", context = "/raspberrypi_mgt", tags = {"raspberrypi"})
@DeviceType(value = "raspberrypi")
public interface RaspberryPiManagerService {
@Path("devices/{device_id}")
@DELETE
Response removeDevice(@PathParam("device_id") String deviceId);
@Path("devices/{device_id}")
@PUT
Response updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name);
@Path("devices/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getDevice(@PathParam("device_id") String deviceId);
@Path("devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
Response getRaspberrypiDevices();
@Path("devices/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String
sketchType);
@Path("devices/{sketch_type}/generate_link")
@GET
Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType);
}

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl;
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
@ -33,8 +33,8 @@ import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.device.mgt.jwt.client.extension.JWTClient;
@ -43,18 +43,6 @@ import org.wso2.carbon.device.mgt.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.device.mgt.jwt.client.extension.exception.JWTClientException;
import org.wso2.carbon.user.api.UserStoreException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
@ -64,25 +52,19 @@ import java.util.Date;
import java.util.List;
import java.util.UUID;
public class RaspberryPiManagerService {
public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService {
private static Log log = LogFactory.getLog(RaspberryPiManagerService.class);
private static Log log = LogFactory.getLog(RaspberryPiManagerServiceImpl.class);
@Context //injected response proxy supporting multiple thread
private HttpServletResponse response;
private static final String KEY_TYPE = "PRODUCTION";
private static ApiApplicationKey apiApplicationKey;
@Path("manager/device/register")
@POST
public boolean register(@QueryParam("deviceId") String deviceId,
@QueryParam("name") String name) {
private boolean register(String deviceId, String name) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
@ -96,24 +78,13 @@ public class RaspberryPiManagerService {
enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
device.setEnrolmentInfo(enrolmentInfo);
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) {
public Response removeDevice(String deviceId) {
try {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
@ -121,22 +92,16 @@ public class RaspberryPiManagerService {
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
return Response.ok().build();
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{device_id}")
@PUT
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
public Response updateDevice(String deviceId, String name) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
@ -148,67 +113,48 @@ public class RaspberryPiManagerService {
device.setType(RaspberrypiConstants.DEVICE_TYPE);
boolean updated = APIUtil.getDeviceManagementService().modifyEnrollment(device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
return Response.ok().build();
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).build();
}
return updated;
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage());
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{device_id}")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device getDevice(@PathParam("device_id") String deviceId) {
public Response getDevice(String deviceId) {
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(RaspberrypiConstants.DEVICE_TYPE);
try {
return APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException ex) {
log.error("Error occurred while retrieving device with Id " + deviceId + "\n" + ex);
return null;
} finally {
PrivilegedCarbonContext.endTenantFlow();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/devices")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Device[] getRaspberrypiDevices() {
public Response getRaspberrypiDevices() {
try {
List<Device> userDevices = APIUtil.getDeviceManagementService().getDevicesOfUser(
APIUtil.getAuthenticatedUser());
ArrayList<Device> usersRaspberrypiDevices = new ArrayList<>();
for (Device device : userDevices) {
if (device.getType().equals(RaspberrypiConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
usersRaspberrypiDevices.add(device);
}
}
return usersRaspberrypiDevices.toArray(new Device[]{});
Device[] devices = usersRaspberrypiDevices.toArray(new Device[]{});
return Response.ok().entity(devices).build();
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
PrivilegedCarbonContext.endTenantFlow();
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).build();
}
}
@Path("manager/device/{sketch_type}/download")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @PathParam("sketch_type") String
sketchType) {
public Response downloadSketch(String deviceName, String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));
@ -229,16 +175,10 @@ public class RaspberryPiManagerService {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@Path("manager/device/{sketch_type}/generate_link")
@GET
public Response generateSketchLink(@QueryParam("deviceName") String deviceName,
@PathParam("sketch_type") String sketchType) {
public Response generateSketchLink(String deviceName, String sketchType) {
try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
@ -256,8 +196,6 @@ public class RaspberryPiManagerService {
return Response.status(500).entity(ex.getMessage()).build();
} catch (UserStoreException ex) {
return Response.status(500).entity(ex.getMessage()).build();
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
@ -295,8 +233,8 @@ public class RaspberryPiManagerService {
status = xmppServerClient.createXMPPAccount(newXmppAccount);
if (!status) {
String msg = "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config" +
".server.configs";
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot.common.config" +
".server.configs";
log.warn(msg);
throw new DeviceManagementException(msg);
}

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.exception;
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.exception;
public class RaspberrypiException extends Exception {
private static final long serialVersionUID = 118512086957330189L;

View File

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.transport;
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -27,16 +27,14 @@ 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.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import org.wso2.carbon.utils.multitenancy.MultitenantUtils;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;

View File

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl.util;
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

Some files were not shown because too many files have changed in this diff Show More