Connected cup device added

application-manager-new
Menaka Madushanka 9 years ago
parent bc84be58ea
commit 6179298d9f

@ -0,0 +1,251 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.controller.service</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Controller Service</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Controller Service</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>mqtt-client</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.1</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
-->
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
</dependency>
<dependency>
<groupId>org.json.wso2</groupId>
<artifactId>json</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<!--plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin-->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>connectedcup</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,180 @@
/*
* 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.coffeeking.controller.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.controller.service.dto.DeviceJSON;
import org.coffeeking.controller.service.transport.ConnectedCupMQTTConnector;
import org.coffeeking.controller.service.util.ConnectedCupServiceUtils;
import org.json.JSONObject;
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.device.mgt.common.DeviceIdentifier;
import org.wso2.carbon.device.mgt.common.DeviceManagementException;
import org.wso2.carbon.device.mgt.iot.DeviceValidator;
import org.wso2.carbon.device.mgt.iot.controlqueue.mqtt.MqttConfig;
import org.wso2.carbon.device.mgt.iot.exception.DeviceControllerException;
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.transport.TransportHandlerException;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
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;
import java.util.Calendar;
@API( name="connectedcup", version="1.0.0", context="/connectedcup")
@DeviceType( value = "connectedcup")
public class ConnectedCupControllerService {
private static Log log = LogFactory.getLog(ConnectedCupControllerService.class);
private static final String SUPER_TENANT = "carbon.super";
private static ConnectedCupMQTTConnector connectedCupMQTTConnector;
@Context
HttpServletResponse response;
public ConnectedCupMQTTConnector connectedCupMQTTConnector() {
return ConnectedCupControllerService.connectedCupMQTTConnector;
}
public void setconnectedCupMQTTConnector(
ConnectedCupMQTTConnector connectedCupMQTTConnector) {
ConnectedCupControllerService.connectedCupMQTTConnector = connectedCupMQTTConnector;
if (MqttConfig.getInstance().isEnabled()) {
connectedCupMQTTConnector.connect();
} else {
log.warn("MQTT disabled in 'devicemgt-config.xml'. " +
"Hence, DigitalDisplayMqttCommunicationHandler not started.");
}
}
/**
* @param deviceId
* @param owner
*/
@Path("controller/cup/coffeelevel")
@GET
public SensorRecord readCoffeeLevel(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, SUPER_TENANT, new DeviceIdentifier(
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.LEVEL_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_LEVEL);
} catch ( DeviceControllerException | TransportHandlerException e ) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
@Path("controller/cup/temperature")
@GET
public SensorRecord readTemperature(@HeaderParam("owner") String owner,
@HeaderParam("deviceId") String deviceId,
@Context HttpServletResponse response) {
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(owner, SUPER_TENANT,
new DeviceIdentifier(deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
if (log.isDebugEnabled()) {
log.debug("Sending request to read connected cup temperature of device " +
"[" + deviceId + "] via MQTT");
}
try {
String mqttResource = ConnectedCupConstants.TEMPERATURE_CONTEXT.replace("/", "");
connectedCupMQTTConnector.publishDeviceData(owner, deviceId, mqttResource, "");
sensorRecord = SensorDataManager.getInstance().getSensorRecord(deviceId,
ConnectedCupConstants.SENSOR_TEMPERATURE);
} catch ( DeviceControllerException | TransportHandlerException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.OK.getStatusCode());
return sensorRecord;
}
@Path("controller/ordercoffee")
@POST
public HttpServletResponse orderCoffee(@QueryParam("deviceId") String deviceId, @QueryParam("deviceOwner") String
deviceOwner, @Context HttpServletResponse response){
SensorRecord sensorRecord = null;
DeviceValidator deviceValidator = new DeviceValidator();
try {
if (!deviceValidator.isExist(deviceOwner, SUPER_TENANT, new DeviceIdentifier(
deviceId, ConnectedCupConstants.DEVICE_TYPE))) {
response.setStatus(Response.Status.UNAUTHORIZED.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
}
response.setStatus(Response.Status.ACCEPTED.getStatusCode());
log.info("Coffee ordered....!");
if (log.isDebugEnabled()) {
log.debug("Sending request to read liquid level value of device [" + deviceId + "] via MQTT");
}
return response;
}
}

@ -0,0 +1,35 @@
/*
* 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.coffeeking.controller.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;
}

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

@ -0,0 +1,204 @@
/*
* 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.coffeeking.controller.service.transport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.controller.service.util.ConnectedCupServiceUtils;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
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.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.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.UUID;
@SuppressWarnings("no JAX-WS annotation")
public class ConnectedCupMQTTConnector extends MQTTTransportHandler {
private static Log log = LogFactory.getLog(ConnectedCupMQTTConnector.class);
private static String serverName = DeviceManagementConfigurationManager.getInstance().
getDeviceManagementServerInfo().getName();
private static String subscribeTopic = "wso2" + File.separator + "+" + File.separator +
ConnectedCupConstants.DEVICE_TYPE + File.separator + "+" + File.separator
+ "connected_publisher";
private static String iotServerSubscriber = UUID.randomUUID().toString().substring(0, 5);
private ConnectedCupMQTTConnector() {
super(iotServerSubscriber, ConnectedCupConstants.DEVICE_TYPE,
MqttConfig.getInstance().getMqttQueueEndpoint(), subscribeTopic);
}
@Override
public void connect() {
Runnable connector = new Runnable() {
public void run() {
while (!isConnected()) {
try {
connectToQueue();
subscribeToQueue();
} catch (TransportHandlerException e) {
log.warn("Connection/Subscription to MQTT Broker at: " + mqttBrokerEndPoint + " failed");
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException ex) {
log.error("MQTT-Subscriber: Thread Sleep Interrupt Exception.", ex);
}
}
}
}
};
Thread connectorThread = new Thread(connector);
connectorThread.setDaemon(true);
connectorThread.start();
}
@Override
public void publishDeviceData(String... publishData) throws TransportHandlerException {
if (publishData.length != 4) {
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 deviceOwner = publishData[0];
String deviceId = publishData[1];
String resource = publishData[2];
String state = publishData[3];
MqttMessage pushMessage = new MqttMessage();
String publishTopic =
serverName + File.separator + deviceOwner + File.separator +
ConnectedCupConstants.DEVICE_TYPE + File.separator + deviceId;
try {
String actualMessage = resource + ":" + state;
pushMessage.setPayload(actualMessage.getBytes(StandardCharsets.UTF_8));
pushMessage.setQos(DEFAULT_MQTT_QUALITY_OF_SERVICE);
pushMessage.setRetained(false);
publishToQueue(publishTopic, pushMessage);
} catch (Exception e) {
String errorMsg = "Preparing Secure payload failed for device - [" + deviceId + "] of owner - " +
"[" + deviceOwner + "].";
log.error(errorMsg);
throw new TransportHandlerException(errorMsg, e);
}
}
@Override
public void processIncomingMessage(MqttMessage mqttMessage, String... strings) throws TransportHandlerException {
String topic = strings[0];
String ownerAndId = topic.replace("wso2" + File.separator + "iot" + File.separator, "");
ownerAndId = ownerAndId.replace(File.separator + ConnectedCupConstants.DEVICE_TYPE + File.separator, ":");
ownerAndId = ownerAndId.replace(File.separator + "connectedcup_publisher", "");
String owner = ownerAndId.split(":")[0];
String deviceId = ownerAndId.split(":")[1];
String[] messageData = mqttMessage.toString().split(":");
Float value = Float.valueOf(messageData[1]);
switch (messageData[0]){
case "temperature":
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE,
String.valueOf(messageData[1]),
Calendar.getInstance().getTimeInMillis());
ConnectedCupServiceUtils.publishToDAS(owner, deviceId, value);
break;
case "coffeelevel":
SensorDataManager.getInstance().setSensorRecord(deviceId, ConnectedCupConstants.SENSOR_TEMPERATURE,
String.valueOf(messageData[1]),
Calendar.getInstance().getTimeInMillis());
ConnectedCupServiceUtils.publishToDAS(owner, deviceId, value);
}
log.info("Received MQTT message for OWNER: " + owner + " DEVICE.ID: " + deviceId + " | Command: " +
messageData[0] +" " + messageData[1] );
}
@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 - " + ConnectedCupConstants.DEVICE_TYPE, e);
}
try {
Thread.sleep(timeoutInterval);
} catch (InterruptedException e1) {
log.error("MQTT-Terminator: Thread Sleep Interrupt Exception at device-type - " +
ConnectedCupConstants.DEVICE_TYPE, e1);
}
}
}
}
};
Thread terminatorThread = new Thread(stopConnection);
terminatorThread.setDaemon(true);
terminatorThread.start();
}
@Override
public void publishDeviceData() {
// nothing to do
}
@Override
public void publishDeviceData(MqttMessage publishData) throws TransportHandlerException {
// nothing to do
}
@Override
public void processIncomingMessage() {
// nothing to do
}
@Override
public void processIncomingMessage(MqttMessage message) throws TransportHandlerException {
// nothing to do
}
}

@ -0,0 +1,216 @@
/*
* 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.coffeeking.controller.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.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
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 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 ConnectedCupServiceUtils {
private static final Log log = LogFactory.getLog(ConnectedCupServiceUtils.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 = ConnectedCupConstants.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;
}
/* ---------------------------------------------------------------------------------------
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, ConnectedCupConstants.DEVICE_TYPE, deviceId,
System.currentTimeMillis()};
Object payloadData[] = {temperature};
try {
deviceAnalyticsService.publishEvent(TEMPERATURE_STREAM_DEFINITION, "1.0.0", metdaData,
new Object[0], payloadData);
} catch (DataPublisherConfigurationException e) {
return false;
} finally {
PrivilegedCarbonContext.endTenantFlow();
}
return true;
}
}

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,48 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
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="ConnectedCupController" address="/connectedcup">
<jaxrs:serviceBeans>
<bean id="ConnectedCupControllerService"
class="org.coffeeking.controller.service.ConnectedCupControllerService">
<property name="connectedCupMQTTConnector" ref="communicationHandler"/>
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
<bean
id="communicationHandler"
class="org.coffeeking.controller.service.transport.ConnectedCupMQTTConnector" >
</bean>
</beans>

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>ConnectedCup-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>false</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>true</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/connectedcup/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>connectedcup</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

@ -0,0 +1,261 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>device-mgt-iot-connectedcup</artifactId>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.manager.service</artifactId>
<version>1.9.2-SNAPSHOT</version>
<packaging>war</packaging>
<name>WSO2 IoTS(Device Types) - Connected Cup Manager Service</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Manager Service</description>
<url>http://wso2.org</url>
<dependencies>
<!-- CDM -->
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.common</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.device.mgt.analytics</artifactId>
<exclusions>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2-client</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.certificate.mgt.core</artifactId>
<exclusions>
<exclusion>
<groupId>commons-codec.wso2</groupId>
<artifactId>commons-codec</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--CXF -->
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
</dependency>
<!--MQTT -->
<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>mqtt-client</artifactId>
</dependency>
<!--IOT -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot</artifactId>
</dependency>
<!--
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl</artifactId>
<scope>provided</scope>
</dependency>
-->
<!--JAX-RS -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
</dependency>
<dependency>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</dependency>
<dependency>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.utils</artifactId>
<exclusions>
<exclusion>
<groupId>org.bouncycastle.wso2</groupId>
<artifactId>bcprov-jdk15on</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.user.api</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.queuing</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</exclusion>
<exclusion>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</exclusion>
<exclusion>
<groupId>jaxen</groupId>
<artifactId>jaxen</artifactId>
</exclusion>
<exclusion>
<groupId>commons-fileupload.wso2</groupId>
<artifactId>commons-fileupload</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>org.apache.ant.wso2</groupId>
<artifactId>ant</artifactId>
</exclusion>
<exclusion>
<groupId>commons-httpclient.wso2</groupId>
<artifactId>commons-httpclient</artifactId>
</exclusion>
<exclusion>
<groupId>org.eclipse.equinox</groupId>
<artifactId>javax.servlet</artifactId>
</exclusion>
<exclusion>
<groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.registry.api</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smack</artifactId>
</dependency>
<dependency>
<groupId>org.igniterealtime.smack.wso2</groupId>
<artifactId>smackx</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.annotations</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt</groupId>
<artifactId>org.wso2.carbon.apimgt.webapp.publisher</artifactId>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
</dependency>
</dependencies>
<build>
<sourceDirectory>${basedir}/src/main/java</sourceDirectory>
<plugins>
<!--plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<encoding>UTF-8</encoding>
<source>${wso2.maven.compiler.source}</source>
<target>${wso2.maven.compiler.target}</target>
</configuration>
</plugin-->
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
<version>2.3.2</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<warName>connectedcup</warName>
</configuration>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,243 @@
/*
* 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.coffeeking.manager.service;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.wso2.carbon.apimgt.annotations.api.API;
import org.wso2.carbon.apimgt.annotations.device.DeviceType;
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.apimgt.AccessTokenInfo;
import org.wso2.carbon.device.mgt.iot.apimgt.TokenClient;
import org.wso2.carbon.device.mgt.iot.exception.AccessTokenException;
import javax.servlet.http.HttpServletResponse;
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.Response;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
@API( name="connectedcup_mgt", version="1.0.0", context="/connectedcup_mgt")
public class ConnectedCupManagerService {
private static Log log = LogFactory.getLog(ConnectedCupManagerService.class);
private static final String SUPER_TENANT = "carbon.super";
@Context
private HttpServletResponse response;
/**
* @param name
* @param owner
* @return
*/
@Path("cup/register")
@POST
public boolean register(@QueryParam("name") String name, @QueryParam("owner") String owner) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
String deviceId = shortUUID();
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
if (deviceManagement.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
response.setStatus(Response.Status.CONFLICT.getStatusCode());
return false;
}
Device device = new Device();
device.setDeviceIdentifier(deviceId);
EnrolmentInfo enrolmentInfo = new EnrolmentInfo();
enrolmentInfo.setDateOfEnrolment(new Date().getTime());
enrolmentInfo.setDateOfLastUpdate(new Date().getTime());
enrolmentInfo.setStatus(EnrolmentInfo.Status.ACTIVE);
enrolmentInfo.setOwnership(EnrolmentInfo.OwnerShip.BYOD);
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
enrolmentInfo.setOwner(owner);
device.setEnrolmentInfo(enrolmentInfo);
KeyGenerationUtil.createApplicationKeys(ConnectedCupConstants.DEVICE_TYPE);
TokenClient accessTokenClient = new TokenClient(ConnectedCupConstants.DEVICE_TYPE);
AccessTokenInfo accessTokenInfo = accessTokenClient.getAccessToken(owner, deviceId);
//create token
String accessToken = accessTokenInfo.getAccess_token();
String refreshToken = accessTokenInfo.getRefresh_token();
List<Device.Property> properties = new ArrayList<>();
Device.Property accessTokenProperty = new Device.Property();
accessTokenProperty.setName("accessToken");
accessTokenProperty.setValue(accessToken);
Device.Property refreshTokenProperty = new Device.Property();
refreshTokenProperty.setName("refreshToken");
refreshTokenProperty.setValue(refreshToken);
properties.add(accessTokenProperty);
properties.add(refreshTokenProperty);
device.setProperties(properties);
boolean added = deviceManagement.getDeviceManagementService().enrollDevice(device);
if (added) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return added;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} catch (AccessTokenException e) {
e.printStackTrace();
} finally {
deviceManagement.endTenantFlow();
}
return true;
}
@Path("/device/remove/{device_id}")
@DELETE
public void removeDevice(@PathParam("device_id") String deviceId,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
boolean removed = deviceManagement.getDeviceManagementService().disenrollDevice(
deviceIdentifier);
if (removed) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("/device/update/{device_id}")
@POST
public boolean updateDevice(@PathParam("device_id") String deviceId,
@QueryParam("name") String name,
@Context HttpServletResponse response) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(
deviceIdentifier);
device.setDeviceIdentifier(deviceId);
// device.setDeviceTypeId(deviceTypeId);
device.getEnrolmentInfo().setDateOfLastUpdate(new Date().getTime());
device.setName(name);
device.setType(ConnectedCupConstants.DEVICE_TYPE);
boolean updated = deviceManagement.getDeviceManagementService().modifyEnrollment(
device);
if (updated) {
response.setStatus(Response.Status.OK.getStatusCode());
} else {
response.setStatus(Response.Status.NOT_ACCEPTABLE.getStatusCode());
}
return updated;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return false;
} finally {
deviceManagement.endTenantFlow();
}
}
@Path("/device/{device_id}")
@GET
@Consumes("application/json")
@Produces("application/json")
public Device getDevice(@PathParam("device_id") String deviceId) {
DeviceManagement deviceManagement = new DeviceManagement(SUPER_TENANT);
DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
deviceIdentifier.setId(deviceId);
deviceIdentifier.setType(ConnectedCupConstants.DEVICE_TYPE);
try {
Device device = deviceManagement.getDeviceManagementService().getDevice(
deviceIdentifier);
return device;
} catch (DeviceManagementException e) {
response.setStatus(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
return null;
} finally {
deviceManagement.endTenantFlow();
}
}
private static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes(StandardCharsets.UTF_8)).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
}

@ -0,0 +1,34 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!--
This file defines class loading policy of the whole container. But this behaviour can be overridden by individual webapps by putting this file into the META-INF/ directory.
-->
<Classloading xmlns="http://wso2.org/projects/as/classloading">
<!-- Parent-first or child-first. Default behaviour is child-first.-->
<ParentFirst>false</ParentFirst>
<!--
Default environments that contains provides to all the webapps. This can be overridden by individual webapps by specifing required environments
Tomcat environment is the default and every webapps gets it even if they didn't specify it.
e.g. If a webapps requires CXF, they will get both Tomcat and CXF.
-->
<Environments>CXF,Carbon</Environments>
</Classloading>

@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="
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="ConnectedCupmanager" address="/connectedcup">
<jaxrs:serviceBeans>
<bean id="ConnectedCupManagerService"
class="org.coffeeking.manager.service.ConnectedCupManagerService">
</bean>
</jaxrs:serviceBeans>
<jaxrs:providers>
<bean class="org.codehaus.jackson.jaxrs.JacksonJsonProvider" />
</jaxrs:providers>
</jaxrs:server>
</beans>

@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>ConnectedCup-Webapp</display-name>
<servlet>
<description>JAX-WS/JAX-RS Endpoint</description>
<display-name>JAX-WS/JAX-RS Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<context-param>
<param-name>isAdminService</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>doAuthentication</param-name>
<param-value>false</param-value>
</context-param>
<!--publish to apim-->
<context-param>
<param-name>managed-api-enabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>managed-api-owner</param-name>
<param-value>admin</param-value>
</context-param>
<context-param>
<param-name>managed-api-context-template</param-name>
<param-value>/connectedcup/{version}</param-value>
</context-param>
<context-param>
<param-name>managed-api-application</param-name>
<param-value>connectedcup</param-value>
</context-param>
<context-param>
<param-name>managed-api-isSecured</param-name>
<param-value>true</param-value>
</context-param>
</web-app>

@ -0,0 +1,22 @@
package org.coffeeking.connectedcup.plugin.constants;
/**
* Created by menaka on 1/11/16.
*/
public class ConnectedCupConstants {
public final static String DEVICE_TYPE = "connectedcup";
public final static String DEVICE_PLUGIN_DEVICE_NAME = "DEVICE_NAME";
public final static String DEVICE_PLUGIN_DEVICE_ID = "CONNECTED_CUP_DEVICE_ID";
public final static String DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN = "accessToken";
public final static String DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN = "refreshToken";
public final static String ORDER_ON = "YES";
public final static String ORDER_OFF = "NO";
public static final String URL_PREFIX = "http://";
public static final String LEVEL_CONTEXT = "/LEVEL/";
public static final String TEMPERATURE_CONTEXT = "/TEMPERATURE/";
public static final String SENSOR_TEMPERATURE = "temperature";
public static final String SENSOR_LEVEL = "level";
}

@ -0,0 +1,122 @@
/*
* 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.coffeeking.connectedcup.plugin.impl.dao;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.connectedcup.plugin.impl.dao.impl.ConnectedCupDAOImpl;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactory;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOFactoryInterface;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class ConnectedCupDAO extends IotDeviceManagementDAOFactory
implements IotDeviceManagementDAOFactoryInterface {
private static final Log log = LogFactory.getLog(ConnectedCupDAO.class);
static DataSource dataSource;
private static ThreadLocal<Connection> currentConnection = new ThreadLocal<Connection>();
public ConnectedCupDAO() {
initFireAlarmDAO();
}
public static void initFireAlarmDAO() {
dataSource = getDataSourceMap().get(ConnectedCupConstants.DEVICE_TYPE);
}
@Override public IotDeviceDAO getIotDeviceDAO() {
return new ConnectedCupDAOImpl();
}
public static void beginTransaction() throws IotDeviceManagementDAOException {
try {
Connection conn = dataSource.getConnection();
conn.setAutoCommit(false);
currentConnection.set(conn);
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving datasource connection", e);
}
}
public static Connection getConnection() throws IotDeviceManagementDAOException {
if (currentConnection.get() == null) {
try {
currentConnection.set(dataSource.getConnection());
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while retrieving data source connection", e);
}
}
return currentConnection.get();
}
public static void commitTransaction() throws IotDeviceManagementDAOException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.commit();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence commit "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while committing the transaction", e);
} finally {
closeConnection();
}
}
public static void closeConnection() throws IotDeviceManagementDAOException {
Connection con = currentConnection.get();
if (con != null) {
try {
con.close();
} catch (SQLException e) {
log.error("Error occurred while close the connection");
}
}
currentConnection.remove();
}
public static void rollbackTransaction() throws IotDeviceManagementDAOException {
try {
Connection conn = currentConnection.get();
if (conn != null) {
conn.rollback();
} else {
if (log.isDebugEnabled()) {
log.debug("Datasource connection associated with the current thread is null, hence rollback "
+ "has not been attempted");
}
}
} catch (SQLException e) {
throw new IotDeviceManagementDAOException("Error occurred while rollback the transaction", e);
} finally {
closeConnection();
}
}
}

@ -0,0 +1,242 @@
/*
* 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.coffeeking.connectedcup.plugin.impl.dao.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.coffeeking.connectedcup.plugin.constants.ConnectedCupConstants;
import org.coffeeking.connectedcup.plugin.impl.dao.ConnectedCupDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceDAO;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.IotDeviceManagementDAOException;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dao.util.IotDeviceManagementDAOUtil;
import org.wso2.carbon.device.mgt.iot.util.iotdevice.dto.IotDevice;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Implements IotDeviceDAO for virtual firealarm Devices.
*/
public class ConnectedCupDAOImpl implements IotDeviceDAO {
private static final Log log = LogFactory.getLog(ConnectedCupDAOImpl.class);
@Override
public IotDevice getIotDevice(String iotDeviceId)
throws IotDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
IotDevice iotDevice = null;
ResultSet resultSet = null;
try {
conn = ConnectedCupDAO.getConnection();
String selectDBQuery =
"SELECT CONNECTED_CUP_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
" FROM CONNECTED_CUP_DEVICE WHERE CONNECTED_CUP_DEVICE_ID = ?";
stmt = conn.prepareStatement(selectDBQuery);
stmt.setString(1, iotDeviceId);
resultSet = stmt.executeQuery();
if (resultSet.next()) {
iotDevice = new IotDevice();
iotDevice.setIotDeviceName(resultSet.getString(
ConnectedCupConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<String, String>();
propertyMap.put(ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN, resultSet.getString("ACCESS_TOKEN"));
propertyMap.put(ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN, resultSet.getString("REFRESH_TOKEN"));
iotDevice.setDeviceProperties(propertyMap);
if (log.isDebugEnabled()) {
log.debug("Connected Cup service " + iotDeviceId + " data has been fetched from " +
"Connected Cup database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while fetching Connected Cup device : '" + iotDeviceId + "'";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
ConnectedCupDAO.closeConnection();
}
return iotDevice;
}
@Override
public boolean addIotDevice(IotDevice iotDevice)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectedCupDAO.getConnection();
String createDBQuery =
"INSERT INTO CONNECTED_CUP_DEVICE(CONNECTED_CUP_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN) VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(createDBQuery);
stmt.setString(1, iotDevice.getIotDeviceId());
stmt.setString(2, iotDevice.getIotDeviceName());
stmt.setString(3, iotDevice.getDeviceProperties().get(ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
stmt.setString(4, iotDevice.getDeviceProperties().get(ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN));
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Connected Cup device " + iotDevice.getIotDeviceId() + " data has been" +
" added to the Connected Cup database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while adding the Connected Cup device '" +
iotDevice.getIotDeviceId() + "' to the Connected Cup db.";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean updateIotDevice(IotDevice iotDevice)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectedCupDAO.getConnection();
String updateDBQuery =
"UPDATE CONNECTED_CUP_DEVICE SET DEVICE_NAME = ?, ACCESS_TOKEN=?, REFRESH_TOKEN=? WHERE CONNECTED_CUP_DEVICE_ID = ?";
stmt = conn.prepareStatement(updateDBQuery);
if (iotDevice.getDeviceProperties() == null) {
iotDevice.setDeviceProperties(new HashMap<String, String>());
}
stmt.setString(1, iotDevice.getIotDeviceName());
stmt.setString(2, iotDevice.getDeviceProperties().get(
ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
stmt.setString(3, iotDevice.getDeviceProperties().get(
ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN));
stmt.setString(4, iotDevice.getIotDeviceId());
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Connected Cup device " + iotDevice.getIotDeviceId() + " data has been" +
" modified.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while modifying the Connected Cup device '" +
iotDevice.getIotDeviceId() + "' data.";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public boolean deleteIotDevice(String iotDeviceId)
throws IotDeviceManagementDAOException {
boolean status = false;
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = ConnectedCupDAO.getConnection();
String deleteDBQuery =
"DELETE FROM CONNECTED_CUP_DEVICE WHERE CONNECTED_CUP_DEVICE_ID = ?";
stmt = conn.prepareStatement(deleteDBQuery);
stmt.setString(1, iotDeviceId);
int rows = stmt.executeUpdate();
if (rows > 0) {
status = true;
if (log.isDebugEnabled()) {
log.debug("Connected Cup device " + iotDeviceId + " data has deleted" +
" from the Connected Cup database.");
}
}
} catch (SQLException e) {
String msg = "Error occurred while deleting Connected Cup device " + iotDeviceId;
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, null);
}
return status;
}
@Override
public List<IotDevice> getAllIotDevices()
throws IotDeviceManagementDAOException {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet resultSet = null;
IotDevice iotDevice;
List<IotDevice> iotDevices = new ArrayList<>();
try {
conn = ConnectedCupDAO.getConnection();
String selectDBQuery =
"SELECT CONNECTED_CUP_DEVICE_ID, DEVICE_NAME, ACCESS_TOKEN, REFRESH_TOKEN" +
"FROM CONNECTED_CUP_DEVICE";
stmt = conn.prepareStatement(selectDBQuery);
resultSet = stmt.executeQuery();
while (resultSet.next()) {
iotDevice = new IotDevice();
iotDevice.setIotDeviceId(resultSet.getString(ConnectedCupConstants.DEVICE_PLUGIN_DEVICE_ID));
iotDevice.setIotDeviceName(resultSet.getString(ConnectedCupConstants.DEVICE_PLUGIN_DEVICE_NAME));
Map<String, String> propertyMap = new HashMap<>();
propertyMap.put(ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_ACCESS_TOKEN,
resultSet.getString("ACCESS_TOKEN"));
propertyMap.put(ConnectedCupConstants.DEVICE_PLUGIN_PROPERTY_REFRESH_TOKEN,
resultSet.getString("REFRESH_TOKEN"));
iotDevice.setDeviceProperties(propertyMap);
iotDevices.add(iotDevice);
}
if (log.isDebugEnabled()) {
log.debug("All Connected Cup device details have fetched from Connected Cup database.");
}
return iotDevices;
} catch (SQLException e) {
String msg = "Error occurred while fetching all Connected Cup device data'";
log.error(msg, e);
throw new IotDeviceManagementDAOException(msg, e);
} finally {
IotDeviceManagementDAOUtil.cleanupResources(stmt, resultSet);
ConnectedCupDAO.closeConnection();
}
}
}

@ -0,0 +1,45 @@
/*
* 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.coffeeking.connectedcup.plugin.impl.dao.util;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Map;
/**
* Contains utility methods used by FireAlarm plugin.
*/
public class ConnectedCupUtils {
private static Log log = LogFactory.getLog(ConnectedCupUtils.class);
public static String getDeviceProperty(Map<String, String> deviceProperties, String property) {
String deviceProperty = deviceProperties.get(property);
if (deviceProperty == null) {
return "";
}
return deviceProperty;
}
}

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<eventReceiver name="EventReceiver_coffeelevel" statistics="disable" trace="disable"
xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.coffeelevel" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventreceiver_coffeelevel" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>Eventreceiver_coffeelevel.xml</file>
</artifact>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventstore_coffeelevel" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_coffeelevel.xml</file>
</artifact>

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.coffeelevel:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>coffeelevel</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventstream_coffeelevel" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.coffeelevel_1.0.0.json</file>
</artifact>

@ -0,0 +1,20 @@
{
"name": "org.wso2.iot.devices.coffeelevel",
"version": "1.0.0",
"nickName": "Coffee Level Data",
"description": "Coffee Level data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{
"name": "coffeelevel","type": "FLOAT"
}
]
}

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Analytics>
<Name>IoTServer_Sensor_Script</Name>
<Script>
CREATE TEMPORARY TABLE DeviceCoffeeLevelData USING CarbonAnalytics OPTIONS(tableName
"ORG_WSO2_IOT_DEVICES_COFFEELEVEL");
CREATE TEMPORARY TABLE DeviceCoffeeLevelSummaryData USING CarbonAnalytics OPTIONS (tableName
"DEVICE_COFFEE_LEVEL_SUMMARY", schema "coffeelevel FLOAT, deviceType STRING -i, deviceId STRING -i, owner
STRING -i,
time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DeviceCoffeeLevelSummaryData select coffeelevel, meta_deviceType as deviceType,
meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from
DeviceCoffeeLevelData group by coffeelevel, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as
BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Sparkscripts" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>CoffeeLevel_Sensor_Script.xml</file>
</artifact>

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifacts>
<artifact name="CoffeeLevel_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="Eventstream_coffeelevel" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventstore_coffeelevel" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventreceiver_coffeelevel" version="1.0.0" include="true"
serverRole="DataAnalyticsServer"/>
<dependency artifact="Sparkscripts" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<eventReceiver name="EventReceiver_temperature" statistics="disable" trace="disable" xmlns="http://wso2.org/carbon/eventreceiver">
<from eventAdapterType="wso2event">
<property name="events.duplicated.in.cluster">false</property>
</from>
<mapping customMapping="disable" type="wso2event"/>
<to streamName="org.wso2.iot.devices.temperature" version="1.0.0"/>
</eventReceiver>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventreceiver_temperature" version="1.0.0" type="event/receiver" serverRole="DataAnalyticsServer">
<file>EventReceiver_temperature.xml</file>
</artifact>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventstore_temperature" version="1.0.0" type="analytics/eventstore" serverRole="DataAnalyticsServer">
<file>org_wso2_iot_devices_temperature.xml</file>
</artifact>

@ -0,0 +1,44 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<EventStoreConfiguration>
<Source>
<StreamId>org.wso2.iot.devices.temperature:1.0.0</StreamId>
</Source>
<RecordStoreName>EVENT_STORE</RecordStoreName>
<TableSchema>
<ColumnDefinition>
<Name>meta_owner</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceType</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_deviceId</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>STRING</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>meta_time</Name>
<EnableIndexing>true</EnableIndexing>
<IsPrimaryKey>true</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>LONG</Type>
</ColumnDefinition>
<ColumnDefinition>
<Name>temperature</Name>
<EnableIndexing>false</EnableIndexing>
<IsPrimaryKey>false</IsPrimaryKey>
<EnableScoreParam>false</EnableScoreParam>
<Type>FLOAT</Type>
</ColumnDefinition>
</TableSchema>
</EventStoreConfiguration>

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Eventstream_temperature" version="1.0.0" type="event/stream" serverRole="DataAnalyticsServer">
<file>org.wso2.iot.devices.temperature_1.0.0.json</file>
</artifact>

@ -0,0 +1,20 @@
{
"name": "org.wso2.iot.devices.temperature",
"version": "1.0.0",
"nickName": "Temperature Data",
"description": "Temperature data received from the Device",
"metaData": [
{"name":"owner","type":"STRING"},
{"name":"deviceType","type":"STRING"},
{"name":"deviceId","type":"STRING"},
{"name":"time","type":"LONG"}
],
"payloadData": [
{
"name": "temperature","type": "FLOAT"
}
]
}

@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Analytics>
<Name>IoTServer_Sensor_Script</Name>
<Script>
CREATE TEMPORARY TABLE DeviceTemperatureData USING CarbonAnalytics OPTIONS(tableName "ORG_WSO2_IOT_DEVICES_TEMPERATURE");
CREATE TEMPORARY TABLE DeviceTemperatureSummaryData USING CarbonAnalytics OPTIONS (tableName "DEVICE_TEMPERATURE_SUMMARY", schema "temperature FLOAT, deviceType STRING -i, deviceId STRING -i, owner STRING -i, time LONG -i",primaryKeys "deviceType, deviceId, owner, time");
insert overwrite table DeviceTemperatureSummaryData select temperature, meta_deviceType as deviceType, meta_deviceId as deviceId, meta_owner as owner, cast(meta_time/1000 as BIGINT)as time from DeviceTemperatureData group by temperature, meta_deviceType, meta_deviceId, meta_owner, cast(meta_time/1000 as BIGINT);
</Script>
<CronExpression>0 * * * * ?</CronExpression>
</Analytics>

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifact name="Sparkscripts" version="1.0.0" type="analytics/spark" serverRole="DataAnalyticsServer">
<file>Temperature_Sensor_Script.xml</file>
</artifact>

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<artifacts>
<artifact name="IoTServer_Sensors_CAPP" version="1.0.0" type="carbon/application">
<dependency artifact="Eventstream_temperature" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventstore_temperature" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Eventreceiver_temperature" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
<dependency artifact="Sparkscripts" version="1.0.0" include="true" serverRole="DataAnalyticsServer"/>
</artifact>
</artifacts>

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<project name="create-sample-sensor-capps" default="zip" basedir="">
<property name="project-name" value="${ant.project.name}"/>
<property name="target-dir"
value="../connectedcup-feature/src/main/resources/carbonapps"/>
<property name="Temperature_Sensor_dir" value="Temperature_Sensor"/>
<property name="CoffeeLevel_Sensor_dir" value="CoffeeLevel_Sensor"/>
<target name="clean">
<delete dir="${target-dir}" />
</target>
<target name="zip" depends="clean">
<mkdir dir="${target-dir}"/>
<zip destfile="${target-dir}/${Temperature_Sensor_dir}.car">
<zipfileset dir="${Temperature_Sensor_dir}"/>
</zip>
<zip destfile="${target-dir}/${CoffeeLevel_Sensor_dir}.car">
<zipfileset dir="${CoffeeLevel_Sensor_dir}"/>
</zip>
</target>
</project>

@ -0,0 +1,72 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
# 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.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>connected-cup-feature-parent</artifactId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.analytics</artifactId>
<packaging>pom</packaging>
<version>1.9.2-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Analytics</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Analytics</description>
<url>http://wso2.org</url>
<build>
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.4.1</version>
<executions>
<execution>
<id>auto-clean</id>
<phase>initialize</phase>
<goals>
<goal>clean</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>process-resources</phase>
<configuration>
<target>
<ant antfile="build.xml" target="zip"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,248 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>connected-cup-feature-parent</artifactId>
<version>1.9.2-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>org.coffeeking.connectedcup.feature</artifactId>
<packaging>pom</packaging>
<version>1.9.2-SNAPSHOT</version>
<name>WSO2 IoTS(Device Types) - Connected Cup Feature</name>
<description>WSO2 IoTS(Device Types) - Connected Cup Feature</description>
<url>http://wso2.org</url>
<dependencies>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.connectedcup.plugin</artifactId>
<version>1.9.2-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.manager.service</artifactId>
<version>1.9.2-SNAPSHOT</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.controller.service</artifactId>
<version>1.9.2-SNAPSHOT</version>
<type>war</type>
</dependency>
<dependency>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeking.agent</artifactId>
<version>1.9.2-SNAPSHOT</version>
<type>war</type>
</dependency>
<dependency>
<groupId>com.h2database.wso2</groupId>
<artifactId>h2-database-engine</artifactId>
<version>1.2.140.wso2v3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<executions>
<execution>
<id>copy-resources</id>
<phase>generate-resources</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>src/main/resources</outputDirectory>
<resources>
<resource>
<directory>resources</directory>
<includes>
<include>build.properties</include>
<include>p2.inf</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy-jaxrs-manager-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.manager.service</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${basedir}/src/main/resources/webapps/</outputDirectory>
<destFileName>connectedcup_mgt.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-controller-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeeking.controller.service</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${basedir}/src/main/resources/webapps/</outputDirectory>
<destFileName>connectedcup.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
<execution>
<id>copy-jaxrs-agent-war</id>
<phase>package</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>org.wso2.carbon.devicemgt-plugins</groupId>
<artifactId>org.coffeking.agent</artifactId>
<type>war</type>
<overWrite>true</overWrite>
<outputDirectory>${basedir}/src/main/resources/webapps/</outputDirectory>
<destFileName>connected-cup-agent.war</destFileName>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<!-- Creating Connected Cup Plugin Management schema -->
<id>create-connected-cup-plugin-mgt-schema</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo
message="########### Create Connected Cup plugin Management H2 Schema ###########"/>
<property name="db.dir"
value="src/main/resources/database"/>
<property name="userid" value="wso2carbon"/>
<property name="password" value="wso2carbon"/>
<property name="dbURL"
value="jdbc:h2:file:${basedir}/${db.dir}/ConnectedCupDM_DB;DB_CLOSE_ON_EXIT=FALSE"/>
<mkdir dir="${basedir}/${db.dir}"/>
<sql driver="org.h2.Driver" url="${dbURL}" userid="${userid}"
password="${password}"
autocommit="true" onerror="continue">
<classpath refid="maven.dependency.classpath"/>
<classpath refid="maven.compile.classpath"/>
<classpath refid="maven.runtime.classpath"/>
<fileset file="${basedir}/src/main/resources/dbscripts/h2.sql"/>
</sql>
<echo message="##################### END ####################"/>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.wso2.maven</groupId>
<artifactId>carbon-p2-plugin</artifactId>
<executions>
<execution>
<id>p2-feature-generation</id>
<phase>package</phase>
<goals>
<goal>p2-feature-gen</goal>
</goals>
<configuration>
<id>org.coffeeking.connectedcup</id>
<propertiesFile>../../../features/etc/feature.properties</propertiesFile>
<adviceFile>
<properties>
<propertyDef>org.wso2.carbon.p2.category.type:server</propertyDef>
<propertyDef>org.eclipse.equinox.p2.type.group:false</propertyDef>
</properties>
</adviceFile>
<bundles>
<bundleDef>
org.wso2.carbon.devicemgt-plugins:org.coffeeking.connectedcup.plugin:${carbon.iot.device.mgt.version}
</bundleDef>
</bundles>
<importFeatures>
<importFeatureDef>org.wso2.carbon.core.server:${carbon.kernel.version}
</importFeatureDef>
<importFeatureDef>org.wso2.carbon.device.mgt.server:${carbon.device.mgt.version}
</importFeatureDef>
</importFeatures>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

@ -0,0 +1,29 @@
#
# 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]
owner=${DEVICE_OWNER}
deviceId=${DEVICE_ID}
device-name=${DEVICE_NAME}
controller-context=/digital_display/controller
mqtt-ep=${MQTT_EP}
auth-method=token
auth-token=${DEVICE_TOKEN}
refresh-token=${DEVICE_REFRESH_TOKEN}
push-interval=15

@ -0,0 +1,2 @@
templates=deviceConfig.properties
zipfilename=DigitalDisplayAgent.zip

@ -0,0 +1,190 @@
#!/bin/bash
echo "----------------------------------------------------------------"
echo "| WSO2 IOT Sample "
echo "| Virtual RaspiAlarm "
echo "| ---------------- "
echo "| ....initializing startup-script "
echo "----------------------------------------------------------------"
#while true; do
# read -p "What is the network-interface of your device that the Agent should use (find from ifconfig. ex: wlan0,en0,eth0..) > " interface
#
# echo "Setting the network-interface to " $interface
# sed s/^network-interface=.*/network-interface=$interface/ deviceConfig.properties > myTmp
# mv -f myTmp deviceConfig.properties
# break;
#done
#
#while true; do
# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-IoT-Server (ex: '60' indicates 1 minute) > " interval
#
# if [ $interval -eq $interval 2>/dev/null ]
# then
# echo "Setting data-push interval to " $interval " seconds."
# sed s/^push-interval=.*/push-interval=$interval/ deviceConfig.properties > myTmp
# mv -f myTmp deviceConfig.properties
# break;
# else
# echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
# fi
#done
#java -jar wso2-firealarm-virtual-agent-advanced.jar
#while true; do
# read -p "Do you wish to run 'apt-get update' and continue? [Yes/No] " yn
# case $yn in
# [Yy]* ) sudo apt-get update;
# break;;
# [Nn]* ) echo "Continuing without apt-get update...";
# break;;
# * ) echo "Please answer yes or no.";
# esac
#done
#
#if [ $? -ne 0 ]; then
# echo "apt-get update failed.... Some dependencies may not get installed"
# echo "If an already installed version of the package exists, try running:"
# echo "----------------------------------------------------------------"
# echo "sudo -i"
# echo "cd /var/lib/dpkg/info"
# echo "rm -rf wso2-raspi-alarm*"
# echo "dpkg --remove --force-remove-reinstreq wso2-raspi-alarm"
# echo "exit"
# echo "----------------------------------------------------------------"
# echo "Retry Installation...."
# break;
#fi
#
#echo "Installing 'gdebi' package..."
#sudo apt-get install gdebi # installation of gdebi
#
#
#if [ $? -ne 0 ]; then
# echo "gdebi installation failed.... dependencies will not be installed without gdebi"
# read -p "Do you wish to continue without gdebi? [Yes/No] " yn
# case $yn in
# [Yy]* ) echo "Continueing without gdebi.....";;
# [Nn]* ) echo "Try to resolve errors and re-run the script.";
# exit;;
# * ) exit;;
# esac
#fi
#
#
#for f in ./wso2-raspi-alarm_1.0_armhf.deb; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit;
# if [ -e "$f" ]; then
# echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing now...."
# else
# echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path. \nExiting installation...";
# exit;
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#echo "Installing the 'wso2-raspi-alarm deb package'"
#sudo gdebi wso2-raspi-alarm_1.0_armhf.deb
#
#if [ $? -ne 0 ]; then
# echo "Installation Failed...."
# exit;
#fi
#sudo killall -9 python
#
#for f in ./RaspberryAgent.zip; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# # [ -e "$f" ] && echo "'wso2-raspi-alarm_1.0_armhf.deb' file found and installing" || echo "'wso2-raspi-alarm_1.0_armhf.deb' file does not exist in current path"; exit;
# if [ -e "$f" ]; then
# echo "Agent files found......"
# sudo rm -rf /usr/local/src/RaspberryAgent
# sudo unzip RaspberryAgent.zip -d /usr/local/src/
# else
# echo "'RaspberryAgent.zip' file does not exist in current path. \nInstalling without upgrading agent...";
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#for f in /usr/local/src/RaspberryAgent/rc.local; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# if [ -e "$f" ]; then
# echo "Copying boot script"
# sudo mv /usr/local/src/RaspberryAgent/rc.local /etc/rc.local
# sudo chmod +x /etc/rc.local
# else
# echo "Unable to set agent statup on boot";
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#for f in ./deviceConfigs.cfg; do
# ## Check if the glob gets expanded to existing files.
# ## If not, f here will be exactly the pattern above
# ## and the exists test will evaluate to false.
# if [ -e "$f" ]; then
# echo "Configuration file found......"
# else
# echo "'deviceConfigs.cfg' file does not exist in current path. \nExiting installation...";
# exit;
# fi
# ## This is all we needed to know, so we can break after the first iteration
# break
#done
#
#echo "Altering Configuration file"
#sed -i 's|[/,]||g' deviceConfigs.cfg
#
#echo "Copying configurations file to /usr/local/src/RaspberryAgent"
#sudo cp ./deviceConfigs.cfg /usr/local/src/RaspberryAgent/
#
#if [ $? -ne 0 ]; then
# echo "Copying configuration file failed...."
# exit;
#fi
#
#while true; do
# read -p "Whats the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute) > " input
#
# if [ $input -eq $input 2>/dev/null ]
# then
# echo "Setting data-push interval to $input seconds."
# echo $input > /usr/local/src/RaspberryAgent/time-interval
# break;
# else
# echo "Input needs to be an integer indicating the number seconds between successive data-pushes."
# fi
#done
#
#cd /usr/local/src/RaspberryAgent/
#sudo chmod +x RaspberryStats.py
#sudo nohup ./RaspberryStats.py -i $input </dev/null &
#
#if [ $? -ne 0 ]; then
# echo "Could not start the service..."
# exit;
#else
# echo "Running the RaspberryAgent service...."
#fi
#
#echo "--------------------------------------------------------------------------"
#echo "| Successfully Started "
#echo "| -------------------------- "
#echo "| cd to /usr/local/src/RaspberryAgent"
#echo "| run 'sudo nohup ./RaspberryStats.py -i time </dev/null &'to start service manually."
#echo "| Relapce time with the time-interval (in seconds) between successive Data-Pushes to the WSO2-DC (ex: '60' indicates 1 minute)"
#echo "| Find logs at: /usr/local/src/RaspberryAgent/logs/RaspberryStats.log"
#echo "---------------------------------------------------------------------------"

@ -0,0 +1,30 @@
{
"deviceType": {
"label": "Connected Cup",
"category": "virtual",
},
"analyticStreams": [
{
"name": "Temperature",
"table": "DEVICE_TEMPERATURE_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"TEMPERATURE", "label":"Temperature", "ui-mapping":"y-axis"}}
]
}
},
{
"name": "Coffee Level",
"table": "DEVICE_COFFEELEVEL_SUMMARY",
"ui_unit": {
"name": "cdmf.unit.analytics.line-chart",
"data":[
{"column": {"name":"TIME", "label":"time", "ui-mapping":"x-axis"}},
{"column": {"name":"COFFEELEVEL", "label":"Coffeelevel", "ui-mapping":"y-axis"}}
]
}
}
]
}

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
~
~ WSO2 Inc. licenses this file to you under the Apache License,
~ Version 2.0 (the "License"); you may not use this file except
~ in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<DeviceTypeConfigurations>
<DeviceTypeConfig type="connectedcup">
<DatasourceName>jdbc/ConnectedCupDM_DB</DatasourceName>
<!--ApiApplicationName>firealarm</ApiApplicationName-->
</DeviceTypeConfig>
</DeviceTypeConfigurations>

@ -0,0 +1,46 @@
<!--
~ 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.
-->
<datasources-configuration xmlns:svns="http://org.wso2.securevault/configuration">
<providers>
<provider>org.wso2.carbon.ndatasource.rdbms.RDBMSDataSourceReader</provider>
</providers>
<datasources>
<datasource>
<name>ConnectedCupDM_DB</name>
<description>The datasource used for the Connected Cup database</description>
<jndiConfig>
<name>jdbc/ConnectedCupDM_DB</name>
</jndiConfig>
<definition type="RDBMS">
<configuration>
<url>jdbc:h2:repository/database/ConnectedCupDM_DB;DB_CLOSE_ON_EXIT=FALSE
</url>
<username>wso2carbon</username>
<password>wso2carbon</password>
<driverClassName>org.h2.Driver</driverClassName>
<maxActive>50</maxActive>
<maxWait>60000</maxWait>
<testOnBorrow>true</testOnBorrow>
<validationQuery>SELECT 1</validationQuery>
<validationInterval>30000</validationInterval>
</configuration>
</definition>
</datasource>
</datasources>
</datasources-configuration>

@ -0,0 +1,13 @@
-- -----------------------------------------------------
-- Table `CONNECTED_CUP_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `CONNECTED_CUP_DEVICE` (
`CONNECTED_CUP_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
`ACCESS_TOKEN` VARCHAR(50) NOT NULL,
`REFRESH_TOKEN` VARCHAR(50) NOT NULL,
PRIMARY KEY (`CONNECTED_CUP_DEVICE_ID`) );

@ -0,0 +1,14 @@
-- -----------------------------------------------------
-- Table `CONNECTED_CUP_DEVICE`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `CONNECTED_CUP_DEVICE` (
`CONNECTED_CUP_DEVICE_ID` VARCHAR(45) NOT NULL ,
`DEVICE_NAME` VARCHAR(100) NULL DEFAULT NULL,
`ACCESS_TOKEN` VARCHAR(50) NOT NULL,
`REFRESH_TOKEN` VARCHAR(50) NOT NULL,
PRIMARY KEY (`CONNECTED_CUP_DEVICE_ID`) )
ENGINE = InnoDB;

@ -0,0 +1,100 @@
{{#zone "topCss"}}
<style>
.thumbnail.icon:before {
padding-top: 0;
}
</style>
{{/zone}}
{{#zone "device-thumbnail"}}
<img src="{{@unit.publicUri}}/images/thumb.png"/>
{{/zone}}
{{#zone "device-opetations"}}
<div style="background: #11375B; color: #fff; padding: 10px; margin-bottom: 5px">
Operations
</div>
<div class="add-margin-top-4x">
<div class="add-margin-top-4x">
<div class="buttons">
<a class="btn-operations" target="_blank" href="https://localhost:9443/connected-cup-agent/index.jsp?deviceOwner={{@user.username}}&deviceId={{../device.deviceIdentifier}}&token={{../device.accessToken}}" >Go To Device</a>
</div>
</div>
</div>
{{/zone}}
{{#zone "device-detail-properties"}}
<div class="media">
<div class="media-left col-xs-12 col-sm-2 col-md-2 col-lg-2">
<ul class="list-group" role="tablist">
<li class="active"><a class="list-group-item" href="#device_statistics" role="tab"
data-toggle="tab" aria-controls="device_statistics">Device
Statistics</a>
</li>
<li><a class="list-group-item" href="#policy_compliance" role="tab"
data-toggle="tab" aria-controls="policy_compliance">Policy Compliance</a>
</li>
<li><a class="list-group-item" href="#event_log" role="tab" data-toggle="tab"
aria-controls="event_log">Operations Log</a></li>
</ul>
</div>
<div class="media-body add-padding-left-5x remove-padding-xs tab-content">
<div class="panel-group tab-content">
<div class="panel panel-default tab-pane active"
id="device_statistics" role="tabpanel" aria-labelledby="device_statistics">
<div class="panel-heading">Device Statistics</div>
{{unit "iot.unit.device.stats" device=device}}
</div>
<div class="panel panel-default tab-pane" id="policy_compliance" role="tabpanel"
aria-labelledby="policy_compliance">
<div class="panel-heading">Policy Compliance <span><a href="#"
id="refresh-policy"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="policy-spinner" class="wr-advance-operations-init hidden">
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<i class="fw fw-settings fw-spin fw-2x"></i>
&nbsp;&nbsp;&nbsp;
Loading Policy Compliance . . .
<br>
<br>
</div>
<div id="policy-list-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
<div class="panel panel-default tab-pane" id="event_log" role="tabpanel"
aria-labelledby="event_log">
<div class="panel-heading">Operations Log <span><a href="#"
id="refresh-operations"><i
class="fw fw-refresh"></i></a></span></div>
<div class="panel-body">
<div id="operations-spinner" class="wr-advance-operations-init hidden">
<br>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<i class="fw fw-settings fw-spin fw-2x"></i>
&nbsp;&nbsp;&nbsp;
Loading Operations Log . . .
<br>
<br>
</div>
<div id="operations-log-container">
<div class="panel-body">
Not available yet
</div>
<br class="c-both"/>
</div>
</div>
</div>
</div>
</div>
</div>
{{/zone}}

@ -0,0 +1,36 @@
/*
* 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.
*/
function onRequest(context) {
var log = new Log("detail.js");
var deviceType = context.uriParams.deviceType;
var deviceId = request.getParameter("id");
if (deviceType != null && deviceType != undefined && deviceId != null && deviceId != undefined) {
var deviceModule = require("/app/modules/device.js").deviceModule;
var device = deviceModule.viewDevice(deviceType, deviceId);
if (device && device.status != "error") {
log.info(device);
var deviceProperties = device.properties;
device.accessToken = deviceProperties.accessToken
return {"device": device};
}
}
}

@ -0,0 +1,208 @@
/*
* 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.
*
*
*/
var modalPopup = ".wr-modalpopup";
var modalPopupContainer = modalPopup + " .modalpopup-container";
var modalPopupContent = modalPopup + " .modalpopup-content";
var body = "body";
/*
* set popup maximum height function.
*/
function setPopupMaxHeight() {
$(modalPopupContent).css('max-height', ($(body).height() - ($(body).height() / 100 * 30)));
$(modalPopupContainer).css('margin-top', (-($(modalPopupContainer).height() / 2)));
}
/*
* show popup function.
*/
function showPopup() {
$(modalPopup).show();
setPopupMaxHeight();
$('#downloadForm').validate({
rules: {
deviceName: {
minlength: 4,
required: true
}
},
highlight: function (element) {
$(element).closest('.control-group').removeClass('success').addClass('error');
},
success: function (element) {
$(element).closest('.control-group').removeClass('error').addClass('success');
$('label[for=deviceName]').remove();
}
});
var deviceType = "";
$('.deviceType').each(function () {
if (this.value != "") {
deviceType = this.value;
}
});
if (deviceType == 'digitaldisplay'){
$('.sketchType').remove();
$('input[name="sketchType"][value="digitaldisplay"]').prop('checked', true);
$("label[for='digitaldisplay']").text("Simple Agent");
}else{
$('.sketchTypes').remove();
}
}
/*
* hide popup function.
*/
function hidePopup() {
$('label[for=deviceName]').remove();
$('.control-group').removeClass('success').removeClass('error');
$(modalPopupContent).html('');
$(modalPopup).hide();
}
/*
* DOM ready functions.
*/
$(document).ready(function () {
attachEvents();
});
function attachEvents() {
/**
* Following click function would execute
* when a user clicks on "Download" link
* on Device Management page in WSO2 DC Console.
*/
$("a.download-link").click(function () {
var sketchType = $(this).data("sketchtype");
var deviceType = $(this).data("devicetype");
var downloadDeviceAPI = "/devicemgt/api/devices/sketch/generate_link";
var payload = {"sketchType": sketchType, "deviceType": deviceType};
$(modalPopupContent).html($('#download-device-modal-content').html());
showPopup();
var deviceName;
$("a#download-device-download-link").click(function () {
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
$('label[for=deviceName]').remove();
if (deviceName && deviceName.length >= 4) {
payload.deviceName = deviceName;
invokerUtil.post(
downloadDeviceAPI,
payload,
function (data, textStatus, jqxhr) {
doAction(data);
},
function (data) {
doAction(data);
}
);
}else if(deviceName){
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">Please enter at least 4 characters.</label>');
$('.control-group').removeClass('success').addClass('error');
} else {
$('.controls').append('<label for="deviceName" generated="true" class="error" style="display: inline-block;">This field is required.</label>');
$('.control-group').removeClass('success').addClass('error');
}
});
$("a#download-device-cancel-link").click(function () {
hidePopup();
});
});
}
function downloadAgent() {
//$('#downloadForm').submit();
var $inputs = $('#downloadForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
console.log($inputs);
console.log($inputs[0].value);
console.log($inputs[1].value);
var payload = {}
payload.name = $inputs[0].value;
payload.owner = $inputs[1].value;
invokerUtil.post(
"/connectedcup_mgt/connectedcup/cup/register?name=" + payload.name + "&owner=" + payload.owner,
payload,
function (data, textStatus, jqxhr) {
hidePopup();
},
function (data) {
hidePopup();
}
);
var deviceName;
$('.new-device-name').each(function () {
if (this.value != "") {
deviceName = this.value;
}
});
if (deviceName && deviceName.length >= 4) {
setTimeout(function () {
hidePopup();
}, 1000);
}
}
function doAction(data) {
//if it is saml redirection response
if (data.status == null) {
document.write(data);
}
if (data.status == "200") {
$(modalPopupContent).html($('#download-device-modal-content-links').html());
$("input#download-device-url").val(data.responseText);
$("input#download-device-url").focus(function () {
$(this).select();
});
showPopup();
} else if (data.status == "401") {
$(modalPopupContent).html($('#device-401-content').html());
$("#device-401-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else if (data == "403") {
$(modalPopupContent).html($('#device-403-content').html());
$("#device-403-link").click(function () {
window.location = "/devicemgt/login";
});
showPopup();
} else {
$(modalPopupContent).html($('#device-unexpected-error-content').html());
$("a#device-unexpected-error-link").click(function () {
hidePopup();
});
}
}

@ -0,0 +1,256 @@
<div class="col-lg-12 margin-top-double" xmlns="http://www.w3.org/1999/html">
<h1 class="grey ">Connected Cup</h1>
<hr>
<p class="margin-bottom-double light-grey ">Connected Coffee Cups from CoffeeKing</p>
</div>
<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 padding-top">
<img src="{{@unit.publicUri}}/images/coffeecup.png" class="img-responsive">
</div>
<div class="col-xs-12 col-sm-6 col-md-8 col-lg-8 padding-top">
<h3 class="uppercase">Ingredients</h3>
<hr>
<p class="grey margin-top">Hardware Requirements </p>
<br>
<ul>
<span class="fw-stack fw-lg margin-right">
<i class="fw fw-ring fw-stack-2x"> </i>
<i class="fw fw-right-arrow fw-stack-1x"></i>
</span> Coffee Cup <br/>
</ul>
<br>
<a href="/api-store/apis/info?name={{@uriParams.deviceType}}&version=1.0.0&provider=admin"
class="btn-operations" target="_blank"><i class="fw fw-api"></i> View API</i> &nbsp;</a>
<a href="#" class="download-link btn-operations"><i class="fw fw-download"></i>Create an Instance</a>
<div id="download-device-modal-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Name your device and download the agent from following link.</h3>
<br/>
<form id="downloadForm">
<div class="control-group">
<div class="controls">
<input class="connectedCupName" style="color:#3f3f3f;padding:5px"
type="text"
placeholder="Ex. Lobby_DigitalDisplay"
name="name" size="60" required>
<br/>
<input type="hidden" class="owner" name="owner" value={{@user.username}} />
</div>
</div>
<br/>
<div class="buttons">
<a class="btn-operations" onclick="downloadAgent()">Create an Instance</a>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="download-device-modal-content-links" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Please download the file from following link(Press CTRL+C).</h3>
<br/>
<div>
<input id="download-device-url" style="color:#3f3f3f;padding:5px"
type="text" value="" placeholder="Type here" size="60">
</div>
</div>
</div>
</div>
</div>
<div id="device-400-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Exception at backend. Try Later.</h3>
<div class="buttons">
<a href="#" id="device-400-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-401-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>You have to log in first.</h3><br/>
<div class="buttons">
<a href="#" id="device-401-link" class="blue-button">
&nbsp;&nbsp;&nbsp;&nbsp;Goto Login Page&nbsp;&nbsp;&nbsp;&nbsp;
</a>&nbsp;&nbsp;
<a href="#" onclick="hidePopup();" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;Cancel&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-403-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Action not permitted.</h3><br/>
<div class="buttons">
<a href="#" id="device-403-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-409-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Device Sketch does not exist.</h3><br/>
<div class="buttons">
<a href="#" id="device-409-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<div id="device-unexpected-error-content" class="hide">
<div class="modal-content">
<div class="row">
<div class="col-md-7 col-centered center-container">
<h3>Unexpected error.</h3><br/>
<div class="buttons">
<a href="#" id="device-unexpected-error-link" class="btn-operations">
&nbsp;&nbsp;&nbsp;&nbsp;OK&nbsp;&nbsp;&nbsp;&nbsp;
</a>
</div>
</div>
</div>
</div>
</div>
<br/><br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double grey-bg ">
<h3 class="uppercase">Prepare</h3><hr>
<p class="grey margin-top">Get your device ready</p>
<br/>
<ul>
<p class="padding-top-double"><span class="circle">01</span> Set up your RaspberryPi device as shown in the schematic below and get the Digital Display setup.</p>
<p class="padding-top-double"><span class="circle">02</span> Connect a monitor to your RaspberryPi via the HDMI cable to get a UI view of the device.</p>
<p class="padding-top-double"><span class="circle">03</span> Get the RaspberryPi to connect to the internet (via Ethernet or Wifi) and note its IP_ADDRESS</p>
</ul>
<br>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double">
<h3 class="uppercase">Schematic Diagram</h3><hr>
<p class="grey margin-top">Click on the image to zoom</p>
<center>
<a href="{{@unit.publicUri}}/images/schematicsGuide.png" target="_blank">
<img src="{{@unit.publicUri}}/images/schematicsGuide.png" class="img-responsive" style="max-width: 500px; max-height: 500px">
</a>
</center>
<br/>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-12 padding-double">
<h3 class="uppercase">Connect (Quick Start)</h3><hr>
<p class="grey margin-top">Internet of Things Foundation Quickstart connection</p>
<br/>
<ul>
<p class="padding-top-double"><span class="circle">01</span> <b>Click on the <i>'Create DEB'</i> button above to get the download link for the Digital Display setup files</b></p>
<p class="padding-top-double"><span class="circle">02</span> <i>(The following commands can be issued by directly typing into the terminal of the device or by an <b>'ssh'</b> login from a remote PC)</i></p>
<p class="padding-top-double"><span class="circle">03</span> <b>Download the Digital Display setup files using the following command: 'curl -k < url_link_received_from_the_above_step >> Agent.zip'</b><br/><i>This will download a zip file named 'Agent.zip'</i></p>
</ul>
<br>
</div>
</div>
<div id="qr-code-modal" data-enrollment-url="{{deviceType.enrollmentURL}}" class="hidden">
<div class="content">
<div class="row">
<div class="col-lg-5 col-md-6 col-centered">
<h3>
Scan QR code to start enrollment
</h3>
<h4>
Please scan the QR code using your mobile device to retrieve enrollment URL.
</h4>
<div class="panel panel-default">
<div class="panel-body col-centered ">
<div class="qr-code"></div>
</div>
</div>
</div>
</div>
</div>
</div>
<style type="text/css">
.circle {
background: none repeat scroll 0 0 #191919;
border-radius: 50px;
height: 50px;
padding: 10px;
width: 50px;
color: #fff;
}
.padding-top-double {
padding-top: 20px;
}
.padding-double {
padding: 20px;
}
.grey {
color: #333;
}
hr {
display: block;
height: 1px;
border: 0;
border-top: 1px solid #7f7f7f;
margin: 1em 0;
padding: 0;
opacity: 0.2;
}
.light-grey {
color: #7c7c7c;
}
.uppercase {
text-transform: uppercase;
}
.grey-bg {
background-color: #f6f4f4;
}
</style>
{{#zone "bottomJs"}}
{{js "/js/download.js"}}
{{js "/js/jquery.validate.js"}}
{{/zone}}

@ -0,0 +1,16 @@
instructions.configure = \
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../conf/device-types/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/configs/,target:${installFolder}/../../conf/device-types/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/webapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/webapps/,target:${installFolder}/../../deployment/server/webapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/carbonapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/carbonapps/,target:${installFolder}/../../deployment/server/carbonapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../resources/sketches/connectedcup/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/agent/,target:${installFolder}/../../resources/sketches/connectedcup/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/dbscripts/,target:${installFolder}/../../../dbscripts/cdm/plugins/connectedcup,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/datasources/,target:${installFolder}/../../conf/datasources/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../deployment/server/jaggeryapps/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/jaggeryapps/,target:${installFolder}/../../deployment/server/jaggeryapps/,overwrite:true);\
org.eclipse.equinox.p2.touchpoint.natives.mkdir(path:${installFolder}/../../database/);\
org.eclipse.equinox.p2.touchpoint.natives.copy(source:${installFolder}/../features/org.coffeeking.connectedcup_${feature.version}/database/,target:${installFolder}/../../database/,overwrite:true);\
Loading…
Cancel
Save