001/**
002 *
003 * Copyright 2016 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.iot.data;
018
019import java.util.ArrayList;
020import java.util.List;
021import java.util.Map;
022import java.util.WeakHashMap;
023import java.util.concurrent.ConcurrentHashMap;
024import java.util.concurrent.atomic.AtomicInteger;
025import java.util.logging.Level;
026import java.util.logging.Logger;
027
028import org.jivesoftware.smack.ConnectionCreationListener;
029import org.jivesoftware.smack.StanzaCollector;
030import org.jivesoftware.smack.SmackException.NoResponseException;
031import org.jivesoftware.smack.SmackException.NotConnectedException;
032import org.jivesoftware.smack.XMPPConnection;
033import org.jivesoftware.smack.XMPPConnectionRegistry;
034import org.jivesoftware.smack.XMPPException.XMPPErrorException;
035import org.jivesoftware.smack.filter.StanzaFilter;
036import org.jivesoftware.smack.iqrequest.IQRequestHandler.Mode;
037import org.jivesoftware.smack.packet.IQ;
038import org.jivesoftware.smack.packet.Message;
039import org.jivesoftware.smackx.iot.IoTManager;
040import org.jivesoftware.smackx.iot.Thing;
041import org.jivesoftware.smackx.iot.data.element.IoTDataField;
042import org.jivesoftware.smackx.iot.data.element.IoTDataReadOutAccepted;
043import org.jivesoftware.smackx.iot.data.element.IoTDataRequest;
044import org.jivesoftware.smackx.iot.data.element.IoTFieldsExtension;
045import org.jivesoftware.smackx.iot.data.filter.IoTFieldsExtensionFilter;
046import org.jivesoftware.smackx.iot.element.NodeInfo;
047import org.jxmpp.jid.EntityFullJid;
048
049/**
050 * A manager for XEP-0323: Internet of Things - Sensor Data.
051 * 
052 * @author Florian Schmaus {@literal <flo@geekplace.eu>}
053 * @see <a href="http://xmpp.org/extensions/xep-0323.html">XEP-0323: Internet of Things - Sensor Data</a>
054 */
055public final class IoTDataManager extends IoTManager {
056
057    private static final Logger LOGGER = Logger.getLogger(IoTDataManager.class.getName());
058
059    private static final Map<XMPPConnection, IoTDataManager> INSTANCES = new WeakHashMap<>();
060
061    // Ensure a IoTDataManager exists for every connection.
062    static {
063        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
064            @Override
065            public void connectionCreated(XMPPConnection connection) {
066                if (!isAutoEnableActive()) return;
067                getInstanceFor(connection);
068            }
069        });
070    }
071
072    /**
073     * Get the manger instance responsible for the given connection.
074     *
075     * @param connection the XMPP connection.
076     * @return a manager instance.
077     */
078    public static synchronized IoTDataManager getInstanceFor(XMPPConnection connection) {
079        IoTDataManager manager = INSTANCES.get(connection);
080        if (manager == null) {
081            manager = new IoTDataManager(connection);
082            INSTANCES.put(connection, manager);
083        }
084        return manager;
085    }
086
087    private final AtomicInteger nextSeqNr = new AtomicInteger();
088
089    private final Map<NodeInfo, Thing> things = new ConcurrentHashMap<>();
090
091    private IoTDataManager(XMPPConnection connection) {
092        super(connection);
093        connection.registerIQRequestHandler(new IoTIqRequestHandler(IoTDataRequest.ELEMENT,
094                        IoTDataRequest.NAMESPACE, IQ.Type.get, Mode.async) {
095            @Override
096            public IQ handleIoTIqRequest(IQ iqRequest) {
097                final IoTDataRequest dataRequest = (IoTDataRequest) iqRequest;
098
099                if (!dataRequest.isMomentary()) {
100                    // TODO return error IQ that non momentary requests are not implemented yet.
101                    return null;
102                }
103
104                // TODO Add support for multiple things(/NodeInfos).
105                final Thing thing = things.get(NodeInfo.EMPTY);
106                if (thing == null) {
107                    // TODO return error if not at least one thing registered.
108                    return null;
109                }
110
111                ThingMomentaryReadOutRequest readOutRequest = thing.getMomentaryReadOutRequestHandler();
112                if (readOutRequest == null) {
113                    // TODO Thing does not provide momentary read-out
114                    return null;
115                }
116
117                // Callback hell begins here. :) XEP-0323 decouples the read-out results from the IQ result. I'm not
118                // sure if I would have made the same design decision but the reasons where likely being able to get a
119                // fast read-out acknowledgement back to the requester even with sensors that take "a long time" to
120                // read-out their values. I had designed that as special case and made the "results in IQ response" the
121                // normal case.
122                readOutRequest.momentaryReadOutRequest(new ThingMomentaryReadOutResult() {
123                    @Override
124                    public void momentaryReadOut(List<? extends IoTDataField> results) {
125                        IoTFieldsExtension iotFieldsExtension = IoTFieldsExtension.buildFor(dataRequest.getSequenceNr(), true, thing.getNodeInfo(), results);
126                        Message message = new Message(dataRequest.getFrom());
127                        message.addExtension(iotFieldsExtension);
128                        try {
129                            connection().sendStanza(message);
130                        }
131                        catch (NotConnectedException | InterruptedException e) {
132                            LOGGER.log(Level.SEVERE, "Could not send read-out response " + message, e);
133                        }
134                    }
135                });
136
137                return new IoTDataReadOutAccepted(dataRequest);
138            }
139        });
140    }
141
142    /**
143     * Install a thing in the manager. Activates data read out functionality (if provided by the
144     * thing).
145     *
146     * @param thing the thing to install.
147     */
148    public void installThing(Thing thing) {
149        things.put(thing.getNodeInfo(), thing);
150    }
151
152    public Thing uninstallThing(Thing thing) {
153        return uninstallThing(thing.getNodeInfo());
154    }
155
156    public Thing uninstallThing(NodeInfo nodeInfo) {
157        return things.remove(nodeInfo);
158    }
159
160    /**
161     * Try to read out a things momentary values.
162     *
163     * @param jid the full JID of the thing to read data from.
164     * @return a list with the read out data.
165     * @throws NoResponseException
166     * @throws XMPPErrorException
167     * @throws NotConnectedException
168     * @throws InterruptedException
169     */
170    public List<IoTFieldsExtension> requestMomentaryValuesReadOut(EntityFullJid jid)
171                    throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
172        final XMPPConnection connection = connection();
173        final int seqNr = nextSeqNr.incrementAndGet();
174        IoTDataRequest iotDataRequest = new IoTDataRequest(seqNr, true);
175        iotDataRequest.setTo(jid);
176
177        StanzaFilter doneFilter = new IoTFieldsExtensionFilter(seqNr, true);
178        StanzaFilter dataFilter = new IoTFieldsExtensionFilter(seqNr, false);
179
180        // Setup the IoTFieldsExtension message collectors before sending the IQ to avoid a data race.
181        StanzaCollector doneCollector = connection.createStanzaCollector(doneFilter);
182
183        StanzaCollector.Configuration dataCollectorConfiguration = StanzaCollector.newConfiguration().setStanzaFilter(
184                        dataFilter).setCollectorToReset(doneCollector);
185        StanzaCollector dataCollector = connection.createStanzaCollector(dataCollectorConfiguration);
186
187        try {
188            connection.createStanzaCollectorAndSend(iotDataRequest).nextResultOrThrow();
189            // Wait until a message with an IoTFieldsExtension and the done flag comes in.
190            doneCollector.nextResult();
191        }
192        finally {
193            // Ensure that the two collectors are canceled in any case.
194            dataCollector.cancel();
195            doneCollector.cancel();
196        }
197
198        int collectedCount = dataCollector.getCollectedCount();
199        List<IoTFieldsExtension> res = new ArrayList<>(collectedCount);
200        for (int i = 0; i < collectedCount; i++) {
201            Message message = dataCollector.pollResult();
202            IoTFieldsExtension iotFieldsExtension = IoTFieldsExtension.from(message);
203            res.add(iotFieldsExtension);
204        }
205
206        return res;
207    }
208}