aboutsummaryrefslogtreecommitdiff
path: root/android/WALT/app/src/main/java/org/chromium/latency/walt/WaltUsbConnection.java
blob: f118ae2b3b09cd42b5bd612804ae7de884a2adfc (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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * 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.
 */

package org.chromium.latency.walt;

import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.util.Log;

import java.io.IOException;

/**
 * A singleton used as an interface for the physical WALT device.
 */
public class WaltUsbConnection extends BaseUsbConnection implements WaltConnection {

    private static final int TEENSY_VID = 0x16c0;
    // TODO: refactor to demystify PID. See BaseUsbConnection.isCompatibleUsbDevice()
    private static final int TEENSY_PID = 0;
    private static final int HALFKAY_PID = 0x0478;
    private static final int USB_READ_TIMEOUT_MS = 200;
    private static final String TAG = "WaltUsbConnection";

    private UsbEndpoint endpointIn = null;
    private UsbEndpoint endpointOut = null;

    private RemoteClockInfo remoteClock = new RemoteClockInfo();

    private static final Object LOCK = new Object();

    private static WaltUsbConnection instance;

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

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

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

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

    @Override
    protected boolean isCompatibleUsbDevice(UsbDevice usbDevice) {
        // Allow any Teensy, but not in HalfKay bootloader mode
        // Teensy PID depends on mode (e.g: Serail + MIDI) and also changed in TeensyDuino 1.31
        return ((usbDevice.getProductId() != HALFKAY_PID) &&
                (usbDevice.getVendorId() == TEENSY_VID));
    }


    // Called when WALT is physically unplugged from USB
    @Override
    public void onDisconnect() {
        endpointIn = null;
        endpointOut = null;
        super.onDisconnect();
    }


    // Called when WALT is physically plugged into USB
    @Override
    public void onConnect() {
        // Serial mode only
        // TODO: find the interface and endpoint indexes no matter what mode it is
        int ifIdx = 1;
        int epInIdx = 1;
        int epOutIdx = 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");
            return;
        }

        endpointIn = iface.getEndpoint(epInIdx);
        endpointOut = iface.getEndpoint(epOutIdx);

        super.onConnect();
    }

    @Override
    public boolean isConnected() {
        return super.isConnected() && (endpointIn != null) && (endpointOut != null);
    }


    @Override
    public void sendByte(char c) throws IOException {
        if (!isConnected()) {
            throw new IOException("Not connected to WALT");
        }
        // logger.log("Sending char " + c);
        usbConnection.bulkTransfer(endpointOut, Utils.char2byte(c), 1, 100);
    }

    @Override
    public int blockingRead(byte[] buffer) {
        return usbConnection.bulkTransfer(endpointIn, buffer, buffer.length, USB_READ_TIMEOUT_MS);
    }


    @Override
    public RemoteClockInfo syncClock() throws IOException {
        if (!isConnected()) {
            throw new IOException("Not connected to WALT");
        }

        try {
            int fd = usbConnection.getFileDescriptor();
            int ep_out = endpointOut.getAddress();
            int ep_in = endpointIn.getAddress();

            remoteClock.baseTime = syncClock(fd, ep_out, ep_in);
            remoteClock.minLag = 0;
            remoteClock.maxLag = getMaxE();
        } catch (Exception e) {
            logger.log("Exception while syncing clocks: " + e.getStackTrace());
        }
        logger.log("Synced clocks, maxE=" + remoteClock.maxLag + "us");
        Log.i(TAG, remoteClock.toString());
        return remoteClock;
    }

    @Override
    public void updateLag() {
        if (! isConnected()) {
            logger.log("ERROR: Not connected, aborting checkDrift()");
            return;
        }
        updateBounds();
        remoteClock.minLag = getMinE();
        remoteClock.maxLag = getMaxE();
    }



    // NDK / JNI stuff
    // TODO: add guards to avoid calls to updateBounds and getter when listener is running.
    private native long syncClock(int fd, int endpoint_out, int endpoint_in);

    private native void updateBounds();

    private native int getMinE();

    private native int getMaxE();

    static {
        System.loadLibrary("sync_clock_jni");
    }
}