1 package org.opentrafficsim.imb.observers;
2
3 import nl.tno.imb.TByteBuffer;
4 import nl.tno.imb.TConnection;
5 import nl.tno.imb.TEventEntry;
6
7 /**
8 * <p>
9 * Copyright (c) 2013-2016 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
10 * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
11 * <p>
12 * @version $Revision$, $LastChangedDate$, by $Author$, initial version Aug 19, 2016 <br>
13 * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
14 * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
15 * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
16 */
17 public class IMBObserver implements Observer
18 {
19 /** Communication link to the observers. */
20 private final TConnection connection;
21
22 /**
23 * Construct a new connection for sending events to IMB.
24 * @param host String; name of the IMB hub
25 * @param port int; port number of the IMB hub
26 * @param modelName String; local model name
27 * @param modelId int; model id
28 * @param federation String; federation on the IMB hub
29 * @throws Exception when a connection to the IMB hub could not be established
30 */
31 public IMBObserver(final String host, final int port, final String modelName, final int modelId, final String federation) throws Exception
32 {
33 this.connection = new TConnection(host, port, modelName, modelId, federation);
34 if (!this.connection.isConnected())
35 {
36 throw new Exception("No connection to broker");
37 }
38 }
39
40 /**
41 * {@inheritDoc}
42 * @throws Exception
43 */
44 @Override
45 public final boolean postMessage(final String eventName, final int eventType, final Object[] args) throws Exception
46 {
47 TByteBuffer payload = new TByteBuffer();
48 payload.writeStart(0);
49 payload.write(eventType);
50 for (Object o : args)
51 {
52 String typeName = o.getClass().getName();
53 switch (typeName)
54 {
55 case "java.lang.String":
56 payload.write((String) o);
57 break;
58
59 case "java.lang.Double":
60 payload.write((Double) o);
61 break;
62
63 default:
64 throw new ClassCastException("cannot pack object of type " + typeName + " in payload");
65 }
66 }
67 int result = this.connection.signalEvent(eventName, TEventEntry.EK_NORMAL_EVENT, payload);
68 if (result < 0)
69 {
70 System.err.println("IMB error in signalEvent code " + result);
71 }
72 return result >= 0;
73 }
74
75 /** {@inheritDoc} */
76 @Override
77 public final String toString()
78 {
79 return "IMBObserver [connection=" + this.connection + "]";
80 }
81
82 }