summaryrefslogtreecommitdiffstats
path: root/src/ble-service.ts
blob: f2a08a337027222498161f56f4d5d8d7e5e93035 (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
import BleManager, {
  BleConnectPeripheralEvent,
  BleDisconnectPeripheralEvent,
  BleManagerDidUpdateValueForCharacteristicEvent,
  BleScanCallbackType,
  BleScanMatchMode,
  BleScanMode,
  Peripheral as PeripheralWithoutConnectInfo,
} from 'react-native-ble-manager';
import {
  EmitterSubscription,
  NativeEventEmitter,
  NativeModules,
  PermissionsAndroid,
  Platform,
} from 'react-native';

import Buffer from 'buffer';

export type Peripheral = PeripheralWithoutConnectInfo & {
  connected?: boolean;
  connecting?: boolean;
};

type Events = {
  bleManagerStartSuccess: () => void | undefined;
  bleManagerStartError: () => void | undefined;
  bleManagerStopScan: () => void | undefined;
  bleManagerStartScan: () => void | undefined;
  bleManagerDiscoverPeripheral: (peripheral: Peripheral) => void | undefined;
  bleManagerDisconnectPeripheral: (
    event: BleDisconnectPeripheralEvent,
  ) => void | undefined;
  bleManagerDidUpdateValueForCharacteristic: (
    event: BleManagerDidUpdateValueForCharacteristicEvent,
  ) => void | undefined;
  bleManagerConnectPeripheral: (
    event: BleConnectPeripheralEvent,
  ) => void | undefined;
};

export default class BleService {
  private _bleManagerModule = NativeModules.BleManager;
  private _bleManagerEmitter = new NativeEventEmitter(this._bleManagerModule);
  private _events: Events;
  private _listeners: EmitterSubscription[];
  private _peripherals: Map<Peripheral['id'], Peripheral>;

  constructor() {
    this._listeners = [];
    this._events = {};
    this._peripherals = new Map();
    BleManager.start({showAlert: false})
      .then(() => {
        this.runEvent(this._events.bleManagerStartSuccess);
        console.debug('[BleService]: BleManager started.');
      })
      .catch((err: any) => {
        this.runEvent(this._events.bleManagerStartError);
        console.debug('[BleService]: BeManager could not be started.', err);
      });
    this.handle_permissions();
  }

  setEvents(events: Events) {
    this._events = events;
    this.setupListiners(events);
  }

  handle_permissions() {
    // po requestach, jak sie zrobi .then() nastepnie gdy (resoult) cos zwroci to oznacza, że ma perma jak nie to nie ma.
    if (Platform.OS === 'android') {
      if (Platform.Version >= 31)
        PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
          PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
        ]);
      else if (Platform.Version >= 23)
        PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        );
    }
  }

  scan() {
    this.runEvent(this._events.bleManagerStartScan);
    this.clearPeripherals();
    BleManager.scan([], 3, false, {
      matchMode: BleScanMatchMode.Sticky,
      scanMode: BleScanMode.LowLatency,
      callbackType: BleScanCallbackType.AllMatches,
    })
      .then(() => {
        console.debug('[startScan] scan promise returned successfully.');
      })
      .catch((err: any) => {
        console.error('[startScan] ble scan returned in error', err);
      });
  }

  destroy() {
    this.destroyListiners();
  }

  getPeripherals() {
    return this._peripherals;
  }

  connect(p: Peripheral) {
    return BleManager.connect(p.id);
  }

  async read(peripheral: Peripheral) {
    await BleManager.requestMTU(peripheral.id, 512);
    BleManager.startNotification(
      peripheral.id,
      '6e400001-b5a3-f393-e0a9-e50e24dcca9e',
      '6e400003-b5a3-f393-e0a9-e50e24dcca9e',
    )
      .then(a => {
        // Success code
        console.log('--------');
        console.log(a);
        console.log('--------');
      })
      .catch(error => {
        // Failure code
        console.log(error);
      });
  }

  private addPeripheral(p: Peripheral) {
    this._peripherals.set(p.id, p);
  }

  private clearPeripherals() {
    this._peripherals = new Map();
  }

  private destroyListiners() {
    for (const listener of this._listeners) {
      if (listener) listener.remove();
    }
  }

  private setupListiners(events: Events) {
    this.destroyListiners();
    this._listeners = [
      this._bleManagerEmitter.addListener(
        'BleManagerDiscoverPeripheral',
        peripheral => {
          this.addPeripheral(peripheral);
          this.runEvent(events.bleManagerDiscoverPeripheral, peripheral);
        },
      ),
      this._bleManagerEmitter.addListener('BleManagerStopScan', () =>
        this.runEvent(events.bleManagerStopScan),
      ),
      this._bleManagerEmitter.addListener(
        'BleManagerDisconnectPeripheral',
        event => this.runEvent(events.bleManagerDisconnectPeripheral, event),
      ),
      this._bleManagerEmitter.addListener(
        'BleManagerDidUpdateValueForCharacteristic',
        event =>
          this.runEvent(
            events.bleManagerDidUpdateValueForCharacteristic,
            event,
          ),
      ),
      this._bleManagerEmitter.addListener(
        'BleManagerConnectPeripheral',
        event => this.runEvent(events.bleManagerConnectPeripheral, event),
      ),
    ];
  }

  private runEvent(
    event: CallableFunction | undefined,
    ...optionalParams: any[]
  ): void {
    if (event) {
      event(...optionalParams);
    }
  }
}