forked from jeffcraighead/CSLSwift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CSLReader.swift
1531 lines (1324 loc) · 73.8 KB
/
CSLReader.swift
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
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// CSLReader.swift
// IntelliView
//
// Created by Jeff Craighead on 11/28/17.
// Copyright © 2017 Silent Partner Technologies. All rights reserved.
//
/**
Notes:
1. For RFID 'firmware' commands, multi-byte data is byte swapped vs what is listed in the API document, per the API document. So Register address 0x0001 is sent and received as 0x0100. (see page 29 of the API document)
2. For RFID 'firmware' commands, some commands require a HST_CMD command to be sent first. The commands that require a HST_CMD activate various GEN2 commands such as Start Inventory, Read, Write, etc. (See page 48 of the API document)
*/
import Foundation
import CoreBluetooth
open class CSLReader: NSObject, RFIDReader, CBPeripheralDelegate{
var appDelegate: AppDelegate?
var currentAccessory: Any?
var bleAccessory: CBPeripheral?
var versionString: String = ""
//These flags are set when a read is in progress
var readerOn: Bool = false
var barcodeOn: Bool = false
var batteryStatus : Int32? = 0
var serialNumber: String = ""
var firmwareVersion: String = ""
var outputPower : Int32 = 300
fileprivate var minPower : Int32 = 50
fileprivate var maxPower : Int32 = 300
private let batteryMaxV = 4100.0
private let batteryMinV = 3400.0
private let rssiOffset = 120.0
var seekerMode = false
var readOneMode = false
var compactMode = false
var tagToSeek = ""
private var lastTagFilter = ""
private var connecting = false
private var rfidConnected = false //True when a connection to the reader is established (but before characteristics are discovered)
private var connectionReady = false //Set this to true after characteristics are discovered
private var displayingAlertMessage = false
private var buttonPressed = false
private var buttonPressCount = 0
private let doublePressDelay = 0.5
private var performSingleButtonPressAction = true
private var performDoubleButtonPressAction = true
private var notifyOnButtonPress = false
private var uplinkUuid = CBUUID(string: "9901")
private var downlinkUuid = CBUUID(string: "9900")
private var downlinkCharacteristic: CBCharacteristic?
private var uplinkCharacteristic: CBCharacteristic?
private var barcodeMultiPacketReadInProgress = false
private var rfidMultiPacketReadInProgress = false
private var lastPacketType: UInt8 = 0
private var readingUnderConstruction: Reading? = nil
private var rfidPacketUnderConstruction: Data? = nil
private var rfidBytesToGo = 0
private var uplinkData:[Data] = []
private var inventorySequenceNumber: UInt8 = 0
private var uplinkPacketLength: UInt8 = 0 //This is grabbed from a packet header in the decodeUplink function and used to make sure we get all the data for multi-packet data
private var rfidCommandDownlinkData:[Data] = []
private var rfidCommandInProgress: Bool = false
private var rfidCommandThreadShouldRun: Bool = false
private var rfidCommandSemaphore = DispatchSemaphore(value: 1)
private var rfidCommandInProgressTimer: Timer? = nil
private var uplinkDecoderThreadShouldRun = false
private var uplinkDataSemaphore = DispatchSemaphore(value: 1)
private var uplinkSerialDispatchQueue = DispatchQueue(label:"uplinkQueue")
private var inventoryAlgorithm: UInt32 = DYNAMIC_Q
private var linkProfile: UInt32 = PROFILE_UNKNOWN
private var willWriteTag = false
private var completion: ((Bool) -> Void)? = nil
private var executeCompletionUponCommandEnd = false
// MARK: - Init functions
public init(bleAccessory: CBPeripheral){
super.init() //Call super.init first!
appDelegate = UIApplication.shared.delegate as? AppDelegate
self.bleAccessory = bleAccessory
self.currentAccessory = bleAccessory
//self.bleAccessory?.delegate = self
connect(anyAccessory: bleAccessory)
//Kick off the uplink processing thread in the background
DispatchQueue.global(qos: .utility).async {
self.uplinkDecoderThreadShouldRun = true
while self.uplinkDecoderThreadShouldRun {
self.uplinkDataSemaphore.wait() //Acquire the semaphore before poking uplinkData
if self.uplinkData.count > 0 {
let nextPacket = self.uplinkData.removeFirst()
self.uplinkDataSemaphore.signal() //Release the semaphore
self.decodeUplinkData(data: nextPacket)
}
else {
self.uplinkDataSemaphore.signal() //Release the semaphore
usleep(10000) // Sleep for 10ms if the array is empty
}
}
}
//Kick off the rfid downlink processing thread in the background
DispatchQueue.global(qos: .utility).async {
self.rfidCommandThreadShouldRun = true
while self.rfidCommandThreadShouldRun {
while self.rfidCommandInProgress {
usleep(25000) // Sleep for 100ms if a command is in progress, then check again
}
//Once the command state is clear, issue the next command if one exists
self.rfidCommandSemaphore.wait() //Acquire the semaphore before poking uplinkData
if self.rfidCommandDownlinkData.count > 0 && self.downlinkCharacteristic != nil {
let command = self.rfidCommandDownlinkData.removeFirst()
if self.isConnected() { // Only send the command if we're actually connected to the gun
print("Sending \(command.hexEncodedString(separator: " "))")
self.rfidCommandInProgress = true
self.bleAccessory?.writeValue(command, for: self.downlinkCharacteristic!, type: CBCharacteristicWriteType.withResponse)
//Start/Reset a timer to set rfidCommandInProgress to false
if self.rfidCommandInProgressTimer != nil {
self.rfidCommandInProgressTimer?.invalidate() //Invalidate the current timer
}
DispatchQueue.main.async {
self.rfidCommandInProgressTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: { // and start a new one
(timer:Timer) -> Void in
self.rfidCommandInProgress = false // After the time interval, assume we missed the End-Command Packet and set rfidCommandInProgress to false)
})
}
}
self.rfidCommandSemaphore.signal() //Release the semaphore
}
else {
if self.displayingAlertMessage {
self.displayingAlertMessage = false
//This will send the notification to clear a buttonless UIAlertMessage that we're using when the reader is connecting/configuring
DispatchQueue.main.async{
NotificationCenter.default.post(name: Notification.Name(rawValue: readerConnectingNotification),object: nil)
}
}
self.rfidCommandSemaphore.signal() //Release the semaphore
usleep(10000) // Sleep for 10ms if the array is empty
}
}
}
}
deinit {
uplinkDecoderThreadShouldRun = false
NotificationCenter.default.removeObserver(self)
}
// MARK: - CSLReader specific methods
func sendDownlink(data: Data){
guard connectionReady && downlinkCharacteristic != nil else { return }
print("Sending \(data.hexEncodedString(separator: " "))")
bleAccessory?.writeValue(data, for: downlinkCharacteristic!, type: CBCharacteristicWriteType.withResponse)
}
//TODO - Need to create a sendRfidCommandDownlink function - this should enqueue the write into a command queue which waits for the reader to return begin and end command packets, specifically, end command packets, before sending the next command in the queue.
func sendRfidCommandDownlink(data: Data){
rfidCommandSemaphore.wait()
rfidCommandDownlinkData.append(data)
rfidCommandSemaphore.signal()
}
//Create a Data packet formatted as needed for the specified command type
func createCommandPacket(data: Data, commandType: CslCommandType) -> Data {
var header = Data(count: 8)
header[0] = PREFIX
header[1] = CslConnectionType.bluetooth.rawValue
header[2] = UInt8(data.count)
header[3] = commandType.rawValue // AKA Destination / Source (TYPE_BARCODE, TYPE_RFID, TYPE_NOTIFY, TYPE_SILAB, TYPE_BT)
header[4] = RESERVE
header[5] = CslLinkDirection.down.rawValue // Send data down to device
header[6] = 0 //CRC byte 1 - setting the CRC to 0 disables the CRC check
header[7] = 0 //CRC byte 2 - setting the CRC to 0 disables the CRC check
//Create an empty full size packet
var packet: Data = Data(count: 8 + data.count)
// Put the header in the packet
for index in 0...7 {
packet[index] = header[index]
}
//Put the data in the packet
for index in 0..<data.count {
packet[index+8] = data[index]
}
return packet
}
// Create the data for a REG_REG, reverse the bytes for address and data so that they can be specified in the 'normal' order, endianness conversion is handeled here
func createRegRequestData(write:Bool, address: UInt16, data: UInt32, dataReversed: Bool = true) -> Data{
var retVal = Data(RFID_COMMAND.toData())
retVal.append(Data([REG_REQ, write ? 0x01 : 0x00]))
retVal.append(Data(address.toData().reversed()))
if dataReversed {
retVal.append(Data(data.toData().reversed()))
}
else {
retVal.append(Data(data.toData()))
}
return retVal
}
/**
decodeRfidData attempts to assemble a complete packet and then either send a notification or print some debug output if a command response packet
OR if the packet contains RFID readings, return a new Reading object to the caller.
parameters: data - Raw data from the BLE uplink, stripped of the uplink header
returns: nil or a Reading object
*/
func decodeRfidData(data: Data) -> [Reading]?{
let startIndex = data.startIndex //Need this because the ArraySlice still has to be indexed with the old index, it does not start at 0
guard rfidMultiPacketReadInProgress || data[startIndex] == 0x80 || data[startIndex] == 0x81 else {
return nil
}
if !rfidMultiPacketReadInProgress && data[startIndex] == 0x80 { //This branch handles module power on/off responses
//Handle RFID module power on response
if data[startIndex+1] == 0x00 && data[startIndex+2] == 0x00 { //Power on success
print("RFID Power On Success")
rfidAbort() //Abort any current RFID operations
updateVersionInfo()
return nil
}
else if data[startIndex+1] == 0x00 && data[startIndex+2] == 0xFF { //Power on failed
print("RFID Power On Failed")
return nil
}
//Handle RFID module power off response
if data[startIndex+1] == 0x01 && data[startIndex+2] == 0x00 { //Power off success
print("RFID Power Off Success")
return nil
}
else if data[startIndex+1] == 0x01 && data[startIndex+2] == 0xFF { //Power off failed
print("RFID Power Off Failed")
return nil
}
//Handle RFID firmware command response
if data[startIndex+1] == 0x02 && (data[startIndex+2] == 0x00 || data[startIndex+2] == 0x01) { //RFID Command success
print("RFID Command Success")
let packet = data[(startIndex + 2)...]
let psi = packet.startIndex
let packetVer = packet[psi]
//Make sure we have enough bytes to decode the packet, otherwise we've probably got garbage from an incomplete transmission and we will return nil
guard packet.count > 6 else {
rfidCommandInProgress = false //Some commands don't have a begin & end response, and are short. We still want to allow a new packet to be sent without waiting for the timer to fire
return nil
}
let flags = packet[psi + 1]
let packetType: UInt16 = UInt16(packet[psi + 3])<<8 + UInt16(packet[psi + 2])
let status: UInt16 = UInt16(packet[psi + 13])<<8 + UInt16(packet[psi + 12])
let errorPort: UInt8 = packet[psi + 14]
switch(packetType){
case 0x0000: //Command-Begin Response Packet
fallthrough
case 0x8000:
break
case 0x0001: //Command-End Response Packet
fallthrough
case 0x8001:
break
default:
break
}
return nil
}
else if data[startIndex+1] == 0x02 && data[startIndex+2] == 0xFF { //RFID Command failed
print("RFID Command Failed")
return nil
}
}
else if !rfidMultiPacketReadInProgress && data[startIndex] == 0x81 { //This branch handles uplink data from the reader (inventory reads, command responses, etc)
if data[startIndex + 1] == 0x00 {
let packet = data[(startIndex + 2)...]
let psi = packet.startIndex
let packetVer = packet[psi]
//Make sure we have enough bytes to decode the packet, otherwise we've probably got garbage from an incomplete transmission and we will return nil
guard packet.count > 6 else {
return nil
}
let flags = packet[psi + 1]
let packetType: UInt16 = UInt16(packet[psi + 3])<<8 + UInt16(packet[psi + 2])
let packetLength: UInt16 = UInt16(packet[psi + 5])<<8 + UInt16(packet[psi + 4])
let reserve: UInt16 = UInt16(packet[psi + 7])<<8 + UInt16(packet[psi + 6])
//If the packet length is obviously too long (remember to multiply by 4) bail, we have garbage. Here I'm testing for ~240 bytes, I don't think we should ever get a packet bigger than that in real life, however the Abort packet doesn't have length bytes, so we need to allow Abort packets anyway
guard packetVer == 0x40 || packetLength <= 80 else {
return nil
}
let crcError = flags & 0x01 > 0
let paddingByteCount = (flags & 0xC0) >> 6
switch(packetVer){
case 0x03:
switch(packetType){
case 0x0005: //Inventory Response
fallthrough
case 0x8005: //Inventory Response
if uplinkPacketLength > data.count {
rfidMultiPacketReadInProgress = true
rfidBytesToGo = Int(uplinkPacketLength) - Int(data.count)
rfidPacketUnderConstruction = Data(packet)
}
else {
print("THERE SHOULDN'T BE A FULL INVENTORY RESPONSE PACKET THIS SMALL!!")
}
//This calculates the total data length for an inventory packet as described on page 52 of the API doc
//let dataLength = (Int(packetLength) - 3)*4 - Int(paddingByteCount)
//let totalDataLength = 20 + dataLength // The Inventory response packet has 20 + n bytes where n is the length of the PC+EPC+DATA1+CRC16 or PC+EPC+DATA1+DATA2+CRC16 depending on the INV_CFG tag_read setting
//Put a copy of packet into rfidPacketUnderConstruction
//rfidPacketUnderConstruction = Data(packet)
//For inventory response, there is always more than one packet.
//rfidMultiPacketReadInProgress = true
//rfidBytesToGo = Int(packetLength) - 10 //We have 10 bytes of RFID packet data in the first BLE packet
default:
break
}
case 0x04:
switch(packetType){
case 0x0005: //Inventory Response
fallthrough
case 0x8005: //Inventory Response
//Put a copy of packet into rfidPacketUnderConstruction
rfidPacketUnderConstruction = Data(packet)
//For inventory response, there is always more than one packet.
rfidMultiPacketReadInProgress = true
rfidBytesToGo = Int(packetLength) - 2 //In the compact mode the packetLength bytes are the payload length, there are 2 bytes (the PC of the first tag) in this first packet.
default:
break
}
case 0x40: //Abort or Reset response
switch(flags){
case 0x02:
print("RESET COMMAND RESPONSE RECEIVED")
break
case 0x03:
print("ABORT ABORT ABORT!")
break
default:
break
}
break
case 0x00: //Firmware info response packet (Mac address, firmware version, etc)
fallthrough
case 0x70:
if flags == 0x00{
let address = packetType
let data = UInt32(reserve) << 16 + UInt32(packetLength)
switch(address){
case 0x00:
let major: UInt8 = UInt8(data >> 24)
let minor: UInt8 = UInt8((data >> 12) & 0x7FF)
let build: UInt8 = UInt8(data & 0x7FF)
break
default:
break
}
}
break
case 0x01: //Tag Access Packet
if uplinkPacketLength > data.count {
rfidMultiPacketReadInProgress = true
rfidBytesToGo = Int(uplinkPacketLength) - Int(data.count)
rfidPacketUnderConstruction = Data(packet)
}
else {
print("TAG ACCESS PACKET")
}
break
case 0x02: //Command Packet Response or other info packets
switch(packetType){
case 0x0000: //Command Packet Begin
fallthrough
case 0x8000:
if uplinkPacketLength > data.count {
rfidMultiPacketReadInProgress = true
rfidBytesToGo = Int(uplinkPacketLength) - Int(data.count)
rfidPacketUnderConstruction = Data(packet)
}
else {
print("COMMAND BEGIN PACKET")
}
break
case 0x0001: //Command Packet End
fallthrough
case 0x8001:
if uplinkPacketLength > data.count {
rfidMultiPacketReadInProgress = true
rfidBytesToGo = Int(uplinkPacketLength) - Int(data.count)
rfidPacketUnderConstruction = Data(packet)
}
else {
rfidCommandInProgress = false
let status = packet[psi + 13] << 8 | packet[psi + 12]
let success = status == 0
print("COMMAND END PACKET")
if executeCompletionUponCommandEnd && completion != nil {
executeCompletionUponCommandEnd = false
completion!(success)
completion = nil
}
}
break
case 0x0007: //Antenna Cycle End
fallthrough
case 0x8007:
if uplinkPacketLength > data.count {
rfidMultiPacketReadInProgress = true
rfidBytesToGo = Int(uplinkPacketLength) - Int(data.count)
rfidPacketUnderConstruction = Data(packet)
}
else {
print("ANTENNA CYCLE END")
}
break
default:
break
}
break
default:
break
}
}
}
else if rfidMultiPacketReadInProgress {
//Append the current data to the rfidPacketUnderConstruction Data object, then reduce the packetsToGo count by 1
rfidPacketUnderConstruction!.append(data)
rfidBytesToGo -= data.count
//Once we've read all the packets for this message, set the multiread flag to false
if rfidBytesToGo <= 0 {
rfidMultiPacketReadInProgress = false
}
}
//If this was a single packet or we're done with a multiPacketRead, decode the packet into a Reading? Maybe need to make a CslRfidResponsePacket class
if !rfidMultiPacketReadInProgress && rfidPacketUnderConstruction != nil {
let rfidPacket = rfidPacketUnderConstruction
rfidPacketUnderConstruction = nil
//TODO - check the checksum and return nil if it doesn't match
//Now decode the Data object into a Reading
return decodeRfidMultiPacket(packet: rfidPacket!)
}
return nil
}
/**
decodeRfidPacket decodes complete (or at least what we assume to be complete) RFID data packets after a multi-packet read is completed in decodeRfidData
parameters: packet - a complete Data packet formed from a multi packet read
returns: Reading?
*/
func decodeRfidMultiPacket(packet: Data) -> [Reading]?{
let psi = packet.startIndex
let packetVer = packet[psi]
let flags = packet[psi + 1]
let packetType: UInt16 = UInt16(packet[psi + 3])<<8 + UInt16(packet[psi + 2])
let packetLength: UInt16 = UInt16(packet[psi + 5])<<8 + UInt16(packet[psi + 4])
//print("PACKET: \(packet.hexEncodedString(separator: " "))")
switch(packetVer){
case 0x01:
switch(packetType){
case 0x0006:
let accessCommand = packet[psi + 12]
let success = (flags & 0x0f) == 0
var commandName = ""
switch(accessCommand){
case 0xC2:
commandName = "Read"
break
case 0xC3:
commandName = "Write"
break
case 0xC4:
commandName = "Kill"
break
case 0xC5:
commandName = "Lock"
break
case 0x04:
commandName = "EAS"
break
default:
commandName = "Unknown Command"
}
if success {
print(commandName + " Succeeded!")
}
else {
print(commandName + " Failed with flags: \(flags) and error code: \(packet[psi + 13])!")
}
if packetLength == 3 && packet.count > 20 {
let _ = decodeRfidMultiPacket(packet: packet[20...])
}
return nil
default:
break
}
case 0x02:
switch(packetType){
case 0x0000: //Command Packet Begin
fallthrough
case 0x8000:
print("COMMAND BEGIN PACKET")
break
case 0x0001: //Command Packet End
fallthrough
case 0x8001:
rfidCommandInProgress = false
let status = packet[psi + 13] << 8 | packet[psi + 12]
let success = status == 0
print("COMMAND END PACKET")
if executeCompletionUponCommandEnd && completion != nil {
executeCompletionUponCommandEnd = false
completion!(success)
completion = nil
}
break
case 0x0007: //Antenna Cycle End
fallthrough
case 0x8007:
print("ANTENNA CYCLE END")
break
default:
break
}
break
case 0x03:
switch(packetType){
case 0x0005: // Inventory Response Packet
fallthrough
case 0x8005:
var msCounter: UInt32 = UInt32(packet[psi + 11])<<24
msCounter = msCounter + (UInt32(packet[psi + 10])<<16)
msCounter = msCounter + (UInt32(packet[psi + 9])<<8)
msCounter = msCounter + UInt32(packet[psi + 8]) //Firmware millisecond coutner tag was inventoried
let wbRssiByte: UInt8 = packet[psi + 12] //Wideband RSSI - See API doc page 51 for conversion formula
let nbRssiByte: UInt8 = packet[psi + 13] //Narrowband RSSI - See API doc page 51 for conversion formula
let phase: UInt8 = packet[psi + 14] //See API doc page 52
let channelIndex: UInt8 = packet[psi + 15]
let data1Count: UInt8 = packet[psi + 16]
let data2Count: UInt8 = packet[psi + 17]
let port: UInt16 = 0xFFFF & (UInt16(packet[psi + 19])<<8) & UInt16(packet[psi + 18])
let inventoryData: Data = Data(packet[(psi + 20)...]) //This is a new Data object, we can turn this into an array slice if we absolutely need to, to probably improve performance a tiny bit
let pc = inventoryData[0...1] //This is an ArraySlice
let pcAsInt = Int(pc[0]) << 8 + Int(pc[1])
let epcLength = (pcAsInt >> 11) * 2
let epcEndIndex = 2 + epcLength - 1
//If the epcEndIndex is <= 2 this is an invalid packet, so return nil
guard epcEndIndex > 2 && epcEndIndex < inventoryData.endIndex else {
return nil
}
let epc = inventoryData[2...epcEndIndex] //This is an ArraySlice
//TODO - extract data1 and data2
let crc16 = Data(inventoryData[inventoryData.endIndex.advanced(by: -2)...])
//TODO - validate CRC
//Calculate RSSI
let mantissa = Int(nbRssiByte & 0x07)
let exponent = Int((nbRssiByte & 0xF8) >> 3)
let rssi = (20.0 * (log(pow(2.0,Double(exponent)) * (1.0 + Double(mantissa)/8.0))/log(10.0))) - rssiOffset
let reading = Reading()
reading.type = ReadingType.rfid
reading.tagid = epc.hexEncodedString().uppercased()
reading.pc = pc.hexEncodedString().uppercased()
reading.rssi = Int(rssi)
return [reading]
default:
break
}
case 0x04:
switch(packetType){
case 0x0005: // Inventory Response Packet
fallthrough
case 0x8005:
var readings:[Reading] = []
//TODO - compact mode returns multiple EPC and RSSI values per packet, need to loop an build a reading array
let inventoryData: Data = Data(packet[(psi + 8)...]) //This is a new Data object, we can turn this into an array slice if we absolutely need to, to probably improve performance a tiny bit
var index = inventoryData.startIndex
while index + 1 < inventoryData.endIndex{
let pc = inventoryData[index...index+1] //This is an ArraySlice
let pcAsInt = Int(pc[index]) << 8 + Int(pc[index+1])
let epcLength = (pcAsInt >> 11) * 2
let epcEndIndex = index + 2 + epcLength - 1
let nbRssiIndex = index + 2 + epcLength
//If the epcEndIndex is <= 2 or the epcEndIndex is past the end of the packet this is an invalid packet, so return nil
guard (epcEndIndex > index+2 && epcEndIndex < inventoryData.endIndex) || (epcLength == 0) else {
return nil
}
let epc = epcLength > 0 ? inventoryData[index+2...epcEndIndex] : Data([])//This is an ArraySlice
let nbRssi = inventoryData[nbRssiIndex]
let mantissa = Int(nbRssi & 0x07)
let exponent = Int((nbRssi & 0xF8) >> 3)
let rssi = (20.0 * (log(pow(2.0,Double(exponent)) * (1.0 + Double(mantissa)/8.0))/log(10.0))) - rssiOffset
//print("ex:\(exponent), mt:\(mantissa), rs:\(rssi)")
let reading = Reading()
reading.type = ReadingType.rfid
reading.tagid = epc.hexEncodedString().uppercased()
reading.pc = pc.hexEncodedString().uppercased()
reading.rssi = Int(rssi)
readings.append(reading)
index = nbRssiIndex + 1
}
return readings
default:
break
}
default:
break
}
return nil
}
func decodeBarcodeData(data: Data) -> [Reading]?{
let startIndex = data.startIndex //Need this because the ArraySlice still has to be indexed with the old index, it does not start at 0
guard barcodeMultiPacketReadInProgress || data[startIndex] == 0x90 || data[startIndex] == 0x91 else {
return nil
}
//If we're not reading in a multipacket read, and the first byte of the payload is 0x90, we've got a barcode status packet
if !barcodeMultiPacketReadInProgress && data[startIndex] == 0x90{
if data[startIndex + 1] == 0x00 && data[startIndex + 2] == 0x00 {
print("Barcode On")
barcodeOn = true
}
else if data[startIndex + 1] == 0x01 && data[startIndex + 2] == 0x00 {
print("Barcode Off")
barcodeOn = false
}
else if data[startIndex + 1] == 0x02 && data[startIndex + 2] == 0x00 {
print("Barcode Trigger Success")
}
}
//This branch should execute for the first packet of a barcode read, if only one packet, this is the only branch that runs
else if !barcodeMultiPacketReadInProgress && data[startIndex] == 0x91 {
if data[startIndex + 1] == 0x00 {
if data.count > 3 && data.last != 0x0D { barcodeMultiPacketReadInProgress = true }
else { barcodeMultiPacketReadInProgress = false }
//Convert the Data object to a String
var bcString = String(data: data[(startIndex+2)...], encoding: .utf8)
if bcString != nil {
if bcString == "" || bcString!.contains("\u{06}") {
barcodeMultiPacketReadInProgress = false
}
else {
//Create a reading object
readingUnderConstruction = Reading()
readingUnderConstruction!.type = .barcode
//Trim and append the barcode string
bcString = bcString?.trim(nil)
readingUnderConstruction?.assetNumber.append(bcString!)
}
}
}
else if data[startIndex + 1] == 0x01 {
//TODO turn off barcode reader here?
}
}
//For multi-packet barcodes, the following packets only contain data, no header
else {
//Check if this is the final packet in the series, will terminate with "\r"
if data.last == 0x0D { barcodeMultiPacketReadInProgress = false }
//Convert the Data object to a String
var bcString = String(data: data, encoding: .utf8)
if bcString != nil {
bcString = bcString?.trim(nil)
readingUnderConstruction?.assetNumber.append(bcString!)
}
}
//Once we're done with this reading we can return it, otherwise return nil until we've read all the packets
if !barcodeMultiPacketReadInProgress && readingUnderConstruction != nil{
let reading = readingUnderConstruction!
readingUnderConstruction = nil
DispatchQueue.main.async {
self.abortBarcode() //Once we've read a tag, turn off the barcode engine.
}
return [reading]
}
else {
return nil
}
}
//Notification type messages include battery and trigger status
func decodeNotificationData(data: Data){
let startIndex = data.startIndex //Need this because the ArraySlice still has to be indexed with the old index, it does not start at 0
guard data.count > 0 && (data[startIndex] == 0xA0 || data[startIndex] == 0xA1) else {
return
}
if data[startIndex] == 0xA0 {
if data[startIndex + 1] == 0x00 { //This is the battery level notification
let valueIndex = startIndex + 2
let batteryActualV = data.scanValue(at: valueIndex, endianess: Data.Endianness.BigEndian) as UInt16
print("Battery level is \(batteryActualV)mV")
self.batteryStatus = min(100, Int32(100*(Double(batteryActualV)-batteryMinV)/(batteryMaxV - batteryMinV))) //calculate and set the battery status as a percentage, don't go over 100%
NotificationCenter.default.post(name: Notification.Name(rawValue: batteryStatusNotification), object: nil)
updateVersionString()
}
else if data[startIndex + 1] == 0x01 {
}
}
else if data[startIndex] == 0xA1 {
if data[startIndex + 1] == 0x01 {
print("ERROR \(data.hexEncodedString())")
}
else if data[startIndex + 1] == 0x02 {
//Trigger pushed
print("Trigger pushed")
buttonPressed = true
buttonPressCount += 1
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(doublePressDelay*Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)){
if self.buttonPressed == true{
if self.buttonPressCount == 1{
if self.performSingleButtonPressAction == true{
self.buttonPressSingle()
}
if self.notifyOnButtonPress == true{
NotificationCenter.default.post(name: Notification.Name(rawValue: readerButtonPressedNotification), object: Int(ReaderButtonStates.single.rawValue))
}
}
else if self.buttonPressCount == 2{
if self.performDoubleButtonPressAction == true {
self.buttonPressDouble()
}
if self.notifyOnButtonPress == true{
NotificationCenter.default.post(name: Notification.Name(rawValue: readerButtonPressedNotification), object: Int(ReaderButtonStates.double.rawValue))
}
}
}
self.buttonPressCount = 0
}
}
else if data[startIndex + 1] == 0x03 {
//Trigger released
print("Trigger released")
buttonPressed = false
//Turn off the barcode reader once the trigger is released
if barcodeOn { abortBarcode() }
else if readerOn { stopContinuousInventory() }
if buttonPressCount == 0 {
abort()
if self.notifyOnButtonPress == true{
NotificationCenter.default.post(name: Notification.Name(rawValue: readerButtonPressedNotification), object: Int(ReaderButtonStates.off.rawValue))
}
}
}
}
}
func decodeUplinkData(data: Data) {
//print(data.hexEncodedString(separator: " "))
// Data packet is [0xA7, 0xB3, <payload length>, <device/packet type>, 0x82, 0x9E, <crc1>, <crc2>, <payload>...]
// let payloadLength = data[2]
let payload: Data? = data.count > 8 ? data[8...] : nil
let packetType: UInt8
if barcodeMultiPacketReadInProgress || rfidMultiPacketReadInProgress { packetType = lastPacketType }
else if data.count > 8 { // to be a valid non-multiread packet, it has to have more than 8 bytes
uplinkPacketLength = data[2]
packetType = data[3]
}
else {
print("SMALL PACKET \(data.hexEncodedString(separator: " "))")
return
}
// let upDownLink = data[5]
// let crc1 = data[6]
// let crc2 = data[7]
//Set the lastPacketType to use in multi-packet reads
lastPacketType = packetType
var readings: [Reading]? = nil
//print("Received \(data.hexEncodedString(separator: " ")), rfidMultiPacketReadInProgress: \(rfidMultiPacketReadInProgress)")
switch(packetType){
case CslCommandType.rfid.rawValue:
if !rfidMultiPacketReadInProgress {
inventorySequenceNumber = UInt8(data[4])
readings = decodeRfidData(data: payload!)
}
else {
readings = decodeRfidData(data: data) //For multi-packet reads, the 2nd, 3rd, Nth packets only contain data, no header
}
break
case CslCommandType.barcode.rawValue:
if !barcodeMultiPacketReadInProgress {
readings = decodeBarcodeData(data: payload!)
}
else {
readings = decodeBarcodeData(data: data) //For multi-packet reads, the 2nd, 3rd, Nth packets only contain data, no header
}
break
case CslCommandType.bluetooth.rawValue:
break
case CslCommandType.silab.rawValue:
break
case CslCommandType.notify.rawValue:
decodeNotificationData(data: payload!)
break
default:
break
}
guard readings != nil else {
return
}
//Post a notification with the reading
if packetType != CslCommandType.silab.rawValue && packetType != CslCommandType.bluetooth.rawValue && readings != nil {
if readOneMode { //If we're in read-one mode, stop reading tags after we read one successfully
readOneMode = false
stopContinuousInventory()
}
for reading in readings! {
//print(reading.tagid)
NotificationCenter.default.post(name: Notification.Name(rawValue: newReadingNotification), object: reading)
}
}
}
//Turn the RFID module on or off. The module must be turned on before commands can be sent to it, it is off by default.
func cslRfidModulePower(on: Bool){
if on == true {
sendRfidCommandDownlink(data: createCommandPacket(data: RFID_POWER_ON.toData(), commandType: .rfid)) //RFID Power on
}
else {
sendRfidCommandDownlink(data: createCommandPacket(data: RFID_POWER_OFF.toData(), commandType: .rfid)) //RFID Power off
}
}
//Turn the barcode module on or off. The module must be turned on before commands can be sent to it, it is off by default.
func cslBarcodeModulePower(on: Bool){
if on == true {
sendDownlink(data: createCommandPacket(data: BARCODE_POWER_ON.toData(), commandType: .barcode)) //Barcode Power on
}
else {
sendDownlink(data: createCommandPacket(data: BARCODE_POWER_OFF.toData(), commandType: .barcode)) //Barcode Power off
}
}
func cslBarcodeModuleFactoryReset(){
//sendDownlink(data: createCommandPacket(data: BARCODE_POWER_ON.toData(), commandType: .barcode)) //Barcode Power on
sendDownlink(data: createCommandPacket(data: BARCODE_RAW_DATA.toData() + Data(BARCODE_CMD_SYS_MODE_ENTER), commandType: .barcode))
sendDownlink(data: createCommandPacket(data: BARCODE_RAW_DATA.toData() + Data(BARCODE_CMD_SCAN_CYCLE_TIME_3000), commandType: .barcode))
sendDownlink(data: createCommandPacket(data: BARCODE_RAW_DATA.toData() + Data(BARCODE_CMD_PERM_TRIGGER_MODE), commandType: .barcode))
sendDownlink(data: createCommandPacket(data: BARCODE_RAW_DATA.toData() + Data(BARCODE_CMD_SYS_MODE_EXIT), commandType: .barcode))
//sendDownlink(data: createCommandPacket(data: BARCODE_POWER_OFF.toData(), commandType: .barcode)) //Barcode Power off
}
//This function will be called by local functions only after they have decoded some updated battery, version, etc data from the reader
private func updateVersionString() {
self.versionString = String(format:"Manufacturer: CSL\nSerial Number: %@\nFirmware: %@\nBattery Level: %d%%",
self.serialNumber,
self.firmwareVersion,
self.batteryStatus!)
print("Connected reader is \(self.versionString)")
NotificationCenter.default.post(name: Notification.Name(rawValue: readerVersionStringUpdatedNotification), object: self.versionString)
}
private func rfidAbort(){
//ABORT, ABORT, ABORT!
print("Enqueuing ABORT, ABORT, ABORT!")
var command = RFID_COMMAND.toData()
command.append(contentsOf: [0x40, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]) //RFID module abort
sendRfidCommandDownlink(data: createCommandPacket(data: command, commandType: .rfid))
sendRfidCommandDownlink(data: createCommandPacket(data: command, commandType: .rfid))
readerOn = false
}
// Set Inventory Config
private func setInventoryConfig(tagDelay: UInt8, qtMode: Bool, crcErrRead: Bool, tagRead: UInt8, disableInventory: Bool, tagSelect: Bool, stopAfter matchRep: UInt8, inventoryAlgo: UInt32) {
//Enable compact mode by:
//Setting Tag Delay to 0
//Setting bit 26 of INV_CFG to 1
var invConfig: UInt32 = UInt32(compactMode ? 1 : 0) << 26
invConfig = invConfig | (UInt32(compactMode ? 0 : tagDelay) << 20) | (UInt32(qtMode ? 1 : 0) << 19)
invConfig = invConfig | (UInt32(crcErrRead ? 1 : 0) << 18) | (UInt32(tagRead) << 16)
invConfig = invConfig | (UInt32(disableInventory ? 1 : 0) << 15) | (UInt32(tagSelect ? 1 : 0) << 14)
invConfig = invConfig | (UInt32(matchRep) << 6) | min(inventoryAlgo,3)
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: INV_CFG, data: invConfig), commandType: .rfid))
}
// Set Inventory Algorithm Parameters
private func setInventoryAlgoParams(inventoryAlgo: UInt32, startQ: UInt32, minQ: UInt32, maxQ: UInt32, retryCount: UInt32, threshholdMult: UInt32, toggleTarget: Bool, runTillZero: Bool) {
let param0: UInt32 = inventoryAlgo == FIXED_Q ? min(startQ,15) : (min(startQ,15) | (min(maxQ,15) << 4) | (min(minQ,15) << 8) | (min(threshholdMult,63) << 12))
let param1: UInt32 = retryCount
let param2: UInt32 = (toggleTarget ? 1 : 0) | ((runTillZero ? 1 : 0) << 1)
//let param3: UInt32 = 0
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: INV_SEL, data: min(inventoryAlgo,3)), commandType: .rfid))
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: INV_ALG_PARM_0, data: param0), commandType: .rfid))
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: INV_ALG_PARM_1, data: param1), commandType: .rfid))
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: INV_ALG_PARM_2, data: param2), commandType: .rfid))
//sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: INV_ALG_PARM_3, data: param3), commandType: .rfid))
}
//Set tag filter / epc mask
private func setTagFilter(tagFilter: String = ""){
//Set TAGMSK_DESC_SEL to 0 ? This is the power on default, and shouldn't have changed.
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: TAGMSK_DESC_SEL, data: 0), commandType: .rfid))
//TODO - finish setting tag mask registers
if tagFilter != "" && tagFilter != lastTagFilter {
let paddedEpcWithPc = RFIDUtilities.epcStringToPaddedEpcWithPc(tagFilter)
//Set TAGMSK_DESC_CFG
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: TAGMSK_DESC_CFG, data: TAGMSK_ENABLE|TAGMSK_TARGET_SL), commandType: .rfid))
//Set TAGMSK_BANK to EPC
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: TAGMSK_BANK, data: MEMORY_BANK_EPC), commandType: .rfid))
//Set TAGMSK_PTR to 0x20 - that skips the PC and CRC
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: TAGMSK_PTR, data: 0x20), commandType: .rfid))
//Set TAGMSK_LEN to the number of words in the tag filter
let byteCount: UInt32 = UInt32(paddedEpcWithPc.epc.count/2)
let bitCount: UInt32 = UInt32(byteCount * 8) // two characters = 1 byte, byte count * 8 = bitCount
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: TAGMSK_LEN, data: bitCount), commandType: .rfid))
//Set the TAGMSK registers to the PC and EPC
let registerCount = ((byteCount - 1) / 4) + 1 //The CSL108 uses the R1000, which has 32-bit (4-byte) registers
let epc = paddedEpcWithPc.epc
//Set the TAGMSK registers to the specified mask. Note that the mask needs to be exact.
//000DEADBEEF1 does not match 0000000DEADBEEF1 and I don't think there is a way to do that
for regIndex in 0..<registerCount {
let startIndex = epc.index(epc.startIndex, offsetBy: Int(regIndex*8))
let endIndex = epc.index(epc.startIndex, offsetBy: min(Int(regIndex*8 + 8), Int(epc.endIndex.encodedOffset)))
var regString: String = String(epc[startIndex..<endIndex])
if regString.count < 8 {
regString = regString.rightPad("0", length: 8)
}
let regData: UInt32 = UInt32(regString, radix: 16)!
sendRfidCommandDownlink(data: createCommandPacket(data: createRegRequestData(write: true, address: TAGMSK_0_3 + UInt16(regIndex), data: regData, dataReversed: false), commandType: .rfid))
}
}
else if lastTagFilter != tagFilter {
//Set TAGMSK_DESC_CFG