Changes for the FireAlarmService to work with real device and SCEP service inclusions

merge-requests/1/head
Shabirmean 9 years ago
parent 3c2a84a07d
commit d28a2bf4b3

@ -18,15 +18,16 @@
#[Device-Configurations] #[Device-Configurations]
owner=${DEVICE_OWNER} owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID} deviceId=${DEVICE_ID}
server-ep=${SERVER_EP} device-name=${DEVICE_NAME}
service-ep=${SERVICE_EP} controller-context=/firealarm/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP} apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP} mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP} xmpp-ep=${XMPP_EP}
auth-method=token auth-method=token
auth-token=${DEVICE_TOKEN} auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN} refresh-token=${DEVICE_REFRESH_TOKEN}
network-interface=wlan0
push-interval=15 push-interval=15

@ -22,4 +22,11 @@ public class FireAlarmConstants {
public final static String DEVICE_PLUGIN_DEVICE_ID = "FIREALARM_DEVICE_ID"; public final static String DEVICE_PLUGIN_DEVICE_ID = "FIREALARM_DEVICE_ID";
public final static String STATE_ON = "ON"; public final static String STATE_ON = "ON";
public final static String STATE_OFF = "OFF"; public final static String STATE_OFF = "OFF";
public static final String URL_PREFIX = "http://";
public static final String BULB_CONTEXT = "/BULB/";
public static final String SONAR_CONTEXT = "/HUMIDITY/";
public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";
public static final String SENSOR_TEMPERATURE = "temperature";
} }

@ -41,12 +41,19 @@ import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException; import org.wso2.carbon.device.mgt.iot.common.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException; import org.wso2.carbon.device.mgt.iot.common.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants; import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util.DeviceJSON; import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.dto.DeviceJSON;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport
.FireAlarmMQTTSubscriber;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport
.FireAlarmXMPPConnector;
import org.wso2.carbon.utils.CarbonUtils; import org.wso2.carbon.utils.CarbonUtils;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -73,6 +80,7 @@ import java.net.URL;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.UUID; import java.util.UUID;
@ -86,24 +94,67 @@ public class FireAlarmService {
private static Log log = LogFactory.getLog(FireAlarmService.class); private static Log log = LogFactory.getLog(FireAlarmService.class);
//TODO; replace this tenant domain //TODO; replace this tenant domain
private final String SUPER_TENANT = "carbon.super"; private static final String SUPER_TENANT = "carbon.super";
@Context //injected response proxy supporting multiple thread @Context //injected response proxy supporting multiple thread
private HttpServletResponse response; private HttpServletResponse response;
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature"; private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
private static final String URL_PREFIX = "http://";
private static final String BULB_CONTEXT = "/BULB/";
private static final String SONAR_CONTEXT = "/SONAR/";
private static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";
public static final String XMPP_PROTOCOL = "XMPP"; public static final String XMPP_PROTOCOL = "XMPP";
public static final String HTTP_PROTOCOL = "HTTP"; public static final String HTTP_PROTOCOL = "HTTP";
public static final String MQTT_PROTOCOL = "MQTT"; public static final String MQTT_PROTOCOL = "MQTT";
private static FireAlarmMQTTSubscriber fireAlarmMQTTSubscriber;
private static FireAlarmXMPPConnector fireAlarmXMPPConnector;
private static ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<String, String>(); private static ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<String, String>();
public void setFireAlarmXMPPConnector(
final FireAlarmXMPPConnector fireAlarmXMPPConnector) {
this.fireAlarmXMPPConnector = fireAlarmXMPPConnector;
Runnable mqttStarter = new Runnable() {
@Override
public void run() {
fireAlarmXMPPConnector.initConnector();
fireAlarmXMPPConnector.connectAndLogin();
}
};
Thread mqttStarterThread = new Thread(mqttStarter);
mqttStarterThread.setDaemon(true);
mqttStarterThread.start();
}
public void setFireAlarmMQTTSubscriber(
final FireAlarmMQTTSubscriber fireAlarmMQTTSubscriber) {
this.fireAlarmMQTTSubscriber = fireAlarmMQTTSubscriber;
Runnable xmppStarter = new Runnable() {
@Override
public void run() {
fireAlarmMQTTSubscriber.initConnector();
fireAlarmMQTTSubscriber.connectAndSubscribe();
}
};
Thread xmppStarterThread = new Thread(xmppStarter);
xmppStarterThread.setDaemon(true);
xmppStarterThread.start();
}
public FireAlarmXMPPConnector getFireAlarmXMPPConnector() {
return fireAlarmXMPPConnector;
}
public FireAlarmMQTTSubscriber getFireAlarmMQTTSubscriber() {
return fireAlarmMQTTSubscriber;
}
/* ---------------------------------------------------------------------------------------
Device management specific APIs
Also contains utility methods required for the execution of these APIs
--------------------------------------------------------------------------------------- */
@Path("manager/device/register") @Path("manager/device/register")
@PUT @PUT
public boolean register(@QueryParam("deviceId") String deviceId, public boolean register(@QueryParam("deviceId") String deviceId,
@ -281,7 +332,7 @@ public class FireAlarmService {
public Response downloadSketch(@QueryParam("owner") String owner, public Response downloadSketch(@QueryParam("owner") String owner,
@QueryParam("deviceName") String customDeviceName, @QueryParam("deviceName") String customDeviceName,
@PathParam("sketch_type") String sketchType) { @PathParam("sketch_type") String sketchType) {
//TODO:: null check customDeviceName at UI level
ZipArchive zipFile = null; ZipArchive zipFile = null;
try { try {
zipFile = createDownloadFile(owner, customDeviceName, sketchType); zipFile = createDownloadFile(owner, customDeviceName, sketchType);
@ -335,7 +386,6 @@ public class FireAlarmService {
TokenClient accessTokenClient = new TokenClient(FireAlarmConstants.DEVICE_TYPE); TokenClient accessTokenClient = new TokenClient(FireAlarmConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = null; AccessTokenInfo accessTokenInfo = null;
accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId); accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token //create token
@ -343,8 +393,6 @@ public class FireAlarmService {
String refreshToken = accessTokenInfo.getRefresh_token(); String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data //adding registering data
XmppAccount newXmppAccount = new XmppAccount(); XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(owner + "_" + deviceId); newXmppAccount.setAccountName(owner + "_" + deviceId);
newXmppAccount.setUsername(deviceId); newXmppAccount.setUsername(deviceId);
@ -354,21 +402,24 @@ public class FireAlarmService {
XmppServerClient xmppServerClient = new XmppServerClient(); XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue(); xmppServerClient.initControlQueue();
boolean status; boolean status;
if(XmppConfig.getInstance().isEnabled()) { if(XmppConfig.getInstance().isEnabled()) {
status = xmppServerClient.createXMPPAccount(newXmppAccount); status = xmppServerClient.createXMPPAccount(newXmppAccount);
if (!status) { if (!status) {
String msg = String msg =
"XMPP Account was not created for device - " + deviceId + " of owner - " + "XMPP Account was not created for device - " + deviceId + " of owner - " +
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); log.warn(msg);
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
} }
//Register the device with CDMF
String deviceName = customDeviceName + "_" + deviceId; String deviceName = customDeviceName + "_" + deviceId;
status = register(deviceId, deviceName, owner); status = register(deviceId, deviceName, owner);
if (!status) { if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + owner; + " owner:" + owner;
@ -378,8 +429,8 @@ public class FireAlarmService {
ZipUtil ziputil = new ZipUtil(); ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = null; ZipArchive zipFile = null;
zipFile = ziputil.downloadSketch(owner, SUPER_TENANT, sketchType, deviceId, deviceName,
zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, refreshToken); accessToken, refreshToken);
zipFile.setDeviceId(deviceId); zipFile.setDeviceId(deviceId);
return zipFile; return zipFile;
} }
@ -390,18 +441,27 @@ public class FireAlarmService {
return Long.toString(l, Character.MAX_RADIX); return Long.toString(l, Character.MAX_RADIX);
} }
@Path("controller/register/{owner}/{deviceId}/{ip}") /* ---------------------------------------------------------------------------------------
Device specific APIs - Control APIs + Data-Publishing APIs
Also contains utility methods required for the execution of these APIs
--------------------------------------------------------------------------------------- */
@Path("controller/register/{owner}/{deviceId}/{ip}/{port}")
@POST @POST
public String registerDeviceIP(@PathParam("owner") String owner, public String registerDeviceIP(@PathParam("owner") String owner,
@PathParam("deviceId") String deviceId, @PathParam("deviceId") String deviceId,
@PathParam("ip") String deviceIP, @PathParam("ip") String deviceIP,
@Context HttpServletResponse response) { @PathParam("port") String devicePort,
@Context HttpServletResponse response,
@Context HttpServletRequest request) {
//TODO:: Need to get IP from the request itself
String result; String result;
log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId + log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId +
" of owner: " + owner); " of owner: " + owner);
deviceToIpMap.put(deviceId, deviceIP); String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered"; result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
@ -413,9 +473,8 @@ public class FireAlarmService {
return result; return result;
} }
/* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb
/* Service to switch "ON" and "OFF" the FireAlarm bulb Called by an external client intended to control the Virtual FireAlarm bulb */
Called by an external client intended to control the FireAlarm bulb */
@Path("controller/bulb/{state}") @Path("controller/bulb/{state}")
@POST @POST
public void switchBulb(@HeaderParam("owner") String owner, public void switchBulb(@HeaderParam("owner") String owner,
@ -446,43 +505,41 @@ public class FireAlarmService {
return; return;
} }
String deviceIP = deviceToIpMap.get(deviceId);
if (deviceIP == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
String protocolString = protocol.toUpperCase(); String protocolString = protocol.toUpperCase();
String callUrlPattern = BULB_CONTEXT + switchToState; String callUrlPattern = FireAlarmConstants.BULB_CONTEXT + switchToState;
log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " + if (log.isDebugEnabled()) {
"via" + " " + protocolString); log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " +
protocolString);
}
try { try {
switch (protocolString) { switch (protocolString) {
case HTTP_PROTOCOL: case HTTP_PROTOCOL:
sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true); String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
break; break;
case MQTT_PROTOCOL: case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId, BULB_CONTEXT.replace("/", ""), sendCommandViaMQTT(owner, deviceId,
FireAlarmConstants.BULB_CONTEXT.replace("/", ""),
switchToState); switchToState);
break; break;
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
// requestBulbChangeViaXMPP(switchToState, response); sendCommandViaXMPP(owner, deviceId, FireAlarmConstants.BULB_CONTEXT,
sendCommandViaXMPP(owner, deviceId, BULB_CONTEXT, switchToState); switchToState);
break; break;
default: default:
if (protocolString == null) {
sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return; return;
} }
break;
}
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" + log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " +
" " + protocol); protocolString);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return; return;
} }
@ -513,43 +570,44 @@ public class FireAlarmService {
return replyMsg; return replyMsg;
} }
String deviceIp = deviceToIpMap.get(deviceId); String protocolString = protocol.toUpperCase();
if (deviceIp == null) { if (log.isDebugEnabled()) {
replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; log.debug("Sending request to read sonar value of device [" + deviceId + "] via " +
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); protocolString);
return replyMsg;
} }
try { try {
switch (protocol) { switch (protocolString) {
case HTTP_PROTOCOL: case HTTP_PROTOCOL:
log.info("Sending request to read sonar value at : " + deviceIp + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
" via " + HTTP_PROTOCOL); if (deviceHTTPEndpoint == null) {
replyMsg =
"IP not registered for device: " + deviceId + " of owner: " + owner;
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return replyMsg;
}
replyMsg = sendCommandViaHTTP(deviceHTTPEndpoint,
FireAlarmConstants.SONAR_CONTEXT, false);
break;
replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false); case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId,
FireAlarmConstants.SONAR_CONTEXT.replace("/", ""),
"");
break; break;
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
log.info("Sending request to read sonar value at : " + deviceIp + sendCommandViaXMPP(owner, deviceId, FireAlarmConstants.SONAR_CONTEXT,
" via " + "");
XMPP_PROTOCOL);
replyMsg = sendCommandViaXMPP(owner, deviceId, SONAR_CONTEXT, ".");
break; break;
default: default:
if (protocol == null) { replyMsg = "Requested protocol '" + protocolString + "' is not supported";
log.info("Sending request to read sonar value at : " + deviceIp +
" via " + HTTP_PROTOCOL);
replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false);
} else {
replyMsg = "Requested protocol '" + protocol + "' is not supported";
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return replyMsg; return replyMsg;
} }
break;
}
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage(); replyMsg = e.getErrorMessage();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
@ -564,11 +622,13 @@ public class FireAlarmService {
@Path("controller/readtemperature") @Path("controller/readtemperature")
@GET @GET
public String requestTemperature(@HeaderParam("owner") String owner, @Consumes("application/json")
@Produces("application/json")
public SensorRecord requestTemperature(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId, @HeaderParam("deviceId") String deviceId,
@HeaderParam("protocol") String protocol, @HeaderParam("protocol") String protocol,
@Context HttpServletResponse response) { @Context HttpServletResponse response) {
String replyMsg = ""; SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator(); DeviceValidator deviceValidator = new DeviceValidator();
try { try {
@ -576,117 +636,72 @@ public class FireAlarmService {
FireAlarmConstants FireAlarmConstants
.DEVICE_TYPE))) { .DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return "Unauthorized Access";
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return replyMsg;
} }
String deviceIp = deviceToIpMap.get(deviceId); String protocolString = protocol.toUpperCase();
if (deviceIp == null) { if (log.isDebugEnabled()) {
replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; log.debug(
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); "Sending request to read virtual-firealarm-temperature of device [" +
return replyMsg; deviceId +
"] via " + protocolString);
} }
try { try {
switch (protocol) { switch (protocolString) {
case HTTP_PROTOCOL: case HTTP_PROTOCOL:
log.info("Sending request to read firealarm-temperature at : " + deviceIp + String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
" via " + HTTP_PROTOCOL); if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
}
String tString = sendCommandViaHTTP(deviceHTTPEndpoint,
FireAlarmConstants
.TEMPERATURE_CONTEXT,
false);
String temperatureValue = tString;
SensorDataManager.getInstance().setSensorRecord(deviceId,
FireAlarmConstants
.SENSOR_TEMPERATURE,
temperatureValue,
Calendar.getInstance()
.getTimeInMillis());
break;
replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false); case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId,
FireAlarmConstants.TEMPERATURE_CONTEXT.replace("/",
""),
"");
break; break;
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
log.info("Sending request to read firealarm-temperature at : " + deviceIp + sendCommandViaXMPP(owner, deviceId, FireAlarmConstants
" via " + .TEMPERATURE_CONTEXT, "");
XMPP_PROTOCOL);
replyMsg = sendCommandViaXMPP(owner, deviceId, TEMPERATURE_CONTEXT, ".");
// replyMsg = requestTemperatureViaXMPP(response);
break; break;
default: default:
if (protocol == null) {
log.info("Sending request to read firealarm-temperature at : " + deviceIp +
" via " + HTTP_PROTOCOL);
replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false);
} else {
replyMsg = "Requested protocol '" + protocol + "' is not supported";
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return replyMsg;
}
break;
} }
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
FireAlarmConstants.SENSOR_TEMPERATURE);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return replyMsg; } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
replyMsg = "The current temperature of the device is " + replyMsg; return sensorRecord;
return replyMsg;
} }
@Path("controller/push_temperature")
// public String requestTemperatureViaXMPP(@Context HttpServletResponse response) {
// String replyMsg = "";
//
// String sep = File.separator;
// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts";
// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep
// + "xmpp_client.py -r Temperature";
// String command = "python " + scriptPath;
//
// replyMsg = executeCommand(command);
//
// response.setStatus(HttpStatus.SC_OK);
// return replyMsg;
// }
// public String requestSonarViaXMPP(@Context HttpServletResponse response) {
// String replyMsg = "";
//
// String sep = File.separator;
// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts";
// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep
// + "xmpp_client.py -r Sonar";
// String command = "python " + scriptPath;
//
// replyMsg = executeCommand(command);
//
// response.setStatus(HttpStatus.SC_OK);
// return replyMsg;
// }
// public String requestBulbChangeViaXMPP(String state,
// @Context HttpServletResponse response) {
// String replyMsg = "";
//
// String sep = File.separator;
// String scriptsFolder = "repository" + sep + "resources" + sep + "scripts";
// String scriptPath = CarbonUtils.getCarbonHome() + sep + scriptsFolder + sep
// + "xmpp_client.py -r Bulb -s " + state;
// String command = "python " + scriptPath;
//
// replyMsg = executeCommand(command);
//
// response.setStatus(HttpStatus.SC_OK);
// return replyMsg;
// }
@Path("/controller/push_temperature")
@POST @POST
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData( public void pushTemperatureData(final DeviceJSON dataMsg,
final DeviceJSON dataMsg, @Context HttpServletResponse response) { @Context HttpServletResponse response) {
boolean result; boolean result;
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply; String deviceIp = dataMsg.reply;
@ -701,227 +716,29 @@ public class FireAlarmService {
return; return;
} else if (!registeredIp.equals(deviceIp)) { } else if (!registeredIp.equals(deviceIp)) {
log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " + log.warn("Conflicting IP: Received IP is " + deviceIp + ". Device with ID " +
deviceId + " is already registered under some other IP. Re-registration " + "required"); deviceId +
" is already registered under some other IP. Re-registration " +
"required");
response.setStatus(Response.Status.CONFLICT.getStatusCode()); response.setStatus(Response.Status.CONFLICT.getStatusCode());
return; return;
} }
SensorDataManager.getInstance().setSensorRecord(deviceId,
FireAlarmConstants
.SENSOR_TEMPERATURE,
String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis());
PrivilegedCarbonContext.startTenantFlow(); if (!publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx
.getOSGiService(DeviceAnalyticsService.class, null);
Object metdaData[] = {dataMsg.owner, FireAlarmConstants.DEVICE_TYPE, dataMsg.deviceId,
System.currentTimeMillis()};
Object payloadData[] = {temperature};
try {
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0",
metdaData, new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
}
/* Service to push all the sensor data collected by the FireAlarm
Called by the FireAlarm device */
// @Path("/pushalarmdata")
// @POST
// @Consumes(MediaType.APPLICATION_JSON)
// public void pushAlarmData(final DeviceJSON dataMsg, @Context HttpServletResponse response) {
// boolean result;
// String sensorValues = dataMsg.value;
// log.info("Recieved Sensor Data Values: " + sensorValues);
//
// String sensors[] = sensorValues.split(":");
// try {
// if (sensors.length == 3) {
// String temperature = sensors[0];
// String bulb = sensors[1];
// String sonar = sensors[2];
// sensorValues = "Temperature:" + temperature + "C\tBulb Status:" + bulb +
// "\t\tSonar Status:" + sonar;
// log.info(sensorValues);
// DeviceController deviceController = new DeviceController();
// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants
// .DEVICE_TYPE,
// dataMsg.deviceId,
// System.currentTimeMillis(), "DeviceData",
// temperature, "TEMPERATURE");
//
// if (!result) {
// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
// log.error("Error whilst pushing temperature: " + sensorValues);
// return;
// }
//
// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants
// .DEVICE_TYPE,
// dataMsg.deviceId,
// System.currentTimeMillis(), "DeviceData",
// bulb,
// "BULB");
//
// if (!result) {
// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
// log.error("Error whilst pushing Bulb data: " + sensorValues);
// return;
// }
//
// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants
// .DEVICE_TYPE,
// dataMsg.deviceId,
// System.currentTimeMillis(), "DeviceData",
// sonar,
// "SONAR");
//
// if (!result) {
// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
// log.error("Error whilst pushing Sonar data: " + sensorValues);
// }
//
// } else {
// DeviceController deviceController = new DeviceController();
// result = deviceController.pushBamData(dataMsg.owner, FireAlarmConstants
// .DEVICE_TYPE,
// dataMsg.deviceId,
// System.currentTimeMillis(), "DeviceData",
// dataMsg.value, dataMsg.reply);
// if (!result) {
// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
// log.error("Error whilst pushing sensor data: " + sensorValues);
// }
// }
//
// } catch (UnauthorizedException e) {
// response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
// log.error("Data Push Attempt Failed at Publisher: " + e.getMessage());
// }
// }
private String sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state) throws DeviceManagementException {
String replyMsg = "";
String scriptArguments = "";
String command = "";
String seperator = File.separator;
String xmppServerURL = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppServerURL.lastIndexOf(seperator);
if (indexOfChar != -1) {
xmppServerURL = xmppServerURL.substring((indexOfChar + 1), xmppServerURL.length());
}
indexOfChar = xmppServerURL.indexOf(":");
if (indexOfChar != -1) {
xmppServerURL = xmppServerURL.substring(0, indexOfChar);
} }
String xmppAdminUName = XmppConfig.getInstance().getXmppUsername();
String xmppAdminPass = XmppConfig.getInstance().getXmppPassword();
String xmppAdminUserLogin = xmppAdminUName + "@" + xmppServerURL + seperator + deviceOwner;
String clientToConnect = deviceId + "@" + xmppServerURL + seperator + deviceOwner;
String scriptsFolder = "repository" + seperator + "resources" + seperator + "scripts";
String scriptPath = CarbonUtils.getCarbonHome() + seperator + scriptsFolder + seperator
+ "xmpp_client.py ";
scriptArguments =
"-j " + xmppAdminUserLogin + " -p " + xmppAdminPass + " -c " + clientToConnect +
" -r " + resource + " -s " + state;
command = "python " + scriptPath + scriptArguments;
if (log.isDebugEnabled()) {
log.debug("Connecting to XMPP Server via Admin credentials: " + xmppAdminUserLogin);
log.debug("Trying to contact xmpp device account: " + clientToConnect);
log.debug("Arguments used for the scripts: '" + scriptArguments + "'");
log.debug("Command exceuted: '" + command + "'");
}
// switch (resource) {
// case BULB_CONTEXT:
// scriptArguments = "-r Bulb -s " + state;
// command = "python " + scriptPath + scriptArguments;
// break;
// case SONAR_CONTEXT:
// scriptArguments = "-r Sonar";
// command = "python " + scriptPath + scriptArguments;
// break;
// case TEMPERATURE_CONTEXT:
// scriptArguments = "-r Temperature";
// command = "python " + scriptPath + scriptArguments;
// break;
// }
replyMsg = executeCommand(command);
return replyMsg;
}
private String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
BufferedReader reader =
new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (Exception e) {
log.info(e.getMessage(), e);
}
return output.toString();
}
private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource,
String state) throws DeviceManagementException {
boolean result = false;
DeviceController deviceController = new DeviceController();
try {
result = deviceController.publishMqttControl(deviceOwner,
FireAlarmConstants.DEVICE_TYPE,
deviceId, resource, state);
} catch (DeviceControllerException e) {
String errorMsg = "Error whilst trying to publish to MQTT Queue";
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
return result;
} }
private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
private String sendCommandViaHTTP(final String deviceIp, int deviceServerPort, boolean fireAndForgot) throws DeviceManagementException {
String callUrlPattern,
boolean fireAndForgot)
throws DeviceManagementException {
if (deviceServerPort == 0) {
deviceServerPort = 80;
}
String responseMsg = ""; String responseMsg = "";
String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern; String urlString = FireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug(urlString); log.debug(urlString);
@ -986,13 +803,54 @@ public class FireAlarmService {
} }
} }
} }
} }
return responseMsg; return responseMsg;
} }
/* Utility methods relevant to creating and sending http requests */
private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource,
String state) throws DeviceManagementException {
boolean result = false;
DeviceController deviceController = new DeviceController();
try {
result = deviceController.publishMqttControl(deviceOwner,
FireAlarmConstants.DEVICE_TYPE,
deviceId, resource, state);
} catch (DeviceControllerException e) {
String errorMsg = "Error whilst trying to publish to MQTT Queue";
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
return result;
}
private void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state) throws DeviceManagementException {
String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppServerDomain.lastIndexOf(File.separator);
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1),
xmppServerDomain.length());
}
indexOfChar = xmppServerDomain.indexOf(":");
if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring(0, indexOfChar);
}
String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner;
String message = resource.replace("/", "") + ":" + state;
fireAlarmXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST");
}
/* ---------------------------------------------------------------------------------------
Utility methods relevant to creating and sending http requests
--------------------------------------------------------------------------------------- */
/* This methods creates and returns a http connection object */ /* This methods creates and returns a http connection object */
@ -1061,4 +919,25 @@ public class FireAlarmService {
return completeResponse.toString(); return completeResponse.toString();
} }
public static boolean publishToDAS(String owner, String deviceId, float temperature) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, FireAlarmConstants.DEVICE_TYPE, deviceId,
System.currentTimeMillis()};
Object payloadData[] = {temperature};
try {
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
} }

@ -1,4 +1,4 @@
package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.codehaus.jackson.annotate.JsonIgnoreProperties;

@ -0,0 +1,110 @@
package org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttSubscriber;
import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants.FireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;
public class FireAlarmMQTTSubscriber extends MqttSubscriber {
private static Log log = LogFactory.getLog(FireAlarmMQTTSubscriber.class);
private static final String subscribeTopic =
"wso2" + File.separator + "iot" + File.separator + "+" + File.separator +
FireAlarmConstants.DEVICE_TYPE + File.separator + "+" + File.separator +
"publisher";
private static final String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private static String mqttEndpoint;
private FireAlarmMQTTSubscriber() {
super(iotServerSubscriber, FireAlarmConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
}
public void initConnector() {
mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
}
public void connectAndSubscribe() {
try {
super.connectAndSubscribe();
} catch (DeviceManagementException e) {
log.error("Subscription to MQTT Broker at: " + mqttEndpoint + " failed");
retryMQTTSubscription();
}
}
@Override
protected void postMessageArrived(String topic, MqttMessage message) {
String ownerAndId = topic.replace("wso2" + File.separator + "iot" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + FireAlarmConstants.DEVICE_TYPE + File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + "publisher", "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
log.info("Received MQTT message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}");
if (message.toString().contains("PUBLISHER")) {
log.info("MQTT: Publisher Message [" + message.toString() + "] topic: [" + topic + "]");
float temperature = Float.parseFloat(message.toString().split(":")[2]);
if(!FireAlarmService.publishToDAS(owner, deviceId, temperature)) {
log.error("MQTT Subscriber: Publishing data to DAS failed.");
}
if(log.isDebugEnabled()) {
log.debug("MQTT Subscriber: Published data to DAS successfully.");
}
} else if (message.toString().contains("TEMPERATURE")) {
log.info("MQTT: Reply Message [" + message.toString() + "] topic: [" + topic + "]");
String temperatureValue = message.toString().split(":")[1];
SensorDataManager.getInstance().setSensorRecord(deviceId, FireAlarmConstants.SENSOR_TEMPERATURE, temperatureValue, Calendar.getInstance().getTimeInMillis());
} else {
log.info("MQTT: Message [" + message.toString() + "] topic: [" + topic + "]");
}
}
private void retryMQTTSubscription() {
Thread retryToSubscribe = new Thread() {
@Override
public void run() {
while (true) {
if (!isConnected()) {
if (log.isDebugEnabled()) {
log.debug("Subscriber re-trying to reach MQTT queue....");
}
try {
FireAlarmMQTTSubscriber.super.connectAndSubscribe();
} catch (DeviceManagementException e1) {
if (log.isDebugEnabled()) {
log.debug("Attempt to re-connect to MQTT-Queue failed");
}
}
} else {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
log.error("MQTT: Thread S;eep Interrupt Exception");
}
}
}
};
retryToSubscribe.setDaemon(true);
retryToSubscribe.start();
}
}

@ -0,0 +1,120 @@
package org.wso2.carbon.device.mgt.iot.sample.firealarm.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.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConnector;
import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.plugin.constants
.FireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService;
import java.util.Calendar;
public class FireAlarmXMPPConnector extends XmppConnector {
private static Log log = LogFactory.getLog(FireAlarmXMPPConnector.class);
private static String xmppServerIP;
// private static int xmppServerPort;
private static String xmppAdminUsername;
private static String xmppAdminPassword;
private static String xmppAdminAccountJID;
private FireAlarmXMPPConnector() {
super(XmppConfig.getInstance().getXmppServerIP(),
XmppConfig.getInstance().getSERVER_CONNECTION_PORT());
}
public void initConnector() {
xmppServerIP = XmppConfig.getInstance().getXmppServerIP();
xmppAdminUsername = XmppConfig.getInstance().getXmppUsername();
xmppAdminPassword = XmppConfig.getInstance().getXmppPassword();
xmppAdminAccountJID = xmppAdminUsername + "@" + xmppServerIP;
}
public void connectAndLogin() {
try {
super.connectAndLogin(xmppAdminUsername, xmppAdminPassword, null);
super.setMessageFilterOnReceiver(xmppAdminAccountJID);
} catch (DeviceManagementException e) {
log.error("Connect/Login attempt to XMPP Server at: " + xmppServerIP + " failed");
retryXMPPConnection();
}
}
@Override
protected void processXMPPMessage(Message xmppMessage) {
String from = xmppMessage.getFrom();
String subject = xmppMessage.getSubject();
String message = xmppMessage.getBody();
int indexOfAt = from.indexOf("@");
int indexOfSlash = from.indexOf("/");
String deviceId = from.substring(0, indexOfAt);
String owner = from.substring(indexOfSlash + 1, from.length());
log.info("Received XMPP message for: {OWNER-" + owner + "} & {DEVICE.ID-" + deviceId + "}");
if (subject.equals("PUBLISHER")) {
log.info("XMPP: Publisher Message [" + message + "] from [" + from + "]");
float temperature = Float.parseFloat(message.split(":")[1]);
if(!FireAlarmService.publishToDAS(owner, deviceId, temperature)) {
log.error("XMPP Connector: Publishing data to DAS failed.");
}
if(log.isDebugEnabled()) {
log.debug("XMPP Connector: Published data to DAS successfully.");
}
} else if(subject.equals("CONTROL-REPLY")) {
log.info("XMPP: Reply Message [" + message + "] from [" + from + "]");
String temperature = message.split(":")[1];
SensorDataManager.getInstance().setSensorRecord(deviceId,FireAlarmConstants.SENSOR_TEMPERATURE, temperature, Calendar.getInstance().getTimeInMillis());
} else {
log.info("SOME XMPP Message [" + message + "] from " + from + "]");
}
}
private void retryXMPPConnection() {
Thread retryToConnect = new Thread() {
@Override
public void run() {
while (true) {
if (!isConnected()) {
if (log.isDebugEnabled()) {
log.debug("Re-trying to reach XMPP Server....");
}
try {
FireAlarmXMPPConnector.super.connectAndLogin(xmppAdminUsername,
xmppAdminPassword,
null);
FireAlarmXMPPConnector.super.setMessageFilterOnReceiver(
xmppAdminAccountJID);
} catch (DeviceManagementException e1) {
if (log.isDebugEnabled()) {
log.debug("Attempt to re-connect to XMPP-Server failed");
}
}
} else {
break;
}
try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
log.error("XMPP: Thread Sleep Interrupt Exception");
}
}
}
};
retryToConnect.setDaemon(true);
retryToConnect.start();
}
}

@ -1,89 +0,0 @@
/*
* Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*//*
package org.wso2.carbon.device.mgt.iot.firealarm.api.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.mqtt.MqttSubscriber;
import org.wso2.carbon.device.mgt.iot.firealarm.api.FireAlarmControllerService;
import org.wso2.carbon.device.mgt.iot.firealarm.constants.FireAlarmConstants;
import java.io.File;
import java.util.LinkedList;
public class MQTTFirealarmSubscriber extends MqttSubscriber {
private static Log log = LogFactory.getLog(MQTTFirealarmSubscriber.class);
private static final String subscribetopic =
"wso2" + File.separator + "iot" + File.separator + "+" + File.separator +
FireAlarmConstants.DEVICE_TYPE + File.separator + "#";
private MQTTFirealarmSubscriber() {
super("Subscriber", FireAlarmConstants.DEVICE_TYPE, FireAlarmControllerService.CONTROL_QUEUE_ENDPOINT,
subscribetopic);
}
@Override protected void postMessageArrived(final String topic, final MqttMessage message) {
int lastIndex = topic.lastIndexOf("/");
String deviceId = topic.substring(lastIndex + 1);
lastIndex = message.toString().lastIndexOf(":");
String msgContext = message.toString().substring(lastIndex + 1);
LinkedList<String> deviceControlList = null;
LinkedList<String> replyMessageList = null;
if (msgContext.equals("IN") || msgContext.equals(FireAlarmConstants.STATE_ON) || msgContext
.equals(FireAlarmConstants.STATE_OFF)) {
log.info("Recieved a control message: ");
log.info("Control message topic: " + topic);
log.info("Control message: " + message.toString());
// synchronized (FireAlarmControllerService.internalControlsQueue) {
// deviceControlList = FireAlarmControllerService.internalControlsQueue.get(deviceId);
synchronized (FireAlarmControllerService.getInternalControlsQueue()) {
deviceControlList = FireAlarmControllerService.getInternalControlsQueue().get(deviceId);
if (deviceControlList == null) {
// FireAlarmControllerService.internalControlsQueue
FireAlarmControllerService.getInternalControlsQueue()
.put(deviceId, deviceControlList = new LinkedList<String>());
}
}
deviceControlList.add(message.toString());
} else if (msgContext.equals("OUT")) {
log.info("Recieved reply from a device: ");
log.info("Reply message topic: " + topic);
log.info("Reply message: " + message.toString().substring(0, lastIndex));
// synchronized (FireAlarmControllerService.replyMsgQueue) {
// replyMessageList = FireAlarmControllerService.replyMsgQueue.get(deviceId);
synchronized (FireAlarmControllerService.getReplyMsgQueue()) {
replyMessageList = FireAlarmControllerService.getReplyMsgQueue().get(deviceId);
if (replyMessageList == null) {
// FireAlarmControllerService.replyMsgQueue
FireAlarmControllerService.getReplyMsgQueue()
.put(deviceId, replyMessageList = new LinkedList<String>());
}
}
replyMessageList.add(message.toString());
}
}
}
*/

@ -0,0 +1,105 @@
<?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.
-->
<!-- 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.
For ex:
Actual API endpoint: mdm-admin/1.0.0/devices/{device-id}
URL to be represented here: /devices/*
NOTE: All the endpoints of the web app should be available in this file. Otherwise
it will result 403 error at the runtime.
-->
<ResourceConfiguration>
<!-- Device related APIs -->
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>PUT</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/device/register</Uri>
<UriTemplate>/manager/device/register/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>DELETE</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/device/remove</Uri>
<UriTemplate>/manager/device/remove/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/device/update</Uri>
<UriTemplate>/manager/device/update/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/device</Uri>
<UriTemplate>/manager/device/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/devices</Uri>
<UriTemplate>/manager/devices/*</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/device/{sketch_type}/download</Uri>
<UriTemplate>/manager/device/{sketch_type}/download</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/firealarm/manager/device/{sketch_type}/generate_link</Uri>
<UriTemplate>/manager/device/{sketch_type}/generate_link</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/firealarm/controller/register/{owner}/{deviceId}/{ip}/{port}</Uri>
<UriTemplate>/controller/register/{owner}/{deviceId}/{ip}/{port}</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/firealarm/controller/controller/bulb/{state}</Uri>
<UriTemplate>/controller/bulb/{state}</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/firealarm/controller/controller/readsonar</Uri>
<UriTemplate>/controller/readsonar</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>GET</HttpVerb>
<Uri>http://localhost:9763/firealarm/controller/controller/readtemperature</Uri>
<UriTemplate>/controller/readtemperature</UriTemplate>
</Resource>
<Resource>
<AuthType>Any</AuthType>
<HttpVerb>POST</HttpVerb>
<Uri>http://localhost:9763/firealarm/controller/controller/push_temperature</Uri>
<UriTemplate>/controller/push_temperature</UriTemplate>
</Resource>
</ResourceConfiguration>

@ -25,7 +25,10 @@
<jaxrs:server id="FireAlarm" address="/"> <jaxrs:server id="FireAlarm" address="/">
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<bean id="FireAlarmService" <bean id="FireAlarmService"
class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService"/> class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.FireAlarmService">
<property name="fireAlarmMQTTSubscriber" ref="mqttSubscriberBean"/>
<property name="fireAlarmXMPPConnector" ref="xmppConnectorBean"/>
</bean>
</jaxrs:serviceBeans> </jaxrs:serviceBeans>
<jaxrs:providers> <jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" /> <bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
@ -33,8 +36,11 @@
</jaxrs:server> </jaxrs:server>
<!--<bean id="mqttSubscriber" class="org.wso2.carbon.device.mgt.iot.firealarm.api.util.MQTTFirealarmSubscriber" >--> <bean id="mqttSubscriberBean"
<!-- --> class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport.FireAlarmMQTTSubscriber">
<!--</bean>--> </bean>
<bean id="xmppConnectorBean"
class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport.FireAlarmXMPPConnector">
</bean>
</beans> </beans>

@ -109,6 +109,13 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<version>${carbon.device.mgt.version}</version>
<scope>provided</scope>
</dependency>
<!--IOT dependencies--> <!--IOT dependencies-->
<dependency> <dependency>
@ -334,6 +341,7 @@
<scope>provided</scope> <scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId> <artifactId>org.wso2.carbon.utils</artifactId>
@ -457,6 +465,7 @@
<commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.version> <commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.version>
<commons-json.version>3.0.0.wso2v1</commons-json.version> <commons-json.version>3.0.0.wso2v1</commons-json.version>
<commons-codec.version>1.7</commons-codec.version>
<jackson.fasterxml.version>2.6.1</jackson.fasterxml.version> <jackson.fasterxml.version>2.6.1</jackson.fasterxml.version>
<!-- Source code --> <!-- Source code -->

@ -25,8 +25,31 @@
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId> <artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<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>
</dependency> </dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF --> <!--CXF -->
<dependency> <dependency>
<groupId>org.apache.cxf</groupId> <groupId>org.apache.cxf</groupId>
@ -151,10 +174,13 @@
</exclusion> </exclusion>
</exclusions> </exclusions>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon.devicemgt</groupId> <groupId>commons-codec</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId> <artifactId>commons-codec</artifactId>
<version>${commons-codec.version}</version>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.igniterealtime.smack.wso2</groupId> <groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId> <artifactId>smack</artifactId>

@ -16,6 +16,7 @@
package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl; package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
@ -23,6 +24,9 @@ import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback; import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients; import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.wso2.carbon.certificate.mgt.core.dto.SCEPResponse;
import org.wso2.carbon.certificate.mgt.core.exception.KeystoreException;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException; 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.service.DeviceAnalyticsService;
@ -45,20 +49,34 @@ import org.wso2.carbon.device.mgt.iot.common.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive; import org.wso2.carbon.device.mgt.iot.common.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil; import org.wso2.carbon.device.mgt.iot.common.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants.VirtualFireAlarmConstants; import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.dto.DeviceJSON; import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.dto.DeviceJSON;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmMQTTSubscriber; import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.exception.VirtualFireAlarmEnrollmentException;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmXMPPConnector; import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.ContentType;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmMQTTSubscriber;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmServiceUtils;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmXMPPConnector;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.scep.SCEPOperation;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*; import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.HttpMethod;
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.Context;
import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.net.HttpURLConnection; import java.net.HttpURLConnection;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@ -66,7 +84,11 @@ import java.net.ProtocolException;
import java.net.URL; import java.net.URL;
import java.nio.ByteBuffer; import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future; import java.util.concurrent.Future;
@ -185,8 +207,7 @@ public class VirtualFireAlarmService {
@Path("manager/device/remove/{device_id}") @Path("manager/device/remove/{device_id}")
@DELETE @DELETE
public void removeDevice(@PathParam("device_id") String deviceId, public void removeDevice(@PathParam("device_id") String deviceId, @Context HttpServletResponse response) {
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT); DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
@ -232,7 +253,8 @@ public class VirtualFireAlarmService {
device.setName(name); device.setName(name);
device.setType(VirtualFireAlarmConstants.DEVICE_TYPE); device.setType(VirtualFireAlarmConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(device); boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(
device);
if (updated) { if (updated) {
response.setStatus(Response.Status.OK.getStatusCode()); response.setStatus(Response.Status.OK.getStatusCode());
@ -297,7 +319,7 @@ public class VirtualFireAlarmService {
} }
} }
return userDevicesforFirealarm.toArray(new Device[] {}); return userDevicesforFirealarm.toArray(new Device[]{});
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null; return null;
@ -490,7 +512,8 @@ public class VirtualFireAlarmService {
String callUrlPattern = VirtualFireAlarmConstants.BULB_CONTEXT + switchToState; String callUrlPattern = VirtualFireAlarmConstants.BULB_CONTEXT + switchToState;
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " + protocolString); log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " +
protocolString);
} }
try { try {
@ -505,17 +528,21 @@ public class VirtualFireAlarmService {
sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true); sendCommandViaHTTP(deviceHTTPEndpoint, callUrlPattern, true);
break; break;
case MQTT_PROTOCOL: case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId, VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", ""), switchToState); sendCommandViaMQTT(owner, deviceId,
VirtualFireAlarmConstants.BULB_CONTEXT.replace("/", ""),
switchToState);
break; break;
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.BULB_CONTEXT, switchToState); sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.BULB_CONTEXT,
switchToState);
break; break;
default: default:
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return; return;
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " + protocolString); log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " +
protocolString);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return; return;
} }
@ -534,7 +561,8 @@ public class VirtualFireAlarmService {
DeviceValidator deviceValidator = new DeviceValidator(); DeviceValidator deviceValidator = new DeviceValidator();
try { try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE))) { if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
VirtualFireAlarmConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return "Unauthorized Access"; return "Unauthorized Access";
} }
@ -547,7 +575,8 @@ public class VirtualFireAlarmService {
String protocolString = protocol.toUpperCase(); String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Sending request to read sonar value of device [" + deviceId + "] via " + protocolString); log.debug("Sending request to read sonar value of device [" + deviceId + "] via " +
protocolString);
} }
try { try {
@ -555,20 +584,25 @@ public class VirtualFireAlarmService {
case HTTP_PROTOCOL: case HTTP_PROTOCOL:
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId); String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
if (deviceHTTPEndpoint == null) { if (deviceHTTPEndpoint == null) {
replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner; replyMsg =
"IP not registered for device: " + deviceId + " of owner: " + owner;
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return replyMsg; return replyMsg;
} }
replyMsg = sendCommandViaHTTP(deviceHTTPEndpoint, VirtualFireAlarmConstants.SONAR_CONTEXT, false); replyMsg = sendCommandViaHTTP(deviceHTTPEndpoint,
VirtualFireAlarmConstants.SONAR_CONTEXT, false);
break; break;
case MQTT_PROTOCOL: case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId, VirtualFireAlarmConstants.SONAR_CONTEXT.replace("/", ""), ""); sendCommandViaMQTT(owner, deviceId,
VirtualFireAlarmConstants.SONAR_CONTEXT.replace("/", ""),
"");
break; break;
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.SONAR_CONTEXT, ""); sendCommandViaXMPP(owner, deviceId, VirtualFireAlarmConstants.SONAR_CONTEXT,
"");
break; break;
default: default:
@ -600,7 +634,8 @@ public class VirtualFireAlarmService {
DeviceValidator deviceValidator = new DeviceValidator(); DeviceValidator deviceValidator = new DeviceValidator();
try { try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE))) { if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(deviceId,
VirtualFireAlarmConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode()); response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
@ -610,7 +645,9 @@ public class VirtualFireAlarmService {
String protocolString = protocol.toUpperCase(); String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Sending request to read virtual-firealarm-temperature of device [" + deviceId + "] via " + protocolString); log.debug(
"Sending request to read virtual-firealarm-temperature of device [" + deviceId +
"] via " + protocolString);
} }
try { try {
@ -620,14 +657,24 @@ public class VirtualFireAlarmService {
if (deviceHTTPEndpoint == null) { if (deviceHTTPEndpoint == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode()); response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
} }
String tString = sendCommandViaHTTP(deviceHTTPEndpoint, VirtualFireAlarmConstants.TEMPERATURE_CONTEXT, false); String tString = sendCommandViaHTTP(deviceHTTPEndpoint,
VirtualFireAlarmConstants
.TEMPERATURE_CONTEXT,
false);
String temperatureValue = tString; String temperatureValue = tString;
SensorDataManager.getInstance().setSensorRecord(deviceId, VirtualFireAlarmConstants.SENSOR_TEMPERATURE, temperatureValue, SensorDataManager.getInstance().setSensorRecord(deviceId,
Calendar.getInstance().getTimeInMillis()); VirtualFireAlarmConstants
.SENSOR_TEMPERATURE,
temperatureValue,
Calendar.getInstance()
.getTimeInMillis());
break; break;
case MQTT_PROTOCOL: case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId, VirtualFireAlarmConstants.TEMPERATURE_CONTEXT.replace("/", ""), ""); sendCommandViaMQTT(owner, deviceId,
VirtualFireAlarmConstants.TEMPERATURE_CONTEXT.replace("/",
""),
"");
break; break;
case XMPP_PROTOCOL: case XMPP_PROTOCOL:
@ -638,10 +685,11 @@ public class VirtualFireAlarmService {
default: default:
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode()); response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
} }
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId, VirtualFireAlarmConstants.SENSOR_TEMPERATURE); sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
VirtualFireAlarmConstants.SENSOR_TEMPERATURE);
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} catch (DeviceControllerException e){ } catch (DeviceControllerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} }
@ -652,7 +700,8 @@ public class VirtualFireAlarmService {
@Path("controller/push_temperature") @Path("controller/push_temperature")
@POST @POST
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData(final DeviceJSON dataMsg, @Context HttpServletResponse response) { public void pushTemperatureData(final DeviceJSON dataMsg,
@Context HttpServletResponse response) {
boolean result; boolean result;
String deviceId = dataMsg.deviceId; String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply; String deviceIp = dataMsg.reply;
@ -674,7 +723,8 @@ public class VirtualFireAlarmService {
return; return;
} }
SensorDataManager.getInstance().setSensorRecord(deviceId, SensorDataManager.getInstance().setSensorRecord(deviceId,
VirtualFireAlarmConstants.SENSOR_TEMPERATURE, VirtualFireAlarmConstants
.SENSOR_TEMPERATURE,
String.valueOf(temperature), String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis()); Calendar.getInstance().getTimeInMillis());
@ -684,7 +734,8 @@ public class VirtualFireAlarmService {
} }
private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext, boolean fireAndForgot) throws DeviceManagementException { private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
boolean fireAndForgot) throws DeviceManagementException {
String responseMsg = ""; String responseMsg = "";
String urlString = VirtualFireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext; String urlString = VirtualFireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;
@ -758,8 +809,8 @@ public class VirtualFireAlarmService {
} }
private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource,
private boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource, String state) throws DeviceManagementException { String state) throws DeviceManagementException {
boolean result = false; boolean result = false;
DeviceController deviceController = new DeviceController(); DeviceController deviceController = new DeviceController();
@ -776,12 +827,14 @@ public class VirtualFireAlarmService {
return result; return result;
} }
private void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource, String state) throws DeviceManagementException { private void sendCommandViaXMPP(String deviceOwner, String deviceId, String resource,
String state) throws DeviceManagementException {
String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint(); String xmppServerDomain = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppServerDomain.lastIndexOf(File.separator); int indexOfChar = xmppServerDomain.lastIndexOf(File.separator);
if (indexOfChar != -1) { if (indexOfChar != -1) {
xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1), xmppServerDomain.length()); xmppServerDomain = xmppServerDomain.substring((indexOfChar + 1),
xmppServerDomain.length());
} }
indexOfChar = xmppServerDomain.indexOf(":"); indexOfChar = xmppServerDomain.indexOf(":");
@ -790,7 +843,7 @@ public class VirtualFireAlarmService {
} }
String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner; String clientToConnect = deviceId + "@" + xmppServerDomain + File.separator + deviceOwner;
String message = resource.replace("/","") + ":" + state; String message = resource.replace("/", "") + ":" + state;
virtualFireAlarmXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST"); virtualFireAlarmXMPPConnector.sendXMPPMessage(clientToConnect, message, "CONTROL-REQUEST");
} }
@ -866,17 +919,19 @@ public class VirtualFireAlarmService {
return completeResponse.toString(); return completeResponse.toString();
} }
public static boolean publishToDAS(String owner, String deviceId, float temperature){ public static boolean publishToDAS(String owner, String deviceId, float temperature) {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext(); PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true); ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService( DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null); DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, VirtualFireAlarmConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()}; Object metdaData[] = {owner, VirtualFireAlarmConstants.DEVICE_TYPE, deviceId,
System.currentTimeMillis()};
Object payloadData[] = {temperature}; Object payloadData[] = {temperature};
try { try {
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadData); deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) { } catch (DataPublisherConfigurationException e) {
return false; return false;
} finally { } finally {
@ -884,4 +939,146 @@ public class VirtualFireAlarmService {
} }
return true; return true;
} }
// @GET
// @Path("/enrol")
// public Response scepRequest(String certificateSignRequest) {
//
// Base64 base64Encoder = new Base64();
// String signedCertEncodedString = "";
//
//
// CertificateManagementService certificateManagementService = null;
// try {
// certificateManagementService = VirtualFireAlarmServiceUtils.getCertificateManagementService();
// X509Certificate signedCeritficate = certificateManagementService.getSignedCertificateFromCSR(certificateSignRequest);
// signedCertEncodedString = base64Encoder.encodeAsString(signedCeritficate.getEncoded());
// } catch (VirtualFireAlarmEnrollmentException e) {
// e.printStackTrace();
// } catch (KeystoreException e) {
// e.printStackTrace();
// } catch (CertificateEncodingException e) {
// e.printStackTrace();
// }
//
//
// Response.ResponseBuilder responseBuilder = Response.ok(signedCertEncodedString, ContentType.X_X509_CA_CERT);;
// return responseBuilder.build();
// }
@GET
@Path("/scep")
public Response scepRequest(@QueryParam("operation") String operation) {
if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation);
}
if (SCEPOperation.GET_CA_CERT.getValue().equals(operation)) {
if (log.isDebugEnabled()) {
log.debug("Invoking GetCACert");
}
try {
CertificateManagementService certificateManagementService =
VirtualFireAlarmServiceUtils.getCertificateManagementService();
SCEPResponse scepResponse = certificateManagementService.getCACertSCEP();
Response.ResponseBuilder responseBuilder;
switch (scepResponse.getResultCriteria()) {
case CA_CERT_FAILED:
log.error("CA cert failed");
responseBuilder = Response.serverError();
break;
case CA_CERT_RECEIVED:
if (log.isDebugEnabled()) {
log.debug("CA certificate received in GetCACert");
}
responseBuilder = Response.ok(scepResponse.getEncodedResponse(),
ContentType.X_X509_CA_CERT);
break;
case CA_RA_CERT_RECEIVED:
if (log.isDebugEnabled()) {
log.debug("CA and RA certificates received in GetCACert");
}
responseBuilder = Response.ok(scepResponse.getEncodedResponse(),
ContentType.X_X509_CA_RA_CERT);
break;
default:
log.error("Invalid SCEP request");
responseBuilder = Response.serverError();
break;
}
return responseBuilder.build();
} catch (VirtualFireAlarmEnrollmentException e) {
log.error("Error occurred while enrolling the iOS device", e);
} catch (KeystoreException e) {
log.error("Keystore error occurred while enrolling the iOS device", e);
}
} else if (SCEPOperation.GET_CA_CAPS.getValue().equals(operation)) {
if (log.isDebugEnabled()) {
log.debug("Invoking GetCACaps");
}
try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils.
getCertificateManagementService();
byte caCaps[] = certificateManagementService.getCACapsSCEP();
return Response.ok(caCaps, MediaType.TEXT_PLAIN).build();
} catch (VirtualFireAlarmEnrollmentException e) {
log.error("Error occurred while enrolling the iOS device", e);
}
} else {
log.error("Invalid SCEP operation " + operation);
}
return Response.serverError().build();
}
@POST
@Consumes({ContentType.X_PKI_MESSAGE})
@Path("/scep")
public Response scepRequestPost(@QueryParam("operation") String operation,
InputStream inputStream) {
if (log.isDebugEnabled()) {
log.debug("Invoking SCEP operation " + operation);
}
if (SCEPOperation.PKI_OPERATION.getValue().equals(operation)) {
if (log.isDebugEnabled()) {
log.debug("Invoking PKIOperation");
}
try {
CertificateManagementService certificateManagementService = VirtualFireAlarmServiceUtils.
getCertificateManagementService();
byte pkiMessage[] = certificateManagementService.getPKIMessageSCEP(inputStream);
return Response.ok(pkiMessage, ContentType.X_PKI_MESSAGE).build();
} catch (VirtualFireAlarmEnrollmentException e) {
log.error("Error occurred while enrolling the iOS device", e);
} catch (KeystoreException e) {
log.error("Keystore error occurred while enrolling the iOS device", e);
}
}
return Response.serverError().build();
}
} }

@ -0,0 +1,13 @@
package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.exception;
public class VirtualFireAlarmEnrollmentException extends Exception {
private static final long serialVersionUID = 118512086957330189L;
public VirtualFireAlarmEnrollmentException(String errorMessage) {
super(errorMessage);
}
public VirtualFireAlarmEnrollmentException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

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

@ -1,11 +1,8 @@
package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util; package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.jivesoftware.smack.packet.Message; import org.jivesoftware.smack.packet.Message;
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.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConnector; import org.wso2.carbon.device.mgt.iot.common.controlqueue.xmpp.XmppConnector;

@ -0,0 +1,8 @@
package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util;
public class ContentType {
public static final String X_PKI_MESSAGE = "application/x-pki-message";
public static final String X_X509_CA_CERT = "application/x-x509-ca-cert";
public static final String X_X509_CA_RA_CERT = "application/x-x509-ca-ra-cert";
}

@ -0,0 +1,29 @@
package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.certificate.mgt.core.service.CertificateManagementService;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.exception
.VirtualFireAlarmEnrollmentException;
public class VirtualFireAlarmServiceUtils {
private static final Log log = LogFactory.getLog(VirtualFireAlarmServiceUtils.class);
public static CertificateManagementService getCertificateManagementService() throws
VirtualFireAlarmEnrollmentException {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
CertificateManagementService certificateManagementService = (CertificateManagementService)
ctx.getOSGiService(CertificateManagementService.class, null);
if (certificateManagementService == null) {
String msg = "EnrollmentService is not initialized";
log.error(msg);
throw new VirtualFireAlarmEnrollmentException(msg);
}
return certificateManagementService;
}
}

@ -0,0 +1,21 @@
package org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.scep;
public enum SCEPOperation {
GET_CA_CERT("GetCACert"),
GET_CA_CAPS("GetCACaps"),
PKI_OPERATION("PKIOperation");
private String value;
private SCEPOperation(String value) {
this.setValue(value);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}

@ -51,10 +51,10 @@
<bean id="mqttSubscriberBean" <bean id="mqttSubscriberBean"
class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmMQTTSubscriber"> class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmMQTTSubscriber">
</bean> </bean>
<bean id="xmppConnectorBean" <bean id="xmppConnectorBean"
class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.util.VirtualFireAlarmXMPPConnector"> class="org.wso2.carbon.device.mgt.iot.sample.virtual.firealarm.service.impl.transport.VirtualFireAlarmXMPPConnector">
</bean> </bean>
</beans> </beans>

Loading…
Cancel
Save