/
ICloudAccountBridgeHandler.java
192 lines (163 loc) · 7.24 KB
/
ICloudAccountBridgeHandler.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.icloud.internal.handler;
import static java.util.concurrent.TimeUnit.*;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ScheduledFuture;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.smarthome.core.cache.ExpiringCache;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler;
import org.eclipse.smarthome.core.types.Command;
import org.eclipse.smarthome.core.types.RefreshType;
import org.openhab.binding.icloud.internal.ICloudConnection;
import org.openhab.binding.icloud.internal.ICloudDeviceInformationListener;
import org.openhab.binding.icloud.internal.ICloudDeviceInformationParser;
import org.openhab.binding.icloud.internal.configuration.ICloudAccountThingConfiguration;
import org.openhab.binding.icloud.internal.json.response.ICloudAccountDataResponse;
import org.openhab.binding.icloud.internal.json.response.ICloudDeviceInformation;
import org.osgi.framework.ServiceRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.gson.JsonSyntaxException;
/**
* Retrieves the data for a given account from iCloud and passes the
* information to {@link org.openhab.binding.icloud.internal.discovery.ICloudDeviceDiscovery} and to the
* {@link ICloudDeviceHandler}s.
*
* @author Patrik Gfeller - Initial contribution
* @author Hans-Jörg Merk - Extended support with initial Contribution
*/
@NonNullByDefault
public class ICloudAccountBridgeHandler extends BaseBridgeHandler {
private final Logger logger = LoggerFactory.getLogger(ICloudAccountBridgeHandler.class);
private static final int CACHE_EXPIRY = (int) SECONDS.toMillis(10);
private final ICloudDeviceInformationParser deviceInformationParser = new ICloudDeviceInformationParser();
private @Nullable ICloudConnection connection;
private @Nullable ExpiringCache<String> iCloudDeviceInformationCache;
@Nullable
ServiceRegistration<?> service;
private final Object synchronizeRefresh = new Object();
private List<ICloudDeviceInformationListener> deviceInformationListeners = Collections
.synchronizedList(new ArrayList<ICloudDeviceInformationListener>());
@Nullable
ScheduledFuture<?> refreshJob;
public ICloudAccountBridgeHandler(Bridge bridge) {
super(bridge);
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
logger.trace("Command '{}' received for channel '{}'", command, channelUID);
if (command instanceof RefreshType) {
refreshData();
}
}
@Override
public void initialize() {
logger.debug("iCloud bridge handler initializing ...");
iCloudDeviceInformationCache = new ExpiringCache<String>(CACHE_EXPIRY, () -> {
try {
return connection.requestDeviceStatusJSON();
} catch (IOException e) {
logger.warn("Unable to refresh device data", e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
return null;
}
});
startHandler();
logger.debug("iCloud bridge initialized.");
}
@Override
public void handleRemoval() {
super.handleRemoval();
}
@Override
public void dispose() {
if (refreshJob != null) {
refreshJob.cancel(true);
}
super.dispose();
}
public void findMyDevice(String deviceId) throws IOException {
if(connection == null) {
logger.debug("Can't send Find My Device request, because connection is null!");
return;
}
connection.findMyDevice(deviceId);
}
public void registerListener(ICloudDeviceInformationListener listener) {
deviceInformationListeners.add(listener);
}
public void unregisterListener(ICloudDeviceInformationListener listener) {
deviceInformationListeners.remove(listener);
}
private void startHandler() {
try {
logger.debug("iCloud bridge starting handler ...");
ICloudAccountThingConfiguration config = getConfigAs(ICloudAccountThingConfiguration.class);
final String appleId = config.appleId;
final String password = config.password;
if(appleId != null || password != null) {
connection = new ICloudConnection(appleId, password);
}
else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Apple ID/Password is not set!");
return;
}
refreshJob = scheduler.scheduleWithFixedDelay(this::refreshData, 0, config.refreshTimeInMinutes, MINUTES);
logger.debug("iCloud bridge handler started.");
} catch (URISyntaxException e) {
logger.debug("Something went wrong while constructing the connection object", e);
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
}
}
public void refreshData() {
synchronized (synchronizeRefresh) {
logger.debug("iCloud bridge refreshing data ...");
String json = iCloudDeviceInformationCache.getValue();
logger.trace("json: {}", json);
if (json == null) {
return;
}
try {
ICloudAccountDataResponse iCloudData = deviceInformationParser.parse(json);
if(iCloudData == null) {
return;
}
int statusCode = Integer.parseUnsignedInt(iCloudData.getICloudAccountStatusCode());
if (statusCode == 200) {
updateStatus(ThingStatus.ONLINE);
informDeviceInformationListeners(iCloudData.getICloudDeviceInformationList());
} else {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"Status = " + statusCode + ", Response = " + json);
}
logger.debug("iCloud bridge data refresh complete.");
} catch (NumberFormatException | JsonSyntaxException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
"iCloud response invalid: " + e.getMessage());
}
}
}
private void informDeviceInformationListeners(List<ICloudDeviceInformation> deviceInformationList) {
this.deviceInformationListeners.forEach(discovery -> discovery.deviceInformationUpdate(deviceInformationList));
}
}