1 package eu.javaexperience.electronic.uartbus.rpc.client;
3 import java.io.Closeable;
4 import java.io.IOException;
5 import java.util.concurrent.TimeUnit;
24 protected static final Logger LOG = JavaExperienceLoggingFacility.getLogger(
new Loggable(
"UartbusTransaction"));
28 public boolean zeroNamespaceAnswer;
35 public byte[] payload;
37 public volatile boolean revoked =
false;
39 public volatile byte[] responsePayload;
46 public byte[] toPacket()
51 public void send()
throws IOException
55 throw new IllegalOperationException(
"Request already sent and responded!");
59 bus.addPendingRequest(
this);
61 byte[] send = toPacket();
64 bus.sendPacket.publish(send);
67 if(LOG.mayLog(LogLevel.TRACE))
69 LoggingTools.tryLogFormat(LOG, LogLevel.TRACE,
"Request sent: %s", hashCode());
74 public void close()
throws IOException
77 bus.revokePendingRequest(
this);
81 protected void finalize()
throws Throwable
88 protected final WaitForSingleEvent wait =
new WaitForSingleEvent();
90 public boolean isResponsed()
92 return null != responsePayload;
95 public boolean isRevoked()
97 return null != responsePayload && revoked;
100 public boolean waitResponse(
long timeout, TimeUnit unit)
throws InterruptedException
102 AssertArgument.assertTrue(!revoked,
"Request has been revoked");
103 long t0 = System.currentTimeMillis();
104 wait.waitForEvent(timeout, unit);
105 AssertArgument.assertTrue(!revoked,
"Request has been revoked");
106 if(LOG.mayLog(LogLevel.TRACE))
108 LoggingTools.tryLogFormat(LOG, LogLevel.TRACE,
"waitResponse ended for %s after %s ms with result: %s", hashCode(), System.currentTimeMillis()-t0, null != responsePayload);
110 return null != responsePayload;
113 public byte[] ensureResponse(
long timeout, TimeUnit unit)
throws InterruptedException
115 return ensureResponse(timeout, unit, null);
118 public byte[] ensureResponse(
long timeout, TimeUnit unit, String errAppendMsg)
throws InterruptedException
120 if(!waitResponse(timeout, unit))
122 throw new TransactionException(
"Device (`"+to+
"`) not responded within "+timeout+
" "+unit+
" for the request"+(null == errAppendMsg?
"":
": "+errAppendMsg));
125 return responsePayload;
128 protected void receiveResponse(byte[] data)
130 AssertArgument.assertNotNull(data,
"data");
131 responsePayload = data;
132 if(LOG.mayLog(LogLevel.TRACE))
134 LoggingTools.tryLogFormat(LOG, LogLevel.TRACE,
"Response received for request: %s", hashCode());
142 if(a.to ==
this.from && a.from ==
this.to && a.payload.length + (zeroNamespaceAnswer?1:0) >= path.length)
146 if(zeroNamespaceAnswer)
148 if(0 != a.payload[0])
156 for(
int i=0;i<path.length;++i)
158 if(path[i] != a.payload[diff+i])
167 receiveResponse(a.payload);