1/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.accessorydisplay.source;
18
19import com.android.accessorydisplay.common.Logger;
20import com.android.accessorydisplay.common.Transport;
21
22import android.hardware.usb.UsbAccessory;
23import android.os.ParcelFileDescriptor;
24
25import java.io.FileInputStream;
26import java.io.FileOutputStream;
27import java.io.IOException;
28
29/**
30 * Sends or receives messages over a file descriptor associated with a {@link UsbAccessory}.
31 */
32public class UsbAccessoryStreamTransport extends Transport {
33    private ParcelFileDescriptor mFd;
34    private FileInputStream mInputStream;
35    private FileOutputStream mOutputStream;
36
37    public UsbAccessoryStreamTransport(Logger logger, ParcelFileDescriptor fd) {
38        super(logger, 16384);
39        mFd = fd;
40        mInputStream = new FileInputStream(fd.getFileDescriptor());
41        mOutputStream = new FileOutputStream(fd.getFileDescriptor());
42    }
43
44    @Override
45    protected void ioClose() {
46        try {
47            mFd.close();
48        } catch (IOException ex) {
49        }
50        mFd = null;
51        mInputStream = null;
52        mOutputStream = null;
53    }
54
55    @Override
56    protected int ioRead(byte[] buffer, int offset, int count) throws IOException {
57        if (mInputStream == null) {
58            throw new IOException("Stream was closed.");
59        }
60        return mInputStream.read(buffer, offset, count);
61    }
62
63    @Override
64    protected void ioWrite(byte[] buffer, int offset, int count) throws IOException {
65        if (mOutputStream == null) {
66            throw new IOException("Stream was closed.");
67        }
68        mOutputStream.write(buffer, offset, count);
69    }
70}
71