RoutingControlAction.java revision 7c3a95633d307c4be30c9dbbf1071063aa7a3c64
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 */
16
17package com.android.server.hdmi;
18
19import android.annotation.Nullable;
20import android.hardware.hdmi.HdmiCecDeviceInfo;
21import android.hardware.hdmi.HdmiControlManager;
22import android.hardware.hdmi.IHdmiControlCallback;
23import android.os.RemoteException;
24import android.util.Slog;
25
26import com.android.server.hdmi.HdmiControlService.SendMessageCallback;
27
28/**
29 * Feature action for routing control. Exchanges routing-related commands with other devices
30 * to determine the new active source.
31 *
32 * <p>This action is initiated by various cases:
33 * <ul>
34 * <li> Manual TV input switching
35 * <li> Routing change of a CEC switch other than TV
36 * <li> New CEC device at the tail of the active routing path
37 * <li> Removed CEC device from the active routing path
38 * <li> Routing at CEC enable time
39 * </ul>
40 */
41final class RoutingControlAction extends FeatureAction {
42    private static final String TAG = "RoutingControlAction";
43
44    // State in which we wait for <Routing Information> to arrive. If timed out, we use the
45    // latest routing path to set the new active source.
46    private static final int STATE_WAIT_FOR_ROUTING_INFORMATION = 1;
47
48    // State in which we wait for <Report Power Status> in response to <Give Device Power Status>
49    // we have sent. If the response tells us the device power is on, we send <Set Stream Path>
50    // to make it the active source. Otherwise we do not send <Set Stream Path>, and possibly
51    // just show the blank screen.
52    private static final int STATE_WAIT_FOR_REPORT_POWER_STATUS = 2;
53
54    // Time out in millseconds used for <Routing Information>
55    private static final int TIMEOUT_ROUTING_INFORMATION_MS = 1000;
56
57    // Time out in milliseconds used for <Report Power Status>
58    private static final int TIMEOUT_REPORT_POWER_STATUS_MS = 1000;
59
60    // true if <Give Power Status> should be sent once the new active routing path is determined.
61    private final boolean mQueryDevicePowerStatus;
62
63    // If set to true, call {@link HdmiControlService#invokeInputChangeListener()} when
64    // the routing control/active source change happens. The listener should be called if
65    // the events are triggered by external events such as manual switch port change or incoming
66    // <Inactive Source> command.
67    private final boolean mNotifyInputChange;
68
69    @Nullable private final IHdmiControlCallback mCallback;
70
71    // The latest routing path. Updated by each <Routing Information> from CEC switches.
72    private int mCurrentRoutingPath;
73
74    RoutingControlAction(HdmiCecLocalDevice localDevice, int path, boolean queryDevicePowerStatus,
75            IHdmiControlCallback callback) {
76        super(localDevice);
77        mCallback = callback;
78        mCurrentRoutingPath = path;
79        mQueryDevicePowerStatus = queryDevicePowerStatus;
80        // Callback is non-null when routing control action is brought up by binder API. Use
81        // this as an indicator for the input change notification. These API calls will get
82        // the result through this callback, not through notification. Any other events that
83        // trigger the routing control is external, for which notifcation is used.
84        mNotifyInputChange = (callback == null);
85    }
86
87    @Override
88    public boolean start() {
89        mState = STATE_WAIT_FOR_ROUTING_INFORMATION;
90        addTimer(mState, TIMEOUT_ROUTING_INFORMATION_MS);
91        return true;
92    }
93
94    @Override
95    public boolean processCommand(HdmiCecMessage cmd) {
96        int opcode = cmd.getOpcode();
97        byte[] params = cmd.getParams();
98        if (mState == STATE_WAIT_FOR_ROUTING_INFORMATION
99                && opcode == Constants.MESSAGE_ROUTING_INFORMATION) {
100            // Keep updating the physicalAddress as we receive <Routing Information>.
101            // If the routing path doesn't belong to the currently active one, we should
102            // ignore it since it might have come from other routing change sequence.
103            int routingPath = HdmiUtils.twoBytesToInt(params);
104            if (!HdmiUtils.isInActiveRoutingPath(mCurrentRoutingPath, routingPath)) {
105                return true;
106            }
107            mCurrentRoutingPath = routingPath;
108            // Stop possible previous routing change sequence if in progress.
109            removeActionExcept(RoutingControlAction.class, this);
110            addTimer(mState, TIMEOUT_ROUTING_INFORMATION_MS);
111            return true;
112        } else if (mState == STATE_WAIT_FOR_REPORT_POWER_STATUS
113                  && opcode == Constants.MESSAGE_REPORT_POWER_STATUS) {
114            handleReportPowerStatus(cmd.getParams()[0]);
115            return true;
116        }
117        return false;
118    }
119
120    private void handleReportPowerStatus(int devicePowerStatus) {
121        if (isPowerOnOrTransient(getTvPowerStatus())) {
122            if (isPowerOnOrTransient(devicePowerStatus)) {
123                sendSetStreamPath();
124            } else {
125                tv().updateActiveInput(mCurrentRoutingPath, mNotifyInputChange);
126            }
127        }
128        finishWithCallback(HdmiControlManager.RESULT_SUCCESS);
129    }
130
131    private int getTvPowerStatus() {
132        return tv().getPowerStatus();
133    }
134
135    private static boolean isPowerOnOrTransient(int status) {
136        return status == HdmiControlManager.POWER_STATUS_ON
137                || status == HdmiControlManager.POWER_STATUS_TRANSIENT_TO_ON;
138    }
139
140    private void sendSetStreamPath() {
141        sendCommand(HdmiCecMessageBuilder.buildSetStreamPath(getSourceAddress(),
142                mCurrentRoutingPath));
143    }
144
145    private void finishWithCallback(int result) {
146        invokeCallback(result);
147        finish();
148    }
149
150    @Override
151    public void handleTimerEvent(int timeoutState) {
152        if (mState != timeoutState || mState == STATE_NONE) {
153            Slog.w("CEC", "Timer in a wrong state. Ignored.");
154            return;
155        }
156        switch (timeoutState) {
157            case STATE_WAIT_FOR_ROUTING_INFORMATION:
158                HdmiCecDeviceInfo device = tv().getDeviceInfoByPath(mCurrentRoutingPath);
159                if (device != null && mQueryDevicePowerStatus) {
160                    int deviceLogicalAddress = device.getLogicalAddress();
161                    queryDevicePowerStatus(deviceLogicalAddress, new SendMessageCallback() {
162                        @Override
163                        public void onSendCompleted(int error) {
164                            handlDevicePowerStatusAckResult(
165                                    error == HdmiControlManager.RESULT_SUCCESS);
166                        }
167                    });
168                } else {
169                    tv().updateActiveInput(mCurrentRoutingPath, mNotifyInputChange);
170                    finishWithCallback(HdmiControlManager.RESULT_SUCCESS);
171                }
172                return;
173            case STATE_WAIT_FOR_REPORT_POWER_STATUS:
174                if (isPowerOnOrTransient(getTvPowerStatus())) {
175                    tv().updateActiveInput(mCurrentRoutingPath, mNotifyInputChange);
176                    sendSetStreamPath();
177                }
178                finishWithCallback(HdmiControlManager.RESULT_SUCCESS);
179                return;
180        }
181    }
182
183    private void queryDevicePowerStatus(int address, SendMessageCallback callback) {
184        sendCommand(HdmiCecMessageBuilder.buildGiveDevicePowerStatus(getSourceAddress(), address),
185                callback);
186    }
187
188    private void handlDevicePowerStatusAckResult(boolean acked) {
189        if (acked) {
190            mState = STATE_WAIT_FOR_REPORT_POWER_STATUS;
191            addTimer(mState, TIMEOUT_REPORT_POWER_STATUS_MS);
192        } else {
193            tv().updateActiveInput(mCurrentRoutingPath, mNotifyInputChange);
194            sendSetStreamPath();
195            finishWithCallback(HdmiControlManager.RESULT_SUCCESS);
196        }
197    }
198
199    private void invokeCallback(int result) {
200        if (mCallback == null) {
201            return;
202        }
203        try {
204            mCallback.onComplete(result);
205        } catch (RemoteException e) {
206            // Do nothing.
207        }
208    }
209}
210