aboutsummaryrefslogtreecommitdiff
path: root/android/WALT/app/src/main/java/org/chromium/latency/walt/programmer/BootloaderConnection.java
blob: 0f2e80293ad37b788882429d89974a041c33e951 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package org.chromium.latency.walt.programmer;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbInterface;

import org.chromium.latency.walt.BaseUsbConnection;

class BootloaderConnection extends BaseUsbConnection {
    private static final int HALFKAY_VID = 0x16C0;
    private static final int HALFKAY_PID = 0x0478;

    private static final Object LOCK = new Object();
    private static BootloaderConnection instance;

    public static BootloaderConnection getInstance(Context context) {
        synchronized (LOCK) {
            if (instance == null) {
                instance = new BootloaderConnection(context.getApplicationContext());
            }
            return instance;
        }
    }

    @Override
    public int getPid() {
        return HALFKAY_PID;
    }

    @Override
    public int getVid() {
        return HALFKAY_VID;
    }

    @Override
    protected boolean isCompatibleUsbDevice(UsbDevice usbDevice) {
        return ((usbDevice.getProductId() == HALFKAY_PID) &&
                (usbDevice.getVendorId() == HALFKAY_VID));
    }

    @Override
    public void onConnect() {
        int ifIdx = 0;

        UsbInterface iface = usbDevice.getInterface(ifIdx);

        if (usbConnection.claimInterface(iface, true)) {
            logger.log("Interface claimed successfully\n");
        } else {
            logger.log("ERROR - can't claim interface\n");
        }

        super.onConnect();
    }

    public void write(byte[] buf, int timeout) {
        write(buf, 0, buf.length, timeout);
    }

    public void write(byte[] buf, int index, int len, int timeout) {
        if (!isConnected()) return;

        while (timeout > 0) {
            // USB HID Set_Report message
            int result = usbConnection.controlTransfer(0x21, 9, 0x0200, index, buf, len, timeout);

            if (result >= 0) break;
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            timeout -= 10;
        }
    }

    private BootloaderConnection(Context context) {
        super(context);
    }
}