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

This commit is contained in:
ayyoob 2016-04-28 22:21:08 +05:30
parent 012fc028cf
commit 315177b787
49 changed files with 308 additions and 421 deletions

View File

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

View File

@ -23,14 +23,12 @@ public class SenseConstants {
public final static String TOKEN_ISSUER_CONTEXT = "/oauth2"; public final static String TOKEN_ISSUER_CONTEXT = "/oauth2";
public final static String API_APPLICATION_REGISTRATION_CONTEXT = "/api-application-registration"; 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_STARTED = "xxStartedxx";
public static final String EVENT_LISTENER_FINISHED = "xxFinishedxx"; public static final String EVENT_LISTENER_FINISHED = "xxFinishedxx";
public static final String EVENT_LISTENER_ONGOING = "xxOngoingxx"; public static final String EVENT_LISTENER_ONGOING = "xxOngoingxx";
public final class Request { public final class Request {
public final static String REQUEST_SUCCESSFUL = "200"; public final static String REQUEST_SUCCESSFUL = "200";
public final static String REQUEST_CONFLICT = "409";
public final static int MAX_ATTEMPTS = 2; public final static int MAX_ATTEMPTS = 2;
} }
} }

View File

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

View File

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

View File

@ -77,9 +77,10 @@ public abstract class MQTTTransportHandler implements MqttCallback, TransportHan
String username = LocalRegistry.getUsername(context); String username = LocalRegistry.getUsername(context);
String deviceId = LocalRegistry.getDeviceId(context); String deviceId = LocalRegistry.getDeviceId(context);
this.clientId = deviceId + ":" + SenseConstants.DEVICE_TYPE; 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.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.timeoutInterval = DEFAULT_TIMEOUT_INTERVAL;
this.initMQTTClient(); this.initMQTTClient();
setUsernameAndPassword(LocalRegistry.getAccessToken(context), ""); setUsernameAndPassword(LocalRegistry.getAccessToken(context), "");

View File

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

View File

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

View File

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

View File

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

View File

@ -15,19 +15,29 @@
* specific language governing permissions and limitations * specific language governing permissions and limitations
* under the License. * 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 {
import org.codehaus.jackson.annotate.JsonIgnoreProperties; public String tenantDomain;
public String mqttEndpoint;
import javax.xml.bind.annotation.XmlElement; public String getTenantDomain() {
import javax.xml.bind.annotation.XmlRootElement; return tenantDomain;
}
@XmlRootElement public void setTenantDomain(String tenantDomain) {
this.tenantDomain = tenantDomain;
}
@JsonIgnoreProperties(ignoreUnknown = true) public String getMqttEndpoint() {
public class DeviceData { return mqttEndpoint;
@XmlElement(required = true) public String owner; }
@XmlElement(required = true) public String deviceId;
@XmlElement public SensorData[] values; public void setMqttEndpoint(String mqttEndpoint) {
this.mqttEndpoint = mqttEndpoint;
}
} }

View File

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

View File

@ -14,9 +14,9 @@
android:layout_marginBottom="8dp" android:visibility="gone" /> android:layout_marginBottom="8dp" android:visibility="gone" />
<ScrollView android:id="@+id/login_form" android:layout_width="match_parent" <ScrollView android:id="@+id/login_form" android:layout_width="match_parent"
android:layout_height="211dp" android:layout_height="153dp"
android:fillViewport="false" android:fillViewport="false"
android:layout_weight="0.07"> >
<LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent" <LinearLayout android:id="@+id/email_login_form" android:layout_width="match_parent"
android:layout_height="wrap_content" android:orientation="vertical"> android:layout_height="wrap_content" android:orientation="vertical">
@ -43,32 +43,14 @@
android:inputType="text" android:inputType="text"
android:maxLines="1" android:singleLine="true"/> 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> </LinearLayout>
</ScrollView> </ScrollView>
<Button android:id="@+id/device_register_button" style="?android:textAppearanceSmall" <Button android:id="@+id/device_register_button" style="?android:textAppearanceSmall"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_marginTop="16dp" android:text="@string/action_sign_in" android:layout_marginTop="16dp" android:text="@string/action_sign_in"
android:textStyle="bold" /> android:textStyle="bold"
android:layout_gravity="center_horizontal"/>
</LinearLayout> </LinearLayout>

View File

@ -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.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.DeviceType;
import org.wso2.carbon.device.mgt.extensions.feature.mgt.annotations.Feature; 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.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET; import javax.ws.rs.GET;
import javax.ws.rs.POST; import javax.ws.rs.POST;
import javax.ws.rs.Path; import javax.ws.rs.Path;
import javax.ws.rs.PathParam; import javax.ws.rs.PathParam;
import javax.ws.rs.Produces; import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam; import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response; import javax.ws.rs.core.Response;
@DeviceType(value = "android_sense") @DeviceType(value = "android_sense")

View File

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

View File

@ -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.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.androidsense.plugin.constants.AndroidSenseConstants; import org.wso2.carbon.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.Consumes;
import javax.ws.rs.DELETE; import javax.ws.rs.DELETE;
@ -53,7 +58,15 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try { try {
if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) { 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 device = new Device();
device.setDeviceIdentifier(deviceId); device.setDeviceIdentifier(deviceId);
@ -69,13 +82,23 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
boolean added = APIUtil.getDeviceManagementService().enrollDevice(device); boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
if (added) { if (added) {
APIUtil.registerApiAccessRoles(APIUtil.getAuthenticatedUser()); 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 { } else {
return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build(); return Response.status(Response.Status.NOT_ACCEPTABLE.getStatusCode()).entity(false).build();
} }
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e); log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(false).build(); 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)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); 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(); return Response.ok().entity(device).build();
} catch (DeviceManagementException e) { } catch (DeviceManagementException e) {
log.error(e.getErrorMessage(), e); log.error(e.getErrorMessage(), e);

View File

@ -131,7 +131,8 @@ public class AndroidSenseMQTTConnector extends MQTTTransportHandler {
String operation = publishData[1]; String operation = publishData[1];
String resource = publishData[2]; String resource = publishData[2];
MqttMessage pushMessage = new MqttMessage(); 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")) { if (operation.equals("add")) {
publishTopic = publishTopic + "/words"; publishTopic = publishTopic + "/words";
} else if (operation.equals("remove")) { } else if (operation.equals("remove")) {

View File

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

View File

@ -18,44 +18,36 @@
package org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util; 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 AndroidConfiguration {
public class SensorData { public String tenantDomain;
public String mqttEndpoint;
@XmlElement public Long time; public String getTenantDomain() {
@XmlElement public String key; return tenantDomain;
@XmlElement public String value;
public String getValue() {
return value;
} }
public void setValue(String value) { public void setTenantDomain(String tenantDomain) {
this.value = value; this.tenantDomain = tenantDomain;
} }
public String getKey() { public String getMqttEndpoint() {
return key; return mqttEndpoint;
} }
public void setKey(String key) { public void setMqttEndpoint(String mqttEndpoint) {
this.key = key; this.mqttEndpoint = mqttEndpoint;
} }
public Long getTime() { public String toString() {
return time; JSONObject obj = new JSONObject();
obj.put("tenantDomain", tenantDomain);
obj.put("mqttEndpoint", mqttEndpoint);
return obj.toString();
} }
public void setTime(Long time) {
this.time = time;
}
} }

View File

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

View File

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

View File

@ -3,7 +3,7 @@
{{/zone}} {{/zone}}
<span id="details" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}" <span id="details" data-devicename="{{device.name}}" data-deviceid="{{device.deviceIdentifier}}"
data-appcontext="{{@app.context}}"></span> 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"> <div class="chartWrapper" id="chartWrapper-battery">
<span id="span-title">Battery</span> <span id="span-title">Battery</span>
<div id="y_axis-battery" class="custom_y_axis"></div> <div id="y_axis-battery" class="custom_y_axis"></div>

View File

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

View File

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

View File

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

View File

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

View File

@ -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));
}
}

View File

@ -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);
}
}

View File

@ -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;
}
}

View File

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

View File

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

View File

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

View File

@ -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_RECONNECTION_INTERVAL = 2; // time in seconds
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; 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_SUBSCRIBE_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "wso2/" + DEVICE_TYPE + "/%s/publisher"; public static final String MQTT_PUBLISH_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s/publisher";
/* --------------------------------------------------------------------------------------- /* ---------------------------------------------------------------------------------------
XMPP Connection specific information XMPP Connection specific information
--------------------------------------------------------------------------------------- */ --------------------------------------------------------------------------------------- */
@ -67,7 +67,7 @@ public class AgentConstants {
Device/Agent specific properties to be read from the 'deviceConfig.properties' file 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 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_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId"; public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String DEVICE_NAME_PROPERTY = "device-name"; public static final String DEVICE_NAME_PROPERTY = "device-name";

View File

@ -133,7 +133,8 @@ public class AgentManager {
log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() + log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() +
", provided in the configuration file is invalid."); ", 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 httpCommunicator = new FireAlarmHTTPCommunicator();
TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(), TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(),

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -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_RECONNECTION_INTERVAL = 2; // time in seconds
public static final int DEFAULT_MQTT_QUALITY_OF_SERVICE = 0; 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_SUBSCRIBE_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s";
public static final String MQTT_PUBLISH_TOPIC = "wso2/" + DEVICE_TYPE + "/%s/publisher"; public static final String MQTT_PUBLISH_TOPIC = "wso2/%s/" + DEVICE_TYPE + "/%s/publisher";
/* --------------------------------------------------------------------------------------- /* ---------------------------------------------------------------------------------------
XMPP Connection specific information XMPP Connection specific information
--------------------------------------------------------------------------------------- */ --------------------------------------------------------------------------------------- */
@ -66,7 +66,7 @@ public class AgentConstants {
Device/Agent specific properties to be read from the 'deviceConfig.properties' file 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 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_OWNER_PROPERTY = "owner";
public static final String DEVICE_ID_PROPERTY = "deviceId"; public static final String DEVICE_ID_PROPERTY = "deviceId";
public static final String DEVICE_NAME_PROPERTY = "device-name"; public static final String DEVICE_NAME_PROPERTY = "device-name";

View File

@ -121,7 +121,8 @@ public class AgentManager {
log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() + log.error("XMPP Endpoint String - " + agentConfigs.getXmppServerEndpoint() +
", provided in the configuration file is invalid."); ", 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 httpCommunicator = new FireAlarmHTTPCommunicator();
TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(), TransportHandler mqttCommunicator = new FireAlarmMQTTCommunicator(agentConfigs.getDeviceOwner(),

View File

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

View File

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

View File

@ -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.controlqueue.xmpp.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException; 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.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.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants; 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.JWTClient;
import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo; import org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo;
import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException; import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientException;

View File

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

View File

@ -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);
}
}
}

View File

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

View File

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

View File

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