Search in sources :

Example 1 with HueResponse

use of org.openhab.io.hueemulation.internal.dto.response.HueResponse in project openhab-addons by openhab.

the class UserManagement method createNewUser.

@POST
@Operation(summary = "Create an API Key", responses = { @ApiResponse(responseCode = "200", description = "API Key created"), @ApiResponse(responseCode = "403", description = "Link button not pressed") })
public Response createNewUser(@Context UriInfo uri, String body) {
    if (!cs.ds.config.linkbutton) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.LINK_BUTTON_NOT_PRESSED, "link button not pressed");
    }
    final HueCreateUser userRequest;
    userRequest = cs.gson.fromJson(body, HueCreateUser.class);
    if (userRequest.devicetype.isEmpty()) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.INVALID_JSON, "Invalid request: No devicetype set");
    }
    String apiKey = UUID.randomUUID().toString();
    String clientKey = UUID.randomUUID().toString();
    addUser(apiKey, clientKey, userRequest.devicetype);
    HueSuccessResponseCreateUser h = new HueSuccessResponseCreateUser(apiKey, clientKey);
    String result = cs.gson.toJson(Collections.singleton(new HueResponse(h)), new TypeToken<List<?>>() {
    }.getType());
    return Response.ok(result).build();
}
Also used : HueSuccessResponseCreateUser(org.openhab.io.hueemulation.internal.dto.response.HueSuccessResponseCreateUser) TypeToken(com.google.gson.reflect.TypeToken) HueCreateUser(org.openhab.io.hueemulation.internal.dto.changerequest.HueCreateUser) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse) POST(javax.ws.rs.POST) Operation(io.swagger.v3.oas.annotations.Operation)

Example 2 with HueResponse

use of org.openhab.io.hueemulation.internal.dto.response.HueResponse in project openhab-addons by openhab.

the class StateUtils method computeCommandByState.

/**
 * Apply the new received state from the REST PUT request.
 *
 * @param responses Creates a response entry for each success and each error. There is one entry per non-null field
 *            of {@link HueStateChange} created.
 * @param prefix The response entry prefix, for example "/groups/mygroupid/state/"
 * @param state The current item state
 * @param newState A state change DTO
 * @return Return a command computed via the incoming state object.
 */
@Nullable
public static Command computeCommandByState(List<HueResponse> responses, String prefix, AbstractHueState state, HueStateChange newState) {
    // Apply new state and collect success, error items
    Map<String, Object> successApplied = new TreeMap<>();
    List<String> errorApplied = new ArrayList<>();
    Command command = null;
    if (newState.on != null) {
        try {
            state.as(HueStatePlug.class).on = newState.on;
            command = OnOffType.from(newState.on);
            successApplied.put("on", newState.on);
        } catch (ClassCastException e) {
            errorApplied.add("on");
        }
    }
    if (newState.bri != null) {
        try {
            state.as(HueStateBulb.class).bri = newState.bri;
            command = new PercentType((int) (newState.bri * 100.0 / HueStateBulb.MAX_BRI + 0.5));
            successApplied.put("bri", newState.bri);
        } catch (ClassCastException e) {
            errorApplied.add("bri");
        }
    }
    if (newState.bri_inc != null) {
        try {
            int newBri = state.as(HueStateBulb.class).bri + newState.bri_inc;
            if (newBri < 0 || newBri > HueStateBulb.MAX_BRI) {
                throw new IllegalArgumentException();
            }
            command = new PercentType((int) (newBri * 100.0 / HueStateBulb.MAX_BRI + 0.5));
            successApplied.put("bri", newState.bri);
        } catch (ClassCastException e) {
            errorApplied.add("bri_inc");
        } catch (IllegalArgumentException e) {
            errorApplied.add("bri_inc");
        }
    }
    if (newState.sat != null) {
        try {
            HueStateColorBulb c = state.as(HueStateColorBulb.class);
            c.sat = newState.sat;
            c.colormode = ColorMode.hs;
            command = c.toHSBType();
            successApplied.put("sat", newState.sat);
        } catch (ClassCastException e) {
            errorApplied.add("sat");
        }
    }
    if (newState.sat_inc != null) {
        try {
            HueStateColorBulb c = state.as(HueStateColorBulb.class);
            int newV = c.sat + newState.sat_inc;
            if (newV < 0 || newV > HueStateColorBulb.MAX_SAT) {
                throw new IllegalArgumentException();
            }
            c.colormode = ColorMode.hs;
            c.sat = newV;
            command = c.toHSBType();
            successApplied.put("sat", newState.sat);
        } catch (ClassCastException e) {
            errorApplied.add("sat_inc");
        } catch (IllegalArgumentException e) {
            errorApplied.add("sat_inc");
        }
    }
    if (newState.hue != null) {
        try {
            HueStateColorBulb c = state.as(HueStateColorBulb.class);
            c.colormode = ColorMode.hs;
            c.hue = newState.hue;
            command = c.toHSBType();
            successApplied.put("hue", newState.hue);
        } catch (ClassCastException e) {
            errorApplied.add("hue");
        }
    }
    if (newState.hue_inc != null) {
        try {
            HueStateColorBulb c = state.as(HueStateColorBulb.class);
            int newV = c.hue + newState.hue_inc;
            if (newV < 0 || newV > HueStateColorBulb.MAX_HUE) {
                throw new IllegalArgumentException();
            }
            c.colormode = ColorMode.hs;
            c.hue = newV;
            command = c.toHSBType();
            successApplied.put("hue", newState.hue);
        } catch (ClassCastException e) {
            errorApplied.add("hue_inc");
        } catch (IllegalArgumentException e) {
            errorApplied.add("hue_inc");
        }
    }
    if (newState.ct != null) {
        try {
            // Adjusting the color temperature implies setting the mode to ct
            if (state instanceof HueStateColorBulb) {
                HueStateColorBulb c = state.as(HueStateColorBulb.class);
                c.sat = 0;
                c.colormode = ColorMode.ct;
                command = c.toHSBType();
            }
            successApplied.put("colormode", ColorMode.ct);
            successApplied.put("sat", 0);
            successApplied.put("ct", newState.ct);
        } catch (ClassCastException e) {
            errorApplied.add("ct");
        }
    }
    if (newState.ct_inc != null) {
        try {
            // Adjusting the color temperature implies setting the mode to ct
            if (state instanceof HueStateColorBulb) {
                HueStateColorBulb c = state.as(HueStateColorBulb.class);
                if (c.colormode != ColorMode.ct) {
                    c.sat = 0;
                    command = c.toHSBType();
                    successApplied.put("colormode", c.colormode);
                }
            }
            successApplied.put("ct", newState.ct);
        } catch (ClassCastException e) {
            errorApplied.add("ct_inc");
        }
    }
    if (newState.transitiontime != null) {
        // Pretend that worked
        successApplied.put("transitiontime", newState.transitiontime);
    }
    if (newState.alert != null) {
        // Pretend that worked
        successApplied.put("alert", newState.alert);
    }
    if (newState.effect != null) {
        // Pretend that worked
        successApplied.put("effect", newState.effect);
    }
    if (newState.xy != null) {
        try {
            HueStateColorBulb c = state.as(HueStateColorBulb.class);
            c.colormode = ColorMode.xy;
            c.bri = state.as(HueStateBulb.class).bri;
            c.xy[0] = newState.xy.get(0);
            c.xy[1] = newState.xy.get(1);
            command = c.toHSBType();
            successApplied.put("xy", newState.xy);
        } catch (ClassCastException e) {
            errorApplied.add("xy");
        }
    }
    if (newState.xy_inc != null) {
        try {
            HueStateColorBulb c = state.as(HueStateColorBulb.class);
            double newX = c.xy[0] + newState.xy_inc.get(0);
            double newY = c.xy[1] + newState.xy_inc.get(1);
            if (newX < 0 || newX > 1 || newY < 0 || newY > 1) {
                throw new IllegalArgumentException();
            }
            c.colormode = ColorMode.xy;
            c.bri = state.as(HueStateBulb.class).bri;
            c.xy[0] = newX;
            c.xy[1] = newY;
            command = c.toHSBType();
            successApplied.put("xy", newState.xy_inc);
        } catch (ClassCastException e) {
            errorApplied.add("xy_inc");
        } catch (IllegalArgumentException e) {
            errorApplied.add("xy_inc");
        }
    }
    // Generate the response. The response consists of a list with an entry each for all
    // submitted change requests. If for example "on" and "bri" was send, 2 entries in the response are
    // expected.
    successApplied.forEach((t, v) -> {
        responses.add(new HueResponse(new HueSuccessResponseStateChanged(prefix + "/" + t, v)));
    });
    errorApplied.forEach(v -> {
        responses.add(new HueResponse(new HueErrorMessage(HueResponse.NOT_AVAILABLE, prefix + "/" + v, "Could not set")));
    });
    return command;
}
Also used : HueStateColorBulb(org.openhab.io.hueemulation.internal.dto.HueStateColorBulb) ArrayList(java.util.ArrayList) PercentType(org.openhab.core.library.types.PercentType) TreeMap(java.util.TreeMap) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse) HueErrorMessage(org.openhab.io.hueemulation.internal.dto.response.HueResponse.HueErrorMessage) Command(org.openhab.core.types.Command) HueSuccessResponseStateChanged(org.openhab.io.hueemulation.internal.dto.response.HueSuccessResponseStateChanged) Nullable(org.eclipse.jdt.annotation.Nullable)

Example 3 with HueResponse

use of org.openhab.io.hueemulation.internal.dto.response.HueResponse in project openhab-addons by openhab.

the class LightsAndGroups method setGroupActionApi.

@SuppressWarnings({ "null", "unused" })
@PUT
@Path("{username}/groups/{id}/action")
@Operation(summary = "Initiate group action", responses = { @ApiResponse(responseCode = "200", description = "OK") })
public // 
Response setGroupActionApi(// 
@Context UriInfo uri, @PathParam("username") @Parameter(description = "username") String username, @PathParam("id") @Parameter(description = "group id") String id, String body) {
    if (!userManagement.authorizeUser(username)) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.UNAUTHORIZED, "Not Authorized");
    }
    HueGroupEntry hueDevice = cs.ds.groups.get(id);
    GroupItem groupItem = hueDevice.groupItem;
    if (hueDevice == null || groupItem == null) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.NOT_AVAILABLE, "Group not existing");
    }
    HueStateChange state = cs.gson.fromJson(body, HueStateChange.class);
    if (state == null) {
        return NetworkUtils.singleError(cs.gson, uri, HueResponse.INVALID_JSON, "Invalid request: No state change data received!");
    }
    // First synchronize the internal state information with the framework
    hueDevice.action = StateUtils.colorStateFromItemState(groupItem.getState(), hueDevice.deviceType);
    List<HueResponse> responses = new ArrayList<>();
    Command command = StateUtils.computeCommandByState(responses, "/groups/" + id + "/state/", hueDevice.action, state);
    // If a command could be created, post it to the framework now
    if (command != null) {
        logger.debug("sending {} to {}", command, id);
        EventPublisher localEventPublisher = eventPublisher;
        if (localEventPublisher != null) {
            localEventPublisher.post(ItemEventFactory.createCommandEvent(groupItem.getUID(), command, "hueemulation"));
        } else {
            logger.warn("No event publisher. Cannot post item '{}' command!", groupItem.getUID());
        }
    }
    return Response.ok(cs.gson.toJson(responses, new TypeToken<List<?>>() {
    }.getType())).build();
}
Also used : HueStateChange(org.openhab.io.hueemulation.internal.dto.changerequest.HueStateChange) EventPublisher(org.openhab.core.events.EventPublisher) Command(org.openhab.core.types.Command) TypeToken(com.google.gson.reflect.TypeToken) ArrayList(java.util.ArrayList) GroupItem(org.openhab.core.items.GroupItem) HueGroupEntry(org.openhab.io.hueemulation.internal.dto.HueGroupEntry) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse) Path(javax.ws.rs.Path) Operation(io.swagger.v3.oas.annotations.Operation) PUT(javax.ws.rs.PUT)

Example 4 with HueResponse

use of org.openhab.io.hueemulation.internal.dto.response.HueResponse in project openhab-addons by openhab.

the class NetworkUtils method singleSuccess.

public static Response singleSuccess(Gson gson, String message, String uriPart) {
    List<HueResponse> responses = new ArrayList<>();
    responses.add(new HueResponse(new HueSuccessGeneric(message, uriPart)));
    return Response.ok(gson.toJson(responses, new TypeToken<List<?>>() {
    }.getType())).build();
}
Also used : TypeToken(com.google.gson.reflect.TypeToken) ArrayList(java.util.ArrayList) HueSuccessGeneric(org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse)

Example 5 with HueResponse

use of org.openhab.io.hueemulation.internal.dto.response.HueResponse in project openhab-addons by openhab.

the class NetworkUtils method singleError.

/**
 * Creates a json response with the correct Hue error code
 *
 * @param gson A gson instance
 * @param uri The original uri of the request
 * @param type Any of HueResponse.*
 * @param message A message
 * @return
 */
public static Response singleError(Gson gson, UriInfo uri, int type, @Nullable String message) {
    HueResponse e = new HueResponse(new HueErrorMessage(type, uri.getPath().replace("/api", ""), message != null ? message : ""));
    String str = gson.toJson(Collections.singleton(e), new TypeToken<List<?>>() {
    }.getType());
    int httpCode = 500;
    switch(type) {
        case HueResponse.UNAUTHORIZED:
            httpCode = 403;
            break;
        case HueResponse.METHOD_NOT_ALLOWED:
            httpCode = 405;
            break;
        case HueResponse.NOT_AVAILABLE:
            httpCode = 404;
            break;
        case HueResponse.ARGUMENTS_INVALID:
        case HueResponse.LINK_BUTTON_NOT_PRESSED:
            httpCode = 200;
            break;
    }
    return Response.status(httpCode).entity(str).build();
}
Also used : HueErrorMessage(org.openhab.io.hueemulation.internal.dto.response.HueResponse.HueErrorMessage) TypeToken(com.google.gson.reflect.TypeToken) HueResponse(org.openhab.io.hueemulation.internal.dto.response.HueResponse)

Aggregations

HueResponse (org.openhab.io.hueemulation.internal.dto.response.HueResponse)8 TypeToken (com.google.gson.reflect.TypeToken)6 ArrayList (java.util.ArrayList)4 Operation (io.swagger.v3.oas.annotations.Operation)3 Path (javax.ws.rs.Path)3 Command (org.openhab.core.types.Command)3 HueErrorMessage (org.openhab.io.hueemulation.internal.dto.response.HueResponse.HueErrorMessage)3 PUT (javax.ws.rs.PUT)2 EventPublisher (org.openhab.core.events.EventPublisher)2 HueStateChange (org.openhab.io.hueemulation.internal.dto.changerequest.HueStateChange)2 HueSuccessResponseCreateUser (org.openhab.io.hueemulation.internal.dto.response.HueSuccessResponseCreateUser)2 JsonElement (com.google.gson.JsonElement)1 TreeMap (java.util.TreeMap)1 POST (javax.ws.rs.POST)1 Produces (javax.ws.rs.Produces)1 Response (javax.ws.rs.core.Response)1 Nullable (org.eclipse.jdt.annotation.Nullable)1 Test (org.junit.jupiter.api.Test)1 GroupItem (org.openhab.core.items.GroupItem)1 PercentType (org.openhab.core.library.types.PercentType)1