hasuniea 9 years ago
commit feadc7d3ae

@ -23,8 +23,8 @@
<property name="username">admin</property> <property name="username">admin</property>
<property name="contentValidationParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:3</property> <property name="contentValidationParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:3</property>
<property name="contentValidation">default</property> <property name="contentValidation">default</property>
<property name="dcrUrl">https://localhost:9443/dynamic-client-web/register</property> <property name="dcrUrl">https://${server.host}:${mgt.transport.https.port}/dynamic-client-web/register</property>
<property name="url">tcp://localhost:1883</property> <property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
<property name="cleanSession">true</property> <property name="cleanSession">true</property>
</from> </from>
<mapping customMapping="disable" type="json"/> <mapping customMapping="disable" type="json"/>

@ -26,6 +26,7 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.transport.AndroidSenseMQTTConnector;
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.service.impl.util.SensorRecord; import org.wso2.carbon.device.mgt.iot.androidsense.service.impl.util.SensorRecord;
@ -78,7 +79,7 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
public Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold) { public Response sendThreshold(@PathParam("deviceId") String deviceId, @QueryParam("threshold") String threshold) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
AndroidSenseConstants.DEVICE_TYPE))) { AndroidSenseConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
androidSenseMQTTConnector.publishDeviceData(deviceId, "threshold", threshold); androidSenseMQTTConnector.publishDeviceData(deviceId, "threshold", threshold);
@ -96,7 +97,7 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
public Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words) { public Response removeKeyWords(@PathParam("deviceId") String deviceId, @QueryParam("words") String words) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
AndroidSenseConstants.DEVICE_TYPE))) { AndroidSenseConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
androidSenseMQTTConnector.publishDeviceData(deviceId, "remove", words); androidSenseMQTTConnector.publishDeviceData(deviceId, "remove", words);
@ -127,7 +128,7 @@ public class AndroidSenseControllerServiceImpl implements AndroidSenseController
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
AndroidSenseConstants.DEVICE_TYPE))) { AndroidSenseConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
List<SensorRecord> sensorDatas; List<SensorRecord> sensorDatas;

@ -25,6 +25,7 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; 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.common.group.mgt.DeviceGroupConstants;
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.AndroidConfiguration;
@ -108,7 +109,8 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier); boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(deviceIdentifier);
@ -133,7 +135,8 @@ public class AndroidSenseManagerServiceImpl implements AndroidSenseManagerServic
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE); deviceIdentifier.setType(AndroidSenseConstants.DEVICE_TYPE);
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
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);

@ -26,6 +26,7 @@ import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorRecord; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.arduino.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants; import org.wso2.carbon.device.mgt.iot.arduino.plugin.constants.ArduinoConstants;
@ -54,7 +55,8 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) { public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE))) { ArduinoConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId); LinkedList<String> deviceControlList = internalControlsQueue.get(deviceId);
@ -79,7 +81,7 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
public Response readControls(@PathParam("deviceId") String deviceId) { public Response readControls(@PathParam("deviceId") String deviceId) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE))) { ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
String result; String result;
@ -121,7 +123,7 @@ public class ArduinoControllerServiceImpl implements ArduinoControllerService {
@QueryParam("to") long to) { @QueryParam("to") long to) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
ArduinoConstants.DEVICE_TYPE))) { ArduinoConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);

@ -31,16 +31,16 @@
<Permission> <Permission>
<name>control bulb</name> <name>control bulb</name>
<path>device-mgt/user/operations</path> <path>/device-mgt/user/operations</path>
<url>/device/*/bulb</url> <url>/device/*/bulb</url>
<method>POST</method> <method>POST</method>
<scope>arduino_user</scope> <scope>arduino_user</scope>
</Permission> </Permission>
<Permission> <Permission>
<name>get controls</name> <name>get controls</name>
<path>device-mgt/user/operations</path> <path>/device-mgt/user/operations</path>
<url>/device/*/controls</url> <url>/device/*/controls</url>
<method>POST</method> <method>GET</method>
<scope>arduino_device</scope> <scope>arduino_device</scope>
</Permission> </Permission>
<Permission> <Permission>

@ -24,7 +24,7 @@
<property name="contentValidation">default</property> <property name="contentValidation">default</property>
<property name="transports">all</property> <property name="transports">all</property>
<property name="maximumTotalHttpConnection">100</property> <property name="maximumTotalHttpConnection">100</property>
<property name="tokenValidationEndpointUrl">https://localhost:9443/services/OAuth2TokenValidationService</property> <property name="tokenValidationEndpointUrl">https://${server.host}:${mgt.transport.https.port}/services/OAuth2TokenValidationService</property>
<property name="password">admin</property> <property name="password">admin</property>
</from> </from>
<mapping customMapping="disable" type="json"/> <mapping customMapping="disable" type="json"/>

@ -19,12 +19,13 @@
<eventReceiver name="temperature-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver"> <eventReceiver name="temperature-mqtt" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="oauth-mqtt"> <from eventAdapterType="oauth-mqtt">
<property name="topic">wso2/carbon.super/+/temperature</property> <property name="topic">wso2/carbon.super/raspberrypi/+/temperature</property>
<property name="username">admin</property> <property name="username">admin</property>
<property name="contentValidationParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:3</property> <property name="contentValidationParams">device_id_json_path:event.metaData.deviceId,device_id_topic_hierarchy_index:3</property>
<property name="contentValidation">default</property> <property name="contentValidation">default</property>
<property name="dcrUrl">https://localhost:9443/dynamic-client-web/register</property> <property name="dcrUrl">https://${server.host}:${mgt.transport.https.port}/dynamic-client-web/register</property>
<property name="url">tcp://localhost:1883</property> <property name="clientId">temperatureMqttClient</property>
<property name="url">tcp://${mqtt.broker.host}:${mqtt.broker.port}</property>
<property name="cleanSession">true</property> <property name="cleanSession">true</property>
</from> </from>
<mapping customMapping="disable" type="json"/> <mapping customMapping="disable" type="json"/>

@ -25,6 +25,7 @@ import org.wso2.carbon.analytics.dataservice.commons.SortByField;
import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException; import org.wso2.carbon.analytics.datasource.commons.exception.AnalyticsException;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorRecord; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.transport.RaspberryPiMQTTConnector; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.transport.RaspberryPiMQTTConnector;
@ -56,7 +57,7 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) { public Response switchBulb(@PathParam("deviceId") String deviceId, @QueryParam("state") String state) {
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
RaspberrypiConstants.DEVICE_TYPE))) { RaspberrypiConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
String switchToState = state.toUpperCase(); String switchToState = state.toUpperCase();
@ -90,7 +91,7 @@ public class RaspberryPiControllerServiceImpl implements RaspberryPiControllerSe
String sensorTableName = RaspberrypiConstants.TEMPERATURE_EVENT_TABLE; String sensorTableName = RaspberrypiConstants.TEMPERATURE_EVENT_TABLE;
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId,
RaspberrypiConstants.DEVICE_TYPE))) { RaspberrypiConstants.DEVICE_TYPE), DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
List<SortByField> sortByFields = new ArrayList<>(); List<SortByField> sortByFields = new ArrayList<>();

@ -157,7 +157,7 @@ public class RaspberryPiManagerServiceImpl implements RaspberryPiManagerService
@Path("devices/download") @Path("devices/download")
@GET @GET
@Produces("application/zip") @Produces("application/zip")
public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketch_type") String sketchType) { public Response downloadSketch(@QueryParam("deviceName") String deviceName, @QueryParam("sketchType") String sketchType) {
try { try {
ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType); ZipArchive zipFile = createDownloadFile(APIUtil.getAuthenticatedUser(), deviceName, sketchType);
Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile())); Response.ResponseBuilder response = Response.ok(FileUtils.readFileToByteArray(zipFile.getZipFile()));

@ -22,11 +22,17 @@ import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException; import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage; import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.json.JSONObject;
import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService; import org.wso2.carbon.apimgt.application.extension.APIManagementProviderService;
import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey; import org.wso2.carbon.apimgt.application.extension.dto.ApiApplicationKey;
import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException; import org.wso2.carbon.apimgt.application.extension.exception.APIManagerException;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.common.Device;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.core.service.DeviceManagementProviderService;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.exception.RaspberrypiException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil; import org.wso2.carbon.device.mgt.iot.raspberrypi.service.impl.util.APIUtil;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants; import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
@ -37,11 +43,13 @@ import org.wso2.carbon.identity.jwt.client.extension.exception.JWTClientExceptio
import org.wso2.carbon.user.api.UserStoreException; import org.wso2.carbon.user.api.UserStoreException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.util.UUID; import java.util.UUID;
public class RaspberryPiMQTTConnector extends MQTTTransportHandler { public class RaspberryPiMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(RaspberryPiMQTTConnector.class); private static Log log = LogFactory.getLog(RaspberryPiMQTTConnector.class);
private static final String subscribeTopic = "wso2/" + RaspberrypiConstants.DEVICE_TYPE + "/+/publisher"; // subscribeTopic is not used for the RaspberryPi sample since the DAS device directly publishes to DAS MQTT receiver
private static final String subscribeTopic = "wso2/+/"+ RaspberrypiConstants.DEVICE_TYPE + "/+/publisher";
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 = "";
@ -104,7 +112,26 @@ public class RaspberryPiMQTTConnector extends MQTTTransportHandler {
} }
@Override @Override
public void processIncomingMessage(MqttMessage message, String... messageParams) throws TransportHandlerException { public void publishDeviceData(String... publishData) throws TransportHandlerException {
if (publishData.length != 3) {
String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " +
"Need to be [owner, deviceId, resource{BULB/TEMP}, state{ON/OFF or null}]";
log.error(errorMsg);
throw new TransportHandlerException(errorMsg);
}
String deviceId = publishData[0];
String resource = publishData[1];
String state = publishData[2];
MqttMessage pushMessage = new MqttMessage();
String publishTopic = "wso2/" + APIUtil.getTenantDomainOftheUser() + "/"
+ RaspberrypiConstants.DEVICE_TYPE + "/" + deviceId;
String actualMessage = resource + ":" + state;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
pushMessage.setRetained(false);
publishToQueue(publishTopic, pushMessage);
} }
@Override @Override
@ -135,6 +162,10 @@ public class RaspberryPiMQTTConnector extends MQTTTransportHandler {
terminatorThread.start(); terminatorThread.start();
} }
@Override
public void processIncomingMessage(MqttMessage mqttMessage, String... messageParams) throws TransportHandlerException {
}
@Override @Override
public void processIncomingMessage() throws TransportHandlerException { public void processIncomingMessage() throws TransportHandlerException {
@ -154,28 +185,5 @@ public class RaspberryPiMQTTConnector extends MQTTTransportHandler {
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException { public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
} }
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
if (publishData.length != 3) {
String errorMsg = "Incorrect number of arguments received to SEND-MQTT Message. " +
"Need to be [owner, deviceId, resource{BULB/TEMP}, state{ON/OFF or null}]";
log.error(errorMsg);
throw new TransportHandlerException(errorMsg);
}
String deviceId = publishData[0];
String resource = publishData[1];
String state = publishData[2];
MqttMessage pushMessage = new MqttMessage();
String publishTopic = "wso2/" + APIUtil.getTenantDomainOftheUser() + "/"
+ RaspberrypiConstants.DEVICE_TYPE + "/" + deviceId;
String actualMessage = resource + ":" + state;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
pushMessage.setRetained(false);
publishToQueue(publishTopic, pushMessage);
}
} }

@ -65,7 +65,7 @@
<div class="controls"> <div class="controls">
<input class="new-device-name" style="color:#3f3f3f;padding:5px" <input class="new-device-name" style="color:#3f3f3f;padding:5px"
type="text" type="text"
placeholder="Ex. Lobby_DigitalDisplay" placeholder="Ex. Lobby_RaspberryPi"
name="deviceName" size="60" required> name="deviceName" size="60" required>
<br/> <br/>
<input type="hidden" class="deviceType" name="deviceType" <input type="hidden" class="deviceType" name="deviceType"

@ -44,6 +44,7 @@ import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.core.Agent
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.advanced.exception.AgentCoreOperationException;
import sun.security.x509.X509CertImpl; import sun.security.x509.X509CertImpl;
import java.io.IOException;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@ -82,6 +83,7 @@ public class EnrollmentManager {
private static final String KEY_PAIR_ALGORITHM = "RSA"; private static final String KEY_PAIR_ALGORITHM = "RSA";
private static final String PROVIDER = "BC"; private static final String PROVIDER = "BC";
private static final String SIGNATURE_ALG = "SHA1withRSA"; private static final String SIGNATURE_ALG = "SHA1withRSA";
private static final String CERT_IS_CA_EXTENSION = "is_ca";
private static final int KEY_SIZE = 2048; private static final int KEY_SIZE = 2048;
// Seed to our PRNG. Make sure this is initialised randomly, NOT LIKE THIS // Seed to our PRNG. Make sure this is initialised randomly, NOT LIKE THIS
@ -376,9 +378,9 @@ public class EnrollmentManager {
log.debug(((X509Certificate) cert).getIssuerDN().getName()); log.debug(((X509Certificate) cert).getIssuerDN().getName());
} }
//TODO: Need to identify the correct certificate. // I have chosen the CA cert based on its BasicConstraintExtension "is_ca" being set to "true"
// I have chosen the CA cert based on its BasicConstraint criticality being set to "true" // This is because the returned keystore may contain many certificates including RAs.
if (((X509CertImpl) cert).getBasicConstraintsExtension().isCritical()) { if (((Boolean) ((X509CertImpl) cert).getBasicConstraintsExtension().get(CERT_IS_CA_EXTENSION))) {
serverCertPublicKey = cert.getPublicKey(); serverCertPublicKey = cert.getPublicKey();
} }
} }
@ -396,6 +398,10 @@ public class EnrollmentManager {
String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server."; String errorMsg = "Could not retrieve [Server-Certificates] from the response message from SCEP-Server.";
log.error(errorMsg); log.error(errorMsg);
throw new AgentCoreOperationException(errorMsg, e); throw new AgentCoreOperationException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Error occurred whilst trying to get property ['is_ca'] from the retreived Certificates";
log.error(errorMsg);
throw new AgentCoreOperationException(errorMsg, e);
} }
return serverCertPublicKey; return serverCertPublicKey;

@ -27,24 +27,26 @@ import org.wso2.carbon.apimgt.annotations.api.Permission;
import org.wso2.carbon.device.mgt.common.DeviceIdentifier; import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException; import org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException;
import org.wso2.carbon.device.mgt.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig; 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.controlqueue.xmpp.XmppConfig;
import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener; import org.wso2.carbon.device.mgt.iot.service.IoTServerStartupListener;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException; import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.DeviceData; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.DeviceData;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmXMPPConnector;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.dto.SensorRecord;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmMQTTConnector; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmMQTTConnector;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.transport.VirtualFireAlarmXMPPConnector;
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.service.impl.util.SecurityManager;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils; import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.VirtualFireAlarmServiceUtils;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.constants.VirtualFireAlarmConstants;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes; import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam; 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.PUT;
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;
@ -72,7 +74,7 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
// holds a mapping of the IP addresses to Device-IDs for HTTP communication // holds a mapping of the IP addresses to Device-IDs for HTTP communication
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>(); private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
@Permission(scope = "virtual_firealarm_user", permissions = {"device-mgt/virtual_firealarm/user"}) @Permission(scope = "virtual_firealarm_user", permissions = { "device-mgt/virtual_firealarm/user" })
@POST @POST
@Path("device/register/{deviceId}/{ip}/{port}") @Path("device/register/{deviceId}/{ip}/{port}")
public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP, public Response registerDeviceIP(@PathParam("deviceId") String deviceId, @PathParam("ip") String deviceIP,
@ -107,8 +109,9 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
protocolString); protocolString);
} }
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(
VirtualFireAlarmConstants.DEVICE_TYPE))) { new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_OPERATOR_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
switch (protocolString) { switch (protocolString) {
@ -138,6 +141,44 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
} }
} }
@PUT
@Path("device/{deviceId}/policy")
public Response updatePolicy(@PathParam("deviceId") String deviceId, @QueryParam("protocol") String protocol,
@FormParam("policy") String policy) {
String protocolString = protocol.toUpperCase();
if (log.isDebugEnabled()) {
log.debug("Sending request to update-policy of device [" + deviceId + "] via " +
protocolString);
}
try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(
new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
DeviceGroupConstants.Permissions.DEFAULT_MANAGE_POLICIES_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
}
switch (protocolString) {
case HTTP_PROTOCOL:
throw new UnsupportedOperationException(
"Sending request to update-policy via HTTP protocol not supported.");
case XMPP_PROTOCOL:
String xmppResource = VirtualFireAlarmConstants.POLICY_CONTEXT.replace("/", "");
virtualFireAlarmXMPPConnector.publishDeviceData(deviceId, xmppResource, policy);
break;
default:
String mqttResource = VirtualFireAlarmConstants.POLICY_CONTEXT.replace("/", "");
virtualFireAlarmMQTTConnector.publishDeviceData(deviceId, mqttResource, policy);
break;
}
return Response.ok().build();
} catch (TransportHandlerException e) {
log.error("Failed to send update-policy request to device [" + deviceId + "] via " + protocolString);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}
@POST @POST
@Path("device/temperature") @Path("device/temperature")
@Consumes(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON)
@ -155,8 +196,8 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
return Response.status(Response.Status.CONFLICT).build(); return Response.status(Response.Status.CONFLICT).build();
} }
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(
VirtualFireAlarmConstants.DEVICE_TYPE))) { new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE))) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
if (!VirtualFireAlarmServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) { if (!VirtualFireAlarmServiceUtils.publishToDAS(dataMsg.deviceId, dataMsg.value)) {
@ -175,33 +216,34 @@ public class VirtualFireAlarmControllerServiceImpl implements VirtualFireAlarmCo
@Produces("application/json") @Produces("application/json")
public Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from, public Response getVirtualFirealarmStats(@PathParam("deviceId") String deviceId, @QueryParam("from") long from,
@QueryParam("to") long to) { @QueryParam("to") long to) {
String fromDate = String.valueOf(from); String fromDate = String.valueOf(from);
String toDate = String.valueOf(to); String toDate = String.valueOf(to);
String query = "deviceId:" + deviceId + " AND deviceType:" + String query = "deviceId:" + deviceId + " AND deviceType:" +
VirtualFireAlarmConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]"; VirtualFireAlarmConstants.DEVICE_TYPE + " AND time : [" + fromDate + " TO " + toDate + "]";
String sensorTableName = VirtualFireAlarmConstants.TEMPERATURE_EVENT_TABLE; String sensorTableName = VirtualFireAlarmConstants.TEMPERATURE_EVENT_TABLE;
try { try {
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(
VirtualFireAlarmConstants.DEVICE_TYPE))) { new DeviceIdentifier(deviceId, VirtualFireAlarmConstants.DEVICE_TYPE),
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); DeviceGroupConstants.Permissions.DEFAULT_STATS_MONITOR_PERMISSIONS)) {
} return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
if (sensorTableName != null) {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
}
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} }
return Response.status(Response.Status.BAD_REQUEST).build(); if (sensorTableName != null) {
List<SortByField> sortByFields = new ArrayList<>();
SortByField sortByField = new SortByField("time", SORT.ASC, false);
sortByFields.add(sortByField);
List<SensorRecord> sensorRecords = APIUtil.getAllEventsForDevice(sensorTableName, query, sortByFields);
return Response.status(Response.Status.OK.getStatusCode()).entity(sensorRecords).build();
}
} catch (AnalyticsException e) {
String errorMsg = "Error on retrieving stats on table " + sensorTableName + " with query " + query;
log.error(errorMsg);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).entity(errorMsg).build();
} catch (DeviceAccessAuthorizationException e) {
log.error(e.getErrorMessage(), e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} }
return Response.status(Response.Status.BAD_REQUEST).build();
}
private boolean waitForServerStartup() { private boolean waitForServerStartup() {
while (!IoTServerStartupListener.isServerReady()) { while (!IoTServerStartupListener.isServerReady()) {

@ -30,13 +30,14 @@ import org.wso2.carbon.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException; import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.common.EnrolmentInfo; 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.common.group.mgt.DeviceGroupConstants;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppAccount;
import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.XmppConfig; import org.wso2.carbon.device.mgt.iot.controlqueue.xmpp.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.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.APIUtil;
import org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.ZipUtil; 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;
@ -75,7 +76,8 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build(); return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
} }
boolean removed = APIUtil.getDeviceManagementService().disenrollDevice( boolean removed = APIUtil.getDeviceManagementService().disenrollDevice(
@ -101,7 +103,8 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
DeviceIdentifier deviceIdentifier = new DeviceIdentifier(); DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId); deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE); deviceIdentifier.setType(VirtualFireAlarmConstants.DEVICE_TYPE);
if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier)) { if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(deviceIdentifier, DeviceGroupConstants.
Permissions.DEFAULT_ADMIN_PERMISSIONS)) {
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);
@ -158,7 +161,7 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
ArrayList<Device> userDevicesforFirealarm = new ArrayList<>(); ArrayList<Device> userDevicesforFirealarm = new ArrayList<>();
for (Device device : userDevices) { for (Device device : userDevices) {
if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) && if (device.getType().equals(VirtualFireAlarmConstants.DEVICE_TYPE) &&
device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) { device.getEnrolmentInfo().getStatus().equals(EnrolmentInfo.Status.ACTIVE)) {
userDevicesforFirealarm.add(device); userDevicesforFirealarm.add(device);
} }
} }
@ -239,8 +242,9 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
//create new device id //create new device id
String deviceId = shortUUID(); String deviceId = shortUUID();
if (apiApplicationKey == null) { if (apiApplicationKey == null) {
String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration() String applicationUsername =
.getAdminUserName(); PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration()
.getAdminUserName();
APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService(); APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE}; String[] tags = {VirtualFireAlarmConstants.DEVICE_TYPE};
apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys( apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(
@ -249,7 +253,8 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient(); JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
String scopes = "device_type_" + VirtualFireAlarmConstants.DEVICE_TYPE + " device_" + deviceId; String scopes = "device_type_" + VirtualFireAlarmConstants.DEVICE_TYPE + " device_" + deviceId;
AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(),
apiApplicationKey.getConsumerSecret(), owner, scopes); apiApplicationKey.getConsumerSecret(), owner,
scopes);
String accessToken = accessTokenInfo.getAccessToken(); String accessToken = accessTokenInfo.getAccessToken();
String refreshToken = accessTokenInfo.getRefreshToken(); String refreshToken = accessTokenInfo.getRefreshToken();
//adding registering data //adding registering data
@ -266,8 +271,8 @@ public class VirtualFireAlarmManagerServiceImpl implements VirtualFireAlarmManag
if (!status) { if (!status) {
String msg = String msg =
"XMPP Account was not created for device - " + deviceId + " of owner - " + owner + "XMPP Account was not created for device - " + deviceId + " of owner - " + owner +
".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" + ".XMPP might have been disabled in org.wso2.carbon.device.mgt.iot" +
".common.config.server.configs"; ".common.config.server.configs";
throw new DeviceManagementException(msg); throw new DeviceManagementException(msg);
} }
} }

@ -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 final 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 = "";

@ -27,6 +27,7 @@ public class VirtualFireAlarmConstants {
public static final String URL_PREFIX = "http://"; public static final String URL_PREFIX = "http://";
public static final String BULB_CONTEXT = "/BULB/"; public static final String BULB_CONTEXT = "/BULB/";
public static final String POLICY_CONTEXT = "/POLICY/";
public static final String HUMIDITY_CONTEXT = "/HUMIDITY/"; public static final String HUMIDITY_CONTEXT = "/HUMIDITY/";
public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/"; public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";

@ -39,8 +39,14 @@
#define DEVICE_ID "${DEVICE_ID}" #define DEVICE_ID "${DEVICE_ID}"
#define DEVICE_TOKEN "${DEVICE_TOKEN}" #define DEVICE_TOKEN "${DEVICE_TOKEN}"
#define REFRESH_DEVICE_TOKEN "${DEVICE_REFRESH_TOKEN}" #define REFRESH_DEVICE_TOKEN "${DEVICE_REFRESH_TOKEN}"
#define DEVICE_TYPE "arduino"
#define TIME 0
#define SUPER_TENANT "carbon.super"
#define SERVICE_EPOINT "/arduino/controller/" #define DAS_SERVICE_EPOINT "/endpoints/temperature-http?deviceId=${DEVICE_ID}"
#define DAS_SERVICE_TEPOINT "/endpoints/t/${TENANT_DOMAIN}/temperature-http?deviceId=${DEVICE_ID}"
#define IOT_SERVICE_EPOINT "/arduino/device/${DEVICE_ID}/controls"
#define POLL_INTERVAL 1000 #define POLL_INTERVAL 1000
#define PUSH_INTERVAL 10000 #define PUSH_INTERVAL 10000
@ -49,19 +55,21 @@
#define SERVICE_PORT 9763 //http port of iot server #define SERVICE_PORT 9763 //http port of iot server
byte server[4] = {192,168,43,168}; //Ip address of iot server byte server[4] = {192,168,1,10}; //Ip address of iot server
byte deviceIP[4] = { 192, 168, 43,11 }; //Ststic ip address of arduino byte deviceIP[4] = { 192, 168, 1,110 }; //Ststic ip address of arduino
byte dns2[] = { 8, 8, 8, 8 }; //Ststic dns of arduino byte dns2[] = { 8, 8, 8, 8 }; //Ststic dns of arduino
byte subnet[] = { 255, 255, 255, 0 }; //Ststic subnet of arduino byte subnet[] = { 255, 255, 255, 0 }; //Ststic subnet of arduino
byte gateway[] = { 192, 168, 43, 1 }; //Ststic gateway of arduino byte gateway[] = { 192, 168, 1, 1 }; //Ststic gateway of arduino
String host, jsonPayLoad, replyMsg; String host, jsonPayLoad, replyMsg;
String responseMsg, subStrn; String responseMsg, subStrn;
double cpuTemperature =0; double cpuTemperature = 0;
static unsigned long pushTimestamp = 0; static unsigned long pushTimestamp = 0;
static unsigned long pollTimestamp = 0; static unsigned long pollTimestamp = 0;
char charBuf[10];
String payLoad;
#endif #endif

@ -97,11 +97,16 @@ void setupResource(){
host = "Host: " + hostIP + ":" + port; host = "Host: " + hostIP + ":" + port;
if(DEBUG) Serial.println(host); if(DEBUG) Serial.println(host);
jsonPayLoad = "{\"owner\":\""; jsonPayLoad = "{\"event\":{\"metaData\":";
jsonPayLoad += "{\"owner\":\"";
jsonPayLoad += String(DEVICE_OWNER); jsonPayLoad += String(DEVICE_OWNER);
jsonPayLoad += "\",\"deviceType\":\"";
jsonPayLoad += String(DEVICE_TYPE);
jsonPayLoad += "\",\"deviceId\":\""; jsonPayLoad += "\",\"deviceId\":\"";
jsonPayLoad += String(DEVICE_ID); jsonPayLoad += String(DEVICE_ID);
jsonPayLoad += "\",\"reply\":\""; jsonPayLoad += "\",\"time\":";
jsonPayLoad += String(TIME);
jsonPayLoad += "}, \"payloadData\":{";
if(DEBUG) { if(DEBUG) {
Serial.print("JSON Payload: "); Serial.print("JSON Payload: ");
@ -156,3 +161,4 @@ void setupClient(){
if(CON_DEBUG) Serial.println(F("client Connection failed")); if(CON_DEBUG) Serial.println(F("client Connection failed"));
} }
} }

@ -23,37 +23,42 @@ void readControls() {
Serial.println("Started.."); Serial.println("Started..");
client.fastrprint(F("GET ")); client.fastrprint(F("GET "));
client.fastrprint(SERVICE_EPOINT); client.fastrprint(IOT_SERVICE_EPOINT);
client.fastrprint(F("readcontrols"));
client.fastrprint(F(" HTTP/1.1")); client.fastrprint(F(" HTTP/1.1"));
client.fastrprint(F("\n")); client.fastrprint(F("\n"));
client.fastrprint(host.c_str()); client.fastrprint(host.c_str());client.fastrprint(F("\n"));
client.fastrprint(F("Authorization: Bearer ")); client.fastrprint(F(DEVICE_TOKEN)); client.fastrprint(F("\n"));
client.fastrprint(F("\n")); client.fastrprint(F("\n"));
client.fastrprint(DEVICE_ID);
client.fastrprint(F("owner: "));
client.fastrprint(DEVICE_OWNER);
client.fastrprint(F("\n"));
client.fastrprint(F("deviceId: "));
client.fastrprint(F(DEVICE_ID));
client.fastrprint(F("\n"));
client.fastrprint(F("deviceId: "));
client.fastrprint(F("protocol: HTTP\n")); client.fastrprint(F("protocol: HTTP\n"));
client.println(); client.println();
if(DEBUG) {
Serial.print("GET ");
Serial.print(IOT_SERVICE_EPOINT);
Serial.print(" HTTP/1.1"); Serial.println();
Serial.print(host); Serial.println();
Serial.print("Content-Type: application/json"); Serial.println();
Serial.println();
}
delay(1000); delay(1000);
Serial.println("Ended..");
while (client.available()) { while (client.available()) {
char response = client.read(); char response = client.read();
if(DEBUG) Serial.print(response);
responseMsg += response; responseMsg += response;
} }
Serial.println();
Serial.println("Ended..");
int index = responseMsg.lastIndexOf(":"); int index = responseMsg.lastIndexOf(":");
int newLine = responseMsg.lastIndexOf("\n"); int newLine = responseMsg.lastIndexOf("\n");
subStrn = responseMsg.substring(index + 1); subStrn = responseMsg.substring(index + 1);
responseMsg = responseMsg.substring(newLine + 1, index); responseMsg = responseMsg.substring(newLine + 1, index);
if(DEBUG) { if(DEBUG) {
Serial.print("Polling Response: ");
Serial.print(responseMsg); Serial.print(responseMsg);
Serial.println(); Serial.println();
Serial.println("-------------------------------"); Serial.println("-------------------------------");
@ -70,6 +75,7 @@ void readControls() {
digitalWrite(6, LOW); digitalWrite(6, LOW);
} }
responseMsg = "";
} }

@ -25,20 +25,22 @@
***********************************************************************************************/ ***********************************************************************************************/
void pushData(){ void pushData(){
String payLoad = "Temp";
payLoad = payLoad + "\",\"value\":\"";
payLoad = "\"temperature\":";
payLoad+=cpuTemperature; payLoad += dtostrf(cpuTemperature, 3, 2, charBuf);
payLoad += "}}}";
payLoad += "\"}";
client.fastrprint(F("POST ")); client.fastrprint(F("POST "));
client.fastrprint(SERVICE_EPOINT); client.fastrprint(F("pushdata")); if (strcmp(TENANT_DOMAIN, SUPER_TENANT) == 0) {
client.fastrprint(DAS_SERVICE_EPOINT);
} else {
client.fastrprint(DAS_SERVICE_TEPOINT);
}
client.fastrprint(F(" HTTP/1.1")); client.fastrprint(F("\n")); client.fastrprint(F(" HTTP/1.1")); client.fastrprint(F("\n"));
client.fastrprint(host.c_str()); client.fastrprint(F("\n")); client.fastrprint(host.c_str()); client.fastrprint(F("\n"));
client.fastrprint(F("Authorization: Bearer ")); client.fastrprint(F(DEVICE_TOKEN)); client.fastrprint(F("\n"));
client.fastrprint(F("Content-Type: application/json")); client.fastrprint(F("\n")); client.fastrprint(F("Content-Type: application/json")); client.fastrprint(F("\n"));
client.fastrprint(F("Accept: application/json")); client.fastrprint(F("\n"));
client.fastrprint(F("Content-Length: ")); client.fastrprint(F("Content-Length: "));
int payLength = jsonPayLoad.length() + payLoad.length(); int payLength = jsonPayLoad.length() + payLoad.length();
@ -48,8 +50,11 @@ void pushData(){
if(DEBUG) { if(DEBUG) {
Serial.print("POST "); Serial.print("POST ");
Serial.print(SERVICE_EPOINT); if (strcmp(TENANT_DOMAIN, SUPER_TENANT) == 0) {
Serial.print("pushdata"); Serial.print(DAS_SERVICE_EPOINT);
} else {
Serial.print(DAS_SERVICE_TEPOINT);
}
Serial.print(" HTTP/1.1"); Serial.println(); Serial.print(" HTTP/1.1"); Serial.println();
Serial.print(host); Serial.println(); Serial.print(host); Serial.println();
Serial.print("Content-Type: application/json"); Serial.println(); Serial.print("Content-Type: application/json"); Serial.println();
@ -104,8 +109,6 @@ void pushData(){
} }
double getBoardTemp(void) double getBoardTemp(void)
{ {
unsigned int wADC; unsigned int wADC;

@ -20,6 +20,8 @@ owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID} deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME} device-name=${DEVICE_NAME}
controller-context=/raspberrypi/controller controller-context=/raspberrypi/controller
mqtt-sub-topic=wso2/{owner}/raspberrypi/{deviceId}
mqtt-pub-topic=wso2/{owner}/raspberrypi/{deviceId}/publisher
https-ep=${HTTPS_EP} https-ep=${HTTPS_EP}
http-ep=${HTTP_EP} http-ep=${HTTP_EP}
apim-ep=${APIM_EP} apim-ep=${APIM_EP}

@ -22,22 +22,22 @@
import logging, logging.handlers import logging, logging.handlers
import sys, os, signal, argparse import sys, os, signal, argparse
import running_mode import running_mode
import time, threading, datetime import time, threading, datetime, calendar
import httplib, ssl # import httplib, ssl
from functools import wraps # from functools import wraps
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Overriding the default SSL version used in some of the Python (2.7.x) versions # Overriding the default SSL version used in some of the Python (2.7.x) versions
# This is a known issue in earlier Python releases # This is a known issue in earlier Python releases
# But was fixed in later versions. Ex-2.7.11 # But was fixed in later versions. Ex-2.7.11
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def sslwrap(func): # def sslwrap(func):
@wraps(func) # @wraps(func)
def bar(*args, **kw): # def bar(*args, **kw):
kw['ssl_version'] = ssl.PROTOCOL_TLSv1 # kw['ssl_version'] = ssl.PROTOCOL_TLSv1
return func(*args, **kw) # return func(*args, **kw)
return bar # return bar
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PUSH_INTERVAL = 5000 # time interval between successive data pushes in seconds PUSH_INTERVAL = 5000 # time interval between successive data pushes in seconds
@ -81,7 +81,8 @@ if args.interval:
if args.mode: if args.mode:
running_mode.RUNNING_MODE = args.mode running_mode.RUNNING_MODE = args.mode
iotUtils = __import__('iotUtils') iotUtils = __import__('iotUtils')
httpServer = __import__('httpServer') # python script used to start a http-server to listen for operations mqttConnector = __import__('mqttConnector')
# httpServer = __import__('httpServer') # python script used to start a http-server to listen for operations
# (includes the TEMPERATURE global variable) # (includes the TEMPERATURE global variable)
if running_mode.RUNNING_MODE == 'N': if running_mode.RUNNING_MODE == 'N':
@ -92,16 +93,16 @@ if args.mode:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Endpoint specific settings to which the data is pushed # Endpoint specific settings to which the data is pushed
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DC_ENDPOINT = iotUtils.HTTPS_EP.split(":") # DC_ENDPOINT = iotUtils.HTTPS_EP.split(":")
DC_IP = DC_ENDPOINT[1].replace('//', '') # DC_IP = DC_ENDPOINT[1].replace('//', '')
DC_PORT = int(DC_ENDPOINT[2]) # DC_PORT = int(DC_ENDPOINT[2])
DC_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT # DC_ENDPOINT_CONTEXT = iotUtils.CONTROLLER_CONTEXT
PUSH_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/push_temperature/' # PUSH_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/push_temperature/'
REGISTER_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/register' # REGISTER_ENDPOINT = str(DC_ENDPOINT_CONTEXT) + '/register'
HOST = iotUtils.getDeviceIP() # HOST = iotUtils.getDeviceIP()
HOST_HTTP_SERVER_PORT = iotUtils.getHTTPServerPort() # HOST_HTTP_SERVER_PORT = iotUtils.getHTTPServerPort()
HOST_AND_PORT = str(HOST)+ ":" + str(HOST_HTTP_SERVER_PORT) # HOST_AND_PORT = str(HOST)+ ":" + str(HOST_HTTP_SERVER_PORT)
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -142,32 +143,32 @@ def configureLogger(loggerName):
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This method registers the DevieIP in the Device-Cloud # This method registers the DevieIP in the Device-Cloud
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def registerDeviceIP(): # def registerDeviceIP():
ssl.wrap_socket = sslwrap(ssl.wrap_socket) # using the overridden sslwrap that uses TLSv1 # ssl.wrap_socket = sslwrap(ssl.wrap_socket) # using the overridden sslwrap that uses TLSv1
if sys.version_info<(2,7,9): # if sys.version_info<(2,7,9):
dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT) # dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
else: # else:
dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context()) # dcConncection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
#TODO need to get server certificate when initializing https connection # #TODO need to get server certificate when initializing https connection
dcConncection.set_debuglevel(1) # dcConncection.set_debuglevel(1)
dcConncection.connect() # dcConncection.connect()
#
registerURL = str(REGISTER_ENDPOINT) + '/' + str(iotUtils.DEVICE_OWNER) + '/' + str(iotUtils.DEVICE_ID) + '/' + \ # registerURL = str(REGISTER_ENDPOINT) + '/' + str(iotUtils.DEVICE_OWNER) + '/' + str(iotUtils.DEVICE_ID) + '/' + \
str(HOST) + '/' + str(HOST_HTTP_SERVER_PORT) + '/' # str(HOST) + '/' + str(HOST_HTTP_SERVER_PORT) + '/'
dcConncection.putrequest('POST', registerURL) # dcConncection.putrequest('POST', registerURL)
dcConncection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN) # dcConncection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
dcConncection.endheaders() # dcConncection.endheaders()
dcResponse = dcConncection.getresponse() # dcResponse = dcConncection.getresponse()
#
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' # print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('RASPBERRY_STATS: ' + str(registerURL)) # print ('RASPBERRY_STATS: ' + str(registerURL))
print ('RASPBERRY_STATS: ' + str(dcResponse.status)) # print ('RASPBERRY_STATS: ' + str(dcResponse.status))
print ('RASPBERRY_STATS: ' + str(dcResponse.reason)) # print ('RASPBERRY_STATS: ' + str(dcResponse.reason))
print ('RASPBERRY_STATS: Response Message') # print ('RASPBERRY_STATS: Response Message')
print str(dcResponse.msg) # print str(dcResponse.msg)
#
dcConncection.close() # dcConncection.close()
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' # print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -175,44 +176,54 @@ def registerDeviceIP():
# This method connects to the Device-Cloud and pushes data # This method connects to the Device-Cloud and pushes data
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def connectAndPushData(): def connectAndPushData():
if sys.version_info<(2,7,9): currentTime = calendar.timegm(time.gmtime())
dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
else:
dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
dcConnection.set_debuglevel(1)
dcConnection.connect()
request = dcConnection.putrequest('POST', PUSH_ENDPOINT)
dcConnection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
dcConnection.putheader('Content-Type', 'application/json')
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
### Read the Temperature and Load info of RPi and construct payload
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rPiTemperature = iotUtils.LAST_TEMP # Push the last read temperature value rPiTemperature = iotUtils.LAST_TEMP # Push the last read temperature value
PUSH_DATA = iotUtils.DEVICE_INFO + iotUtils.DEVICE_IP.format(ip=HOST_AND_PORT) + iotUtils.DEVICE_DATA.format( PUSH_DATA = iotUtils.DEVICE_INFO.format(currentTime, rPiTemperature)
temperature=rPiTemperature)
PUSH_DATA += '}' print '~~~~~~~~~~~~~~~~~~~~~~~~ Publishing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~'
dcConnection.putheader('Content-Length', len(PUSH_DATA)) print ('PUBLISHED DATA: ' + PUSH_DATA)
dcConnection.endheaders() print ('PUBLISHED TOPIC: ' + mqttConnector.TOPIC_TO_PUBLISH)
mqttConnector.publish(PUSH_DATA)
print PUSH_DATA # print '~~~~~~~~~~~~~~~~~~~~~~~~ End Of Publishing ~~~~~~~~~~~~~~~~~~~~~~~~~'
print '~~~~~~~~~~~~~~~~~~~~~~~~ Pushing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~'
# if sys.version_info<(2,7,9):
dcConnection.send(PUSH_DATA) # Push the data # dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT)
dcResponse = dcConnection.getresponse() # else:
# dcConnection = httplib.HTTPSConnection(host=DC_IP, port=DC_PORT, context=ssl._create_unverified_context())
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print ('RASPBERRY_STATS: ' + str(dcResponse.status)) # dcConnection.set_debuglevel(1)
print ('RASPBERRY_STATS: ' + str(dcResponse.reason)) # dcConnection.connect()
print ('RASPBERRY_STATS: Response Message') # request = dcConnection.putrequest('POST', PUSH_ENDPOINT)
print str(dcResponse.msg) # dcConnection.putheader('Authorization', 'Bearer ' + iotUtils.AUTH_TOKEN)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~' # dcConnection.putheader('Content-Type', 'application/json')
dcConnection.close() # ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ### Read the Temperature and Load info of RPi and construct payload
if (dcResponse.status == 409 or dcResponse.status == 412): # ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
print 'RASPBERRY_STATS: Re-registering Device IP'
registerDeviceIP() # rPiTemperature = iotUtils.LAST_TEMP # Push the last read temperature value
# PUSH_DATA = iotUtils.DEVICE_INFO + iotUtils.DEVICE_IP.format(ip=HOST_AND_PORT) + iotUtils.DEVICE_DATA.format(
# temperature=rPiTemperature)
# PUSH_DATA += '}'
# dcConnection.putheader('Content-Length', len(PUSH_DATA))
# dcConnection.endheaders()
# print PUSH_DATA
# print '~~~~~~~~~~~~~~~~~~~~~~~~ Pushing Device-Data ~~~~~~~~~~~~~~~~~~~~~~~~~'
# dcConnection.send(PUSH_DATA) # Push the data
# dcResponse = dcConnection.getresponse()
# print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# print ('RASPBERRY_STATS: ' + str(dcResponse.status))
# print ('RASPBERRY_STATS: ' + str(dcResponse.reason))
# print ('RASPBERRY_STATS: Response Message')
# print str(dcResponse.msg)
# print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# dcConnection.close()
# if (dcResponse.status == 409 or dcResponse.status == 412):
# print 'RASPBERRY_STATS: Re-registering Device IP'
# registerDeviceIP()
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -249,9 +260,9 @@ class TemperatureReaderThread(object):
print 'RASPBERRY_STATS: Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity) print 'RASPBERRY_STATS: Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity)
except Exception, e: except Exception, e:
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print "RASPBERRY_STATS: Exception in TempReaderThread: Could not successfully read Temperature" print "RASPBERRY_STATS: Exception in TempReaderThread: Could not successfully read Temperature"
print ("RASPBERRY_STATS: " + str(e)) print ("RASPBERRY_STATS: " + str(e))
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass pass
time.sleep(self.interval) time.sleep(self.interval)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -282,6 +293,19 @@ class ListenHTTPServerThread(object):
httpServer.main() httpServer.main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# This is a Thread object for connecting and subscribing to an MQTT Queue
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class SubscribeToMQTTQueue(object):
def __init__(self):
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
mqttConnector.main()
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# When sysvinit sends the TERM signal, cleanup before exiting # When sysvinit sends the TERM signal, cleanup before exiting
@ -300,12 +324,11 @@ signal.signal(signal.SIGTERM, sigterm_handler)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main(): def main():
configureLogger("WSO2IOT_RPiStats") configureLogger("WSO2IOT_RPiStats")
if running_mode.RUNNING_MODE == 'N':
iotUtils.setUpGPIOPins()
UtilsThread() UtilsThread()
registerDeviceIP() # Call the register endpoint and register Device IP # registerDeviceIP() # Call the register endpoint and register Device IP
# ListenHTTPServerThread() # starts an HTTP Server that listens for operational commands to switch ON/OFF Led
SubscribeToMQTTQueue() # connects and subscribes to an MQTT Queue that receives MQTT commands from the server
TemperatureReaderThread() # initiates and runs the thread to continuously read temperature from DHT Sensor TemperatureReaderThread() # initiates and runs the thread to continuously read temperature from DHT Sensor
ListenHTTPServerThread() # starts an HTTP Server that listens for operational commands to switch ON/OFF Led
while True: while True:
try: try:
if iotUtils.LAST_TEMP > 0: # Push data only if there had been a successful temperature read if iotUtils.LAST_TEMP > 0: # Push data only if there had been a successful temperature read

@ -1,33 +0,0 @@
#
# Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
[Device-Configurations]
server-name=${SERVER_NAME}
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/raspberrypi/controller
https-ep=${HTTPS_EP}
http-ep=${HTTP_EP}
apim-ep=${APIM_EP}
mqtt-ep=${MQTT_EP}
xmpp-ep=${XMPP_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -26,7 +26,7 @@ import random
import running_mode import running_mode
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# HOST_NAME(IP) of the Device # HOST_NAME(IP) of the Device
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
global HOST_NAME global HOST_NAME
HOST_NAME = "0.0.0.0" HOST_NAME = "0.0.0.0"
@ -52,18 +52,27 @@ configParser = ConfigParser.RawConfigParser()
configFilePath = os.path.join(os.path.dirname(__file__), './deviceConfig.properties') configFilePath = os.path.join(os.path.dirname(__file__), './deviceConfig.properties')
configParser.read(configFilePath) configParser.read(configFilePath)
SERVER_NAME = configParser.get('Device-Configurations', 'server-name')
DEVICE_OWNER = configParser.get('Device-Configurations', 'owner') DEVICE_OWNER = configParser.get('Device-Configurations', 'owner')
DEVICE_ID = configParser.get('Device-Configurations', 'deviceId') DEVICE_ID = configParser.get('Device-Configurations', 'deviceId')
MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep') MQTT_EP = configParser.get('Device-Configurations', 'mqtt-ep')
XMPP_EP = configParser.get('Device-Configurations', 'xmpp-ep') XMPP_EP = configParser.get('Device-Configurations', 'xmpp-ep')
AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token') AUTH_TOKEN = configParser.get('Device-Configurations', 'auth-token')
CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context') CONTROLLER_CONTEXT = configParser.get('Device-Configurations', 'controller-context')
DEVICE_INFO = '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '","reply":' MQTT_SUB_TOPIC = configParser.get('Device-Configurations', 'mqtt-sub-topic').format(owner = DEVICE_OWNER, deviceId = DEVICE_ID)
MQTT_PUB_TOPIC = configParser.get('Device-Configurations', 'mqtt-pub-topic').format(owner = DEVICE_OWNER, deviceId = DEVICE_ID)
DEVICE_INFO = '{{"event":{{"metaData":{{"owner":"' + DEVICE_OWNER + '","type":"raspberrypi","deviceId":"' + DEVICE_ID + '","time":{:.2f}}},"payloadData":{{"temperature":{:.2f}}}}}}}'
# '{"owner":"' + DEVICE_OWNER + '","deviceId":"' + DEVICE_ID + '","temperature":'
HTTPS_EP = configParser.get('Device-Configurations', 'https-ep') HTTPS_EP = configParser.get('Device-Configurations', 'https-ep')
HTTP_EP = configParser.get('Device-Configurations', 'http-ep') HTTP_EP = configParser.get('Device-Configurations', 'http-ep')
APIM_EP = configParser.get('Device-Configurations', 'apim-ep') APIM_EP = configParser.get('Device-Configurations', 'apim-ep')
DEVICE_IP = '"{ip}","value":' # DEVICE_IP = '"{ip}","value":'
DEVICE_DATA = '"{temperature}"' # '"{temperature}:{load}:OFF"' # DEVICE_DATA = '"{temperature}"' # '"{temperature}:{load}:OFF"'
# {"event": {"metaData": {"owner": "admin", "type": "arduino","deviceId": "s15kdwf34vue","time": 0},"payloadData": { "temperature": 22} }}
### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ### ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -73,6 +82,7 @@ DEVICE_DATA = '"{temperature}"' # '"{temperature}:{load}:OFF"'
# Method used to switch ON/OFF the LED attached to RPi # Method used to switch ON/OFF the LED attached to RPi
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def switchBulb(state): def switchBulb(state):
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print "Requested Switch State: " + state print "Requested Switch State: " + state
if running_mode.RUNNING_MODE == "N": if running_mode.RUNNING_MODE == "N":
@ -88,7 +98,6 @@ def switchBulb(state):
print "BULB Switched ON" print "BULB Switched ON"
elif state == "OFF": elif state == "OFF":
print "BULB Switched OFF" print "BULB Switched OFF"
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -174,7 +183,7 @@ def setUpGPIOPins():
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main(): def main():
global HOST_NAME global HOST_NAME
HOST_NAME = getDeviceIP() # HOST_NAME = getDeviceIP()
if running_mode.RUNNING_MODE == 'N': if running_mode.RUNNING_MODE == 'N':
setUpGPIOPins() setUpGPIOPins()

@ -0,0 +1,132 @@
#!/usr/bin/env python
"""
/**
* 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.
**/
"""
import time
import iotUtils
import paho.mqtt.client as mqtt
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
print("MQTT_LISTENER: Connected with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
print ("MQTT_LISTENER: Subscribing with topic " + TOPIC_TO_SUBSCRIBE)
client.subscribe(TOPIC_TO_SUBSCRIBE)
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'MQTT_LISTENER: Message Received by Device'
print( "MQTT_LISTENER: " + msg.topic + " --> " + str(msg.payload) )
request = str(msg.payload)
resource = request.split(":")[0].upper()
state = request.split(":")[1].upper()
print "MQTT_LISTENER: Resource- " + resource
if resource == "TEMP":
pass
#request.send_response(200)
#request.send_header("Content-type", "text/plain")
#request.end_headers()
#request.wfile.write(LAST_TEMP)
# return
elif resource == "BULB":
iotUtils.switchBulb(state)
def on_publish(client, userdata, mid):
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
print 'Temperature Data Published Succesfully'
# print (client)
# print (userdata)
# print (mid)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The callback for when a PUBLISH message to the server when door is open or close
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def publish(msg):
# global mqttClient
mqttClient.publish(TOPIC_TO_PUBLISH, msg)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# The Main method of the server script
# This method is invoked from RaspberryStats.py on a new thread
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
def main():
MQTT_ENDPOINT = iotUtils.MQTT_EP.split(":")
MQTT_IP = MQTT_ENDPOINT[1].replace('//','')
MQTT_PORT = int(MQTT_ENDPOINT[2])
SERVER_NAME = iotUtils.SERVER_NAME
DEV_ID = iotUtils.DEVICE_ID
global TOPIC_TO_SUBSCRIBE
# TOPIC_TO_SUBSCRIBE = SERVER_NAME + "/raspberrypi/" + DEV_ID
TOPIC_TO_SUBSCRIBE = SERVER_NAME + "/raspberrypi/" + DEV_ID
global TOPIC_TO_PUBLISH
# TOPIC_TO_PUBLISH = SERVER_NAME + "/raspberrypi/" + DEV_ID + "/publisher"
TOPIC_TO_PUBLISH = SERVER_NAME + "/raspberrypi/" + DEV_ID + "/temperature"
print ("MQTT_LISTENER: MQTT_ENDPOINT is " + str(MQTT_ENDPOINT))
print ("MQTT_LISTENER: MQTT_TOPIC is " + TOPIC_TO_SUBSCRIBE)
global mqttClient
mqttClient = mqtt.Client()
mqttClient.on_connect = on_connect
mqttClient.on_message = on_message
mqttClient.on_publish = on_publish
mqttClient.username_pw_set(iotUtils.AUTH_TOKEN, password = "")
while True:
try:
mqttClient.connect(MQTT_IP, MQTT_PORT, 180)
print "MQTT_LISTENER: " + time.asctime(), "Connected to MQTT Broker - %s:%s" % (MQTT_IP, MQTT_PORT)
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
mqttClient.loop_forever()
except (KeyboardInterrupt, Exception) as e:
print "MQTT_LISTENER: Exception in MQTTServerThread (either KeyboardInterrupt or Other)"
print ("MQTT_LISTENER: " + str(e))
mqttClient.disconnect()
print "MQTT_LISTENER: " + time.asctime(), "Connection to Broker closed - %s:%s" % (MQTT_IP, MQTT_PORT)
print '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'
pass
if __name__ == '__main__':
iotUtils.setUpGPIOPins()
main()

@ -97,14 +97,26 @@ done
cp deviceConfig.properties ./src cp deviceConfig.properties ./src
if [ "$mode" = "N" ]; then if [ "$mode" = "N" ]; then
# Install RPi.GPIO Library for Accessing RPi GPIO Pins
sudo apt-get install rpi.gpio sudo apt-get install rpi.gpio
# -----------------------------------------------------
# Install Adafruit_Python_DHT Library for reading DHT Sensor
git clone https://github.com/adafruit/Adafruit_Python_DHT.git git clone https://github.com/adafruit/Adafruit_Python_DHT.git
sudo apt-get install build-essential python-dev python-openssl sudo apt-get install build-essential python-dev python-openssl
sudo python ./Adafruit_Python_DHT/setup.py install cd ./Adafruit_Python_DHT
sudo python setup.py install
cd ..
# -----------------------------------------------------
# Install Paho-MQTT-Library for MQTT Communication
git clone https://github.com/eclipse/paho.mqtt.python.git
cd ./paho.mqtt.python
sudo python setup.py install
cd ..
# -----------------------------------------------------
fi fi
chmod +x ./src/RaspberryAgent.py chmod +x ./src/RaspberryAgent.py
./src/RaspberryAgent.py -i $input -m $mode sudo python ./src/RaspberryAgent.py -i $input -m $mode
if [ $? -ne 0 ]; then if [ $? -ne 0 ]; then
echo "Could not start the service..." echo "Could not start the service..."

@ -0,0 +1,11 @@
define stream fireAlarmEventStream (deviceID string, temp int);
from fireAlarmEventStream#window.time(7886776 sec)
select deviceID, max(temp) as maxValue
group by deviceID
insert into analyzeStream for expired-events;
from analyzeStream[maxValue < 88]
select maxValue
insert into bulbOnStream;
from fireAlarmEventStream[temp > 1093]
select deviceID, temp
insert into bulbOffStream;
Loading…
Cancel
Save