/
UartBaseViewController.swift
657 lines (523 loc) · 26.5 KB
/
UartBaseViewController.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
//
// UartBaseViewController.swift
// Bluefruit
//
// Created by Antonio García on 05/08/2017.
// Copyright © 2017 Adafruit. All rights reserved.
//
import UIKit
import UIKit
import UIColor_Hex
class UartBaseViewController: PeripheralModeViewController {
// Config
fileprivate static var dataRxFont = UIFont(name: "CourierNewPSMT", size: 14)!
fileprivate static var dataTxFont = UIFont(name: "CourierNewPS-BoldMT", size: 14)!
// Export
fileprivate static let kExportFormats: [ExportFormat] = [.txt, .csv, .json/*, .xml*/, .bin]
// UI
@IBOutlet weak var baseTableView: UITableView!
@IBOutlet weak var baseTextView: UITextView!
@IBOutlet weak var statsLabel: UILabel!
@IBOutlet weak var statsLabeliPadLeadingConstraint: NSLayoutConstraint! // remove ipad or iphone depending on the platform
@IBOutlet weak var statsLabeliPhoneLeadingConstraint: NSLayoutConstraint! // remove ipad or iphone depending on the platform
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var sendInputButton: UIButton!
@IBOutlet weak var sendPeripheralButton: UIButton?
@IBOutlet weak var keyboardSpacerHeightConstraint: NSLayoutConstraint!
fileprivate var mqttBarButtonItem: UIBarButtonItem!
fileprivate var mqttBarButtonItemImageView: UIImageView?
@IBOutlet weak var moreOptionsNavigationItem: UIBarButtonItem!
@IBOutlet weak var mainStackView: UIStackView!
@IBOutlet weak var controlsView: UIView!
@IBOutlet weak var inputControlsStackView: UIStackView!
@IBOutlet weak var showEolSwitch: UISwitch!
@IBOutlet weak var addEolSwitch: UISwitch!
@IBOutlet weak var exportButton: UIButton!
@IBOutlet weak var displayModeSegmentedControl: UISegmentedControl!
@IBOutlet weak var dataModeSegmentedControl: UISegmentedControl!
// Data
enum DisplayMode {
case text // Display a TextView with all uart data as a String
case table // Display a table where each data packet is a row
}
enum ExportFormat: String {
case txt = "txt"
case csv = "csv"
case json = "json"
case xml = "xml"
case bin = "bin"
}
internal var uartData: UartPacketManagerBase!
internal var colorForPeripheral = [UUID: UIColor]()
fileprivate let timestampDateFormatter = DateFormatter()
fileprivate var tableCachedDataBuffer: [UartPacket]?
fileprivate var textCachedBuffer = NSMutableAttributedString()
internal var multiUartSendToPeripheralId: UUID? // nil = all peripherals
private let keyboardPositionNotifier = KeyboardPositionNotifier()
override func viewDidLoad() {
super.viewDidLoad()
// Init Data
keyboardPositionNotifier.delegate = self
timestampDateFormatter.setLocalizedDateFormatFromTemplate("HH:mm:ss")
// Setup tableView
// Note: Don't use automatic height because its to slow with a large amount of rows
baseTableView.layer.borderWidth = 1
baseTableView.layer.borderColor = UIColor.lightGray.cgColor
// Setup textview
baseTextView.layer.borderWidth = 1
baseTextView.layer.borderColor = UIColor.lightGray.cgColor
// Setup controls
let localizationManager = LocalizationManager.sharedInstance
displayModeSegmentedControl.setTitle(localizationManager.localizedString("uart_settings_displayMode_timestamp"), forSegmentAt: 0)
displayModeSegmentedControl.setTitle(localizationManager.localizedString("uart_settings_displayMode_text"), forSegmentAt: 1)
dataModeSegmentedControl.setTitle(localizationManager.localizedString("uart_settings_dataMode_ascii"), forSegmentAt: 0)
dataModeSegmentedControl.setTitle(localizationManager.localizedString("uart_settings_dataMode_hex"), forSegmentAt: 1)
// Init options layout
if UI_USER_INTERFACE_IDIOM() == .pad { //traitCollection.userInterfaceIdiom == .pad { // iPad
self.view.removeConstraint(statsLabeliPhoneLeadingConstraint)
// Resize input UISwitch controls
for subStackView in inputControlsStackView.subviews {
for subview in subStackView.subviews {
if let switchView = subview as? UISwitch {
switchView.transform = CGAffineTransform(scaleX: 0.6, y: 0.6)
}
}
}
} else { // iPhone
self.view.removeConstraint(statsLabeliPadLeadingConstraint)
statsLabel.textAlignment = .left
inputControlsStackView.isHidden = true
}
sendPeripheralButton?.isHidden = !isInMultiUartMode()
if !isInMultiUartMode() {
// Mqtt init
mqttBarButtonItemImageView = UIImageView(image: UIImage(named: "mqtt_disconnected")!.tintWithColor(self.view.tintColor)) // use a uiimageview as custom barbuttonitem to allow frame animations
mqttBarButtonItemImageView!.tintColor = self.view.tintColor
mqttBarButtonItemImageView?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onClickMqtt)))
if MqttSettings.shared.isConnected {
let mqttManager = MqttManager.shared
mqttManager.delegate = self
mqttManager.connectFromSavedSettings()
}
}
// Localization
sendInputButton.setTitle(localizationManager.localizedString("uart_send_action"), for: .normal)
sendPeripheralButton?.setTitle(localizationManager.localizedString("uart_send_toall_action"), for: .normal) // Default value
// Note: uartData should be initialized on the subclasses
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Hide top controls on iPhone
if UI_USER_INTERFACE_IDIOM() == .phone {// traitCollection.userInterfaceIdiom == .phone {
controlsView.isHidden = true
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
registerNotifications(enabled: true)
// Update the navigation bar items
if var rightButtonItems = navigationItem.rightBarButtonItems, rightButtonItems.count == 2 {
if UI_USER_INTERFACE_IDIOM() == .pad { // traitCollection.userInterfaceIdiom == .pad {
// Remove more item
rightButtonItems.remove(at: 0)
// Add mqtt bar item
if !isInMultiUartMode() {
mqttBarButtonItem = UIBarButtonItem(customView: mqttBarButtonItemImageView!)
rightButtonItems.append(mqttBarButtonItem)
}
} else {
// Add mqtt bar item
if !isInMultiUartMode() {
mqttBarButtonItem = UIBarButtonItem(customView: mqttBarButtonItemImageView!)
rightButtonItems.append(mqttBarButtonItem)
}
}
navigationItem.rightBarButtonItems = rightButtonItems
}
// UI
reloadDataUI()
reloadControlsUI()
// Enable Uart
setupUart()
// MQTT
if !isInMultiUartMode() {
if MqttSettings.shared.isConnected {
MqttManager.shared.delegate = self
}
mqttUpdateStatusUI()
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
registerNotifications(enabled: false)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
baseTableView.enh_cancelPendingReload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
uartData = nil
let mqttManager = MqttManager.shared
mqttManager.disconnect()
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "uartSettingsSegue" {
if let controller = segue.destination.popoverPresentationController {
controller.delegate = self
//controller.backgroundColor = UIColor.lightGray
let uartSettingsViewController = segue.destination as! UartSettingsViewController
uartSettingsViewController.onClickClear = { [unowned self] in
self.onClickClear(self)
}
uartSettingsViewController.onClickExport = { [unowned self] in
self.onClickExport(self)
}
}
}
}
// MARK: - BLE Notifications
private weak var didUpdatePreferencesObserver: NSObjectProtocol?
private func registerNotifications(enabled: Bool) {
let notificationCenter = NotificationCenter.default
if enabled {
didUpdatePreferencesObserver = notificationCenter.addObserver(forName: .didUpdatePreferences, object: nil, queue: .main, using: didUpdatePreferences)
} else {
if let didUpdatePreferencesObserver = didUpdatePreferencesObserver {notificationCenter.removeObserver(didUpdatePreferencesObserver)}
}
}
private func didUpdatePreferences(notification: Notification) {
// txColor = Preferences.uartSentDataColor
// rxColor = Preferences.uartReceveivedDataColor
reloadDataUI()
}
// MARK: - UART
internal func isInMultiUartMode() -> Bool {
assert(false, "Should be implemented by subclasses")
return false
}
internal func setupUart() {
assert(false, "Should be implemented by subclasses")
}
// MARK: - UI Updates
private func reloadDataUI() {
let displayMode: UartModeViewController.DisplayMode = Preferences.uartIsDisplayModeTimestamp ? .table : .text
baseTableView.isHidden = displayMode == .text
baseTextView.isHidden = displayMode == .table
switch displayMode {
case .text:
textCachedBuffer.setAttributedString(NSAttributedString())
let dataPackets = uartData.packetsCache()
for dataPacket in dataPackets {
onUartPacketText(dataPacket)
}
baseTextView.attributedText = textCachedBuffer
reloadData()
case .table:
reloadData()
}
updateBytesUI()
}
fileprivate func reloadControlsUI() {
showEolSwitch.isOn = Preferences.uartIsAutomaticEolEnabled
addEolSwitch.isOn = Preferences.uartIsEchoEnabled
displayModeSegmentedControl.selectedSegmentIndex = Preferences.uartIsDisplayModeTimestamp ? 0:1
dataModeSegmentedControl.selectedSegmentIndex = Preferences.uartIsInHexMode ? 1:0
}
fileprivate func updateBytesUI() {
let localizationManager = LocalizationManager.sharedInstance
let sentBytesMessage = String(format: localizationManager.localizedString("uart_sentbytes_format"), arguments: [uartData.sentBytes])
let receivedBytesMessage = String(format: localizationManager.localizedString("uart_receivedbytes_format"), arguments: [uartData.receivedBytes])
statsLabel.text = String(format: "%@ %@", arguments: [sentBytesMessage, receivedBytesMessage])
}
internal func updateUartReadyUI(isReady: Bool) {
inputTextField.isEnabled = isReady
inputTextField.backgroundColor = isReady ? UIColor.white : UIColor.black.withAlphaComponent(0.1)
sendInputButton.isEnabled = isReady
}
internal func send(message: String) {
assert(false, "Should be implemented by subclasses")
}
// MARK: - UI Actions
@objc func onClickMqtt() {
let viewController = storyboard!.instantiateViewController(withIdentifier: "UartMqttSettingsViewController")
viewController.modalPresentationStyle = .popover
if let popovoverController = viewController.popoverPresentationController {
popovoverController.barButtonItem = mqttBarButtonItem
popovoverController.delegate = self
// popovoverController.backgroundColor = UIColor.lightGray
}
present(viewController, animated: true, completion: nil)
}
@IBAction func onClickSend(_ sender: AnyObject) {
//guard let blePeripheral = blePeripheral else { return }
var newText = inputTextField.text ?? ""
// Eol
if Preferences.uartIsAutomaticEolEnabled {
newText += Preferences.uartEolCharacters //"\n"
}
send(message: newText)
inputTextField.text = ""
inputTextField.resignFirstResponder()
}
@IBAction func onInputTextFieldEdidtingDidEndOnExit(_ sender: UITextField) {
onClickSend(sender)
}
@IBAction func onClickClear(_ sender: AnyObject) {
uartData.clearPacketsCache()
reloadDataUI()
}
@IBAction func onClickExport(_ sender: AnyObject) {
let uartRxCache = uartData.packetsCache()
guard !uartRxCache.isEmpty else {
showDialogWarningNoTextToExport()
return
}
let localizationManager = LocalizationManager.sharedInstance
let alertController = UIAlertController(title: "Export data", message: "Choose the prefered format:", preferredStyle: .actionSheet)
for exportFormat in UartModeViewController.kExportFormats {
let exportAction = UIAlertAction(title: exportFormat.rawValue, style: .default) { [unowned self] (_) in
var exportObject: AnyObject?
switch exportFormat {
case .txt:
exportObject = UartDataExport.packetsAsText(uartRxCache) as AnyObject
case .csv:
exportObject = UartDataExport.packetsAsCsv(uartRxCache) as AnyObject
case .json:
exportObject = UartDataExport.packetsAsJson(uartRxCache) as AnyObject
case .xml:
exportObject = UartDataExport.packetsAsXml(uartRxCache) as AnyObject
case .bin:
exportObject = UartDataExport.packetsAsBinary(uartRxCache) as AnyObject
}
self.export(object: exportObject)
}
alertController.addAction(exportAction)
}
let cancelAction = UIAlertAction(title: localizationManager.localizedString("dialog_cancel"), style: .cancel, handler:nil)
alertController.addAction(cancelAction)
alertController.popoverPresentationController?.sourceView = exportButton
alertController.popoverPresentationController?.sourceRect = exportButton.bounds
self.present(alertController, animated: true, completion: nil)
}
private func export(object: AnyObject?) {
if let object = object {
// TODO: replace randomly generated iOS filenames: https://thomasguenzel.com/blog/2015/04/16/uiactivityviewcontroller-nsdata-with-filename/
let activityViewController = UIActivityViewController(activityItems: [object], applicationActivities: nil)
activityViewController.popoverPresentationController?.sourceView = exportButton
activityViewController.popoverPresentationController?.sourceRect = exportButton.bounds
navigationController?.present(activityViewController, animated: true, completion: nil)
} else {
DLog("exportString with empty text")
showDialogWarningNoTextToExport()
}
}
private func showDialogWarningNoTextToExport() {
let localizationManager = LocalizationManager.sharedInstance
let alertController = UIAlertController(title: nil, message: localizationManager.localizedString("uart_export_nodata"), preferredStyle: .alert)
let okAction = UIAlertAction(title: localizationManager.localizedString("dialog_ok"), style: .default, handler:nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
@IBAction func onShowEchoValueChanged(_ sender: UISwitch) {
Preferences.uartIsEchoEnabled = sender.isOn
}
@IBAction func onAddEolValueChanged(_ sender: UISwitch) {
Preferences.uartIsAutomaticEolEnabled = sender.isOn
}
@IBAction func onDisplayModeChanged(_ sender: UISegmentedControl) {
Preferences.uartIsDisplayModeTimestamp = sender.selectedSegmentIndex == 0
}
@IBAction func onDataModeChanged(_ sender: UISegmentedControl) {
Preferences.uartIsInHexMode = sender.selectedSegmentIndex == 1
}
@IBAction func onClickHelp(_ sender: UIBarButtonItem) {
let localizationManager = LocalizationManager.sharedInstance
let helpViewController = storyboard!.instantiateViewController(withIdentifier: "HelpViewController") as! HelpViewController
helpViewController.setHelp(localizationManager.localizedString("uart_help_text"), title: localizationManager.localizedString("uart_help_title"))
let helpNavigationController = UINavigationController(rootViewController: helpViewController)
helpNavigationController.modalPresentationStyle = .popover
helpNavigationController.popoverPresentationController?.barButtonItem = sender
present(helpNavigationController, animated: true, completion: nil)
}
// MARK: - Style
internal func colorForPacket(packet: UartPacket) -> UIColor {
assert(false, "Should be implemented by subclasses")
return .black
}
fileprivate func fontForPacket(packet: UartPacket) -> UIFont {
let font = packet.mode == .tx ? UartModeViewController.dataTxFont : UartModeViewController.dataRxFont
return font
}
}
// MARK: - UITableViewDataSource
extension UartBaseViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if Preferences.uartIsEchoEnabled {
tableCachedDataBuffer = uartData.packetsCache()
} else {
tableCachedDataBuffer = uartData.packetsCache().filter({ (dataPacket: UartPacket) -> Bool in
dataPacket.mode == .rx
})
}
return tableCachedDataBuffer?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let reuseIdentifier = "TimestampCell"
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for:indexPath)
// Data binding in cellForRowAtIndexPath to avoid problems with multiple-line labels and dyanmic tableview height calculation
let dataPacket = tableCachedDataBuffer![indexPath.row]
let date = Date(timeIntervalSinceReferenceDate: dataPacket.timestamp)
let dateString = timestampDateFormatter.string(from: date)
let modeString = LocalizationManager.sharedInstance.localizedString(dataPacket.mode == .rx ? "uart_timestamp_direction_rx" : "uart_timestamp_direction_tx")
let color = colorForPacket(packet: dataPacket)
let font = fontForPacket(packet: dataPacket)
let timestampCell = cell as! UartTimetampTableViewCell
timestampCell.timeStampLabel.text = String(format: "%@ %@", arguments: [dateString, modeString])
if let attributedText = attributedStringFromData(dataPacket.data, useHexMode: Preferences.uartIsInHexMode, color: color, font: font), attributedText.length > 0 {
timestampCell.dataLabel.attributedText = attributedText
} else {
timestampCell.dataLabel.attributedText = NSAttributedString(string: " ") // space to maintain height
}
timestampCell.contentView.backgroundColor = indexPath.row%2 == 0 ? UIColor.white : UIColor(hex: 0xeeeeee)
return cell
}
}
// MARK: UITableViewDelegate
extension UartBaseViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
}
}
// MARK: - UartModuleDelegate
extension UartBaseViewController: UartPacketManagerDelegate {
func onUartPacket(_ packet: UartPacket) {
// Check that the view has been initialized before updating UI
guard isViewLoaded && view.window != nil && baseTableView != nil else { return }
let displayMode: UartModeViewController.DisplayMode = Preferences.uartIsDisplayModeTimestamp ? .table : .text
switch displayMode {
case .text:
onUartPacketText(packet)
self.enh_throttledReloadData() // it will call self.reloadData without overloading the main thread with calls
case .table:
self.enh_throttledReloadData() // it will call self.reloadData without overloading the main thread with calls
}
updateBytesUI()
}
func reloadData() {
let displayMode: UartModeViewController.DisplayMode = Preferences.uartIsDisplayModeTimestamp ? .table : .text
switch displayMode {
case .text:
baseTextView.attributedText = textCachedBuffer
let textLength = textCachedBuffer.length
if textLength > 0 {
let range = NSMakeRange(textLength - 1, 1)
baseTextView.scrollRangeToVisible(range)
}
case .table:
baseTableView.reloadData()
if let tableCachedDataBuffer = tableCachedDataBuffer {
if tableCachedDataBuffer.count > 0 {
let lastIndex = IndexPath(row: tableCachedDataBuffer.count-1, section: 0)
baseTableView.scrollToRow(at: lastIndex, at: .bottom, animated: false)
}
}
}
}
fileprivate func onUartPacketText(_ packet: UartPacket) {
guard Preferences.uartIsEchoEnabled || packet.mode == .rx else { return }
let color = colorForPacket(packet: packet)
let font = fontForPacket(packet: packet)
if let attributedString = attributedStringFromData(packet.data, useHexMode: Preferences.uartIsInHexMode, color: color, font: font) {
textCachedBuffer.append(attributedString)
}
}
func mqttUpdateStatusUI() {
guard let imageView = mqttBarButtonItemImageView, let tintColor = self.view.tintColor else { return }
let status = MqttManager.shared.status
switch status {
case .connecting:
let imageFrames = [
UIImage(named:"mqtt_connecting1")!.tintWithColor(tintColor),
UIImage(named:"mqtt_connecting2")!.tintWithColor(tintColor),
UIImage(named:"mqtt_connecting3")!.tintWithColor(tintColor)
]
imageView.animationImages = imageFrames
imageView.animationDuration = 0.5 * Double(imageFrames.count)
imageView.animationRepeatCount = 0
imageView.startAnimating()
case .connected:
imageView.stopAnimating()
imageView.image = UIImage(named:"mqtt_connected")!.tintWithColor(tintColor)
default:
imageView.stopAnimating()
imageView.image = UIImage(named:"mqtt_disconnected")!.tintWithColor(tintColor)
}
}
func mqttError(message: String, isConnectionError: Bool) {
let localizationManager = LocalizationManager.sharedInstance
let alertMessage = isConnectionError ? localizationManager.localizedString("uart_mqtt_connectionerror_title") : message
let alertController = UIAlertController(title: nil, message: alertMessage, preferredStyle: .alert)
let okAction = UIAlertAction(title: localizationManager.localizedString("dialog_ok"), style: .default, handler:nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
// MARK: - UIPopoverPresentationControllerDelegate
extension UartBaseViewController: UIPopoverPresentationControllerDelegate {
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
// This *forces* a popover to be displayed on the iPhone
return .none
}
func popoverPresentationControllerDidDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) {
// Note: same delegate used for MQTT popover and Export popover
// MQTT
let mqttManager = MqttManager.shared
if MqttSettings.shared.isConnected {
mqttManager.delegate = self
}
mqttUpdateStatusUI()
}
}
// MARK: - KeyboardPositionNotifierDelegate
extension UartBaseViewController: KeyboardPositionNotifierDelegate {
func onKeyboardPositionChanged(keyboardFrame: CGRect, keyboardShown: Bool) {
var spacerHeight = keyboardFrame.height
spacerHeight -= StyleConfig.tabbarHeight
keyboardSpacerHeightConstraint.constant = max(spacerHeight, 0)
}
}
// MARK: - MqttManagerDelegate
extension UartBaseViewController: MqttManagerDelegate {
func onMqttConnected() {
DispatchQueue.main.async { [unowned self] in
self.mqttUpdateStatusUI()
}
}
func onMqttDisconnected() {
DispatchQueue.main.async { [unowned self] in
self.mqttUpdateStatusUI()
}
}
@objc func onMqttMessageReceived(message: String, topic: String) {
assert(false, "should be overrided by subclasses")
}
func onMqttError(message: String) {
let mqttManager = MqttManager.shared
let status = mqttManager.status
let isConnectionError = status == .connecting
DispatchQueue.main.async { [unowned self] in
self.mqttError(message: message, isConnectionError: isConnectionError)
}
}
}
// MARK: - UartSelectPeripheralViewControllerDelegate
extension UartBaseViewController: UartSelectPeripheralViewControllerDelegate {
func onUartSendToChanged(uuid: UUID?, name: String) {
multiUartSendToPeripheralId = uuid
sendPeripheralButton?.setTitle(name, for: .normal)
}
}