]> git.basschouten.com Git - openhab-addons.git/blob
fcf05993a4394d241adca05c5771afe95e2a64fd
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.tapocontrol.internal.helpers;
14
15 import org.eclipse.jdt.annotation.NonNullByDefault;
16
17 import com.google.gson.Gson;
18 import com.google.gson.JsonObject;
19
20 /**
21  * PAYLOAD BUILDER
22  * Generates payload for TapoHttp request
23  *
24  * @author Christian Wild - Initial contribution
25  */
26 @NonNullByDefault
27 public class PayloadBuilder {
28     public String method = "";
29     private JsonObject parameters = new JsonObject();
30
31     /**
32      * Set Command
33      *
34      * @param command command (method) to send
35      */
36     public void setCommand(String command) {
37         this.method = command;
38     }
39
40     /**
41      * Add Parameter
42      *
43      * @param name parameter name
44      * @param value parameter value (typeOf Bool,Number or String)
45      */
46     public void addParameter(String name, Object value) {
47         if (value instanceof Boolean bool) {
48             this.parameters.addProperty(name, bool);
49         } else if (value instanceof Number number) {
50             this.parameters.addProperty(name, number);
51         } else {
52             this.parameters.addProperty(name, value.toString());
53         }
54     }
55
56     /**
57      * Get JSON Payload (STRING)
58      *
59      * @return String JSON-Payload
60      */
61     public String getPayload() {
62         Gson gson = new Gson();
63         JsonObject payload = getJsonPayload();
64         return gson.toJson(payload);
65     }
66
67     /**
68      * Get JSON Payload (JSON-Object)
69      *
70      * @return JsonObject JSON-Payload
71      */
72     public JsonObject getJsonPayload() {
73         JsonObject payload = new JsonObject();
74         long timeMils = System.currentTimeMillis();// * 1000;
75
76         payload.addProperty("method", this.method);
77         if (this.parameters.size() > 0) {
78             payload.add("params", this.parameters);
79         }
80         payload.addProperty("requestTimeMils", timeMils);
81
82         return payload;
83     }
84
85     /**
86      * Flush Parameters
87      * remove all parameters
88      */
89     public void flushParameters(String command) {
90         parameters = new JsonObject();
91     }
92 }