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
9
10
11
12
13
14
15
16
17 public class IMBObserver implements Observer
18 {
19
20 private final TConnection connection;
21
22
23
24
25
26
27
28
29
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
42
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
76 @Override
77 public final String toString()
78 {
79 return "IMBObserver [connection=" + this.connection + "]";
80 }
81
82 }