package com.jiebao.h518.scan;

import android.gpio.GpioJNI;
import android.util.Log;
import android_serialport_api.SerialPort;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class NewScanControler {
	protected SerialPort mSerialPort;
	protected OutputStream mOutputStream;
	private InputStream mInputStream;

	public NewScanControler() throws SecurityException, IOException {
		mSerialPort = new SerialPort(new File("/dev/ttySAC1"), 9600, 8, 'N', 1,
				0);
		mOutputStream = mSerialPort.getOutputStream();
		mInputStream = mSerialPort.getInputStream();
	}

	public void close() {

		mSerialPort.close();
	}

	public String getData() {
		int size;
		try {
			if (mInputStream == null) {
				return "";
			}
			int cout = mInputStream.available();
			byte[] buffer1 = new byte[cout];

			cout = 0;
			buffer1 = null;

			cout = mInputStream.available();
			buffer1 = new byte[cout];

			size = mInputStream.read(buffer1);
			if (size > 0) {
				String data = new String(buffer1);
				return data;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return "";
	}

	public void initScan() {
		GpioJNI.gpio_switch_scan_rf_ired(0);
		GpioJNI.gpio_switch_scan_power(1);
	}

	public void stopScan() {
		GpioJNI.gpio_switch_scan_trig(0);

	}

	public void scanOnce() {
		int triggerVal = GpioJNI.gpio_get_scan_trig();
		if (triggerVal == 1) {
			GpioJNI.gpio_switch_scan_trig(0);
		} else {
			// checkIsSleep();
			GpioJNI.gpio_switch_scan_trig(1);
		}
//		Log.i("info", "-----");
	}

	void checkIsSleep() {
		int triggerVal = GpioJNI.gpio_get_scan_trig();
		if (triggerVal == 1) {
			Log.i("info", "+++++");
			GpioJNI.gpio_switch_scan_trig(0);
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
