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]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
server-ep=${SERVER_EP}
service-ep=${SERVICE_EP}
device-name=${DEVICE_NAME}
controller-context=/firealarm/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
network-interface=wlan0
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 STATE_ON = "ON";
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.exception.AccessTokenException;
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.ZipUtil;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@ -73,6 +80,7 @@ import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@ -86,24 +94,67 @@ public class FireAlarmService {
private static Log log = LogFactory.getLog(FireAlarmService.class);
//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
private HttpServletResponse response;
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 HTTP_PROTOCOL = "HTTP";
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>();
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")
@PUT
public boolean register(@QueryParam("deviceId") String deviceId,
@ -281,7 +332,7 @@ public class FireAlarmService {
public Response downloadSketch(@QueryParam("owner") String owner,
@QueryParam("deviceName") String customDeviceName,
@PathParam("sketch_type") String sketchType) {
//TODO:: null check customDeviceName at UI level
ZipArchive zipFile = null;
try {
zipFile = createDownloadFile(owner, customDeviceName, sketchType);
@ -335,7 +386,6 @@ public class FireAlarmService {
TokenClient accessTokenClient = new TokenClient(FireAlarmConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = null;
accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
@ -343,8 +393,6 @@ public class FireAlarmService {
String refreshToken = accessTokenInfo.getRefresh_token();
//adding registering data
XmppAccount newXmppAccount = new XmppAccount();
newXmppAccount.setAccountName(owner + "_" + deviceId);
newXmppAccount.setUsername(deviceId);
@ -354,21 +402,24 @@ public class FireAlarmService {
XmppServerClient xmppServerClient = new XmppServerClient();
xmppServerClient.initControlQueue();
boolean status;
if(XmppConfig.getInstance().isEnabled()) {
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);
}
}
//Register the device with CDMF
String deviceName = customDeviceName + "_" + deviceId;
status = register(deviceId, deviceName, owner);
if (!status) {
String msg = "Error occurred while registering the device with " + "id: " + deviceId
+ " owner:" + owner;
@ -378,8 +429,8 @@ public class FireAlarmService {
ZipUtil ziputil = new ZipUtil();
ZipArchive zipFile = null;
zipFile = ziputil.downloadSketch(owner,SUPER_TENANT, sketchType, deviceId, deviceName, accessToken, refreshToken);
zipFile = ziputil.downloadSketch(owner, SUPER_TENANT, sketchType, deviceId, deviceName,
accessToken, refreshToken);
zipFile.setDeviceId(deviceId);
return zipFile;
}
@ -390,18 +441,27 @@ public class FireAlarmService {
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
public String registerDeviceIP(@PathParam("owner") String owner,
@PathParam("deviceId") String deviceId,
@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;
log.info("Got register call from IP: " + deviceIP + " for Device ID: " + deviceId +
" of owner: " + owner);
deviceToIpMap.put(deviceId, deviceIP);
String deviceHttpEndpoint = deviceIP + ":" + devicePort;
deviceToIpMap.put(deviceId, deviceHttpEndpoint);
result = "Device-IP Registered";
response.setStatus(Response.Status.OK.getStatusCode());
@ -413,9 +473,8 @@ public class FireAlarmService {
return result;
}
/* Service to switch "ON" and "OFF" the FireAlarm bulb
Called by an external client intended to control the FireAlarm bulb */
/* Service to switch "ON" and "OFF" the Virtual FireAlarm bulb
Called by an external client intended to control the Virtual FireAlarm bulb */
@Path("controller/bulb/{state}")
@POST
public void switchBulb(@HeaderParam("owner") String owner,
@ -446,43 +505,41 @@ public class FireAlarmService {
return;
}
String deviceIP = deviceToIpMap.get(deviceId);
if (deviceIP == null) {
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return;
}
String protocolString = protocol.toUpperCase();
String callUrlPattern = BULB_CONTEXT + switchToState;
String callUrlPattern = FireAlarmConstants.BULB_CONTEXT + switchToState;
log.info("Sending command: '" + callUrlPattern + "' to firealarm at: " + deviceIP + " " +
"via" + " " + protocolString);
if (log.isDebugEnabled()) {
log.debug("Sending request to switch-bulb of device [" + deviceId + "] via " +
protocolString);
}
try {
switch (protocolString) {
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;
case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId, BULB_CONTEXT.replace("/", ""),
sendCommandViaMQTT(owner, deviceId,
FireAlarmConstants.BULB_CONTEXT.replace("/", ""),
switchToState);
break;
case XMPP_PROTOCOL:
// requestBulbChangeViaXMPP(switchToState, response);
sendCommandViaXMPP(owner, deviceId, BULB_CONTEXT, switchToState);
sendCommandViaXMPP(owner, deviceId, FireAlarmConstants.BULB_CONTEXT,
switchToState);
break;
default:
if (protocolString == null) {
sendCommandViaHTTP(deviceIP, 80, callUrlPattern, true);
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return;
}
break;
}
} catch (DeviceManagementException e) {
log.error("Failed to send command '" + callUrlPattern + "' to: " + deviceIP + " via" +
" " + protocol);
log.error("Failed to send switch-bulb request to device [" + deviceId + "] via " +
protocolString);
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return;
}
@ -513,43 +570,44 @@ public class FireAlarmService {
return replyMsg;
}
String deviceIp = deviceToIpMap.get(deviceId);
String protocolString = protocol.toUpperCase();
if (deviceIp == null) {
replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner;
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return replyMsg;
if (log.isDebugEnabled()) {
log.debug("Sending request to read sonar value of device [" + deviceId + "] via " +
protocolString);
}
try {
switch (protocol) {
switch (protocolString) {
case HTTP_PROTOCOL:
log.info("Sending request to read sonar value at : " + deviceIp +
" via " + HTTP_PROTOCOL);
replyMsg = sendCommandViaHTTP(deviceIp, 80, SONAR_CONTEXT, false);
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
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;
case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId,
FireAlarmConstants.SONAR_CONTEXT.replace("/", ""),
"");
break;
case XMPP_PROTOCOL:
log.info("Sending request to read sonar value at : " + deviceIp +
" via " +
XMPP_PROTOCOL);
replyMsg = sendCommandViaXMPP(owner, deviceId, SONAR_CONTEXT, ".");
sendCommandViaXMPP(owner, deviceId, FireAlarmConstants.SONAR_CONTEXT,
"");
break;
default:
if (protocol == null) {
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";
replyMsg = "Requested protocol '" + protocolString + "' is not supported";
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
return replyMsg;
}
break;
}
} catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
@ -564,11 +622,13 @@ public class FireAlarmService {
@Path("controller/readtemperature")
@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("protocol") String protocol,
@Context HttpServletResponse response) {
String replyMsg = "";
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
@ -576,117 +636,72 @@ public class FireAlarmService {
FireAlarmConstants
.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
return "Unauthorized Access";
}
} catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage();
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return replyMsg;
}
String deviceIp = deviceToIpMap.get(deviceId);
String protocolString = protocol.toUpperCase();
if (deviceIp == null) {
replyMsg = "IP not registered for device: " + deviceId + " of owner: " + owner;
response.setStatus(Response.Status.PRECONDITION_FAILED.getStatusCode());
return replyMsg;
if (log.isDebugEnabled()) {
log.debug(
"Sending request to read virtual-firealarm-temperature of device [" +
deviceId +
"] via " + protocolString);
}
try {
switch (protocol) {
switch (protocolString) {
case HTTP_PROTOCOL:
log.info("Sending request to read firealarm-temperature at : " + deviceIp +
" via " + HTTP_PROTOCOL);
replyMsg = sendCommandViaHTTP(deviceIp, 80, TEMPERATURE_CONTEXT, false);
String deviceHTTPEndpoint = deviceToIpMap.get(deviceId);
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;
case MQTT_PROTOCOL:
sendCommandViaMQTT(owner, deviceId,
FireAlarmConstants.TEMPERATURE_CONTEXT.replace("/",
""),
"");
break;
case XMPP_PROTOCOL:
log.info("Sending request to read firealarm-temperature at : " + deviceIp +
" via " +
XMPP_PROTOCOL);
replyMsg = sendCommandViaXMPP(owner, deviceId, TEMPERATURE_CONTEXT, ".");
// replyMsg = requestTemperatureViaXMPP(response);
sendCommandViaXMPP(owner, deviceId, FireAlarmConstants
.TEMPERATURE_CONTEXT, "");
break;
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());
return replyMsg;
}
break;
}
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
FireAlarmConstants.SENSOR_TEMPERATURE);
} catch (DeviceManagementException e) {
replyMsg = e.getErrorMessage();
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());
replyMsg = "The current temperature of the device is " + replyMsg;
return replyMsg;
return sensorRecord;
}
// 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")
@Path("controller/push_temperature")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void pushTemperatureData(
final DeviceJSON dataMsg, @Context HttpServletResponse response) {
public void pushTemperatureData(final DeviceJSON dataMsg,
@Context HttpServletResponse response) {
boolean result;
String deviceId = dataMsg.deviceId;
String deviceIp = dataMsg.reply;
@ -701,227 +716,29 @@ public class FireAlarmService {
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");
deviceId +
" is already registered under some other IP. Re-registration " +
"required");
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return;
}
SensorDataManager.getInstance().setSensorRecord(deviceId,
FireAlarmConstants
.SENSOR_TEMPERATURE,
String.valueOf(temperature),
Calendar.getInstance().getTimeInMillis());
PrivilegedCarbonContext.startTenantFlow();
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) {
if (!publishToDAS(dataMsg.owner, dataMsg.deviceId, dataMsg.value)) {
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 deviceIp, int deviceServerPort,
String callUrlPattern,
boolean fireAndForgot)
throws DeviceManagementException {
if (deviceServerPort == 0) {
deviceServerPort = 80;
}
private String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
boolean fireAndForgot) throws DeviceManagementException {
String responseMsg = "";
String urlString = URL_PREFIX + deviceIp + ":" + deviceServerPort + callUrlPattern;
String urlString = FireAlarmConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;
if (log.isDebugEnabled()) {
log.debug(urlString);
@ -986,13 +803,54 @@ public class FireAlarmService {
}
}
}
}
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 */
@ -1061,4 +919,25 @@ public class FireAlarmService {
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;
}
}

@ -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:serviceBeans>
<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:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
@ -33,8 +36,11 @@
</jaxrs:server>
<!--<bean id="mqttSubscriber" class="org.wso2.carbon.device.mgt.iot.firealarm.api.util.MQTTFirealarmSubscriber" >-->
<!-- -->
<!--</bean>-->
<bean id="mqttSubscriberBean"
class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport.FireAlarmMQTTSubscriber">
</bean>
<bean id="xmppConnectorBean"
class="org.wso2.carbon.device.mgt.iot.sample.firealarm.service.impl.transport.FireAlarmXMPPConnector">
</bean>
</beans>

@ -109,6 +109,13 @@
<scope>provided</scope>
</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-->
<dependency>
@ -334,6 +341,7 @@
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
@ -457,6 +465,7 @@
<commons-httpclient.orbit.version>3.1.0.wso2v2</commons-httpclient.orbit.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>
<!-- Source code -->

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

@ -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,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.LogFactory;
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.iot.common.controlqueue.xmpp.XmppConfig;
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"
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 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>
</beans>

Loading…
Cancel
Save