Few changes to support multi tenancy for virtual fire alarm and android sense

revert-dabc3590
ayyoob 9 years ago
parent 012fc028cf
commit 315177b787

@ -52,7 +52,6 @@ public class RegisterActivity extends Activity {
private EditText mUsernameView;
private EditText mPasswordView;
private EditText mHostView;
private EditText mMqttPortView;
private View mProgressView;
private View mLoginFormView;
private Handler mUiHandler = new Handler();
@ -71,7 +70,6 @@ public class RegisterActivity extends Activity {
mUsernameView = (EditText) findViewById(R.id.username);
mPasswordView = (EditText) findViewById(R.id.password);
mHostView = (EditText) findViewById(R.id.hostname);
mMqttPortView = (EditText) findViewById(R.id.mqttPort);
AvailableSensorsInDevice availableSensorsInDevice = new AvailableSensorsInDevice(getApplicationContext());
availableSensorsInDevice.setContent();
@ -99,7 +97,6 @@ public class RegisterActivity extends Activity {
final String username = mUsernameView.getText().toString();
final String password = mPasswordView.getText().toString();
final String hostname = mHostView.getText().toString();
String mqttPort = mMqttPortView.getText().toString();
boolean cancel = false;
View focusView = null;
@ -124,7 +121,6 @@ public class RegisterActivity extends Activity {
if (cancel) {
focusView.requestFocus();
} else {
final int mqttPortNo= Integer.parseInt(mqttPort);
Thread myThread = new Thread(new Runnable() {
@Override
public void run() {
@ -143,7 +139,6 @@ public class RegisterActivity extends Activity {
LocalRegistry.setEnrolled(getApplicationContext(), true);
LocalRegistry.addUsername(getApplicationContext(), username);
LocalRegistry.addDeviceId(getApplicationContext(), deviceId);
LocalRegistry.addMqttPort(getApplicationContext(), mqttPortNo);
MQTTTransportHandler mqttTransportHandler = AndroidSenseMQTTHandler.getInstance(getApplicationContext());
if (!mqttTransportHandler.isConnected()) {
mqttTransportHandler.connect();

@ -23,14 +23,12 @@ public class SenseConstants {
public final static String TOKEN_ISSUER_CONTEXT = "/oauth2";
public final static String API_APPLICATION_REGISTRATION_CONTEXT = "/api-application-registration";
public static final int MQTT_BROKER_PORT = 1883;
public static final String EVENT_LISTENER_STARTED = "xxStartedxx";
public static final String EVENT_LISTENER_FINISHED = "xxFinishedxx";
public static final String EVENT_LISTENER_ONGOING = "xxOngoingxx";
public final class Request {
public final static String REQUEST_SUCCESSFUL = "200";
public final static String REQUEST_CONFLICT = "409";
public final static int MAX_ATTEMPTS = 2;
}
}

@ -50,6 +50,7 @@ public class DataPublisherService extends Service {
private static String VALUE_TAG = "value";
public static Context context;
@Nullable
@Override
public IBinder onBind(Intent intent) {
@ -125,7 +126,7 @@ public class DataPublisherService extends Service {
}
SenseDataHolder.resetLocationDataHolder();
//retreive words
//retrieve words
ProcessWords.cleanAndPushToWordMap();
List<WordData> wordDatMap = SenseDataHolder.getWordDataHolder();
for (WordData wordData : wordDatMap) {
@ -161,7 +162,9 @@ public class DataPublisherService extends Service {
if (!mqttTransportHandler.isConnected()) {
mqttTransportHandler.connect();
}
mqttTransportHandler.publishDeviceData(user, deviceId, jsonArray.toString());
String topic = "wso2/" + LocalRegistry.getTenantDomain(context) + "/" + SenseConstants
.DEVICE_TYPE + "/" + deviceId + "/data";
mqttTransportHandler.publishDeviceData(user, deviceId, jsonArray.toString(), topic);
}
} catch (JSONException e) {
Log.e(TAG, "Json Data Parsing Exception", e);

@ -26,6 +26,7 @@ import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.MQTTTrans
import org.wso2.carbon.iot.android.sense.data.publisher.mqtt.transport.TransportHandlerException;
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
import org.wso2.carbon.iot.android.sense.speech.detector.util.ProcessWords;
import org.wso2.carbon.iot.android.sense.util.LocalRegistry;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
@ -46,7 +47,7 @@ import java.util.Arrays;
public class AndroidSenseMQTTHandler extends MQTTTransportHandler {
private static final String TAG = "AndroidSenseMQTTHandler";
private static volatile AndroidSenseMQTTHandler mInstance;
private Context context;
/**
* return a sigleton Instance
@ -54,6 +55,7 @@ public class AndroidSenseMQTTHandler extends MQTTTransportHandler {
* @return AndroidSenseMQTTHandler.
*/
public static AndroidSenseMQTTHandler getInstance(Context context) {
context = context;
if (mInstance == null) {
Class clazz = AndroidSenseMQTTHandler.class;
synchronized (clazz) {
@ -169,7 +171,7 @@ public class AndroidSenseMQTTHandler extends MQTTTransportHandler {
String resource = publishData[2];
MqttMessage pushMessage = new MqttMessage();
String publishTopic = "wso2/" + SenseConstants.DEVICE_TYPE + "/" + deviceId + "/data";
String publishTopic = publishData[3];
String actualMessage = resource;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);

@ -77,9 +77,10 @@ public abstract class MQTTTransportHandler implements MqttCallback, TransportHan
String username = LocalRegistry.getUsername(context);
String deviceId = LocalRegistry.getDeviceId(context);
this.clientId = deviceId + ":" + SenseConstants.DEVICE_TYPE;
this.subscribeTopic = "wso2/" + SenseConstants.DEVICE_TYPE + "/" + deviceId + "/command/#";
this.subscribeTopic = "wso2/" + LocalRegistry.getTenantDomain(context)+ "/" + SenseConstants.DEVICE_TYPE + "/" +
deviceId + "/command/#";
this.clientWillTopic = DISCONNECTION_WILL_TOPIC_PREFIX + SenseConstants.DEVICE_TYPE;
this.mqttBrokerEndPoint = "tcp://" + LocalRegistry.getServerHost(context) + ":" + LocalRegistry.getMqttPort(context);
this.mqttBrokerEndPoint = LocalRegistry.getMqttEndpoint(context);
this.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL;
this.initMQTTClient();
setUsernameAndPassword(LocalRegistry.getAccessToken(context), "");

@ -182,7 +182,8 @@ public class ActivitySelectSensor extends AppCompatActivity
LocalRegistry.removeServerURL(getApplicationContext());
LocalRegistry.removeAccessToken(getApplicationContext());
LocalRegistry.removeRefreshToken(getApplicationContext());
LocalRegistry.removeMqttPort(getApplicationContext());
LocalRegistry.removeMqttEndpoint(getApplicationContext());
LocalRegistry.removeTenantDomain(getApplicationContext());
LocalRegistry.setExist(false);
//Stop the current running background services.
stopService(new Intent(this, SenseService.class)); //Stop sensor reading service

@ -34,8 +34,9 @@ public class LocalRegistry {
private static final String SERVER_HOST_KEY = "serverHostKey";
private static final String ACCESS_TOKEN_KEY = "accessTokenKey";
private static final String REFRESH_TOKEN_KEY = "refreshTokenKey";
private static final String MQTT_PORT_KEY = "mqttPort";
private static final String IS_ENROLLED_KEY = "enrolled";
private static final String MQTT_ENDPOINT_KEY = "mqttEndpointKey";
private static final String IS_ENROLLED_KEY = "enrolledKey";
private static final String TENANT_DOMAIN_KEY = "tenantDomainKey";
private static boolean exists = false;
private static String username;
private static String deviceId;
@ -43,8 +44,9 @@ public class LocalRegistry {
private static MQTTTransportHandler mqttTransportHandler;
private static String accessToken;
private static String refreshToken;
private static int mqttPort;
private static String mqttEndpoint;
private static boolean enrolled;
private static String tenantDomain;
public static boolean isExist(Context context) {
if (!exists) {
@ -186,29 +188,29 @@ public class LocalRegistry {
return LocalRegistry.refreshToken;
}
public static void addMqttPort(Context context, int port) {
public static void addMqttEndpoint(Context context, String endpoint) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt(MQTT_PORT_KEY, port);
editor.putString(MQTT_ENDPOINT_KEY, endpoint);
editor.commit();
LocalRegistry.mqttPort = port;
LocalRegistry.mqttEndpoint = endpoint;
}
public static void removeMqttPort(Context context) {
public static void removeMqttEndpoint(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.remove(MQTT_PORT_KEY);
editor.remove(MQTT_ENDPOINT_KEY);
editor.clear();
editor.commit();
LocalRegistry.mqttPort = 0;
LocalRegistry.mqttEndpoint = null;
}
public static int getMqttPort(Context context) {
if (LocalRegistry.mqttPort == 0) {
public static String getMqttEndpoint(Context context) {
if (LocalRegistry.mqttEndpoint == null) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
LocalRegistry.mqttPort = sharedpreferences.getInt(MQTT_PORT_KEY, SenseConstants.MQTT_BROKER_PORT);
LocalRegistry.mqttEndpoint = sharedpreferences.getString(MQTT_ENDPOINT_KEY, "");
}
return LocalRegistry.mqttPort;
return LocalRegistry.mqttEndpoint;
}
public static void setEnrolled(Context context, boolean enrolled) {
@ -227,6 +229,31 @@ public class LocalRegistry {
return LocalRegistry.enrolled;
}
public static void addTenantDomain(Context context, String tenantDomain) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(TENANT_DOMAIN_KEY, tenantDomain);
editor.commit();
LocalRegistry.tenantDomain = tenantDomain;
}
public static void removeTenantDomain(Context context) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.remove(TENANT_DOMAIN_KEY);
editor.clear();
editor.commit();
LocalRegistry.tenantDomain = null;
}
public static String getTenantDomain(Context context) {
if (LocalRegistry.tenantDomain == null) {
SharedPreferences sharedpreferences = context.getSharedPreferences(SENSE_SHARED_PREFERENCES, Context.MODE_PRIVATE);
LocalRegistry.tenantDomain = sharedpreferences.getString(TENANT_DOMAIN_KEY, "");
}
return LocalRegistry.mqttEndpoint;
}
public static String getServerHost(Context context) {
URL url = null;

@ -51,11 +51,7 @@ public class SenseClient {
String responseStatus = response.get("status");
RegisterInfo registerInfo = new RegisterInfo();
if (responseStatus.trim().contains(SenseConstants.Request.REQUEST_SUCCESSFUL)) {
registerInfo.setMsg("Device Registered");
registerInfo.setIsRegistered(true);
return registerInfo;
} else if (responseStatus.trim().contains(SenseConstants.Request.REQUEST_CONFLICT)) {
registerInfo.setMsg("Login Successful");
registerInfo.setMsg("Login Succesful");
registerInfo.setIsRegistered(true);
return registerInfo;
} else {

@ -21,6 +21,7 @@ import android.util.Log;
import org.wso2.carbon.iot.android.sense.constants.SenseConstants;
import org.wso2.carbon.iot.android.sense.util.dto.AccessTokenInfo;
import org.wso2.carbon.iot.android.sense.util.dto.AndroidConfiguration;
import org.wso2.carbon.iot.android.sense.util.dto.AndroidSenseManagerService;
import org.wso2.carbon.iot.android.sense.util.dto.ApiApplicationRegistrationService;
import org.wso2.carbon.iot.android.sense.util.dto.ApiRegistrationProfile;
@ -138,18 +139,16 @@ public class SenseClientAsyncExecutor extends AsyncTask<String, Void, Map<String
.requestInterceptor(new OAuthRequestInterceptor(accessTokenInfo.getAccess_token()))
.contract(new JAXRSContract()).encoder(new JacksonEncoder()).decoder(new JacksonDecoder())
.target(AndroidSenseManagerService.class, endpoint + SenseConstants.REGISTER_CONTEXT);
boolean registered = androidSenseManagerService.register(deviceId, DEVICE_NAME);
if (registered) {
AndroidConfiguration androidConfiguration = androidSenseManagerService.register(deviceId, DEVICE_NAME);
if (androidConfiguration != null) {
LocalRegistry.addAccessToken(context, accessTokenInfo.getAccess_token());
LocalRegistry.addRefreshToken(context, accessTokenInfo.getRefresh_token());
LocalRegistry.addMqttEndpoint(context, androidConfiguration.getMqttEndpoint());
LocalRegistry.addTenantDomain(context, androidConfiguration.getTenantDomain());
}
return responseMap;
} catch (FeignException e) {
responseMap.put(STATUS, "" + e.status());
if (e.status() == 409) {
LocalRegistry.addAccessToken(context, accessTokenInfo.getAccess_token());
LocalRegistry.addRefreshToken(context, accessTokenInfo.getRefresh_token());
}
return responseMap;
}
}

@ -15,19 +15,29 @@
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.iot.android.sense.util.dto;
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
/**
* This holds the required configuration for agent to connect to the server.
*/
public class AndroidConfiguration {
public String tenantDomain;
public String mqttEndpoint;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
public String getTenantDomain() {
return tenantDomain;
}
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
@XmlRootElement
public String getMqttEndpoint() {
return mqttEndpoint;
}
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceData {
@XmlElement(required = true) public String owner;
@XmlElement(required = true) public String deviceId;
@XmlElement public SensorData[] values;
public void setMqttEndpoint(String mqttEndpoint) {
this.mqttEndpoint = mqttEndpoint;
}
}

@ -26,5 +26,5 @@ public interface AndroidSenseManagerService {
@Path("/enrollment/devices/{device_id}")
@POST
boolean register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
AndroidConfiguration register(@PathParam("device_id") String deviceId, @QueryParam("deviceName") String deviceName);
}

@ -14,9 +14,9 @@
android:layout_marginBottom="8dp" android:visibility="gone" />
<ScrollView android:id="@+id/login_form" android:layout_width="match_parent"
android:layout_height="211dp"
android:layout_height="153dp"
android:fillViewport="false"
android:layout_weight="0.07">
>
<LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="vertical">
@ -43,32 +43,14 @@
android:inputType="text"
android:maxLines="1" android:singleLine="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="MQTT Port"
android:id="@+id/textView4"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/hostname"
android:id="@+id/mqttPort"
android:text="1883"
android:inputType="text"
android:maxLines="1"
android:singleLine="true"
/>
</LinearLayout>
</ScrollView>
<Button android:id="@+id/device_register_button" style="?android:textAppearanceSmall"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:text="@string/action_sign_in"
android:textStyle="bold" />
android:textStyle="bold"
android:layout_gravity="center_horizontal"/>
</LinearLayout>

@ -21,17 +21,14 @@ package org.wso2.carbon.device.mgt.iot.androidsense.service.impl;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.DeviceData;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@DeviceType(value = "android_sense")

@ -133,7 +133,7 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
List<SensorRecord> sensorDatas;
if (sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) {
if (!sensor.equals(AndroidSenseConstants.SENSOR_WORDCOUNT)) {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
@ -183,7 +183,7 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
sensorEventTableName = "DEVICE_PRESSURE_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_PROXIMITY:
sensorEventTableName = "DevicePROXIMITYSummaryData";
sensorEventTableName = "DEVICE_PROXIMITY_SUMMARY";
break;
case AndroidSenseConstants.SENSOR_ROTATION:
sensorEventTableName = "DEVICE_ROTATION_SUMMARY";

@ -27,6 +27,11 @@ import org.wso2.carbon.device.mgt.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.AndroidConfiguration;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.Constants;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.device.mgt.iot.util.IoTUtil;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
@ -53,7 +58,15 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
return Response.status(Response.Status.CONFLICT.getStatusCode()).build();
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, IoTUtil.getHostName());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.status(Response.Status.ACCEPTED.getStatusCode()).entity(androidConfiguration.toString())
.build();
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
@ -69,13 +82,23 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser());
return Response.ok(true).build();
AndroidConfiguration androidConfiguration = new AndroidConfiguration();
androidConfiguration.setTenantDomain(APIUtil.getAuthenticatedUserTenantDomain());
String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
if (mqttEndpoint.contains(Constants.LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(Constants.LOCALHOST, IoTUtil.getHostName());
}
androidConfiguration.setMqttEndpoint(mqttEndpoint);
return Response.ok(androidConfiguration.toString()).build();
} else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build();
}
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build();
} catch (IoTException e) {
log.error(e.getMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build();
}
}
@ -146,7 +169,7 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
Device device = APIUtil.getDeviceManagementService().getDevice(deviceIdentifier);
return Response.ok().entity(device).build();
} catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e);

@ -131,7 +131,8 @@ public class AndroidSenseMQTTConnector extends MQTTTransportHandler {
String operation = publishData[1];
String resource = publishData[2];
MqttMessage pushMessage = new MqttMessage();
String publishTopic = "wso2/" + AndroidSenseConstants.DEVICE_TYPE + "/" + deviceId + "/command";
String publishTopic = "wso2/" + APIUtil.getAuthenticatedUserTenantDomain()
+ "/" + AndroidSenseConstants.DEVICE_TYPE + "/" + deviceId + "/command";
if (operation.equals("add")) {
publishTopic = publishTopic + "/words";
} else if (operation.equals("remove")) {

@ -48,6 +48,11 @@ public class APIUtil {
return username;
}
public static String getAuthenticatedUserTenantDomain() {
PrivilegedCarbonContext threadLocalCarbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
return threadLocalCarbonContext.getTenantDomain();
}
public static DeviceManagementProviderService getDeviceManagementService() {
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =

@ -18,44 +18,36 @@
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.json.simple.JSONObject;
import org.wso2.carbon.apimgt.application.extension.constants.ApiApplicationConstants;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
/**
* This stores sensor event data for android sense.
* This holds the required configuration for agent to connect to the server.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class SensorData {
@XmlElement public Long time;
@XmlElement public String key;
@XmlElement public String value;
public class AndroidConfiguration {
public String tenantDomain;
public String mqttEndpoint;
public String getValue() {
return value;
public String getTenantDomain() {
return tenantDomain;
}
public void setValue(String value) {
this.value = value;
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public String getKey() {
return key;
public String getMqttEndpoint() {
return mqttEndpoint;
}
public void setKey(String key) {
this.key = key;
public void setMqttEndpoint(String mqttEndpoint) {
this.mqttEndpoint = mqttEndpoint;
}
public Long getTime() {
return time;
public String toString() {
JSONObject obj = new JSONObject();
obj.put("tenantDomain", tenantDomain);
obj.put("mqttEndpoint", mqttEndpoint);
return obj.toString();
}
public void setTime(Long time) {
this.time = time;
}
}

@ -29,4 +29,5 @@ public class Constants {
public static final String DEFAULT_ROLE_NAME = "android_sense_user";
public static final Permission DEFAULT_PERMISSION[] = new Permission[]{new Permission(Constants.DEFAULT_PERMISSION_RESOURCE,
"ui.execute")};
public static final String LOCALHOST = "localhost";
}

@ -44,8 +44,8 @@
</Permission>
<Permission>
<name>delete words</name>
<path>/device-mgt/android_sense/user</path>
<url>/device/*/words</url>
<path>/device-mgt/android_sense/user</path>
<url>/device/*/words</url>
<method>DELETE</method>
<scope>android_sense_user</scope>
</Permission>

@ -3,7 +3,7 @@
{{/zone}}
<span id="details" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span>
<div id="div-chart" data-backend-api-url = {{backendApiUri}}>
<div id="device-chart" data-backend-api-url = {{backendApiUrl}}>
<div class="chartWrapper" id="chartWrapper-battery">
<span id="span-title">Battery</span>
<div id="y_axis-battery" class="custom_y_axis"></div>

@ -26,7 +26,7 @@ function onRequest(context) {
if (device && device.status != "error") {
return {
"device": device,
"backendApiUri": devicemgtProps["httpsURL"] + "/virtual_firealarm/stats/" + deviceId + "sensors/"
"backendApiUrl": devicemgtProps["httpsURL"] + "/android_sense/stats/" + deviceId + "/sensors/"
};
} else {
response.sendError(404, "Device Id " + deviceId + " of type " + deviceType + " cannot be found!");

@ -30,8 +30,8 @@ function drawGraph(from, to) {
retrieveDataAndDrawMultiLineGraph("gravity", from, to);
}
function retrieveDataAndDrawLineGraph(sensorType, from, to, column) {
var backendApiUrl = $("#div-chart").data("backend-api-url") + sensorType + "?from=" + from + "&to=" + to;
function retrieveDataAndDrawLineGraph(sensorType, from, to) {
var backendApiUrl = $("#device-chart").data("backend-api-url") + sensorType + "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawLineGraph(JSON.parse(data), sensorType);
@ -43,7 +43,7 @@ function retrieveDataAndDrawLineGraph(sensorType, from, to, column) {
}
function retrieveDataAndDrawMultiLineGraph(sensorType, from, to) {
var backendApiUrl = $("#div-chart").data("backend-api-url") + sensorType + "?from=" + from + "&to=" + to;
var backendApiUrl = $("#device-chart").data("backend-api-url") + sensorType + "?from=" + from + "&to=" + to;
var successCallback = function (data) {
if (data) {
drawMultiLineGraph(JSON.parse(data), sensorType);
@ -55,12 +55,13 @@ function retrieveDataAndDrawMultiLineGraph(sensorType, from, to) {
}
function drawLineGraph(data, type) {
var chartWrapperElmId = "#div-chart";
var chartWrapperElmId = "#device-chart";
var graphWidth = $(chartWrapperElmId).width() - 50;
if (data.length == 0 || data.length == undefined) {
$("#chart" + type).html("<br/>No data available...");
$("#chart-" + type).html("<br/>No data available...");
return;
}
$("#chart-" + type).empty();
var graphConfig = {
element: document.getElementById("chart-" + type),
@ -108,17 +109,12 @@ function drawLineGraph(data, type) {
{
'color': palette.color(),
'data': chartData,
'name': $("#details").data("devicename"),
'name': type,
'scale': d3.scale.linear().domain([Math.min(min, min_val), Math.max(max, max_val)])
.nice()
}
);
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var graph = new Rickshaw.Graph(graphConfig);
graph.render();
@ -179,12 +175,13 @@ function drawLineGraph(data, type) {
function drawMultiLineGraph(data, type) {
var chartWrapperElmId = "#div-chart";
var chartWrapperElmId = "#device-chart";
var graphWidth = $(chartWrapperElmId).width() - 50;
if (data.length == 0 || data.length == undefined) {
$("#chart-" + type).html("<br/>No data available...");
return;
}
$("#chart-" + type).empty();
var graphConfig = {
element: document.getElementById("chart-" + type),
@ -256,38 +253,27 @@ function drawMultiLineGraph(data, type) {
y: parseInt(data[i].values.z)
});
}
if (range_max < max_val) {
range_max = max_val;
}
if (range_min > min_val) {
range_min = min_val;
}
graphConfig['series'].push(
{
'color': palette.color(),
'data': chartDataX,
'name': $("#details").data("devicename"),
'name': "x",
'scale': d3.scale.linear().domain([Math.min(min, min_valX), Math.max(max, max_valX)]).nice()
},
{
'color': palette.color(),
'data': chartDataY,
'name': $("#details").data("devicename"),
'name': "y",
'scale': d3.scale.linear().domain([Math.min(min, min_valY), Math.max(max, max_valY)]).nice()
},
{
'color': palette.color(),
'data': chartDataZ,
'name': $("#details").data("devicename"),
'name': "z",
'scale': d3.scale.linear().domain([Math.min(min, min_valZ), Math.max(max, max_valZ)]).nice()
}
);
if (graphConfig['series'].length == 0) {
$(chartWrapperElmId).html("No data available...");
return;
}
var graph = new Rickshaw.Graph(graphConfig);
graph.render();
@ -298,25 +284,21 @@ function drawMultiLineGraph(data, type) {
xAxis.render();
var yAxis = new Rickshaw.Graph.Axis.Y.Scaled({
var yAxis = new Rickshaw.Graph.Axis.Y({
graph: graph,
orientation: 'left',
element: document.getElementById("y_axis-type"),
width: 40,
height: 410,
'scale': d3.scale.linear().domain([Math.min(min, range_min), Math.max(max, range_max)]).nice()
element: document.getElementById("y_axis-" + type)
});
yAxis.render();
var slider = new Rickshaw.Graph.RangeSlider.Preview({
graph: graph,
element: document.getElementById("slider-type")
element: document.getElementById("slider-" + type)
});
var legend = new Rickshaw.Graph.Legend({
graph: graph,
element: document.getElementById('legend-type')
element: document.getElementById('legend-' + type)
});
var hoverDetail = new Rickshaw.Graph.HoverDetail({

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

@ -82,7 +82,7 @@ function submitForm(formId) {
} else if (httpMethod == "PUT") {
invokerUtil.put(uri, payload, successCallBack, errorCallBack, contentType);
} else if (httpMethod == "DELETE") {
invokerUtil.get(uri, successCallBack, errorCallBack, contentType);
invokerUtil.delete(uri, successCallBack, errorCallBack, contentType);
} else {
title.html("An Error Occurred!");
statusIcon.attr("class", defaultStatusClasses + " fw-error");

@ -1,43 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.sensormgt;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
@XmlRootElement
public class DeviceRecord implements Serializable {
private Map<String, SensorRecord> sensorDataList = new HashMap<>();
public DeviceRecord(String sensorName, String sensorValue, long time) {
sensorDataList.put(sensorName, new SensorRecord(sensorValue, time));
}
@XmlElement
public Map<String, SensorRecord> getSensorDataList() {
return sensorDataList;
}
public void addDeviceRecord(String sensorName, String sensorValue, long time) {
sensorDataList.put(sensorName, new SensorRecord(sensorValue, time));
}
}

@ -1,137 +0,0 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.sensormgt;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* This class is used to store latest sensor value readings against a device id in an in-memory map.
*/
public class SensorDataManager {
private static final SensorDataManager instance = new SensorDataManager();
private Map<String, DeviceRecord> deviceMap = new HashMap<>();
private SensorDataManager() {
}
public static SensorDataManager getInstance() {
return instance;
}
/**
* Store sensor record in a map.
*
* @param deviceId
* @param sensorName
* @param sensorValue
* @param time
* @return if success returns true
*/
public boolean setSensorRecord(String deviceId, String sensorName, String sensorValue, long time) {
DeviceRecord deviceRecord = deviceMap.get(deviceId);
if (deviceRecord == null) {
deviceRecord = new DeviceRecord(sensorName, sensorValue, time);
} else {
deviceRecord.addDeviceRecord(sensorName, sensorValue, time);
}
deviceMap.put(deviceId, deviceRecord);
return true;
}
/**
* Returns last updated sensor records list for a device
*
* @param deviceId
* @return list of sensor records
*/
public SensorRecord[] getSensorRecords(String deviceId) throws DeviceControllerException {
DeviceRecord deviceRecord = deviceMap.get(deviceId);
if (deviceRecord != null) {
Collection<SensorRecord> list = deviceRecord.getSensorDataList().values();
return list.toArray(new SensorRecord[list.size()]);
}
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
}
/**
* Returns last updated sensor record for a device's sensor
*
* @param deviceId
* @param sensorName
* @return sensor record
*/
public SensorRecord getSensorRecord(String deviceId, String sensorName) throws
DeviceControllerException {
DeviceRecord deviceRecord = deviceMap.get(deviceId);
if (deviceRecord != null) {
SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName);
if (sensorRecord != null) {
return sensorRecord;
}
throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId +
" Sensor Name: " + sensorName);
}
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
}
/**
* Returns last updated sensor value for a device's sensor
*
* @param deviceId
* @param sensorName
* @return sensor reading
*/
public String getSensorRecordValue(String deviceId, String sensorName) throws DeviceControllerException {
DeviceRecord deviceRecord = deviceMap.get(deviceId);
if (deviceRecord != null) {
SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName);
if (sensorRecord != null) {
return sensorRecord.getSensorValue();
}
throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId +
" Sensor Name: " + sensorName);
}
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
}
/**
* Returns last updated sensor value reading time for a device's sensor
*
* @param deviceId
* @param sensorName
* @return time in millis
*/
public long getSensorRecordTime(String deviceId, String sensorName) throws DeviceControllerException {
DeviceRecord deviceRecord = deviceMap.get(deviceId);
if (deviceRecord != null) {
SensorRecord sensorRecord = deviceRecord.getSensorDataList().get(sensorName);
if (sensorRecord != null) {
return sensorRecord.getTime();
}
throw new DeviceControllerException("Error: No records found for the Device ID: " + deviceId +
" Sensor Name: " + sensorName);
}
throw new DeviceControllerException("Error: No records found for the device ID: " + deviceId);
}
}

@ -1,46 +0,0 @@
/*
* Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.sensormgt;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.io.Serializable;
@XmlRootElement
public class SensorRecord implements Serializable {
//sensor value float, int, boolean all should be converted into string
private String sensorValue;
private long time;
public SensorRecord(String sensorValue, long time) {
this.sensorValue = sensorValue;
this.time = time;
}
@XmlElement
public String getSensorValue() {
return sensorValue;
}
@XmlElement
public long getTime() {
return time;
}
}

@ -106,7 +106,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
final AgentManager agentManager = AgentManager.getInstance();
String serverName = agentManager.getAgentConfigs().getServerName();
String tenantDomain = agentManager.getAgentConfigs().getTenantDomain();
String deviceOwner = agentManager.getAgentConfigs().getDeviceOwner();
String deviceID = agentManager.getAgentConfigs().getDeviceId();
String receivedMessage;
@ -143,7 +143,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
String replyTemperature = "Current temperature was read as: '" + currentTemperature + "C'";
log.info(AgentConstants.LOG_APPENDER + replyTemperature);
String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, deviceID);
String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, tenantDomain, deviceID);
replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
@ -157,7 +157,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
log.info(AgentConstants.LOG_APPENDER + replyHumidity);
String humidPublishTopic = String.format(
AgentConstants.MQTT_PUBLISH_TOPIC, deviceID);
AgentConstants.MQTT_PUBLISH_TOPIC,tenantDomain, deviceID);
replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity;
securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
@ -202,6 +202,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
pushMessage.setRetained(false);
String topic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC,
agentManager.getAgentConfigs().getTenantDomain(),
agentManager.getAgentConfigs().getDeviceId());
publishToQueue(topic, pushMessage);

@ -71,7 +71,7 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
resource = agentManager.getAgentConfigs().getDeviceOwner();
xmppDeviceJID = username + "@" + server;
xmppAdminJID = agentManager.getAgentConfigs().getServerName() + "_" + AgentConstants.DEVICE_TYPE + "@" + server;
xmppAdminJID = "wso2_" + AgentConstants.DEVICE_TYPE + "@" + server;
Runnable connect = new Runnable() {

@ -24,7 +24,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core;
* downloading the device agent from the IoT-Server.
*/
public class AgentConfiguration {
private String serverName;
private String tenantDomain;
private String deviceOwner;
private String deviceId;
private String deviceName;
@ -40,12 +40,12 @@ public class AgentConfiguration {
private String refreshToken;
private int dataPushInterval;
public String getServerName() {
return serverName;
public String getTenantDomain() {
return tenantDomain;
}
public void setServerName(String serverName) {
this.serverName = serverName;
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public String getDeviceOwner() {

@ -57,8 +57,8 @@ public class AgentConstants {
--------------------------------------------------------------------------------------- */
public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0;
public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "wso2/" + DEVICE_TYPE + "/%s/publisher";
public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s/publisher";
/* ---------------------------------------------------------------------------------------
XMPP Connection specific information
--------------------------------------------------------------------------------------- */
@ -67,7 +67,7 @@ public class AgentConstants {
Device/Agent specific properties to be read from the 'deviceConfig.properties' file
--------------------------------------------------------------------------------------- */
public static final String AGENT_PROPERTIES_FILE_NAME = "deviceConfig.properties";
public static final String SERVER_NAME_PROPERTY = "server-name";
public static final String TENANT_DOMAIN = "tenantDomain";
public static final String DEVICE_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String DEVICE_NAME_PROPERTY = "device-name";

@ -133,7 +133,8 @@ public class AgentManager {
log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() +
", provided in the configuration file is invalid.");
}
String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, agentConfigs.getDeviceId());
String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, agentConfigs.getTenantDomain(),
agentConfigs.getDeviceId());
// TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator();
TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(),

@ -47,7 +47,6 @@ public class AgentUtilOperations {
private static final String JSON_MESSAGE_KEY = "Msg";
private static final String JSON_SIGNATURE_KEY = "Sig";
private static final String JSON_SERIAL_KEY = "SerialNumber";
private static final String JSON_TENANT_KEY = "Tenant";
/**
* This method reads the agent specific configurations for the device from the
@ -81,8 +80,8 @@ public class AgentUtilOperations {
//load a properties file from class path, inside static method
properties.load(propertiesInputStream);
iotServerConfigs.setServerName(properties.getProperty(
AgentConstants.SERVER_NAME_PROPERTY));
iotServerConfigs.setTenantDomain(properties.getProperty(
AgentConstants.TENANT_DOMAIN));
iotServerConfigs.setDeviceOwner(properties.getProperty(
AgentConstants.DEVICE_OWNER_PROPERTY));
iotServerConfigs.setDeviceId(properties.getProperty(
@ -112,8 +111,8 @@ public class AgentUtilOperations {
iotServerConfigs.setDataPushInterval(Integer.parseInt(properties.getProperty(
AgentConstants.PUSH_INTERVAL_PROPERTY)));
log.info(AgentConstants.LOG_APPENDER + "Server name: " +
iotServerConfigs.getServerName());
log.info(AgentConstants.LOG_APPENDER + "Tenant Domain: " +
iotServerConfigs.getTenantDomain());
log.info(AgentConstants.LOG_APPENDER + "Device Owner: " +
iotServerConfigs.getDeviceOwner());
log.info(AgentConstants.LOG_APPENDER + "Device ID: " + iotServerConfigs.getDeviceId());
@ -251,7 +250,6 @@ public class AgentUtilOperations {
jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload);
//below statements are temporary fix.
jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber());
jsonPayload.put(JSON_TENANT_KEY, "carbon.super");
return jsonPayload.toString();
}

@ -227,7 +227,7 @@ public class EnrollmentManager {
private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException {
// Build the CN for the cert that's being requested.
X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE);
nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getServerName());
nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getTenantDomain());
nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId());

@ -104,7 +104,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) {
final AgentManager agentManager = AgentManager.getInstance();
String serverName = agentManager.getAgentConfigs().getServerName();
String tenantDomain = agentManager.getAgentConfigs().getTenantDomain();
String deviceOwner = agentManager.getAgentConfigs().getDeviceOwner();
String deviceID = agentManager.getAgentConfigs().getDeviceId();
String receivedMessage;
@ -137,7 +137,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
String replyTemperature = "Current temperature was read as: '" + currentTemperature + "C'";
log.info(AgentConstants.LOG_APPENDER + replyTemperature);
String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, deviceID);
String tempPublishTopic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC, tenantDomain, deviceID);
replyMessage = AgentConstants.TEMPERATURE_CONTROL + ":" + currentTemperature;
securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
@ -151,7 +151,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
log.info(AgentConstants.LOG_APPENDER + replyHumidity);
String humidPublishTopic = String.format(
AgentConstants.MQTT_PUBLISH_TOPIC, deviceID);
AgentConstants.MQTT_PUBLISH_TOPIC, tenantDomain, deviceID);
replyMessage = AgentConstants.HUMIDITY_CONTROL + ":" + currentHumidity;
securePayLoad = AgentUtilOperations.prepareSecurePayLoad(replyMessage);
@ -192,6 +192,7 @@ public class FireAlarmMQTTCommunicator extends MQTTTransportHandler {
pushMessage.setRetained(false);
String topic = String.format(AgentConstants.MQTT_PUBLISH_TOPIC,
agentManager.getAgentConfigs().getTenantDomain(),
agentManager.getAgentConfigs().getDeviceId());
publishToQueue(topic, pushMessage);

@ -71,7 +71,7 @@ public class FireAlarmXMPPCommunicator extends XMPPTransportHandler {
resource = agentManager.getAgentConfigs().getDeviceOwner();
xmppDeviceJID = username + "@" + server;
xmppAdminJID = agentManager.getAgentConfigs().getServerName() + "_" + AgentConstants.DEVICE_TYPE + "@" + server;
xmppAdminJID = "wso2_" + AgentConstants.DEVICE_TYPE + "@" + server;
Runnable connect = new Runnable() {

@ -24,7 +24,7 @@ package org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.core;
* downloading the device agent from the IoT-Server.
*/
public class AgentConfiguration {
private String serverName;
private String tenantDomain;
private String deviceOwner;
private String deviceId;
private String deviceName;
@ -40,12 +40,12 @@ public class AgentConfiguration {
private String refreshToken;
private int dataPushInterval;
public String getServerName() {
return serverName;
public String getTenantDomain() {
return tenantDomain;
}
public void setServerName(String serverName) {
this.serverName = serverName;
public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
public String getDeviceOwner() {

@ -56,8 +56,8 @@ public class AgentConstants {
--------------------------------------------------------------------------------------- */
public static final int DEFAULT_MQTT_RECONNECTION_INTERVAL = 2; // time in seconds
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0;
public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "wso2/" + DEVICE_TYPE + "/%s/publisher";
public static final String MQTT_SUBSCRIBE_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s/publisher";
/* ---------------------------------------------------------------------------------------
XMPP Connection specific information
--------------------------------------------------------------------------------------- */
@ -66,7 +66,7 @@ public class AgentConstants {
Device/Agent specific properties to be read from the 'deviceConfig.properties' file
--------------------------------------------------------------------------------------- */
public static final String AGENT_PROPERTIES_FILE_NAME = "deviceConfig.properties";
public static final String SERVER_NAME_PROPERTY = "server-name";
public static final String TENANT_DOMAIN = "tenantDomain";
public static final String DEVICE_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String DEVICE_NAME_PROPERTY = "device-name";

@ -121,7 +121,8 @@ public class AgentManager {
log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() +
", provided in the configuration file is invalid.");
}
String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, agentConfigs.getDeviceId());
String mqttTopic = String.format(AgentConstants.MQTT_SUBSCRIBE_TOPIC, agentConfigs.getTenantDomain(),
agentConfigs.getDeviceId());
// TransportHandler httpCommunicator = new FireAlarmHTTPCommunicator();
TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(),

@ -51,7 +51,6 @@ public class AgentUtilOperations {
private static final String JSON_MESSAGE_KEY = "Msg";
private static final String JSON_SIGNATURE_KEY = "Sig";
private static final String JSON_SERIAL_KEY = "SerialNumber";
private static final String JSON_TENANT_KEY = "Tenant";
/**
* This method reads the agent specific configurations for the device from the
@ -85,8 +84,8 @@ public class AgentUtilOperations {
//load a properties file from class path, inside static method
properties.load(propertiesInputStream);
iotServerConfigs.setServerName(properties.getProperty(
AgentConstants.SERVER_NAME_PROPERTY));
iotServerConfigs.setTenantDomain(properties.getProperty(
AgentConstants.TENANT_DOMAIN));
iotServerConfigs.setDeviceOwner(properties.getProperty(
AgentConstants.DEVICE_OWNER_PROPERTY));
iotServerConfigs.setDeviceId(properties.getProperty(
@ -116,8 +115,8 @@ public class AgentUtilOperations {
iotServerConfigs.setDataPushInterval(Integer.parseInt(properties.getProperty(
AgentConstants.PUSH_INTERVAL_PROPERTY)));
log.info(AgentConstants.LOG_APPENDER + "Server name: " +
iotServerConfigs.getServerName());
log.info(AgentConstants.LOG_APPENDER + "Tenant Domain: " +
iotServerConfigs.getTenantDomain());
log.info(AgentConstants.LOG_APPENDER + "Device Owner: " +
iotServerConfigs.getDeviceOwner());
log.info(AgentConstants.LOG_APPENDER + "Device ID: " + iotServerConfigs.getDeviceId());
@ -224,7 +223,6 @@ public class AgentUtilOperations {
jsonPayload.put(JSON_SIGNATURE_KEY, signedPayload);
//below statements are temporary fix.
jsonPayload.put(JSON_SERIAL_KEY, EnrollmentManager.getInstance().getSCEPCertificate().getSerialNumber());
jsonPayload.put(JSON_TENANT_KEY, "carbon.super");
return jsonPayload.toString();
}

@ -227,7 +227,7 @@ public class EnrollmentManager {
private PKCS10CertificationRequest generateCertSignRequest() throws AgentCoreOperationException {
// Build the CN for the cert that's being requested.
X500NameBuilder nameBld = new X500NameBuilder(BCStyle.INSTANCE);
nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getServerName());
nameBld.addRDN(BCStyle.CN, AgentManager.getInstance().getAgentConfigs().getTenantDomain());
nameBld.addRDN(BCStyle.O, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
nameBld.addRDN(BCStyle.OU, AgentManager.getInstance().getAgentConfigs().getDeviceOwner());
nameBld.addRDN(BCStyle.UNIQUE_IDENTIFIER, AgentManager.getInstance().getAgentConfigs().getDeviceId());

@ -35,9 +35,9 @@ import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipUtil;
import org.wso2.carbon.identity.jwt.client.extension.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;

@ -69,7 +69,7 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(VirtualFireAlarmMQTTConnector.class);
// subscription topic: <SERVER_NAME>/+/virtual_firealarm/+/publisher
// wildcard (+) is in place for device_owner & device_id
private static String subscribeTopic = "wso2/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/+/publisher";
private static String subscribeTopic = "wso2/+/"+ VirtualFireAlarmConstants.DEVICE_TYPE + "/+/publisher";
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private static final String KEY_TYPE = "PRODUCTION";
private static final String EMPTY_STRING = "";
@ -155,14 +155,14 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler {
// <Topic> = [ServerName/Owner/DeviceType/DeviceId/"publisher"]
String topic = messageParams[0];
String[] topicParams = topic.split("/");
String deviceId = topicParams[2];
String tenantDomain = topicParams[1];
String deviceId = topicParams[3];
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [DEVICE.ID-" + deviceId + "]");
}
JSONObject jsonPayload = new JSONObject(mqttMessage.toString());
String actualMessage;
try {
String tenantDomain = (String) jsonPayload.get(JSON_TENANT_KEY);
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
DeviceManagementProviderService deviceManagementProviderService =
@ -240,7 +240,8 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler {
String state = publishData[2];
MqttMessage pushMessage = new MqttMessage();
String publishTopic = "wso2/" + VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;
String publishTopic = "wso2/" + APIUtil.getTenantDomainOftheUser() + "/"
+ VirtualFireAlarmConstants.DEVICE_TYPE + "/" + deviceId;
try {
PrivateKey serverPrivateKey = SecurityManager.getServerPrivateKey();

@ -0,0 +1,97 @@
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.exception.IoTException;
import org.wso2.carbon.device.mgt.iot.util.IoTUtil;
import org.wso2.carbon.device.mgt.iot.util.IotDeviceManagementUtil;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.utils.CarbonUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
/**
* This is used to create a zip file that includes the necessary configuration required for the agent.
*/
public class ZipUtil {
private static final String HTTPS_PORT_PROPERTY = "httpsPort";
private static final String HTTP_PORT_PROPERTY = "httpPort";
private static final String LOCALHOST = "localhost";
private static final String HTTPS_PROTOCOL_APPENDER = "https://";
private static final String HTTP_PROTOCOL_APPENDER = "http://";
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType,
String deviceId, String deviceName, String token,
String refreshToken) throws DeviceManagementException {
String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" +
File.separator + deviceId;
String templateSketchPath = sketchFolder + File.separator + deviceType;
String iotServerIP;
try {
iotServerIP = IoTUtil.getHostName();
String httpsServerPort = System.getProperty(HTTPS_PORT_PROPERTY);
String httpServerPort = System.getProperty(HTTP_PORT_PROPERTY);
String httpsServerEP = HTTPS_PROTOCOL_APPENDER + iotServerIP + ":" + httpsServerPort;
String httpServerEP = HTTP_PROTOCOL_APPENDER + iotServerIP + ":" + httpServerPort;
String apimEndpoint = httpsServerEP;
String mqttEndpoint = MqttConfig.getInstance().getMqttQueueEndpoint();
if (mqttEndpoint.contains(LOCALHOST)) {
mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
}
String xmppEndpoint = XmppConfig.getInstance().getXmppEndpoint();
int indexOfChar = xmppEndpoint.lastIndexOf(":");
if (indexOfChar != -1) {
xmppEndpoint = xmppEndpoint.substring(0, indexOfChar);
}
xmppEndpoint = xmppEndpoint + ":" + XmppConfig.getInstance().getSERVER_CONNECTION_PORT();
Map<String, String> contextParams = new HashMap<>();
contextParams.put("TENANT_DOMAIN", APIUtil.getTenantDomainOftheUser());
contextParams.put("DEVICE_OWNER", owner);
contextParams.put("DEVICE_ID", deviceId);
contextParams.put("DEVICE_NAME", deviceName);
contextParams.put("HTTPS_EP", httpsServerEP);
contextParams.put("HTTP_EP", httpServerEP);
contextParams.put("APIM_EP", apimEndpoint);
contextParams.put("MQTT_EP", mqttEndpoint);
contextParams.put("XMPP_EP", xmppEndpoint);
contextParams.put("DEVICE_TOKEN", token);
contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
ZipArchive zipFile;
zipFile = IotDeviceManagementUtil.getSketchArchive(archivesPath, templateSketchPath, contextParams);
return zipFile;
} catch (IoTException e) {
throw new DeviceManagementException(e.getMessage());
} catch (IOException e) {
throw new DeviceManagementException("Zip File Creation Failed", e);
}
}
}

@ -38,7 +38,7 @@ function drawLineGraph(data) {
$("#chart").html("<br/>No data available...");
return;
}
$("#chart").empty();
var graphConfig = {
element: document.getElementById("chart"),
width: graphWidth,

@ -16,7 +16,7 @@
#
#[Device-Configurations]
server-name=${SERVER_NAME}
tenantDomain=${TENANT_DOMAIN}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}

@ -16,7 +16,7 @@
#
#[Device-Configurations]
server-name=${SERVER_NAME}
tenantDomain=${TENANT_DOMAIN}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}

Loading…
Cancel
Save