summaryrefslogtreecommitdiff
path: root/packages/SystemUI/src/com/android/systemui/statusbar/policy/SignalController.java
blob: 52f7ae0c583747d8d82ae5918231e3da29258bd7 (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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
/*
 * Copyright (C) 2015 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 com.android.systemui.statusbar.policy;

import static com.android.systemui.statusbar.policy.NetworkControllerImpl.TAG;

import android.annotation.NonNull;
import android.content.Context;
import android.text.format.DateFormat;
import android.util.Log;

import com.android.systemui.statusbar.policy.NetworkController.SignalCallback;

import java.io.PrintWriter;
import java.util.BitSet;


/**
 * Common base class for handling signal for both wifi and mobile data.
 */
public abstract class SignalController<T extends SignalController.State,
        I extends SignalController.IconGroup> {
    // Save the previous SignalController.States of all SignalControllers for dumps.
    static final boolean RECORD_HISTORY = true;
    // If RECORD_HISTORY how many to save, must be a power of 2.
    static final int HISTORY_SIZE = 64;

    protected static final boolean DEBUG = NetworkControllerImpl.DEBUG;
    protected static final boolean CHATTY = NetworkControllerImpl.CHATTY;

    protected final String mTag;
    protected final T mCurrentState;
    protected final T mLastState;
    protected final int mTransportType;
    protected final Context mContext;
    // The owner of the SignalController (i.e. NetworkController will maintain the following
    // lists and call notifyListeners whenever the list has changed to ensure everyone
    // is aware of current state.
    protected final NetworkControllerImpl mNetworkController;

    private final CallbackHandler mCallbackHandler;

    // Save the previous HISTORY_SIZE states for logging.
    private final State[] mHistory;
    // Where to copy the next state into.
    private int mHistoryIndex;

    public SignalController(String tag, Context context, int type, CallbackHandler callbackHandler,
            NetworkControllerImpl networkController) {
        mTag = TAG + "." + tag;
        mNetworkController = networkController;
        mTransportType = type;
        mContext = context;
        mCallbackHandler = callbackHandler;
        mCurrentState = cleanState();
        mLastState = cleanState();
        if (RECORD_HISTORY) {
            mHistory = new State[HISTORY_SIZE];
            for (int i = 0; i < HISTORY_SIZE; i++) {
                mHistory[i] = cleanState();
            }
        }
    }

    public T getState() {
        return mCurrentState;
    }

    public void updateConnectivity(BitSet connectedTransports, BitSet validatedTransports) {
        mCurrentState.inetCondition = validatedTransports.get(mTransportType) ? 1 : 0;
        notifyListenersIfNecessary();
    }

    /**
     * Used at the end of demo mode to clear out any ugly state that it has created.
     * Since we haven't had any callbacks, then isDirty will not have been triggered,
     * so we can just take the last good state directly from there.
     *
     * Used for demo mode.
     */
    public void resetLastState() {
        mCurrentState.copyFrom(mLastState);
    }

    /**
     * Determines if the state of this signal controller has changed and
     * needs to trigger callbacks related to it.
     */
    public boolean isDirty() {
        if (!mLastState.equals(mCurrentState)) {
            if (DEBUG) {
                Log.d(mTag, "Change in state from: " + mLastState + "\n"
                        + "\tto: " + mCurrentState);
            }
            return true;
        }
        return false;
    }

    public void saveLastState() {
        if (RECORD_HISTORY) {
            recordLastState();
        }
        // Updates the current time.
        mCurrentState.time = System.currentTimeMillis();
        mLastState.copyFrom(mCurrentState);
    }

    /**
     * Gets the signal icon for QS based on current state of connected, enabled, and level.
     */
    public int getQsCurrentIconId() {
        if (mCurrentState.connected) {
            return getIcons().mQsIcons[mCurrentState.inetCondition][mCurrentState.level];
        } else if (mCurrentState.enabled) {
            return getIcons().mQsDiscState;
        } else {
            return getIcons().mQsNullState;
        }
    }

    /**
     * Gets the signal icon for SB based on current state of connected, enabled, and level.
     */
    public int getCurrentIconId() {
        if (mCurrentState.connected) {
            return getIcons().mSbIcons[mCurrentState.inetCondition][mCurrentState.level];
        } else if (mCurrentState.enabled) {
            return getIcons().mSbDiscState;
        } else {
            return getIcons().mSbNullState;
        }
    }

    /**
     * Gets the content description id for the signal based on current state of connected and
     * level.
     */
    public int getContentDescription() {
        if (mCurrentState.connected) {
            return getIcons().mContentDesc[mCurrentState.level];
        } else {
            return getIcons().mDiscContentDesc;
        }
    }

    public void notifyListenersIfNecessary() {
        if (isDirty()) {
            saveLastState();
            notifyListeners();
        }
    }

    /**
     * Returns the resource if resId is not 0, and an empty string otherwise.
     */
    @NonNull CharSequence getStringIfExists(int resId) {
        return resId != 0 ? mContext.getText(resId) : "";
    }

    protected I getIcons() {
        return (I) mCurrentState.iconGroup;
    }

    /**
     * Saves the last state of any changes, so we can log the current
     * and last value of any state data.
     */
    protected void recordLastState() {
        mHistory[mHistoryIndex++ & (HISTORY_SIZE - 1)].copyFrom(mLastState);
    }

    public void dump(PrintWriter pw) {
        pw.println("  - " + mTag + " -----");
        pw.println("  Current State: " + mCurrentState);
        if (RECORD_HISTORY) {
            // Count up the states that actually contain time stamps, and only display those.
            int size = 0;
            for (int i = 0; i < HISTORY_SIZE; i++) {
                if (mHistory[i].time != 0) size++;
            }
            // Print out the previous states in ordered number.
            for (int i = mHistoryIndex + HISTORY_SIZE - 1;
                    i >= mHistoryIndex + HISTORY_SIZE - size; i--) {
                pw.println("  Previous State(" + (mHistoryIndex + HISTORY_SIZE - i) + "): "
                        + mHistory[i & (HISTORY_SIZE - 1)]);
            }
        }
    }

    public final void notifyListeners() {
        notifyListeners(mCallbackHandler);
    }

    /**
     * Trigger callbacks based on current state.  The callbacks should be completely
     * based on current state, and only need to be called in the scenario where
     * mCurrentState != mLastState.
     */
    public abstract void notifyListeners(SignalCallback callback);

    /**
     * Generate a blank T.
     */
    protected abstract T cleanState();

    /*
     * Holds icons for a given state. Arrays are generally indexed as inet
     * state (full connectivity or not) first, and second dimension as
     * signal strength.
     */
    static class IconGroup {
        final int[][] mSbIcons;
        final int[][] mQsIcons;
        final int[] mContentDesc;
        final int mSbNullState;
        final int mQsNullState;
        final int mSbDiscState;
        final int mQsDiscState;
        final int mDiscContentDesc;
        // For logging.
        final String mName;

        public IconGroup(String name, int[][] sbIcons, int[][] qsIcons, int[] contentDesc,
                int sbNullState, int qsNullState, int sbDiscState, int qsDiscState,
                int discContentDesc) {
            mName = name;
            mSbIcons = sbIcons;
            mQsIcons = qsIcons;
            mContentDesc = contentDesc;
            mSbNullState = sbNullState;
            mQsNullState = qsNullState;
            mSbDiscState = sbDiscState;
            mQsDiscState = qsDiscState;
            mDiscContentDesc = discContentDesc;
        }

        @Override
        public String toString() {
            return "IconGroup(" + mName + ")";
        }
    }

    static class State {
        boolean connected;
        boolean enabled;
        boolean activityIn;
        boolean activityOut;
        int level;
        IconGroup iconGroup;
        int inetCondition;
        int rssi; // Only for logging.

        // Not used for comparison, just used for logging.
        long time;

        public void copyFrom(State state) {
            connected = state.connected;
            enabled = state.enabled;
            level = state.level;
            iconGroup = state.iconGroup;
            inetCondition = state.inetCondition;
            activityIn = state.activityIn;
            activityOut = state.activityOut;
            rssi = state.rssi;
            time = state.time;
        }

        @Override
        public String toString() {
            if (time != 0) {
                StringBuilder builder = new StringBuilder();
                toString(builder);
                return builder.toString();
            } else {
                return "Empty " + getClass().getSimpleName();
            }
        }

        protected void toString(StringBuilder builder) {
            builder.append("connected=").append(connected).append(',')
                    .append("enabled=").append(enabled).append(',')
                    .append("level=").append(level).append(',')
                    .append("inetCondition=").append(inetCondition).append(',')
                    .append("iconGroup=").append(iconGroup).append(',')
                    .append("activityIn=").append(activityIn).append(',')
                    .append("activityOut=").append(activityOut).append(',')
                    .append("rssi=").append(rssi).append(',')
                    .append("lastModified=").append(DateFormat.format("MM-dd HH:mm:ss", time));
        }

        @Override
        public boolean equals(Object o) {
            if (!o.getClass().equals(getClass())) {
                return false;
            }
            State other = (State) o;
            return other.connected == connected
                    && other.enabled == enabled
                    && other.level == level
                    && other.inetCondition == inetCondition
                    && other.iconGroup == iconGroup
                    && other.activityIn == activityIn
                    && other.activityOut == activityOut
                    && other.rssi == rssi;
        }
    }
}