NewDeviceAction.java revision 79c58a4b97f27ede6a1b680d2fece9c2a0edf7b7
1/*
2 * Copyright (C) 2014 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 */
16package com.android.server.hdmi;
17
18import android.hardware.hdmi.HdmiCec;
19import android.hardware.hdmi.HdmiCecDeviceInfo;
20import android.hardware.hdmi.HdmiCecMessage;
21import android.util.Slog;
22
23import java.io.UnsupportedEncodingException;
24
25/**
26 * Feature action that discovers the information of a newly found logical device.
27 *
28 * This action is created when receiving <Report Physical Address>, a CEC command a newly
29 * connected HDMI-CEC device broadcasts to announce its advent. Additional commands are issued in
30 * this action to gather more information on the device such as OSD name and device vendor ID.
31 *
32 * <p>The result is made in the form of {@link HdmiCecDeviceInfo} object, and passed to service
33 * for the management through its life cycle.
34 *
35 * <p>Package-private, accessed by {@link HdmiControlService} only.
36 */
37final class NewDeviceAction extends FeatureAction {
38
39    private static final String TAG = "NewDeviceAction";
40
41    // State in which the action sent <Give OSD Name> and is waiting for <Set OSD Name>
42    // that contains the name of the device for display on screen.
43    static final int STATE_WAITING_FOR_SET_OSD_NAME = 1;
44
45    // State in which the action sent <Give Device Vendor ID> and is waiting for
46    // <Device Vendor ID> that contains the vendor ID of the device.
47    static final int STATE_WAITING_FOR_DEVICE_VENDOR_ID = 2;
48
49    private final int mDeviceLogicalAddress;
50    private final int mDevicePhysicalAddress;
51    private final boolean mRequireRoutingChange;
52
53    private int mVendorId;
54    private String mDisplayName;
55
56    /**
57     * Constructor.
58     *
59     * @param source {@link HdmiCecLocalDevice} instance
60     * @param deviceLogicalAddress logical address of the device in interest
61     * @param devicePhysicalAddress physical address of the device in interest
62     * @param requireRoutingChange whether to initiate routing change or not
63     */
64    NewDeviceAction(HdmiCecLocalDevice source, int deviceLogicalAddress,
65            int devicePhysicalAddress, boolean requireRoutingChange) {
66        super(source);
67        mDeviceLogicalAddress = deviceLogicalAddress;
68        mDevicePhysicalAddress = devicePhysicalAddress;
69        mVendorId = HdmiCec.UNKNOWN_VENDOR_ID;
70        mRequireRoutingChange = requireRoutingChange;
71    }
72
73    @Override
74    public boolean start() {
75        if (HdmiCec.getTypeFromAddress(getSourceAddress()) == HdmiCec.DEVICE_AUDIO_SYSTEM) {
76            if (tv().getAvrDeviceInfo() == null) {
77                // TODO: Start system audio initiation action
78            }
79
80            // If new device is connected through ARC enabled port,
81            // initiates ARC channel establishment.
82            if (tv().isConnectedToArcPort(mDevicePhysicalAddress)) {
83                addAndStartAction(new RequestArcInitiationAction(localDevice(),
84                                mDeviceLogicalAddress));
85            }
86        }
87
88        if (mRequireRoutingChange) {
89            startRoutingChange();
90        }
91
92        mState = STATE_WAITING_FOR_SET_OSD_NAME;
93        if (mayProcessCommandIfCached(mDeviceLogicalAddress, HdmiCec.MESSAGE_SET_OSD_NAME)) {
94            return true;
95        }
96
97        sendCommand(HdmiCecMessageBuilder.buildGiveOsdNameCommand(getSourceAddress(),
98                mDeviceLogicalAddress));
99        addTimer(mState, TIMEOUT_MS);
100        return true;
101    }
102
103    @Override
104    public boolean processCommand(HdmiCecMessage cmd) {
105        // For the logical device in interest, we want two more pieces of information -
106        // osd name and vendor id. They are requested in sequence. In case we don't
107        // get the expected responses (either by timeout or by receiving <feature abort> command),
108        // set them to a default osd name and unknown vendor id respectively.
109        int opcode = cmd.getOpcode();
110        int src = cmd.getSource();
111        byte[] params = cmd.getParams();
112
113        if (mDeviceLogicalAddress != src) {
114            return false;
115        }
116
117        if (mState == STATE_WAITING_FOR_SET_OSD_NAME) {
118            if (opcode == HdmiCec.MESSAGE_SET_OSD_NAME) {
119                try {
120                    mDisplayName = new String(params, "US-ASCII");
121                } catch (UnsupportedEncodingException e) {
122                    Slog.e(TAG, "Failed to get OSD name: " + e.getMessage());
123                }
124                requestVendorId();
125                return true;
126            } else if (opcode == HdmiCec.MESSAGE_FEATURE_ABORT) {
127                int requestOpcode = params[1] & 0xFF;
128                if (requestOpcode == HdmiCec.MESSAGE_SET_OSD_NAME) {
129                    requestVendorId();
130                    return true;
131                }
132            }
133        } else if (mState == STATE_WAITING_FOR_DEVICE_VENDOR_ID) {
134            if (opcode == HdmiCec.MESSAGE_DEVICE_VENDOR_ID) {
135                if (params.length == 3) {
136                    mVendorId = HdmiUtils.threeBytesToInt(params);
137                } else {
138                    Slog.e(TAG, "Failed to get device vendor ID: ");
139                }
140                addDeviceInfo();
141                finish();
142                return true;
143            } else if (opcode == HdmiCec.MESSAGE_FEATURE_ABORT) {
144                int requestOpcode = params[1] & 0xFF;
145                if (requestOpcode == HdmiCec.MESSAGE_DEVICE_VENDOR_ID) {
146                    addDeviceInfo();
147                    finish();
148                    return true;
149                }
150            }
151        }
152        return false;
153    }
154
155    private void startRoutingChange() {
156        // Stop existing routing control.
157        removeAction(RoutingControlAction.class);
158
159        // Send routing change. The the address is a path of the active port.
160        int newPath = toTopMostPortPath(mDevicePhysicalAddress);
161        sendCommand(HdmiCecMessageBuilder.buildRoutingChange(getSourceAddress(),
162                localDevice().getActivePath(), newPath));
163        addAndStartAction(new RoutingControlAction(localDevice(),
164                localDevice().pathToPortId(newPath), null));
165    }
166
167    private static int toTopMostPortPath(int physicalAddress) {
168        return physicalAddress & HdmiConstants.ROUTING_PATH_TOP_MASK;
169    }
170
171    private boolean mayProcessCommandIfCached(int destAddress, int opcode) {
172        HdmiCecMessage message = getCecMessageCache().getMessage(destAddress, opcode);
173        if (message != null) {
174            return processCommand(message);
175        }
176        return false;
177    }
178
179    private void requestVendorId() {
180        // At first, transit to waiting status for <Device Vendor Id>.
181        mState = STATE_WAITING_FOR_DEVICE_VENDOR_ID;
182        // If the message is already in cache, process it.
183        if (mayProcessCommandIfCached(mDeviceLogicalAddress, HdmiCec.MESSAGE_DEVICE_VENDOR_ID)) {
184            return;
185        }
186        sendCommand(HdmiCecMessageBuilder.buildGiveDeviceVendorIdCommand(getSourceAddress(),
187                mDeviceLogicalAddress));
188        addTimer(mState, TIMEOUT_MS);
189    }
190
191    private void addDeviceInfo() {
192        if (mDisplayName == null) {
193            mDisplayName = HdmiCec.getDefaultDeviceName(mDeviceLogicalAddress);
194        }
195        tv().addCecDevice(new HdmiCecDeviceInfo(
196                mDeviceLogicalAddress, mDevicePhysicalAddress,
197                HdmiCec.getTypeFromAddress(mDeviceLogicalAddress),
198                mVendorId, mDisplayName));
199    }
200
201    @Override
202    public void handleTimerEvent(int state) {
203        if (mState == STATE_NONE || mState != state) {
204            return;
205        }
206        if (state == STATE_WAITING_FOR_SET_OSD_NAME) {
207            // Osd name request timed out. Try vendor id
208            requestVendorId();
209        } else if (state == STATE_WAITING_FOR_DEVICE_VENDOR_ID) {
210            // vendor id timed out. Go ahead creating the device info what we've got so far.
211            addDeviceInfo();
212            finish();
213        }
214    }
215}
216