C
C
Chvalov2015-10-02 10:44:25
Java
Chvalov, 2015-10-02 10:44:25

Who has an error in the code or am I doing something wrong?

There is a usb-serial-for-android library in which there is a code that is responsible for connecting to an FTDI device.
See starting from line 115 in the code, the author states the following:

if (sPort == null) {
            mTitleTextView.setText("No serial device.");
        } else {

And at the very beginning, it says in the change that private static UsbSerialPort sPort = null;
But if I take his example, then I will always display the text No serial device, I did this sPort != null and everything plows
My code:
import android.content.Context;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.hoho.android.usbserial.driver.UsbSerialDriver;
import com.hoho.android.usbserial.driver.UsbSerialPort;
import com.hoho.android.usbserial.driver.UsbSerialProber;
import com.hoho.android.usbserial.util.HexDump;
import com.hoho.android.usbserial.util.SerialInputOutputManager;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainActivity extends AppCompatActivity {
    private static UsbSerialPort sPort = null;
    private final ExecutorService mExecutor = Executors.newSingleThreadExecutor();
    private SerialInputOutputManager mSerialIoManager;

    TextView TV_Errors, TV_Otvet;

    private final SerialInputOutputManager.Listener mListener = new SerialInputOutputManager.Listener() {
        @Override
        public void onRunError(Exception e) {
            Log.d("MyLog", "Runner stopped.");
        }

        @Override
        public void onNewData(final byte[] data) {
            MainActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    MainActivity.this.updateReceivedData(data);
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TV_Errors = (TextView) findViewById(R.id.TV_Errors);
        TV_Otvet = (TextView) findViewById(R.id.TV_Otvet);
   }

    @Override
    protected void onResume() {
        super.onResume();
        if (sPort != null) {
            TV_Errors.setText("No serial device.");
        } else {
            // Находим все доступные устройста для роботы
            final UsbManager manager = (UsbManager) getSystemService(Context.USB_SERVICE);
            List<UsbSerialDriver> availableDrivers = UsbSerialProber.getDefaultProber().findAllDrivers(manager);
            if (availableDrivers.isEmpty()) {
                return;
            }

            // Соединяемся с первым устройством (У нас всего оно 1)
            UsbSerialDriver driver = availableDrivers.get(0);
            UsbDeviceConnection connection = manager.openDevice(driver.getDevice());
            if (connection == null) {
                TV_Errors.setText("Opening device failed");

                // Возможо нужны вызвать UsbManager.requestPermission(driver.getDevice(), ..)
                return;
            }

            try {
                sPort = driver.getPorts().get(0);
                sPort.open(connection);
                sPort.setParameters(19200, 8, UsbSerialPort.STOPBITS_1, UsbSerialPort.PARITY_NONE);
            } catch (IOException e) {
                // Deal with error.
                TV_Errors.setText("Error opening device: " + e.getMessage());
                try {
                    sPort.close();
                } catch (IOException e2) {
                    // Ignore.
                }
                sPort = null;
                return;
            }
            TV_Errors.setText("Serial device: " + sPort.getClass().getSimpleName());
        }
        onDeviceStateChange();
    }

    private void stopIoManager() {
        if (mSerialIoManager != null) {
            Log.i("MyLog", "Stopping io manager ..");
            mSerialIoManager.stop();
            mSerialIoManager = null;
        }
    }

    private void startIoManager() {
        if (sPort != null) {
            Log.i("MyLog", "Starting io manager ..");
            mSerialIoManager = new SerialInputOutputManager(sPort, mListener);
            mExecutor.submit(mSerialIoManager);
        }
    }

    private void onDeviceStateChange() {
        stopIoManager();
        startIoManager();
    }

    private void updateReceivedData(byte[] data) {
        final String message = "Read " + data.length + " bytes: \n" + HexDump.dumpHexString(data) + "\n\n";
        TV_Otvet.append(message);
        Log.d("MyLog" ,Arrays.toString(data) + "размер - " + data.length);
    }

    // Это отправка !
    public void OnClick_On1(View view) {
        byte[] send = new byte[]{1, 5, 0, 5, 0, 1, 28, 11};
        try {
            sPort.write(send, 100);  // а что 100 значит?, Я хз какоето время

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void OnClick_Exit(View view){
        finish();
        System.exit(0);
    }
}

Tell me who made a mistake, if I have something that I missed and did wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Oleg, 2015-10-02
@ollisso

The original library has this code:

static void show(Context context, UsbSerialPort port) {
sPort = port;
        final Intent intent = new Intent(context, SerialConsoleActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NO_HISTORY);
        context.startActivity(intent);
    }

The second line is important here. In it, we pass the created port and save it to sPort.
I don't see any similar piece of code.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question