Refactored the RaspberryPi device-type components & features

Shabirmean 9 years ago
parent fda220b3f6
commit 0e47fbc48a

@ -32,8 +32,8 @@
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi API</name>
<description>WSO2 Carbon - RaspberryPi Service API Implementation</description>
<name>WSO2 Carbon - IoT Server RaspberryPi Controller API</name>
<description>WSO2 Carbon - RaspberryPi Controller Service API Implementation</description>
<url>http://wso2.org</url>
<dependencies>

@ -16,37 +16,24 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.service;
package org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
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.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
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.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.transport.RaspberryPiMQTTConnector;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.dto.DeviceJSON;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.transport.RaspberryPiMQTTSubscriber;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.dto.DeviceJSON;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@ -54,21 +41,14 @@ import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@API(name = "raspberrypi", version = "1.0.0", context = "/raspberrypi")
@DeviceType(value = "raspberrypi")
public class RaspberryPiService {
public class RaspberryPiControllerService {
private static Log log = LogFactory.getLog(RaspberryPiService.class);
private static Log log = LogFactory.getLog(RaspberryPiControllerService.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
@ -80,35 +60,25 @@ public class RaspberryPiService {
public static final String MQTT_PROTOCOL = "MQTT";
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private RaspberryPiMQTTSubscriber raspberryPiMQTTSubscriber;
private RaspberryPiMQTTConnector raspberryPiMQTTConnector;
/**
* @param raspberryPiMQTTSubscriber
* @param raspberryPiMQTTConnector
*/
public void setRaspberryPiMQTTSubscriber(final RaspberryPiMQTTSubscriber raspberryPiMQTTSubscriber) {
this.raspberryPiMQTTSubscriber = raspberryPiMQTTSubscriber;
/*if (MqttConfig.getInstance().isEnabled()) {
Runnable xmppStarter = new Runnable() {
@Override
public void run() {
raspberryPiMQTTSubscriber.initConnector();
raspberryPiMQTTSubscriber.connectAndSubscribe();
}
};
Thread xmppStarterThread = new Thread(xmppStarter);
xmppStarterThread.setDaemon(true);
xmppStarterThread.start();
public void setRaspberryPiMQTTConnector(final RaspberryPiMQTTConnector raspberryPiMQTTConnector) {
this.raspberryPiMQTTConnector = raspberryPiMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
raspberryPiMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml");
}*/
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, RaspberryPiMQTTConnector not started.");
}
}
/**
* @return
*/
public RaspberryPiMQTTSubscriber getRaspberryPiMQTTSubscriber() {
return raspberryPiMQTTSubscriber;
public RaspberryPiMQTTConnector getRaspberryPiMQTTConnector() {
return raspberryPiMQTTConnector;
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.exception;
package org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.exception;
public class RaspberrypiException extends Exception {
private static final long serialVersionUID = 118512086957330189L;

@ -0,0 +1,179 @@
/*
* 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.raspberrypi.controller.service.impl.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.config.server.DeviceManagementConfigurationManager;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttSubscriber;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.transport.TransportHandlerException;
import org.wso2.carbon.device.mgt.iot.transport.mqtt.MQTTTransportHandler;
import java.io.File;
import java.util.Calendar;
import java.util.UUID;
public class RaspberryPiMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(RaspberryPiMQTTConnector.class);
private static final String serverName =
DeviceManagementConfigurationManager.getInstance().getDeviceManagementServerInfo().getName();
private static final String subscribeTopic =
serverName + File.separator + "+" + File.separator + RaspberrypiConstants.DEVICE_TYPE +
File.separator + "+" + File.separator + "publisher";
private static final String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private RaspberryPiMQTTConnector() {
super(iotServerSubscriber, RaspberrypiConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
}
@Override
public void connect() {
Runnable connector = new Runnable() {
public void run() {
while (!isConnected()) {
try {
String brokerUsername = MqttConfig.getInstance().getMqttQueueUsername();
String brokerPassword = MqttConfig.getInstance().getMqttQueuePassword();
setUsernameAndPassword(brokerUsername, brokerPassword);
connectToQueue();
} catch (TransportHandlerException e) {
log.error("Connection to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Connector: Thread Sleep Interrupt Exception.", ex);
}
}
try {
subscribeToQueue();
} catch (TransportHandlerException e) {
log.warn("Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed", e);
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Override
public void processIncomingMessage(MqttMessage message, String... messageParams) throws TransportHandlerException {
String topic = messageParams[0];
// owner and the deviceId are extracted from the MQTT topic to which the messgae was received.
String ownerAndId = topic.replace(serverName + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + RaspberrypiConstants.DEVICE_TYPE + File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + "publisher", "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
String receivedMessage = message.toString();
if (log.isDebugEnabled()) {
log.debug("Received MQTT message for: [OWNER-" + owner + "] & [DEVICE.ID-" + deviceId + "]");
log.debug("Message [" + receivedMessage + "] topic: [" + topic + "]");
}
if (receivedMessage.contains("PUBLISHER")) {
float temperature = Float.parseFloat(receivedMessage.split(":")[2]);
if (!RaspberrypiServiceUtils.publishToDAS(owner, deviceId, temperature)) {
log.error("MQTT Subscriber: Publishing data to DAS failed.");
}
if (log.isDebugEnabled()) {
log.debug("MQTT Subscriber: Published data to DAS successfully.");
}
} else if (receivedMessage.contains("TEMPERATURE")) {
String temperatureValue = receivedMessage.split(":")[1];
SensorDataManager.getInstance().setSensorRecord(deviceId, RaspberrypiConstants.SENSOR_TEMPERATURE,
temperatureValue,
Calendar.getInstance().getTimeInMillis());
}
}
@Override
public void disconnect() {
Runnable stopConnection = new Runnable() {
public void run() {
while (isConnected()) {
try {
closeConnection();
} catch (MqttException e) {
if (log.isDebugEnabled()) {
log.warn("Unable to 'STOP' MQTT connection at broker at: " + mqttBrokerEndPoint
+ " for device-type - " + RaspberrypiConstants.DEVICE_TYPE, e);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception at device-type - " +
RaspberrypiConstants.DEVICE_TYPE, e1);
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void processIncomingMessage() throws TransportHandlerException {
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
}
@Override
public void publishDeviceData() throws TransportHandlerException {
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
}
}

@ -16,7 +16,7 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.service.util;
package org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@ -29,8 +29,6 @@ import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceController;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import javax.ws.rs.HttpMethod;

@ -1,36 +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.raspberrypi.service.dto;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@JsonIgnoreProperties(ignoreUnknown = true)
public class DeviceJSON {
@XmlElement(required = true) public String owner;
@XmlElement(required = true) public String deviceId;
@XmlElement(required = true) public String reply;
@XmlElement public Long time;
@XmlElement public String key;
@XmlElement public float value;
}

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

@ -25,14 +25,11 @@
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd">
<jaxrs:server id="RaspberryPi" address="/">
<jaxrs:server id="RaspberryPiController" address="/">
<jaxrs:serviceBeans>
<bean id="RaspberryPiService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.RaspberryPiService">
<property name="raspberryPiMQTTSubscriber" ref="mqttSubscriberBean"/>
<bean id="RaspberryPiControllerService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.RaspberryPiControllerService">
<property name="raspberryPiMQTTConnector" ref="raspberryPiMQTTConnector"/>
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
@ -40,8 +37,8 @@
</jaxrs:providers>
</jaxrs:server>
<bean id="mqttSubscriberBean"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.transport.RaspberryPiMQTTSubscriber">
<bean id="raspberryPiMQTTConnector"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl.transport.RaspberryPiMQTTConnector">
</bean>
</beans>

@ -29,11 +29,11 @@
<modelVersion>4.0.0</modelVersion>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.mgt.service.impl</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 Carbon - IoT Server RaspberryPi API</name>
<description>WSO2 Carbon - RaspberryPi Service API Implementation</description>
<name>WSO2 Carbon - IoT Server RaspberryPi Manager API</name>
<description>WSO2 Carbon - RaspberryPi Manager Service API Implementation</description>
<url>http://wso2.org</url>
<dependencies>

@ -16,41 +16,39 @@
* under the License.
*/
package org.wso2.carbon.device.mgt.iot.raspberrypi.service;
package org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
import org.wso2.carbon.apimgt.annotations.device.feature.Feature;
import org.wso2.carbon.apimgt.webapp.publisher.KeyGenerationUtil;
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.common.EnrolmentInfo;
import org.wso2.carbon.device.mgt.iot.DeviceManagement;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import org.wso2.carbon.device.mgt.iot.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
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.XmppServerClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.dto.DeviceJSON;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.transport.RaspberryPiMQTTSubscriber;
import org.wso2.carbon.device.mgt.iot.raspberrypi.service.util.RaspberrypiServiceUtils;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorDataManager;
import org.wso2.carbon.device.mgt.iot.sensormgt.SensorRecord;
import org.wso2.carbon.device.mgt.iot.util.ZipArchive;
import org.wso2.carbon.device.mgt.iot.util.ZipUtil;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.*;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
@ -58,16 +56,15 @@ import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
@DeviceType(value = "raspberrypi")
public class RaspberryPiService {
public class RaspberryPiManagerService {
private static Log log = LogFactory.getLog(RaspberryPiService.class);
private static Log log = LogFactory.getLog(RaspberryPiManagerService.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
@ -79,38 +76,6 @@ public class RaspberryPiService {
public static final String MQTT_PROTOCOL = "MQTT";
private ConcurrentHashMap<String, String> deviceToIpMap = new ConcurrentHashMap<>();
private RaspberryPiMQTTSubscriber raspberryPiMQTTSubscriber;
/**
* @param raspberryPiMQTTSubscriber
*/
public void setRaspberryPiMQTTSubscriber(
final RaspberryPiMQTTSubscriber raspberryPiMQTTSubscriber) {
this.raspberryPiMQTTSubscriber = raspberryPiMQTTSubscriber;
if (MqttConfig.getInstance().isEnabled()) {
Runnable xmppStarter = new Runnable() {
@Override
public void run() {
raspberryPiMQTTSubscriber.initConnector();
raspberryPiMQTTSubscriber.connectAndSubscribe();
}
};
Thread xmppStarterThread = new Thread(xmppStarter);
xmppStarterThread.setDaemon(true);
xmppStarterThread.start();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. Hence, VirtualFireAlarmMQTTConnector not started.");
}
}
/**
* @return
*/
public RaspberryPiMQTTSubscriber getRaspberryPiMQTTSubscriber() {
return raspberryPiMQTTSubscriber;
}
/* ---------------------------------------------------------------------------------------
Device management specific APIs

@ -28,11 +28,10 @@
<jaxrs:server id="RaspberryPi" address="/">
<jaxrs:server id="RaspberryPiManager" address="/">
<jaxrs:serviceBeans>
<bean id="RaspberryPiService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.RaspberryPiService">
<property name="raspberryPiMQTTSubscriber" ref="mqttSubscriberBean"/>
<bean id="RaspberryPiManagerService"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl.RaspberryPiManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
@ -40,9 +39,5 @@
</jaxrs:providers>
</jaxrs:server>
<bean id="mqttSubscriberBean"
class="org.wso2.carbon.device.mgt.iot.raspberrypi.service.transport.RaspberryPiMQTTSubscriber">
</bean>
</beans>

@ -1,31 +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.raspberrypi.service.exception;
public class RaspberrypiException extends Exception {
private static final long serialVersionUID = 118512086957330189L;
public RaspberrypiException(String errorMessage) {
super(errorMessage);
}
public RaspberrypiException(String errorMessage, Throwable throwable) {
super(errorMessage, throwable);
}
}

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

@ -1,234 +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.raspberrypi.service.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.concurrent.FutureCallback;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.device.mgt.analytics.exception.DataPublisherConfigurationException;
import org.wso2.carbon.device.mgt.analytics.service.DeviceAnalyticsService;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceController;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
import org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.constants.RaspberrypiConstants;
import javax.ws.rs.HttpMethod;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
public class RaspberrypiServiceUtils {
private static final Log log = LogFactory.getLog(RaspberrypiServiceUtils.class);
//TODO; replace this tenant domain
private static final String SUPER_TENANT = "carbon.super";
private static final String TEMPERATURE_STREAM_DEFINITION = "org.wso2.iot.devices.temperature";
public static String sendCommandViaHTTP(final String deviceHTTPEndpoint, String urlContext,
boolean fireAndForgot) throws DeviceManagementException {
String responseMsg = "";
String urlString = RaspberrypiConstants.URL_PREFIX + deviceHTTPEndpoint + urlContext;
if (log.isDebugEnabled()) {
log.debug(urlString);
}
if (!fireAndForgot) {
HttpURLConnection httpConnection = getHttpConnection(urlString);
try {
httpConnection.setRequestMethod(HttpMethod.GET);
} catch (ProtocolException e) {
String errorMsg =
"Protocol specific error occurred when trying to set method to GET" +
" for:" + urlString;
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
responseMsg = readResponseFromGetRequest(httpConnection);
} else {
CloseableHttpAsyncClient httpclient = null;
try {
httpclient = HttpAsyncClients.createDefault();
httpclient.start();
HttpGet request = new HttpGet(urlString);
final CountDownLatch latch = new CountDownLatch(1);
Future<HttpResponse> future = httpclient.execute(
request, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse httpResponse) {
latch.countDown();
}
@Override
public void failed(Exception e) {
latch.countDown();
}
@Override
public void cancelled() {
latch.countDown();
}
});
latch.await();
} catch (InterruptedException e) {
if (log.isDebugEnabled()) {
log.debug("Sync Interrupted");
}
} finally {
try {
if (httpclient != null) {
httpclient.close();
}
} catch (IOException e) {
if (log.isDebugEnabled()) {
log.debug("Failed on close");
}
}
}
}
return responseMsg;
}
public static boolean sendCommandViaMQTT(String deviceOwner, String deviceId, String resource,
String state) throws DeviceManagementException {
boolean result;
DeviceController deviceController = new DeviceController();
try {
result = deviceController.publishMqttControl(deviceOwner, RaspberrypiConstants.DEVICE_TYPE, deviceId, resource, state);
} catch (DeviceControllerException e) {
String errorMsg = "Error whilst trying to publish to MQTT Queue";
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
return result;
}
/* ---------------------------------------------------------------------------------------
Utility methods relevant to creating and sending http requests
--------------------------------------------------------------------------------------- */
/* This methods creates and returns a http connection object */
public static HttpURLConnection getHttpConnection(String urlString) throws
DeviceManagementException {
URL connectionUrl = null;
HttpURLConnection httpConnection;
try {
connectionUrl = new URL(urlString);
httpConnection = (HttpURLConnection) connectionUrl.openConnection();
} catch (MalformedURLException e) {
String errorMsg =
"Error occured whilst trying to form HTTP-URL from string: " + urlString;
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
} catch (IOException e) {
String errorMsg = "Error occured whilst trying to open a connection to: " +
connectionUrl.toString();
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
return httpConnection;
}
/* This methods reads and returns the response from the connection */
public static String readResponseFromGetRequest(HttpURLConnection httpConnection)
throws DeviceManagementException {
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new InputStreamReader(
httpConnection.getInputStream()));
} catch (IOException e) {
String errorMsg =
"There is an issue with connecting the reader to the input stream at: " +
httpConnection.getURL();
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
String responseLine;
StringBuilder completeResponse = new StringBuilder();
try {
while ((responseLine = bufferedReader.readLine()) != null) {
completeResponse.append(responseLine);
}
} catch (IOException e) {
String errorMsg =
"Error occured whilst trying read from the connection stream at: " +
httpConnection.getURL();
log.error(errorMsg);
throw new DeviceManagementException(errorMsg, e);
}
try {
bufferedReader.close();
} catch (IOException e) {
log.error(
"Could not succesfully close the bufferedReader to the connection at: " +
httpConnection.getURL());
}
return completeResponse.toString();
}
public static boolean publishToDAS(String owner, String deviceId, float temperature) {
PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext ctx = PrivilegedCarbonContext.getThreadLocalCarbonContext();
ctx.setTenantDomain(SUPER_TENANT, true);
DeviceAnalyticsService deviceAnalyticsService = (DeviceAnalyticsService) ctx.getOSGiService(
DeviceAnalyticsService.class, null);
Object metdaData[] = {owner, RaspberrypiConstants.DEVICE_TYPE, deviceId, System.currentTimeMillis()};
Object payloadData[] = {temperature};
try {
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData, new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
}

@ -37,7 +37,7 @@
<modules>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.plugin.impl</module>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.mgt.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl</module>
<module>org.wso2.carbon.device.mgt.iot.raspberrypi.controller.service.impl</module>
</modules>

@ -109,7 +109,6 @@ public class VirtualFireAlarmMQTTConnector extends MQTTTransportHandler {
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();

@ -44,7 +44,7 @@
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.mgt.service.impl</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl</artifactId>
<type>war</type>
</dependency>
<dependency>
@ -108,7 +108,7 @@
</artifactItem>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.mgt.service.impl
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl
</artifactId>
<type>war</type>
<overWrite>true</overWrite>

@ -470,7 +470,7 @@
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.mgt.service.impl</artifactId>
<artifactId>org.wso2.carbon.device.mgt.iot.raspberrypi.manager.service.impl</artifactId>
<version>${carbon.iot.device.mgt.version}</version>
<type>war</type>
</dependency>

Loading…
Cancel
Save