summaryrefslogtreecommitdiffhomepage
path: root/main.mjs
blob: 9d0d0259fb842d521f775727157ebf76699f61e9 (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
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
class Device {
  #deviceName
  #primaryServiceUuid
  #writeCharacteristicUuid
  #notifyCharacteristicUuid

  constructor(deviceName, primaryServiceUuid, writeCharacteristicUuid, notifyCharacteristicUuid) {
    this.#deviceName = deviceName
    this.#primaryServiceUuid = primaryServiceUuid
    this.#writeCharacteristicUuid = writeCharacteristicUuid
    this.#notifyCharacteristicUuid = notifyCharacteristicUuid
  }

  static airmxPro() {
    return new Device(
      'AIRMX Pro',
      '22210000-554a-4546-5542-46534450464d',
      '22210001-554a-4546-5542-46534450464d',
      '22210002-554a-4546-5542-46534450464d'
    )
  }

  get name() {
    return this.#deviceName
  }

  get primaryServiceUuid() {
    return this.#primaryServiceUuid
  }

  get writeCharacteristicUuid() {
    return this.#writeCharacteristicUuid
  }

  get notifyCharacteristicUuid() {
    return this.#notifyCharacteristicUuid
  }
}

class Dispatcher {
  #characteristic
  #sequenceNumber = 1
  #chunkSize = 16

  constructor(characteristic) {
    this.#characteristic = characteristic
  }

  async dispatch(command) {
    const data = this.#chunk(command.payload, command)

    for (let chunk of data) {
      console.log(`Sending chunk: ${Array.from(chunk).map(b => b.toString(16).padStart(2, '0')).join(' ')}`)
      await this.#characteristic.writeValueWithResponse(chunk)
      await delay(500)
    }
  }

  #chunk(data, command) {
    const packets = this.#chunked(data, this.#chunkSize)
    const total = packets.length

    if (total === 0) {
      return [
        this.#packetHeader(
          this.#sequenceNumber++, 1, 1, // 1 of 1 packet
          command.commandId
        )
      ]
    }

    return packets.map((chunk, index) => {
      return new Uint8Array([
        ...this.#packetHeader(
          this.#sequenceNumber++, index + 1, total,
          command.commandId
        ),
        ...chunk
      ])
    })
  }

  /**
   * Splits an array into chunks of `size`.
   *
   * @param {Uint8Array} data - The array of 8-bit unsigned integers.
   * @param {number} size - The size of each chunk.
   */
  #chunked(data, size) {
    const packets = []

    for (let i = 0; i < data.length; i += size) {
      packets.push(data.slice(i, i + size))
    }

    return packets
  }

  #packetHeader(sequenceNumber, currentPacket, totalPacket, commandId) {
    return new Uint8Array([
      sequenceNumber,
      currentPacket << 4 | totalPacket,
      0x00, // Unencrypted flag
      commandId
    ])
  }
}

class BluetoothHandler {
  #device
  #dispatcher = null
  #gatt = null
  #writeCharacteristic = null
  #notifyCharacteristic = null
  #notificationHandler = null

  /**
   * @param {Device} device
   */
  constructor(device) {
    this.#device = device
  }

  async connect() {
    const device = await navigator.bluetooth.requestDevice({
      filters: [{ name: this.#device.name }],
      optionalServices: [this.#device.primaryServiceUuid]
    })

    this.#gatt = await device.gatt.connect()
    const service = await this.#gatt.getPrimaryService(this.#device.primaryServiceUuid)
    this.#writeCharacteristic = await service.getCharacteristic(this.#device.writeCharacteristicUuid)
    this.#notifyCharacteristic = await service.getCharacteristic(this.#device.notifyCharacteristicUuid)
    this.#dispatcher = new Dispatcher(this.#writeCharacteristic)

    await this.#notifyCharacteristic.startNotifications()
    this.#notifyCharacteristic.addEventListener('characteristicvaluechanged', this.#handleNotification.bind(this))
  }

  async disconnect() {
    if (this.#notifyCharacteristic) {
      await this.#notifyCharacteristic.stopNotifications()
      this.#notifyCharacteristic.removeEventListener('characteristicvaluechanged', this.#handleNotification.bind(this))
      this.#notifyCharacteristic = null
    }

    this.#dispatcher = null
    this.#writeCharacteristic = null

    if (this.#gatt) {
      this.#gatt.disconnect()
      this.#gatt = null
    }
  }

  /**
   * @param {Command} command - The command to dispatch.
   */
  async dispatch(command) {
    if (! this.#dispatcher) {
      return
    }
    await this.#dispatcher.dispatch(command)
    return this
  }

  onNotification(handler) {
    this.#notificationHandler = handler
    return this
  }

  #handleNotification(event) {
    if (this.#notificationHandler) {
      this.#notificationHandler(event)
    }
  }
}

class Command {
  get commandId() {
    throw new Error('The command ID does not exist.')
  }

  get payload() {
    throw new Error('The payload does not exist.')
  }
}

class HandshakeCommand extends Command {
  get commandId() {
    return 0x0b
  }

  get payload() {
    return new Uint8Array([
      0x08, // The storage size of the token
      0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Token: 0
      0x05, // The length of the version
      0x31, 0x2e, 0x30, 0x2e, 0x30 // Version: 1.0.0
    ])
  }
}

class ConfigureWifiCommand extends Command {
  #ssid
  #password

  constructor(ssid, password) {
    super()
    this.#ssid = ssid
    this.#password = password
  }

  get commandId() {
    return 0x15
  }

  get payload() {
    const encoder = new TextEncoder()
    const ssid = encoder.encode(this.#ssid)
    const password = encoder.encode(this.#password)

    return new Uint8Array([
      ssid.length, ...ssid,
      password.length, ...password
    ])
  }
}

class RequestIdentityCommand extends Command {
  get commandId() {
    return 0x16
  }

  get payload() {
    return new Uint8Array([
      //
    ])
  }
}

async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms))
}

class IncomingMessageHandler {
  #encoder
  #bag = []
  #messageHandler = null

  constructor() {
    this.#encoder = new TextEncoder()
  }

  handle(packet) {
    const message = IncomingMessage.parse(this.#encoder.encode(packet))
    this.#addToBag(message)
  }

  onMessage(handler) {
    this.#messageHandler = handler
    return this
  }

  /**
   * @param {IncomingMessage} message
   */
  #addToBag(message) {
    this.#bag.push(message)

    if (message.currentPacket === message.totalPacket) {
      this.#processBag()
    }
  }

  #processBag() {
    const bag = [...this.#bag]
    const lastMessage = bag.at(-1)

    if (bag.length !== lastMessage.totalPacket) {
      throw new Error('Incomplete message received.')
    }

    const data = []

    for (const [index, message] of bag.entries()) {
      if (message.currentPacket !== index + 1) {
        throw new Error(`Message packet ${index + 1} is missing.`)
      }

      data.push(...message.payload)
    }

    const completeMessage = new CompleteMessage(
      lastMessage.commandId, new Uint8Array(data)
    )

    this.#notify(completeMessage)
    this.#clearBag()
  }

  #clearBag() {
    this.#bag = []
  }

  /**
   * @param {CompleteMessage} message
   */
  #notify(message) {
    if (this.#messageHandler) {
      this.#messageHandler(message)
    }
  }
}

class IncomingMessage {
  /**
   * @param {number} sequenceNumber - The sequence number of the packet.
   * @param {number} currentPacket - The current packet number.
   * @param {number} totalPacket - The total number of packets.
   * @param {boolean} encrypted - Determines if the packet is encrypted.
   * @param {number} commandId - The command ID.
   * @param {Uint8Array} payload - The message payload.
   */
  constructor(sequenceNumber, currentPacket, totalPacket, encrypted, commandId, payload) {
    this.sequenceNumber = sequenceNumber
    this.currentPacket = currentPacket
    this.totalPacket = totalPacket
    this.encrypted = encrypted
    this.commandId = commandId
    this.payload = payload
  }

  /**
   * @param {Uint8Array} packet - The raw packet data.
   * @returns {IncomingMessage}
   */
  static parse(packet) {
    if (packet.length < 4) {
      throw new Error('Invalid packet length.')
    }

    const sequenceNumber = packet[0]
    const currentPacket = packet[1] >> 4
    const totalPacket = packet[1] & 0x0f
    const encrypted = packet[2]
    const commandId = packet[3]

    return new IncomingMessage(
      sequenceNumber, currentPacket, totalPacket,
      !! encrypted, commandId, packet.slice(4)
    )
  }
}

class CompleteMessage {
  /**
   * @param {number} commandId - The command ID of the message.
   * @param {Uint8Array} payload - The message payload.
   */
  constructor(commandId, payload) {
    this.commandId = commandId
    this.payload = payload
  }
}

class Countdown {
  #clock = null
  #stopHandler = null
  #completeHandler = null

  /**
   * @param {HTMLElement|null} el - The HTML element to display the countdown.
   * @param {number} seconds - The number of seconds for the countdown.
   */
  constructor(el, seconds) {
    this.el = el
    this.seconds = seconds

    if (this.el === null) {
      throw new Error('The HTML element could not be found to mount the countdown.')
    }
  }

  start() {
    this.stop()

    let remaining = this.seconds
    this.#clock = setInterval(() => {
      this.el.textContent = `${--remaining}s`
      if (remaining === 0) {
        this.stop()
        this.notifyComplete()
      }
    }, 1000)
  }

  stop() {
    if (! this.#clock) {
      return
    }

    clearInterval(this.#clock)
    this.#clock = null

    if (this.#stopHandler) {
      this.#stopHandler()
    }
  }

  onStop(callback) {
    this.#stopHandler = callback
  }

  onComplete(callback) {
    this.#completeHandler = callback
  }

  notifyComplete() {
    if (this.#completeHandler) {
      this.#completeHandler()
    }
  }
}

class Form {
  #activeClassName = 'form--active'

  constructor(id) {
    this.form = document.getElementById(id)
    if (this.form === null) {
      throw new Error(`Form with id ${id} does not exist.`)
    }
  }

  display() {
    this.form.classList.add(this.#activeClassName)

    if (typeof this.onDisplay === 'function') {
      this.onDisplay()
    }
  }

  hide() {
    this.form.classList.remove(this.#activeClassName)

    if (typeof this.onHide === 'function') {
      this.onHide()
    }
  }
}

class ProgressibleForm extends Form {
  #nextForm = null

  nextTo(form) {
    this.#nextForm = form
    return this
  }

  transitToNextForm() {
    if (this.#nextForm === null) {
      return
    }

    this.hide()
    this.#nextForm.display()
  }
}

class WelcomeForm extends ProgressibleForm {
  constructor(id) {
    super(id)
    this.form.addEventListener('submit', this.handleSubmit.bind(this))
  }

  handleSubmit(event) {
    event.preventDefault()
    this.transitToNextForm()
  }
}

class WifiCredentialsForm extends ProgressibleForm {
  #submitCallback = null

  constructor(id) {
    super(id)
    this.form.addEventListener('submit', this.handleSubmit.bind(this))
  }

  handleSubmit(event) {
    event.preventDefault()
    const { elements } = event.target
    try {
      const [ssid, password] = this.validate(elements.ssid.value, elements.password.value)
      if (this.#submitCallback) {
        this.#submitCallback({ ssid, password })
      }
      this.transitToNextForm()
    } catch (error) {
      this.alert(error.message)
    }
  }

  validate(ssid, password) {
    if (ssid === '' ) {
      throw new Error('SSID cannot be empty.')
    }

    if (ssid.length > 32) {
      throw new Error('SSID cannot be longer than 32 characters.')
    }

    if (password === '' ) {
      throw new Error('Password cannot be empty.')
    }

    if (password.length < 8 || password.length > 63) {
      throw new Error('Password must be between 8 and 63 characters long.')
    }

    return [ssid, password]
  }

  alert(message) {
    this.form.querySelector('.help-text')?.remove()

    const element = document.createElement('div')
    element.classList.add('help-text', 'help-text--danger')
    element.textContent = message

    this.form.querySelector('.form__footer').before(element)
  }

  onSubmit(callback) {
    this.#submitCallback = callback
    return this
  }
}

class PairingActivationForm extends ProgressibleForm {
  constructor(id) {
    super(id)
    this.form.addEventListener('submit', this.handleSubmit.bind(this))
  }

  handleSubmit(event) {
    event.preventDefault()
    this.transitToNextForm()
  }
}

class CommunicationForm extends Form {
  #handler
  #messages = null

  /** @type {Countdown} */
  #countdown

  /** @type {HTMLElement|null} */
  #description

  /** @type {string} */
  #descriptionText

  /** @type {Progress} */
  #progress

  #handshakeCommand
  #wifiCredentialsCommand
  #identityCommand

  #successForm = null
  #failureForm = null

  #retryMessage = null
  #retryMessageClassName = 'retry-message'
  #retryMessageShownClassName = 'retry-message--shown'

  #retryLink = null
  #retryLinkClassName = `retry-link`

  /**
   * @param {string} id - The ID of the form.
   * @param {BluetoothHandler} handler - The Bluetooth handler to manage the connection.
   */
  constructor(id, handler) {
    super(id)
    this.#handler = handler
    this.#handler.onNotification((event) => {
      this.#messages.handle(event.target.value)
    })
    this.#messages = new IncomingMessageHandler()
    this.#messages.onMessage(this.handleMessage.bind(this))
    this.#setupCounter()
    this.#setupProgress()
    this.#handshakeCommand = new HandshakeCommand()
    this.#wifiCredentialsCommand = new ConfigureWifiCommand('', '')
    this.#identityCommand = new RequestIdentityCommand()
    this.#retryMessage = this.form.querySelector(`.${this.#retryMessageClassName}`)
    if (this.#retryMessage) {
      this.#retryLink = this.form.querySelector(`.${this.#retryLinkClassName}`)
      this.#retryLink.addEventListener('click', () => {
        this.hideRetryOption()
        this.startPairing()
      })
    }
  }

  onDisplay() {
    this.startPairing()
  }

  #setupCounter() {
    this.#description = this.form.querySelector('.form__description')
    this.#descriptionText = this.#description ? this.#description.textContent : ''
    this.#countdown = new Countdown(this.#description, 10)
    this.#countdown.onComplete(() => {
      this.#progress.clear()
      this.disconnectIfNeeded()
      this.transitToFailureResultForm()
    })
    this.#countdown.onStop(() => {
      this.#description.textContent = this.#descriptionText
    })
  }

  #setupProgress() {
    const el = this.form.querySelector('[data-slot="progress"]')
    this.#progress = new Progress(el, [
      { id: 'handshake', name: 'Say a hello to the machine' },
      { id: 'wifi', name: 'Send Wi-Fi credentials' },
      { id: 'identity', name: 'Receive the device\'s identity' }
    ])
  }

  async startPairing() {
    try {
      await this.connect()
    } catch {
      this.showRetryOption()
    }
  }

  async connect() {
    await this.#handler.connect()

    this.#countdown.start()
    this.#progress.render()

    this.#progress.markAsCurrent('handshake')
    await this.#handler.dispatch(this.#handshakeCommand)
  }

  async disconnectIfNeeded() {
    await this.#handler.disconnect()
  }

  /**
   * @param {CompleteMessage} message
   */
  handleMessage(message) {
    switch (message.commandId) {
      case this.#handshakeCommand.commandId:
        this.handleHandshakeMessage(message)
        break
      case this.#wifiCredentialsCommand.commandId:
        this.handleWifiCredentialsMessage(message)
        break
      case this.#identityCommand.commandId:
        this.handleIdentityMessage(message)
        break
      default:
        console.warn(`Unknown command ID: ${message.commandId}`)
        break
    }
  }

  /**
   * @param {CompleteMessage} message
   */
  handleHandshakeMessage(message) {
    this.#progress.markAsComplete('handshake')
    this.#progress.markAsCurrent('wifi')
    this.#handler.dispatch(this.#wifiCredentialsCommand)
  }

  /**
   * @param {CompleteMessage} message
   */
  handleWifiCredentialsMessage(message) {
    this.#progress.markAsComplete('wifi')
    this.#progress.markAsCurrent('identity')
    this.#handler.dispatch(this.#identityCommand)
  }

  /**
   * @param {CompleteMessage} message
   */
  handleIdentityMessage(message) {
    this.#countdown.stop()
    this.#progress.markAsComplete('identity')
    this.#progress.clear()
    this.disconnectIfNeeded()
    this.transitToSuccessResultForm()
  }

  showRetryOption() {
    if (this.#retryMessage === null) {
      return
    }

    this.#retryMessage.classList.add(this.#retryMessageShownClassName)
  }

  hideRetryOption() {
    if (this.#retryMessage === null) {
      return
    }

    this.#retryMessage.classList.remove(this.#retryMessageShownClassName)
  }

  succeedTo(form) {
    this.#successForm = form
    return this
  }

  failTo(form) {
    this.#failureForm = form
    return this
  }

  wifiCredentialsUsing(credentials) {
    this.#wifiCredentialsCommand = new ConfigureWifiCommand(credentials.ssid, credentials.password)
    return this
  }

  transitToSuccessResultForm() {
    this.hide()
    this.#successForm?.display()
  }

  transitToFailureResultForm() {
    this.hide()
    this.#failureForm?.display()
  }
}

class FailureForm extends ProgressibleForm {
  constructor(id) {
    super(id)
    this.form.addEventListener('submit', this.handleSubmit.bind(this))
  }

  handleSubmit(event) {
    event.preventDefault()
    this.transitToNextForm()
  }
}

class Progress {
  #el
  #steps

  /**
   * @param {HTMLElement|null} el - The HTML element to display the progress.
   * @param {{ id: string, name: string }[]} steps - The progress steps.
   */
  constructor(el, steps) {
    this.#el = el
    this.#steps = steps
    if (this.#el === null) {
      throw new Error('The HTML element could not be found to mount the progress.')
    }
  }

  render() {
    if (! this.#el.classList.contains('progress')) {
      this.#el.classList.add('progress')
    }

    for (const step of this.#steps) {
      const el = document.createElement('li')
      el.innerText = step.name
      el.classList.add('progress__item')
      el.dataset.progress = step.id
      this.#el.appendChild(el)
    }
  }

  clear() {
    this.#el.innerHTML = ''
  }

  /**
   * @param {string} step - The step ID.
   */
  markAsCurrent(step) {
    this.markAsDefault(step)

    const el = this.#stepElement(step)
    el.dataset.current = ''
  }

  /**
   * @param {string} step - The step ID.
   */
  markAsComplete(step) {
    this.markAsDefault(step)

    const el = this.#stepElement(step)
    el.dataset.complete = ''
  }

  /**
   * @param {string} step - The step ID.
   */
  markAsDefault(step) {
    const el = this.#stepElement(step)
    if ('current' in el.dataset) {
      delete el.dataset.current
    }
    if ('complete' in el.dataset) {
      delete el.dataset.complete
    }
  }

  /**
   * @param {string} id - The step ID.
   */
  #stepElement(id) {
    const el = this.#el.querySelector(`[data-progress="${id}"]`)
    if (! el) {
      throw new Error(`Progress step "${step}" does not exist.`)
    }
    return el
  }
}

class Application {
  static supportBluetoothApi() {
    return 'bluetooth' in navigator
  }

  static run() {
    if (! this.supportBluetoothApi()) {
      const unsupportedForm = new Form('form-unsupported')
      unsupportedForm.display()
      return
    }

    const handler = new BluetoothHandler(Device.airmxPro())

    const successForm = new Form('form-result-success')
    const failureForm = new FailureForm('form-result-failure')
    const communicationForm = new CommunicationForm('form-communication', handler)
      .succeedTo(successForm)
      .failTo(failureForm)
    const pairingActivationForm = new PairingActivationForm('form-pairing-activation')
      .nextTo(communicationForm)
    const wifiCredentialsForm = new WifiCredentialsForm('form-wifi-credentials')
      .nextTo(pairingActivationForm)
      .onSubmit((credentials) => {
        communicationForm.wifiCredentialsUsing(credentials)
      })
    const welcomeForm = new WelcomeForm('form-welcome')
      .nextTo(wifiCredentialsForm)

    // If the pairing process fails, we will redirect the user to the Wi-Fi
    // credentials form so that they can retry with different credentials.
    failureForm.nextTo(wifiCredentialsForm)

    // Now that everything is set up, it's time to show the user
    // the welcome screen.
    welcomeForm.display()
  }
}

Application.run()