aboutsummaryrefslogtreecommitdiffstats
path: root/src/java/com/android/internal/telephony/test/ModelInterpreter.java
blob: 20aca897446f81065db8482a4e83d1462ff50b52 (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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
/*
 * Copyright (C) 2006 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.internal.telephony.test;

import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.telephony.Rlog;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

// Also in ATChannel.java
class LineReader
{
    /**
     * Not threadsafe
     * Assumes input is ASCII
     */

    //***** Constants

    // For what it's worth, this is also the size of an
    // OMAP CSMI mailbox
    static final int BUFFER_SIZE = 0x1000;

    // just to prevent constant allocations
    byte buffer[] = new byte[BUFFER_SIZE];

    //***** Instance Variables

    InputStream inStream;

    LineReader (InputStream s)
    {
        inStream = s;
    }

    String
    getNextLine()
    {
        return getNextLine(false);
    }

    String
    getNextLineCtrlZ()
    {
        return getNextLine(true);
    }

    /**
     * Note: doesn't return the last incomplete line read on EOF, since
     * it doesn't typically matter anyway
     *
     * Returns NULL on EOF
     */

    String
    getNextLine(boolean ctrlZ)
    {
        int i = 0;

        try {
            for (;;) {
                int result;

                result = inStream.read();

                if (result < 0) {
                    return null;
                }

                if (ctrlZ && result == 0x1a) {
                    break;
                } else if (result == '\r' || result == '\n') {
                    if (i == 0) {
                        // Skip leading cr/lf
                        continue;
                    } else {
                        break;
                    }
                }

                buffer[i++] = (byte)result;
            }
        } catch (IOException ex) {
            return null;
        } catch (IndexOutOfBoundsException ex) {
            System.err.println("ATChannel: buffer overflow");
        }

        try {
            return new String(buffer, 0, i, "US-ASCII");
        } catch (UnsupportedEncodingException ex) {
            System.err.println("ATChannel: implausable UnsupportedEncodingException");
            return null;
        }
    }
}



class InterpreterEx extends Exception
{
    public
    InterpreterEx (String result)
    {
        this.result = result;
    }

    String result;
}

public class ModelInterpreter
            implements Runnable, SimulatedRadioControl
{
    static final int MAX_CALLS = 6;

    /** number of msec between dialing -> alerting and alerting->active */
    static final int CONNECTING_PAUSE_MSEC = 5 * 100;

    static final String LOG_TAG = "ModelInterpreter";

    //***** Instance Variables

    InputStream in;
    OutputStream out;
    LineReader lineReader;
    ServerSocket ss;

    private String finalResponse;

    SimulatedGsmCallState simulatedCallState;

    HandlerThread mHandlerThread;

    int pausedResponseCount;
    Object pausedResponseMonitor = new Object();

    //***** Events

    static final int PROGRESS_CALL_STATE        = 1;

    //***** Constructor

    public
    ModelInterpreter (InputStream in, OutputStream out)
    {
        this.in = in;
        this.out = out;

        init();
    }

    public
    ModelInterpreter (InetSocketAddress sa) throws java.io.IOException
    {
        ss = new ServerSocket();

        ss.setReuseAddress(true);
        ss.bind(sa);

        init();
    }

    private void
    init()
    {
        new Thread(this, "ModelInterpreter").start();
        mHandlerThread = new HandlerThread("ModelInterpreter");
        mHandlerThread.start();
        Looper looper = mHandlerThread.getLooper();
        simulatedCallState = new SimulatedGsmCallState(looper);
    }

    //***** Runnable Implementation

    public void run()
    {
        for (;;) {
            if (ss != null) {
                Socket s;

                try {
                    s = ss.accept();
                } catch (java.io.IOException ex) {
                    Rlog.w(LOG_TAG,
                        "IOException on socket.accept(); stopping", ex);
                    return;
                }

                try {
                    in = s.getInputStream();
                    out = s.getOutputStream();
                } catch (java.io.IOException ex) {
                    Rlog.w(LOG_TAG,
                        "IOException on accepted socket(); re-listening", ex);
                    continue;
                }

                Rlog.i(LOG_TAG, "New connection accepted");
            }


            lineReader = new LineReader (in);

            println ("Welcome");

            for (;;) {
                String line;

                line = lineReader.getNextLine();

                //System.out.println("MI<< " + line);

                if (line == null) {
                    break;
                }

                synchronized(pausedResponseMonitor) {
                    while (pausedResponseCount > 0) {
                        try {
                            pausedResponseMonitor.wait();
                        } catch (InterruptedException ex) {
                        }
                    }
                }

                synchronized (this) {
                    try {
                        finalResponse = "OK";
                        processLine(line);
                        println(finalResponse);
                    } catch (InterpreterEx ex) {
                        println(ex.result);
                    } catch (RuntimeException ex) {
                        ex.printStackTrace();
                        println("ERROR");
                    }
                }
            }

            Rlog.i(LOG_TAG, "Disconnected");

            if (ss == null) {
                // no reconnect in this case
                break;
            }
        }
    }


    //***** Instance Methods

    /** Start the simulated phone ringing */
    public void
    triggerRing(String number)
    {
        synchronized (this) {
            boolean success;

            success = simulatedCallState.triggerRing(number);

            if (success) {
                println ("RING");
            }
        }
    }

    /** If a call is DIALING or ALERTING, progress it to the next state */
    public void
    progressConnectingCallState()
    {
        simulatedCallState.progressConnectingCallState();
    }


    /** If a call is DIALING or ALERTING, progress it all the way to ACTIVE */
    public void
    progressConnectingToActive()
    {
        simulatedCallState.progressConnectingToActive();
    }

    /** automatically progress mobile originated calls to ACTIVE.
     *  default to true
     */
    public void
    setAutoProgressConnectingCall(boolean b)
    {
        simulatedCallState.setAutoProgressConnectingCall(b);
    }

    public void
    setNextDialFailImmediately(boolean b)
    {
        simulatedCallState.setNextDialFailImmediately(b);
    }

    public void setNextCallFailCause(int gsmCause)
    {
        //FIXME implement
    }


    /** hangup ringing, dialing, or actuve calls */
    public void
    triggerHangupForeground()
    {
        boolean success;

        success = simulatedCallState.triggerHangupForeground();

        if (success) {
            println ("NO CARRIER");
        }
    }

    /** hangup holding calls */
    public void
    triggerHangupBackground()
    {
        boolean success;

        success = simulatedCallState.triggerHangupBackground();

        if (success) {
            println ("NO CARRIER");
        }
    }

    /** hangup all */

    public void
    triggerHangupAll()
    {
        boolean success;

        success = simulatedCallState.triggerHangupAll();

        if (success) {
            println ("NO CARRIER");
        }
    }

    public void
    sendUnsolicited (String unsol)
    {
        synchronized (this) {
            println(unsol);
        }
    }

    public void triggerSsn(int a, int b) {}
    public void triggerIncomingUssd(String statusCode, String message) {}

    public void
    triggerIncomingSMS(String message)
    {
/**************
        StringBuilder pdu = new StringBuilder();

        pdu.append ("00");      //SMSC address - 0 bytes

        pdu.append ("04");      // Message type indicator

        // source address: +18005551212
        pdu.append("918100551521F0");

        // protocol ID and data coding scheme
        pdu.append("0000");

        Calendar c = Calendar.getInstance();

        pdu.append (c.



        synchronized (this) {
            println("+CMT: ,1\r" + pdu.toString());
        }

**************/
    }

    public void
    pauseResponses()
    {
        synchronized(pausedResponseMonitor) {
            pausedResponseCount++;
        }
    }

    public void
    resumeResponses()
    {
        synchronized(pausedResponseMonitor) {
            pausedResponseCount--;

            if (pausedResponseCount == 0) {
                pausedResponseMonitor.notifyAll();
            }
        }
    }

    //***** Private Instance Methods

    private void
    onAnswer() throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.onAnswer();

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    onHangup() throws InterpreterEx
    {
        boolean success = false;

        success = simulatedCallState.onAnswer();

        if (!success) {
            throw new InterpreterEx("ERROR");
        }

        finalResponse = "NO CARRIER";
    }

    private void
    onCHLD(String command) throws InterpreterEx
    {
        // command starts with "+CHLD="
        char c0;
        char c1 = 0;
        boolean success;

        c0 = command.charAt(6);

        if (command.length() >= 8) {
            c1 = command.charAt(7);
        }

        success = simulatedCallState.onChld(c0, c1);

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    releaseHeldOrUDUB() throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.releaseHeldOrUDUB();

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    releaseActiveAcceptHeldOrWaiting() throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.releaseActiveAcceptHeldOrWaiting();

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    switchActiveAndHeldOrWaiting() throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.switchActiveAndHeldOrWaiting();

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    separateCall(int index) throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.separateCall(index);

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    conference() throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.conference();

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    onDial(String command) throws InterpreterEx
    {
        boolean success;

        success = simulatedCallState.onDial(command.substring(1));

        if (!success) {
            throw new InterpreterEx("ERROR");
        }
    }

    private void
    onCLCC() throws InterpreterEx
    {
        List<String> lines;

        lines = simulatedCallState.getClccLines();

        for (int i = 0, s = lines.size() ; i < s ; i++) {
            println (lines.get(i));
        }
    }

    private void
    onSMSSend(String command) throws InterpreterEx
    {
        String pdu;

        print ("> ");
        pdu = lineReader.getNextLineCtrlZ();

        println("+CMGS: 1");
    }

    void
    processLine (String line) throws InterpreterEx
    {
        String[] commands;

        commands = splitCommands(line);

        for (int i = 0; i < commands.length ; i++) {
            String command = commands[i];

            if (command.equals("A")) {
                onAnswer();
            } else if (command.equals("H")) {
                onHangup();
            } else if (command.startsWith("+CHLD=")) {
                onCHLD(command);
            } else if (command.equals("+CLCC")) {
                onCLCC();
            } else if (command.startsWith("D")) {
                onDial(command);
            } else if (command.startsWith("+CMGS=")) {
                onSMSSend(command);
            } else {
                boolean found = false;

                for (int j = 0; j < sDefaultResponses.length ; j++) {
                    if (command.equals(sDefaultResponses[j][0])) {
                        String r = sDefaultResponses[j][1];
                        if (r != null) {
                            println(r);
                        }
                        found = true;
                        break;
                    }
                }

                if (!found) {
                    throw new InterpreterEx ("ERROR");
                }
            }
        }
    }


    String[]
    splitCommands(String line) throws InterpreterEx
    {
        if (!line.startsWith ("AT")) {
            throw new InterpreterEx("ERROR");
        }

        if (line.length() == 2) {
            // Just AT by itself
            return new String[0];
        }

        String ret[] = new String[1];

        //TODO fix case here too
        ret[0] = line.substring(2);

        return ret;
/****
        try {
            // i = 2 to skip over AT
            for (int i = 2, s = line.length() ; i < s ; i++) {
                // r"|([A-RT-Z]\d?)" # Normal commands eg ATA or I0
                // r"|(&[A-Z]\d*)" # & commands eg &C
                // r"|(S\d+(=\d+)?)" # S registers
                // r"((\+|%)\w+(\?|=([^;]+(;|$)))?)" # extended command eg +CREG=2


            }
        } catch (StringIndexOutOfBoundsException ex) {
            throw new InterpreterEx ("ERROR");
        }
***/
    }

    void
    println (String s)
    {
        synchronized(this) {
            try {
                byte[] bytes =  s.getBytes("US-ASCII");

                //System.out.println("MI>> " + s);

                out.write(bytes);
                out.write('\r');
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    void
    print (String s)
    {
        synchronized(this) {
            try {
                byte[] bytes =  s.getBytes("US-ASCII");

                //System.out.println("MI>> " + s + " (no <cr>)");

                out.write(bytes);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }


    public void
    shutdown()
    {
        Looper looper = mHandlerThread.getLooper();
        if (looper != null) {
            looper.quit();
        }

        try {
            in.close();
        } catch (IOException ex) {
        }
        try {
            out.close();
        } catch (IOException ex) {
        }
    }


    static final String [][] sDefaultResponses = {
        {"E0Q0V1",   null},
        {"+CMEE=2",  null},
        {"+CREG=2",  null},
        {"+CGREG=2", null},
        {"+CCWA=1",  null},
        {"+COPS=0",  null},
        {"+CFUN=1",  null},
        {"+CGMI",    "+CGMI: Android Model AT Interpreter\r"},
        {"+CGMM",    "+CGMM: Android Model AT Interpreter\r"},
        {"+CGMR",    "+CGMR: 1.0\r"},
        {"+CGSN",    "000000000000000\r"},
        {"+CIMI",    "320720000000000\r"},
        {"+CSCS=?",  "+CSCS: (\"HEX\",\"UCS2\")\r"},
        {"+CFUN?",   "+CFUN: 1\r"},
        {"+COPS=3,0;+COPS?;+COPS=3,1;+COPS?;+COPS=3,2;+COPS?",
                "+COPS: 0,0,\"Android\"\r"
                + "+COPS: 0,1,\"Android\"\r"
                + "+COPS: 0,2,\"310995\"\r"},
        {"+CREG?",   "+CREG: 2,5, \"0113\", \"6614\"\r"},
        {"+CGREG?",  "+CGREG: 2,0\r"},
        {"+CSQ",     "+CSQ: 16,99\r"},
        {"+CNMI?",   "+CNMI: 1,2,2,1,1\r"},
        {"+CLIR?",   "+CLIR: 1,3\r"},
        {"%CPVWI=2", "%CPVWI: 0\r"},
        {"+CUSD=1,\"#646#\"",  "+CUSD=0,\"You have used 23 minutes\"\r"},
        {"+CRSM=176,12258,0,0,10", "+CRSM: 144,0,981062200050259429F6\r"},
        {"+CRSM=192,12258,0,0,15", "+CRSM: 144,0,0000000A2FE204000FF55501020000\r"},

        /* EF[ADN] */
        {"+CRSM=192,28474,0,0,15", "+CRSM: 144,0,0000005a6f3a040011f5220102011e\r"},
        {"+CRSM=178,28474,1,4,30", "+CRSM: 144,0,437573746f6d65722043617265ffffff07818100398799f7ffffffffffff\r"},
        {"+CRSM=178,28474,2,4,30", "+CRSM: 144,0,566f696365204d61696cffffffffffff07918150367742f3ffffffffffff\r"},
        {"+CRSM=178,28474,3,4,30", "+CRSM: 144,0,4164676a6dffffffffffffffffffffff0b918188551512c221436587ff01\r"},
        {"+CRSM=178,28474,4,4,30", "+CRSM: 144,0,810101c1ffffffffffffffffffffffff068114455245f8ffffffffffffff\r"},
        /* EF[EXT1] */
        {"+CRSM=192,28490,0,0,15", "+CRSM: 144,0,000000416f4a040011f5550102010d\r"},
        {"+CRSM=178,28490,1,4,13", "+CRSM: 144,0,0206092143658709ffffffffff\r"}
    };
}