Search in sources :

Example 46 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class DevicesPage method viewDevice.

/**
 * This method performs the navigation to the Device view of the given device.
 * Here the navigation happens to the Connected cup device.
 * @param deviceName : Name of the device.
 * @return : The corresponding device view page. Null if not visible.
 */
public ConnectedCupDeviceViewPage viewDevice(String deviceName) throws IOException {
    WebElement deviceTable = driver.findElement(By.xpath(uiElementMapper.getElement("iot.devices.table.xpath")));
    List<WebElement> anchors = deviceTable.findElements(By.cssSelector("a"));
    for (WebElement element : anchors) {
        String connectedCupLink = getLink(element, "/device/connectedcup?id=");
        if (connectedCupLink != null) {
            driver.get(connectedCupLink);
            return new ConnectedCupDeviceViewPage(driver, deviceName);
        }
    }
    return null;
}
Also used : ConnectedCupDeviceViewPage(org.wso2.iot.integration.ui.pages.samples.ConnectedCupDeviceViewPage) WebElement(org.openqa.selenium.WebElement)

Example 47 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class DeviceTypeServiceImpl method register.

/**
 * Register device into device management service.
 *
 * @param deviceId unique identifier for given device type instance
 * @param name     name for the device type instance
 * @return check whether device is installed into cdmf
 */
private boolean register(String deviceId, String name) {
    try {
        DeviceIdentifier deviceIdentifier = new DeviceIdentifier();
        deviceIdentifier.setId(deviceId);
        deviceIdentifier.setType(DeviceTypeConstants.DEVICE_TYPE);
        if (APIUtil.getDeviceManagementService().isEnrolled(deviceIdentifier)) {
            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(DeviceTypeConstants.DEVICE_TYPE);
        enrolmentInfo.setOwner(APIUtil.getAuthenticatedUser());
        device.setEnrolmentInfo(enrolmentInfo);
        boolean added = APIUtil.getDeviceManagementService().enrollDevice(device);
        return added;
    } catch (DeviceManagementException e) {
        log.error(e.getMessage(), e);
        return false;
    }
}
Also used : DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) Device(org.wso2.carbon.device.mgt.common.Device) EnrolmentInfo(org.wso2.carbon.device.mgt.common.EnrolmentInfo) Date(java.util.Date) DeviceIdentifier(org.wso2.carbon.device.mgt.common.DeviceIdentifier)

Example 48 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class DeviceTypeServiceImpl method createDownloadFile.

private ZipArchive createDownloadFile(String owner, String deviceName, String sketchType) throws DeviceManagementException, JWTClientException, APIManagerException, UserStoreException {
    // create new device id
    String deviceId = shortUUID();
    if (apiApplicationKey == null) {
        String applicationUsername = PrivilegedCarbonContext.getThreadLocalCarbonContext().getUserRealm().getRealmConfiguration().getAdminUserName();
        applicationUsername = applicationUsername + "@" + APIUtil.getAuthenticatedUserTenantDomain();
        APIManagementProviderService apiManagementProviderService = APIUtil.getAPIManagementProviderService();
        String[] tags = { DeviceTypeConstants.DEVICE_TYPE };
        apiApplicationKey = apiManagementProviderService.generateAndRetrieveApplicationKeys(DeviceTypeConstants.DEVICE_TYPE, tags, KEY_TYPE, applicationUsername, true, "3600");
    }
    JWTClient jwtClient = APIUtil.getJWTClientManagerService().getJWTClient();
    String scopes = "device_type_" + DeviceTypeConstants.DEVICE_TYPE + " device_" + deviceId;
    AccessTokenInfo accessTokenInfo = jwtClient.getAccessToken(apiApplicationKey.getConsumerKey(), apiApplicationKey.getConsumerSecret(), owner + "@" + APIUtil.getAuthenticatedUserTenantDomain(), scopes);
    // create token
    String accessToken = accessTokenInfo.getAccessToken();
    String refreshToken = accessTokenInfo.getRefreshToken();
    boolean status = register(deviceId, deviceName);
    if (!status) {
        String msg = "Error occurred while registering the device with " + "id: " + deviceId + " owner:" + owner;
        throw new DeviceManagementException(msg);
    }
    ZipUtil ziputil = new ZipUtil();
    ZipArchive zipFile = ziputil.createZipFile(owner, APIUtil.getTenantDomainOftheUser(), sketchType, deviceId, deviceName, accessToken, refreshToken, apiApplicationKey.toString());
    return zipFile;
}
Also used : AccessTokenInfo(org.wso2.carbon.identity.jwt.client.extension.dto.AccessTokenInfo) DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) APIManagementProviderService(org.wso2.carbon.apimgt.application.extension.APIManagementProviderService) JWTClient(org.wso2.carbon.identity.jwt.client.extension.JWTClient) ZipUtil(org.wso2.iot.sampledevice.api.util.ZipUtil) ZipArchive(org.wso2.iot.sampledevice.api.util.ZipArchive)

Example 49 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class DeviceTypeServiceImpl method changeStatus.

/**
 * @param deviceId unique identifier for given device type instance
 * @param state    change status of sensor: on/off
 */
@Path("device/{deviceId}/change-status")
@POST
public Response changeStatus(@PathParam("deviceId") String deviceId, @QueryParam("state") String state, @Context HttpServletResponse response) {
    try {
        if (!APIUtil.getDeviceAccessAuthorizationService().isUserAuthorized(new DeviceIdentifier(deviceId, DeviceTypeConstants.DEVICE_TYPE))) {
            return Response.status(Response.Status.UNAUTHORIZED.getStatusCode()).build();
        }
        String sensorState = state.toUpperCase();
        if (!sensorState.equals(DeviceTypeConstants.STATE_ON) && !sensorState.equals(DeviceTypeConstants.STATE_OFF)) {
            log.error("The requested state change should be either - 'ON' or 'OFF'");
            return Response.status(Response.Status.BAD_REQUEST.getStatusCode()).build();
        }
        Map<String, String> dynamicProperties = new HashMap<>();
        String publishTopic = APIUtil.getAuthenticatedUserTenantDomain() + "/" + DeviceTypeConstants.DEVICE_TYPE + "/" + deviceId + "/command";
        String actualMessage = DeviceTypeConstants.BULB_CONTEXT + ':' + sensorState;
        dynamicProperties.put(DeviceTypeConstants.ADAPTER_TOPIC_PROPERTY, publishTopic);
        Operation commandOp = new CommandOperation();
        commandOp.setCode("change-status");
        commandOp.setType(Operation.Type.COMMAND);
        commandOp.setEnabled(true);
        commandOp.setPayLoad(actualMessage);
        Properties props = new Properties();
        props.setProperty("mqtt.adapter.topic", publishTopic);
        commandOp.setProperties(props);
        List<DeviceIdentifier> deviceIdentifiers = new ArrayList<>();
        deviceIdentifiers.add(new DeviceIdentifier(deviceId, "sampledevice"));
        APIUtil.getDeviceManagementService().addOperation("sampledevice", commandOp, deviceIdentifiers);
        return Response.ok().build();
    } catch (DeviceAccessAuthorizationException e) {
        log.error(e.getErrorMessage(), e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (OperationManagementException e) {
        String msg = "Error occurred while executing command operation upon ringing the buzzer";
        log.error(msg, e);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
    } catch (InvalidDeviceException e) {
        String msg = "Error occurred while executing command operation to send keywords";
        log.error(msg, e);
        return Response.status(Response.Status.BAD_REQUEST).build();
    }
}
Also used : DeviceAccessAuthorizationException(org.wso2.carbon.device.mgt.common.authorization.DeviceAccessAuthorizationException) HashMap(java.util.HashMap) CommandOperation(org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation) ArrayList(java.util.ArrayList) Operation(org.wso2.carbon.device.mgt.common.operation.mgt.Operation) CommandOperation(org.wso2.carbon.device.mgt.core.operation.mgt.CommandOperation) OperationManagementException(org.wso2.carbon.device.mgt.common.operation.mgt.OperationManagementException) Properties(java.util.Properties) InvalidDeviceException(org.wso2.carbon.device.mgt.common.InvalidDeviceException) DeviceIdentifier(org.wso2.carbon.device.mgt.common.DeviceIdentifier) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 50 with Device

use of org.wso2.carbon.device.mgt.common.Device in project product-iots by wso2.

the class ZipUtil method createZipFile.

/**
 * Create agent zip file.
 *
 * @param owner             Owner of device.
 * @param tenantDomain      Tenant of the device.
 * @param deviceType        Device type.
 * @param deviceId          Device ID.
 * @param deviceName        Device Name
 * @param token             Auth token to access the api.
 * @param refreshToken      Refresh token to generate new auth token.
 * @param apiApplicationKey Application key.
 * @return Zip archive.
 * @throws DeviceManagementException Error creating zip archive.
 */
public ZipArchive createZipFile(String owner, String tenantDomain, String deviceType, String deviceId, String deviceName, String token, String refreshToken, String apiApplicationKey) throws DeviceManagementException {
    String sketchFolder = "repository" + File.separator + "resources" + File.separator + "sketches";
    String archivesPath = CarbonUtils.getCarbonHome() + File.separator + sketchFolder + File.separator + "archives" + File.separator + deviceId;
    String templateSketchPath = sketchFolder + File.separator + deviceType;
    String iotServerIP;
    try {
        iotServerIP = getServerUrl();
        String httpsServerEP = Utils.replaceSystemProperty(HTTPS_PROTOCOL_URL);
        String httpServerEP = Utils.replaceSystemProperty(HTTP_PROTOCOL_URL);
        String mqttEndpoint = Utils.replaceSystemProperty(DEFAULT_MQTT_ENDPOINT);
        if (mqttEndpoint.contains(LOCALHOST)) {
            mqttEndpoint = mqttEndpoint.replace(LOCALHOST, iotServerIP);
            httpsServerEP = httpsServerEP.replace(LOCALHOST, iotServerIP);
            httpServerEP = httpServerEP.replace(LOCALHOST, iotServerIP);
        }
        String base64EncodedApplicationKey = getBase64EncodedAPIAppKey(apiApplicationKey).trim();
        Map<String, String> contextParams = new HashMap<>();
        contextParams.put("SERVER_NAME", APIUtil.getTenantDomainOftheUser());
        contextParams.put("DEVICE_OWNER", owner);
        contextParams.put("DEVICE_ID", deviceId);
        contextParams.put("DEVICE_NAME", deviceName);
        contextParams.put("HTTPS_EP", httpsServerEP);
        contextParams.put("HTTP_EP", httpServerEP);
        contextParams.put("APIM_EP", httpsServerEP);
        contextParams.put("MQTT_EP", mqttEndpoint);
        contextParams.put("DEVICE_TOKEN", token);
        contextParams.put("DEVICE_REFRESH_TOKEN", refreshToken);
        contextParams.put("API_APPLICATION_KEY", base64EncodedApplicationKey);
        ZipArchive zipFile;
        zipFile = getSketchArchive(archivesPath, templateSketchPath, contextParams, deviceName);
        return zipFile;
    } catch (IOException e) {
        throw new DeviceManagementException("Zip File Creation Failed", e);
    }
}
Also used : DeviceManagementException(org.wso2.carbon.device.mgt.common.DeviceManagementException) HashMap(java.util.HashMap) IOException(java.io.IOException)

Aggregations

Test (org.testng.annotations.Test)20 HttpResponse (org.wso2.carbon.automation.test.utils.http.client.HttpResponse)17 DeviceManagementException (org.wso2.carbon.device.mgt.common.DeviceManagementException)13 DeviceMgtPluginException (org.wso2.iot.sampledevice.plugin.exception.DeviceMgtPluginException)11 JsonParser (com.google.gson.JsonParser)10 SQLException (java.sql.SQLException)8 JsonObject (com.google.gson.JsonObject)7 Connection (java.sql.Connection)7 PreparedStatement (java.sql.PreparedStatement)7 HashMap (java.util.HashMap)6 ConnectedCupDeviceMgtPluginException (org.coffeeking.connectedcup.plugin.exception.ConnectedCupDeviceMgtPluginException)6 Device (org.wso2.carbon.device.mgt.common.Device)6 JsonArray (com.google.gson.JsonArray)5 JsonElement (com.google.gson.JsonElement)4 ResultSet (java.sql.ResultSet)4 ArrayList (java.util.ArrayList)4 Path (javax.ws.rs.Path)4 JSONObject (org.json.simple.JSONObject)4 PrivilegedCarbonContext (org.wso2.carbon.context.PrivilegedCarbonContext)4 DeviceIdentifier (org.wso2.carbon.device.mgt.common.DeviceIdentifier)4