package com.intelligt.modbus.jlibmodbus.serial;

import com.google.android.things.pio.PeripheralManager;
import com.google.android.things.pio.UartDevice;
import com.intelligt.modbus.jlibmodbus.Modbus;
import com.intelligt.modbus.jlibmodbus.utils.ByteFifo;

import java.io.IOException;

/*
 * Copyright (C) 2017 Vladislav Y. Kochedykov
 *
 * [http://jlibmodbus.sourceforge.net]
 *
 * This file is part of JLibModbus.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Authors: Vladislav Y. Kochedykov, software engineer.
 * email: vladislav.kochedykov@gmail.com
 */

public class SerialPortAT extends SerialPort {

    private UartDevice port;
    byte[] buffer = new byte[Modbus.MAX_PDU_LENGTH];
    volatile long readTime = 0;

    public SerialPortAT(SerialParameters sp) {
        super(sp);
        port = null;
    }

    @Override
    public void write(int b) throws IOException {
        try {
            port.write(new byte[]{(byte)(b&0xff)}, 1);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public void write(byte[] bytes) throws IOException {
        try {
            port.write(bytes, bytes.length);
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public void open() throws SerialPortException {
        try {
            SerialParameters sp = getSerialParameters();
            port = PeripheralManager.getInstance().openUartDevice(sp.getDevice());
            port.setBaudrate(sp.getBaudRate());
            port.setDataSize(sp.getDataBits());
            port.setParity(sp.getParity().getValue());
            port.setStopBits(sp.getStopBits());
            port.setHardwareFlowControl(UartDevice.HW_FLOW_CONTROL_NONE);
        } catch (Exception ex) {
            throw new SerialPortException(ex);
        }
    }

    @Override
    public int read() throws IOException {
        try {
            readTime = System.currentTimeMillis();
            while ((System.currentTimeMillis() - readTime) < getReadTimeout() && port.read(buffer, 1) != 1);
            return buffer[0];
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public int read(byte[] b, int off, final int len) throws IOException {
        try {
            readTime = System.currentTimeMillis();
            int count;

            count = port.read(buffer, buffer.length);
            while ((System.currentTimeMillis() - readTime) < getReadTimeout() && count > 0) {
                System.arraycopy(buffer, 0, b, off, count);
                off += count;
                //byteFifo.write(buffer, 0, count);
                count = port.read(buffer, buffer.length);
            }
            return off;
        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    @Override
    public void close() {
        if (isOpened()) {
            try {
                synchronized (this) {
                    port.close();
                    port = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    synchronized public boolean isOpened() {
        return port != null;
    }
}

@@ -2485,32 +2485,80 @@
           while 
+(port.read(buffer, 1) %3C 1) %7B%0A                if 
 ((System.current
@@ -2574,33 +2574,33 @@
 s() - readTime) 
-%3C
+%3E
  getReadTimeout(
@@ -2604,39 +2604,102 @@
 ut()
- && port.read(buffer, 1) != 1);
+) %7B%0A                    throw new IOException(%22Read timeout%22);%0A                %7D%0A            %7D
 %0A   
@@ -2958,32 +2958,54 @@
 ntTimeMillis();%0A
+            int read;%0A
             int 
@@ -3009,16 +3009,20 @@
 nt count
+ = 0
 ;%0A%0A     
@@ -3020,37 +3020,74 @@
 0;%0A%0A            
-count
+while (count %3C len) %7B%0A                read
  = port.read(buf
@@ -3123,89 +3123,192 @@
     
-while ((System.currentTimeMillis() - readTime) %3C getReadTimeout() && count %3E 0) %7B
+    count += read;%0A                if (count %3E len) %7B%0A                    int diff = count - len;%0A                    read -= diff;%0A                    count -= diff;%0A                %7D
 %0A   
@@ -3356,21 +3356,20 @@
 b, off, 
-count
+read
 );%0A     
@@ -3390,14 +3390,14 @@
  += 
-count;
+read;%0A
 %0A   
@@ -3413,101 +3413,150 @@
     
-//byteFifo.write(buffer, 0, count);%0A                count = port.read(buffer, buffer.length);
+if ((System.currentTimeMillis() - readTime) %3E getReadTimeout()) %7B%0A                    throw new IOException(%22Read timeout%22);%0A                %7D
 %0A   
@@ -3585,19 +3585,21 @@
  return 
-off
+count
 ;%0A      

Fix bug with listening for incoming data on Android Things device.