11package com .licheedev .modbus4android ;
22
3+ import android .os .SystemClock ;
34import android .support .annotation .NonNull ;
45import android .util .Log ;
56import com .serotonin .modbus4j .ModbusMaster ;
@@ -50,6 +51,8 @@ public class ModbusWorker implements IModbusWorker {
5051 private final ExecutorService mRequestExecutor ;
5152
5253 protected ModbusMaster mModbusMaster ;
54+ private long mSendTime ;
55+ private long mSendIntervalTime ;
5356
5457 public ModbusWorker () {
5558
@@ -115,13 +118,33 @@ public void checkWorkingState() throws ModbusInitException, IllegalStateExceptio
115118 * @throws ModbusRespException
116119 * @throws ExecutionException
117120 */
118- private <T > T doSync (Callable <T > callable )
121+ private <T > T doSync (final Callable <T > callable )
119122 throws InterruptedException , ModbusInitException , ModbusTransportException ,
120123 ModbusRespException , ExecutionException {
121124
122125 Future <T > submit = null ;
123126 try {
124- submit = mRequestExecutor .submit (callable );
127+
128+ Callable <T > finalCallable = callable ;
129+
130+ if (getSendIntervalTime () > 0 ) {
131+ finalCallable = new Callable <T >() {
132+ @ Override
133+ public T call () throws Exception {
134+ if (mSendTime > 0 ) {
135+ long offset =
136+ (getSendIntervalTime () - SystemClock .uptimeMillis () - mSendTime );
137+ if (offset > 0 ) {
138+ SystemClock .sleep (offset );
139+ }
140+ }
141+ T result = callable .call ();
142+ mSendTime = SystemClock .uptimeMillis ();
143+ return result ;
144+ }
145+ };
146+ }
147+ submit = mRequestExecutor .submit (finalCallable );
125148 return submit .get ();
126149 } catch (InterruptedException e ) {
127150 if (submit != null ) {
@@ -144,6 +167,31 @@ private <T> T doSync(Callable<T> callable)
144167 }
145168 }
146169
170+ /**
171+ * 发送命令间隔时间
172+ *
173+ * @return
174+ */
175+ protected long getSendIntervalTime () {
176+ return mSendIntervalTime ;
177+ }
178+
179+ /**
180+ * 设置两次发送命令之间必须要等待的时间
181+ *
182+ * @param ms
183+ * @return
184+ */
185+ public void setSendIntervalTime (long ms ) {
186+
187+ if (ms < 0 ) {
188+ throw new IllegalArgumentException (
189+ "Send interval time should not be negative, but now ms=" + ms );
190+ }
191+
192+ mSendIntervalTime = ms ;
193+ }
194+
147195 /**
148196 * Rx发送数据源
149197 *
@@ -234,6 +282,9 @@ private Callable<ModbusMaster> callableInit(final ModbusParam param) {
234282 @ Override
235283 public ModbusMaster call () throws Exception {
236284
285+ // 重置发送时间
286+ mSendTime = 0 ;
287+
237288 if (mModbusMaster != null ) {
238289 mModbusMaster .destroy ();
239290 mModbusMaster = null ;
@@ -286,7 +337,7 @@ public synchronized ModbusMaster syncInit(final ModbusParam param)
286337 */
287338 @ Override
288339 public Observable <ModbusMaster > rxInit (final ModbusParam param ) {
289- return getRxObservable (callableInit (param ));
340+ return getRxObservable (callableInit (param )). subscribeOn ( Schedulers . io ()) ;
290341 }
291342
292343 /**
0 commit comments