Commit 9220992f authored by Roddi Deecke's avatar Roddi Deecke

use swiftlint autocorrect

parent f27d5a2b
......@@ -14,12 +14,11 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window?.tintColor = UIColor(named: "tintColor")
UITableView.appearance().backgroundColor = UIColor(named: "tableViewBackground")
UITextField.appearance(whenContainedInInstancesOf: [UISearchBar.self]).defaultTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
return true
}
}
......@@ -33,7 +33,7 @@ struct RGBLED {
let r: UInt8
let g: UInt8
let b: UInt8
public var data: Data {
return Data([r, g, b])
}
......@@ -53,26 +53,25 @@ struct WeakDelegate {
}
class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate, DataTransferManagerDelegate {
static private let _sharedInstance = BluetoothManager()
public static func sharedInstance() -> BluetoothManager {
// break reference cycles by turning shared instance into a method
return BluetoothManager._sharedInstance
}
}
var dataTransferManager: DataTransferManager?
var centralManager: CBCentralManager!
/// card10 main service
let card10ServiceUUID = CBUUID(string: "0x42230200-2342-2342-2342-234223422342")
/// Time update characteristic (write)
let card10TimeCharacteristic = CBUUID(string: "42230201-2342-2342-2342-234223422342")
/// Vibra characteristic (write)
let card10VibrateCharacteristic = CBUUID(string:"4223020f-2342-2342-2342-234223422342")
let card10VibrateCharacteristic = CBUUID(string: "4223020f-2342-2342-2342-234223422342")
/// Rockets characteristic (write)
let card10RocketsCharacteristic = CBUUID(string:"42230210-2342-2342-2342-234223422342")
let card10RocketsCharacteristic = CBUUID(string: "42230210-2342-2342-2342-234223422342")
/// Background LED Bottom Left characteristic (write)
let card10BackgroundLedBottomLeftCharacteristic = CBUUID(string: "42230211-2342-2342-2342-234223422342")
/// Background LED Bottom Right characteristic (write)
......@@ -92,44 +91,42 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
/// Light sensor characteristic
let card10LightSensorCharacteristic = CBUUID(string: "422302f0-2342-2342-2342-234223422342")
/// File transfer service. The two channels are seen from the Central perspective (iOS device)
/// and hence named Central TX and Central RX.
let card10RxTxServiceUUID = CBUUID(string: "42230100-2342-2342-2342-234223422342")
let card10TXWriteCharacteristicUUID = CBUUID(string: "01422342-2342-2342-2342-234223422342")
let card10RXReadCharacteristicUUID = CBUUID(string: "02422342-2342-2342-2342-234223422342")
private(set) public var foundPeripheral: Array<FoundPeripheral>
public var connectedPeripheral: CBPeripheral?
/// Holds BluetoothManagerDelegates weakly
private var subscribers: [WeakDelegate] = []
private(set) public var isScanning: Bool = false
override init() {
foundPeripheral = []
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
// MARK: - Public Functions
public func subscribe(_ subscriber: BluetoothManagerDelegate) {
subscribers.append(WeakDelegate(value: subscriber))
}
public func unsubscribe(_ subscriber: BluetoothManagerDelegate) {
subscribers.removeAll { (delegate) -> Bool in
return delegate.value == nil || delegate.value === subscriber
}
}
public func startScan() {
guard isScanning == false, centralManager.state == .poweredOn else { return }
isScanning = true
foundPeripheral = []
subscribers.forEach { $0.value?.didFindNewPeripherals(self.foundPeripheral) }
......@@ -141,7 +138,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
centralManager.scanForPeripherals(withServices: nil, options: nil)
print("scan started")
}
public func stopScan() {
guard isScanning == true else { return }
isScanning = false
......@@ -149,34 +146,34 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
centralManager.stopScan()
print("scan stopped")
}
public var state: CBManagerState {
return centralManager.state
}
public func connectToCard10Badge(peripheral: CBPeripheral) {
print("connecting to \(peripheral.identifier)...")
centralManager.connect(peripheral, options: nil)
}
public func disconnectFromCard10Badge() {
guard self.connectedPeripheral != nil else { return }
centralManager.cancelPeripheralConnection(self.connectedPeripheral!)
}
/// Starts BLE pairing process by writing the time characteristics. This triggers
/// the pairing process. FIXME: not working due to FW disconnect after bonding glitch.
public func pairWithCard10Badge(peripheral: CBPeripheral) {
setTimeOnPeripheral()
}
public func sendFileData(data: Data, fileName: String) {
self.dataTransferManager = DataTransferManager(self)
self.subscribeToRxChannel()
self.dataTransferManager?.transferData(data,filename: fileName)
self.dataTransferManager?.transferData(data, filename: fileName)
}
public func setTimeOnPeripheral() {
guard let peripheral = self.connectedPeripheral else {
print("setTimeOnPeripheral() failed, self.connectedPeripheral is nil")
......@@ -193,16 +190,16 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
let unixTimeWithTimeZoneOffset: Int = Int(Date().timeIntervalSince1970)
let badgeTimeInMilliseconds: UInt64 = UInt64(unixTimeWithTimeZoneOffset * 1000 )
let time = UInt64(bigEndian: badgeTimeInMilliseconds)
print("setTimeOnPeripheral \(peripheral.identifier) to \(currentDate) (\(badgeTimeInMilliseconds))")
self.connectedPeripheral?.writeValue(time.data, for: characteristic, type: .withoutResponse)
}
public func setVibrate(milliseconds: UInt16) {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let characteristic = self.findCharacteristic(on: peripheral, forServiceUUID: card10ServiceUUID, forCharacteristicUUID: card10VibrateCharacteristic) else {
print("could not find vibration characteristic!")
return
......@@ -214,7 +211,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
public func illuminateRocketsWithBrightness(rocketOne: UInt8, rocketTwo: UInt8, rocketThree: UInt8) {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let characteristic = self.findCharacteristic(on: peripheral, forServiceUUID: card10ServiceUUID, forCharacteristicUUID: card10RocketsCharacteristic) else {
print("could not find card10RocketsCharacteristic!")
return
......@@ -223,10 +220,10 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
print("set rockets to \(rocketOne), \(rocketTwo), \(rocketThree) on \(peripheral.identifier)")
self.connectedPeripheral?.writeValue(Data([rocketOne, rocketTwo, rocketThree]), for: characteristic, type: .withoutResponse)
}
public func setBackgroundLEDs (topLeft: RGBLED, topRight: RGBLED, bottomRight: RGBLED, bottomLeft: RGBLED) {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let tlCharacteristic = self.findCharacteristic(on: peripheral,
forServiceUUID: card10ServiceUUID,
forCharacteristicUUID: card10BackgroundLedTopLeftCharacteristic),
......@@ -248,7 +245,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
self.connectedPeripheral?.writeValue(bottomRight.data, for: brCharacteristic, type: .withoutResponse)
self.connectedPeripheral?.writeValue(bottomLeft.data, for: blCharacteristic, type: .withoutResponse)
}
/// Set's the 11 RGB leds at the top. Parameters are from left to right.
public func setLEDsAbove(a: RGBLED,
b: RGBLED,
......@@ -262,19 +259,19 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
j: RGBLED,
k: RGBLED) {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let aboveCharacteristic = self.findCharacteristic(on: peripheral,
forServiceUUID: card10ServiceUUID,
forCharacteristicUUID: card10LedsAboveCharacteristic) else {
print("setLEDsAbove could not find card10RocketsCharacteristic!")
return
}
self.connectedPeripheral?.writeValue(mergeLedsAboveIntoData(a: a, b: b, c: c, d: d, e: e, f: f, g: g, h: h, i: i, j: j, k: k),
for: aboveCharacteristic,
type: .withoutResponse)
}
private func mergeLedsAboveIntoData(a: RGBLED,
b: RGBLED,
c: RGBLED,
......@@ -286,9 +283,9 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
i: RGBLED,
j: RGBLED,
k: RGBLED) -> Data {
var data = Data()
data.append(a.data)
data.append(b.data)
data.append(c.data)
......@@ -300,7 +297,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
data.append(i.data)
data.append(j.data)
data.append(k.data)
return data
}
......@@ -308,30 +305,30 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let characteristic = self.findCharacteristic(on: peripheral, forServiceUUID: card10ServiceUUID, forCharacteristicUUID: card10LightSensorCharacteristic) else { return }
self.connectedPeripheral?.readValue(for: characteristic)
}
// MARK: - File Transfer Helpers
func subscribeToRxChannel() {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let characteristic = self.findCharacteristic(on: peripheral, forServiceUUID: card10RxTxServiceUUID, forCharacteristicUUID: card10RXReadCharacteristicUUID) else { return }
self.connectedPeripheral?.setNotifyValue(true, for: characteristic)
}
func unsubscrubeFromRxChannel() {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let characteristic = self.findCharacteristic(on: peripheral, forServiceUUID: card10RxTxServiceUUID, forCharacteristicUUID: card10RXReadCharacteristicUUID) else { return }
self.connectedPeripheral?.setNotifyValue(false, for: characteristic)
}
// MARK: - CBCentralManagerDelegate
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .unknown:
......@@ -350,14 +347,14 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
print("This shouldn't happen")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
// I failed to scan for the CBUUD 42230100-2342-2342-2342-234223422342 :-/
guard let name = peripheral.name, name.hasPrefix("card10") else { return }
let advName = String("\(advertisementData[CBAdvertisementDataLocalNameKey] ?? "")")
print("did discover: \(name) \(peripheral.identifier)), CBAdvertisementDataLocalNameKey: \(advName)")
// sort & unique foundPeripherals
foundPeripheral.append(FoundPeripheral.init(peripheral: peripheral, advertisementName: advName, rssi: RSSI.intValue))
foundPeripheral = Array(Set(foundPeripheral)).sorted { $0.peripheral.identifier.uuidString > $1.peripheral.identifier.uuidString }
......@@ -372,13 +369,13 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
self.connectedPeripheral = peripheral
subscribers.forEach { $0.value?.didConnectToPeripheal(FoundPeripheral(peripheral: peripheral, advertisementName: nil, rssi: nil)) }
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("did disconnect: \(peripheral.name ?? "<nil>") \(peripheral.identifier))")
self.connectedPeripheral = nil
subscribers.forEach { $0.value?.didDisconnectFromPeripheral() }
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
print("found service: \(service.uuid)")
......@@ -405,20 +402,20 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
print("did didDiscoverCharacteristicsFor: \(service.uuid) \(service.characteristics!))")
// FIXME: pairing is broken ATM
// pairWithCard10Badge(peripheral: peripheral)
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
if characteristic.uuid.isEqual(card10LightSensorCharacteristic) {
guard let data = characteristic.value else { return }
var value: UInt16 = 0
_ = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)} )
_ = withUnsafeMutableBytes(of: &value, { data.copyBytes(to: $0)})
subscribers.forEach { $0.value?.didGetNewLightSensorData(value) }
}
if characteristic.uuid.isEqual(card10RXReadCharacteristicUUID) {
guard let data = characteristic.value else { return }
guard let nextChunk = String(data: data, encoding: String.Encoding.utf8) else {
......@@ -428,24 +425,24 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
self.dataTransferManager?.receivedNewPackage(nextChunk)
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
// only log errors
error.map {
print("periperal: \(peripheral.identifier) didWriteValueFor: \(characteristic.uuid) error: \($0.localizedDescription)")
}
}
// MARK: - DataTransferManagerDelegate
func wantsToSendPackage(_ package: Data) {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let characteristic = self.findCharacteristic(on: peripheral, forServiceUUID: card10RxTxServiceUUID, forCharacteristicUUID: card10TXWriteCharacteristicUUID) else { return }
self.connectedPeripheral?.writeValue(package, for: characteristic, type: .withResponse)
}
func didUpdateState(_ state: TransferState) {
switch state {
case .IDLE:
......@@ -463,17 +460,17 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
}
}
func didFailToSendFile() {
subscribers.forEach { $0.value?.didFailToSendFile() }
}
func didUpdateProgress(_ progress: Double) {
subscribers.forEach { $0.value?.didUpdateProgressOnFile(progress) }
}
// MARK: - Helper methods
func findCharacteristic(on peripheral: CBPeripheral, forServiceUUID: CBUUID, forCharacteristicUUID: CBUUID) -> CBCharacteristic? {
return peripheral.services?
.filter { $0.uuid.isEqual(forServiceUUID) }
......@@ -482,5 +479,5 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
.filter { $0.uuid.isEqual(forCharacteristicUUID) }
.first
}
}
......@@ -3,7 +3,7 @@
//
class CRC32 {
static var table: [UInt32] = {
(0...255).map { i -> UInt32 in
(0..<8).reduce(UInt32(i), { c, _ in
......@@ -11,11 +11,11 @@ class CRC32 {
})
}
}()
static func checksum(bytes: [UInt8]) -> UInt32 {
return ~(bytes.reduce(~UInt32(0), { crc, byte in
(crc >> 8) ^ table[(Int(crc) ^ Int(byte)) & 0xFF]
}))
}
}
......@@ -12,35 +12,34 @@ class ChunkedDataReader: NSObject {
var dataToChunk: Data
let packageSize = 95
public var currentOffset: Int = 0
init(_ data: Data) {
dataToChunk = data
}
public func nextChunk() -> Data? {
guard dataToChunk.count > 0 else { return nil }
let dataToReturn = extractData(offset: currentOffset, length: packageSize)
guard dataToReturn!.count > 0 else { return nil }
currentOffset += 95
return dataToReturn
}
func extractData(offset: Int, length: Int) -> Data? {
guard dataToChunk.count > 0 else {
return nil
}
var range:Range<Data.Index>
var range: Range<Data.Index>
// Create a range based on the length of data to return
if dataToChunk.count >= offset+length{
if dataToChunk.count >= offset+length {
range = offset..<length
}
else{
} else {
range = offset..<dataToChunk.count
}
// Get a new copy of data
......
......@@ -7,15 +7,15 @@
import UIKit
extension Data {
var uint8: UInt8 {
get {
var number: UInt8 = 0
self.copyBytes(to:&number, count: MemoryLayout<UInt8>.size)
self.copyBytes(to: &number, count: MemoryLayout<UInt8>.size)
return number
}
}
var uint16: UInt16 {
get {
let i16array = self.withUnsafeBytes {
......@@ -24,7 +24,7 @@ extension Data {
return i16array[0]
}
}
var uint32: UInt32 {
get {
let i32array = self.withUnsafeBytes {
......@@ -33,7 +33,7 @@ extension Data {
return i32array[0]
}
}
var uint64: UInt64 {
get {
let i64array = self.withUnsafeBytes {
......@@ -42,11 +42,11 @@ extension Data {
return i64array[0]
}
}
var uuid: NSUUID? {
get {
var bytes = [UInt8](repeating: 0, count: self.count)
self.copyBytes(to:&bytes, count: self.count * MemoryLayout<UInt32>.size)
self.copyBytes(to: &bytes, count: self.count * MemoryLayout<UInt32>.size)
return NSUUID(uuidBytes: bytes)
}
}
......@@ -55,21 +55,21 @@ extension Data {
return NSString(data: self, encoding: String.Encoding.ascii.rawValue) as String?
}
}
var stringUTF8: String? {
get {
return NSString(data: self, encoding: String.Encoding.utf8.rawValue) as String?
}
}
struct HexEncodingOptions: OptionSet {
let rawValue: Int
static let upperCase = HexEncodingOptions(rawValue: 1 << 0)
}
func hexEncodedString(options: HexEncodingOptions = []) -> String {
let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
return map { String(format: format, $0) }.joined()
}
}
......@@ -16,7 +16,7 @@ enum TransferState {
case FINISH_SENT
}
enum PackageType :String {
enum PackageType: String {
case START = "s"
case START_ACK = "S"
case CHUNK = "c"
......@@ -35,7 +35,7 @@ protocol DataTransferManagerDelegate: class {
}
class DataTransferManager: NSObject {
weak var delegate: DataTransferManagerDelegate?
var chunkedReader: ChunkedDataReader?
......@@ -44,17 +44,17 @@ class DataTransferManager: NSObject {
delegate?.didUpdateState(self.transferState)
}
}
var lastPackageSentAt: TimeInterval?
var dataToSend: Data?
var currentChunkToSend: Data?
var retryCount: Int = 0
init(_ delegateToUse: DataTransferManagerDelegate) {
delegate = delegateToUse
self.transferState = .IDLE
}
public func receivedNewPackage(_ package: String) {
let firstChar = String(package.prefix(1))
let packageType = PackageType(rawValue: firstChar)
......@@ -85,7 +85,7 @@ class DataTransferManager: NSObject {
self.currentChunkToSend = chunkToSend
sendPackage(type: .CHUNK, payload: chunkToSend)
}
} else if (retryCount < 9){
} else if (retryCount < 9) {
sendPackage(type: .CHUNK, payload: self.currentChunkToSend)
retryCount += 1
} else {
......@@ -111,25 +111,25 @@ class DataTransferManager: NSObject {
self.transferState = .IDLE
break
default:
print("Broken Package ",firstChar)
print("Broken Package ", firstChar)
}
}