-
Notifications
You must be signed in to change notification settings - Fork 74
/
connectionService.js
223 lines (191 loc) · 6.78 KB
/
connectionService.js
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
import EventEmitter from "eventemitter3";
import { AsyncStorage } from "react-native";
export default function createConnectionService(StripeTerminal, options) {
class STCS {
static StorageKey = "@STCS:persistedSerialNumber";
static EventConnectionError = "connectionError";
static EventPersistedReaderNotFound = "persistedReaderNotFound";
static EventReadersDiscovered = "readersDiscovered";
static EventReaderPersisted = "readerPersisted";
static EventLog = "log";
static PolicyAuto = "auto";
static PolicyPersist = "persist";
static PolicyManual = "manual";
static PolicyPersistManual = "persist-manual";
static Policies = [
STCS.PolicyAuto,
STCS.PolicyPersist,
STCS.PolicyManual,
STCS.PolicyPersistManual
];
static DesiredReaderAny = "any";
constructor({ policy, deviceType, discoveryMode, locationId }) {
this.policy = policy;
this.deviceType = deviceType || StripeTerminal.DeviceTypeChipper2X;
this.discoveryMode =
discoveryMode || StripeTerminal.DiscoveryMethodBluetoothProximity;
this.locationId = locationId
if (STCS.Policies.indexOf(policy) === -1) {
throw new Error(
`Invalid policy passed to STCS: got "${policy}", expects "${STCS.Policies.join(
"|"
)}"`
);
}
this.emitter = new EventEmitter();
this.desiredReader = null;
StripeTerminal.addReadersDiscoveredListener(this.onReadersDiscovered);
StripeTerminal.addDidReportUnexpectedReaderDisconnectListener(
this.onUnexpectedDisconnect
);
}
onReadersDiscovered = readers => {
this.emitter.emit(STCS.EventReadersDiscovered, readers);
if (!readers.length) {
return;
}
// If we are not currently in a connecting phase, just emit the found readers without
// connecting to anything (that will wait until the connect() call).
if (!this.desiredReader) {
return;
}
let connectionPromise;
// Auto-reconnect to "desired" reader, if one exists. This could happen
// if the connection drops, for example. Or when restoring from memory.
const foundReader = readers.find(
r => r.serialNumber === this.desiredReader
);
if (foundReader) {
connectionPromise = StripeTerminal.connectReader(
foundReader.serialNumber,
this.locationId
);
// Otherwise, connect to best strength reader.
} else if (
this.policy === STCS.PolicyAuto ||
(this.policy === STCS.PolicyPersist && !this.desiredReader) ||
this.desiredReader === STCS.DesiredReaderAny
) {
connectionPromise = StripeTerminal.connectReader(
readers[0].serialNumber,
this.locationId
);
}
// If a connection is in progress, save the connected reader.
if (connectionPromise) {
connectionPromise
.then(r => {
this.desiredReader = r.serialNumber;
if (
this.policy === STCS.PolicyPersist ||
this.policy === STCS.PolicyPersistManual
) {
this.setPersistedReaderSerialNumber(this.desiredReader);
}
})
.catch(e => {
// If unable to connect, emit error & restart if in automatic mode.
this.emitter.emit(STCS.EventConnectionError, e);
if (this.policy !== STCS.PolicyManual) {
this.connect();
}
});
// If the only reader found was not an "allowed" persisted reader, restart the search.
} else {
this.emitter.emit(STCS.EventPersistedReaderNotFound, readers);
this.connect();
}
};
onUnexpectedDisconnect = () => {
// Automatically attempt to reconnect.
this.connect();
};
async connect(serialNumber, locationId) {
this.emitter.emit(
STCS.EventLog,
`Connecting to reader: "${serialNumber || "any"}"...`
);
if (serialNumber) {
this.desiredReader = serialNumber;
}
if (!this.desiredReader) {
this.desiredReader = STCS.DesiredReaderAny;
}
// Don't reconnect if we are already connected to the desired reader.
// (This state can occur when hot-reloading, for example.)
const currentReader = await this.getReader();
if (currentReader) {
return Promise.resolve();
}
await StripeTerminal.abortDiscoverReaders(); // end any pending search
await StripeTerminal.disconnectReader(); // cancel any existing non-matching reader
return StripeTerminal.discoverReaders(
this.discoveryMode,
0
);
}
async discover() {
await StripeTerminal.abortDiscoverReaders(); // end any pending search
return StripeTerminal.discoverReaders(
this.discoveryMode,
0
);
}
async disconnect() {
if (
this.policy === STCS.PolicyPersist ||
this.policy === STCS.PolicyPersistManual
) {
await this.setPersistedReaderSerialNumber(null);
this.desiredReader = null;
}
return StripeTerminal.disconnectReader();
}
async getReader() {
const reader = await StripeTerminal.getConnectedReader();
return reader && reader.serialNumber === this.desiredReader
? reader
: null;
}
addListener(event, handler) {
return this.emitter.addListener(event, handler);
}
async getPersistedReaderSerialNumber() {
const serialNumber = await AsyncStorage.getItem(STCS.StorageKey);
return serialNumber;
}
async setPersistedReaderSerialNumber(serialNumber) {
if (!serialNumber) {
await AsyncStorage.removeItem(STCS.StorageKey);
} else {
await AsyncStorage.setItem(STCS.StorageKey, serialNumber);
}
this.emitter.emit(STCS.EventReaderPersisted, serialNumber);
}
async start() {
if (this.policy === STCS.PolicyAuto) {
this.connect();
} else if (
this.policy === STCS.PolicyPersist ||
this.policy === STCS.PolicyPersistManual
) {
const serialNumber = await this.getPersistedReaderSerialNumber();
if (this.policy === STCS.PolicyPersist || serialNumber) {
this.connect(serialNumber);
}
} else {
/* fallthrough, on PolicyManual, or PolicyPersistManual with no found reader, wait for user action */
}
}
async stop() {
await StripeTerminal.disconnectReader();
StripeTerminal.removeReadersDiscoveredListener(this.onReadersDiscovered);
StripeTerminal.removeDidReportUnexpectedReaderDisconnectListener(
this.onUnexpectedDisconnect
);
}
}
const StripeTerminalConnectionService = STCS;
const service = new StripeTerminalConnectionService(options);
return service;
}