[amazonechocontrol] refactor arrays to modern types (#9476)

* refactor arrays to modern types
* address review comments

Signed-off-by: Jan N. Klug <jan.n.klug@rub.de>
pull/9819/head
J-N-K 2021-01-13 23:31:26 +01:00 committed by GitHub
parent 04d87f33db
commit e651aa6d03
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
41 changed files with 374 additions and 452 deletions

View File

@ -20,9 +20,7 @@ import java.net.URISyntaxException;
import java.net.URLDecoder; import java.net.URLDecoder;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.HashMap; import java.util.*;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.HttpsURLConnection;
@ -499,19 +497,14 @@ public class AccountServlet extends HttpServlet {
private void renderCapabilities(Connection connection, Device device, StringBuilder html) { private void renderCapabilities(Connection connection, Device device, StringBuilder html) {
html.append("<h2>Capabilities</h2>"); html.append("<h2>Capabilities</h2>");
html.append("<table><tr><th align='left'>Name</th></tr>"); html.append("<table><tr><th align='left'>Name</th></tr>");
String[] capabilities = device.capabilities; device.getCapabilities().forEach(capability -> html.append("<tr><td>")
if (capabilities != null) { .append(StringEscapeUtils.escapeHtml(capability)).append("</td></tr>"));
for (String capability : capabilities) {
html.append("<tr><td>");
html.append(StringEscapeUtils.escapeHtml(capability));
html.append("</td></tr>");
}
}
html.append("</table>"); html.append("</table>");
} }
private void renderMusicProviderIdChannel(Connection connection, StringBuilder html) { private void renderMusicProviderIdChannel(Connection connection, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_MUSIC_PROVIDER_ID) + "</h2>"); html.append("<h2>").append(StringEscapeUtils.escapeHtml("Channel " + CHANNEL_MUSIC_PROVIDER_ID))
.append("</h2>");
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>"); html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
List<JsonMusicProvider> musicProviders = connection.getMusicProviders(); List<JsonMusicProvider> musicProviders = connection.getMusicProviders();
for (JsonMusicProvider musicProvider : musicProviders) { for (JsonMusicProvider musicProvider : musicProviders) {
@ -532,8 +525,8 @@ public class AccountServlet extends HttpServlet {
} }
private void renderPlayAlarmSoundChannel(Connection connection, Device device, StringBuilder html) { private void renderPlayAlarmSoundChannel(Connection connection, Device device, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_PLAY_ALARM_SOUND) + "</h2>"); html.append("<h2>").append(StringEscapeUtils.escapeHtml("Channel " + CHANNEL_PLAY_ALARM_SOUND)).append("</h2>");
JsonNotificationSound[] notificationSounds = null; List<JsonNotificationSound> notificationSounds = List.of();
String errorMessage = "No notifications sounds found"; String errorMessage = "No notifications sounds found";
try { try {
notificationSounds = connection.getNotificationSounds(device); notificationSounds = connection.getNotificationSounds(device);
@ -541,7 +534,7 @@ public class AccountServlet extends HttpServlet {
| InterruptedException e) { | InterruptedException e) {
errorMessage = e.getLocalizedMessage(); errorMessage = e.getLocalizedMessage();
} }
if (notificationSounds != null) { if (!notificationSounds.isEmpty()) {
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>"); html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
for (JsonNotificationSound notificationSound : notificationSounds) { for (JsonNotificationSound notificationSound : notificationSounds) {
if (notificationSound.folder == null && notificationSound.providerId != null if (notificationSound.folder == null && notificationSound.providerId != null
@ -562,7 +555,8 @@ public class AccountServlet extends HttpServlet {
} }
private void renderAmazonMusicPlaylistIdChannel(Connection connection, Device device, StringBuilder html) { private void renderAmazonMusicPlaylistIdChannel(Connection connection, Device device, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_AMAZON_MUSIC_PLAY_LIST_ID) + "</h2>"); html.append("<h2>").append(StringEscapeUtils.escapeHtml("Channel " + CHANNEL_AMAZON_MUSIC_PLAY_LIST_ID))
.append("</h2>");
JsonPlaylists playLists = null; JsonPlaylists playLists = null;
String errorMessage = "No playlists found"; String errorMessage = "No playlists found";
@ -600,7 +594,7 @@ public class AccountServlet extends HttpServlet {
} }
private void renderBluetoothMacChannel(Connection connection, Device device, StringBuilder html) { private void renderBluetoothMacChannel(Connection connection, Device device, StringBuilder html) {
html.append("<h2>" + StringEscapeUtils.escapeHtml("Channel " + CHANNEL_BLUETOOTH_MAC) + "</h2>"); html.append("<h2>").append(StringEscapeUtils.escapeHtml("Channel " + CHANNEL_BLUETOOTH_MAC)).append("</h2>");
JsonBluetoothStates bluetoothStates = connection.getBluetoothConnectionStates(); JsonBluetoothStates bluetoothStates = connection.getBluetoothConnectionStates();
if (bluetoothStates == null) { if (bluetoothStates == null) {
return; return;
@ -616,8 +610,8 @@ public class AccountServlet extends HttpServlet {
String stateDeviceSerialNumber = state.deviceSerialNumber; String stateDeviceSerialNumber = state.deviceSerialNumber;
if ((stateDeviceSerialNumber == null && device.serialNumber == null) if ((stateDeviceSerialNumber == null && device.serialNumber == null)
|| (stateDeviceSerialNumber != null && stateDeviceSerialNumber.equals(device.serialNumber))) { || (stateDeviceSerialNumber != null && stateDeviceSerialNumber.equals(device.serialNumber))) {
PairedDevice[] pairedDeviceList = state.pairedDeviceList; List<PairedDevice> pairedDeviceList = state.getPairedDeviceList();
if (pairedDeviceList != null && pairedDeviceList.length > 0) { if (pairedDeviceList.size() > 0) {
html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>"); html.append("<table><tr><th align='left'>Name</th><th align='left'>Value</th></tr>");
for (PairedDevice pairedDevice : pairedDeviceList) { for (PairedDevice pairedDevice : pairedDeviceList) {
html.append("<tr><td>"); html.append("<tr><td>");

View File

@ -14,11 +14,7 @@ package org.openhab.binding.amazonechocontrol.internal;
import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*; import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants.*;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -106,17 +102,13 @@ public class AmazonEchoDynamicStateDescriptionProvider implements DynamicStateDe
if (bluetoothState == null) { if (bluetoothState == null) {
return null; return null;
} }
PairedDevice[] pairedDeviceList = bluetoothState.pairedDeviceList; List<PairedDevice> pairedDeviceList = bluetoothState.getPairedDeviceList();
if (pairedDeviceList == null) { if (pairedDeviceList.isEmpty()) {
return null; return null;
} }
List<StateOption> options = new ArrayList<>(); List<StateOption> options = new ArrayList<>();
options.add(new StateOption("", "")); options.add(new StateOption("", ""));
for (PairedDevice device : pairedDeviceList) { for (PairedDevice device : pairedDeviceList) {
if (device == null) {
continue;
}
final String value = device.address; final String value = device.address;
if (value != null && device.friendlyName != null) { if (value != null && device.friendlyName != null) {
options.add(new StateOption(value, device.friendlyName)); options.add(new StateOption(value, device.friendlyName));
@ -160,8 +152,8 @@ public class AmazonEchoDynamicStateDescriptionProvider implements DynamicStateDe
return null; return null;
} }
JsonNotificationSound[] notificationSounds = handler.findAlarmSounds(); List<JsonNotificationSound> notificationSounds = handler.findAlarmSounds();
if (notificationSounds == null) { if (notificationSounds.isEmpty()) {
return null; return null;
} }
@ -169,9 +161,8 @@ public class AmazonEchoDynamicStateDescriptionProvider implements DynamicStateDe
options.add(new StateOption("", "")); options.add(new StateOption("", ""));
for (JsonNotificationSound notificationSound : notificationSounds) { for (JsonNotificationSound notificationSound : notificationSounds) {
if (notificationSound != null && notificationSound.folder == null if (notificationSound.folder == null && notificationSound.providerId != null
&& notificationSound.providerId != null && notificationSound.id != null && notificationSound.id != null && notificationSound.displayName != null) {
&& notificationSound.displayName != null) {
String providerSoundId = notificationSound.providerId + ":" + notificationSound.id; String providerSoundId = notificationSound.providerId + ":" + notificationSound.id;
options.add(new StateOption(providerSoundId, notificationSound.displayName)); options.add(new StateOption(providerSoundId, notificationSound.displayName));
} }
@ -197,8 +188,7 @@ public class AmazonEchoDynamicStateDescriptionProvider implements DynamicStateDe
options.add(new StateOption("", "")); options.add(new StateOption("", ""));
for (Device device : devices) { for (Device device : devices) {
final String value = device.serialNumber; final String value = device.serialNumber;
if (value != null && device.capabilities != null if (value != null && device.getCapabilities().contains("FLASH_BRIEFING")) {
&& Arrays.asList(device.capabilities).contains("FLASH_BRIEFING")) {
options.add(new StateOption(value, device.accountName)); options.add(new StateOption(value, device.accountName));
} }
} }
@ -210,7 +200,7 @@ public class AmazonEchoDynamicStateDescriptionProvider implements DynamicStateDe
return null; return null;
} }
List<JsonMusicProvider> musicProviders = handler.findMusicProviders(); List<JsonMusicProvider> musicProviders = handler.findMusicProviders();
if (musicProviders == null) { if (musicProviders.isEmpty()) {
return null; return null;
} }

View File

@ -53,7 +53,6 @@ import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm.AscendingAlarmModel; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm.AscendingAlarmModel;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation.Payload; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation.Payload;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAutomation.Trigger;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBootstrapResult; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBootstrapResult;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBootstrapResult.Authentication; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBootstrapResult.Authentication;
@ -483,15 +482,13 @@ public class Connection {
try { try {
String bootstrapResultJson = convertStream(connection); String bootstrapResultJson = convertStream(connection);
JsonBootstrapResult result = parseJson(bootstrapResultJson, JsonBootstrapResult.class); JsonBootstrapResult result = parseJson(bootstrapResultJson, JsonBootstrapResult.class);
if (result != null) { Authentication authentication = result.authentication;
Authentication authentication = result.authentication; if (authentication != null && authentication.authenticated) {
if (authentication != null && authentication.authenticated) { this.customerName = authentication.customerName;
this.customerName = authentication.customerName; if (this.accountCustomerId == null) {
if (this.accountCustomerId == null) { this.accountCustomerId = authentication.customerId;
this.accountCustomerId = authentication.customerId;
}
return authentication;
} }
return authentication;
} }
} catch (JsonSyntaxException | IllegalStateException e) { } catch (JsonSyntaxException | IllegalStateException e) {
logger.info("No valid json received", e); logger.info("No valid json received", e);
@ -726,11 +723,8 @@ public class Connection {
webSiteCookies.add(new JsonWebSiteCookie(cookie.getName(), cookie.getValue())); webSiteCookies.add(new JsonWebSiteCookie(cookie.getName(), cookie.getValue()));
} }
JsonWebSiteCookie[] webSiteCookiesArray = new JsonWebSiteCookie[webSiteCookies.size()];
webSiteCookiesArray = webSiteCookies.toArray(webSiteCookiesArray);
JsonRegisterAppRequest registerAppRequest = new JsonRegisterAppRequest(serial, accessToken, frc, JsonRegisterAppRequest registerAppRequest = new JsonRegisterAppRequest(serial, accessToken, frc,
webSiteCookiesArray); webSiteCookies);
String registerAppRequestJson = gson.toJson(registerAppRequest); String registerAppRequestJson = gson.toJson(registerAppRequest);
HashMap<String, String> registerHeaders = new HashMap<>(); HashMap<String, String> registerHeaders = new HashMap<>();
@ -740,9 +734,6 @@ public class Connection {
registerAppRequestJson, true, registerHeaders); registerAppRequestJson, true, registerHeaders);
JsonRegisterAppResponse registerAppResponse = parseJson(registerAppResultJson, JsonRegisterAppResponse.class); JsonRegisterAppResponse registerAppResponse = parseJson(registerAppResultJson, JsonRegisterAppResponse.class);
if (registerAppResponse == null) {
throw new ConnectionException("Error: No response received from register application");
}
Response response = registerAppResponse.response; Response response = registerAppResponse.response;
if (response == null) { if (response == null) {
throw new ConnectionException("Error: No response received from register application"); throw new ConnectionException("Error: No response received from register application");
@ -770,9 +761,6 @@ public class Connection {
String usersMeResponseJson = makeRequestAndReturnString("GET", String usersMeResponseJson = makeRequestAndReturnString("GET",
"https://alexa.amazon.com/api/users/me?platform=ios&version=2.2.223830.0", null, false, null); "https://alexa.amazon.com/api/users/me?platform=ios&version=2.2.223830.0", null, false, null);
JsonUsersMeResponse usersMeResponse = parseJson(usersMeResponseJson, JsonUsersMeResponse.class); JsonUsersMeResponse usersMeResponse = parseJson(usersMeResponseJson, JsonUsersMeResponse.class);
if (usersMeResponse == null) {
throw new IllegalArgumentException("Received no response on me-request");
}
URI uri = new URI(usersMeResponse.marketPlaceDomainName); URI uri = new URI(usersMeResponse.marketPlaceDomainName);
String host = uri.getHost(); String host = uri.getHost();
@ -928,6 +916,7 @@ public class Connection {
} }
} }
@SuppressWarnings("null") // current value in compute can be null
private void replaceTimer(TimerType type, @Nullable ScheduledFuture<?> newTimer) { private void replaceTimer(TimerType type, @Nullable ScheduledFuture<?> newTimer) {
timers.compute(type, (timerType, oldTimer) -> { timers.compute(type, (timerType, oldTimer) -> {
if (oldTimer != null) { if (oldTimer != null) {
@ -967,9 +956,10 @@ public class Connection {
} }
// parser // parser
private <T> @Nullable T parseJson(String json, Class<T> type) throws JsonSyntaxException, IllegalStateException { private <T> T parseJson(String json, Class<T> type) throws JsonSyntaxException, IllegalStateException {
try { try {
return gson.fromJson(json, type); // gson.fromJson is always non-null if json is non-null
return Objects.requireNonNull(gson.fromJson(json, type));
} catch (JsonParseException | IllegalStateException e) { } catch (JsonParseException | IllegalStateException e) {
logger.warn("Parsing json failed: {}", json, e); logger.warn("Parsing json failed: {}", json, e);
throw e; throw e;
@ -977,21 +967,16 @@ public class Connection {
} }
// commands and states // commands and states
public WakeWord[] getWakeWords() { public List<WakeWord> getWakeWords() {
String json; String json;
try { try {
json = makeRequestAndReturnString(alexaServer + "/api/wake-word?cached=true"); json = makeRequestAndReturnString(alexaServer + "/api/wake-word?cached=true");
JsonWakeWords wakeWords = parseJson(json, JsonWakeWords.class); JsonWakeWords wakeWords = parseJson(json, JsonWakeWords.class);
if (wakeWords != null) { return Objects.requireNonNullElse(wakeWords.wakeWords, List.of());
WakeWord[] result = wakeWords.wakeWords;
if (result != null) {
return result;
}
}
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.info("getting wakewords failed", e); logger.info("getting wakewords failed", e);
} }
return new WakeWord[0]; return List.of();
} }
public List<SmartHomeBaseDevice> getSmarthomeDeviceList() public List<SmartHomeBaseDevice> getSmarthomeDeviceList()
@ -1001,9 +986,6 @@ public class Connection {
logger.debug("getSmartHomeDevices result: {}", json); logger.debug("getSmartHomeDevices result: {}", json);
JsonNetworkDetails networkDetails = parseJson(json, JsonNetworkDetails.class); JsonNetworkDetails networkDetails = parseJson(json, JsonNetworkDetails.class);
if (networkDetails == null) {
throw new IllegalArgumentException("received no response on network detail request");
}
Object jsonObject = gson.fromJson(networkDetails.networkDetail, Object.class); Object jsonObject = gson.fromJson(networkDetails.networkDetail, Object.class);
List<SmartHomeBaseDevice> result = new ArrayList<>(); List<SmartHomeBaseDevice> result = new ArrayList<>();
searchSmartHomeDevicesRecursive(jsonObject, result); searchSmartHomeDevicesRecursive(jsonObject, result);
@ -1023,15 +1005,11 @@ public class Connection {
// device node found, create type element and add it to the results // device node found, create type element and add it to the results
JsonElement element = gson.toJsonTree(jsonNode); JsonElement element = gson.toJsonTree(jsonNode);
SmartHomeDevice shd = parseJson(element.toString(), SmartHomeDevice.class); SmartHomeDevice shd = parseJson(element.toString(), SmartHomeDevice.class);
if (shd != null) { devices.add(shd);
devices.add(shd);
}
} else if (map.containsKey("applianceGroupName")) { } else if (map.containsKey("applianceGroupName")) {
JsonElement element = gson.toJsonTree(jsonNode); JsonElement element = gson.toJsonTree(jsonNode);
SmartHomeGroup shg = parseJson(element.toString(), SmartHomeGroup.class); SmartHomeGroup shg = parseJson(element.toString(), SmartHomeGroup.class);
if (shg != null) { devices.add(shg);
devices.add(shg);
}
} else { } else {
map.values().forEach(value -> searchSmartHomeDevicesRecursive(value, devices)); map.values().forEach(value -> searchSmartHomeDevicesRecursive(value, devices));
} }
@ -1062,8 +1040,10 @@ public class Connection {
String applianceId = device.findId(); String applianceId = device.findId();
if (applianceId != null) { if (applianceId != null) {
JsonObject stateRequest; JsonObject stateRequest;
if (device instanceof SmartHomeDevice && !((SmartHomeDevice) device).mergedApplianceIds.isEmpty()) { if (device instanceof SmartHomeDevice && ((SmartHomeDevice) device).mergedApplianceIds != null) {
for (String idToMerge : ((SmartHomeDevice) device).mergedApplianceIds) { List<String> mergedApplianceIds = Objects
.requireNonNullElse(((SmartHomeDevice) device).mergedApplianceIds, List.of());
for (String idToMerge : mergedApplianceIds) {
mergedApplianceMap.put(idToMerge, applianceId); mergedApplianceMap.put(idToMerge, applianceId);
stateRequest = new JsonObject(); stateRequest = new JsonObject();
stateRequest.addProperty("entityId", idToMerge); stateRequest.addProperty("entityId", idToMerge);
@ -1125,22 +1105,16 @@ public class Connection {
return mediaState; return mediaState;
} }
public Activity[] getActivities(int number, @Nullable Long startTime) { public List<Activity> getActivities(int number, @Nullable Long startTime) {
String json;
try { try {
json = makeRequestAndReturnString(alexaServer + "/api/activities?startTime=" String json = makeRequestAndReturnString(alexaServer + "/api/activities?startTime="
+ (startTime != null ? startTime : "") + "&size=" + number + "&offset=1"); + (startTime != null ? startTime : "") + "&size=" + number + "&offset=1");
JsonActivities activities = parseJson(json, JsonActivities.class); JsonActivities activities = parseJson(json, JsonActivities.class);
if (activities != null) { return Objects.requireNonNullElse(activities.activities, List.of());
Activity[] activiesArray = activities.activities;
if (activiesArray != null) {
return activiesArray;
}
}
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.info("getting activities failed", e); logger.info("getting activities failed", e);
} }
return new Activity[0]; return List.of();
} }
public @Nullable JsonBluetoothStates getBluetoothConnectionStates() { public @Nullable JsonBluetoothStates getBluetoothConnectionStates() {
@ -1211,17 +1185,16 @@ public class Connection {
String resultBody = makeRequestAndReturnString("PUT", url, requestBody, true, null); String resultBody = makeRequestAndReturnString("PUT", url, requestBody, true, null);
logger.trace("Request '{}' resulted in '{}", requestBody, resultBody); logger.trace("Request '{}' resulted in '{}", requestBody, resultBody);
JsonObject result = parseJson(resultBody, JsonObject.class); JsonObject result = parseJson(resultBody, JsonObject.class);
if (result != null) { JsonElement errors = result.get("errors");
JsonElement errors = result.get("errors"); if (errors != null && errors.isJsonArray()) {
if (errors != null && errors.isJsonArray()) { JsonArray errorList = errors.getAsJsonArray();
JsonArray errorList = errors.getAsJsonArray(); if (errorList.size() > 0) {
if (errorList.size() > 0) { logger.warn("Smart home device command failed. The request '{}' resulted in error(s): {}",
logger.warn("Smart home device command failed. The request '{}' resulted in error(s): {}", requestBody, StreamSupport.stream(errorList.spliterator(), false).map(JsonElement::toString)
requestBody, StreamSupport.stream(errorList.spliterator(), false) .collect(Collectors.joining(" / ")));
.map(JsonElement::toString).collect(Collectors.joining(" / ")));
}
} }
} }
} catch (URISyntaxException e) { } catch (URISyntaxException e) {
logger.warn("URL '{}' has invalid format for request '{}': {}", url, requestBody, e.getMessage()); logger.warn("URL '{}' has invalid format for request '{}': {}", url, requestBody, e.getMessage());
} }
@ -1245,38 +1218,28 @@ public class Connection {
makeRequest("PUT", url, command, true, true, null, 0); makeRequest("PUT", url, command, true, true, null, 0);
} }
public DeviceNotificationState[] getDeviceNotificationStates() { public List<DeviceNotificationState> getDeviceNotificationStates() {
String json;
try { try {
json = makeRequestAndReturnString(alexaServer + "/api/device-notification-state"); String json = makeRequestAndReturnString(alexaServer + "/api/device-notification-state");
JsonDeviceNotificationState result = parseJson(json, JsonDeviceNotificationState.class); JsonDeviceNotificationState result = parseJson(json, JsonDeviceNotificationState.class);
if (result != null) { return Objects.requireNonNullElse(result.deviceNotificationStates, List.of());
DeviceNotificationState[] deviceNotificationStates = result.deviceNotificationStates;
if (deviceNotificationStates != null) {
return deviceNotificationStates;
}
}
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.info("Error getting device notification states", e); logger.info("Error getting device notification states", e);
} }
return new DeviceNotificationState[0]; return List.of();
} }
public AscendingAlarmModel[] getAscendingAlarm() { public List<AscendingAlarmModel> getAscendingAlarm() {
String json; String json;
try { try {
json = makeRequestAndReturnString(alexaServer + "/api/ascending-alarm"); json = makeRequestAndReturnString(alexaServer + "/api/ascending-alarm");
JsonAscendingAlarm result = parseJson(json, JsonAscendingAlarm.class); JsonAscendingAlarm result = parseJson(json, JsonAscendingAlarm.class);
if (result != null) { return Objects.requireNonNullElse(result.ascendingAlarmModelList, List.of());
AscendingAlarmModel[] ascendingAlarmModelList = result.ascendingAlarmModelList;
if (ascendingAlarmModelList != null) {
return ascendingAlarmModelList;
}
}
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.info("Error getting device notification states", e); logger.info("Error getting device notification states", e);
} }
return new AscendingAlarmModel[0]; return List.of();
} }
public void bluetooth(Device device, @Nullable String address) public void bluetooth(Device device, @Nullable String address)
@ -1630,6 +1593,7 @@ public class Connection {
logger.debug("added {} device {}", queueObject.hashCode(), serialNumbers); logger.debug("added {} device {}", queueObject.hashCode(), serialNumbers);
} }
@SuppressWarnings("null") // peek can return null
private void handleExecuteSequenceNode() { private void handleExecuteSequenceNode() {
Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.DEVICES, k -> new ReentrantLock())); Lock lock = Objects.requireNonNull(locks.computeIfAbsent(TimerType.DEVICES, k -> new ReentrantLock()));
if (lock.tryLock()) { if (lock.tryLock()) {
@ -1853,12 +1817,9 @@ public class Connection {
} }
for (JsonAutomation routine : routines) { for (JsonAutomation routine : routines) {
if (routine != null) { if (routine != null) {
Trigger[] triggers = routine.triggers; if (routine.sequence != null) {
if (triggers != null && routine.sequence != null) { List<JsonAutomation.Trigger> triggers = Objects.requireNonNullElse(routine.triggers, List.of());
for (JsonAutomation.Trigger trigger : triggers) { for (JsonAutomation.Trigger trigger : triggers) {
if (trigger == null) {
continue;
}
Payload payload = trigger.payload; Payload payload = trigger.payload;
if (payload == null) { if (payload == null) {
continue; continue;
@ -1921,20 +1882,13 @@ public class Connection {
return result; return result;
} }
public JsonFeed[] getEnabledFlashBriefings() throws IOException, URISyntaxException, InterruptedException { public List<JsonFeed> getEnabledFlashBriefings() throws IOException, URISyntaxException, InterruptedException {
String json = makeRequestAndReturnString(alexaServer + "/api/content-skills/enabled-feeds"); String json = makeRequestAndReturnString(alexaServer + "/api/content-skills/enabled-feeds");
JsonEnabledFeeds result = parseJson(json, JsonEnabledFeeds.class); JsonEnabledFeeds result = parseJson(json, JsonEnabledFeeds.class);
if (result == null) { return Objects.requireNonNullElse(result.enabledFeeds, List.of());
return new JsonFeed[0];
}
JsonFeed[] enabledFeeds = result.enabledFeeds;
if (enabledFeeds != null) {
return enabledFeeds;
}
return new JsonFeed[0];
} }
public void setEnabledFlashBriefings(JsonFeed[] enabledFlashBriefing) public void setEnabledFlashBriefings(List<JsonFeed> enabledFlashBriefing)
throws IOException, URISyntaxException, InterruptedException { throws IOException, URISyntaxException, InterruptedException {
JsonEnabledFeeds enabled = new JsonEnabledFeeds(); JsonEnabledFeeds enabled = new JsonEnabledFeeds();
enabled.enabledFeeds = enabledFlashBriefing; enabled.enabledFeeds = enabledFlashBriefing;
@ -1942,33 +1896,19 @@ public class Connection {
makeRequest("POST", alexaServer + "/api/content-skills/enabled-feeds", json, true, true, null, 0); makeRequest("POST", alexaServer + "/api/content-skills/enabled-feeds", json, true, true, null, 0);
} }
public JsonNotificationSound[] getNotificationSounds(Device device) public List<JsonNotificationSound> getNotificationSounds(Device device)
throws IOException, URISyntaxException, InterruptedException { throws IOException, URISyntaxException, InterruptedException {
String json = makeRequestAndReturnString( String json = makeRequestAndReturnString(
alexaServer + "/api/notification/sounds?deviceSerialNumber=" + device.serialNumber + "&deviceType=" alexaServer + "/api/notification/sounds?deviceSerialNumber=" + device.serialNumber + "&deviceType="
+ device.deviceType + "&softwareVersion=" + device.softwareVersion); + device.deviceType + "&softwareVersion=" + device.softwareVersion);
JsonNotificationSounds result = parseJson(json, JsonNotificationSounds.class); JsonNotificationSounds result = parseJson(json, JsonNotificationSounds.class);
if (result == null) { return Objects.requireNonNullElse(result.notificationSounds, List.of());
return new JsonNotificationSound[0];
}
JsonNotificationSound[] notificationSounds = result.notificationSounds;
if (notificationSounds != null) {
return notificationSounds;
}
return new JsonNotificationSound[0];
} }
public JsonNotificationResponse[] notifications() throws IOException, URISyntaxException, InterruptedException { public List<JsonNotificationResponse> notifications() throws IOException, URISyntaxException, InterruptedException {
String response = makeRequestAndReturnString(alexaServer + "/api/notifications"); String response = makeRequestAndReturnString(alexaServer + "/api/notifications");
JsonNotificationsResponse result = parseJson(response, JsonNotificationsResponse.class); JsonNotificationsResponse result = parseJson(response, JsonNotificationsResponse.class);
if (result == null) { return Objects.requireNonNullElse(result.notifications, List.of());
return new JsonNotificationResponse[0];
}
JsonNotificationResponse[] notifications = result.notifications;
if (notifications == null) {
return new JsonNotificationResponse[0];
}
return notifications;
} }
public @Nullable JsonNotificationResponse notification(Device device, String type, @Nullable String label, public @Nullable JsonNotificationResponse notification(Device device, String type, @Nullable String label,
@ -2019,8 +1959,8 @@ public class Connection {
String response = makeRequestAndReturnString("GET", String response = makeRequestAndReturnString("GET",
alexaServer + "/api/behaviors/entities?skillId=amzn1.ask.1p.music", null, true, headers); alexaServer + "/api/behaviors/entities?skillId=amzn1.ask.1p.music", null, true, headers);
if (!response.isEmpty()) { if (!response.isEmpty()) {
JsonMusicProvider[] result = parseJson(response, JsonMusicProvider[].class); JsonMusicProvider[] musicProviders = parseJson(response, JsonMusicProvider[].class);
return Arrays.asList(result); return Arrays.asList(musicProviders);
} }
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.warn("getMusicProviders fails: {}", e.getMessage()); logger.warn("getMusicProviders fails: {}", e.getMessage());
@ -2050,12 +1990,10 @@ public class Connection {
if (!validateResultJson.isEmpty()) { if (!validateResultJson.isEmpty()) {
JsonPlayValidationResult validationResult = parseJson(validateResultJson, JsonPlayValidationResult.class); JsonPlayValidationResult validationResult = parseJson(validateResultJson, JsonPlayValidationResult.class);
if (validationResult != null) { JsonPlaySearchPhraseOperationPayload validatedOperationPayload = validationResult.operationPayload;
JsonPlaySearchPhraseOperationPayload validatedOperationPayload = validationResult.operationPayload; if (validatedOperationPayload != null) {
if (validatedOperationPayload != null) { payload.sanitizedSearchPhrase = validatedOperationPayload.sanitizedSearchPhrase;
payload.sanitizedSearchPhrase = validatedOperationPayload.sanitizedSearchPhrase; payload.searchPhrase = validatedOperationPayload.searchPhrase;
payload.searchPhrase = validatedOperationPayload.searchPhrase;
}
} }
} }

View File

@ -73,9 +73,7 @@ public class WebSocketConnection {
IWebSocketCommandHandler webSocketCommandHandler) throws IOException { IWebSocketCommandHandler webSocketCommandHandler) throws IOException {
this.webSocketCommandHandler = webSocketCommandHandler; this.webSocketCommandHandler = webSocketCommandHandler;
amazonEchoControlWebSocket = new AmazonEchoControlWebSocket(); amazonEchoControlWebSocket = new AmazonEchoControlWebSocket();
webSocketClient = new WebSocketClient(new SslContextFactory.Client());
SslContextFactory sslContextFactory = new SslContextFactory();
webSocketClient = new WebSocketClient(sslContextFactory);
try { try {
String host; String host;
if (amazonSite.equalsIgnoreCase("amazon.com")) { if (amazonSite.equalsIgnoreCase("amazon.com")) {

View File

@ -22,14 +22,12 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler; import org.openhab.binding.amazonechocontrol.internal.handler.AccountHandler;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler; import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDeviceAlias; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDeviceAlias;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
@ -171,25 +169,23 @@ public class SmartHomeDevicesDiscovery extends AbstractDiscoveryService {
continue; continue;
} }
JsonSmartHomeCapabilities.SmartHomeCapability[] capabilities = shd.capabilities; if (shd.getCapabilities().stream()
if (capabilities == null || Stream.of(capabilities).noneMatch(capability -> capability != null .noneMatch(capability -> Constants.SUPPORTED_INTERFACES.contains(capability.interfaceName))) {
&& Constants.SUPPORTED_INTERFACES.contains(capability.interfaceName))) {
// No supported interface found // No supported interface found
continue; continue;
} }
thingUID = new ThingUID(THING_TYPE_SMART_HOME_DEVICE, bridgeThingUID, entityId.replace(".", "-")); thingUID = new ThingUID(THING_TYPE_SMART_HOME_DEVICE, bridgeThingUID, entityId.replace(".", "-"));
JsonSmartHomeDeviceAlias[] aliases = shd.aliases; List<JsonSmartHomeDeviceAlias> aliases = shd.aliases;
if ("Amazon".equals(shd.manufacturerName) && driverIdentity != null if ("Amazon".equals(shd.manufacturerName) && driverIdentity != null
&& "SonarCloudService".equals(driverIdentity.identifier)) { && "SonarCloudService".equals(driverIdentity.identifier)) {
deviceName = "Alexa Guard on " + shd.friendlyName; deviceName = "Alexa Guard on " + shd.friendlyName;
} else if ("Amazon".equals(shd.manufacturerName) && driverIdentity != null } else if ("Amazon".equals(shd.manufacturerName) && driverIdentity != null
&& "OnGuardSmartHomeBridgeService".equals(driverIdentity.identifier)) { && "OnGuardSmartHomeBridgeService".equals(driverIdentity.identifier)) {
deviceName = "Alexa Guard"; deviceName = "Alexa Guard";
} else if (aliases != null && aliases.length > 0 && aliases[0] != null } else if (aliases != null && !aliases.isEmpty() && aliases.get(0).friendlyName != null) {
&& aliases[0].friendlyName != null) { deviceName = aliases.get(0).friendlyName;
deviceName = aliases[0].friendlyName;
} else { } else {
deviceName = shd.friendlyName; deviceName = shd.friendlyName;
} }

View File

@ -17,15 +17,7 @@ import java.net.URISyntaxException;
import java.net.URLEncoder; import java.net.URLEncoder;
import java.net.UnknownHostException; import java.net.UnknownHostException;
import java.time.ZonedDateTime; import java.time.ZonedDateTime;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
@ -44,7 +36,6 @@ import org.openhab.binding.amazonechocontrol.internal.WebSocketConnection;
import org.openhab.binding.amazonechocontrol.internal.channelhandler.ChannelHandler; import org.openhab.binding.amazonechocontrol.internal.channelhandler.ChannelHandler;
import org.openhab.binding.amazonechocontrol.internal.channelhandler.ChannelHandlerSendMessage; import org.openhab.binding.amazonechocontrol.internal.channelhandler.ChannelHandlerSendMessage;
import org.openhab.binding.amazonechocontrol.internal.channelhandler.IAmazonThingHandler; import org.openhab.binding.amazonechocontrol.internal.channelhandler.IAmazonThingHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonActivities.Activity.SourceDeviceId;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm.AscendingAlarmModel; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonAscendingAlarm.AscendingAlarmModel;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonBluetoothStates.BluetoothState;
@ -473,18 +464,17 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
if (!currentConnection.getIsLoggedIn()) { if (!currentConnection.getIsLoggedIn()) {
return; return;
} }
JsonNotificationResponse[] notifications;
ZonedDateTime timeStamp = ZonedDateTime.now(); ZonedDateTime timeStamp = ZonedDateTime.now();
try { try {
notifications = currentConnection.notifications(); List<JsonNotificationResponse> notifications = currentConnection.notifications();
ZonedDateTime timeStampNow = ZonedDateTime.now();
echoHandlers.forEach(echoHandler -> echoHandler.updateNotifications(timeStamp, timeStampNow, pushPayload,
notifications));
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.debug("refreshNotifications failed", e); logger.debug("refreshNotifications failed", e);
return; return;
} }
ZonedDateTime timeStampNow = ZonedDateTime.now();
echoHandlers.forEach(
echoHandler -> echoHandler.updateNotifications(timeStamp, timeStampNow, pushPayload, notifications));
} }
private void refreshData() { private void refreshData() {
@ -509,8 +499,8 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
updateSmartHomeDeviceList(false); updateSmartHomeDeviceList(false);
updateFlashBriefingHandlers(); updateFlashBriefingHandlers();
DeviceNotificationState[] deviceNotificationStates = null; List<DeviceNotificationState> deviceNotificationStates = List.of();
AscendingAlarmModel[] ascendingAlarmModels = null; List<AscendingAlarmModel> ascendingAlarmModels = List.of();
JsonBluetoothStates states = null; JsonBluetoothStates states = null;
List<JsonMusicProvider> musicProviders = null; List<JsonMusicProvider> musicProviders = null;
if (currentConnection.getIsLoggedIn()) { if (currentConnection.getIsLoggedIn()) {
@ -536,7 +526,7 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
for (EchoHandler child : echoHandlers) { for (EchoHandler child : echoHandlers) {
Device device = findDeviceJson(child.findSerialNumber()); Device device = findDeviceJson(child.findSerialNumber());
JsonNotificationSound[] notificationSounds = null; List<JsonNotificationSound> notificationSounds = List.of();
JsonPlaylists playlists = null; JsonPlaylists playlists = null;
if (device != null && currentConnection.getIsLoggedIn()) { if (device != null && currentConnection.getIsLoggedIn()) {
// update notification sounds // update notification sounds
@ -562,17 +552,12 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
if (device != null) { if (device != null) {
final String serialNumber = device.serialNumber; final String serialNumber = device.serialNumber;
if (serialNumber != null) { if (serialNumber != null) {
if (ascendingAlarmModels != null) { ascendingAlarmModel = ascendingAlarmModels.stream()
ascendingAlarmModel = Arrays.stream(ascendingAlarmModels).filter(Objects::nonNull) .filter(current -> serialNumber.equals(current.deviceSerialNumber)).findFirst()
.filter(current -> serialNumber.equals(current.deviceSerialNumber)).findFirst() .orElse(null);
.orElse(null); deviceNotificationState = deviceNotificationStates.stream()
} .filter(current -> serialNumber.equals(current.deviceSerialNumber)).findFirst()
if (deviceNotificationStates != null) { .orElse(null);
deviceNotificationState = Arrays.stream(deviceNotificationStates)
.filter(Objects::nonNull)
.filter(current -> serialNumber.equals(current.deviceSerialNumber)).findFirst()
.orElse(null);
}
} }
} }
child.updateState(this, device, state, deviceNotificationState, ascendingAlarmModel, playlists, child.updateState(this, device, state, deviceNotificationState, ascendingAlarmModel, playlists,
@ -631,19 +616,13 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
.collect(Collectors.toMap(d -> Objects.requireNonNull(d.serialNumber), d -> d)); .collect(Collectors.toMap(d -> Objects.requireNonNull(d.serialNumber), d -> d));
} }
WakeWord[] wakeWords = currentConnection.getWakeWords(); List<WakeWord> wakeWords = currentConnection.getWakeWords();
// update handlers // update handlers
for (EchoHandler echoHandler : echoHandlers) { for (EchoHandler echoHandler : echoHandlers) {
String serialNumber = echoHandler.findSerialNumber(); String serialNumber = echoHandler.findSerialNumber();
String deviceWakeWord = null; String deviceWakeWord = wakeWords.stream()
for (WakeWord wakeWord : wakeWords) { .filter(wakeWord -> serialNumber.equals(wakeWord.deviceSerialNumber)).findFirst()
if (wakeWord != null) { .map(wakeWord -> wakeWord.wakeWord).orElse(null);
if (serialNumber.equals(wakeWord.deviceSerialNumber)) {
deviceWakeWord = wakeWord.wakeWord;
break;
}
}
}
echoHandler.setDeviceAndUpdateThingState(this, findDeviceJson(serialNumber), deviceWakeWord); echoHandler.setDeviceAndUpdateThingState(this, findDeviceJson(serialNumber), deviceWakeWord);
} }
@ -658,7 +637,7 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
JsonFeed[] feeds = gson.fromJson(flashBriefingJson, JsonFeed[].class); JsonFeed[] feeds = gson.fromJson(flashBriefingJson, JsonFeed[].class);
if (currentConnection != null && feeds != null) { if (currentConnection != null && feeds != null) {
try { try {
currentConnection.setEnabledFlashBriefings(feeds); currentConnection.setEnabledFlashBriefings(Arrays.asList(feeds));
} catch (IOException | URISyntaxException | InterruptedException e) { } catch (IOException | URISyntaxException | InterruptedException e) {
logger.warn("Set flashbriefing profile failed", e); logger.warn("Set flashbriefing profile failed", e);
} }
@ -707,17 +686,9 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
private void updateFlashBriefingProfiles(Connection currentConnection) { private void updateFlashBriefingProfiles(Connection currentConnection) {
try { try {
JsonFeed[] feeds = currentConnection.getEnabledFlashBriefings();
// Make a copy and remove changeable parts // Make a copy and remove changeable parts
JsonFeed[] forSerializer = new JsonFeed[feeds.length]; JsonFeed[] forSerializer = currentConnection.getEnabledFlashBriefings().stream()
for (int i = 0; i < feeds.length; i++) { .map(source -> new JsonFeed(source.feedId, source.skillId)).toArray(JsonFeed[]::new);
JsonFeed source = feeds[i];
JsonFeed copy = new JsonFeed();
copy.feedId = source.feedId;
copy.skillId = source.skillId;
// Do not copy imageUrl here, because it will change
forSerializer[i] = copy;
}
this.currentFlashBriefingJson = gson.toJson(forSerializer); this.currentFlashBriefingJson = gson.toJson(forSerializer);
} catch (HttpException | JsonSyntaxException | IOException | URISyntaxException | ConnectionException } catch (HttpException | JsonSyntaxException | IOException | URISyntaxException | ConnectionException
| InterruptedException e) { | InterruptedException e) {
@ -796,17 +767,12 @@ public class AccountHandler extends BaseBridgeHandler implements IWebSocketComma
} }
String search = key.registeredUserId + "#" + key.entryId; String search = key.registeredUserId + "#" + key.entryId;
Arrays.stream(connection.getActivities(10, pushActivity.timestamp)) connection.getActivities(10, pushActivity.timestamp).stream().filter(activity -> search.equals(activity.id))
.filter(activity -> activity != null && search.equals(activity.id)).findFirst() .findFirst()
.ifPresent(currentActivity -> { .ifPresent(currentActivity -> currentActivity.getSourceDeviceIds().stream()
SourceDeviceId[] sourceDeviceIds = currentActivity.sourceDeviceIds; .map(sourceDeviceId -> findEchoHandlerBySerialNumber(sourceDeviceId.serialNumber))
if (sourceDeviceIds != null) { .filter(Objects::nonNull).forEach(echoHandler -> Objects.requireNonNull(echoHandler)
Arrays.stream(sourceDeviceIds).filter(Objects::nonNull) .handlePushActivity(currentActivity)));
.map(sourceDeviceId -> findEchoHandlerBySerialNumber(sourceDeviceId.serialNumber))
.filter(Objects::nonNull).forEach(echoHandler -> Objects.requireNonNull(echoHandler)
.handlePushActivity(currentActivity));
}
});
} }
void refreshAfterCommand() { void refreshAfterCommand() {

View File

@ -24,8 +24,6 @@ import java.time.temporal.ChronoUnit;
import java.util.*; import java.util.*;
import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -122,8 +120,8 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
private @Nullable Integer notificationVolumeLevel; private @Nullable Integer notificationVolumeLevel;
private @Nullable Boolean ascendingAlarm; private @Nullable Boolean ascendingAlarm;
private @Nullable JsonPlaylists playLists; private @Nullable JsonPlaylists playLists;
private @Nullable JsonNotificationSound @Nullable [] alarmSounds; private List<JsonNotificationSound> alarmSounds = List.of();
private @Nullable List<JsonMusicProvider> musicProviders; private List<JsonMusicProvider> musicProviders = List.of();
private List<ChannelHandler> channelHandlers = new ArrayList<>(); private List<ChannelHandler> channelHandlers = new ArrayList<>();
private @Nullable JsonNotificationResponse currentNotification; private @Nullable JsonNotificationResponse currentNotification;
@ -163,10 +161,7 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
return false; return false;
} }
this.device = device; this.device = device;
String[] capabilities = device.capabilities; this.capabilities = device.getCapabilities();
if (capabilities != null) {
this.capabilities = Stream.of(capabilities).filter(Objects::nonNull).collect(Collectors.toSet());
}
if (!device.online) { if (!device.online) {
updateStatus(ThingStatus.OFFLINE); updateStatus(ThingStatus.OFFLINE);
return false; return false;
@ -204,11 +199,11 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
return this.playLists; return this.playLists;
} }
public @Nullable JsonNotificationSound @Nullable [] findAlarmSounds() { public List<JsonNotificationSound> findAlarmSounds() {
return this.alarmSounds; return this.alarmSounds;
} }
public @Nullable List<JsonMusicProvider> findMusicProviders() { public List<JsonMusicProvider> findMusicProviders() {
return this.musicProviders; return this.musicProviders;
} }
@ -444,17 +439,11 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
String bluetoothId = lastKnownBluetoothMAC; String bluetoothId = lastKnownBluetoothMAC;
BluetoothState state = bluetoothState; BluetoothState state = bluetoothState;
if (state != null && (bluetoothId == null || bluetoothId.isEmpty())) { if (state != null && (bluetoothId == null || bluetoothId.isEmpty())) {
PairedDevice[] pairedDeviceList = state.pairedDeviceList; for (PairedDevice paired : state.getPairedDeviceList()) {
if (pairedDeviceList != null) { String pairedAddress = paired.address;
for (PairedDevice paired : pairedDeviceList) { if (pairedAddress != null && !pairedAddress.isEmpty()) {
if (paired == null) { lastKnownBluetoothMAC = pairedAddress;
continue; break;
}
String pairedAddress = paired.address;
if (pairedAddress != null && !pairedAddress.isEmpty()) {
lastKnownBluetoothMAC = pairedAddress;
break;
}
} }
} }
} }
@ -806,8 +795,7 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
public void updateState(AccountHandler accountHandler, @Nullable Device device, public void updateState(AccountHandler accountHandler, @Nullable Device device,
@Nullable BluetoothState bluetoothState, @Nullable DeviceNotificationState deviceNotificationState, @Nullable BluetoothState bluetoothState, @Nullable DeviceNotificationState deviceNotificationState,
@Nullable AscendingAlarmModel ascendingAlarmModel, @Nullable JsonPlaylists playlists, @Nullable AscendingAlarmModel ascendingAlarmModel, @Nullable JsonPlaylists playlists,
@Nullable JsonNotificationSound @Nullable [] alarmSounds, @Nullable List<JsonNotificationSound> alarmSounds, @Nullable List<JsonMusicProvider> musicProviders) {
@Nullable List<JsonMusicProvider> musicProviders) {
try { try {
this.logger.debug("Handle updateState {}", this.getThing().getUID()); this.logger.debug("Handle updateState {}", this.getThing().getUID());
@ -974,24 +962,19 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
boolean bluetoothIsConnected = false; boolean bluetoothIsConnected = false;
if (bluetoothState != null) { if (bluetoothState != null) {
this.bluetoothState = bluetoothState; this.bluetoothState = bluetoothState;
PairedDevice[] pairedDeviceList = bluetoothState.pairedDeviceList; for (PairedDevice paired : bluetoothState.getPairedDeviceList()) {
if (pairedDeviceList != null) { String pairedAddress = paired.address;
for (PairedDevice paired : pairedDeviceList) { if (paired.connected && pairedAddress != null) {
if (paired == null) { bluetoothIsConnected = true;
continue; bluetoothMAC = pairedAddress;
} bluetoothDeviceName = paired.friendlyName;
String pairedAddress = paired.address; if (bluetoothDeviceName == null || bluetoothDeviceName.isEmpty()) {
if (paired.connected && pairedAddress != null) { bluetoothDeviceName = pairedAddress;
bluetoothIsConnected = true;
bluetoothMAC = pairedAddress;
bluetoothDeviceName = paired.friendlyName;
if (bluetoothDeviceName == null || bluetoothDeviceName.isEmpty()) {
bluetoothDeviceName = pairedAddress;
}
break;
} }
break;
} }
} }
} }
if (!bluetoothMAC.isEmpty()) { if (!bluetoothMAC.isEmpty()) {
lastKnownBluetoothMAC = bluetoothMAC; lastKnownBluetoothMAC = bluetoothMAC;
@ -1036,22 +1019,21 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
} }
} }
if (mediaState != null) { if (mediaState != null) {
QueueEntry[] queueEntries = mediaState.queue; List<QueueEntry> queueEntries = Objects.requireNonNullElse(mediaState.queue, List.of());
if (queueEntries != null && queueEntries.length > 0) { if (!queueEntries.isEmpty()) {
QueueEntry entry = queueEntries[0]; QueueEntry entry = queueEntries.get(0);
if (entry != null) { if (isRadio) {
if (isRadio) { if ((imageUrl == null || imageUrl.isEmpty()) && entry.imageURL != null) {
if ((imageUrl == null || imageUrl.isEmpty()) && entry.imageURL != null) { imageUrl = entry.imageURL;
imageUrl = entry.imageURL; }
} if ((subTitle1 == null || subTitle1.isEmpty()) && entry.radioStationSlogan != null) {
if ((subTitle1 == null || subTitle1.isEmpty()) && entry.radioStationSlogan != null) { subTitle1 = entry.radioStationSlogan;
subTitle1 = entry.radioStationSlogan; }
} if ((subTitle2 == null || subTitle2.isEmpty()) && entry.radioStationLocation != null) {
if ((subTitle2 == null || subTitle2.isEmpty()) && entry.radioStationLocation != null) { subTitle2 = entry.radioStationLocation;
subTitle2 = entry.radioStationLocation;
}
} }
} }
} }
} }
@ -1287,7 +1269,8 @@ public class EchoHandler extends BaseThingHandler implements IEchoThingHandler {
} }
public void updateNotifications(ZonedDateTime currentTime, ZonedDateTime now, public void updateNotifications(ZonedDateTime currentTime, ZonedDateTime now,
@Nullable JsonCommandPayloadPushNotificationChange pushPayload, JsonNotificationResponse[] notifications) { @Nullable JsonCommandPayloadPushNotificationChange pushPayload,
List<JsonNotificationResponse> notifications) {
Device device = this.device; Device device = this.device;
if (device == null) { if (device == null) {
return; return;

View File

@ -16,7 +16,7 @@ import static org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBi
import static org.openhab.binding.amazonechocontrol.internal.smarthome.Constants.SUPPORTED_INTERFACES; import static org.openhab.binding.amazonechocontrol.internal.smarthome.Constants.SUPPORTED_INTERFACES;
import java.util.*; import java.util.*;
import java.util.function.Supplier; import java.util.function.Function;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -93,15 +93,15 @@ public class SmartHomeDeviceHandler extends BaseThingHandler {
if (handler != null) { if (handler != null) {
unusedHandlers.remove(interfaceName); unusedHandlers.remove(interfaceName);
} else { } else {
Supplier<HandlerBase> creator = Constants.HANDLER_FACTORY.get(interfaceName); Function<SmartHomeDeviceHandler, HandlerBase> creator = Constants.HANDLER_FACTORY.get(interfaceName);
if (creator != null) { if (creator != null) {
handler = creator.get(); handler = creator.apply(this);
handlers.put(interfaceName, handler); handlers.put(interfaceName, handler);
} }
} }
if (handler != null) { if (handler != null) {
Collection<ChannelInfo> required = handler.initialize(this, Collection<ChannelInfo> required = handler
capabilities.getOrDefault(interfaceName, Collections.emptyList())); .initialize(capabilities.getOrDefault(interfaceName, List.of()));
for (ChannelInfo channelInfo : required) { for (ChannelInfo channelInfo : required) {
unusedChannels.remove(channelInfo.channelId); unusedChannels.remove(channelInfo.channelId);
if (addChannelToDevice(thingBuilder, channelInfo.channelId, channelInfo.itemType, if (addChannelToDevice(thingBuilder, channelInfo.channelId, channelInfo.itemType,
@ -289,13 +289,8 @@ public class SmartHomeDeviceHandler extends BaseThingHandler {
if (entityId == null) { if (entityId == null) {
continue; continue;
} }
SmartHomeCapability[] capabilities = shd.capabilities;
if (capabilities == null) {
logger.debug("capabilities is null in {}", thing.getUID());
return;
}
accountHandler.forceDelayedSmartHomeStateUpdate(getId()); // block updates accountHandler.forceDelayedSmartHomeStateUpdate(getId()); // block updates
if (handlerBase.handleCommand(connection, shd, entityId, capabilities, channelUID.getId(), if (handlerBase.handleCommand(connection, shd, entityId, shd.getCapabilities(), channelUID.getId(),
command)) { command)) {
accountHandler.forceDelayedSmartHomeStateUpdate(getId()); // force update again to restart accountHandler.forceDelayedSmartHomeStateUpdate(getId()); // force update again to restart
// update timer // update timer
@ -312,11 +307,7 @@ public class SmartHomeDeviceHandler extends BaseThingHandler {
SmartHomeBaseDevice device) { SmartHomeBaseDevice device) {
if (device instanceof SmartHomeDevice) { if (device instanceof SmartHomeDevice) {
SmartHomeDevice shd = (SmartHomeDevice) device; SmartHomeDevice shd = (SmartHomeDevice) device;
SmartHomeCapability[] capabilities = shd.capabilities; for (SmartHomeCapability capability : shd.getCapabilities()) {
if (capabilities == null) {
return;
}
for (SmartHomeCapability capability : capabilities) {
String interfaceName = capability.interfaceName; String interfaceName = capability.interfaceName;
if (interfaceName != null) { if (interfaceName != null) {
Objects.requireNonNull(result.computeIfAbsent(interfaceName, name -> new ArrayList<>())) Objects.requireNonNull(result.computeIfAbsent(interfaceName, name -> new ArrayList<>()))
@ -340,12 +331,10 @@ public class SmartHomeDeviceHandler extends BaseThingHandler {
Set<SmartHomeDevice> result = new HashSet<>(); Set<SmartHomeDevice> result = new HashSet<>();
if (baseDevice instanceof SmartHomeDevice) { if (baseDevice instanceof SmartHomeDevice) {
SmartHomeDevice shd = (SmartHomeDevice) baseDevice; SmartHomeDevice shd = (SmartHomeDevice) baseDevice;
SmartHomeCapability[] capabilities = shd.capabilities; if (shd.getCapabilities().stream().map(capability -> capability.interfaceName)
if (capabilities != null) { .anyMatch(SUPPORTED_INTERFACES::contains)) {
if (Arrays.stream(capabilities).map(capability -> capability.interfaceName) result.add(shd);
.anyMatch(SUPPORTED_INTERFACES::contains)) {
result.add(shd);
}
} }
} else { } else {
SmartHomeGroup shg = (SmartHomeGroup) baseDevice; SmartHomeGroup shg = (SmartHomeGroup) baseDevice;
@ -356,13 +345,12 @@ public class SmartHomeDeviceHandler extends BaseThingHandler {
if (tags != null) { if (tags != null) {
JsonSmartHomeGroupIdentity.SmartHomeGroupIdentity tagNameToValueSetMap = tags.tagNameToValueSetMap; JsonSmartHomeGroupIdentity.SmartHomeGroupIdentity tagNameToValueSetMap = tags.tagNameToValueSetMap;
JsonSmartHomeGroupIdentifiers.SmartHomeGroupIdentifier applianceGroupIdentifier = shg.applianceGroupIdentifier; JsonSmartHomeGroupIdentifiers.SmartHomeGroupIdentifier applianceGroupIdentifier = shg.applianceGroupIdentifier;
if (tagNameToValueSetMap != null && tagNameToValueSetMap.groupIdentity != null if (tagNameToValueSetMap != null) {
&& applianceGroupIdentifier != null && applianceGroupIdentifier.value != null List<String> groupIdentity = Objects.requireNonNullElse(tagNameToValueSetMap.groupIdentity,
&& Arrays.asList(tagNameToValueSetMap.groupIdentity) List.of());
.contains(applianceGroupIdentifier.value)) { if (applianceGroupIdentifier != null && applianceGroupIdentifier.value != null
SmartHomeCapability[] capabilities = shd.capabilities; && groupIdentity.contains(applianceGroupIdentifier.value)) {
if (capabilities != null) { if (shd.getCapabilities().stream().map(capability -> capability.interfaceName)
if (Arrays.stream(capabilities).map(capability -> capability.interfaceName)
.anyMatch(SUPPORTED_INTERFACES::contains)) { .anyMatch(SUPPORTED_INTERFACES::contains)) {
result.add(shd); result.add(shd);
} }

View File

@ -12,6 +12,9 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -26,7 +29,7 @@ import com.google.gson.JsonSyntaxException;
@NonNullByDefault @NonNullByDefault
public class JsonActivities { public class JsonActivities {
public @Nullable Activity @Nullable [] activities; public @Nullable List<Activity> activities;
public static class Activity { public static class Activity {
public @Nullable String activityStatus; public @Nullable String activityStatus;
@ -40,10 +43,14 @@ public class JsonActivities {
public @Nullable String providerInfoDescription; public @Nullable String providerInfoDescription;
public @Nullable String registeredCustomerId; public @Nullable String registeredCustomerId;
public @Nullable Object sourceActiveUsers; public @Nullable Object sourceActiveUsers;
public @Nullable SourceDeviceId @Nullable [] sourceDeviceIds; public @Nullable List<SourceDeviceId> sourceDeviceIds;
public @Nullable String utteranceId; public @Nullable String utteranceId;
public @Nullable Long version; public @Nullable Long version;
public List<SourceDeviceId> getSourceDeviceIds() {
return Objects.requireNonNullElse(sourceDeviceIds, List.of());
}
public static class SourceDeviceId { public static class SourceDeviceId {
public @Nullable String deviceAccountId; public @Nullable String deviceAccountId;
public @Nullable String deviceType; public @Nullable String deviceType;
@ -51,7 +58,6 @@ public class JsonActivities {
} }
public static class Description { public static class Description {
public @Nullable String summary; public @Nullable String summary;
public @Nullable String firstUtteranceId; public @Nullable String firstUtteranceId;
public @Nullable String firstStreamId; public @Nullable String firstStreamId;

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -23,7 +25,7 @@ import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault @NonNullByDefault
public class JsonAscendingAlarm { public class JsonAscendingAlarm {
public @Nullable AscendingAlarmModel @Nullable [] ascendingAlarmModelList; public @Nullable List<AscendingAlarmModel> ascendingAlarmModelList;
public static class AscendingAlarmModel { public static class AscendingAlarmModel {
public @Nullable Boolean ascendingAlarmEnabled; public @Nullable Boolean ascendingAlarmEnabled;

View File

@ -12,6 +12,7 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import java.util.TreeMap; import java.util.TreeMap;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -26,7 +27,7 @@ import org.eclipse.jdt.annotation.Nullable;
public class JsonAutomation { public class JsonAutomation {
public @Nullable String automationId; public @Nullable String automationId;
public @Nullable String name; public @Nullable String name;
public @Nullable Trigger @Nullable [] triggers; public @Nullable List<Trigger> triggers;
public @Nullable TreeMap<String, Object> sequence; public @Nullable TreeMap<String, Object> sequence;
public @Nullable String status; public @Nullable String status;
public long creationTimeEpochMillis; public long creationTimeEpochMillis;

View File

@ -12,6 +12,7 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
@ -50,7 +51,7 @@ public class JsonBluetoothStates {
public boolean connected; public boolean connected;
public @Nullable String deviceClass; public @Nullable String deviceClass;
public @Nullable String friendlyName; public @Nullable String friendlyName;
public @Nullable String @Nullable [] profiles; public @Nullable List<String> profiles;
} }
public static class BluetoothState { public static class BluetoothState {
@ -59,6 +60,10 @@ public class JsonBluetoothStates {
public @Nullable String friendlyName; public @Nullable String friendlyName;
public boolean gadgetPaired; public boolean gadgetPaired;
public boolean online; public boolean online;
public @Nullable PairedDevice @Nullable [] pairedDeviceList; public @Nullable List<PairedDevice> pairedDeviceList;
public List<PairedDevice> getPairedDeviceList() {
return Objects.requireNonNullElse(pairedDeviceList, List.of());
}
} }
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -23,7 +25,7 @@ import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault @NonNullByDefault
public class JsonDeviceNotificationState { public class JsonDeviceNotificationState {
public @Nullable DeviceNotificationState @Nullable [] deviceNotificationStates; public @Nullable List<DeviceNotificationState> deviceNotificationStates;
public static class DeviceNotificationState { public static class DeviceNotificationState {
public @Nullable String deviceSerialNumber; public @Nullable String deviceSerialNumber;

View File

@ -12,8 +12,9 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -35,7 +36,11 @@ public class JsonDevices {
public @Nullable String deviceType; public @Nullable String deviceType;
public @Nullable String softwareVersion; public @Nullable String softwareVersion;
public boolean online; public boolean online;
public @Nullable String @Nullable [] capabilities; public @Nullable Set<String> capabilities;
public Set<String> getCapabilities() {
return Objects.requireNonNullElse(capabilities, Set.of());
}
@Override @Override
public String toString() { public String toString() {
@ -43,7 +48,7 @@ public class JsonDevices {
+ ", deviceOwnerCustomerId='" + deviceOwnerCustomerId + '\'' + ", deviceAccountId='" + ", deviceOwnerCustomerId='" + deviceOwnerCustomerId + '\'' + ", deviceAccountId='"
+ deviceAccountId + '\'' + ", deviceFamily='" + deviceFamily + '\'' + ", deviceType='" + deviceType + deviceAccountId + '\'' + ", deviceFamily='" + deviceFamily + '\'' + ", deviceType='" + deviceType
+ '\'' + ", softwareVersion='" + softwareVersion + '\'' + ", online=" + online + ", capabilities=" + '\'' + ", softwareVersion='" + softwareVersion + '\'' + ", online=" + online + ", capabilities="
+ Arrays.toString(capabilities) + '}'; + capabilities + '}';
} }
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -22,5 +24,5 @@ import org.eclipse.jdt.annotation.Nullable;
*/ */
@NonNullByDefault @NonNullByDefault
public class JsonEnabledFeeds { public class JsonEnabledFeeds {
public @Nullable JsonFeed @Nullable [] enabledFeeds; public @Nullable List<JsonFeed> enabledFeeds;
} }

View File

@ -16,7 +16,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
/** /**
* The {@link JsonActivity} encapsulate the GSON data of the get equalizer command * The {@link JsonEqualizer} encapsulate the GSON data of the get equalizer command
* *
* @author Michael Geramb - Initial contribution * @author Michael Geramb - Initial contribution
*/ */

View File

@ -26,4 +26,9 @@ public class JsonFeed {
public @Nullable String name; public @Nullable String name;
public @Nullable String skillId; public @Nullable String skillId;
public @Nullable String imageUrl; public @Nullable String imageUrl;
public JsonFeed(@Nullable Object feedId, @Nullable String skillId) {
this.feedId = feedId;
this.skillId = skillId;
}
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -36,7 +38,7 @@ public class JsonMediaState {
public @Nullable String programId; public @Nullable String programId;
public int progressSeconds; public int progressSeconds;
public @Nullable String providerId; public @Nullable String providerId;
public @Nullable QueueEntry @Nullable [] queue; public @Nullable List<QueueEntry> queue;
public @Nullable String queueId; public @Nullable String queueId;
public @Nullable Integer queueSize; public @Nullable Integer queueSize;
public @Nullable String radioStationId; public @Nullable String radioStationId;
@ -48,7 +50,6 @@ public class JsonMediaState {
public int volume; public int volume;
public static class QueueEntry { public static class QueueEntry {
public @Nullable String album; public @Nullable String album;
public @Nullable String albumAsin; public @Nullable String albumAsin;
public @Nullable String artist; public @Nullable String artist;

View File

@ -25,7 +25,7 @@ import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault @NonNullByDefault
public class JsonMusicProvider { public class JsonMusicProvider {
public @Nullable String displayName; public @Nullable String displayName;
public @Nullable List<Object> @Nullable [] supportedTriggers; public List<Object> @Nullable [] supportedTriggers;
public @Nullable String icon; public @Nullable String icon;
public @Nullable List<String> supportedProperties; public @Nullable List<String> supportedProperties;
public @Nullable String id; public @Nullable String id;

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -22,5 +24,5 @@ import org.eclipse.jdt.annotation.Nullable;
*/ */
@NonNullByDefault @NonNullByDefault
public class JsonNotificationSounds { public class JsonNotificationSounds {
public @Nullable JsonNotificationSound @Nullable [] notificationSounds; public @Nullable List<JsonNotificationSound> notificationSounds;
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -22,5 +24,5 @@ import org.eclipse.jdt.annotation.Nullable;
*/ */
@NonNullByDefault @NonNullByDefault
public class JsonNotificationsResponse { public class JsonNotificationsResponse {
public JsonNotificationResponse @Nullable [] notifications; public @Nullable List<JsonNotificationResponse> notifications;
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -26,7 +28,7 @@ import com.google.gson.annotations.SerializedName;
public class JsonRegisterAppRequest { public class JsonRegisterAppRequest {
public JsonRegisterAppRequest(String serial, @Nullable String accessToken, String frc, public JsonRegisterAppRequest(String serial, @Nullable String accessToken, String frc,
JsonWebSiteCookie[] webSiteCookies) { List<JsonWebSiteCookie> webSiteCookies) {
registrationData.deviceSerial = serial; registrationData.deviceSerial = serial;
authData.accessToken = accessToken; authData.accessToken = accessToken;
userContextMap.frc = frc; userContextMap.frc = frc;
@ -48,7 +50,7 @@ public class JsonRegisterAppRequest {
public static class Cookies { public static class Cookies {
@SerializedName("website_cookies") @SerializedName("website_cookies")
public @Nullable JsonWebSiteCookie @Nullable [] webSiteCookies; public List<JsonWebSiteCookie> webSiteCookies = List.of();
public @Nullable String domain = ".amazon.com"; public @Nullable String domain = ".amazon.com";
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -30,12 +32,12 @@ public class JsonSmartHomeCapabilities {
} }
public static class Properties { public static class Properties {
public @Nullable Property @Nullable [] supported; public @Nullable List<Property> supported;
} }
public static class Property { public static class Property {
public @Nullable String name; public @Nullable String name;
} }
public @Nullable SmartHomeCapability @Nullable [] capabilites; public @Nullable List<SmartHomeCapability> capabilites;
} }

View File

@ -12,8 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -28,6 +28,27 @@ import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeTags.Js
public class JsonSmartHomeDevices { public class JsonSmartHomeDevices {
public static class SmartHomeDevice implements SmartHomeBaseDevice { public static class SmartHomeDevice implements SmartHomeBaseDevice {
public @Nullable Integer updateIntervalInSeconds; public @Nullable Integer updateIntervalInSeconds;
public @Nullable String applianceId;
public @Nullable String manufacturerName;
public @Nullable String friendlyDescription;
public @Nullable String modelName;
public @Nullable String friendlyName;
public @Nullable String reachability;
public @Nullable String entityId;
public @Nullable SmartHomeDeviceNetworkState applianceNetworkState;
public @Nullable List<SmartHomeCapability> capabilities;
public @Nullable JsonSmartHomeTag tags;
public @Nullable List<String> applianceTypes;
public @Nullable List<JsonSmartHomeDeviceAlias> aliases;
public @Nullable List<SmartHomeDevice> groupDevices;
public @Nullable String connectedVia;
public @Nullable DriverIdentity driverIdentity;
public @Nullable List<String> mergedApplianceIds;
public @Nullable List<SmartHomeDevice> smarthomeDevices;
public List<SmartHomeCapability> getCapabilities() {
return Objects.requireNonNullElse(capabilities, List.of());
}
@Override @Override
public @Nullable String findId() { public @Nullable String findId() {
@ -39,34 +60,16 @@ public class JsonSmartHomeDevices {
return false; return false;
} }
public @Nullable String applianceId;
public @Nullable String manufacturerName;
public @Nullable String friendlyDescription;
public @Nullable String modelName;
public @Nullable String friendlyName;
public @Nullable String reachability;
public @Nullable String entityId;
public @Nullable SmartHomeDeviceNetworkState applianceNetworkState;
public @Nullable SmartHomeCapability @Nullable [] capabilities;
public @Nullable JsonSmartHomeTag tags;
public @Nullable String @Nullable [] applianceTypes;
public @Nullable JsonSmartHomeDeviceAlias @Nullable [] aliases;
public @Nullable SmartHomeDevice @Nullable [] groupDevices;
public @Nullable String connectedVia;
public @Nullable DriverIdentity driverIdentity;
public List<String> mergedApplianceIds = List.of();
@Override @Override
public String toString() { public String toString() {
return "SmartHomeDevice{" + "updateIntervalInSeconds=" + updateIntervalInSeconds + ", applianceId='" return "SmartHomeDevice{" + "updateIntervalInSeconds=" + updateIntervalInSeconds + ", applianceId='"
+ applianceId + '\'' + ", manufacturerName='" + manufacturerName + '\'' + ", friendlyDescription='" + applianceId + '\'' + ", manufacturerName='" + manufacturerName + '\'' + ", friendlyDescription='"
+ friendlyDescription + '\'' + ", modelName='" + modelName + '\'' + ", friendlyName='" + friendlyDescription + '\'' + ", modelName='" + modelName + '\'' + ", friendlyName='"
+ friendlyName + '\'' + ", reachability='" + reachability + '\'' + ", entityId='" + entityId + '\'' + friendlyName + '\'' + ", reachability='" + reachability + '\'' + ", entityId='" + entityId + '\''
+ ", applianceNetworkState=" + applianceNetworkState + ", capabilities=" + ", applianceNetworkState=" + applianceNetworkState + ", capabilities=" + capabilities + ", tags="
+ Arrays.toString(capabilities) + ", tags=" + tags + ", applianceTypes=" + tags + ", applianceTypes=" + applianceTypes + ", aliases=" + aliases + ", groupDevices="
+ Arrays.toString(applianceTypes) + ", aliases=" + Arrays.toString(aliases) + ", groupDevices=" + groupDevices + ", connectedVia='" + connectedVia + '\'' + ", driverIdentity=" + driverIdentity
+ Arrays.toString(groupDevices) + ", connectedVia='" + connectedVia + '\'' + ", driverIdentity=" + ", mergedApplianceIds=" + mergedApplianceIds + ", smarthomeDevices=" + smarthomeDevices + '}';
+ driverIdentity + ", mergedApplianceIds=" + mergedApplianceIds + '}';
} }
} }
@ -79,6 +82,4 @@ public class JsonSmartHomeDevices {
return "DriverIdentity{" + "namespace='" + namespace + '\'' + ", identifier='" + identifier + '\'' + '}'; return "DriverIdentity{" + "namespace='" + namespace + '\'' + ", identifier='" + identifier + '\'' + '}';
} }
} }
public @Nullable SmartHomeDevice @Nullable [] smarthomeDevices;
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -23,8 +25,8 @@ import org.eclipse.jdt.annotation.Nullable;
@NonNullByDefault @NonNullByDefault
public class JsonSmartHomeGroupIdentity { public class JsonSmartHomeGroupIdentity {
public static class SmartHomeGroupIdentity { public static class SmartHomeGroupIdentity {
public @Nullable String @Nullable [] groupIdentity; public @Nullable List<String> groupIdentity;
} }
public @Nullable SmartHomeGroupIdentity @Nullable [] groupIdentity; public @Nullable List<SmartHomeGroupIdentity> groupIdentity;
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroupIdentifiers.SmartHomeGroupIdentifier; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeGroupIdentifiers.SmartHomeGroupIdentifier;
@ -54,5 +56,5 @@ public class JsonSmartHomeGroups {
} }
} }
public @Nullable SmartHomeGroup @Nullable [] groups; public @Nullable List<SmartHomeGroup> groups;
} }

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -26,7 +28,7 @@ public class JsonUsersMeResponse {
public @Nullable String effectiveMarketPlaceId; public @Nullable String effectiveMarketPlaceId;
public @Nullable String email; public @Nullable String email;
public @Nullable Boolean eulaAcceptance; public @Nullable Boolean eulaAcceptance;
public @Nullable String @Nullable [] features; public @Nullable List<String> features;
public @Nullable String fullName; public @Nullable String fullName;
public @Nullable Boolean hasActiveDopplers; public @Nullable Boolean hasActiveDopplers;
public @Nullable String id; public @Nullable String id;

View File

@ -12,6 +12,8 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.jsons; package org.openhab.binding.amazonechocontrol.internal.jsons;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
@ -22,7 +24,7 @@ import org.eclipse.jdt.annotation.Nullable;
*/ */
@NonNullByDefault @NonNullByDefault
public class JsonWakeWords { public class JsonWakeWords {
public @Nullable WakeWord @Nullable [] wakeWords; public @Nullable List<WakeWord> wakeWords;
public static class WakeWord { public static class WakeWord {
public @Nullable Boolean active; public @Nullable Boolean active;

View File

@ -12,13 +12,13 @@
*/ */
package org.openhab.binding.amazonechocontrol.internal.smarthome; package org.openhab.binding.amazonechocontrol.internal.smarthome;
import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import java.util.function.Supplier; import java.util.function.Function;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.core.thing.type.ChannelTypeUID; import org.openhab.core.thing.type.ChannelTypeUID;
/** /**
@ -26,20 +26,15 @@ import org.openhab.core.thing.type.ChannelTypeUID;
*/ */
@NonNullByDefault @NonNullByDefault
public class Constants { public class Constants {
public static final Map<String, Supplier<HandlerBase>> HANDLER_FACTORY = new HashMap<>(); public static final Map<String, Function<SmartHomeDeviceHandler, HandlerBase>> HANDLER_FACTORY = Map.of(
HandlerPowerController.INTERFACE, HandlerPowerController::new, HandlerBrightnessController.INTERFACE,
static { HandlerBrightnessController::new, HandlerColorController.INTERFACE, HandlerColorController::new,
HANDLER_FACTORY.put(HandlerPowerController.INTERFACE, HandlerPowerController::new); HandlerColorTemperatureController.INTERFACE, HandlerColorTemperatureController::new,
HANDLER_FACTORY.put(HandlerBrightnessController.INTERFACE, HandlerBrightnessController::new); HandlerSecurityPanelController.INTERFACE, HandlerSecurityPanelController::new,
HANDLER_FACTORY.put(HandlerColorController.INTERFACE, HandlerColorController::new); HandlerAcousticEventSensor.INTERFACE, HandlerAcousticEventSensor::new, HandlerTemperatureSensor.INTERFACE,
HANDLER_FACTORY.put(HandlerColorTemperatureController.INTERFACE, HandlerColorTemperatureController::new); HandlerTemperatureSensor::new, HandlerThermostatController.INTERFACE, HandlerThermostatController::new,
HANDLER_FACTORY.put(HandlerSecurityPanelController.INTERFACE, HandlerSecurityPanelController::new); HandlerPercentageController.INTERFACE, HandlerPercentageController::new,
HANDLER_FACTORY.put(HandlerAcousticEventSensor.INTERFACE, HandlerAcousticEventSensor::new); HandlerPowerLevelController.INTERFACE, HandlerPowerLevelController::new);
HANDLER_FACTORY.put(HandlerTemperatureSensor.INTERFACE, HandlerTemperatureSensor::new);
HANDLER_FACTORY.put(HandlerThermostatController.INTERFACE, HandlerThermostatController::new);
HANDLER_FACTORY.put(HandlerPercentageController.INTERFACE, HandlerPercentageController::new);
HANDLER_FACTORY.put(HandlerPowerLevelController.INTERFACE, HandlerPowerLevelController::new);
}
public static final Set<String> SUPPORTED_INTERFACES = HANDLER_FACTORY.keySet(); public static final Set<String> SUPPORTED_INTERFACES = HANDLER_FACTORY.keySet();

View File

@ -22,6 +22,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.OpenClosedType; import org.openhab.core.library.types.OpenClosedType;
@ -57,6 +58,10 @@ public class HandlerAcousticEventSensor extends HandlerBase {
"smokeAlarmDetectionState" /* propertyName */ , "smokeAlarmDetectionState" /* ChannelId */, "smokeAlarmDetectionState" /* propertyName */ , "smokeAlarmDetectionState" /* ChannelId */,
CHANNEL_TYPE_SMOKE_ALARM_DETECTION_STATE /* Channel Type */ , ITEM_TYPE_CONTACT /* Item Type */); CHANNEL_TYPE_SMOKE_ALARM_DETECTION_STATE /* Channel Type */ , ITEM_TYPE_CONTACT /* Item Type */);
public HandlerAcousticEventSensor(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
private ChannelInfo[] getAlarmChannels() { private ChannelInfo[] getAlarmChannels() {
return new ChannelInfo[] { GLASS_BREAK_DETECTION_STATE, SMOKE_ALARM_DETECTION_STATE }; return new ChannelInfo[] { GLASS_BREAK_DETECTION_STATE, SMOKE_ALARM_DETECTION_STATE };
} }
@ -101,7 +106,7 @@ public class HandlerAcousticEventSensor extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) throws IOException { List<SmartHomeCapability> capabilities, String channelId, Command command) throws IOException {
return false; return false;
} }

View File

@ -13,16 +13,13 @@
package org.openhab.binding.amazonechocontrol.internal.smarthome; package org.openhab.binding.amazonechocontrol.internal.smarthome;
import java.io.IOException; import java.io.IOException;
import java.util.Collection; import java.util.*;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler; import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.Properties; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.Properties;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.Property; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.Property;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
@ -39,15 +36,19 @@ import com.google.gson.JsonObject;
*/ */
@NonNullByDefault @NonNullByDefault
public abstract class HandlerBase { public abstract class HandlerBase {
protected @Nullable SmartHomeDeviceHandler smartHomeDeviceHandler; protected SmartHomeDeviceHandler smartHomeDeviceHandler;
protected Map<String, ChannelInfo> channels = new HashMap<>(); protected Map<String, ChannelInfo> channels = new HashMap<>();
public HandlerBase(SmartHomeDeviceHandler smartHomeDeviceHandler) {
this.smartHomeDeviceHandler = smartHomeDeviceHandler;
}
protected abstract ChannelInfo @Nullable [] findChannelInfos(SmartHomeCapability capability, String property); protected abstract ChannelInfo @Nullable [] findChannelInfos(SmartHomeCapability capability, String property);
public abstract void updateChannels(String interfaceName, List<JsonObject> stateList, UpdateChannelResult result); public abstract void updateChannels(String interfaceName, List<JsonObject> stateList, UpdateChannelResult result);
public abstract boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public abstract boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException; throws IOException, InterruptedException;
public abstract @Nullable StateDescription findStateDescription(String channelId, public abstract @Nullable StateDescription findStateDescription(String channelId,
@ -59,38 +60,30 @@ public abstract class HandlerBase {
public abstract String[] getSupportedInterface(); public abstract String[] getSupportedInterface();
SmartHomeDeviceHandler getSmartHomeDeviceHandler() throws IllegalStateException { SmartHomeDeviceHandler getSmartHomeDeviceHandler() {
SmartHomeDeviceHandler smartHomeDeviceHandler = this.smartHomeDeviceHandler;
if (smartHomeDeviceHandler == null) {
throw new IllegalStateException("Handler not initialized");
}
return smartHomeDeviceHandler; return smartHomeDeviceHandler;
} }
public Collection<ChannelInfo> initialize(SmartHomeDeviceHandler smartHomeDeviceHandler, public Collection<ChannelInfo> initialize(List<SmartHomeCapability> capabilities) {
List<SmartHomeCapability> capabilities) {
this.smartHomeDeviceHandler = smartHomeDeviceHandler;
Map<String, ChannelInfo> channels = new HashMap<>(); Map<String, ChannelInfo> channels = new HashMap<>();
for (SmartHomeCapability capability : capabilities) { for (SmartHomeCapability capability : capabilities) {
Properties properties = capability.properties; Properties properties = capability.properties;
if (properties != null) { if (properties != null) {
Property @Nullable [] supported = properties.supported; List<JsonSmartHomeCapabilities.Property> supported = Objects.requireNonNullElse(properties.supported,
if (supported != null) { List.of());
for (Property property : supported) { for (Property property : supported) {
if (property != null) { String name = property.name;
String name = property.name; if (name != null) {
if (name != null) { ChannelInfo[] channelInfos = findChannelInfos(capability, name);
ChannelInfo[] channelInfos = findChannelInfos(capability, name); if (channelInfos != null) {
if (channelInfos != null) { for (ChannelInfo channelInfo : channelInfos) {
for (ChannelInfo channelInfo : channelInfos) { if (channelInfo != null) {
if (channelInfo != null) { channels.put(channelInfo.channelId, channelInfo);
channels.put(channelInfo.channelId, channelInfo);
}
}
} }
} }
} }
} }
} }
} }
} }
@ -98,19 +91,14 @@ public abstract class HandlerBase {
return channels.values(); return channels.values();
} }
protected boolean containsCapabilityProperty(SmartHomeCapability[] capabilties, String propertyName) { protected boolean containsCapabilityProperty(List<SmartHomeCapability> capabilities, String propertyName) {
for (SmartHomeCapability capability : capabilties) { for (SmartHomeCapability capability : capabilities) {
Properties properties = capability.properties; Properties properties = capability.properties;
if (properties != null) { if (properties != null) {
Property @Nullable [] supportedProperties = properties.supported; List<JsonSmartHomeCapabilities.Property> supported = Objects.requireNonNullElse(properties.supported,
if (supportedProperties != null) { List.of());
for (Property property : supportedProperties) { if (supported.stream().anyMatch(p -> propertyName.equals(p.name))) {
if (property != null) { return true;
if (propertyName != null && propertyName.equals(property.name)) {
return true;
}
}
}
} }
} }
} }

View File

@ -22,6 +22,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.IncreaseDecreaseType;
@ -56,6 +57,10 @@ public class HandlerBrightnessController extends HandlerBase {
private @Nullable Integer lastBrightness; private @Nullable Integer lastBrightness;
public HandlerBrightnessController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE }; return new String[] { INTERFACE };
@ -91,10 +96,10 @@ public class HandlerBrightnessController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(BRIGHTNESS.channelId)) { if (channelId.equals(BRIGHTNESS.channelId)) {
if (containsCapabilityProperty(capabilties, BRIGHTNESS.propertyName)) { if (containsCapabilityProperty(capabilities, BRIGHTNESS.propertyName)) {
if (command.equals(IncreaseDecreaseType.INCREASE)) { if (command.equals(IncreaseDecreaseType.INCREASE)) {
Integer lastBrightness = this.lastBrightness; Integer lastBrightness = this.lastBrightness;
if (lastBrightness != null) { if (lastBrightness != null) {

View File

@ -23,6 +23,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.DecimalType;
@ -65,6 +66,10 @@ public class HandlerColorController extends HandlerBase {
private @Nullable HSBType lastColor; private @Nullable HSBType lastColor;
private @Nullable String lastColorName; private @Nullable String lastColorName;
public HandlerColorController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE, INTERFACE_COLOR_PROPERTIES }; return new String[] { INTERFACE, INTERFACE_COLOR_PROPERTIES };
@ -123,10 +128,10 @@ public class HandlerColorController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(COLOR.channelId)) { if (channelId.equals(COLOR.channelId)) {
if (containsCapabilityProperty(capabilties, COLOR.propertyName)) { if (containsCapabilityProperty(capabilities, COLOR.propertyName)) {
if (command instanceof HSBType) { if (command instanceof HSBType) {
HSBType color = ((HSBType) command); HSBType color = ((HSBType) command);
JsonObject colorObject = new JsonObject(); JsonObject colorObject = new JsonObject();
@ -138,7 +143,7 @@ public class HandlerColorController extends HandlerBase {
} }
} }
if (channelId.equals(COLOR_PROPERTIES.channelId)) { if (channelId.equals(COLOR_PROPERTIES.channelId)) {
if (containsCapabilityProperty(capabilties, COLOR.propertyName)) { if (containsCapabilityProperty(capabilities, COLOR.propertyName)) {
if (command instanceof StringType) { if (command instanceof StringType) {
String colorName = command.toFullString(); String colorName = command.toFullString();
if (!colorName.isEmpty()) { if (!colorName.isEmpty()) {

View File

@ -23,6 +23,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.DecimalType;
@ -65,6 +66,10 @@ public class HandlerColorTemperatureController extends HandlerBase {
private @Nullable Integer lastColorTemperature; private @Nullable Integer lastColorTemperature;
private @Nullable String lastColorName; private @Nullable String lastColorName;
public HandlerColorTemperatureController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE, INTERFACE_COLOR_PROPERTIES }; return new String[] { INTERFACE, INTERFACE_COLOR_PROPERTIES };
@ -120,11 +125,11 @@ public class HandlerColorTemperatureController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(COLOR_TEMPERATURE_IN_KELVIN.channelId)) { if (channelId.equals(COLOR_TEMPERATURE_IN_KELVIN.channelId)) {
// WRITING TO THIS CHANNEL DOES CURRENTLY NOT WORK, BUT WE LEAVE THE CODE FOR FUTURE USE! // WRITING TO THIS CHANNEL DOES CURRENTLY NOT WORK, BUT WE LEAVE THE CODE FOR FUTURE USE!
if (containsCapabilityProperty(capabilties, COLOR_TEMPERATURE_IN_KELVIN.propertyName)) { if (containsCapabilityProperty(capabilities, COLOR_TEMPERATURE_IN_KELVIN.propertyName)) {
if (command instanceof DecimalType) { if (command instanceof DecimalType) {
int intValue = ((DecimalType) command).intValue(); int intValue = ((DecimalType) command).intValue();
if (intValue < 1000) { if (intValue < 1000) {
@ -139,7 +144,7 @@ public class HandlerColorTemperatureController extends HandlerBase {
} }
} }
if (channelId.equals(COLOR_TEMPERATURE_NAME.channelId)) { if (channelId.equals(COLOR_TEMPERATURE_NAME.channelId)) {
if (containsCapabilityProperty(capabilties, COLOR_TEMPERATURE_IN_KELVIN.propertyName)) { if (containsCapabilityProperty(capabilities, COLOR_TEMPERATURE_IN_KELVIN.propertyName)) {
if (command instanceof StringType) { if (command instanceof StringType) {
String colorTemperatureName = command.toFullString(); String colorTemperatureName = command.toFullString();
if (!colorTemperatureName.isEmpty()) { if (!colorTemperatureName.isEmpty()) {

View File

@ -22,6 +22,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.IncreaseDecreaseType;
@ -56,6 +57,10 @@ public class HandlerPercentageController extends HandlerBase {
private @Nullable Integer lastPercentage; private @Nullable Integer lastPercentage;
public HandlerPercentageController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE }; return new String[] { INTERFACE };
@ -91,10 +96,10 @@ public class HandlerPercentageController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(PERCENTAGE.channelId)) { if (channelId.equals(PERCENTAGE.channelId)) {
if (containsCapabilityProperty(capabilties, PERCENTAGE.propertyName)) { if (containsCapabilityProperty(capabilities, PERCENTAGE.propertyName)) {
if (command.equals(IncreaseDecreaseType.INCREASE)) { if (command.equals(IncreaseDecreaseType.INCREASE)) {
Integer lastPercentage = this.lastPercentage; Integer lastPercentage = this.lastPercentage;
if (lastPercentage != null) { if (lastPercentage != null) {

View File

@ -22,6 +22,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.OnOffType; import org.openhab.core.library.types.OnOffType;
@ -56,6 +57,10 @@ public class HandlerPowerController extends HandlerBase {
"powerState" /* ChannelId */, CHANNEL_TYPE_POWER_STATE /* Channel Type */ , "powerState" /* ChannelId */, CHANNEL_TYPE_POWER_STATE /* Channel Type */ ,
ITEM_TYPE_SWITCH /* Item Type */); ITEM_TYPE_SWITCH /* Item Type */);
public HandlerPowerController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE }; return new String[] { INTERFACE };
@ -77,12 +82,7 @@ public class HandlerPowerController extends HandlerBase {
if (POWER_STATE.propertyName.equals(state.get("name").getAsString())) { if (POWER_STATE.propertyName.equals(state.get("name").getAsString())) {
String value = state.get("value").getAsString(); String value = state.get("value").getAsString();
// For groups take true if all true // For groups take true if all true
if ("ON".equals(value)) { powerStateValue = "ON".equals(value);
powerStateValue = true;
} else {
powerStateValue = false;
}
} }
} }
logger.trace("{} final state {}", this.smartHomeDeviceHandler.getId(), powerStateValue); logger.trace("{} final state {}", this.smartHomeDeviceHandler.getId(), powerStateValue);
@ -91,7 +91,7 @@ public class HandlerPowerController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilities, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(POWER_STATE.channelId)) { if (channelId.equals(POWER_STATE.channelId)) {
if (containsCapabilityProperty(capabilities, POWER_STATE.propertyName)) { if (containsCapabilityProperty(capabilities, POWER_STATE.propertyName)) {

View File

@ -22,6 +22,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.IncreaseDecreaseType; import org.openhab.core.library.types.IncreaseDecreaseType;
@ -56,6 +57,10 @@ public class HandlerPowerLevelController extends HandlerBase {
private @Nullable Integer lastPowerLevel; private @Nullable Integer lastPowerLevel;
public HandlerPowerLevelController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE }; return new String[] { INTERFACE };
@ -92,10 +97,10 @@ public class HandlerPowerLevelController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(POWER_LEVEL.channelId)) { if (channelId.equals(POWER_LEVEL.channelId)) {
if (containsCapabilityProperty(capabilties, POWER_LEVEL.propertyName)) { if (containsCapabilityProperty(capabilities, POWER_LEVEL.propertyName)) {
if (command.equals(IncreaseDecreaseType.INCREASE)) { if (command.equals(IncreaseDecreaseType.INCREASE)) {
Integer lastPowerLevel = this.lastPowerLevel; Integer lastPowerLevel = this.lastPowerLevel;
if (lastPowerLevel != null) { if (lastPowerLevel != null) {

View File

@ -23,6 +23,7 @@ import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants; import org.openhab.binding.amazonechocontrol.internal.AmazonEchoControlBindingConstants;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.OpenClosedType; import org.openhab.core.library.types.OpenClosedType;
@ -81,6 +82,10 @@ public class HandlerSecurityPanelController extends HandlerBase {
"waterAlarm" /* ChannelId */, CHANNEL_TYPE_WATER_ALARM /* Channel Type */ , "waterAlarm" /* ChannelId */, CHANNEL_TYPE_WATER_ALARM /* Channel Type */ ,
ITEM_TYPE_CONTACT /* Item Type */); ITEM_TYPE_CONTACT /* Item Type */);
public HandlerSecurityPanelController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
private ChannelInfo[] getAlarmChannels() { private ChannelInfo[] getAlarmChannels() {
return new ChannelInfo[] { BURGLARY_ALARM, CARBON_MONOXIDE_ALARM, FIRE_ALARM, WATER_ALARM }; return new ChannelInfo[] { BURGLARY_ALARM, CARBON_MONOXIDE_ALARM, FIRE_ALARM, WATER_ALARM };
} }
@ -146,7 +151,7 @@ public class HandlerSecurityPanelController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilities, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(ARM_STATE.channelId)) { if (channelId.equals(ARM_STATE.channelId)) {
if (containsCapabilityProperty(capabilities, ARM_STATE.propertyName)) { if (containsCapabilityProperty(capabilities, ARM_STATE.propertyName)) {

View File

@ -23,6 +23,7 @@ import javax.measure.quantity.Temperature;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.QuantityType; import org.openhab.core.library.types.QuantityType;
@ -49,6 +50,10 @@ public class HandlerTemperatureSensor extends HandlerBase {
"temperature" /* ChannelId */, CHANNEL_TYPE_TEMPERATURE /* Channel Type */ , "temperature" /* ChannelId */, CHANNEL_TYPE_TEMPERATURE /* Channel Type */ ,
ITEM_TYPE_NUMBER_TEMPERATURE /* Item Type */); ITEM_TYPE_NUMBER_TEMPERATURE /* Item Type */);
public HandlerTemperatureSensor(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE }; return new String[] { INTERFACE };
@ -85,7 +90,7 @@ public class HandlerTemperatureSensor extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) throws IOException { List<SmartHomeCapability> capabilities, String channelId, Command command) throws IOException {
return false; return false;
} }

View File

@ -23,6 +23,7 @@ import javax.measure.quantity.Temperature;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable; import org.eclipse.jdt.annotation.Nullable;
import org.openhab.binding.amazonechocontrol.internal.Connection; import org.openhab.binding.amazonechocontrol.internal.Connection;
import org.openhab.binding.amazonechocontrol.internal.handler.SmartHomeDeviceHandler;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.openhab.core.library.types.QuantityType; import org.openhab.core.library.types.QuantityType;
@ -48,6 +49,10 @@ public class HandlerThermostatController extends HandlerBase {
"targetSetpoint" /* ChannelId */, CHANNEL_TYPE_TEMPERATURE /* Channel Type */ , "targetSetpoint" /* ChannelId */, CHANNEL_TYPE_TEMPERATURE /* Channel Type */ ,
ITEM_TYPE_NUMBER_TEMPERATURE /* Item Type */); ITEM_TYPE_NUMBER_TEMPERATURE /* Item Type */);
public HandlerThermostatController(SmartHomeDeviceHandler smartHomeDeviceHandler) {
super(smartHomeDeviceHandler);
}
@Override @Override
public String[] getSupportedInterface() { public String[] getSupportedInterface() {
return new String[] { INTERFACE }; return new String[] { INTERFACE };
@ -84,10 +89,10 @@ public class HandlerThermostatController extends HandlerBase {
@Override @Override
public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId, public boolean handleCommand(Connection connection, SmartHomeDevice shd, String entityId,
SmartHomeCapability[] capabilties, String channelId, Command command) List<SmartHomeCapability> capabilities, String channelId, Command command)
throws IOException, InterruptedException { throws IOException, InterruptedException {
if (channelId.equals(TARGET_SETPOINT.channelId)) { if (channelId.equals(TARGET_SETPOINT.channelId)) {
if (containsCapabilityProperty(capabilties, TARGET_SETPOINT.propertyName)) { if (containsCapabilityProperty(capabilities, TARGET_SETPOINT.propertyName)) {
if (command instanceof QuantityType) { if (command instanceof QuantityType) {
connection.smartHomeCommand(entityId, "setTargetTemperature", "targetTemperature", command); connection.smartHomeCommand(entityId, "setTargetTemperature", "targetTemperature", command);
return true; return true;

View File

@ -20,7 +20,6 @@ import java.util.Map;
import java.util.Set; import java.util.Set;
import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeCapabilities.SmartHomeCapability;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.DriverIdentity;
import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice; import org.openhab.binding.amazonechocontrol.internal.jsons.JsonSmartHomeDevices.SmartHomeDevice;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -64,15 +63,11 @@ public class SmartHomeDeviceStateGroupUpdateCalculator {
if (updateIntervalInSeconds != null) { if (updateIntervalInSeconds != null) {
return updateIntervalInSeconds; return updateIntervalInSeconds;
} }
SmartHomeCapability[] capabilities = shd.capabilities; if (shd.getCapabilities().stream()
if (capabilities != null) { .anyMatch(capability -> HandlerAcousticEventSensor.INTERFACE.equals(capability.interfaceName))) {
for (SmartHomeCapability capability : capabilities) { updateIntervalInSeconds = UPDATE_INTERVAL_ACOUSTIC_EVENTS_IN_SECONDS;
if (capability != null && HandlerAcousticEventSensor.INTERFACE.equals(capability.interfaceName)) {
updateIntervalInSeconds = UPDATE_INTERVAL_ACOUSTIC_EVENTS_IN_SECONDS;
break;
}
}
} }
if (updateIntervalInSeconds == null) { if (updateIntervalInSeconds == null) {
String manufacturerName = shd.manufacturerName; String manufacturerName = shd.manufacturerName;
if (manufacturerName != null && ("openHAB".equalsIgnoreCase(manufacturerName) if (manufacturerName != null && ("openHAB".equalsIgnoreCase(manufacturerName)