UTMSerialPort.swift 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. //
  2. // Copyright © 2021 osy. All rights reserved.
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. //
  16. import Foundation
  17. @objc class UTMSerialPort: NSObject {
  18. let name: String
  19. private let readFileHandle: FileHandle
  20. private let writeFileHandle: FileHandle
  21. private let terminalFileHandle: FileHandle?
  22. public weak var delegate: UTMSerialPortDelegate? {
  23. didSet {
  24. if let delegate = delegate {
  25. readFileHandle.readabilityHandler = { handle in
  26. delegate.serialPort(self, didRecieveData: handle.availableData)
  27. }
  28. } else {
  29. readFileHandle.readabilityHandler = nil
  30. }
  31. }
  32. }
  33. init(portNamed name: String, readFileHandle: FileHandle, writeFileHandle: FileHandle, terminalFileHandle: FileHandle? = nil) {
  34. self.name = name
  35. self.readFileHandle = readFileHandle
  36. self.writeFileHandle = writeFileHandle
  37. self.terminalFileHandle = terminalFileHandle
  38. }
  39. deinit {
  40. close()
  41. }
  42. public func write(data: Data) {
  43. if #available(iOS 13.4, macOS 10.15, *) {
  44. try! writeFileHandle.write(contentsOf: data)
  45. } else {
  46. writeFileHandle.write(data)
  47. }
  48. }
  49. public func close() {
  50. if #available(iOS 13, macOS 10.15, *) {
  51. try? readFileHandle.close()
  52. try? writeFileHandle.close()
  53. try? terminalFileHandle?.close()
  54. } else {
  55. readFileHandle.closeFile()
  56. writeFileHandle.closeFile()
  57. terminalFileHandle?.closeFile()
  58. }
  59. }
  60. }