Search in sources :

Example 1 with CallItem

use of com.bwssystems.HABridge.api.CallItem in project ha-bridge by bwssytems.

the class HueMulator method changeState.

private String changeState(String userId, String lightId, String body, String ipAddress) {
    String responseString = null;
    String url = null;
    StateChangeBody theStateChanges = null;
    DeviceState state = null;
    Integer targetBri = null;
    Integer targetBriInc = null;
    MultiCommandUtil aMultiUtil = new MultiCommandUtil();
    aMultiUtil.setTheDelay(bridgeSettings.getButtonsleep());
    aMultiUtil.setDelayDefault(bridgeSettings.getButtonsleep());
    aMultiUtil.setSetCount(1);
    log.debug("hue state change requested: " + userId + " from " + ipAddress + " body: " + body);
    HueError[] theErrors = bridgeSettingMaster.getBridgeSecurity().validateWhitelistUser(userId, null, bridgeSettingMaster.getBridgeSecurity().isUseLinkButton());
    if (theErrors != null)
        return aGsonHandler.toJson(theErrors);
    try {
        theStateChanges = aGsonHandler.fromJson(body, StateChangeBody.class);
    } catch (Exception e) {
        theStateChanges = null;
    }
    if (theStateChanges == null) {
        log.warn("Could not parse state change body. Light state not changed.");
        return aGsonHandler.toJson(HueErrorResponse.createResponse("2", "/lights/" + lightId, "Could not parse state change body.", null, null, null).getTheErrors(), HueError[].class);
    }
    DeviceDescriptor device = repository.findOne(lightId);
    if (device == null) {
        log.warn("Could not find device: " + lightId + " for hue state change request: " + userId + " from " + ipAddress + " body: " + body);
        return aGsonHandler.toJson(HueErrorResponse.createResponse("3", "/lights/" + lightId, "Could not find device.", "/lights/" + lightId, null, null).getTheErrors(), HueError[].class);
    }
    if (body.contains("\"bri_inc\"")) {
        targetBriInc = new Integer(theStateChanges.getBri_inc());
    } else if (body.contains("\"bri\"")) {
        targetBri = new Integer(theStateChanges.getBri());
    }
    state = device.getDeviceState();
    if (state == null) {
        state = DeviceState.createDeviceState();
        device.setDeviceState(state);
    }
    if (targetBri != null || targetBriInc != null) {
        url = device.getDimUrl();
        if (url == null || url.length() == 0)
            url = device.getOnUrl();
    } else {
        if (theStateChanges.isOn()) {
            url = device.getOnUrl();
        } else if (!theStateChanges.isOn()) {
            url = device.getOffUrl();
        }
    }
    // code for backwards compatibility
    if (device.getMapType() != null && device.getMapType().equalsIgnoreCase(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) {
        if (url == null)
            url = device.getOnUrl();
    }
    if (url != null && !url.equals("")) {
        if (!url.startsWith("[")) {
            if (url.startsWith("{\"item"))
                url = "[" + url + "]";
            else {
                if (url.startsWith("{"))
                    url = "[{\"item\":" + url + "}]";
                else
                    url = "[{\"item\":\"" + url + "\"}]";
            }
        } else if (!url.startsWith("[{\"item\""))
            url = "[{\"item\":" + url + "}]";
        log.debug("Decode Json for url items: " + url);
        CallItem[] callItems = null;
        try {
            callItems = aGsonHandler.fromJson(url, CallItem[].class);
        } catch (JsonSyntaxException e) {
            log.warn("Could not decode Json for url items: " + lightId + " for hue state change request: " + userId + " from " + ipAddress + " body: " + body + " url items: " + url);
            return aGsonHandler.toJson(HueErrorResponse.createResponse("3", "/lights/" + lightId, "Could decode json in request", "/lights/" + lightId, null, null).getTheErrors(), HueError[].class);
        }
        for (int i = 0; callItems != null && i < callItems.length; i++) {
            if (!filterByRequester(device.getRequesterAddress(), ipAddress) || !filterByRequester(callItems[i].getFilterIPs(), ipAddress)) {
                log.warn("filter for requester address not present in: (device)" + device.getRequesterAddress() + " OR then (item)" + callItems[i].getFilterIPs() + " with request ip of: " + ipAddress);
                continue;
            }
            if (callItems[i].getCount() != null && callItems[i].getCount() > 0)
                aMultiUtil.setSetCount(callItems[i].getCount());
            else
                aMultiUtil.setSetCount(1);
            // code for backwards compatibility
            if ((callItems[i].getType() == null || callItems[i].getType().trim().isEmpty())) {
                if (validMapTypes.validateType(device.getMapType()))
                    callItems[i].setType(device.getMapType().trim());
                else if (validMapTypes.validateType(device.getDeviceType()))
                    callItems[i].setType(device.getDeviceType().trim());
                else
                    callItems[i].setType(DeviceMapTypes.CUSTOM_DEVICE[DeviceMapTypes.typeIndex]);
            }
            if (callItems[i].getType() != null) {
                for (int x = 0; x < aMultiUtil.getSetCount(); x++) {
                    if (x > 0 || i > 0) {
                        try {
                            Thread.sleep(aMultiUtil.getTheDelay());
                        } catch (InterruptedException e) {
                        // ignore
                        }
                    }
                    if (callItems[i].getDelay() != null && callItems[i].getDelay() > 0)
                        aMultiUtil.setTheDelay(callItems[i].getDelay());
                    else
                        aMultiUtil.setTheDelay(aMultiUtil.getDelayDefault());
                    responseString = homeManager.findHome(callItems[i].getType().trim()).deviceHandler(callItems[i], aMultiUtil, lightId, state.getBri(), targetBri, targetBriInc, device, body);
                    if (responseString != null && responseString.contains("{\"error\":")) {
                        x = aMultiUtil.getSetCount();
                    }
                }
            }
        }
    } else {
        log.warn("Could not find url: " + lightId + " for hue state change request: " + userId + " from " + ipAddress + " body: " + body);
        responseString = aGsonHandler.toJson(HueErrorResponse.createResponse("3", "/lights/" + lightId, "Could not find url.", "/lights/" + lightId, null, null).getTheErrors(), HueError[].class);
    }
    if (responseString == null || !responseString.contains("[{\"error\":")) {
        if (!device.isNoState()) {
            responseString = this.formatSuccessHueResponse(theStateChanges, body, lightId, state, targetBri, targetBriInc, device.isOffState());
            device.setDeviceState(state);
        } else {
            DeviceState dummyState = DeviceState.createDeviceState();
            responseString = this.formatSuccessHueResponse(theStateChanges, body, lightId, dummyState, targetBri, targetBriInc, device.isOffState());
        }
    }
    return responseString;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) DeviceState(com.bwssystems.HABridge.api.hue.DeviceState) JsonSyntaxException(com.google.gson.JsonSyntaxException) HueError(com.bwssystems.HABridge.api.hue.HueError) StateChangeBody(com.bwssystems.HABridge.api.hue.StateChangeBody) CallItem(com.bwssystems.HABridge.api.CallItem)

Example 2 with CallItem

use of com.bwssystems.HABridge.api.CallItem in project ha-bridge by bwssytems.

the class HueMulator method lightsListHandler.

private Object lightsListHandler(String userId, String requestIp) {
    HueError[] theErrors = null;
    Map<String, DeviceResponse> deviceResponseMap = null;
    if (bridgeSettings.isTraceupnp())
        log.info("Traceupnp: hue lights list requested: " + userId + " from " + requestIp);
    log.debug("hue lights list requested: " + userId + " from " + requestIp);
    theErrors = bridgeSettingMaster.getBridgeSecurity().validateWhitelistUser(userId, null, bridgeSettingMaster.getBridgeSecurity().isUseLinkButton());
    if (theErrors == null) {
        if (bridgeSettingMaster.getBridgeSecurity().isSettingsChanged())
            bridgeSettingMaster.updateConfigFile();
        List<DeviceDescriptor> deviceList = repository.findAllByRequester(requestIp);
        //			List<DeviceDescriptor> deviceList = repository.findActive();
        deviceResponseMap = new HashMap<String, DeviceResponse>();
        for (DeviceDescriptor device : deviceList) {
            DeviceResponse deviceResponse = null;
            if (!device.isInactive()) {
                if (device.containsType(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) {
                    CallItem[] callItems = null;
                    try {
                        if (device.getOnUrl() != null)
                            callItems = aGsonHandler.fromJson(device.getOnUrl(), CallItem[].class);
                    } catch (JsonSyntaxException e) {
                        log.warn("Could not decode Json for url items to get Hue state for device: " + device.getName());
                        callItems = null;
                    }
                    for (int i = 0; callItems != null && i < callItems.length; i++) {
                        if ((callItems[i].getType() != null && callItems[i].getType().equals(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) || (callItems[i].getItem().getAsString().contains("hueName"))) {
                            deviceResponse = myHueHome.getHueDeviceInfo(callItems[i], device);
                            i = callItems.length;
                        }
                    }
                }
                if (deviceResponse == null)
                    deviceResponse = DeviceResponse.createResponse(device);
                deviceResponseMap.put(device.getId(), deviceResponse);
            }
        }
    }
    if (theErrors != null)
        return theErrors;
    return deviceResponseMap;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) DeviceResponse(com.bwssystems.HABridge.api.hue.DeviceResponse) HueError(com.bwssystems.HABridge.api.hue.HueError) CallItem(com.bwssystems.HABridge.api.CallItem)

Example 3 with CallItem

use of com.bwssystems.HABridge.api.CallItem in project ha-bridge by bwssytems.

the class DeviceResource method setupEndpoints.

private void setupEndpoints() {
    log.info("HABridge device management service started.... ");
    before(API_CONTEXT + "/*", (request, response) -> {
        // This never gets called as the HueMulator class covers this path. This is here for backup
        if (bridgeSettings.getBridgeSecurity().isSecure()) {
            User authUser = bridgeSettings.getBridgeSecurity().getAuthenticatedUser(request);
            if (authUser == null) {
                halt(401, "{\"message\":\"User not authenticated\"}");
            }
        }
    });
    // http://ip_address:port/api/devices CORS request
    options(API_CONTEXT, "application/json", (request, response) -> {
        response.status(HttpStatus.SC_OK);
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
        response.header("Content-Type", "text/html; charset=utf-8");
        return "";
    });
    post(API_CONTEXT, "application/json", (request, response) -> {
        log.debug("Create a Device(s) - request body: " + request.body());
        DeviceDescriptor[] devices;
        if (request.body().substring(0, 1).equalsIgnoreCase("[") == true) {
            devices = new Gson().fromJson(request.body(), DeviceDescriptor[].class);
        } else {
            devices = new Gson().fromJson("[" + request.body() + "]", DeviceDescriptor[].class);
        }
        CallItem[] callItems = null;
        String errorMessage = null;
        for (int i = 0; i < devices.length; i++) {
            if (devices[i].getContentBody() != null) {
                if (devices[i].getContentType() == null || devices[i].getHttpVerb() == null || !supportedVerbs.contains(devices[i].getHttpVerb().toLowerCase())) {
                    response.status(HttpStatus.SC_BAD_REQUEST);
                    errorMessage = "Bad http verb in create device(s) for name: " + devices[i].getName() + " with verb: " + devices[i].getHttpVerb();
                    log.debug(errorMessage);
                    return new ErrorMessage(errorMessage);
                }
            }
            try {
                if (devices[i].getOnUrl() != null && !devices[i].getOnUrl().isEmpty())
                    callItems = aGsonHandler.fromJson(devices[i].getOnUrl(), CallItem[].class);
            } catch (JsonSyntaxException e) {
                response.status(HttpStatus.SC_BAD_REQUEST);
                errorMessage = "Bad on URL JSON in create device(s) for name: " + devices[i].getName() + " with on URL: " + devices[i].getOnUrl();
                log.debug(errorMessage);
                return new ErrorMessage(errorMessage);
            }
            try {
                if (devices[i].getDimUrl() != null && !devices[i].getDimUrl().isEmpty())
                    callItems = aGsonHandler.fromJson(devices[i].getDimUrl(), CallItem[].class);
            } catch (JsonSyntaxException e) {
                response.status(HttpStatus.SC_BAD_REQUEST);
                errorMessage = "Bad dim URL JSON in create device(s) for name: " + devices[i].getName() + " with dim URL: " + devices[i].getDimUrl();
                log.debug(errorMessage);
                return new ErrorMessage(errorMessage);
            }
            try {
                if (devices[i].getOffUrl() != null && !devices[i].getOffUrl().isEmpty())
                    callItems = aGsonHandler.fromJson(devices[i].getOffUrl(), CallItem[].class);
            } catch (JsonSyntaxException e) {
                response.status(HttpStatus.SC_BAD_REQUEST);
                errorMessage = "Bad off URL JSON in create device(s) for name: " + devices[i].getName() + " with off URL: " + devices[i].getOffUrl();
                log.debug(errorMessage);
                return new ErrorMessage(errorMessage);
            }
        }
        deviceRepository.save(devices);
        log.debug("Created a Device(s): " + request.body());
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.status(HttpStatus.SC_CREATED);
        return devices;
    }, new JsonTransformer());
    // http://ip_address:port/api/devices/:id CORS request
    options(API_CONTEXT + "/:id", "application/json", (request, response) -> {
        response.status(HttpStatus.SC_OK);
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
        response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
        response.header("Content-Type", "text/html; charset=utf-8");
        return "";
    });
    put(API_CONTEXT + "/:id", "application/json", (request, response) -> {
        log.debug("Edit a Device - request body: " + request.body());
        DeviceDescriptor device = new Gson().fromJson(request.body(), DeviceDescriptor.class);
        if (deviceRepository.findOne(request.params(":id")) == null) {
            log.debug("Could not save an edited device, Device Id not found: " + request.params(":id"));
            response.status(HttpStatus.SC_BAD_REQUEST);
            return new ErrorMessage("Could not save an edited device, Device Id not found: " + request.params(":id") + " ");
        } else {
            log.debug("Saving an edited Device: " + device.getName());
            if (device.getDeviceType() != null)
                device.setDeviceType(device.getDeviceType());
            DeviceDescriptor[] theDevices = new DeviceDescriptor[1];
            theDevices[0] = device;
            deviceRepository.save(theDevices);
            response.status(HttpStatus.SC_OK);
        }
        return device;
    }, new JsonTransformer());
    get(API_CONTEXT, "application/json", (request, response) -> {
        List<DeviceDescriptor> deviceList = deviceRepository.findAll();
        log.debug("Get all devices");
        JsonTransformer aRenderer = new JsonTransformer();
        String theStream = aRenderer.render(deviceList);
        log.debug("The Device List: " + theStream);
        response.status(HttpStatus.SC_OK);
        return deviceList;
    }, new JsonTransformer());
    get(API_CONTEXT + "/:id", "application/json", (request, response) -> {
        log.debug("Get a device");
        DeviceDescriptor descriptor = deviceRepository.findOne(request.params(":id"));
        if (descriptor == null) {
            response.status(HttpStatus.SC_NOT_FOUND);
            return new ErrorMessage("Could not find, id: " + request.params(":id") + " ");
        } else
            response.status(HttpStatus.SC_OK);
        return descriptor;
    }, new JsonTransformer());
    delete(API_CONTEXT + "/:id", "application/json", (request, response) -> {
        String anId = request.params(":id");
        log.debug("Delete a device: " + anId);
        DeviceDescriptor deleted = deviceRepository.findOne(anId);
        if (deleted == null) {
            response.status(HttpStatus.SC_NOT_FOUND);
            return new ErrorMessage("Could not delete, id: " + anId + " not found. ");
        } else {
            deviceRepository.delete(deleted);
            response.status(HttpStatus.SC_OK);
        }
        return null;
    }, new JsonTransformer());
    get(API_CONTEXT + "/vera/devices", "application/json", (request, response) -> {
        log.debug("Get vera devices");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/vera/scenes", "application/json", (request, response) -> {
        log.debug("Get vera scenes");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.VERA_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.VERA_SCENE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/harmony/activities", "application/json", (request, response) -> {
        log.debug("Get harmony activities");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/harmony/show", "application/json", (request, response) -> {
        log.debug("Get harmony current activity");
        return homeManager.findResource(DeviceMapTypes.HARMONY_ACTIVITY[DeviceMapTypes.typeIndex]).getItems("current_activity");
    }, new JsonTransformer());
    get(API_CONTEXT + "/harmony/devices", "application/json", (request, response) -> {
        log.debug("Get harmony devices");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.HARMONY_BUTTON[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/nest/items", "application/json", (request, response) -> {
        log.debug("Get nest items");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.NEST_HOMEAWAY[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/hue/devices", "application/json", (request, response) -> {
        log.debug("Get hue items");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/hal/devices", "application/json", (request, response) -> {
        log.debug("Get hal items");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.HAL_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.HAL_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/mqtt/devices", "application/json", (request, response) -> {
        log.debug("Get MQTT brokers");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.MQTT_MESSAGE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/hass/devices", "application/json", (request, response) -> {
        log.debug("Get HomeAssistant Clients");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.HASS_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/domoticz/devices", "application/json", (request, response) -> {
        log.debug("Get Domoticz Clients");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.DOMOTICZ_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.DOMOTICZ_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/lifx/devices", "application/json", (request, response) -> {
        log.debug("Get LIFX devices");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.LIFX_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.LIFX_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/somfy/devices", "application/json", (request, response) -> {
        log.debug("Get somfy devices");
        response.status(HttpStatus.SC_OK);
        return homeManager.findResource(DeviceMapTypes.SOMFY_DEVICE[DeviceMapTypes.typeIndex]).getItems(DeviceMapTypes.SOMFY_DEVICE[DeviceMapTypes.typeIndex]);
    }, new JsonTransformer());
    get(API_CONTEXT + "/map/types", "application/json", (request, response) -> {
        log.debug("Get map types");
        return new DeviceMapTypes().getDeviceMapTypes();
    }, new JsonTransformer());
    // http://ip_address:port/api/devices/exec/renumber CORS request
    options(API_CONTEXT + "/exec/renumber", "application/json", (request, response) -> {
        response.status(HttpStatus.SC_OK);
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.header("Access-Control-Allow-Methods", "POST");
        response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
        response.header("Content-Type", "text/html; charset=utf-8");
        return "";
    });
    post(API_CONTEXT + "/exec/renumber", "application/json", (request, response) -> {
        log.debug("Renumber devices.");
        deviceRepository.renumber();
        return null;
    }, new JsonTransformer());
    get(API_CONTEXT + "/backup/available", "application/json", (request, response) -> {
        log.debug("Get backup filenames");
        response.status(HttpStatus.SC_OK);
        return deviceRepository.getBackups();
    }, new JsonTransformer());
    // http://ip_address:port/api/devices/backup/create CORS request
    options(API_CONTEXT + "/backup/create", "application/json", (request, response) -> {
        response.status(HttpStatus.SC_OK);
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.header("Access-Control-Allow-Methods", "PUT");
        response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
        response.header("Content-Type", "text/html; charset=utf-8");
        return "";
    });
    put(API_CONTEXT + "/backup/create", "application/json", (request, response) -> {
        log.debug("Create backup: " + request.body());
        BackupFilename aFilename = new Gson().fromJson(request.body(), BackupFilename.class);
        BackupFilename returnFilename = new BackupFilename();
        returnFilename.setFilename(deviceRepository.backup(aFilename.getFilename()));
        return returnFilename;
    }, new JsonTransformer());
    // http://ip_address:port/api/devices/backup/delete CORS request
    options(API_CONTEXT + "/backup/delete", "application/json", (request, response) -> {
        response.status(HttpStatus.SC_OK);
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.header("Access-Control-Allow-Methods", "POST");
        response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
        response.header("Content-Type", "text/html; charset=utf-8");
        return "";
    });
    post(API_CONTEXT + "/backup/delete", "application/json", (request, response) -> {
        log.debug("Delete backup: " + request.body());
        BackupFilename aFilename = new Gson().fromJson(request.body(), BackupFilename.class);
        if (aFilename != null)
            deviceRepository.deleteBackup(aFilename.getFilename());
        else
            log.warn("No filename given for delete backup.");
        return null;
    }, new JsonTransformer());
    // http://ip_address:port/api/devices/backup/restore CORS request
    options(API_CONTEXT + "/backup/restore", "application/json", (request, response) -> {
        response.status(HttpStatus.SC_OK);
        response.header("Access-Control-Allow-Origin", request.headers("Origin"));
        response.header("Access-Control-Allow-Methods", "POST");
        response.header("Access-Control-Allow-Headers", request.headers("Access-Control-Request-Headers"));
        response.header("Content-Type", "text/html; charset=utf-8");
        return "";
    });
    post(API_CONTEXT + "/backup/restore", "application/json", (request, response) -> {
        log.debug("Restore backup: " + request.body());
        BackupFilename aFilename = new Gson().fromJson(request.body(), BackupFilename.class);
        if (aFilename != null) {
            deviceRepository.restoreBackup(aFilename.getFilename());
            deviceRepository.loadRepository();
        } else
            log.warn("No filename given for restore backup.");
        return null;
    }, new JsonTransformer());
}
Also used : User(com.bwssystems.HABridge.User) BackupFilename(com.bwssystems.HABridge.dao.BackupFilename) DeviceDescriptor(com.bwssystems.HABridge.dao.DeviceDescriptor) Gson(com.google.gson.Gson) DeviceMapTypes(com.bwssystems.HABridge.DeviceMapTypes) JsonSyntaxException(com.google.gson.JsonSyntaxException) CallItem(com.bwssystems.HABridge.api.CallItem) ErrorMessage(com.bwssystems.HABridge.dao.ErrorMessage) JsonTransformer(com.bwssystems.HABridge.util.JsonTransformer)

Example 4 with CallItem

use of com.bwssystems.HABridge.api.CallItem in project ha-bridge by bwssytems.

the class HueMulator method getLight.

private Object getLight(String userId, String lightId, String ipAddress) {
    log.debug("hue light requested: " + lightId + " for user: " + userId + " from " + ipAddress);
    HueError[] theErrors = bridgeSettingMaster.getBridgeSecurity().validateWhitelistUser(userId, null, bridgeSettingMaster.getBridgeSecurity().isUseLinkButton());
    if (theErrors != null)
        return theErrors;
    DeviceDescriptor device = repository.findOne(lightId);
    if (device == null) {
        //			response.status(HttpStatus.SC_NOT_FOUND);
        return HueErrorResponse.createResponse("3", "/api/" + userId + "/lights/" + lightId, "Object not found", null, null, null).getTheErrors();
    } else {
        log.debug("found device named: " + device.getName());
    }
    DeviceResponse lightResponse = null;
    if (device.containsType(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) {
        CallItem[] callItems = null;
        try {
            if (device.getOnUrl() != null)
                callItems = aGsonHandler.fromJson(device.getOnUrl(), CallItem[].class);
        } catch (JsonSyntaxException e) {
            log.warn("Could not decode Json for url items to get Hue state for device: " + device.getName());
            callItems = null;
        }
        for (int i = 0; callItems != null && i < callItems.length; i++) {
            if ((callItems[i].getType() != null && callItems[i].getType().equals(DeviceMapTypes.HUE_DEVICE[DeviceMapTypes.typeIndex])) || callItems[i].getItem().getAsString().startsWith("{\"ipAddress\":\"")) {
                lightResponse = myHueHome.getHueDeviceInfo(callItems[i], device);
                i = callItems.length;
            }
        }
    }
    if (lightResponse == null)
        lightResponse = DeviceResponse.createResponse(device);
    return lightResponse;
}
Also used : JsonSyntaxException(com.google.gson.JsonSyntaxException) DeviceResponse(com.bwssystems.HABridge.api.hue.DeviceResponse) HueError(com.bwssystems.HABridge.api.hue.HueError) CallItem(com.bwssystems.HABridge.api.CallItem)

Aggregations

CallItem (com.bwssystems.HABridge.api.CallItem)4 JsonSyntaxException (com.google.gson.JsonSyntaxException)4 HueError (com.bwssystems.HABridge.api.hue.HueError)3 DeviceResponse (com.bwssystems.HABridge.api.hue.DeviceResponse)2 DeviceMapTypes (com.bwssystems.HABridge.DeviceMapTypes)1 User (com.bwssystems.HABridge.User)1 DeviceState (com.bwssystems.HABridge.api.hue.DeviceState)1 StateChangeBody (com.bwssystems.HABridge.api.hue.StateChangeBody)1 BackupFilename (com.bwssystems.HABridge.dao.BackupFilename)1 DeviceDescriptor (com.bwssystems.HABridge.dao.DeviceDescriptor)1 ErrorMessage (com.bwssystems.HABridge.dao.ErrorMessage)1 JsonTransformer (com.bwssystems.HABridge.util.JsonTransformer)1 Gson (com.google.gson.Gson)1