Commit 1312246f authored by Thomas Mellenthin's avatar Thomas Mellenthin

Merge branch 'roddi-swiftlint-fixes' into 'master'

Roddi swiftlint fixes

See merge request !16
parents 54b8b5e9 3b30dab2
......@@ -5,25 +5,18 @@ excluded: # paths to ignore during linting. Takes precedence over `included`.
identifier_name:
min_length: 2 # only warning
max_length: # warning and error
warning: 40
error: 50
warning: 50
error: 60
excluded: Carthage # excluded via string
# disable those *for* *now* so that the compile step
# does not create issues for not yet fixed issues
disabled_rules:
- identifier_name
- function_parameter_count
- line_length
- force_cast
- syntactic_sugar
- implicit_getter
- control_statement
- todo
- file_length
- function_body_length
- cyclomatic_complexity
- unneeded_break_in_switch
- type_body_length
- vertical_parameter_alignment
\ No newline at end of file
......@@ -26,6 +26,8 @@
BF4952E3230AD92900A12944 /* UInt+Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF4952E2230AD92900A12944 /* UInt+Extension.swift */; };
BF647C58230C491E00DF6265 /* Card10TabBarController.swift in Sources */ = {isa = PBXBuildFile; fileRef = BF647C57230C491E00DF6265 /* Card10TabBarController.swift */; };
D4A8821222E92670E899561E /* Pods_card10badge.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7C391F1792BB7FCA2208D837 /* Pods_card10badge.framework */; };
DD01715A2310279500E5F7FA /* RGBLED.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD0171592310279500E5F7FA /* RGBLED.swift */; };
DD01715C231027DF00E5F7FA /* AboveLEDs.swift in Sources */ = {isa = PBXBuildFile; fileRef = DD01715B231027DF00E5F7FA /* AboveLEDs.swift */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
......@@ -52,6 +54,8 @@
B864A7E1B7A4A7505C7F3979 /* Pods-card10badge.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-card10badge.debug.xcconfig"; path = "Pods/Target Support Files/Pods-card10badge/Pods-card10badge.debug.xcconfig"; sourceTree = "<group>"; };
BF4952E2230AD92900A12944 /* UInt+Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "UInt+Extension.swift"; sourceTree = "<group>"; };
BF647C57230C491E00DF6265 /* Card10TabBarController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Card10TabBarController.swift; sourceTree = "<group>"; };
DD0171592310279500E5F7FA /* RGBLED.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RGBLED.swift; sourceTree = "<group>"; };
DD01715B231027DF00E5F7FA /* AboveLEDs.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AboveLEDs.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
......@@ -141,12 +145,14 @@
B4CBD21E2306D8C40064E6D7 /* Bluetooth */ = {
isa = PBXGroup;
children = (
BF4952E2230AD92900A12944 /* UInt+Extension.swift */,
B479A2072305925B007C9672 /* BluetoothManager.swift */,
B4CBD2212306DD1B0064E6D7 /* DataTransferManager.swift */,
B4CBD21F2306D8FA0064E6D7 /* ChunkedDataReader.swift */,
B4CBD22323075F8F0064E6D7 /* CRC32.swift */,
B4CBD225230762240064E6D7 /* DataExtension.swift */,
B4CBD2212306DD1B0064E6D7 /* DataTransferManager.swift */,
DD0171592310279500E5F7FA /* RGBLED.swift */,
BF4952E2230AD92900A12944 /* UInt+Extension.swift */,
DD01715B231027DF00E5F7FA /* AboveLEDs.swift */,
);
path = Bluetooth;
sourceTree = "<group>";
......@@ -299,7 +305,9 @@
B4CBD2222306DD1B0064E6D7 /* DataTransferManager.swift in Sources */,
B46C7E202309F45900B12DE4 /* HatcheryRootTableViewController.swift in Sources */,
BF4952E3230AD92900A12944 /* UInt+Extension.swift in Sources */,
DD01715C231027DF00E5F7FA /* AboveLEDs.swift in Sources */,
BF647C58230C491E00DF6265 /* Card10TabBarController.swift in Sources */,
DD01715A2310279500E5F7FA /* RGBLED.swift in Sources */,
B46C7E242309F61500B12DE4 /* HatcheryClient.swift in Sources */,
B46A7C3C230D8D2900404143 /* HatcheryRootTableViewCell.swift in Sources */,
B479A2082305925B007C9672 /* BluetoothManager.swift in Sources */,
......
//
// AboveLEDs.swift
// card10badge
//
// Created by Ruotger Deecke on 23.8.19.
// Copyright © 2019 Brechler, Philip. All rights reserved.
//
import Foundation
struct AboveLEDs {
let LEDs: [RGBLED]
public var data: Data {
assert(LEDs.count == 11)
var result = Data()
for led in LEDs {
result.append(led.data)
}
return result
}
public static func randomRGB() -> AboveLEDs {
var LEDs: [RGBLED] = []
for _ in 0 ..< 11 {
LEDs.append(RGBLED.randomRGB())
}
return AboveLEDs(LEDs: LEDs)
}
}
......@@ -9,7 +9,7 @@
import CoreBluetooth
protocol BluetoothManagerDelegate: class {
func didFindNewPeripherals(_ peripherals: Array<FoundPeripheral>?)
func didFindNewPeripherals(_ peripherals: [FoundPeripheral]?)
func didConnectToPeripheal(_ peripheral: FoundPeripheral?)
func didDisconnectFromPeripheral()
func didGetNewLightSensorData(_ data: UInt16)
......@@ -20,7 +20,7 @@ protocol BluetoothManagerDelegate: class {
// Provide default empty implementation to avoid empty boilerplate in the delegate
extension BluetoothManagerDelegate {
func didFindNewPeripherals(_ peripherals: Array<FoundPeripheral>?) {}
func didFindNewPeripherals(_ peripherals: [FoundPeripheral]?) {}
func didConnectToPeripheal(_ peripheral: FoundPeripheral?) {}
func didDisconnectFromPeripheral() {}
func didGetNewLightSensorData(_ data: UInt16) {}
......@@ -29,16 +29,6 @@ extension BluetoothManagerDelegate {
func didUpdateProgressOnFile(_ progress: Double) {}
}
struct RGBLED {
let r: UInt8
let g: UInt8
let b: UInt8
public var data: Data {
return Data([r, g, b])
}
}
public struct FoundPeripheral: Hashable {
let peripheral: CBPeripheral
let advertisementName: String?
......@@ -97,7 +87,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
let card10TXWriteCharacteristicUUID = CBUUID(string: "42230101-2342-2342-2342-234223422342")
let card10RXReadCharacteristicUUID = CBUUID(string: "42230102-2342-2342-2342-234223422342")
private(set) public var foundPeripheral: Array<FoundPeripheral>
private(set) public var foundPeripheral: [FoundPeripheral]
public var connectedPeripheral: CBPeripheral?
/// Holds BluetoothManagerDelegates weakly
......@@ -253,17 +243,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
}
/// Set's the 11 RGB leds at the top. Parameters are from left to right.
public func setLEDsAbove(a: RGBLED,
b: RGBLED,
c: RGBLED,
d: RGBLED,
e: RGBLED,
f: RGBLED,
g: RGBLED,
h: RGBLED,
i: RGBLED,
j: RGBLED,
k: RGBLED) {
public func setLEDsAbove(_ aboveLEDs: AboveLEDs) {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
guard let aboveCharacteristic = self.findCharacteristic(on: peripheral,
......@@ -273,40 +253,11 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
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),
self.connectedPeripheral?.writeValue(aboveLEDs.data,
for: aboveCharacteristic,
type: .withoutResponse)
}
private func mergeLedsAboveIntoData(a: RGBLED,
b: RGBLED,
c: RGBLED,
d: RGBLED,
e: RGBLED,
f: RGBLED,
g: RGBLED,
h: RGBLED,
i: RGBLED,
j: RGBLED,
k: RGBLED) -> Data {
var data = Data()
data.append(a.data)
data.append(b.data)
data.append(c.data)
data.append(d.data)
data.append(e.data)
data.append(f.data)
data.append(g.data)
data.append(h.data)
data.append(i.data)
data.append(j.data)
data.append(k.data)
return data
}
public func getLightSensorData() {
guard let peripheral = self.connectedPeripheral else { return } //TODO: Tell the delegate it failed?
......@@ -385,7 +336,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service in peripheral.services! {
print("found service: \(service.uuid)")
if (service.uuid.isEqual(card10ServiceUUID)) {
if service.uuid.isEqual(card10ServiceUUID) {
peripheral.discoverCharacteristics([card10TimeCharacteristic,
card10VibrateCharacteristic,
card10RocketsCharacteristic,
......@@ -399,7 +350,7 @@ class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate
card10SingleRgbLedCharacteristic,
card10LightSensorCharacteristic], for: service)
}
if (service.uuid.isEqual(card10RxTxServiceUUID)) {
if service.uuid.isEqual(card10RxTxServiceUUID) {
peripheral.discoverCharacteristics([card10TXWriteCharacteristicUUID,
card10RXReadCharacteristicUUID], for: service)
}
......
......@@ -5,9 +5,9 @@
class CRC32 {
static var table: [UInt32] = {
(0...255).map { i -> UInt32 in
(0..<8).reduce(UInt32(i), { c, _ in
(c % 2 == 0) ? (c >> 1) : (0xEDB88320 ^ (c >> 1))
(0...255).map { idx -> UInt32 in
(0..<8).reduce(UInt32(idx), { crc, _ in
(crc % 2 == 0) ? (crc >> 1) : (0xEDB88320 ^ (crc >> 1))
})
}
}()
......
......@@ -9,57 +9,43 @@ import UIKit
extension Data {
var uint8: UInt8 {
get {
var number: UInt8 = 0
self.copyBytes(to: &number, count: MemoryLayout<UInt8>.size)
return number
}
var number: UInt8 = 0
self.copyBytes(to: &number, count: MemoryLayout<UInt8>.size)
return number
}
var uint16: UInt16 {
get {
let i16array = self.withUnsafeBytes {
UnsafeBufferPointer<UInt16>(start: $0, count: self.count/2).map(UInt16.init(littleEndian:))
}
return i16array[0]
let i16array = self.withUnsafeBytes {
UnsafeBufferPointer<UInt16>(start: $0, count: self.count/2).map(UInt16.init(littleEndian:))
}
return i16array[0]
}
var uint32: UInt32 {
get {
let i32array = self.withUnsafeBytes {
UnsafeBufferPointer<UInt32>(start: $0, count: self.count/2).map(UInt32.init(littleEndian:))
}
return i32array[0]
let i32array = self.withUnsafeBytes {
UnsafeBufferPointer<UInt32>(start: $0, count: self.count/2).map(UInt32.init(littleEndian:))
}
return i32array[0]
}
var uint64: UInt64 {
get {
let i64array = self.withUnsafeBytes {
UnsafeBufferPointer<UInt64>(start: $0, count: self.count/2).map(UInt64.init(littleEndian:))
}
return i64array[0]
let i64array = self.withUnsafeBytes {
UnsafeBufferPointer<UInt64>(start: $0, count: self.count/2).map(UInt64.init(littleEndian:))
}
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)
return NSUUID(uuidBytes: bytes)
}
var bytes = [UInt8](repeating: 0, count: self.count)
self.copyBytes(to: &bytes, count: self.count * MemoryLayout<UInt32>.size)
return NSUUID(uuidBytes: bytes)
}
var stringASCII: String? {
get {
return NSString(data: self, encoding: String.Encoding.ascii.rawValue) as String?
}
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?
}
return NSString(data: self, encoding: String.Encoding.utf8.rawValue) as String?
}
struct HexEncodingOptions: OptionSet {
......
......@@ -8,6 +8,8 @@
import CoreBluetooth
// To make those identifiers look more C-lick we'll make an exception here
// swiftlint:disable identifier_name
enum TransferState {
case IDLE
case START_SENT
......@@ -26,6 +28,7 @@ enum PackageType: String {
case ERROR = "e"
case ERROR_ACK = "E"
}
// swiftlint:enable identifier_name
protocol DataTransferManagerDelegate: class {
func wantsToSendPackage(_ package: Data)
......@@ -62,23 +65,24 @@ class DataTransferManager: NSObject {
switch packageType {
case .START?:
break
case .START_ACK?:
self.transferState = .READY_TO_SEND
let chunkToSend = self.chunkedReader?.nextChunk()
guard chunkToSend!.count > 0 else { self.sendPackage(type: .ERROR, payload: nil, offset: 0); return }
self.currentChunkToSend = chunkToSend
sendPackage(type: .CHUNK, payload: chunkToSend, offset: 0)
break
case .CHUNK?:
break
case .CHUNK_ACK?:
self.transferState = .CHUNK_SENT
// calculate CRC and send new chunk
let range: Range<Data.Index> = 0..<1
let crc = package.subdata(in: range)
updateProgress()
if (checkChunkWithResponse(crc)) {
if (currentChunkToSend!.count < chunkedReader!.packageSize) {
if checkChunkWithResponse(crc) {
if currentChunkToSend!.count < chunkedReader!.packageSize {
// The last package arrived, we are done here
sendPackage(type: .FINISH, payload: nil, offset: 0)
break
......@@ -88,34 +92,36 @@ class DataTransferManager: NSObject {
self.currentChunkToSend = chunkToSend
sendPackage(type: .CHUNK, payload: chunkToSend, offset: self.chunkedReader!.currentOffset-20)
}
} else if (retryCount < 9) {
} else if retryCount < 9 {
sendPackage(type: .CHUNK, payload: self.currentChunkToSend, offset: self.chunkedReader!.currentOffset-20)
retryCount += 1
} else {
self.sendPackage(type: .ERROR, payload: nil,offset: 0)
}
break
case .FINISH?:
break
case .FINISH_ACK?:
// finished, cleanup
self.transferState = .FINISH_SENT
self.chunkedReader = nil
self.dataToSend = nil
self.transferState = .IDLE
break
case .ERROR?:
// fucked up, send error ack
print("Error from card10, message ",String(data:package,encoding: .ascii)!)
self.sendPackage(type: .ERROR_ACK, payload: nil, offset: 0)
delegate?.didFailToSendFile()
break
case .ERROR_ACK?:
// device knows we aborted
self.chunkedReader = nil
self.dataToSend = nil
self.transferState = .IDLE
break
default:
print("Broken Package ", firstChar)
}
......@@ -141,31 +147,33 @@ class DataTransferManager: NSObject {
payloadToSend = PackageType.START.rawValue.data(using: .ascii)
payloadToSend?.append(payload!)
lastPackageSentAt = NSDate.init().timeIntervalSinceNow
break
case .START_ACK:
break
case .CHUNK:
payloadToSend = PackageType.CHUNK.rawValue.data(using: .ascii)
var int = UInt32(bigEndian: UInt32(offset))
payloadToSend?.append(Data(bytes: &int, count: MemoryLayout.size(ofValue: UInt32())))
payloadToSend?.append(payload!)
lastPackageSentAt = NSDate.init().timeIntervalSinceNow
break
case .CHUNK_ACK:
break
case .FINISH:
payloadToSend = PackageType.FINISH.rawValue.data(using: .ascii)
break
case .FINISH_ACK:
break
case .ERROR:
payloadToSend = PackageType.ERROR.rawValue.data(using: .ascii)
delegate?.didFailToSendFile()
break
case .ERROR_ACK:
payloadToSend = PackageType.ERROR_ACK.rawValue.data(using: .ascii)
delegate?.didFailToSendFile()
break
}
if payloadToSend != nil {
delegate?.wantsToSendPackage(payloadToSend!)
......@@ -180,7 +188,7 @@ class DataTransferManager: NSObject {
let responseInUInt32 = response.withUnsafeBytes{ $0.load(as: UInt8.self) }
let chunkInUInt8 = [UInt8](self.currentChunkToSend!)
let checksum = CRC32.checksum(bytes: chunkInUInt8)
if (responseInUInt32 == checksum) {
if responseInUInt32 == checksum {
return true
}
return false
......
//
// RGBLED.swift
// card10badge
//
// Created by Ruotger Deecke on 23.8.19.
// Copyright © 2019 Brechler, Philip. All rights reserved.
//
import Foundation
struct RGBLED {
let red: UInt8
let green: UInt8
let blue: UInt8
public var data: Data {
return Data([red, green, blue])
}
public static func randomRGB() -> RGBLED {
var red: UInt8 = 0
var green: UInt8 = 0
var blue: UInt8 = 0
while UInt64(red) + UInt64(green) + UInt64(blue) == UInt64(0) {
red = UInt8.random(in: 0..<3) * 127 // 128 would overflow UInt 😬
green = UInt8.random(in: 0..<3) * 127
blue = UInt8.random(in: 0..<3) * 127
}
return RGBLED(red: red, green: green, blue: blue)
}
}
......@@ -11,7 +11,7 @@ import CoreBluetooth
public class Card10TabBarController: UITabBarController, UITabBarControllerDelegate, BluetoothManagerDelegate {
var allViewControllers: Array<UIViewController>? = []
var allViewControllers: [UIViewController]? = []
public override func viewDidLoad() {
super.viewDidLoad()
......
......@@ -126,7 +126,7 @@ extension ConnectedViewController {
extension ConnectedViewController {
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
if (controller.documentPickerMode == .import) {
if controller.documentPickerMode == .import {
for url in urls {
do {
let data = try Data(contentsOf: url as URL)
......@@ -179,35 +179,12 @@ extension ConnectedViewController {
}
func setRandomBackgroundLedColors() {
BluetoothManager.sharedInstance().setBackgroundLEDs(topLeft: randomRGB(),
topRight: randomRGB(),
bottomRight: randomRGB(),
bottomLeft: randomRGB())
BluetoothManager.sharedInstance().setLEDsAbove(a: randomRGB(),
b: randomRGB(),
c: randomRGB(),
d: randomRGB(),
e: randomRGB(),
f: randomRGB(),
g: randomRGB(),
h: randomRGB(),
i: randomRGB(),
j: randomRGB(),
k: randomRGB())
}
fileprivate func randomRGB() -> RGBLED {
var r: UInt8 = 0
var g: UInt8 = 0
var b: UInt8 = 0
while (UInt64(r) + UInt64(g) + UInt64(b) == UInt64(0)) {
r = UInt8.random(in: 0..<3) * 127 // 128 would overflow UInt 😬
g = UInt8.random(in: 0..<3) * 127
b = UInt8.random(in: 0..<3) * 127
}
return RGBLED(r: r, g: g, b: b)
BluetoothManager.sharedInstance().setBackgroundLEDs(topLeft: RGBLED.randomRGB(),
topRight: RGBLED.randomRGB(),
bottomRight: RGBLED.randomRGB(),
bottomLeft: RGBLED.randomRGB())
BluetoothManager.sharedInstance().setLEDsAbove(AboveLEDs.randomRGB())
}
}
......
......@@ -27,7 +27,7 @@ extension HatcheryClientDelegate {
class HatcheryClient: NSObject, URLSessionDelegate {
let hatcheryBaseURL: URL = URL(string: "https://badge.team/")!
private(set) public var loadedEggs: Array<Array<HatcheryEgg>> = []
private(set) public var loadedEggs: [[HatcheryEgg]] = []
weak var delegate: HatcheryClientDelegate?
......@@ -59,8 +59,8 @@ class HatcheryClient: NSObject, URLSessionDelegate {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
if let jsonArray = json as? [Any] {
self.loadedEggs.removeAll()
var loadedEggsUncategorized: Array<HatcheryEgg> = []
for case let dictionary as Dictionary<String, Any> in jsonArray {
var loadedEggsUncategorized: [HatcheryEgg] = []
for case let dictionary as [String: Any] in jsonArray {
loadedEggsUncategorized.append(HatcheryEgg.init(dictionary: dictionary))
}
......@@ -69,7 +69,7 @@ class HatcheryClient: NSObject, URLSessionDelegate {
uniqueCategories = uniqueCategories.sorted { $0.lowercased() < $1.lowercased() }
for category in uniqueCategories {
var eggsForCategory: Array<HatcheryEgg> = []
var eggsForCategory: [HatcheryEgg] = []
for egg in loadedEggsUncategorized {
if egg.category == category {
eggsForCategory.append(egg)
......@@ -109,9 +109,9 @@ class HatcheryClient: NSObject, URLSessionDelegate {
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
if let eggDict = json as? Dictionary<String, Any> {
if let releases = eggDict["releases"] as? Dictionary<String, Any> {
if let latestRelease = releases[revision] as? Array<Dictionary<String, String>> {
if let eggDict = json as? [String: Any] {
if let releases = eggDict["releases"] as? [String: Any] {
if let latestRelease = releases[revision] as? [[String: String]] {
let releaseURL = latestRelease[0]["url"]