summaryrefslogtreecommitdiffstats
path: root/src/org/codeaurora/bluetooth/a4wp/A4wpService.java
blob: 4e6ceaac3b71f8c8679c611ff5814652b61550e9 (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
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
/*
 * Copyright (c) 2013-2014, The Linux Foundation. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *        * Redistributions of source code must retain the above copyright
 *            notice, this list of conditions and the following disclaimer.
 *        * Redistributions in binary form must reproduce the above copyright
 *            notice, this list of conditions and the following disclaimer in the
 *            documentation and/or other materials provided with the distribution.
 *        * Neither the name of The Linux Foundation nor
 *            the names of its contributors may be used to endorse or promote
 *            products derived from this software without specific prior written
 *            permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NON-INFRINGEMENT ARE DISCLAIMED.    IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.codeaurora.bluetooth.a4wp;

import java.util.UUID;

import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothGattServer;
import android.bluetooth.BluetoothGattServerCallback;
import android.bluetooth.BluetoothProfile;
import android.content.Context;
import android.app.Service;
import android.net.Credentials;
import java.io.OutputStream;
import android.util.Log;
import android.os.IBinder;
import android.content.Intent;
import android.os.Process;
import java.nio.ByteBuffer;
import android.wipower.WipowerManager;
import android.wipower.WipowerManagerCallback;
import android.wipower.WipowerManager.WipowerState;
import android.wipower.WipowerManager.WipowerAlert;
import android.wipower.WipowerManager.PowerApplyEvent;
import android.wipower.WipowerManager.PowerLevel;
import android.wipower.WipowerDynamicParam;
import com.quicinc.wbc.WbcManager;
import com.quicinc.wbc.WbcTypes;

import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.os.ParcelUuid;

/**
 * Class which executes A4WP service
 */
public class A4wpService extends Service
{
    private static final String LOGTAG = "A4wpService";
    private static OutputStream mOutputStream = null;
    private BluetoothAdapter mBluetoothAdapter = null;
    private BluetoothGattServer mBluetoothGattServer = null;
    private BluetoothDevice mDevice = null;
    private static final UUID A4WP_SERVICE_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200cfffe");
    //PRU writes
    private static final UUID A4WP_PRU_CTRL_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200c9a67");
    private static final UUID A4WP_PTU_STATIC_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200c9a68");
    //PRU reads
    private static final UUID A4WP_PRU_ALERT_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200c9a69");
    private static final UUID A4WP_PRU_STATIC_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200c9a70");
    private static final UUID A4WP_PRU_DYNAMIC_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200c9a71");

    private static final UUID A4WP_PRU_ALERT_DESC_UUID = UUID.fromString("6455e670-a146-11e2-9e96-0800200c9a69");
    //CHECK: Using the Alert UUID for now

    private static final Object mLock = new Object();
    private int mState = BluetoothProfile.STATE_DISCONNECTED;

    private final static short DEFAULT_FIELDS = 0x0000;
    private final static short DEFAULT_PROTOCOL_REV = 0x0000;
    private final static short DEFAULT_RFU = 0x0000;
    private final static byte DEFAULT_CATEGORY = 0x0003;
    private final static byte DEFAULT_CAPABILITIES = 0x0010;
    private final static byte DEFAULT_HW_VERSION = 0x0007;
    private final static byte DEFAULT_FW_VERSION = 0x0006;
    private final static byte DEFAULT_MAX_POWER_DESIRED = 0x0032;
    private final static short DEFAULT_VRECT_MIN = 0x003200;
    private final static short DEFAULT_VRECT_MAX = 0x004650;
    private final static short DEFAULT_VRECT_SET = 0x003580;
    private final static short DEFAULT_DELTA_R1 = 0x0001;
    private final static int DEFAULT_RFU_VAL = 0x0000;
    private static final int MSB_MASK = 0xFF00;
    private static final int LSB_MASK= 0x00FF;

    //Timeout value set to 5Sec which enures we advertise in limited mode
    private static final int WIPOWER_ADV_TIMEOUT = 5000;

    //PRU Write param length for validation
    private static final byte A4WP_PTU_STATIC_LENGTH = 0x11;
    private static final byte A4WP_PRU_CTRL_LENGTH = 0x05;

    //Advertisement interval values.
    private static final byte A4WP_ADV_MIN_INTERVAL = 0x20;
    private static final byte A4WP_ADV_MAX_INTERVAL = 0x20;

    private static boolean mWipowerBoot = false;
    static boolean mChargeComplete = true;
    static boolean isConnected = false;

    private AdvertiseSettings mAdvertiseSettings;
    private AdvertiseData mAdvertisementData;
    private BluetoothLeAdvertiser mAdvertiser;
    private AdvertiseCallback mAdvertiseCallback = new myAdvertiseCallback(1);
    ParcelUuid uuid1 = ParcelUuid.fromString("6455e670-a146-11e2-9e96-0800200cfffe");

    private WbcManager.WbcEventListener mWbcCallback = new WbcManager.WbcEventListener() {

        @Override
        public void onWbcEventUpdate(int what, int arg1, int arg2) {
            Log.v(LOGTAG, "onWbcEventUpdate rcvd: " + what + ", " + arg1 + ", " + arg2);
            if ((what == WbcTypes.WBC_EVENT_TYPE_CHARGING_REQUIRED_STATUS)){
                if ((arg1 == WbcTypes.WBC_BATTERY_STATUS_CHARGING_NOT_REQUIRED)){
                    // this will set charge complete bit in pru alert
                    // eventally leading to a possible disconnect from ptu
                    mChargeComplete = true;
                } else {
                    // We could be in 600mS scan state here and since charging needs to be resumed
                    // send enable power apply command to scan for short beacons */
                    mChargeComplete = false;
                    mWipowerManager.enablePowerApply(true, true, false);
                }
            }
            Log.v(LOGTAG, "onWbcEventUpdate: charge complete " +  mChargeComplete);
        }
    };

    private class PruStaticParam {
        private byte mOptvalidity;
        private byte mProtoRevision;
        private byte  mRfu;
        private byte mCategory;
        private byte mCapabilities;
        private byte mHwRev;
        private byte mFwRev;
        private byte mMaxPowerDesired;
        private short mVrectMinStatic;
        private short mVrectMaxStatic;
        private short mVrectSet;
        private short mDeltaR1;
        private int mRfuVal;

        public PruStaticParam() {
            mOptvalidity = (byte)DEFAULT_FIELDS;
            mProtoRevision = (byte)DEFAULT_PROTOCOL_REV;
            mRfu = (byte)DEFAULT_RFU;
            mCategory = (byte)DEFAULT_CATEGORY;
            mCapabilities = (byte)DEFAULT_CAPABILITIES;
            mHwRev = (byte)DEFAULT_HW_VERSION;
            mFwRev = (byte)DEFAULT_FW_VERSION;
            mMaxPowerDesired = (byte)DEFAULT_MAX_POWER_DESIRED;
            mVrectMinStatic = (short)DEFAULT_VRECT_MIN;
            mVrectMaxStatic = (short)DEFAULT_VRECT_MAX;
            mVrectSet = (short)DEFAULT_VRECT_SET;
            mDeltaR1 = (short)DEFAULT_DELTA_R1;
            mRfuVal = (int)DEFAULT_RFU_VAL;
            Log.v(LOGTAG, "PruStaticParam initialized");
        }

        public byte[] getValue() {
            byte[] res = new byte[20];
            res[0] = mOptvalidity;
            res[1] = mProtoRevision;
            res[2] = mRfu;
            res[3] = mCategory;
            res[4] = mCapabilities;
            res[5] = mHwRev;
            res[6] = mFwRev;
            res[7] = mMaxPowerDesired;
            res[8] =  (byte)(LSB_MASK & mVrectMinStatic);
            res[9] = (byte)((MSB_MASK & mVrectMinStatic) >> 8);
            res[10] =  (byte)(LSB_MASK & mVrectMaxStatic);
            res[11] = (byte)((MSB_MASK & mVrectMaxStatic) >> 8);
            res[12] =  (byte)(LSB_MASK & mVrectSet);
            res[13] = (byte)((MSB_MASK & mVrectSet) >> 8);
            res[14] =  (byte)(LSB_MASK & mDeltaR1);
            res[15] = (byte)((MSB_MASK & mDeltaR1) >> 8);
            res[16] =  (byte)(LSB_MASK & mRfuVal);
            res[17] = (byte)((MSB_MASK & mRfuVal) >> 8);
            res[18] =  (byte)((0xFF0000 & mRfuVal) >> 16);
            res[19] = (byte)((0xFF000000 & mRfuVal) >> 24);

            return res;
        }

        /*This is used to set the charging values*/
        public void setValue(byte[] value) {
            mOptvalidity = value[0];
            mProtoRevision = value[1];
            mRfu = value[2];
            mCategory = value[3] ;
            mCapabilities = value[4];
            mHwRev = value[5];
            mFwRev = value[6];
            mMaxPowerDesired = value[7];
            mVrectMinStatic = value[8];
            mVrectMinStatic |= (short)(value[9] << 8);
            mVrectMinStatic = value[10];
            mVrectMinStatic |= (short)(value[11] << 8);
            mVrectSet = value[12];
            mVrectSet |= (short)(value[13] << 8);
            mDeltaR1 = value[14];
            mDeltaR1 |= (short)(value[15] << 8);
            mRfuVal = value[16];
            mRfuVal |= (int)(value[17] << 8);
            mRfuVal |= (int)(value[18] << 16);
            mRfuVal |= (int)(value[19] << 24);

            return;
        }

    }

    private class PruAlert {
       private byte mAlert;

       public PruAlert(byte value) {
           mAlert = value;
       }

       public void setValue(byte value) {
           mAlert = value;
       }

       public byte[] getValue() {
           byte[] res = new byte[1];
           res[0] = mAlert;
           return res;
       }
    }

    private class PtuStaticParam {
        private byte mOptValidity;
        private byte mPower;
        private byte mMaxSrcImpedence;
        private byte mMaxLoadResistance;
        private short mId;
        private byte mClass;
        private byte mHwRev;
        private byte mFwRev;
        private byte mProtocolRev;
        private byte mMaxDevicesSupported;
        private int mReserved1;
        private short mReserved2;

        public PtuStaticParam(byte[] value) {
            mOptValidity = value[0];
            mPower = value[1];
            mMaxSrcImpedence = value[2];
            mMaxLoadResistance = value[3];
            mId = (short)(value[4] & 0xff);
            mId |= (short)((value[5] & 0xff) << 8);
            mClass = value[6];
            mHwRev = value[7];
            mFwRev = value[8];
            mProtocolRev = value[9];
            mMaxDevicesSupported = value[10];
            mReserved1 = (int)(value[11] & 0xff);
            mReserved1 |= (int)((value[12] & 0xff) << 8);
            mReserved1 |= (int)((value[13] & 0xff) << 16);
            mReserved1 |= (int)((value[14] & 0xff) << 16);
            mReserved2 = (short)(value[15] & 0xff);
            mReserved2 |= (short)((value[16] & 0xff) << 8);
        }

        public void print() {
            Log.v(LOGTAG, "mOptValidity" +  toHex(mOptValidity) +  "mPower" +  toHex(mPower) + "mMaxSrcImpedence" +  toHex(mMaxSrcImpedence) + "mMaxLoadResistance" +  toHex(mMaxLoadResistance));
            Log.v(LOGTAG, "mId" +  toHex(mId) + "mClass" +  toHex(mClass) + "mHwRev" +  toHex(mHwRev) +  "mFwRev" +  toHex(mFwRev));
            Log.v(LOGTAG, "mProtocolRev" +  toHex(mProtocolRev) + "mMaxDevicesSupported" +  toHex(mMaxDevicesSupported) + "mReserved1" +  toHex(mReserved1) + "mReserved2" +  toHex(mReserved2));
        }

        public double getPower() {
            double val = ((mPower&0xfc)>>2);
            val = 0.5*(val+1);
            Log.v(LOGTAG, "getPower<=" + val);
            if (val > 22) val = 22.0;
            return val;
        }

        public double getMaxSrcImpedence() {
            double val = ((mMaxSrcImpedence&0xf8)>>3);
            val = 50 + (val*10);
            Log.v(LOGTAG, "getSrcImpedence<=" + val);
            if (val > 375) val = 375.0;
            return val;
        }

        public double getMaxLoadResistance() {
            double val = ((mMaxLoadResistance&0xf8)>>3);
            val = 5 * (val+1);
            Log.v(LOGTAG, "getMaxLoadResistance<=" + val);
            if (val > 55) val = 55.0;
            return val;
        }

        public float getMaxDevicesSupported() {
            int val = mMaxDevicesSupported +1;
            Log.v(LOGTAG, "getMaxDevicesSupported<=" + val);
            if (val > 8) val = 8;
            return val;
        }

        public short getId() {
            return mId;
        }

        public int getPtuClass() {
            return (mClass > 4) ? 5 : (mClass+1);
        }

        public byte getHwRev () {
            return mHwRev;
        }

        public byte getFwRev () {
            return mFwRev;
        }

        public byte getProtocolRev () {
            return mProtocolRev;
        }
    }

    public static String toHex(int num) {
        return String.format("0x%8s", Integer.toHexString(num)).replace(' ', '0');
    }

    private class PruControl {
         public byte mEnable;
         public byte mPermission;
         public byte mTimeSet;
         public short mReserved;
         public PruControl (byte[] value) {
             mEnable = (byte)value[0];
             mPermission = (byte)value[1];
             mTimeSet = (byte)value[2];
             mReserved = (short)(value[3] & 0xFF);
             mReserved = (short)((value[4] & 0xFF) << 8);
         }

         public void print() {
             Log.v(LOGTAG, "mEnable: " +  toHex(mEnable));
             Log.v(LOGTAG, "mPermission: " +  toHex(mPermission));
             Log.v(LOGTAG, "mTimeSet: " +  toHex(mTimeSet));
             Log.v(LOGTAG, "mReserved: " +  toHex(mReserved));
         }

         public boolean getEnablePruOutput() {
              if ((mEnable&0x80) == 0x80) return true;
              else return false;
         }

         public boolean getEnableCharger() {
              if ((mEnable&0x40) == 0x40) return true;
              else return false;
         }

         /* returns 0 Maximum power
                    1 66%
                    2 33%
          */
         public PowerLevel getReducePower() {
             PowerLevel res = PowerLevel.POWER_LEVEL_MINIMUM;
             int val = ((mEnable & 0x30) >> 4 );
             if (val == 0) {
                 res = PowerLevel.POWER_LEVEL_MAXIMUM;
             } else if (val == 1 && val == 3) {
                 res = PowerLevel.POWER_LEVEL_MEDIUM;
             } else if (val == 2) {
                 res = PowerLevel.POWER_LEVEL_MINIMUM;
             }
             return res;
         }

         /* returns 0x00 permitted without reason
                    0x01 Permitted with waiting time due to limited affordable power
                    0x80 Denied with system error 3
                    0x81 Denied due to limited affordable power
                    0x82 Denied due to limited PTU Number of Devices
                    0x83 Denied due to limited PTU Class support
          */
         public boolean getPermission() {

             Log.v(LOGTAG, "getPermission" + mPermission);
             if ((mPermission&0x80) == 0x80) return false;
             else return true;
         }

         /* returns time in ms */
         public int getSetTime() {
             return (mTimeSet*10);
         }
    };

    private PruAlert mPruAlert;
    private PruStaticParam mPruStaticParam; //20 bytes
    private PtuStaticParam mPtuStaticParam; //20 bytes
    private static WipowerDynamicParam mPruDynamicParam; //20 bytes
    private WipowerManager mWipowerManager;
    private WbcManager mWbcManager;

    public A4wpService() {
        Log.v(LOGTAG, "A4wpService");
    }

    static private void cleanupService() {
        Log.v(LOGTAG, "cleanupService");
    }

    private int processPruControl(byte[] value) {
        int status = 0;

        Log.v(LOGTAG, "processPruControl>");
        PruControl control = new PruControl(value);
        control.print();

        if (mWipowerManager == null) {
            Log.e(LOGTAG, "mWipowerManager is null");
            return status;
        }

        if (control.getEnablePruOutput()) {
            Log.v(LOGTAG, "do Enable PruOutPut");
            mWipowerManager.startCharging();
            mWipowerManager.enableAlertNotification(false);
            mWipowerManager.enableDataNotification(true);
        } else {
            Log.v(LOGTAG, "do Disable PruOutPut");
            if (mChargeComplete == true) {
                mWipowerManager.enablePowerApply(true, true, true);
            }
            mWipowerManager.stopCharging();
            mWipowerManager.enableDataNotification(false);
            return status;
        }

        if (control.getEnableCharger()) {
            Log.v(LOGTAG, "do Enable Charging");
        } else {
            Log.v(LOGTAG, "do Disable Charging");
        }

        PowerLevel val = control.getReducePower();
        if (val == PowerLevel.POWER_LEVEL_MAXIMUM) {
            Log.v(LOGTAG, "put to Max Power");
        } else if (val == PowerLevel.POWER_LEVEL_MEDIUM){
            Log.v(LOGTAG, "put to Medium Power");
        } else if (val == PowerLevel.POWER_LEVEL_MINIMUM){
            Log.v(LOGTAG, "put to Min Power");
        }

        mWipowerManager.setPowerLevel(val);

        return status;
    }

    private int processPtuStaticParam(byte[] value) {
        int status = 0;
        Log.v(LOGTAG, "processPtuStaticParam>");
        mPtuStaticParam = new PtuStaticParam(value);
        mPtuStaticParam.print();

        return status;
    }

    private static final int OVER_VOLT_BIT = 0x80;
    private static final byte OVER_CURR_BIT = 0x40;
    private static final byte OVER_TEMP_BIT = 0x20;
    private static final byte SELF_PROT_BIT = 0x10;
    private static final byte CHARGE_COMPLETE_BIT = 0x08;
    private static final byte WIRED_CHARGE_DETECT = 0x04;
    private static final byte CHARGE_PORT = 0x02;

    /**
     * Wipower callbacks
     */
    private final WipowerManagerCallback mWipowerCallback = new WipowerManagerCallback() {

        @Override
        public void onWipowerReady() {
            Log.v(LOGTAG, "onWipowerReady");
            if (mChargeComplete == true) {
                mWipowerManager.enablePowerApply(true, true, true);
            } else {
                mWipowerManager.enablePowerApply(true, true, false);
            }
            mWipowerBoot = true;
        }

        @Override
        public void onWipowerStateChange(WipowerState state) {
            Log.v(LOGTAG, "onWipowerStateChange" + state);
        }

        @Override
        public void onPowerApply(PowerApplyEvent state) {
            Log.v(LOGTAG, "onPowerApply" + state);
            if (state == PowerApplyEvent.ON) {
                Log.v(LOGTAG, "StartAdvertising");
                StartAdvertising();
            } else {
                Log.v(LOGTAG, "Cancel connection as part of -" + state);
                if (mBluetoothGattServer != null) {
                    if (mDevice != null) {
                        mBluetoothGattServer.cancelConnection(mDevice);
                    }
                }
            }
        }

        @Override
        public void onWipowerAlert(WipowerAlert alert) {
            Log.v(LOGTAG, "onWipowerAlert");
            byte alertVal = 0;
            if (alert == WipowerAlert.ALERT_OVER_VOLTAGE) {
                Log.v(LOGTAG, "Over Voltage");
                alertVal |= OVER_VOLT_BIT&0xff;
            }
            else if (alert == WipowerAlert.ALERT_OVER_CURRENT) {
                Log.v(LOGTAG, "Over Current");
                alertVal |= OVER_CURR_BIT;
            }
            else if (alert == WipowerAlert.ALERT_OVER_TEMPERATURE) {
                Log.v(LOGTAG, "Over Temperature");
                alertVal |= OVER_TEMP_BIT;
            }
            else if (alert == WipowerAlert.ALERT_SELF_PROTECTION) {
                Log.v(LOGTAG, "PRU self protection ON");
                alertVal |= SELF_PROT_BIT;
            }
            else if (alert == WipowerAlert.ALERT_CHARGE_COMPLETE) {
                Log.v(LOGTAG, "Charge complete alert ");
                alertVal |= CHARGE_COMPLETE_BIT;
            }
            else if (alert == WipowerAlert.ALERT_WIRED_CHARGER_DETECTED) {
                Log.v(LOGTAG, "Wired charger detected");
                alertVal |= WIRED_CHARGE_DETECT;
            }
            else if (alert == WipowerAlert.ALERT_CHARGE_PORT) {
                Log.v(LOGTAG, "Alert charge port");
                alertVal |= CHARGE_PORT;
            }
        }


        @Override
        public void onWipowerData(WipowerDynamicParam data) {
            Log.v(LOGTAG, "onWipowerData Alert");
            byte[] value = data.getValue();

            Log.v(LOGTAG, "calling SetValue");
            mPruDynamicParam.setValue(value);
        }

    };


    /**
     * GATT callbacks
     */
    private final BluetoothGattServerCallback mGattCallbacks = new BluetoothGattServerCallback() {
        @Override
        public void onConnectionStateChange(BluetoothDevice device, int status, int newState) {
            WipowerState state = WipowerState.OFF;
            mState = newState;
            if (mState == BluetoothProfile.STATE_DISCONNECTED && isConnected == true) {
                Log.v(LOGTAG, "onConnectionStateChange:DISCONNECTED " + device + "charge complete " + mChargeComplete);
                isConnected = false;
                if (mDevice != null && mWipowerManager != null) {
                    stopAdvertising();
                    mWipowerManager.enableDataNotification(false);
                    mWipowerManager.stopCharging();
                    if (mChargeComplete != true) {
                        mWipowerManager.enablePowerApply(true, true, false);
                    }
                    mDevice = null;
                }
            } else if (mState == BluetoothProfile.STATE_CONNECTED) {
                Log.v(LOGTAG, "onConnectionStateChange:CONNECTED");
                mDevice = device;
                /* Initiate a dummy connection such that on stop advertisment
                   the advetisment instances are cleared properly */
                mBluetoothGattServer.connect(mDevice, false);
            }
        }

        @Override
        public void onCharacteristicWriteRequest(BluetoothDevice device, int requestId,
                BluetoothGattCharacteristic characteristic,
                boolean preparedWrite, boolean responseNeeded,
                int offset, byte[] value) {

                UUID id = characteristic.getUuid();
                int status =0;

                Log.v(LOGTAG, "onCharacteristicWriteRequest:" + id);
                if (id == A4WP_PRU_CTRL_UUID && value.length == A4WP_PRU_CTRL_LENGTH)
                {
                     status = processPruControl(value);
                }
                else if(id == A4WP_PTU_STATIC_UUID && value.length == A4WP_PTU_STATIC_LENGTH)
                {
                     status = processPtuStaticParam(value);
                }
                if (responseNeeded == true) {
                    mBluetoothGattServer.sendResponse(device, requestId, status,
                                       offset, value);
                }
        }

        @Override
        public void onCharacteristicReadRequest(BluetoothDevice device, int requestId,
                        int offset, BluetoothGattCharacteristic characteristic) {

                UUID id = characteristic.getUuid();
                byte[] value = {0};
                int status = 0;

                Log.v(LOGTAG, "onCharacteristicReadRequest:" + id);
                if (id == A4WP_PRU_ALERT_UUID)
                {
                    value = mPruAlert.getValue();
                }
                else if(id == A4WP_PRU_STATIC_UUID)
                {
                    value = mPruStaticParam.getValue();
                    isConnected = true;
                }
                else if (id == A4WP_PRU_DYNAMIC_UUID) {
                    if (mPruDynamicParam == null) {
                         Log.e(LOGTAG, "mPruDynamicParam is NULL");
                         return;
                    }
                    value = mPruDynamicParam.getValue();
                    if (mChargeComplete == true) {
                        value[16] = (byte)(value[16] | CHARGE_COMPLETE_BIT);
                    } else {
                        value[16] = (byte)(value[16] & (~CHARGE_COMPLETE_BIT));
                    }
                }
                if (value != null)
                {
                     Log.v(LOGTAG, "device=" + id + "requestId=" + requestId + "status=" + status + "offset=" + offset + "value=" + value[16]);
                     mBluetoothGattServer.sendResponse(device, requestId, status, offset, value);
                }
        }

        @Override
        public void onServiceAdded(final int status, BluetoothGattService service) {
                Log.i(LOGTAG, "Service added");
        }
    };

    private void closeServer() {
        if (mBluetoothGattServer != null) {
            if (mDevice != null) mBluetoothGattServer.cancelConnection(mDevice);
            mBluetoothGattServer.close();
        }
    }

    private final class myAdvertiseCallback extends AdvertiseCallback {
        private int mIndex;

        myAdvertiseCallback(int index) {
            mIndex = index;
        }

        //@Override
        public void onSuccess(AdvertiseSettings settingsInEffect) {
            Log.d(LOGTAG, "advertise success " + mIndex);
        }

        //@Override
        public void onFailure(int errorCode) {
            Log.d(LOGTAG, "advetise failure " + mIndex);
        }
    }


    private void StartAdvertising()
    {
        byte[] serviceData = new byte[] {
                (byte)0xfe, (byte)0xff, 0x28, 0x00, (byte)0xff, 0x60 };

        mAdvertiser = mBluetoothAdapter.getBluetoothLeAdvertiser();
        mAdvertisementData = new AdvertiseData.Builder()
            .setServiceData(uuid1, serviceData).build();

        mAdvertiseSettings = new AdvertiseSettings.Builder()
            .setAdvertiseMode(AdvertiseSettings.ADVERTISE_MODE_WIPOWER_LATENCY)
            .setTxPowerLevel(AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW)
            .setConnectable(true).build();

        Log.d(LOGTAG, " Calling mAdvertiser.startAdvertising");
        mAdvertiser.startAdvertising(mAdvertiseSettings, mAdvertisementData, mAdvertiseCallback);
    }

    private void stopAdvertising()
    {
       /* to be completed */
       if (mAdvertiseCallback != null &&  mAdvertiser != null) {
           mAdvertiser.stopAdvertising(mAdvertiseCallback);
       }
    }

    private boolean startServer() {
        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (bluetoothManager == null) return false;

        mBluetoothGattServer = bluetoothManager.openGattServer(this, mGattCallbacks);
        Log.d(LOGTAG,"calling start server......");
        if (mBluetoothGattServer == null) {
            Log.e(LOGTAG,"mBluetoothGattServer is NULL");
            return false;
        }

        BluetoothGattCharacteristic pruControl = new BluetoothGattCharacteristic(
                A4WP_PRU_CTRL_UUID,
                BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ,
                BluetoothGattCharacteristic.PERMISSION_WRITE |
                BluetoothGattCharacteristic.PERMISSION_READ);

        BluetoothGattCharacteristic ptuStatic = new BluetoothGattCharacteristic(
                A4WP_PTU_STATIC_UUID,
                BluetoothGattCharacteristic.PROPERTY_WRITE | BluetoothGattCharacteristic.PROPERTY_READ,
                BluetoothGattCharacteristic.PERMISSION_WRITE |
                BluetoothGattCharacteristic.PERMISSION_READ);

        BluetoothGattCharacteristic pruAlert = new BluetoothGattCharacteristic(
                A4WP_PRU_ALERT_UUID,
                BluetoothGattCharacteristic.PROPERTY_READ | BluetoothGattCharacteristic.PROPERTY_NOTIFY,
                BluetoothGattCharacteristic.PERMISSION_READ );

        BluetoothGattCharacteristic pruStatic = new BluetoothGattCharacteristic(
                A4WP_PRU_STATIC_UUID,
                BluetoothGattCharacteristic.PROPERTY_READ,
                BluetoothGattCharacteristic.PERMISSION_READ);

        BluetoothGattCharacteristic pruDynamic = new BluetoothGattCharacteristic(
                A4WP_PRU_DYNAMIC_UUID,
                BluetoothGattCharacteristic.PROPERTY_READ,
                BluetoothGattCharacteristic.PERMISSION_READ);


        BluetoothGattDescriptor pruAlertDesc = new BluetoothGattDescriptor(
                A4WP_PRU_ALERT_DESC_UUID,
                BluetoothGattCharacteristic.PERMISSION_READ |
                BluetoothGattCharacteristic.PERMISSION_WRITE);

        pruAlert.addDescriptor(pruAlertDesc);

        BluetoothGattService a4wpService = new BluetoothGattService(
                A4WP_SERVICE_UUID, BluetoothGattService.SERVICE_TYPE_PRIMARY);

        a4wpService.addCharacteristic(pruControl);
        a4wpService.addCharacteristic(ptuStatic);
        a4wpService.addCharacteristic(pruAlert);
        a4wpService.addCharacteristic(pruStatic);
        a4wpService.addCharacteristic(pruDynamic);


        mBluetoothGattServer.addService(a4wpService);

        return true;
    }

    @Override
    public void onCreate() {
        Log.v(LOGTAG, "onCreate");
        super.onCreate();

        // Ensure Bluetooth is enabled
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
            Log.d(LOGTAG, "Bluetooth is not available or enabled - exiting...");
            return;
        }

        Log.v(LOGTAG, "calling startService");
        startServer();
        //Initialize PRU Static param
        mPruStaticParam = new PruStaticParam();
        mPruDynamicParam = new WipowerDynamicParam();

        mWipowerManager = WipowerManager.getWipowerManger(this, mWipowerCallback);
        if (mWipowerManager != null)
             mWipowerManager.registerCallback(mWipowerCallback);
        mWbcManager = WbcManager.getInstance();
        if (mWbcManager != null) {
            mChargeComplete = (mWbcManager.getChargingRequired() == 0);
            Log.v(LOGTAG, "onCreate: charge complete " + mChargeComplete);
            mWbcManager.register(mWbcCallback);
        }
    }

    @Override
    public void onDestroy() {
        Log.v(LOGTAG, "onDestroy");
        if (mWipowerManager != null)
             mWipowerManager.unregisterCallback(mWipowerCallback);
        if (mWbcManager != null)
             mWbcManager.unregister(mWbcCallback);
    }

    @Override
    public IBinder onBind(Intent in) {
        Log.v(LOGTAG, "onBind");
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(LOGTAG, "onStart Command called!!");

        //mWipowerBoot is used to hold power enable command till the service is been registered completely
        if (mWipowerBoot == true) {
            if (mChargeComplete == true) {
                mWipowerManager.enablePowerApply(true, true, true);
            } else {
                mWipowerManager.enablePowerApply(true, true, false);
            }
        }
        return START_STICKY;
   }
}