-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTasksCollectionViewController.swift
More file actions
1216 lines (1096 loc) · 53.9 KB
/
Copy pathTasksCollectionViewController.swift
File metadata and controls
1216 lines (1096 loc) · 53.9 KB
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
/*
WunderLINQ Client Application
Copyright (C) 2020 Keith Conger, Black Box Embedded, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import CoreLocation
import UIKit
import MapKit
import CoreLocation
import AVFoundation
import SQLite3
import Photos
import os.log
class TasksCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, AVCaptureVideoDataOutputSampleBufferDelegate, AVCaptureFileOutputRecordingDelegate {
private let notificationCenter = NotificationCenter.default
var faultsBtn: UIButton!
var faultsButton: UIBarButtonItem!
let flowLayout = ZoomAndSnapFlowLayout()
var tasks:[Tasks] = [Tasks]()
var mapping = [Int]()
var device: AVCaptureDevice?
var captureSession: AVCaptureSession?
var cameraImage: UIImage?
private let audioSession = AVAudioSession.sharedInstance()
var videoCaptureSession = AVCaptureSession()
let movieOutput = AVCaptureMovieFileOutput()
var activeInput: AVCaptureDeviceInput!
var outputURL: URL!
var isRecording = false
var db: OpaquePointer?
var waypoints = [Waypoint]()
var itemRow = 0
var seconds = 10
var timer = Timer()
var isTimerRunning = false
let scenic = ScenicAPI()
let motorcycleData = MotorcycleData.shared
let wlqData = WLQ.shared
let faults = Faults.shared
let emptyTask = 16
private func loadRows() {
let taskRow1 = UserDefaults.standard.integer(forKey: "task_one_preference")
if (taskRow1 != emptyTask){
mapping.append(taskRow1)
}
let taskRow2 = UserDefaults.standard.integer(forKey: "task_two_preference")
if (taskRow2 != emptyTask){
mapping.append(taskRow2)
}
let taskRow3 = UserDefaults.standard.integer(forKey: "task_three_preference")
if (taskRow3 != emptyTask){
mapping.append(taskRow3)
}
let taskRow4 = UserDefaults.standard.integer(forKey: "task_four_preference")
if (taskRow4 != emptyTask){
mapping.append(taskRow4)
}
let taskRow5 = UserDefaults.standard.integer(forKey: "task_five_preference")
if (taskRow5 != emptyTask){
mapping.append(taskRow5)
}
let taskRow6 = UserDefaults.standard.integer(forKey: "task_six_preference")
if (taskRow6 != emptyTask){
mapping.append(taskRow6)
}
let taskRow7 = UserDefaults.standard.integer(forKey: "task_seven_preference")
if (taskRow7 != emptyTask){
mapping.append(taskRow7)
}
let taskRow8 = UserDefaults.standard.integer(forKey: "task_eight_preference")
if (taskRow8 != emptyTask){
mapping.append(taskRow8)
}
let taskRow9 = UserDefaults.standard.integer(forKey: "task_nine_preference")
if (taskRow9 != emptyTask){
mapping.append(taskRow9)
}
let taskRow10 = UserDefaults.standard.integer(forKey: "task_ten_preference")
if (taskRow10 != emptyTask){
mapping.append(taskRow10)
}
let taskRow11 = UserDefaults.standard.integer(forKey: "task_eleven_preference")
if (taskRow11 != emptyTask){
mapping.append(taskRow11)
}
let taskRow12 = UserDefaults.standard.integer(forKey: "task_twelve_preference")
if (taskRow12 != emptyTask){
mapping.append(taskRow12)
}
let taskRow13 = UserDefaults.standard.integer(forKey: "task_thirteen_preference")
if (taskRow13 != emptyTask){
mapping.append(taskRow13)
}
let taskRow14 = UserDefaults.standard.integer(forKey: "task_fourteen_preference")
if (taskRow14 != emptyTask){
mapping.append(taskRow14)
}
let taskRow15 = UserDefaults.standard.integer(forKey: "task_fifteen_preference")
if (taskRow15 != emptyTask){
mapping.append(taskRow15)
}
}
private func loadTasks() {
// Navigate Task
guard let task0 = Tasks(label: NSLocalizedString("task_title_navigation", comment: ""), icon: UIImage(named: "Map")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Navigate Task")
}
// Go Home Task
guard let task1 = Tasks(label: NSLocalizedString("task_title_gohome", comment: ""), icon: UIImage(named: "Home")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Go Home Task")
}
// Call Home Task
guard let task2 = Tasks(label: NSLocalizedString("task_title_favnumber", comment: ""), icon: UIImage(named: "Phone")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Call Home Task")
}
// Call Contact Task
guard let task3 = Tasks(label: NSLocalizedString("task_title_callcontact", comment: ""), icon: UIImage(named: "Contacts")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Call Contact Task")
}
// Take Photo Task
guard let task4 = Tasks(label: NSLocalizedString("task_title_photo", comment: ""), icon: UIImage(named: "Camera")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Take Photo Task")
}
// Take Selfie Task
guard let task5 = Tasks(label: NSLocalizedString("task_title_selfie", comment: ""), icon: UIImage(named: "Portrait")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Take Photo Task")
}
// Video Recording Task
var vidRecLabel = NSLocalizedString("task_title_start_record", comment: "")
if isRecording{
vidRecLabel = NSLocalizedString("task_title_stop_record", comment: "")
}
guard let task6 = Tasks(label: vidRecLabel, icon: UIImage(named: "VideoCamera")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Video Recording Task")
}
// Trip Log Task
var tripLogLabel = NSLocalizedString("task_title_start_trip", comment: "")
let loggingStatus = UserDefaults.standard.string(forKey: "loggingStatus")
if loggingStatus != nil {
//Stop Logging
tripLogLabel = NSLocalizedString("task_title_stop_trip", comment: "")
}
guard let task7 = Tasks(label: tripLogLabel, icon: UIImage(named: "Road")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Trip Log Task")
}
// Save Waypoint Task
guard let task8 = Tasks(label: NSLocalizedString("task_title_waypoint", comment: ""), icon: UIImage(named: "MapMarker")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Save Waypoint Task")
}
// Navigate to Waypoint Task
guard let task9 = Tasks(label: NSLocalizedString("task_title_waypoint_nav", comment: ""), icon: UIImage(named: "Route")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Navigate to Waypoint Task")
}
// Settings Task
guard let task10 = Tasks(label: NSLocalizedString("task_title_settings", comment: ""), icon: UIImage(named: "Cog")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// GoPro Remote Task
guard let task11 = Tasks(label: NSLocalizedString("task_title_gopro", comment: ""), icon: UIImage(named: "Action-Camera")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// WeatherMap Task
guard let task12 = Tasks(label: NSLocalizedString("task_title_weathermap", comment: ""), icon: UIImage(named: "CloudSun")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// Road Book Task
guard let task13 = Tasks(label: NSLocalizedString("task_title_roadbook", comment: ""), icon: UIImage(named: "RoadBook")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// System Volume Task
guard let task14 = Tasks(label: NSLocalizedString("task_title_systemvolume", comment: ""), icon: UIImage(named: "Speaker")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// Insta360 Remote Task
guard let task15 = Tasks(label: NSLocalizedString("task_title_insta360", comment: ""), icon: UIImage(named: "Spherical-Camera")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
//Empty
guard let task16 = Tasks(label: NSLocalizedString("task_title_empty", comment: ""), icon: UIImage(named: "Cog")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// Front Camera Recording Task
var frontRecLabel = NSLocalizedString("task_title_front_start_record", comment: "")
if isRecording{
frontRecLabel = NSLocalizedString("task_title_stop_record", comment: "")
}
guard let task17 = Tasks(label: frontRecLabel, icon: UIImage(named: "VideoCamera")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Video Recording Task")
}
// Fuel Task
guard let task18 = Tasks(label: NSLocalizedString("task_title_fuel", comment: ""), icon: UIImage(named: "Gas-pump")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
// Active Faults
guard let task19 = Tasks(label: NSLocalizedString("task_title_faults", comment: ""), icon: UIImage(named: "Alert")?.withRenderingMode(.alwaysTemplate)) else {
fatalError("Unable to instantiate Settings Task")
}
self.tasks = [task0, task1, task2, task3, task4, task5, task6, task7, task8, task9, task10, task11, task12, task13, task14, task15, task16, task17, task18, task19]
}
private func execute_task(taskID:Int) {
switch taskID {
case 0:
//Navigation
NavAppHelper().open()
break
case 1:
//Go Home
if let homeAddress = UserDefaults.standard.string(forKey: "gohome_address_preference"){
if homeAddress != "" {
let geocoder = CLGeocoder()
geocoder.geocodeAddressString(homeAddress,
completionHandler: { (placemarks, error) in
if error == nil {
let placemark = placemarks?.first
let lat = placemark?.location?.coordinate.latitude
let lon = placemark?.location?.coordinate.longitude
let destLatitude: CLLocationDegrees = lat!
let destLongitude: CLLocationDegrees = lon!
if let currentLocation = self.motorcycleData.getLocation() {
if (!NavAppHelper.navigateTo(destLatitude: destLatitude, destLongitude: destLongitude, destLabel: NSLocalizedString("home", comment: ""), currentLatitude: currentLocation.coordinate.latitude, currentLongitude: currentLocation.coordinate.longitude)){
self.showToast(message: NSLocalizedString("nav_app_feature_not_supported", comment: ""))
}
}
}
else {
// An error occurred during geocoding.
self.showToast(message: NSLocalizedString("geocode_error", comment: ""))
}
})
} else {
self.showToast(message: NSLocalizedString("toast_address_not_set", comment: ""))
}
} else {
self.showToast(message: NSLocalizedString("toast_address_not_set", comment: ""))
}
break
case 2:
//Favorite Number
if let phoneNumber = UserDefaults.standard.string(forKey: "callhome_number_preference"){
if phoneNumber != "" {
if let phoneCallURL = URL(string: "telprompt:\(phoneNumber)") {
if (UIApplication.shared.canOpenURL(phoneCallURL)) {
UIApplication.shared.open(phoneCallURL, options: convertToUIApplicationOpenExternalURLOptionsKeyDictionary([:]), completionHandler: nil)
}
}
} else {
self.showToast(message: NSLocalizedString("toast_phone_not_set", comment: ""))
}
} else {
self.showToast(message: NSLocalizedString("toast_phone_not_set", comment: ""))
}
break
case 3:
//Call Contact
performSegue(withIdentifier: "taskGridToContacts", sender: self)
break
case 4:
//Take Rear Photo
self.showToast(message: NSLocalizedString("toast_photo_taken", comment: ""))
setupCamera(position: .back)
setupTimer()
break
case 5:
//Take Front Photo (Selfie)
self.showToast(message: NSLocalizedString("toast_photo_taken", comment: ""))
setupCamera(position: .front)
setupTimer()
break
case 6:
//Rear Video Recording
if movieOutput.isRecording {
stopRecording()
isRecording = false
} else {
videoCaptureSession = AVCaptureSession()
if setupSession(position: .back) {
startSession(orientation: currentVideoOrientation())
isRecording = true
}
}
break
case 7:
//Trip Log
let loggingStatus = UserDefaults.standard.string(forKey: "loggingStatus")
if loggingStatus != nil {
// Check for auto-trip logging
if UserDefaults.standard.bool(forKey: "autotrip_enable_preference") {
self.showToast(message: NSLocalizedString("toast_auto_trip_logging", comment: ""))
} else {
//Stop Logging
UserDefaults.standard.set(nil, forKey: "loggingStatus")
}
} else {
//Start Logging
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd-HH-mm-ss"
let dateString = dateFormatter.string(from: Date())
UserDefaults.standard.set(dateString, forKey: "loggingStatus")
}
break
case 8:
//Save Waypoint
saveWaypoint()
break
case 9:
//Navigate to Waypoint
performSegue(withIdentifier: "taskGridToWaypoints", sender: self)
break
case 10:
//Settings
if let appSettings = URL(string: UIApplication.openSettingsURLString + Bundle.main.bundleIdentifier!) {
if UIApplication.shared.canOpenURL(appSettings) {
UIApplication.shared.open(appSettings)
}
}
break
case 11:
//GoPro Remote
let wlqGoProURL = "wunderlinqgp://"
if let uRL = URL(string: wlqGoProURL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {
if (UIApplication.shared.canOpenURL(uRL)) {
UIApplication.shared.open(uRL, options: [:], completionHandler: nil)
} else {
let alert = UIAlertController(title: NSLocalizedString("nogpremote_alert_title", comment: ""), message: NSLocalizedString("nogpremote_alert_body", comment: ""), preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("alert_message_exit_ok", comment: ""), style: UIAlertAction.Style.default, handler: { action in
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1661727055") {
UIApplication.shared.open(url)
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("negative_alert_btn_cancel", comment: ""), style: UIAlertAction.Style.cancel, handler: { action in }))
self.present(alert, animated: true, completion: nil)
}
}
break
case 12:
//Weather Map
performSegue(withIdentifier: "taskGridToWeatherMap", sender: self)
break
case 13:
//Road Book
let roadbookAppValue = UserDefaults.standard.integer(forKey: "roadbook_app_preference")
switch roadbookAppValue {
case 0: //Rabbit Rally
let urlString = "rabbitrally://app?back_url=wunderlinq://app"
if let uRL = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {
if (UIApplication.shared.canOpenURL(uRL)) {
UIApplication.shared.open(uRL, options: [:], completionHandler: nil)
}
}
break
default:
break
}
case 14:
//System Volume
performSegue(withIdentifier: "taskGridToVolume", sender: self)
break
case 15:
//Insta360 Remote
let wlqInsta360URL = "wunderlinqi360://"
if let uRL = URL(string: wlqInsta360URL.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!) {
if (UIApplication.shared.canOpenURL(uRL)) {
UIApplication.shared.open(uRL, options: [:], completionHandler: nil)
} else {
let alert = UIAlertController(title: NSLocalizedString("no360remote_alert_title", comment: ""), message: NSLocalizedString("no360remote_alert_body", comment: ""), preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("alert_message_exit_ok", comment: ""), style: UIAlertAction.Style.default, handler: { action in
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1671376660") {
UIApplication.shared.open(url)
}
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("negative_alert_btn_cancel", comment: ""), style: UIAlertAction.Style.cancel, handler: { action in }))
self.present(alert, animated: true, completion: nil)
}
}
break
case 17:
//Front Video Recording
if movieOutput.isRecording {
stopRecording()
isRecording = false
} else {
videoCaptureSession = AVCaptureSession()
if setupSession(position: .front) {
startSession(orientation: currentVideoOrientation())
isRecording = true
}
}
break
case 18:
//Fuel
if let currentLocation = motorcycleData.getLocation() {
if (!NavAppHelper.navigateToFuel(currentLatitude: currentLocation.coordinate.latitude, currentLongitude: currentLocation.coordinate.longitude)){
self.showToast(message: NSLocalizedString("nav_app_feature_not_supported", comment: ""))
}
}
break
case 19:
//Active Faults
performSegue(withIdentifier: "taskGridToFaults", sender: self)
break
default:
NSLog("TasksCollectionViewController: Unknown Task")
}
loadTasks()
self.collectionView!.reloadData()
}
override var keyCommands: [UIKeyCommand]? {
let commands = [
UIKeyCommand(input: "\u{d}", modifierFlags:[], action: #selector(selectItem)),
UIKeyCommand(input: UIKeyCommand.inputUpArrow, modifierFlags:[], action: #selector(upRow)),
UIKeyCommand(input: "+", modifierFlags:[], action: #selector(upRow)),
UIKeyCommand(input: UIKeyCommand.inputDownArrow, modifierFlags:[], action: #selector(downRow)),
UIKeyCommand(input: "-", modifierFlags:[], action: #selector(downRow)),
UIKeyCommand(input: UIKeyCommand.inputLeftArrow, modifierFlags:[], action: #selector(leftScreen)),
UIKeyCommand(input: UIKeyCommand.inputRightArrow, modifierFlags:[], action: #selector(rightScreen))
]
if #available(iOS 15, *) {
commands.forEach { $0.wantsPriorityOverSystemBehavior = true }
}
return commands
}
@objc func selectItem() {
SoundManager().playSoundEffect("enter")
execute_task(taskID: mapping[itemRow])
}
@objc func upRow() {
SoundManager().playSoundEffect("directional")
if (itemRow < mapping.count && itemRow >= 1){
let nextRow = itemRow - 1
itemRow = nextRow
self.setOffset(itemRow: itemRow)
}
}
@objc func downRow() {
SoundManager().playSoundEffect("directional")
if (itemRow < (mapping.count - 1)){
let nextRow = itemRow + 1
itemRow = nextRow
self.setOffset(itemRow: itemRow)
}
}
private func setOffset(itemRow: Int){
//Scroll to the offset calculated
UIView.animate(withDuration: 0.5, animations: {
let itemIndex = IndexPath(item: itemRow, section: 0)
if UIApplication.shared.statusBarOrientation.isLandscape {
self.collectionView.scrollToItem(at: itemIndex, at: .centeredHorizontally, animated: true)
} else {
self.collectionView.scrollToItem(at: itemIndex, at: .centeredVertically, animated: true)
}
self.view.layoutIfNeeded()
})
self.collectionView!.reloadData()
}
@objc func onTouch(recognizer: UITapGestureRecognizer){
DispatchQueue.main.async(){
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
if isTimerRunning == false {
runTimer()
}
}
@objc func leftScreen() {
SoundManager().playSoundEffect("directional")
if UserDefaults.standard.bool(forKey: "display_music_preference"){
performSegue(withIdentifier: "tasksToMusic", sender: [])
} else if UserDefaults.standard.bool(forKey: "display_dashboard_preference"){
performSegue(withIdentifier: "tasksToDash", sender: [])
} else {
navigationController?.popToRootViewController(animated: true)
}
}
@objc func rightScreen() {
SoundManager().playSoundEffect("directional")
if (WLQ.initialized){
if (wlqData.getStatus() != nil){
let secondViewController = self.storyboard!.instantiateViewController(withIdentifier: "AccessoryViewController") as! AccessoryViewController
if let viewControllers = self.navigationController?.viewControllers
{
if viewControllers.contains(where: {
return $0 is AccessoryViewController
})
{
_ = navigationController?.popViewController(animated: true)
return
} else {
self.navigationController!.pushViewController(secondViewController, animated: true)
return
}
}
}
}
navigationController?.popToRootViewController(animated: true)
}
@IBAction func prepareForUnwind(segue: UIStoryboardSegue) {
}
@IBAction func forward(_ sender: UIBarButtonItem) {
self.performSegue(withIdentifier: "unwindToContainerVC", sender: self)
}
@objc func handleGesture(gesture: UISwipeGestureRecognizer) -> Void {
if gesture.direction == UISwipeGestureRecognizer.Direction.right {
leftScreen()
}
else if gesture.direction == UISwipeGestureRecognizer.Direction.left {
rightScreen()
}
}
override func viewDidLoad() {
super.viewDidLoad()
if UserDefaults.standard.bool(forKey: "display_brightness_preference") {
UIScreen.main.brightness = CGFloat(1.0)
} else {
UIScreen.main.brightness = CGFloat(UserDefaults.standard.float(forKey: "systemBrightness"))
}
let backBtn = UIButton()
backBtn.setImage(UIImage(named: "Left")?.withRenderingMode(.alwaysTemplate), for: .normal)
backBtn.tintColor = UIColor(named: "imageTint")
backBtn.addTarget(self, action: #selector(leftScreen), for: .touchUpInside)
let backButton = UIBarButtonItem(customView: backBtn)
let backButtonWidth = backButton.customView?.widthAnchor.constraint(equalToConstant: 30)
backButtonWidth?.isActive = true
let backButtonHeight = backButton.customView?.heightAnchor.constraint(equalToConstant: 30)
backButtonHeight?.isActive = true
let forwardBtn = UIButton()
forwardBtn.setImage(UIImage(named: "Right")?.withRenderingMode(.alwaysTemplate), for: .normal)
forwardBtn.tintColor = UIColor(named: "imageTint")
forwardBtn.addTarget(self, action: #selector(rightScreen), for: .touchUpInside)
let forwardButton = UIBarButtonItem(customView: forwardBtn)
let forwardButtonWidth = forwardButton.customView?.widthAnchor.constraint(equalToConstant: 30)
forwardButtonWidth?.isActive = true
let forwardButtonHeight = forwardButton.customView?.heightAnchor.constraint(equalToConstant: 30)
forwardButtonHeight?.isActive = true
faultsBtn = UIButton(type: .custom)
let faultsImage = UIImage(named: "Alert")?.withRenderingMode(.alwaysTemplate)
faultsBtn.setImage(faultsImage, for: .normal)
faultsBtn.tintColor = UIColor.clear
faultsBtn.accessibilityIgnoresInvertColors = true
faultsBtn.addTarget(self, action: #selector(self.faultsButtonTapped), for: .touchUpInside)
faultsButton = UIBarButtonItem(customView: faultsBtn)
faultsButton.accessibilityRespondsToUserInteraction = false
faultsButton.isAccessibilityElement = false
let faultsButtonWidth = faultsButton.customView?.widthAnchor.constraint(equalToConstant: 30)
faultsButtonWidth?.isActive = true
let faultsButtonHeight = faultsButton.customView?.heightAnchor.constraint(equalToConstant: 30)
faultsButtonHeight?.isActive = true
// Update Buttons
if (faults.getallActiveDesc().isEmpty){
faultsBtn.tintColor = UIColor.clear
faultsButton.isEnabled = false
} else {
faultsBtn.tintColor = UIColor.red
faultsButton.isEnabled = true
}
self.navigationItem.title = NSLocalizedString("quicktask_title", comment: "")
self.navigationItem.leftBarButtonItems = [backButton, faultsButton]
self.navigationItem.rightBarButtonItems = [forwardButton]
self.collectionView.collectionViewLayout = flowLayout
self.collectionView.allowsMultipleSelection = true
self.collectionView.contentInsetAdjustmentBehavior = .always
let touchRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTouch))
touchRecognizer.cancelsTouchesInView = false
self.collectionView.isUserInteractionEnabled = true
self.collectionView.addGestureRecognizer(touchRecognizer)
let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeLeft.direction = .left
self.collectionView.addGestureRecognizer(swipeLeft)
let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(handleGesture))
swipeRight.direction = .right
self.collectionView.addGestureRecognizer(swipeRight)
if UserDefaults.standard.bool(forKey: "display_brightness_preference") {
UIScreen.main.brightness = CGFloat(1.0)
} else {
UIScreen.main.brightness = CGFloat(UserDefaults.standard.float(forKey: "systemBrightness"))
}
loadTasks();
loadRows();
// Waypoint Database
let databaseURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("waypoints.sqlite")
// Opening the database
if sqlite3_open(databaseURL.path, &db) != SQLITE_OK {
NSLog("TasksCollectionViewController: error opening database")
}
// Creating table
if sqlite3_exec(db, "CREATE TABLE IF NOT EXISTS records (id INTEGER PRIMARY KEY AUTOINCREMENT, date TEXT, latitude TEXT, longitude TEXT, elevation TEXT, label TEXT)", nil, nil, nil) != SQLITE_OK {
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: error creating table: \(errmsg)")
}
// Update table if needed
let updateStatementString = "ALTER TABLE records ADD COLUMN elevation TEXT"
var updateStatement: OpaquePointer?
if sqlite3_prepare_v2(db, updateStatementString, -1, &updateStatement, nil) == SQLITE_OK {
if sqlite3_step(updateStatement) == SQLITE_DONE {
NSLog("TasksCollectionViewController: Table updated successfully")
} else {
NSLog("TasksCollectionViewController: Error updating table")
}
} else {
NSLog("TasksCollectionViewController: Error preparing update statement")
}
updateDisplay()
notificationCenter.addObserver(self, selector:#selector(self.launchAccPage), name: NSNotification.Name("StatusUpdate"), object: nil)
}
private func setupScreenOrientation() {
self.collectionView.transform = CGAffineTransform.identity
switch (currentVideoOrientation()){
case .portrait:
if let layout = self.collectionView.collectionViewLayout as? ZoomAndSnapFlowLayout {
layout.scrollDirection = .vertical
}
case .portraitUpsideDown:
if let layout = self.collectionView.collectionViewLayout as? ZoomAndSnapFlowLayout {
layout.scrollDirection = .vertical
}
case .landscapeLeft:
if let layout = self.collectionView.collectionViewLayout as? ZoomAndSnapFlowLayout {
layout.scrollDirection = .horizontal
}
case .landscapeRight:
if let layout = self.collectionView.collectionViewLayout as? ZoomAndSnapFlowLayout {
layout.scrollDirection = .horizontal
}
default:
if let layout = self.collectionView.collectionViewLayout as? ZoomAndSnapFlowLayout {
layout.scrollDirection = .horizontal
}
}
collectionView.collectionViewLayout.invalidateLayout()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
NSLog("TasksCollectionViewController: viewWillTransition")
self.loadTasks()
coordinator.animate(alongsideTransition: nil) { _ in
self.setupScreenOrientation()
self.collectionView!.reloadData()
self.setOffset(itemRow: self.itemRow)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NSLog("TasksCollectionViewController: viewWillAppear")
if isTimerRunning == false {
runTimer()
}
setupScreenOrientation()
self.collectionView!.reloadData()
self.setOffset(itemRow: self.itemRow)
updateDisplay()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
timer.invalidate()
seconds = 0
// Show the navigation bar on other view controllers
DispatchQueue.main.async(){
self.navigationController?.setNavigationBarHidden(false, animated: animated)
}
notificationCenter.removeObserver(self, name: NSNotification.Name("StatusUpdate"), object: nil)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return mapping.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "TaskCollectionViewCell", for: indexPath) as! TaskCollectionViewCell
// Configure the cell
if (indexPath.row < self.tasks.count ){
let tasks = self.tasks[mapping[indexPath.row]]
cell.displayContent(icon: tasks.icon!,label: tasks.label)
if (itemRow == indexPath.row){
cell.highlightEffect()
} else {
cell.removeHighlight()
}
}
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
itemRow = indexPath.row
DispatchQueue.main.async(){
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
if isTimerRunning == false {
runTimer()
}
execute_task(taskID: mapping[indexPath.row])
}
// MARK: - Updating UI
func updateDisplay() {
// Update Buttons
if (faults.getallActiveDesc().isEmpty){
faultsBtn.tintColor = UIColor.clear
faultsButton.isEnabled = false
} else {
faultsBtn.tintColor = UIColor(named: "motorrad_red")
faultsButton.isEnabled = true
}
}
func saveWaypoint(){
// Waypoint stuff below
if let currentLocation = motorcycleData.getLocation() {
// Waypoint Database
let databaseURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("waypoints.sqlite")
// Opening the database
if sqlite3_open(databaseURL.path, &db) != SQLITE_OK {
NSLog("TasksCollectionViewController: error opening database")
}
// Creating a statement
var stmt: OpaquePointer?
//the insert query
let queryString = "INSERT INTO records (date, latitude, longitude, elevation, label) VALUES (?,?,?,?,?)"
//preparing the query
if sqlite3_prepare(db, queryString, -1, &stmt, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: error preparing insert: \(errmsg)")
return
}
let date = Date().toString() as NSString
let label : String = ""
if sqlite3_bind_text(stmt, 1, date.utf8String, -1, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: failure binding name: \(errmsg)")
return
}
if sqlite3_bind_double(stmt, 2, (currentLocation.coordinate.latitude)) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: failure binding name: \(errmsg)")
return
}
if sqlite3_bind_double(stmt, 3, (currentLocation.coordinate.longitude)) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: failure binding name: \(errmsg)")
return
}
if sqlite3_bind_double(stmt, 4, (currentLocation.altitude)) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: failure binding name: \(errmsg)")
return
}
if sqlite3_bind_text(stmt, 5, label, -1, nil) != SQLITE_OK{
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: failure binding name: \(errmsg)")
return
}
//executing the query to insert values
if sqlite3_step(stmt) != SQLITE_DONE {
let errmsg = String(cString: sqlite3_errmsg(db)!)
NSLog("TasksCollectionViewController: failure inserting wapoint: \(errmsg)")
return
}
self.showToast(message: NSLocalizedString("toast_waypoint_saved", comment: ""))
}
}
func setupCamera(position: AVCaptureDevice.Position) {
// tweak delay
let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera],
mediaType: AVMediaType(rawValue: convertFromAVMediaType(AVMediaType.video)),
position: position)
device = discoverySession.devices[0]
let input: AVCaptureDeviceInput
do {
input = try AVCaptureDeviceInput(device: device!)
} catch {
return
}
let output = AVCaptureVideoDataOutput()
output.alwaysDiscardsLateVideoFrames = true
let queue = DispatchQueue(label: "cameraQueue")
output.setSampleBufferDelegate(self, queue: queue)
output.videoSettings = [kCVPixelBufferPixelFormatTypeKey as AnyHashable: kCVPixelFormatType_32BGRA] as? [String : Any]
captureSession = AVCaptureSession()
captureSession?.addInput(input)
captureSession?.addOutput(output)
captureSession?.sessionPreset = AVCaptureSession.Preset(rawValue: convertFromAVCaptureSessionPreset(AVCaptureSession.Preset.photo))
//Testing line below
let connection = output.connection(with: AVMediaType.video)
connection?.videoOrientation = AVCaptureVideoOrientation(rawValue: UIApplication.shared.statusBarOrientation.rawValue)!
captureSession?.startRunning()
}
func captureOutput(_ captureOutput: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let imageBuffer = CMSampleBufferGetImageBuffer(sampleBuffer)
CVPixelBufferLockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))
let baseAddress = UnsafeMutableRawPointer(CVPixelBufferGetBaseAddress(imageBuffer!))
let bytesPerRow = CVPixelBufferGetBytesPerRow(imageBuffer!)
let width = CVPixelBufferGetWidth(imageBuffer!)
let height = CVPixelBufferGetHeight(imageBuffer!)
let colorSpace = CGColorSpaceCreateDeviceRGB()
let newContext = CGContext(data: baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo:
CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue)
let newImage = newContext!.makeImage()
cameraImage = UIImage(cgImage: newImage!)
CVPixelBufferUnlockBaseAddress(imageBuffer!, CVPixelBufferLockFlags(rawValue: 0))
}
func setupTimer() {
_ = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(snapshot), userInfo: nil, repeats: false)
}
@objc func snapshot() {
captureSession?.stopRunning()
if ( cameraImage == nil ){
NSLog("TasksCollectionViewController: No Image")
} else {
addAsset(image: cameraImage!, location: motorcycleData.getLocation())
}
}
//MARK: - Add image to Library
func addAsset(image: UIImage, location: CLLocation? = nil) {
PHPhotoLibrary.shared().performChanges({
// Request creating an asset from the image.
let creationRequest = PHAssetChangeRequest.creationRequestForAsset(from: image)
// Set metadata location
if let location = location {
creationRequest.location = location
}
}, completionHandler: { success, error in
if !success {
NSLog("TasksCollectionViewController: Picture not Saved, error")
} else {
NSLog("TasksCollectionViewController: Picture Saved")
if (UserDefaults.standard.bool(forKey: "photo_preview_enable_preference")){
DispatchQueue.main.async(){
[unowned self] in
self.performSegue(withIdentifier: "tasksToAlert", sender: [])
}
}
}
})
}
//MARK: - Select Audio Source
// Prefer BT HFP, else fall back to built-in mic
private func configureAudioSessionForVideo() throws {
// Let *you* control the audio session (not AVCaptureSession)
videoCaptureSession.automaticallyConfiguresApplicationAudioSession = false
// Category/mode appropriate for video capture; allow BT HFP input
try audioSession.setCategory(.playAndRecord,
mode: .videoRecording,
options: [.allowBluetooth, .defaultToSpeaker])
// HFP is typically 8–16 kHz mono; asking for 16 kHz reduces resampling
try? audioSession.setPreferredSampleRate(16_000)
// Pick HFP if available; otherwise nil = system default (built-in mic)
if let hfp = audioSession.availableInputs?.first(where: { $0.portType == .bluetoothHFP }) {
try audioSession.setPreferredInput(hfp)
} else {
try audioSession.setPreferredInput(nil)
}
try audioSession.setActive(true, options: [])
// (Optional) log the actual route you got
let routeDesc = audioSession.currentRoute.inputs.map { "\($0.portType.rawValue) \($0.portName)" }.joined(separator: ", ")
NSLog("Audio route inputs: \(routeDesc)")
}
// Keep preferring HFP when the route changes (AirPods in/out, etc.)
@objc private func handleRouteChange(_ note: Notification) {
do {
if let hfp = audioSession.availableInputs?.first(where: { $0.portType == .bluetoothHFP }) {
try audioSession.setPreferredInput(hfp)
} else {
try audioSession.setPreferredInput(nil) // fallback (built-in)
}
} catch {
NSLog("Audio route change handling failed: \(error)")
}
}
//MARK: - Setup Camera
func setupSession(position: AVCaptureDevice.Position) -> Bool {
videoCaptureSession.sessionPreset = .high
// 1) Configure audio session first (prefer BT HFP, else builtin)
do {
try configureAudioSessionForVideo()
NotificationCenter.default.addObserver(self,
selector: #selector(handleRouteChange(_:)),
name: AVAudioSession.routeChangeNotification,
object: audioSession)
} catch {
NSLog("Audio session config failed: \(error)")
// keep going; we'll still attempt builtin mic via default route
}
// 2) Setup Camera
if let camera = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: position) {
do {
let input = try AVCaptureDeviceInput(device: camera)
if videoCaptureSession.canAddInput(input) {
videoCaptureSession.addInput(input)
activeInput = input
}
} catch {
NSLog("Error setting device video input: \(error)")
return false
}
} else {
NSLog("Front camera not available")
}
// 3) Setup Microphone (device is generic; AVAudioSession decides route)
if let microphone = AVCaptureDevice.default(for: .audio) {
do {