@@ -59,33 +59,53 @@ final public class ZorbDevice {
5959 - Parameter bytes: Byte representation of the Javascript bytecode to be written
6060 */
6161 private func writeBytecode( _ bytes: Data , completion: @escaping WriteRequestCallback ) {
62- // If bytes are empty, send only the integer 0
62+ // Fill the packet queue appropriately based on `bytes` to be written
6363 if bytes. count == 0 {
64- let bytes = Data ( bytes: [ UInt8 ( 0 ) ] )
64+ // If bytes are empty, send byte-array containing only the integer 0
65+
66+ // This indicates to the receiving firmware that an empty message has been sent
67+ let uZero = UInt8 ( 0 )
68+
69+ let bytes = Data ( bytes: [ uZero] )
6570 packetQueue. enqueue ( ArraySlice ( bytes) )
6671 } else {
67- // Split data in 20-byte packets and fill packet list
72+ // If bytes are not empty, split data in 20-byte packets and fill packet queue
73+
74+ // Because we want to include the number of packets as the first byte in our message,
75+ // we must add 1 to the count of bytes before calculating the packet count
6876 let packetCount = Int ( ceil ( Double ( bytes. count + 1 ) / 20 ) )
77+
78+ // We then append a byte containing number of packets to be sent to our byte-array
6979 let bytes = Data ( bytes: [ UInt8 ( packetCount) ] ) + bytes
80+
81+ // For each of the packets that we plan to send, iterate through the byte array and slice off
82+ // a 20-byte section of bytes.
7083 for i in 0 ..< packetCount {
71- let min = i * 20
72- let max = ( ( ( i + 1 ) * 20 ) < bytes. count) ? ( ( i + 1 ) * 20 ) : bytes. count
73- let packet = ArraySlice ( bytes [ min..< max] )
84+ // Min slice is always (i * 20)
85+ let sliceMin = i * 20
86+
87+ // Max slice changes conditionally depending on if we within bounds of the end of our byte-array
88+ // If we are within bounds, we slice to (i + 1 * 20) otherwise to the end of our byte-array
89+ let sliceInBounds = ( ( ( i + 1 ) * 20 ) < bytes. count)
90+ let sliceMax = sliceInBounds ? ( ( i + 1 ) * 20 ) : bytes. count
91+
92+ let packet = ArraySlice ( bytes [ sliceMin..< sliceMax] )
7493 packetQueue. enqueue ( packet)
7594 }
7695 }
7796
78- // Create recursive writing function
97+ // Create recursive function to send Bluetooth packet on successful write of previous packet
7998 func recursiveWrite( completion: @escaping WriteRequestCallback ) {
8099 DispatchQueue . main. async {
100+ // Check if there are still remaining packets in the queue
81101 if self . packetQueue. isEmpty {
82102 // Handle base case
83103 while self . packetQueue. numSets > 0 {
84104 completion ( . success( ( ) ) )
85105 self . packetQueue. numSets -= 1
86106 }
87107 } else {
88- // Get data to send
108+ // Get data to send from packet queue
89109 guard let packet = self . packetQueue. dequeue ( ) else {
90110 return
91111 }
0 commit comments