diff --git a/CovidSafe.xcodeproj/project.pbxproj b/CovidSafe.xcodeproj/project.pbxproj index bf1e0ee..edfdb97 100644 --- a/CovidSafe.xcodeproj/project.pbxproj +++ b/CovidSafe.xcodeproj/project.pbxproj @@ -36,6 +36,38 @@ 3A8951FDED310D7ABA54259E /* Pods_CovidSafe.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 34E9EB96EA6E42A571E73C8E /* Pods_CovidSafe.framework */; }; 5904A5C22462471A008C8012 /* EncounterV1toV2.xcmappingmodel in Sources */ = {isa = PBXBuildFile; fileRef = 5904A5C12462471A008C8012 /* EncounterV1toV2.xcmappingmodel */; }; 5904A5C32462471A008C8012 /* EncounterV1toV2.xcmappingmodel in Sources */ = {isa = PBXBuildFile; fileRef = 5904A5C12462471A008C8012 /* EncounterV1toV2.xcmappingmodel */; }; + 5905460C2543E0F5009B82AD /* BLESensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545EE2543E0F5009B82AD /* BLESensor.swift */; }; + 5905460D2543E0F5009B82AD /* BLESensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545EE2543E0F5009B82AD /* BLESensor.swift */; }; + 5905460E2543E0F5009B82AD /* BLEDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545EF2543E0F5009B82AD /* BLEDatabase.swift */; }; + 5905460F2543E0F5009B82AD /* BLEDatabase.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545EF2543E0F5009B82AD /* BLEDatabase.swift */; }; + 590546102543E0F5009B82AD /* BLEUtilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F02543E0F5009B82AD /* BLEUtilities.swift */; }; + 590546112543E0F5009B82AD /* BLEUtilities.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F02543E0F5009B82AD /* BLEUtilities.swift */; }; + 590546122543E0F6009B82AD /* BLETransmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F12543E0F5009B82AD /* BLETransmitter.swift */; }; + 590546132543E0F6009B82AD /* BLETransmitter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F12543E0F5009B82AD /* BLETransmitter.swift */; }; + 590546142543E0F6009B82AD /* BLEReceiver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F22543E0F5009B82AD /* BLEReceiver.swift */; }; + 590546152543E0F6009B82AD /* BLEReceiver.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F22543E0F5009B82AD /* BLEReceiver.swift */; }; + 590546162543E0F6009B82AD /* AwakeSensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F42543E0F5009B82AD /* AwakeSensor.swift */; }; + 590546172543E0F6009B82AD /* AwakeSensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F42543E0F5009B82AD /* AwakeSensor.swift */; }; + 590546182543E0F6009B82AD /* Sensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F52543E0F5009B82AD /* Sensor.swift */; }; + 590546192543E0F6009B82AD /* Sensor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590545F52543E0F5009B82AD /* Sensor.swift */; }; + 590546282543E0F6009B82AD /* SensorArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546012543E0F5009B82AD /* SensorArray.swift */; }; + 590546292543E0F6009B82AD /* SensorArray.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546012543E0F5009B82AD /* SensorArray.swift */; }; + 5905462A2543E0F6009B82AD /* PayloadDataSupplier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546022543E0F5009B82AD /* PayloadDataSupplier.swift */; }; + 5905462B2543E0F6009B82AD /* PayloadDataSupplier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546022543E0F5009B82AD /* PayloadDataSupplier.swift */; }; + 5905462C2543E0F6009B82AD /* TextFile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546042543E0F5009B82AD /* TextFile.swift */; }; + 5905462D2543E0F6009B82AD /* TextFile.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546042543E0F5009B82AD /* TextFile.swift */; }; + 5905462E2543E0F6009B82AD /* BatteryLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546052543E0F5009B82AD /* BatteryLog.swift */; }; + 5905462F2543E0F6009B82AD /* BatteryLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546052543E0F5009B82AD /* BatteryLog.swift */; }; + 590546302543E0F6009B82AD /* DetectionLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546062543E0F5009B82AD /* DetectionLog.swift */; }; + 590546312543E0F6009B82AD /* DetectionLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546062543E0F5009B82AD /* DetectionLog.swift */; }; + 590546322543E0F6009B82AD /* SensorLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546072543E0F5009B82AD /* SensorLogger.swift */; }; + 590546332543E0F6009B82AD /* SensorLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546072543E0F5009B82AD /* SensorLogger.swift */; }; + 590546342543E0F6009B82AD /* ContactLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546082543E0F5009B82AD /* ContactLog.swift */; }; + 590546352543E0F6009B82AD /* ContactLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546082543E0F5009B82AD /* ContactLog.swift */; }; + 590546362543E0F6009B82AD /* StatisticsLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546092543E0F5009B82AD /* StatisticsLog.swift */; }; + 590546372543E0F6009B82AD /* StatisticsLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 590546092543E0F5009B82AD /* StatisticsLog.swift */; }; + 590546382543E0F6009B82AD /* SensorDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5905460A2543E0F5009B82AD /* SensorDelegate.swift */; }; + 590546392543E0F6009B82AD /* SensorDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5905460A2543E0F5009B82AD /* SensorDelegate.swift */; }; 590888AF2431B9E3008C9B9F /* UITextView + Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B55E1912430760500C9E798 /* UITextView + Extensions.swift */; }; 590888B02431B9E7008C9B9F /* UIColor + Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0BC141AD2430685800399FA8 /* UIColor + Extensions.swift */; }; 590888B12431B9EB008C9B9F /* Question3ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1B86119424303F5E00EA4B6B /* Question3ViewController.swift */; }; @@ -96,6 +128,7 @@ 59F25D69245B917A002A7ED8 /* Spinner_home.json in Resources */ = {isa = PBXBuildFile; fileRef = 59F25D68245B917A002A7ED8 /* Spinner_home.json */; }; 59F25D6A245B917A002A7ED8 /* Spinner_home.json in Resources */ = {isa = PBXBuildFile; fileRef = 59F25D68245B917A002A7ED8 /* Spinner_home.json */; }; 59F25D6F245BED80002A7ED8 /* Debug.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 59F25D6E245BED80002A7ED8 /* Debug.storyboard */; }; + 5ADBDDED2579A7DC0078872F /* EncounterMessageManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D5F83AC23F023F600770DEF /* EncounterMessageManager.swift */; }; 5B04074124BC0CEA00FAAFD0 /* MessageAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B04074024BC0CEA00FAAFD0 /* MessageAPI.swift */; }; 5B04074224BC0CEA00FAAFD0 /* MessageAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B04074024BC0CEA00FAAFD0 /* MessageAPI.swift */; }; 5B110C10248F275B00B68291 /* SelectCountryViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5B110C0F248F275A00B68291 /* SelectCountryViewController.swift */; }; @@ -167,12 +200,11 @@ 5B92D67F243018040049877B /* PogoInstructionsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F19B4DC23F565850071A11E /* PogoInstructionsViewController.swift */; }; 5B92D680243018040049877B /* CodeInputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30E91BEA23EFEA0B002D592A /* CodeInputView.swift */; }; 5B92D681243018040049877B /* EncounterRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30BE1CAE23F1349F005DCE4F /* EncounterRecord.swift */; }; - 5B92D683243018040049877B /* OnboardingStep2bViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C58D817623F169DB00345771 /* OnboardingStep2bViewController.swift */; }; + 5B92D683243018040049877B /* RegistrationSuccessViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C58D817623F169DB00345771 /* RegistrationSuccessViewController.swift */; }; 5B92D684243018040049877B /* AsyncAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2F9242DF1B000DC9E2A /* AsyncAction.swift */; }; 5B92D685243018040049877B /* UILabelExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B60F8BE3242659810007A641 /* UILabelExtension.swift */; }; 5B92D686243018040049877B /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D3A23DCB03B00FD4AB0 /* AppDelegate.swift */; }; 5B92D687243018040049877B /* PhoneNumberViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D8B248A23F146C500DBB74D /* PhoneNumberViewController.swift */; }; - 5B92D688243018040049877B /* BluetraceUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DC7B8D2242B8D87008E1715 /* BluetraceUtils.swift */; }; 5B92D689243018040049877B /* NewFeedbackFlowController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D302242DF1B000DC9E2A /* NewFeedbackFlowController.swift */; }; 5B92D68A243018040049877B /* Outcome.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2EE242DF1B000DC9E2A /* Outcome.swift */; }; 5B92D68B243018040049877B /* Encounter+EncounterRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 30BE1CB023F134D0005DCE4F /* Encounter+EncounterRecord.swift */; }; @@ -184,9 +216,8 @@ 5B92D691243018040049877B /* RespondToAuthChallengeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C0242F047F007E893B /* RespondToAuthChallengeAPI.swift */; }; 5B92D692243018040049877B /* BluetraceManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D269C0C23E2958F00ADF2DE /* BluetraceManager.swift */; }; 5B92D693243018040049877B /* UIColor+Hex.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2F0242DF1B000DC9E2A /* UIColor+Hex.swift */; }; - 5B92D694243018040049877B /* OnboardingStep1ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5046D5B23EF18600046E96D /* OnboardingStep1ViewController.swift */; }; + 5B92D694243018040049877B /* RegistrationIntroViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5046D5B23EF18600046E96D /* RegistrationIntroViewController.swift */; }; 5B92D695243018040049877B /* DeviceInfoExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2F5242DF1B000DC9E2A /* DeviceInfoExtension.swift */; }; - 5B92D697243018040049877B /* PeripheralController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D5223DD4CA400FD4AB0 /* PeripheralController.swift */; }; 5B92D698243018040049877B /* SendFeedbackAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2FA242DF1B000DC9E2A /* SendFeedbackAction.swift */; }; 5B92D699243018040049877B /* UITextViewFixed.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5D209FB23F4476F007233BE /* UITextViewFixed.swift */; }; 5B92D69A243018040049877B /* GradientButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = C585C83A23EEB99B0061B7C6 /* GradientButton.swift */; }; @@ -198,9 +229,8 @@ 5B92D6A1243018040049877B /* AlertController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2F6242DF1B000DC9E2A /* AlertController.swift */; }; 5B92D6A2243018040049877B /* GetTempIdAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C2242F0FE9007E893B /* GetTempIdAPI.swift */; }; 5B92D6A3243018040049877B /* PhoneValidationAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BFFD94A242EC120003AEF4F /* PhoneValidationAPI.swift */; }; - 5B92D6A4243018040049877B /* CentralController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D4E23DCB05600FD4AB0 /* CentralController.swift */; }; 5B92D6A5243018040049877B /* UIWindow+TopMost.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D305242DF1B000DC9E2A /* UIWindow+TopMost.swift */; }; - 5B92D6A6243018040049877B /* OnboardingStep1bViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8DEB6812423AE2E00D99925 /* OnboardingStep1bViewController.swift */; }; + 5B92D6A6243018040049877B /* HowItWorksViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8DEB6812423AE2E00D99925 /* HowItWorksViewController.swift */; }; 5B92D6A7243018040049877B /* OnboardingStep4ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56CF43E23F18A15006B05B0 /* OnboardingStep4ViewController.swift */; }; 5B92D6A8243018040049877B /* PresentFeedbackExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2FD242DF1B000DC9E2A /* PresentFeedbackExtensions.swift */; }; 5B92D6A9243018040049877B /* Errors.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D304242DF1B000DC9E2A /* Errors.swift */; }; @@ -210,7 +240,7 @@ 5B92D6AD243018040049877B /* FeedbackSettings.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D301242DF1B000DC9E2A /* FeedbackSettings.swift */; }; 5B92D6AE243018040049877B /* JMCTargetJSONFromDisk.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2EF242DF1B000DC9E2A /* JMCTargetJSONFromDisk.swift */; }; 5B92D6B0243018040049877B /* Action.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D309242DF1B000DC9E2A /* Action.swift */; }; - 5B92D6B1243018040049877B /* OnboardingStep2ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2F0BA123EFFF75006D7404 /* OnboardingStep2ViewController.swift */; }; + 5B92D6B1243018040049877B /* AppSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2F0BA123EFFF75006D7404 /* AppSettingsViewController.swift */; }; 5B92D6B2243018040049877B /* HTTPPostFeedbackAction.swift in Sources */ = {isa = PBXBuildFile; fileRef = A767D2F4242DF1B000DC9E2A /* HTTPPostFeedbackAction.swift */; }; 5B92D6B3243018040049877B /* PushNotificationConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F36305E23F7F81400CC6E1D /* PushNotificationConstants.swift */; }; 5B92D6B4243018040049877B /* UIViewController + Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B615C5A823FA403400345969 /* UIViewController + Extension.swift */; }; @@ -242,6 +272,11 @@ 5BA33A7E24B55E7D00D12515 /* BLELogRecord.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BA33A7D24B55E7D00D12515 /* BLELogRecord.swift */; }; 5BA33A8024B55EF200D12515 /* BLELogDB.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BA33A7F24B55EF200D12515 /* BLELogDB.swift */; }; 5BA33A8224B5602500D12515 /* BLELogRecord+BLELogSave.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BA33A8124B5602500D12515 /* BLELogRecord+BLELogSave.swift */; }; + 5BBC571D25526F99005E90AA /* staging-Info.plist in Resources */ = {isa = PBXBuildFile; fileRef = 5BBC571C25526F99005E90AA /* staging-Info.plist */; }; + 5BBE61B125633B6D00B8C983 /* CSGenericContentView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 5BBE61B025633B6D00B8C983 /* CSGenericContentView.xib */; }; + 5BBE61B225633B6D00B8C983 /* CSGenericContentView.xib in Resources */ = {isa = PBXBuildFile; fileRef = 5BBE61B025633B6D00B8C983 /* CSGenericContentView.xib */; }; + 5BBE61B725633E8D00B8C983 /* CSGenericViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BBE61B625633E8D00B8C983 /* CSGenericViewController.swift */; }; + 5BBE61B825633E8D00B8C983 /* CSGenericViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BBE61B625633E8D00B8C983 /* CSGenericViewController.swift */; }; 5BD3EE8324330E1A0004A007 /* UploadDataStep2VC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BD3EE8224330E1A0004A007 /* UploadDataStep2VC.swift */; }; 5BD3EE84243313450004A007 /* UploadDataStep2VC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BD3EE8224330E1A0004A007 /* UploadDataStep2VC.swift */; }; 5BED1E3A24A96D1C0066C4D2 /* LaunchScreen_ar.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5BED1E3924A96D1C0066C4D2 /* LaunchScreen_ar.storyboard */; }; @@ -257,22 +292,18 @@ 5BFFD94B242EC120003AEF4F /* PhoneValidationAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5BFFD94A242EC120003AEF4F /* PhoneValidationAPI.swift */; }; 5D269C0B23E22CC400ADF2DE /* DeviceIdentifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D269C0A23E22CC400ADF2DE /* DeviceIdentifier.swift */; }; 5D269C0D23E2958F00ADF2DE /* BluetraceManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D269C0C23E2958F00ADF2DE /* BluetraceManager.swift */; }; - 5D5F83AD23F023F600770DEF /* EncounterMessageManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D5F83AC23F023F600770DEF /* EncounterMessageManager.swift */; }; 5D5F83B023F045A800770DEF /* HomeViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D5F83AF23F045A800770DEF /* HomeViewController.swift */; }; 5D8B248B23F146C500DBB74D /* PhoneNumberViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D8B248A23F146C500DBB74D /* PhoneNumberViewController.swift */; }; 5D8DD06123E319B300E097EF /* Encounter+CoreDataClass.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D8DD05F23E319B300E097EF /* Encounter+CoreDataClass.swift */; }; 5D8DD06223E319B300E097EF /* Encounter+CoreDataProperties.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D8DD06023E319B300E097EF /* Encounter+CoreDataProperties.swift */; }; 5D8DD06723E329A200E097EF /* tracer.xcdatamodeld in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D7723DE141700FD4AB0 /* tracer.xcdatamodeld */; }; 5DC7B8D1242B8536008E1715 /* BluetraceConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DC7B8D0242B8536008E1715 /* BluetraceConfig.swift */; }; - 5DC7B8D3242B8D87008E1715 /* BluetraceUtils.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DC7B8D2242B8D87008E1715 /* BluetraceUtils.swift */; }; 5DD41D3B23DCB03B00FD4AB0 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D3A23DCB03B00FD4AB0 /* AppDelegate.swift */; }; 5DD41D4223DCB03B00FD4AB0 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5DD41D4023DCB03B00FD4AB0 /* Main.storyboard */; }; 5DD41D4423DCB03D00FD4AB0 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 5DD41D4323DCB03D00FD4AB0 /* Assets.xcassets */; }; 5DD41D4723DCB03D00FD4AB0 /* LaunchScreen_en.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 5DD41D4523DCB03D00FD4AB0 /* LaunchScreen_en.storyboard */; }; - 5DD41D4F23DCB05600FD4AB0 /* CentralController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D4E23DCB05600FD4AB0 /* CentralController.swift */; }; - 5DD41D5323DD4CA400FD4AB0 /* PeripheralController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5DD41D5223DD4CA400FD4AB0 /* PeripheralController.swift */; }; 7F19B4DD23F565850071A11E /* PogoInstructionsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F19B4DC23F565850071A11E /* PogoInstructionsViewController.swift */; }; - 7F2F0BA223EFFF75006D7404 /* OnboardingStep2ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2F0BA123EFFF75006D7404 /* OnboardingStep2ViewController.swift */; }; + 7F2F0BA223EFFF75006D7404 /* AppSettingsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F2F0BA123EFFF75006D7404 /* AppSettingsViewController.swift */; }; 7F36305F23F7F81400CC6E1D /* PushNotificationConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7F36305E23F7F81400CC6E1D /* PushNotificationConstants.swift */; }; 7FACD53A23F25A9A0042A33A /* InitialScreenViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FACD53923F25A9A0042A33A /* InitialScreenViewController.swift */; }; 7FEC361523F16A1E00127AFB /* UIViewExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 7FEC361423F16A1E00127AFB /* UIViewExtension.swift */; }; @@ -307,19 +338,19 @@ B60F8BE4242659810007A641 /* UILabelExtension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B60F8BE3242659810007A641 /* UILabelExtension.swift */; }; B615C5A723F8EB1700345969 /* UIProgressView + Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B615C5A623F8EB1700345969 /* UIProgressView + Extension.swift */; }; B615C5A923FA403500345969 /* UIViewController + Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = B615C5A823FA403400345969 /* UIViewController + Extension.swift */; }; - C5046D5C23EF18600046E96D /* OnboardingStep1ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5046D5B23EF18600046E96D /* OnboardingStep1ViewController.swift */; }; + C5046D5C23EF18600046E96D /* RegistrationIntroViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5046D5B23EF18600046E96D /* RegistrationIntroViewController.swift */; }; C56CF43F23F18A15006B05B0 /* OnboardingStep4ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C56CF43E23F18A15006B05B0 /* OnboardingStep4ViewController.swift */; }; C585C83B23EEB99B0061B7C6 /* GradientButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = C585C83A23EEB99B0061B7C6 /* GradientButton.swift */; }; - C58D817723F169DB00345771 /* OnboardingStep2bViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C58D817623F169DB00345771 /* OnboardingStep2bViewController.swift */; }; + C58D817723F169DB00345771 /* RegistrationSuccessViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = C58D817623F169DB00345771 /* RegistrationSuccessViewController.swift */; }; C5D209FC23F4476F007233BE /* UITextViewFixed.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5D209FB23F4476F007233BE /* UITextViewFixed.swift */; }; - D8DEB6822423AE2E00D99925 /* OnboardingStep1bViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8DEB6812423AE2E00D99925 /* OnboardingStep1bViewController.swift */; }; + D8DEB6822423AE2E00D99925 /* HowItWorksViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8DEB6812423AE2E00D99925 /* HowItWorksViewController.swift */; }; D8EB201B23FA722D001C60EC /* HelpNavController.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8EB201A23FA722D001C60EC /* HelpNavController.swift */; }; D8EB201D23FBE216001C60EC /* help_center_article_style.css in Resources */ = {isa = PBXBuildFile; fileRef = D8EB201C23FBE216001C60EC /* help_center_article_style.css */; }; F4992D5F7DAE4B13FF4BB47D /* Pods_CovidSafe_staging.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = FFB86126400FA51506E1B416 /* Pods_CovidSafe_staging.framework */; }; FB12C4C1242F0480007E893B /* RespondToAuthChallengeAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C0242F047F007E893B /* RespondToAuthChallengeAPI.swift */; }; FB12C4C3242F0FE9007E893B /* GetTempIdAPI.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C2242F0FE9007E893B /* GetTempIdAPI.swift */; }; - FB12C4C524304AF0007E893B /* OnboardingStep1aViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C424304AF0007E893B /* OnboardingStep1aViewController.swift */; }; - FBBBFCE82430A933002B174D /* OnboardingStep1aViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C424304AF0007E893B /* OnboardingStep1aViewController.swift */; }; + FB12C4C524304AF0007E893B /* PrivacyPolicyViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C424304AF0007E893B /* PrivacyPolicyViewController.swift */; }; + FBBBFCE82430A933002B174D /* PrivacyPolicyViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FB12C4C424304AF0007E893B /* PrivacyPolicyViewController.swift */; }; /* End PBXBuildFile section */ /* Begin PBXFileReference section */ @@ -353,6 +384,23 @@ 46A5730925DA6B664DFE9546 /* Pods-CovidSafe-staging.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CovidSafe-staging.debug.xcconfig"; path = "Target Support Files/Pods-CovidSafe-staging/Pods-CovidSafe-staging.debug.xcconfig"; sourceTree = ""; }; 49A22E09D113DF058C94C6E6 /* Pods-CovidSafe-staging.covid-staging.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CovidSafe-staging.covid-staging.xcconfig"; path = "Target Support Files/Pods-CovidSafe-staging/Pods-CovidSafe-staging.covid-staging.xcconfig"; sourceTree = ""; }; 5904A5C12462471A008C8012 /* EncounterV1toV2.xcmappingmodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcmappingmodel; path = EncounterV1toV2.xcmappingmodel; sourceTree = ""; }; + 590545EE2543E0F5009B82AD /* BLESensor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLESensor.swift; sourceTree = ""; }; + 590545EF2543E0F5009B82AD /* BLEDatabase.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLEDatabase.swift; sourceTree = ""; }; + 590545F02543E0F5009B82AD /* BLEUtilities.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLEUtilities.swift; sourceTree = ""; }; + 590545F12543E0F5009B82AD /* BLETransmitter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLETransmitter.swift; sourceTree = ""; }; + 590545F22543E0F5009B82AD /* BLEReceiver.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLEReceiver.swift; sourceTree = ""; }; + 590545F42543E0F5009B82AD /* AwakeSensor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AwakeSensor.swift; sourceTree = ""; }; + 590545F52543E0F5009B82AD /* Sensor.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Sensor.swift; sourceTree = ""; }; + 590546012543E0F5009B82AD /* SensorArray.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SensorArray.swift; sourceTree = ""; }; + 590546022543E0F5009B82AD /* PayloadDataSupplier.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PayloadDataSupplier.swift; sourceTree = ""; }; + 590546042543E0F5009B82AD /* TextFile.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TextFile.swift; sourceTree = ""; }; + 590546052543E0F5009B82AD /* BatteryLog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BatteryLog.swift; sourceTree = ""; }; + 590546062543E0F5009B82AD /* DetectionLog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DetectionLog.swift; sourceTree = ""; }; + 590546072543E0F5009B82AD /* SensorLogger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SensorLogger.swift; sourceTree = ""; }; + 590546082543E0F5009B82AD /* ContactLog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ContactLog.swift; sourceTree = ""; }; + 590546092543E0F5009B82AD /* StatisticsLog.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = StatisticsLog.swift; sourceTree = ""; }; + 5905460A2543E0F5009B82AD /* SensorDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SensorDelegate.swift; sourceTree = ""; }; + 5905460B2543E0F5009B82AD /* herald.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = herald.h; sourceTree = ""; }; 5909E4AA245043C400D41C26 /* CovidPersistentContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CovidPersistentContainer.swift; sourceTree = ""; }; 592CBB7F2441A583001FFCE9 /* PersonalDetailsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PersonalDetailsViewController.swift; sourceTree = ""; }; 59490B61245FE22C00C9802B /* ModelV2.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = ModelV2.xcdatamodel; sourceTree = ""; }; @@ -432,6 +480,9 @@ 5BA33A7D24B55E7D00D12515 /* BLELogRecord.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLELogRecord.swift; sourceTree = ""; }; 5BA33A7F24B55EF200D12515 /* BLELogDB.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = BLELogDB.swift; sourceTree = ""; }; 5BA33A8124B5602500D12515 /* BLELogRecord+BLELogSave.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "BLELogRecord+BLELogSave.swift"; sourceTree = ""; }; + 5BBC571C25526F99005E90AA /* staging-Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = "staging-Info.plist"; sourceTree = ""; }; + 5BBE61B025633B6D00B8C983 /* CSGenericContentView.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = CSGenericContentView.xib; sourceTree = ""; }; + 5BBE61B625633E8D00B8C983 /* CSGenericViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CSGenericViewController.swift; sourceTree = ""; }; 5BD3EE8224330E1A0004A007 /* UploadDataStep2VC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = UploadDataStep2VC.swift; sourceTree = ""; }; 5BED1E2F24A95ECB0066C4D2 /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/Localizable.strings; sourceTree = ""; }; 5BED1E3024A95ECB0066C4D2 /* ar */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = ar; path = ar.lproj/InfoPlist.strings; sourceTree = ""; }; @@ -460,17 +511,14 @@ 5D8DD05F23E319B300E097EF /* Encounter+CoreDataClass.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Encounter+CoreDataClass.swift"; sourceTree = ""; }; 5D8DD06023E319B300E097EF /* Encounter+CoreDataProperties.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Encounter+CoreDataProperties.swift"; sourceTree = ""; }; 5DC7B8D0242B8536008E1715 /* BluetraceConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BluetraceConfig.swift; sourceTree = ""; }; - 5DC7B8D2242B8D87008E1715 /* BluetraceUtils.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BluetraceUtils.swift; sourceTree = ""; }; 5DD41D3723DCB03B00FD4AB0 /* COVIDSafe.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = COVIDSafe.app; sourceTree = BUILT_PRODUCTS_DIR; }; 5DD41D3A23DCB03B00FD4AB0 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; 5DD41D4323DCB03D00FD4AB0 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 5DD41D4823DCB03D00FD4AB0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; - 5DD41D4E23DCB05600FD4AB0 /* CentralController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CentralController.swift; sourceTree = ""; }; - 5DD41D5223DD4CA400FD4AB0 /* PeripheralController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PeripheralController.swift; sourceTree = ""; }; 5DD41D7823DE141700FD4AB0 /* Model.xcdatamodel */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcdatamodel; path = Model.xcdatamodel; sourceTree = ""; }; 5DDB85EA23EE39C000B186BC /* Project Bluetrace.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "Project Bluetrace.entitlements"; sourceTree = ""; }; 7F19B4DC23F565850071A11E /* PogoInstructionsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PogoInstructionsViewController.swift; sourceTree = ""; }; - 7F2F0BA123EFFF75006D7404 /* OnboardingStep2ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingStep2ViewController.swift; sourceTree = ""; }; + 7F2F0BA123EFFF75006D7404 /* AppSettingsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppSettingsViewController.swift; sourceTree = ""; }; 7F36305E23F7F81400CC6E1D /* PushNotificationConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PushNotificationConstants.swift; sourceTree = ""; }; 7FACD53923F25A9A0042A33A /* InitialScreenViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = InitialScreenViewController.swift; sourceTree = ""; }; 7FEC361423F16A1E00127AFB /* UIViewExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UIViewExtension.swift; sourceTree = ""; }; @@ -506,18 +554,18 @@ B60F8BE3242659810007A641 /* UILabelExtension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UILabelExtension.swift; sourceTree = ""; }; B615C5A623F8EB1700345969 /* UIProgressView + Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIProgressView + Extension.swift"; sourceTree = ""; }; B615C5A823FA403400345969 /* UIViewController + Extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "UIViewController + Extension.swift"; sourceTree = ""; }; - C5046D5B23EF18600046E96D /* OnboardingStep1ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingStep1ViewController.swift; sourceTree = ""; }; + C5046D5B23EF18600046E96D /* RegistrationIntroViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegistrationIntroViewController.swift; sourceTree = ""; }; C56CF43E23F18A15006B05B0 /* OnboardingStep4ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingStep4ViewController.swift; sourceTree = ""; }; C585C83A23EEB99B0061B7C6 /* GradientButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GradientButton.swift; sourceTree = ""; }; - C58D817623F169DB00345771 /* OnboardingStep2bViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingStep2bViewController.swift; sourceTree = ""; }; + C58D817623F169DB00345771 /* RegistrationSuccessViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RegistrationSuccessViewController.swift; sourceTree = ""; }; C5D209FB23F4476F007233BE /* UITextViewFixed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UITextViewFixed.swift; sourceTree = ""; }; - D8DEB6812423AE2E00D99925 /* OnboardingStep1bViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingStep1bViewController.swift; sourceTree = ""; }; + D8DEB6812423AE2E00D99925 /* HowItWorksViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HowItWorksViewController.swift; sourceTree = ""; }; D8EB201A23FA722D001C60EC /* HelpNavController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HelpNavController.swift; sourceTree = ""; }; D8EB201C23FBE216001C60EC /* help_center_article_style.css */ = {isa = PBXFileReference; lastKnownFileType = text.css; path = help_center_article_style.css; sourceTree = ""; }; DC24373E23F51531007BDBDF /* covid-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "covid-Bridging-Header.h"; sourceTree = ""; }; FB12C4C0242F047F007E893B /* RespondToAuthChallengeAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RespondToAuthChallengeAPI.swift; sourceTree = ""; }; FB12C4C2242F0FE9007E893B /* GetTempIdAPI.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GetTempIdAPI.swift; sourceTree = ""; }; - FB12C4C424304AF0007E893B /* OnboardingStep1aViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnboardingStep1aViewController.swift; sourceTree = ""; }; + FB12C4C424304AF0007E893B /* PrivacyPolicyViewController.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PrivacyPolicyViewController.swift; sourceTree = ""; }; FB81BAD81D73C6FD42202A04 /* Pods-CovidSafe-staging.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-CovidSafe-staging.release.xcconfig"; path = "Target Support Files/Pods-CovidSafe-staging/Pods-CovidSafe-staging.release.xcconfig"; sourceTree = ""; }; FFB86126400FA51506E1B416 /* Pods_CovidSafe_staging.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_CovidSafe_staging.framework; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ @@ -586,34 +634,22 @@ 30E91BEC23EFEA14002D592A /* View Controllers */ = { isa = PBXGroup; children = ( + 5BBE61D625637BB100B8C983 /* Debug */, + 5BBE61D525637B7600B8C983 /* Registration */, + 1B86118F24303ED400EA4B6B /* Questions */, 5B728B4624B5667000654ABC /* BLELogViewController.swift */, - 5D8DD05923E2F08400E097EF /* ContactViewController.swift */, 5B92B0BF24F4DC3A0069C57D /* CovidStatisticsViewController.swift */, + 5B9E41112521688700434B25 /* CSAlertViewController.swift */, + 5BBE61B625633E8D00B8C983 /* CSGenericViewController.swift */, D8EB201A23FA722D001C60EC /* HelpNavController.swift */, 5D5F83AF23F045A800770DEF /* HomeViewController.swift */, - 5B92B0AD24EFADB00069C57D /* SettingsViewController.swift */, - 5D8DD05D23E2F0BA00E097EF /* InfoViewController.swift */, 7FACD53923F25A9A0042A33A /* InitialScreenViewController.swift */, 5B92B09324D14AE00069C57D /* InternetConnectionViewController.swift */, - 5B9E41112521688700434B25 /* CSAlertViewController.swift */, 5B7ABF24244D3BC600BB249B /* IsolationSuccessViewController.swift */, - 5D8DD05B23E2F0A700E097EF /* LogViewController.swift */, 5961ABE92474E358004040DF /* MigrationViewController.swift */, - FB12C4C424304AF0007E893B /* OnboardingStep1aViewController.swift */, - D8DEB6812423AE2E00D99925 /* OnboardingStep1bViewController.swift */, - C5046D5B23EF18600046E96D /* OnboardingStep1ViewController.swift */, - C58D817623F169DB00345771 /* OnboardingStep2bViewController.swift */, - 7F2F0BA123EFFF75006D7404 /* OnboardingStep2ViewController.swift */, - C56CF43E23F18A15006B05B0 /* OnboardingStep4ViewController.swift */, - 30BE1CB423F15D47005DCE4F /* OTPViewController.swift */, - 592CBB7F2441A583001FFCE9 /* PersonalDetailsViewController.swift */, - 5D8B248A23F146C500DBB74D /* PhoneNumberViewController.swift */, 7F19B4DC23F565850071A11E /* PogoInstructionsViewController.swift */, - 59B7416F24514126006E1EEA /* RegistrationConsentViewController.swift */, - 5B110C0F248F275A00B68291 /* SelectCountryViewController.swift */, + 5B92B0AD24EFADB00069C57D /* SettingsViewController.swift */, B615C5A823FA403400345969 /* UIViewController + Extension.swift */, - 5B7ABF27244D6BE100BB249B /* UnderSixteenViewController.swift */, - 1B86118F24303ED400EA4B6B /* Questions */, ); name = "View Controllers"; sourceTree = ""; @@ -622,9 +658,6 @@ isa = PBXGroup; children = ( 5D269C0C23E2958F00ADF2DE /* BluetraceManager.swift */, - 5DD41D4E23DCB05600FD4AB0 /* CentralController.swift */, - 5DC7B8D2242B8D87008E1715 /* BluetraceUtils.swift */, - 5DD41D5223DD4CA400FD4AB0 /* PeripheralController.swift */, 5D5F83AC23F023F600770DEF /* EncounterMessageManager.swift */, 5DC7B8D0242B8536008E1715 /* BluetraceConfig.swift */, ); @@ -636,11 +669,17 @@ children = ( 5B9360EC24F6196A008859FC /* Cells */, 30E91BEA23EFEA0B002D592A /* CodeInputView.swift */, - 5B9E410C2521683500434B25 /* CSAlertView.xib */, - B615C5A623F8EB1700345969 /* UIProgressView + Extension.swift */, 0BC141AB24305D9C00399FA8 /* NSMutableString + Extensions.swift */, 0BC141AD2430685800399FA8 /* UIColor + Extensions.swift */, + B615C5A623F8EB1700345969 /* UIProgressView + Extension.swift */, 0B55E1912430760500C9E798 /* UITextView + Extensions.swift */, + 5B92B0BC24F4DBE20069C57D /* CovidStatisticsView.xib */, + 5B9E410C2521683500434B25 /* CSAlertView.xib */, + 5BBE61B025633B6D00B8C983 /* CSGenericContentView.xib */, + 5B92B0A424EF61480069C57D /* HomeView.xib */, + 5B92B0B324F37E3E0069C57D /* InternetConnectionView.xib */, + 5B92B0AA24EFA3160069C57D /* SettingsView.xib */, + 5DD41D4023DCB03B00FD4AB0 /* Main.storyboard */, ); name = Views; sourceTree = ""; @@ -660,6 +699,62 @@ name = Utils; sourceTree = ""; }; + 590545EB2543E0F5009B82AD /* Herald */ = { + isa = PBXGroup; + children = ( + 590545EC2543E0F5009B82AD /* Sensor */, + 5905460B2543E0F5009B82AD /* herald.h */, + ); + path = Herald; + sourceTree = ""; + }; + 590545EC2543E0F5009B82AD /* Sensor */ = { + isa = PBXGroup; + children = ( + 590545ED2543E0F5009B82AD /* BLE */, + 590545F32543E0F5009B82AD /* Location */, + 590545F52543E0F5009B82AD /* Sensor.swift */, + 590546012543E0F5009B82AD /* SensorArray.swift */, + 590546022543E0F5009B82AD /* PayloadDataSupplier.swift */, + 590546032543E0F5009B82AD /* Data */, + 5905460A2543E0F5009B82AD /* SensorDelegate.swift */, + ); + path = Sensor; + sourceTree = ""; + }; + 590545ED2543E0F5009B82AD /* BLE */ = { + isa = PBXGroup; + children = ( + 590545EE2543E0F5009B82AD /* BLESensor.swift */, + 590545EF2543E0F5009B82AD /* BLEDatabase.swift */, + 590545F02543E0F5009B82AD /* BLEUtilities.swift */, + 590545F12543E0F5009B82AD /* BLETransmitter.swift */, + 590545F22543E0F5009B82AD /* BLEReceiver.swift */, + ); + path = BLE; + sourceTree = ""; + }; + 590545F32543E0F5009B82AD /* Location */ = { + isa = PBXGroup; + children = ( + 590545F42543E0F5009B82AD /* AwakeSensor.swift */, + ); + path = Location; + sourceTree = ""; + }; + 590546032543E0F5009B82AD /* Data */ = { + isa = PBXGroup; + children = ( + 590546042543E0F5009B82AD /* TextFile.swift */, + 590546052543E0F5009B82AD /* BatteryLog.swift */, + 590546062543E0F5009B82AD /* DetectionLog.swift */, + 590546072543E0F5009B82AD /* SensorLogger.swift */, + 590546082543E0F5009B82AD /* ContactLog.swift */, + 590546092543E0F5009B82AD /* StatisticsLog.swift */, + ); + path = Data; + sourceTree = ""; + }; 5909E4A92450438A00D41C26 /* CoreData */ = { isa = PBXGroup; children = ( @@ -767,6 +862,35 @@ name = Cells; sourceTree = ""; }; + 5BBE61D525637B7600B8C983 /* Registration */ = { + isa = PBXGroup; + children = ( + 7F2F0BA123EFFF75006D7404 /* AppSettingsViewController.swift */, + D8DEB6812423AE2E00D99925 /* HowItWorksViewController.swift */, + C56CF43E23F18A15006B05B0 /* OnboardingStep4ViewController.swift */, + 30BE1CB423F15D47005DCE4F /* OTPViewController.swift */, + 592CBB7F2441A583001FFCE9 /* PersonalDetailsViewController.swift */, + 5D8B248A23F146C500DBB74D /* PhoneNumberViewController.swift */, + FB12C4C424304AF0007E893B /* PrivacyPolicyViewController.swift */, + 59B7416F24514126006E1EEA /* RegistrationConsentViewController.swift */, + C5046D5B23EF18600046E96D /* RegistrationIntroViewController.swift */, + C58D817623F169DB00345771 /* RegistrationSuccessViewController.swift */, + 5B110C0F248F275A00B68291 /* SelectCountryViewController.swift */, + 5B7ABF27244D6BE100BB249B /* UnderSixteenViewController.swift */, + ); + name = Registration; + sourceTree = ""; + }; + 5BBE61D625637BB100B8C983 /* Debug */ = { + isa = PBXGroup; + children = ( + 5D8DD05923E2F08400E097EF /* ContactViewController.swift */, + 5D8DD05D23E2F0BA00E097EF /* InfoViewController.swift */, + 5D8DD05B23E2F0A700E097EF /* LogViewController.swift */, + ); + name = Debug; + sourceTree = ""; + }; 5BED1E3824A96CF50066C4D2 /* LaunchScreen */ = { isa = PBXGroup; children = ( @@ -824,6 +948,7 @@ 5DD41D3923DCB03B00FD4AB0 /* CovidSafe */ = { isa = PBXGroup; children = ( + 590545EB2543E0F5009B82AD /* Herald */, 597BB7CA245FACE20067A2E2 /* Crypto */, 5949DC522434859600AE76BC /* lottie */, 5B92D661243005B10049877B /* Resources */, @@ -843,14 +968,10 @@ 30FADD6C23F520F5006C125F /* Utils */, 5DD41D7723DE141700FD4AB0 /* tracer.xcdatamodeld */, 5B728B4C24B5A26D00654ABC /* debug.xcdatamodeld */, - 5B92B0BC24F4DBE20069C57D /* CovidStatisticsView.xib */, - 5B92B0A424EF61480069C57D /* HomeView.xib */, - 5B92B0B324F37E3E0069C57D /* InternetConnectionView.xib */, - 5B92B0AA24EFA3160069C57D /* SettingsView.xib */, - 5DD41D4023DCB03B00FD4AB0 /* Main.storyboard */, D8EB201C23FBE216001C60EC /* help_center_article_style.css */, 5DD41D4323DCB03D00FD4AB0 /* Assets.xcassets */, 5DD41D4823DCB03D00FD4AB0 /* Info.plist */, + 5BBC571C25526F99005E90AA /* staging-Info.plist */, 5D269C0A23E22CC400ADF2DE /* DeviceIdentifier.swift */, DC24373E23F51531007BDBDF /* covid-Bridging-Header.h */, ); @@ -1088,6 +1209,7 @@ 5BED1E3B24A96D1C0066C4D2 /* LaunchScreen_ar.storyboard in Resources */, 5BED1E4424A98EB60066C4D2 /* LaunchScreen_vi.storyboard in Resources */, 5B30F78D24B817A100CDED63 /* LaunchScreen_el.storyboard in Resources */, + 5BBC571D25526F99005E90AA /* staging-Info.plist in Resources */, 5B9360FE24F73CE6008859FC /* LoadingViewCell.xib in Resources */, 5B92D6C9243018040049877B /* LaunchScreen_en.storyboard in Resources */, 5B92B0A624EF61490069C57D /* HomeView.xib in Resources */, @@ -1096,6 +1218,7 @@ 5B92D6CB243018040049877B /* Assets.xcassets in Resources */, 5B92B0A324E0CD190069C57D /* LaunchScreen_tr.storyboard in Resources */, 5BED1E4124A98EAF0066C4D2 /* LaunchScreen_zh-Hant.storyboard in Resources */, + 5BBE61B225633B6D00B8C983 /* CSGenericContentView.xib in Resources */, 5B30F78A24B8179600CDED63 /* LaunchScreen_it.storyboard in Resources */, 5B337AB0245AA26300537620 /* Spinner_upload.json in Resources */, 5B92B0B524F37E3E0069C57D /* InternetConnectionView.xib in Resources */, @@ -1129,6 +1252,7 @@ 5BED1E3A24A96D1C0066C4D2 /* LaunchScreen_ar.storyboard in Resources */, 5B30F78C24B817A100CDED63 /* LaunchScreen_el.storyboard in Resources */, 5B92B0A124E0CD140069C57D /* LaunchScreen_pa-IN.storyboard in Resources */, + 5BBE61B125633B6D00B8C983 /* CSGenericContentView.xib in Resources */, 5B82435E2480DC2100705CB1 /* Localizable.strings in Resources */, 5B92D663243011B40049877B /* CovidSafe-config.plist in Resources */, 5BED1E4324A98EB60066C4D2 /* LaunchScreen_vi.storyboard in Resources */, @@ -1255,32 +1379,36 @@ 5B92D67D243018040049877B /* HomeViewController.swift in Sources */, 5B92D67E243018040049877B /* InfoViewController.swift in Sources */, 5B92D67F243018040049877B /* PogoInstructionsViewController.swift in Sources */, - FBBBFCE82430A933002B174D /* OnboardingStep1aViewController.swift in Sources */, + FBBBFCE82430A933002B174D /* PrivacyPolicyViewController.swift in Sources */, 5B51ED512485DF9C008CE722 /* UILocalization.swift in Sources */, 5BA33A8024B55EF200D12515 /* BLELogDB.swift in Sources */, 594E77C3247387B1009B8B34 /* EncounterDB+migration.swift in Sources */, + 590546292543E0F6009B82AD /* SensorArray.swift in Sources */, 590C99332432C1C400A5EC71 /* UploadDataHomeViewController.swift in Sources */, + 590546112543E0F5009B82AD /* BLEUtilities.swift in Sources */, 59B7417124514126006E1EEA /* RegistrationConsentViewController.swift in Sources */, 5B92B0AF24EFADB00069C57D /* SettingsViewController.swift in Sources */, 5B92B0C124F4DC3A0069C57D /* CovidStatisticsViewController.swift in Sources */, 5B92D680243018040049877B /* CodeInputView.swift in Sources */, 5B92D681243018040049877B /* EncounterRecord.swift in Sources */, + 5905462D2543E0F6009B82AD /* TextFile.swift in Sources */, 5B728B4B24B581C100654ABC /* BLELog+CoreDataProperties.swift in Sources */, 5B337AAD245A9EF800537620 /* UploadDataErrorViewController.swift in Sources */, 590888B02431B9E7008C9B9F /* UIColor + Extensions.swift in Sources */, 5B728B4E24B5A26D00654ABC /* debug.xcdatamodeld in Sources */, + 5905460F2543E0F5009B82AD /* BLEDatabase.swift in Sources */, 5B92D74F243022EF0049877B /* DataUploadS3.swift in Sources */, - 5B92D683243018040049877B /* OnboardingStep2bViewController.swift in Sources */, + 5B92D683243018040049877B /* RegistrationSuccessViewController.swift in Sources */, 5BA33A8224B5602500D12515 /* BLELogRecord+BLELogSave.swift in Sources */, 5B92B09524D14AE00069C57D /* InternetConnectionViewController.swift in Sources */, 5B92D684243018040049877B /* AsyncAction.swift in Sources */, 5B92D685243018040049877B /* UILabelExtension.swift in Sources */, + 5905462B2543E0F6009B82AD /* PayloadDataSupplier.swift in Sources */, 5B92D686243018040049877B /* AppDelegate.swift in Sources */, 5B92D687243018040049877B /* PhoneNumberViewController.swift in Sources */, 5BA33A7C24B41ECA00D12515 /* UIFont + Traits.swift in Sources */, 5961ABEB2474E358004040DF /* MigrationViewController.swift in Sources */, 5B110C11248F275B00B68291 /* SelectCountryViewController.swift in Sources */, - 5B92D688243018040049877B /* BluetraceUtils.swift in Sources */, 5B92D689243018040049877B /* NewFeedbackFlowController.swift in Sources */, 5B92D68A243018040049877B /* Outcome.swift in Sources */, 5B92D68B243018040049877B /* Encounter+EncounterRecord.swift in Sources */, @@ -1302,12 +1430,13 @@ 597BB7CD245FAEC00067A2E2 /* SecKey+CovidSafe.swift in Sources */, 597BB7D0245FB1250067A2E2 /* Crypto.swift in Sources */, 5B92D693243018040049877B /* UIColor+Hex.swift in Sources */, - 5B92D694243018040049877B /* OnboardingStep1ViewController.swift in Sources */, + 590546372543E0F6009B82AD /* StatisticsLog.swift in Sources */, + 5B92D694243018040049877B /* RegistrationIntroViewController.swift in Sources */, 5B92D695243018040049877B /* DeviceInfoExtension.swift in Sources */, 5BD3EE84243313450004A007 /* UploadDataStep2VC.swift in Sources */, - 5B92D697243018040049877B /* PeripheralController.swift in Sources */, 5B92D698243018040049877B /* SendFeedbackAction.swift in Sources */, 5B92D699243018040049877B /* UITextViewFixed.swift in Sources */, + 590546152543E0F6009B82AD /* BLEReceiver.swift in Sources */, 5BA33A7E24B55E7D00D12515 /* BLELogRecord.swift in Sources */, 590888B12431B9EB008C9B9F /* Question3ViewController.swift in Sources */, 5957EB67244E936E002F5388 /* UnderSixteenViewController.swift in Sources */, @@ -1323,6 +1452,7 @@ 5B92D6A0243018040049877B /* CountriesData.swift in Sources */, 590888B22431B9EF008C9B9F /* Question2ViewController.swift in Sources */, 0B42D0E02432B3AF00E4F44C /* QuestionUploadDataViewController.swift in Sources */, + 590546352543E0F6009B82AD /* ContactLog.swift in Sources */, 5B92D6A1243018040049877B /* AlertController.swift in Sources */, 5B92D750243022F20049877B /* InitiateUploadAPI.swift in Sources */, 5B92D69F243018040049877B /* EncounterMessageManager.swift in Sources */, @@ -1330,29 +1460,37 @@ 5B728B4924B5816C00654ABC /* BLELog+CoreDataClass.swift in Sources */, 5B92D6A2243018040049877B /* GetTempIdAPI.swift in Sources */, 5B92D6A3243018040049877B /* PhoneValidationAPI.swift in Sources */, + 590546132543E0F6009B82AD /* BLETransmitter.swift in Sources */, 59AF2EB32435A38100ACCAF2 /* CovidRequestRetrier.swift in Sources */, 592CBB812441A583001FFCE9 /* PersonalDetailsViewController.swift in Sources */, - 5B92D6A4243018040049877B /* CentralController.swift in Sources */, 5B92D6A5243018040049877B /* UIWindow+TopMost.swift in Sources */, - 5B92D6A6243018040049877B /* OnboardingStep1bViewController.swift in Sources */, + 5B92D6A6243018040049877B /* HowItWorksViewController.swift in Sources */, + 590546312543E0F6009B82AD /* DetectionLog.swift in Sources */, 5B92D6A7243018040049877B /* OnboardingStep4ViewController.swift in Sources */, 5B92D6A8243018040049877B /* PresentFeedbackExtensions.swift in Sources */, + 590546392543E0F6009B82AD /* SensorDelegate.swift in Sources */, 5B92D6A9243018040049877B /* Errors.swift in Sources */, 5B92D6AA243018040049877B /* UINavigationBar+Style.swift in Sources */, + 590546172543E0F6009B82AD /* AwakeSensor.swift in Sources */, 5B92D6AB243018040049877B /* UploadFileData.swift in Sources */, 590888B52431BA76008C9B9F /* NSMutableString + Extensions.swift in Sources */, 5B92D6AC243018040049877B /* BundleInfoExtension.swift in Sources */, + 5905460D2543E0F5009B82AD /* BLESensor.swift in Sources */, + 5BBE61B825633E8D00B8C983 /* CSGenericViewController.swift in Sources */, 5909E4AC245043C400D41C26 /* CovidPersistentContainer.swift in Sources */, + 5905462F2543E0F6009B82AD /* BatteryLog.swift in Sources */, 5B92D6AD243018040049877B /* FeedbackSettings.swift in Sources */, 5B92D6AE243018040049877B /* JMCTargetJSONFromDisk.swift in Sources */, 5B92D6B0243018040049877B /* Action.swift in Sources */, - 5B92D6B1243018040049877B /* OnboardingStep2ViewController.swift in Sources */, + 5B92D6B1243018040049877B /* AppSettingsViewController.swift in Sources */, 59AF2E9A2435533A00ACCAF2 /* CovidCertificates.swift in Sources */, 5B92D6B2243018040049877B /* HTTPPostFeedbackAction.swift in Sources */, 5B92B0C424F4DE6F0069C57D /* StatisticsAPI.swift in Sources */, + 590546192543E0F6009B82AD /* Sensor.swift in Sources */, 59898604245173C200966E61 /* URLHelper.swift in Sources */, 590888B32431B9F2008C9B9F /* Question1ViewController.swift in Sources */, 590888B62431BA7C008C9B9F /* Question3ErrorViewController.swift in Sources */, + 590546332543E0F6009B82AD /* SensorLogger.swift in Sources */, 5B900FC22485C4EE00CAA419 /* String+Localization.swift in Sources */, 59AF2E9D2435581600ACCAF2 /* CovidNetworking.swift in Sources */, 596B189D24499591003E190F /* UploadHelper.swift in Sources */, @@ -1368,14 +1506,17 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + 5ADBDDED2579A7DC0078872F /* EncounterMessageManager.swift in Sources */, B615C5A723F8EB1700345969 /* UIProgressView + Extension.swift in Sources */, 5D8DD06723E329A200E097EF /* tracer.xcdatamodeld in Sources */, 30E91BE923EFE514002D592A /* UploadDataVC.swift in Sources */, 0BC141AE2430685800399FA8 /* UIColor + Extensions.swift in Sources */, 7FEC361523F16A1E00127AFB /* UIViewExtension.swift in Sources */, + 590546122543E0F6009B82AD /* BLETransmitter.swift in Sources */, 5D269C0B23E22CC400ADF2DE /* DeviceIdentifier.swift in Sources */, A767D31E242DF1B000DC9E2A /* LanguageInfoExtension.swift in Sources */, B605A7B12427429D008BA819 /* PlistHelper.swift in Sources */, + 5905460E2543E0F5009B82AD /* BLEDatabase.swift in Sources */, 5DC7B8D1242B8536008E1715 /* BluetraceConfig.swift in Sources */, 0B69E7E92430C22E00561DD9 /* UploadDataHomeViewController.swift in Sources */, 1B86119524303F5E00EA4B6B /* Question3ViewController.swift in Sources */, @@ -1389,20 +1530,23 @@ 59B7417024514126006E1EEA /* RegistrationConsentViewController.swift in Sources */, 5D5F83B023F045A800770DEF /* HomeViewController.swift in Sources */, 5B337AAB245A9BBC00537620 /* UploadDataErrorViewController.swift in Sources */, - FB12C4C524304AF0007E893B /* OnboardingStep1aViewController.swift in Sources */, + FB12C4C524304AF0007E893B /* PrivacyPolicyViewController.swift in Sources */, 7F19B4DD23F565850071A11E /* PogoInstructionsViewController.swift in Sources */, 30E91BEB23EFEA0B002D592A /* CodeInputView.swift in Sources */, 597BB7CF245FB1250067A2E2 /* Crypto.swift in Sources */, 30BE1CAF23F1349F005DCE4F /* EncounterRecord.swift in Sources */, + 590546102543E0F5009B82AD /* BLEUtilities.swift in Sources */, + 590546382543E0F6009B82AD /* SensorDelegate.swift in Sources */, 59490B64245FE3DA00C9802B /* EncounterV2Mapping.swift in Sources */, - C58D817723F169DB00345771 /* OnboardingStep2bViewController.swift in Sources */, + 590546282543E0F6009B82AD /* SensorArray.swift in Sources */, + C58D817723F169DB00345771 /* RegistrationSuccessViewController.swift in Sources */, 59ACB574242F195A00E63E3C /* InitiateUploadAPI.swift in Sources */, A767D324242DF1B100DC9E2A /* AsyncAction.swift in Sources */, B60F8BE4242659810007A641 /* UILabelExtension.swift in Sources */, 5DD41D3B23DCB03B00FD4AB0 /* AppDelegate.swift in Sources */, 5D8B248B23F146C500DBB74D /* PhoneNumberViewController.swift in Sources */, - 5DC7B8D3242B8D87008E1715 /* BluetraceUtils.swift in Sources */, A767D32D242DF1B100DC9E2A /* NewFeedbackFlowController.swift in Sources */, + 590546362543E0F6009B82AD /* StatisticsLog.swift in Sources */, A767D319242DF1B000DC9E2A /* Outcome.swift in Sources */, 30BE1CB123F134D0005DCE4F /* Encounter+EncounterRecord.swift in Sources */, A767D336242DF1B100DC9E2A /* GetJMCTargetAction.swift in Sources */, @@ -1411,25 +1555,31 @@ D8EB201B23FA722D001C60EC /* HelpNavController.swift in Sources */, 596B189924496D32003E190F /* Encounter+Util.swift in Sources */, 5961ABEA2474E358004040DF /* MigrationViewController.swift in Sources */, + 590546182543E0F6009B82AD /* Sensor.swift in Sources */, + 590546162543E0F6009B82AD /* AwakeSensor.swift in Sources */, 5B04074124BC0CEA00FAAFD0 /* MessageAPI.swift in Sources */, 30BE1CB523F15D47005DCE4F /* OTPViewController.swift in Sources */, + 5905460C2543E0F5009B82AD /* BLESensor.swift in Sources */, 5B900FC12485C4EE00CAA419 /* String+Localization.swift in Sources */, 5D8DD06123E319B300E097EF /* Encounter+CoreDataClass.swift in Sources */, 594E77BF24736B77009B8B34 /* EncounterDB.swift in Sources */, + 590546322543E0F6009B82AD /* SensorLogger.swift in Sources */, + 5905462E2543E0F6009B82AD /* BatteryLog.swift in Sources */, FB12C4C1242F0480007E893B /* RespondToAuthChallengeAPI.swift in Sources */, 5D269C0D23E2958F00ADF2DE /* BluetraceManager.swift in Sources */, 1B86119124303EF200EA4B6B /* Question1ViewController.swift in Sources */, 5BD3EE8324330E1A0004A007 /* UploadDataStep2VC.swift in Sources */, A767D31B242DF1B000DC9E2A /* UIColor+Hex.swift in Sources */, 5BA33A7B24B3FE2700D12515 /* UIFont + Traits.swift in Sources */, - C5046D5C23EF18600046E96D /* OnboardingStep1ViewController.swift in Sources */, + 590546142543E0F6009B82AD /* BLEReceiver.swift in Sources */, + C5046D5C23EF18600046E96D /* RegistrationIntroViewController.swift in Sources */, 0B69E7ED2430D72900561DD9 /* UploadDataNavigationController.swift in Sources */, A767D320242DF1B100DC9E2A /* DeviceInfoExtension.swift in Sources */, - 5DD41D5323DD4CA400FD4AB0 /* PeripheralController.swift in Sources */, 5B7ABF28244D6BE100BB249B /* UnderSixteenViewController.swift in Sources */, A767D325242DF1B100DC9E2A /* SendFeedbackAction.swift in Sources */, C5D209FC23F4476F007233BE /* UITextViewFixed.swift in Sources */, C585C83B23EEB99B0061B7C6 /* GradientButton.swift in Sources */, + 590546342543E0F6009B82AD /* ContactLog.swift in Sources */, 597BB7CC245FAEC00067A2E2 /* SecKey+CovidSafe.swift in Sources */, 5B92B0AE24EFADB00069C57D /* SettingsViewController.swift in Sources */, 5B7ABF25244D3BC600BB249B /* IsolationSuccessViewController.swift in Sources */, @@ -1438,25 +1588,25 @@ 5B577815245A584C0088F111 /* UploadDataPrefaceViewController.swift in Sources */, 0BC141AC24305D9C00399FA8 /* NSMutableString + Extensions.swift in Sources */, 59ACB576242F404500E63E3C /* DataUploadS3.swift in Sources */, + 590546302543E0F6009B82AD /* DetectionLog.swift in Sources */, 5B92B0C024F4DC3A0069C57D /* CovidStatisticsViewController.swift in Sources */, A767D326242DF1B100DC9E2A /* JMCTarget.swift in Sources */, - 5D5F83AD23F023F600770DEF /* EncounterMessageManager.swift in Sources */, 7FF75C222429FEE800C11FEA /* CountriesData.swift in Sources */, 0B55E1922430760600C9E798 /* UITextView + Extensions.swift in Sources */, 5B110C10248F275B00B68291 /* SelectCountryViewController.swift in Sources */, A767D321242DF1B100DC9E2A /* AlertController.swift in Sources */, - 5D5F83AD23F023F600770DEF /* EncounterMessageManager.swift in Sources */, FB12C4C3242F0FE9007E893B /* GetTempIdAPI.swift in Sources */, 5BFFD94B242EC120003AEF4F /* PhoneValidationAPI.swift in Sources */, 59AF2EB22435A38100ACCAF2 /* CovidRequestRetrier.swift in Sources */, 592CBB802441A583001FFCE9 /* PersonalDetailsViewController.swift in Sources */, - 5DD41D4F23DCB05600FD4AB0 /* CentralController.swift in Sources */, A767D330242DF1B100DC9E2A /* UIWindow+TopMost.swift in Sources */, - D8DEB6822423AE2E00D99925 /* OnboardingStep1bViewController.swift in Sources */, + D8DEB6822423AE2E00D99925 /* HowItWorksViewController.swift in Sources */, 5B92B0C324F4DE6F0069C57D /* StatisticsAPI.swift in Sources */, + 5905462C2543E0F6009B82AD /* TextFile.swift in Sources */, C56CF43F23F18A15006B05B0 /* OnboardingStep4ViewController.swift in Sources */, A767D328242DF1B100DC9E2A /* PresentFeedbackExtensions.swift in Sources */, A767D32F242DF1B100DC9E2A /* Errors.swift in Sources */, + 5905462A2543E0F6009B82AD /* PayloadDataSupplier.swift in Sources */, 0B22A56B242F286900D1FE60 /* UINavigationBar+Style.swift in Sources */, 0B1810122431EE610005D11F /* PhoneNumberParser.swift in Sources */, 1B86119B24303FA200EA4B6B /* Question3ErrorViewController.swift in Sources */, @@ -1465,10 +1615,11 @@ A767D31D242DF1B000DC9E2A /* BundleInfoExtension.swift in Sources */, A767D32C242DF1B100DC9E2A /* FeedbackSettings.swift in Sources */, A767D31A242DF1B000DC9E2A /* JMCTargetJSONFromDisk.swift in Sources */, + 5BBE61B725633E8D00B8C983 /* CSGenericViewController.swift in Sources */, 5B92B09424D14AE00069C57D /* InternetConnectionViewController.swift in Sources */, A767D334242DF1B100DC9E2A /* Action.swift in Sources */, 59AF2E992435533A00ACCAF2 /* CovidCertificates.swift in Sources */, - 7F2F0BA223EFFF75006D7404 /* OnboardingStep2ViewController.swift in Sources */, + 7F2F0BA223EFFF75006D7404 /* AppSettingsViewController.swift in Sources */, 594E77C2247387B1009B8B34 /* EncounterDB+migration.swift in Sources */, 59898603245173C200966E61 /* URLHelper.swift in Sources */, A767D31F242DF1B000DC9E2A /* HTTPPostFeedbackAction.swift in Sources */, @@ -1627,7 +1778,7 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 95; DEVELOPMENT_TEAM = 45792XH5L8; INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; @@ -1635,7 +1786,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; ONLY_ACTIVE_ARCH = YES; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; PRODUCT_NAME = COVIDSafe; @@ -1711,7 +1862,7 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 95; DEVELOPMENT_TEAM = 45792XH5L8; INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; @@ -1719,7 +1870,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; PRODUCT_NAME = COVIDSafe; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -1739,15 +1890,15 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 93; DEVELOPMENT_TEAM = 45792XH5L8; - INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; + INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/staging-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; ONLY_ACTIVE_ARCH = YES; OTHER_SWIFT_FLAGS = "$(inherited) -D COCOAPODS -D DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; @@ -1769,15 +1920,15 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 93; DEVELOPMENT_TEAM = 45792XH5L8; - INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; + INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/staging-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; ONLY_ACTIVE_ARCH = YES; OTHER_SWIFT_FLAGS = "$(inherited) -D COCOAPODS -D DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; @@ -1799,15 +1950,15 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 93; DEVELOPMENT_TEAM = 45792XH5L8; - INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; + INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/staging-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; OTHER_SWIFT_FLAGS = "$(inherited) -D COCOAPODS -D DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; PRODUCT_MODULE_NAME = COVIDSafe; @@ -1829,15 +1980,15 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 93; DEVELOPMENT_TEAM = 45792XH5L8; - INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; + INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/staging-Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; OTHER_SWIFT_FLAGS = "$(inherited) -D COCOAPODS -D DEBUG"; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; PRODUCT_MODULE_NAME = COVIDSafe; @@ -1977,7 +2128,7 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 95; DEVELOPMENT_TEAM = 45792XH5L8; INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; @@ -1985,7 +2136,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; ONLY_ACTIVE_ARCH = YES; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; PRODUCT_NAME = COVIDSafe; @@ -2005,7 +2156,7 @@ CODE_SIGN_ENTITLEMENTS = "CovidSafe/Project Bluetrace.entitlements"; CODE_SIGN_IDENTITY = "Apple Development"; CODE_SIGN_STYLE = Automatic; - CURRENT_PROJECT_VERSION = 83; + CURRENT_PROJECT_VERSION = 95; DEVELOPMENT_TEAM = 45792XH5L8; INFOPLIST_FILE = "$(SRCROOT)/CovidSafe/Info.plist"; IPHONEOS_DEPLOYMENT_TARGET = 10.0; @@ -2013,7 +2164,7 @@ "$(inherited)", "@executable_path/Frameworks", ); - MARKETING_VERSION = 1.14; + MARKETING_VERSION = 2.0; PRODUCT_BUNDLE_IDENTIFIER = au.gov.health.covidsafe; PRODUCT_NAME = COVIDSafe; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/CovidSafe/AppDelegate.swift b/CovidSafe/AppDelegate.swift index e5b39e5..073de3f 100644 --- a/CovidSafe/AppDelegate.swift +++ b/CovidSafe/AppDelegate.swift @@ -29,14 +29,6 @@ class AppDelegate: UIResponder, UIApplicationDelegate { UIBarButtonItem.appearance().setTitleTextAttributes([.foregroundColor: UIColor.covidSafeColor], for: .normal) UINavigationBar.appearance().tintColor = UIColor.covidSafeColor - let hasUserConsent = true - let hasUserCompletedOnboarding = UserDefaults.standard.bool(forKey: "turnedOnBluetooth") - let bluetoothAuthorised = BluetraceManager.shared.isBluetoothAuthorized() - if (hasUserConsent && hasUserCompletedOnboarding && bluetoothAuthorised) { - BluetraceManager.shared.turnOn() - } else { - print("Onboarding not yet done.") - } EncounterMessageManager.shared.setup() UIApplication.shared.isIdleTimerDisabled = true diff --git a/CovidSafe/AppSettingsViewController.swift b/CovidSafe/AppSettingsViewController.swift new file mode 100644 index 0000000..064695a --- /dev/null +++ b/CovidSafe/AppSettingsViewController.swift @@ -0,0 +1,63 @@ +// +// AppSettingsViewController.swift +// CovidSafe +// +// Copyright © 2020 Australian Government. All rights reserved. +// + +import UIKit +import CoreBluetooth +import UserNotifications + +class AppSettingsViewController: UIViewController { + private var backupSensorDidUpdateStateCallback: ((SensorState, SensorType?) -> Void)? + + @IBOutlet weak var stepCounterLabel: UILabel! + @IBOutlet weak var topContentTextView: UITextView! + + override func viewDidLoad() { + super.viewDidLoad() + stepCounterLabel.text = String.localizedStringWithFormat( "stepCounter".localizedString(), + 4, + 4 + ) + topContentTextView.addLink("\(URLHelper.getHelpURL())#location-permission-android", enclosedIn: "*") + topContentTextView.addAllBold(enclosedIn: "#") + } + + @IBAction func proceedTapped(_ sender: UIButton) { + self.backupSensorDidUpdateStateCallback = BluetraceManager.shared.sensorDidUpdateStateCallback + BluetraceManager.shared.sensorDidUpdateStateCallback = sensorManagerDidUpdateBluetoothCallback + BluetraceManager.shared.turnOnBLE() + UserDefaults.standard.set(true, forKey: "turnedOnBluetooth") + } + + func sensorManagerDidUpdateBluetoothCallback(_ state: SensorState, type: SensorType?) { + DLog("Bluetooth state changed in permission request to \(state.rawValue)") + requestPushPermissions() + } + + func sensorManagerDidUpdateLocationCallback(_ state: SensorState, type: SensorType?) { + DLog("Location state changed in permission request to \(state.rawValue)") + + UserDefaults.standard.set(true, forKey: "allowedPermissions") + BluetraceManager.shared.sensorDidUpdateStateCallback = self.backupSensorDidUpdateStateCallback + DispatchQueue.main.async { + self.performSegue(withIdentifier: "showSuccessSegue", sender: self) + } + } + + func requestPushPermissions() { + + UNUserNotificationCenter.current() + .requestAuthorization(options: [.alert, .sound, .badge]) { + granted, error in + print("Permissions granted: \(granted)") + DispatchQueue.main.async { + UIApplication.shared.registerForRemoteNotifications() + BluetraceManager.shared.sensorDidUpdateStateCallback = self.sensorManagerDidUpdateLocationCallback + BluetraceManager.shared.turnOnLocationSensor() + } + } + } +} diff --git a/CovidSafe/Base.lproj/Main.storyboard b/CovidSafe/Base.lproj/Main.storyboard index 2a6007f..8a493b9 100644 --- a/CovidSafe/Base.lproj/Main.storyboard +++ b/CovidSafe/Base.lproj/Main.storyboard @@ -1,18 +1,18 @@ - + - + - + - + @@ -197,7 +197,7 @@ - + @@ -215,7 +215,7 @@ - + - + @@ -334,8 +334,14 @@ Together we can help stop the spread and stay healthy. - + + @@ -355,7 +361,7 @@ Together we can help stop the spread and stay healthy. + + + + COVIDSafe needs Bluetooth® enabled to work. By enabling Notifications, you get updates to remind you when COVIDSafe is not active. + +Select ‘Proceed' to enable: + + + + + + + + - + + + @@ -405,6 +422,7 @@ COVIDSafe does not send pairing requests. + @@ -460,6 +478,7 @@ COVIDSafe does not send pairing requests. + @@ -1257,10 +1276,10 @@ and save lives. - + - + @@ -1597,10 +1616,10 @@ For more information please refer to the *Help Topics* page. - + - + @@ -2261,9 +2280,9 @@ See the COVIDSafe *privacy policy* for further details about your rights about y - - - + + + diff --git a/CovidSafe/Base.lproj/UploadData.storyboard b/CovidSafe/Base.lproj/UploadData.storyboard index 6fb9424..cb16535 100644 --- a/CovidSafe/Base.lproj/UploadData.storyboard +++ b/CovidSafe/Base.lproj/UploadData.storyboard @@ -11,7 +11,7 @@ - + diff --git a/CovidSafe/BluetraceConfig.swift b/CovidSafe/BluetraceConfig.swift index 4cb1c04..e4bcfc6 100644 --- a/CovidSafe/BluetraceConfig.swift +++ b/CovidSafe/BluetraceConfig.swift @@ -16,7 +16,10 @@ struct BluetraceConfig { static let ProtocolVersion = 2 static let CentralScanInterval = 60.0 // in seconds + static let PayloadExpiry = 20.0 // in seconds + static let PeripheralPayloadExpiry = TimeInterval.minute * 5 static let PeripheralCleanInterval = 120.0 // in seconds + static let PeripheralPayloadSaveInterval = 30.0 // in seconds static let CentralScanDuration = 10 // in seconds static let DummyModel = "" diff --git a/CovidSafe/BluetraceManager.swift b/CovidSafe/BluetraceManager.swift index 589a18d..1d8d408 100644 --- a/CovidSafe/BluetraceManager.swift +++ b/CovidSafe/BluetraceManager.swift @@ -2,24 +2,58 @@ import UIKit import CoreData import CoreBluetooth -class BluetraceManager { - private var peripheralController: PeripheralController! - private var centralController: CentralController! - var queue: DispatchQueue! - var bluetoothDidUpdateStateCallback: ((CBManagerState) -> Void)? +class BluetraceManager: SensorDelegate { + + private let logger = ConcreteSensorLogger(subsystem: "Herald", category: "BluetraceManager") + + var sensorDidUpdateStateCallback: ((SensorState, SensorType?) -> Void)? + + // Payload data supplier, sensor and contact log + var payloadDataSupplier: PayloadDataSupplier? + var sensor: Sensor? static let shared = BluetraceManager() - private init() { - queue = DispatchQueue(label: "BluetraceManager") - peripheralController = PeripheralController(peripheralName: "TR", queue: queue) - centralController = CentralController(queue: queue) - centralController.centralDidUpdateStateCallback = centralDidUpdateStateCallback + var bleSensorState: SensorState = .unavailable + var awakeSensorState: SensorState = .unavailable + + private var didRecordPayloadData: [String:Date] = [:] + private var didWriteLegacyPayloadData: [String:Date] = [:] + + func turnOnBLE() { + payloadDataSupplier = EncounterMessageManager.shared + if sensor == nil { + sensor = SensorArray(payloadDataSupplier!) + sensor?.add(delegate: self) + } + sensor?.start() } - func turnOn() { - peripheralController.turnOn() - centralController.turnOn() + func turnOnAllSensors() { + payloadDataSupplier = EncounterMessageManager.shared + if sensor == nil { + sensor = SensorArray(payloadDataSupplier!) + sensor?.add(delegate: self) + // we are going to turn on one at a time + let previousSensorDidUpdateStateCallback = sensorDidUpdateStateCallback + sensorDidUpdateStateCallback = { state, type in + if (state == .on ) { + self.sensorDidUpdateStateCallback = previousSensorDidUpdateStateCallback + self.turnOnLocationSensor() + } + } + } + sensor?.start() + } + + + func turnOnLocationSensor() { + guard let sensorArray = sensor as? SensorArray else { + return + } + DispatchQueue.main.async { + sensorArray.startAwakeSensor() + } } func isBluetoothAuthorized() -> Bool { @@ -31,26 +65,161 @@ class BluetraceManager { } func isBluetoothOn() -> Bool { - return centralController.getState() == .poweredOn + return bleSensorState == .on + } + + func isLocationOnAuthorized() -> Bool { + return awakeSensorState == .on } func centralDidUpdateStateCallback(_ state: CBManagerState) { - bluetoothDidUpdateStateCallback?(state) + if state == .poweredOn { + sensorDidUpdateStateCallback?(.on, .BLE) + } else { + sensorDidUpdateStateCallback?(.off, .BLE) + } } func toggleAdvertisement(_ state: Bool) { if state { - peripheralController.turnOn() + sensor?.start() } else { - peripheralController.turnOff() + sensor?.stop() } } func toggleScanning(_ state: Bool) { if state { - centralController.turnOn() + sensor?.start() } else { - centralController.turnOff() + sensor?.stop() } } + + func cleanRecordsData( records: inout [String:Date], expiryInterval: TimeInterval) { + let removeDataBefore = Date() - expiryInterval + let recentDidWritePayloadData = records.filter({ $0.value >= removeDataBefore }) + records = recentDidWritePayloadData + } + + func saveEncounter(payload: PayloadData, proximity: Proximity, txPower: Int? ) throws { + let peripheralCharData = try JSONDecoder().decode(PeripheralCharacteristicsData.self, from: payload) + var encounterStruct = EncounterRecord(rssi: proximity.value, txPower: txPower == nil ? nil : Double(txPower!)) + encounterStruct.msg = peripheralCharData.msg + encounterStruct.update(modelP: peripheralCharData.modelP) + encounterStruct.org = peripheralCharData.org + encounterStruct.v = peripheralCharData.v + encounterStruct.timestamp = Date() + // here the remote blob will be msg and modelp if v1, msg if v2 + // local blob will be rssi, txpower, modelc + try encounterStruct.saveRemotePeripheralToCoreData() + } + + func getIdentifier(forDevice: BLEDevice) -> String { + return forDevice.pseudoDeviceAddress != nil ? "\(forDevice.pseudoDeviceAddress!.address)" : forDevice.identifier + } + + func shouldSaveEncounter(forDeviceIdentifier: String) -> Bool { + + guard didRecordPayloadData[forDeviceIdentifier] == nil || abs(didRecordPayloadData[forDeviceIdentifier]!.timeIntervalSinceNow) > BluetraceConfig.PeripheralPayloadSaveInterval else { + return false + } + return true + } + + // MARK:- SensorDelegate + + func sensor(_ sensor: SensorType, didDetect: TargetIdentifier) { + logger.info(sensor.rawValue + ",didDetect=" + didDetect.description) + } + + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier) { + logger.info(sensor.rawValue + ",didMeasure=" + didMeasure.description + ",fromTarget=" + fromTarget.description) + + // Make a call to the messages API if needed. + // Dispatch in background queue + DispatchQueue.global(qos: .background).async { + MessageAPI.getMessagesIfNeeded() { (messageResponse, error) in + if let error = error { + DLog("Get messages error: \(error.localizedDescription)") + } + // We currently dont do anything with the response. Messages are delivered via APN + } + } + } + + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier, withPayload: PayloadData, forDevice: BLEDevice) { + logger.info(sensor.rawValue + ",didMeasure=" + didMeasure.description + ",fromTarget=" + fromTarget.description + ",withPayload=" + withPayload.shortName) + + let deviceIdentifier = getIdentifier(forDevice: forDevice) + guard shouldSaveEncounter(forDeviceIdentifier: deviceIdentifier) else { + logger.info("didMeasure, skipping save as time since last saved too recet fromTarget=" + fromTarget.description) + return + } + didRecordPayloadData[deviceIdentifier] = Date() + cleanRecordsData(records: &didRecordPayloadData, expiryInterval: BluetraceConfig.PeripheralPayloadExpiry) + do { + logger.debug("Saving on didMeasure fromTarget=" + fromTarget.description) + try saveEncounter(payload: withPayload, proximity: didMeasure, txPower: nil) + } catch { + logger.fault("ERROR "+sensor.rawValue + ",didMeasure=" + didMeasure.description + ",fromTarget=" + fromTarget.description + ",withPayload=" + withPayload.shortName ) + } + + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier) { + do { + let dataFromCentral = try JSONDecoder().decode(CentralWriteData.self, from: didRead) + logger.info(sensor.rawValue + ",didRead=" + dataFromCentral.msg + ",fromTarget=" + fromTarget.description) + } catch { + logger.fault(sensor.rawValue + ",didRead=" + didRead.shortName + ",fromTarget=" + fromTarget.description) + } + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier, atProximity: Proximity, withTxPower: Int?) { + logger.info(sensor.rawValue + ",didRead=\(didRead.shortName))" + ",fromTarget=" + fromTarget.description + ",atProximity=" + atProximity.description + ",withTxPower=\(String(describing: withTxPower))") + } + + func sensor(_ sensor: SensorType, didShare: [PayloadData], fromTarget: TargetIdentifier, atProximity: Proximity) { + let payloads = didShare.map { $0.shortName } + logger.info(sensor.rawValue + ",didShare=" + payloads.description + ",fromTarget=" + fromTarget.description) + + } + + func sensor(_ sensor: SensorType, didUpdateState: SensorState) { + logger.info(sensor.rawValue + ",didUpdateState=" + didUpdateState.rawValue) + + if sensor == .BLE { + bleSensorState = didUpdateState + sensorDidUpdateStateCallback?(didUpdateState, sensor) + } + + if sensor == .AWAKE { + awakeSensorState = didUpdateState + sensorDidUpdateStateCallback?(didUpdateState, sensor) + } + } + + func shouldWriteToLegacyDevice(_ device: BLEDevice) -> Bool { + + guard device.legacyPayloadCharacteristic != nil && + device.payloadCharacteristic == nil else { + return false + } + + let cleanInterval = BluetraceConfig.PeripheralPayloadExpiry + let writeInterval = BluetraceConfig.PeripheralPayloadSaveInterval + let deviceIdentifier = getIdentifier(forDevice: device) + cleanRecordsData(records: &didWriteLegacyPayloadData, expiryInterval: cleanInterval) + + guard didWriteLegacyPayloadData[deviceIdentifier] == nil || abs(didWriteLegacyPayloadData[deviceIdentifier]!.timeIntervalSinceNow) > writeInterval else { + return false + } + return true + } + + func didWriteToLegacyDevice(_ device: BLEDevice) { + let deviceIdentifier = getIdentifier(forDevice: device) + didWriteLegacyPayloadData[deviceIdentifier] = Date() + } } diff --git a/CovidSafe/BluetraceUtils.swift b/CovidSafe/BluetraceUtils.swift deleted file mode 100644 index efc96cf..0000000 --- a/CovidSafe/BluetraceUtils.swift +++ /dev/null @@ -1,45 +0,0 @@ -// -// BluetraceUtils.swift -// CovidSafe -// -// Copyright © 2020 Australian Government. All rights reserved. -// - -import Foundation -import CoreBluetooth - -class BluetraceUtils { - static func centralStateToString(_ state: CBManagerState) -> String { - switch state { - case .poweredOff: - return "poweredOff" - case .poweredOn: - return "poweredOn" - case .resetting: - return "resetting" - case .unauthorized: - return "unauthorized" - case .unknown: - return "unknown" - case .unsupported: - return "unsupported" - default: - return "unknown" - } - } - - static func peripheralStateToString(_ state: CBPeripheralState) -> String { - switch state { - case .disconnected: - return "disconnected" - case .connecting: - return "connecting" - case .connected: - return "connected" - case .disconnecting: - return "disconnecting" - default: - return "unknown" - } - } -} diff --git a/CovidSafe/CSGenericContentView.xib b/CovidSafe/CSGenericContentView.xib new file mode 100644 index 0000000..2b2d388 --- /dev/null +++ b/CovidSafe/CSGenericContentView.xib @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin vel sapien a sapien dignissim tempus. 

Vestibulum ut ante ipsum. Vivamus lobortis hendrerit elit, non maximus nulla maximus in. Vivamus euismod elementum finibus. 

Nulla leo leo, gravida vel enim in, ultricies fringilla orci. Duis tincidunt vel tortor quis pellentesque. 
Fusce sit amet elit massa. Cras tellus tortor, convallis id vulputate sit amet, accumsan sit amet nisl. + +Praesent viverra pretium lobortis. In laoreet at leo non viverra. Nullam sagittis nulla a lobortis auctor. Donec a pulvinar odio, eget eleifend velit. Maecenas vulputate eget libero at malesuada. Vestibulum orci nulla, consectetur ut lobortis a, tincidunt vel mauris. Integer et eros pharetra, porta sem et, rhoncus mauris. Duis porta semper malesuada. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/CovidSafe/CSGenericViewController.swift b/CovidSafe/CSGenericViewController.swift new file mode 100644 index 0000000..8dd663b --- /dev/null +++ b/CovidSafe/CSGenericViewController.swift @@ -0,0 +1,73 @@ +// +// CSGenericContentViewController.swift +// CovidSafe +// +// Copyright © 2020 Australian Government. All rights reserved. +// + +import UIKit +import SafariServices + +class CSGenericContentViewController: UIViewController { + + @IBOutlet weak var stepCounterLabel: UILabel! + @IBOutlet weak var contentIllustration: UIImageView! + @IBOutlet weak var contentTitleLabel: UILabel! + @IBOutlet weak var contentDescriptionText: UITextView! + @IBOutlet weak var actionButton: UIButton! + + var contentViewModel: CSGenericContentViewModel? + + override func viewDidLoad() { + super.viewDidLoad() + + guard let viewModel = contentViewModel else { + return + } + + // set the step counter + if let contentStep = viewModel.contentStepNumber, let contentTotal = viewModel.contentStepTotal { + stepCounterLabel.text = String.localizedStringWithFormat( "stepCounter".localizedString(), + contentStep, + contentTotal + ) + } else { + stepCounterLabel.text = "" + stepCounterLabel.isHidden = true + } + + // set the illustration + if let illustration = viewModel.contentIllustration { + contentIllustration.image = illustration + } + + // set title and content + contentTitleLabel.text = viewModel.viewTitle + contentDescriptionText.attributedText = viewModel.viewContentDescription + contentDescriptionText.parseHTMLTags() + contentDescriptionText.addAllBold(enclosedIn: "#") + + //set button label and action + actionButton.setTitle(viewModel.buttonLabel, for: .normal) + actionButton.addTarget(self, action: #selector(pressed), for: .touchUpInside) + } + + @objc func pressed(sender: UIButton!) { + guard let viewModel = contentViewModel else { + return + } + + viewModel.buttonCallback() + } + +} + +struct CSGenericContentViewModel { + var viewTitle: String + var viewContentDescription: NSAttributedString + var buttonLabel: String + var buttonCallback: () -> Void + var contentIllustration: UIImage? + var contentStepNumber: Int? + var contentStepTotal: Int? +} diff --git a/CovidSafe/CentralController.swift b/CovidSafe/CentralController.swift deleted file mode 100644 index e3554f4..0000000 --- a/CovidSafe/CentralController.swift +++ /dev/null @@ -1,496 +0,0 @@ -// -// CentralController.swift -// CovidSafe -// -// Copyright © 2020 Australian Government. All rights reserved. -// -import Foundation -import CoreData -import CoreBluetooth -import UIKit - -struct CentralWriteData: Codable { - var modelC: String // phone model of central - var rssi: Double - var txPower: Double? - var msg: String // tempID - var org: String - var v: Int -} - -class CentralController: NSObject { - enum CentralError: Error { - case centralAlreadyOn - case centralAlreadyOff - } - var centralDidUpdateStateCallback: ((CBManagerState) -> Void)? - var characteristicDidReadValue: ((EncounterRecord) -> Void)? - private let restoreIdentifierKey = "com.joelkek.tracer.central" - private var central: CBCentralManager? - private var recoveredPeripherals: [CBPeripheral] = [] - private var cleanupPeripherals: [CBPeripheral] = [] - private var queue: DispatchQueue - - // This dict is to keep track of discovered android devices, so that i do not connect to the same android device multiple times within the same BluetraceConfig.CentralScanInterval - private var discoveredAndroidPeriManufacturerToUUIDMap = [Data: UUID]() - - // This dict has 2 purpose - // 1. To store all the EncounterRecord, because the RSSI and TxPower is gotten at the didDiscoverPeripheral delegate, but the characterstic value is gotten at didUpdateValueForCharacteristic delegate - // 2. Use to check for duplicated iphones peripheral being discovered, so that i dont connect to the same iphone again in the same scan window - private var scannedPeripherals = [UUID: (lastUpdated: Date, peripheral: CBPeripheral, encounter: EncounterRecord)]() // stores the peripherals encountered within one scan interval - var timerForScanning: Timer? - private var lastCleanedScannedPeripherals = Date() - - public init(queue: DispatchQueue) { - self.queue = queue - - super.init() - - NotificationCenter.default.addObserver( - forName: UIApplication.didReceiveMemoryWarningNotification, - object: nil, - queue: .main) { [weak self] notification in - self?.queue.async { - self?.cleanupScannedPeripherals() - } - } - } - - func turnOn() { - DLog("CC requested to be turnOn") - guard central == nil else { - return - } - let options: [String: Any] = [CBCentralManagerOptionRestoreIdentifierKey: restoreIdentifierKey, - CBCentralManagerOptionShowPowerAlertKey: NSNumber(true)] - central = CBCentralManager(delegate: self, queue: self.queue, options: options ) - } - - func turnOff() { - DLog("CC turnOff") - guard central != nil else { - return - } - central?.stopScan() - central = nil - } - - func shouldRecordEncounter(_ encounter: EncounterRecord) -> Bool { - guard let scannedDate = encounter.timestamp else { - DLog("Not recorded encounter before \(encounter)") - return true - } - if abs(scannedDate.timeIntervalSinceNow) > BluetraceConfig.CentralScanInterval { - DLog("Encounter last recorded \(abs(scannedDate.timeIntervalSinceNow)) seconds ago") - return true - } - return false - } - - func shouldReconnectToPeripheral(peripheral: CBPeripheral) -> Bool { - guard peripheral.state == .disconnected else { - return false - } - guard let encounteredPeripheral = scannedPeripherals[peripheral.identifier] else { - DLog("Not previously encountered CBPeripheral \(String(describing: peripheral.name))") - return true - } - guard let scannedDate = encounteredPeripheral.encounter.timestamp else { - DLog("Not previously recorded an encounter with \(encounteredPeripheral)") - return true - } - if abs(scannedDate.timeIntervalSinceNow) > BluetraceConfig.CentralScanInterval { - DLog("Peripheral last recorded \(abs(scannedDate.timeIntervalSinceNow)) seconds ago") - return true - } - return false - } - - public func getState() -> CBManagerState? { - return central?.state - } - - public func logPeripheralsCount(description: String) { - #if DEBUG - guard let peripherals = central?.retrieveConnectedPeripherals(withServices: [BluetraceConfig.BluetoothServiceID]) else { - return - } - - var connected = 0 - var connecting = 0 - var disconnected = 0 - var disconnecting = 0 - var unknown = 0 - - for peripheral in peripherals { - switch peripheral.state { - case .connecting: - connecting+=1 - case .connected: - connected+=1 - case .disconnected: - disconnected+=1 - case .disconnecting: - disconnecting+=1 - default: - unknown+=1 - } - } - - let bleLogStr = "CC \(description) Current peripherals \nconnected: \(connected), \nconnecting: \(connecting), \ndisconnected: \(disconnected), \ndisconnecting: \(disconnecting), \nunknown: \(unknown), \nscannedPeripherals: \(scannedPeripherals.count)" - let logRecord = BLELogRecord(message: bleLogStr) - logRecord.saveToCoreData() - #endif - } -} - -extension CentralController: CBCentralManagerDelegate { - - func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { - DLog("CC willRestoreState. Central state: \(BluetraceUtils.centralStateToString(central.state))") - recoveredPeripherals = [] - if let peripheralsObject = dict[CBCentralManagerRestoredStatePeripheralsKey] { - let peripherals = peripheralsObject as! Array - DLog("CC restoring \(peripherals.count) peripherals from system.") - logPeripheralsCount(description: "Restoring peripherals") - for peripheral in peripherals { - if peripheral.state == .connected { - // only recover connected peripherals, dispose/disconnect otherwise. - recoveredPeripherals.append(peripheral) - peripheral.delegate = self - } else { - cleanupPeripherals.append(peripheral) - } - } - logPeripheralsCount(description: "Done Restoring peripherals") - } - } - - func centralManagerDidUpdateState(_ central: CBCentralManager) { - centralDidUpdateStateCallback?(central.state) - switch central.state { - case .poweredOn: - DLog("CC Starting a scan") - - // for all peripherals that are not disconnected, disconnect them - self.scannedPeripherals.forEach { (scannedPeri) in - central.cancelPeripheralConnection(scannedPeri.value.peripheral) - } - // clear all peripherals, such that a new scan window can take place - self.scannedPeripherals = [UUID: (Date, CBPeripheral, EncounterRecord)]() - self.discoveredAndroidPeriManufacturerToUUIDMap = [Data: UUID]() - // handle a state restoration scenario - for recoveredPeripheral in recoveredPeripherals { - var restoredEncounter = EncounterRecord(rssi: 0, txPower: nil) - restoredEncounter.timestamp = nil - scannedPeripherals.updateValue((Date(), recoveredPeripheral, restoredEncounter), - forKey: recoveredPeripheral.identifier) - central.connect(recoveredPeripheral) - } - - // can't cancel peripheral when BL OFF - for cleanupPeripheral in self.cleanupPeripherals { - central.cancelPeripheralConnection(cleanupPeripheral) - } - self.cleanupPeripherals = [] - - central.scanForPeripherals(withServices: [BluetraceConfig.BluetoothServiceID], options:nil) - logPeripheralsCount(description: "Update state powerOn") - default: - DLog("State chnged to \(central.state)") - } - } - - func handlePeripheralOfUncertainStatus(_ peripheral: CBPeripheral) { - // If not connected to Peripheral, attempt connection and exit - if peripheral.state != .connected { - DLog("CC handlePeripheralOfUncertainStatus not connected") - central?.connect(peripheral) - return - } - // If don't know about Peripheral's services, discover services and exit - if peripheral.services == nil { - DLog("CC handlePeripheralOfUncertainStatus unknown services") - peripheral.discoverServices([BluetraceConfig.BluetoothServiceID]) - return - } - // If Peripheral's services don't contain targetID, disconnect and remove, then exit. - // If it does contain targetID, discover characteristics for service - guard let service = peripheral.services?.first(where: { $0.uuid == BluetraceConfig.BluetoothServiceID }) else { - DLog("CC handlePeripheralOfUncertainStatus no matching Services") - central?.cancelPeripheralConnection(peripheral) - return - } - DLog("CC handlePeripheralOfUncertainStatus discoverCharacteristics") - peripheral.discoverCharacteristics([BluetraceConfig.BluetoothServiceID], for: service) - // If Peripheral's service's characteristics don't contain targetID, disconnect and remove, then exit. - // If it does contain targetID, read value for characteristic - guard let characteristic = service.characteristics?.first(where: { $0.uuid == BluetraceConfig.BluetoothServiceID}) else { - DLog("CC handlePeripheralOfUncertainStatus no matching Characteristics") - central?.cancelPeripheralConnection(peripheral) - return - } - DLog("CC handlePeripheralOfUncertainStatus readValue") - peripheral.readValue(for: characteristic) - return - } - - fileprivate func cleanupScannedPeripherals() { - - DLog("CC scannedPeripherals/pending connections cleanup \(scannedPeripherals.count)") - scannedPeripherals = scannedPeripherals.filter { scannedPeripheral in - // if has been sitting in scanned for over 2 mins, remove - if abs(scannedPeripheral.value.lastUpdated.timeIntervalSinceNow) > BluetraceConfig.PeripheralCleanInterval { - // expired timestamp, remove - cleanupPeripherals.append(scannedPeripheral.value.peripheral) - return false - } else { - // not yet expired timestamp, keep this scanned peripheral data - return true - } - } - - // remove android manufacturer data where peripheral has been removed - discoveredAndroidPeriManufacturerToUUIDMap = discoveredAndroidPeriManufacturerToUUIDMap.filter( - { andperi in - return !scannedPeripherals.keys.contains(andperi.value)} - ) - - - guard let central = central else { - DLog("CC central is nil, unable to clean peripherals at the moment") - return - } - - for cleanupPeripheral in cleanupPeripherals { - central.cancelPeripheralConnection(cleanupPeripheral) - } - cleanupPeripherals = [] - lastCleanedScannedPeripherals = Date() - DLog("CC post scannedPeripherals/pending connections cleanup \(scannedPeripherals.count)") - return - } - - func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { - let debugLogs = ["CentralState": BluetraceUtils.centralStateToString(central.state), - "peripheral": peripheral, - "advertisments": advertisementData as AnyObject] as AnyObject - - // dispatch in bluetrace queue - DispatchQueue.global(qos: .background).async { - MessageAPI.getMessagesIfNeeded() { (messageResponse, error) in - if let error = error { - DLog("Get messages error: \(error.localizedDescription)") - } - // We currently dont do anything with the response. Messages are delivered via APN - } - } - - DLog("\(debugLogs)") - // regularly cleanup and close pending connections - if abs(lastCleanedScannedPeripherals.timeIntervalSince(Date())) > BluetraceConfig.CentralScanInterval { - cleanupScannedPeripherals() - } - - var initialEncounter = EncounterRecord(rssi: RSSI.doubleValue, txPower: advertisementData[CBAdvertisementDataTxPowerLevelKey] as? Double) - initialEncounter.timestamp = nil - - // iphones will "mask" the peripheral's identifier for android devices, resulting in the same android device being discovered multiple times with different peripheral identifier. Hence Android is using use CBAdvertisementDataServiceDataKey data for identifying an android pheripheral - // Also, check that the length is greater than 2 to prevent crash. Otherwise ignore. - if let manuData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data, manuData.count > 2 { - let androidIdentifierData = manuData.subdata(in: 2..")") - } - } else { - DLog("Error: scannedPeripherals[peripheral.identifier] is \(String(describing: scannedPeripherals[peripheral.identifier])), characteristic.value is \(String(describing: characteristic.value))") - } - - // regularly cleanup and close pending connections - if (abs(lastCleanedScannedPeripherals.timeIntervalSince(Date())) > BluetraceConfig.CentralScanInterval) { - cleanupScannedPeripherals() - } - } - - func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { - DLog("didWriteValueFor to peripheral: \(peripheral), for characteristics: \(characteristic). \(error != nil ? "error: \(error.debugDescription)" : "" )") - central?.cancelPeripheralConnection(peripheral) - } -} diff --git a/CovidSafe/EncounterMessageManager.swift b/CovidSafe/EncounterMessageManager.swift index 421b4d2..c6e0887 100644 --- a/CovidSafe/EncounterMessageManager.swift +++ b/CovidSafe/EncounterMessageManager.swift @@ -1,10 +1,34 @@ import Foundation +import CoreBluetooth + +struct CentralWriteData: Codable { + var modelC: String // phone model of central + var rssi: Double + var txPower: Double? + var msg: String // tempID + var org: String + var v: Int +} + +public struct PeripheralCharacteristicsData: Codable { + var modelP: String // phone model of peripheral + var msg: String // tempID + var org: String + var v: Int +} class EncounterMessageManager { let userDefaultsTempIdKey = "BROADCAST_MSG" let userDefaultsAdvtKey = "ADVT_DATA" let userDefaultsAdvtExpiryKey = "ADVT_EXPIRY" + struct CachedPayload { + var payload: Data, + expiry: TimeInterval + } + + private var payloadLookaside = [UUID: CachedPayload]() + static let shared = EncounterMessageManager() var tempId: String? { @@ -75,6 +99,92 @@ class EncounterMessageManager { } } + fileprivate func cleanUpExpiredCachedPayloads() { + for payloadKey in payloadLookaside.keys { + let currentTime = Date().timeIntervalSince1970 + guard let payload = payloadLookaside[payloadKey], payload.expiry < currentTime else { + continue + } + // if payload exists and expiry time is less than current time, remove. + payloadLookaside.removeValue(forKey: payloadKey) + } + } + + func getWritePayloadForCentral(device: BLEDevice, onComplete: @escaping (Data?) -> Void) { + guard let rssi = device.rssi else { + DLog("getWritePayloadForCentral failed, no rssi") + onComplete(nil) + return + } + guard device.legacyPayloadCharacteristic != nil else { + DLog("getWritePayloadForCentral failed, no legacyPayloadCharacteristic") + onComplete(nil) + return + } + getTempId { (result) in + guard let tempId = result else { + DLog("getWritePayloadForCentral failed, no tempid") + onComplete(nil) + return + } + var txPower: Double? = nil + if let bleTxPower = device.txPower { + txPower = Double(bleTxPower) + } + + let encounterToBroadcast = EncounterBlob(modelC: DeviceIdentifier.getModel(), + rssi: Double(rssi), + txPower: txPower, + modelP: nil, + msg: tempId, + timestamp: Date().timeIntervalSince1970) + + + do { + let jsonMsg = try JSONEncoder().encode(encounterToBroadcast) + let encryptedMsg = try Crypto.encrypt(dataToEncrypt: jsonMsg) + let dataToWrite = CentralWriteData(modelC: BluetraceConfig.DummyModel, + rssi: Double(BluetraceConfig.DummyRSSI), + txPower: Double(BluetraceConfig.DummyTxPower), + msg: encryptedMsg, + org: BluetraceConfig.OrgID, + v: BluetraceConfig.ProtocolVersion) + let encodedData = try JSONEncoder().encode(dataToWrite) + onComplete(encodedData) + } catch { + DLog("Error: \(error)") + } + } + } + + func getAdvertisementPayload(identifier: UUID, offset: Int, onComplete: @escaping (Data?) -> Void) { + cleanUpExpiredCachedPayloads() + guard offset > 0 else { + // new request coming in + getAdvertisementPayload{ (payloadToAdvertise) in + if let payload = payloadToAdvertise { + self.payloadLookaside[identifier] = CachedPayload(payload: payload, expiry: Date().timeIntervalSince1970 + BluetraceConfig.PayloadExpiry); + } + onComplete(payloadToAdvertise) + } + return + } + guard let cachedPayload = self.payloadLookaside[identifier] else { + // subsequent request but nothing cached + onComplete(nil) + return + } + onComplete(cachedPayload.payload) + } + + func getLastKnownAdvertisementPayload(identifier: UUID) -> Data? { + guard let cachedPayload = self.payloadLookaside[identifier] else { + return nil + } + return cachedPayload.payload + } + + // this will give herald the payload it's after // gets the anon tempid for broadcasting func getAdvertisementPayload(onComplete: @escaping (Data?) -> Void) { // check expiry date of payload @@ -147,3 +257,36 @@ class EncounterMessageManager { } } } + + +extension EncounterMessageManager: PayloadDataSupplier { + + func payload(_ timestamp: PayloadTimestamp) -> PayloadData { + return advertisedPayload! + } + + func payload(_ identifier: UUID, offset: Int, onComplete: @escaping (PayloadData?) -> Void) -> Void { + getAdvertisementPayload(identifier: identifier, offset: offset, onComplete: onComplete) + } + + func payload(_ data: Data) -> [PayloadData] { + // We share only one payload at a time due to the length. + // No need to split payloads based on length or delimiter. + return [PayloadData(data)] + } + +} + +public extension PayloadData { + var shortName: String { + do { + let decodedPayload = try JSONDecoder().decode(PeripheralCharacteristicsData.self, from: self) + let message = decodedPayload.msg + return String(message.suffix(25)) + } catch { + let startIndex = count >= 3 ? 3 : 0 + let endIndex = count >= 3 ? count-3 : 0 + return String(subdata(in: startIndex.. BLEDevice + + /// Get or create device for collating information from asynchronous BLE operations. + func device(_ peripheral: CBPeripheral, delegate: CBPeripheralDelegate) -> BLEDevice + + /// Get or create device for collating information from asynchronous BLE operations. + func device(_ payload: PayloadData) -> BLEDevice + + /// Get if a device exists + func hasDevice(_ payload: PayloadData) -> Bool + + /// Get all devices + func devices() -> [BLEDevice] + + /// Delete device from database + func delete(_ identifier: TargetIdentifier) +} + +/// Delegate for receiving registry create/update/delete events +protocol BLEDatabaseDelegate { + + func bleDatabase(didCreate device: BLEDevice) + + func bleDatabase(didUpdate device: BLEDevice, attribute: BLEDeviceAttribute) + + func bleDatabase(didDelete device: BLEDevice) +} + +extension BLEDatabaseDelegate { + func bleDatabase(didCreate device: BLEDevice) {} + + func bleDatabase(didUpdate device: BLEDevice, attribute: BLEDeviceAttribute) {} + + func bleDatabase(didDelete device: BLEDevice) {} +} + +class ConcreteBLEDatabase : NSObject, BLEDatabase, BLEDeviceDelegate { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "BLE.ConcreteBLEDatabase") + private var delegates: [BLEDatabaseDelegate] = [] + private var database: [TargetIdentifier : BLEDevice] = [:] + private var queue = DispatchQueue(label: "Sensor.BLE.ConcreteBLEDatabase") + + func add(delegate: BLEDatabaseDelegate) { + delegates.append(delegate) + } + + func devices() -> [BLEDevice] { + return database.values.map { $0 } + } + + func device(_ identifier: TargetIdentifier) -> BLEDevice { + if database[identifier] == nil { + let device = BLEDevice(identifier, delegate: self) + database[identifier] = device + queue.async { + self.logger.debug("create (device=\(identifier))") + self.delegates.forEach { $0.bleDatabase(didCreate: device) } + } + } + let device = database[identifier]! + return device + } + + func device(_ peripheral: CBPeripheral, delegate: CBPeripheralDelegate) -> BLEDevice { + let identifier = TargetIdentifier(peripheral: peripheral) + if database[identifier] == nil { + let device = BLEDevice(identifier, delegate: self) + database[identifier] = device + queue.async { + self.logger.debug("create (device=\(identifier))") + self.delegates.forEach { $0.bleDatabase(didCreate: device) } + } + } + let device = database[identifier]! + if device.peripheral != peripheral { + device.peripheral = peripheral + peripheral.delegate = delegate + } + return device + } + + func device(_ payload: PayloadData) -> BLEDevice { + if let device = database.values.filter({ $0.payloadData == payload }).first { + return device + } + // Create temporary UUID, the taskRemoveDuplicatePeripherals function + // will delete this when a direct connection to the peripheral has been + // established + let identifier = TargetIdentifier(UUID().uuidString) + let placeholder = device(identifier) + placeholder.payloadData = payload + return placeholder + } + + func hasDevice(_ payload: PayloadData) -> Bool { + if database.values.filter({ $0.payloadData == payload }).first != nil { + return true + } + return false + } + + func delete(_ identifier: TargetIdentifier) { + guard let device = database[identifier] else { + return + } + database[identifier] = nil + queue.async { + self.logger.debug("delete (device=\(identifier))") + self.delegates.forEach { $0.bleDatabase(didDelete: device) } + } + } + + // MARK:- BLEDeviceDelegate + + func device(_ device: BLEDevice, didUpdate attribute: BLEDeviceAttribute) { + queue.async { + self.logger.debug("update (device=\(device.identifier),attribute=\(attribute.rawValue))") + self.delegates.forEach { $0.bleDatabase(didUpdate: device, attribute: attribute) } + } + } +} + +// MARK:- BLEDatabase data + +public class BLEDevice : NSObject { + /// Device registratiion timestamp + let createdAt: Date + /// Last time anything changed, e.g. attribute update + var lastUpdatedAt: Date + /// Last time a wake up call was received from this device (iOS only) + var lastNotifiedAt: Date = Date.distantPast + /// Ephemeral device identifier, e.g. peripheral identifier UUID + let identifier: TargetIdentifier + /// Pseudo device address for tracking devices that change device identifier constantly like the Samsung A10, A20 and Note 8 + var pseudoDeviceAddress: BLEPseudoDeviceAddress? { + didSet { + lastUpdatedAt = Date() + }} + /// Delegate for listening to attribute updates events. + let delegate: BLEDeviceDelegate + /// CoreBluetooth peripheral object for interacting with this device. + var peripheral: CBPeripheral? { + didSet { + lastUpdatedAt = Date() + delegate.device(self, didUpdate: .peripheral) + }} + /// Service characteristic for signalling between BLE devices, e.g. to keep awake + var signalCharacteristic: CBCharacteristic? { + didSet { + lastUpdatedAt = Date() + delegate.device(self, didUpdate: .signalCharacteristic) + }} + /// Service characteristic for reading payload data + var payloadCharacteristic: CBCharacteristic? { + didSet { + lastUpdatedAt = Date() + delegate.device(self, didUpdate: .payloadCharacteristic) + }} + var legacyPayloadCharacteristic: CBCharacteristic? { + didSet { + lastUpdatedAt = Date() + delegate.device(self, didUpdate: .payloadCharacteristic) + }} + /// Device operating system, this is necessary for selecting different interaction procedures for each platform. + var operatingSystem: BLEDeviceOperatingSystem = .unknown { + didSet { + lastUpdatedAt = Date() + delegate.device(self, didUpdate: .operatingSystem) + }} + /// Device is receive only, this is necessary for filtering payload sharing data + var receiveOnly: Bool = false { + didSet { + lastUpdatedAt = Date() + }} + /// Payload data acquired from the device via payloadCharacteristic read + var payloadData: PayloadData? { + didSet { + payloadDataLastUpdatedAt = Date() + lastUpdatedAt = payloadDataLastUpdatedAt + delegate.device(self, didUpdate: .payloadData) + }} + /// Payload data last update timestamp, this is used to determine what needs to be shared with peers. + var payloadDataLastUpdatedAt: Date = Date.distantPast + /// Payload data already shared with this peer + var payloadSharingData: [PayloadData] = [] + /// Most recent RSSI measurement taken by readRSSI or didDiscover. + var rssi: BLE_RSSI? { + didSet { + lastUpdatedAt = Date() + rssiLastUpdatedAt = lastUpdatedAt + delegate.device(self, didUpdate: .rssi) + }} + /// RSSI last update timestamp, this is used to track last advertised at without relying on didDiscover + var rssiLastUpdatedAt: Date = Date.distantPast + /// Transmit power data where available (only provided by Android devices) + var txPower: BLE_TxPower? { + didSet { + lastUpdatedAt = Date() + delegate.device(self, didUpdate: .txPower) + }} + /// Track discovered at timestamp, used by taskConnect to prioritise connection when device runs out of concurrent connection capacity + var lastDiscoveredAt: Date = Date.distantPast + /// Track connect request at timestamp, used by taskConnect to prioritise connection when device runs out of concurrent connection capacity + var lastConnectRequestedAt: Date = Date.distantPast + /// Track connected at timestamp, used by taskConnect to prioritise connection when device runs out of concurrent connection capacity + var lastConnectedAt: Date? { + didSet { + // Reset lastDisconnectedAt + lastDisconnectedAt = nil + // Reset lastConnectionInitiationAttempt + lastConnectionInitiationAttempt = nil + }} + /// Track read payload request at timestamp, used by readPayload to de-duplicate requests from asynchronous calls + var lastReadPayloadRequestedAt: Date = Date.distantPast + /// Track Herald initiated connection attempts - workaround for iOS peripheral caching incorrect state bug + var lastConnectionInitiationAttempt: Date? + /// Track disconnected at timestamp, used by taskConnect to prioritise connection when device runs out of concurrent connection capacity + var lastDisconnectedAt: Date? { + didSet { + // Reset lastConnectionInitiationAttempt + lastConnectionInitiationAttempt = nil + } + } + + /// Last advert timestamp, inferred from payloadDataLastUpdatedAt, payloadSharingDataLastUpdatedAt, rssiLastUpdatedAt + var lastAdvertAt: Date { get { + max(createdAt, lastDiscoveredAt, payloadDataLastUpdatedAt, rssiLastUpdatedAt) + }} + + /// Time interval since last payload data update, this is used to identify devices that require a payload update. + var timeIntervalSinceLastPayloadDataUpdate: TimeInterval { get { + Date().timeIntervalSince(payloadDataLastUpdatedAt) + }} + + /// Time interval since created at timestamp + var timeIntervalSinceCreated: TimeInterval { get { + Date().timeIntervalSince(createdAt) + }} + /// Time interval since last attribute value update, this is used to identify devices that may have expired and should be removed from the database. + var timeIntervalSinceLastUpdate: TimeInterval { get { + Date().timeIntervalSince(lastUpdatedAt) + }} + /// Time interval since last advert detected, this is used to detect concurrent connection quota and prioritise disconnections + var timeIntervalSinceLastAdvert: TimeInterval { get { + Date().timeIntervalSince(lastAdvertAt) + }} + /// Time interval between last connection request, this is used to priortise disconnections + var timeIntervalSinceLastConnectRequestedAt: TimeInterval { get { + Date().timeIntervalSince(lastConnectRequestedAt) + }} + /// Time interval between last connected at and last advert, this is used to estimate last period of continuous tracking, to priortise disconnections + var timeIntervalSinceLastDisconnectedAt: TimeInterval { get { + guard let lastDisconnectedAt = lastDisconnectedAt else { + return Date().timeIntervalSince(createdAt) + } + return Date().timeIntervalSince(lastDisconnectedAt) + }} + /// Time interval between last connected at and last advert, this is used to estimate last period of continuous tracking, to priortise disconnections + var timeIntervalBetweenLastConnectedAndLastAdvert: TimeInterval { get { + guard let lastConnectedAt = lastConnectedAt, lastAdvertAt > lastConnectedAt else { + return TimeInterval(0) + } + return lastAdvertAt.timeIntervalSince(lastConnectedAt) + }} + + public override var description: String { get { + return "BLEDevice[id=\(identifier),os=\(operatingSystem.rawValue),payload=\(payloadData?.shortName ?? "nil"),address=\(pseudoDeviceAddress?.data.base64EncodedString() ?? "nil")]" + }} + + init(_ identifier: TargetIdentifier, delegate: BLEDeviceDelegate) { + self.createdAt = Date() + self.identifier = identifier + self.delegate = delegate + lastUpdatedAt = createdAt + } +} + +protocol BLEDeviceDelegate { + func device(_ device: BLEDevice, didUpdate attribute: BLEDeviceAttribute) +} + +enum BLEDeviceAttribute : String { + case peripheral, signalCharacteristic, payloadCharacteristic, payloadSharingCharacteristic, operatingSystem, payloadData, rssi, txPower +} + +enum BLEDeviceOperatingSystem : String { + case android, ios, restored, unknown, shared +} + +/// RSSI in dBm. +typealias BLE_RSSI = Int + +typealias BLE_TxPower = Int + +class BLEPseudoDeviceAddress { + let address: Int + let data: Data + var description: String { get { + return "BLEPseudoDeviceAddress(address=\(address),data=\(data.base64EncodedString()))" + }} + + init?(fromAdvertisementData: [String: Any]) { + guard let manufacturerData = fromAdvertisementData["kCBAdvDataManufacturerData"] as? Data else { + return nil + } + guard let manufacturerId = manufacturerData.uint16(0), manufacturerId == BLESensorConfiguration.manufacturerIdForSensor else { + return nil + } + guard manufacturerData.count == 8 else { + return nil + } + data = Data(manufacturerData.subdata(in: 2..<8)) + var longValueData = Data(repeating: 0, count: 2) + longValueData.append(data) + guard let longValue = longValueData.int64(0) else { + return nil + } + address = Int(longValue) + } +} diff --git a/CovidSafe/Herald/Sensor/BLE/BLEReceiver.swift b/CovidSafe/Herald/Sensor/BLE/BLEReceiver.swift new file mode 100644 index 0000000..301e557 --- /dev/null +++ b/CovidSafe/Herald/Sensor/BLE/BLEReceiver.swift @@ -0,0 +1,1004 @@ +// +// BLEReceiver.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import CoreBluetooth +import os + +/** + Beacon receiver scans for peripherals with fixed service UUID. + */ +protocol BLEReceiver : Sensor { +} + +/** + Beacon receiver scans for peripherals with fixed service UUID in foreground and background modes. Background scan + for Android is trivial as scanForPeripherals will always return all Android devices on every call. Background scan for iOS + devices that are transmitting in background mode is more complex, requiring an open connection to subscribe to a + notifying characteristic that is used as trigger for keeping both iOS devices in background state (rather than suspended + or killed). For iOS - iOS devices, on detection, the receiver will (1) write blank data to the transmitter, which triggers the + transmitter to send a characteristic data update after 8 seconds, which in turns (2) triggers the receiver to receive a value + update notification, to (3) create the opportunity for a read RSSI call and repeat of this looped process that keeps both + devices awake. + + Please note, the iOS - iOS process is unreliable if (1) the user switches off bluetooth via Airplane mode settings, (2) the + device reboots, and (3) it will fail completely if the app has been killed by the user. These are conditions that cannot be + handled reliably by CoreBluetooth state restoration. + */ +class ConcreteBLEReceiver: NSObject, BLEReceiver, BLEDatabaseDelegate, CBCentralManagerDelegate, CBPeripheralDelegate { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "BLE.ConcreteBLEReceiver") + private var delegates: [SensorDelegate] = [] + private var connectionDelegate: SensorDelegate? + /// Dedicated sequential queue for all beacon transmitter and receiver tasks. + private let queue: DispatchQueue! + private let delegateQueue: DispatchQueue + /// Database of peripherals + private let database: BLEDatabase + /// Payload data supplier for parsing shared payloads + private let payloadDataSupplier: PayloadDataSupplier + /// Central manager for managing all connections, using a single manager for simplicity. + private var central: CBCentralManager! + /// Dummy data for writing to the transmitter to trigger state restoration or resume from suspend state to background state. + private let emptyData = Data(repeating: 0, count: 0) + /** + Shifting timer for triggering peripheral scan just before the app switches from background to suspend state following a + call to CoreBluetooth delegate methods. Apple documentation suggests the time limit is about 10 seconds. + */ + private var scanTimer: DispatchSourceTimer? + /// Dedicated sequential queue for the shifting timer. + private let scanTimerQueue = DispatchQueue(label: "Sensor.BLE.ConcreteBLEReceiver.ScanTimer") + /// Dedicated sequential queue for the actual scan call. + private let scheduleScanQueue = DispatchQueue(label: "Sensor.BLE.ConcreteBLEReceiver.ScheduleScan") + /// Track scan interval and up time statistics for the receiver, for debug purposes. + private let statistics = TimeIntervalSample() + /// Scan result queue for recording discovered devices with no immediate pending action. + private var scanResults: [BLEDevice] = [] + + /// Create a BLE receiver that shares the same sequential dispatch queue as the transmitter because concurrent transmit and receive + /// operations impacts CoreBluetooth stability. The receiver and transmitter share a common database of devices to enable the transmitter + /// to register centrals for resolution by the receiver as peripherals to create symmetric connections. The payload data supplier provides + /// the actual payload data to be transmitted and received via BLE. + required init(queue: DispatchQueue, delegateQueue: DispatchQueue, database: BLEDatabase, payloadDataSupplier: PayloadDataSupplier) { + self.queue = queue + self.delegateQueue = delegateQueue + self.database = database + self.payloadDataSupplier = payloadDataSupplier + super.init() + database.add(delegate: self) + } + + func add(delegate: SensorDelegate) { + delegates.append(delegate) + } + + func addConnectionDelegate(delegate: SensorDelegate) { + connectionDelegate = delegate + } + + func removeConnectionDelegate() { + connectionDelegate = nil + } + + func start() { + logger.debug("start") + + if central == nil { + self.central = CBCentralManager(delegate: self, queue: queue, options: [ + CBCentralManagerOptionRestoreIdentifierKey : "Sensor.BLE.ConcreteBLEReceiver", + // Set this to false to stop iOS from displaying an alert if the app is opened while bluetooth is off. + CBCentralManagerOptionShowPowerAlertKey : false]) + } + // Start scanning + if central.state == .poweredOn { + scan("start") + } + } + + func stop() { + logger.debug("stop") + guard central != nil else { + return + } + guard central.isScanning else { + logger.fault("stop denied, already stopped") + central = nil + return + } + // Stop scanning + scanTimer?.cancel() + scanTimer = nil + queue.async { + self.central.stopScan() + self.central = nil + } + // Cancel all connections, the resulting didDisconnect and didFailToConnect + database.devices().forEach() { device in + if let peripheral = device.peripheral, peripheral.state != .disconnected { + disconnect("stop", peripheral) + } + } + } + + // MARK:- Scan for peripherals and initiate connection if required + + /// All work starts from scan loop. + func scan(_ source: String) { + statistics.add() + logger.debug("scan (source=\(source),statistics={\(statistics.description)})") + guard central.state == .poweredOn else { + logger.fault("scan failed, bluetooth is not powered on") + return + } + // Scan for periperals advertising the sensor service. + // This will find all Android and iOS foreground adverts + // but it will miss the iOS background adverts unless + // location has been enabled and screen is on for a moment. + queue.async { self.taskScanForPeripherals() } + // Register connected peripherals that are advertising the + // sensor service. This catches the orphan peripherals that + // may have been missed by CoreBluetooth during state + // restoration or internal errors. + queue.async { self.taskRegisterConnectedPeripherals() } + // Resolve peripherals by device identifier obtained via + // the transmitter. When an iOS central connects to this + // peripheral, the transmitter code registers the central's + // address as a new device pending resolution here to + // establish a symmetric connection. This enables either + // device to detect the other (e.g. with screen on) + // and triggering both devices to detect each other. + queue.async { self.taskResolveDevicePeripherals() } + // Remove devices that have not been seen for a while as + // the identifier would have changed after about 20 mins, + // thus it is wasteful to maintain a reference. + queue.async { self.taskRemoveExpiredDevices() } + // Remove duplicate devices with the same payload but + // different identifiers. This happens frequently as + // device address changes at regular intervals as part + // of the Bluetooth privacy feature, thus it looks like + // a new device but is actually associated with the same + // payload. All references to the duplicate will be + // removed but the actual connection will be terminated + // by CoreBluetooth, often showing an API misuse warning + // which can be ignored. + queue.async { self.taskRemoveDuplicatePeripherals() } + // iOS devices are kept in background state indefinitely + // (instead of dropping into suspended or terminated state) + // by a series of time delayed BLE operations. While this + // device is awake, it will write data to other iOS devices + // to keep them awake, and vice versa. + queue.async { self.taskWakeTransmitters() } + // All devices have an upper limit on the number of concurrent + // BLE connections it can maintain. For iOS, it is usually 12 + // or above. iOS devices maintain an active connection with + // other iOS devices to keep awake and obtain regular RSSI + // measurements, thus it can track up to 12 iOS devices at any + // moment in time. Above this figure, this device will need + // to rotate (disconnect/connect) connections to multiplex + // between the iOS devices for coverage. This is unnecessary + // for tracking Android devices as they are tracked by scan + // only. A connection to Android is only required for reading + // its payload upon discovery. + queue.async { self.taskIosMultiplex() } + // Connect to discovered devices if the device has pending tasks. + // The vast majority of devices will be connected immediately upon + // discovery, if they have a pending task (e.g. to establish its + // operating system or read its payload). Devices may be discovered + // but not have a pending task if they have already been fully + // resolved (e.g. has operating system, payload and recent RSSI + // measuremnet), these are placed in the scan results queue for + // regular checking by this connect task (e.g. to read RSSI if + // the existing value is now out of date). + queue.async { self.taskConnect() } + // Schedule this scan call again for execution in at least 8 seconds + // time to repeat the scan loop. The actual call may be delayed beyond + // the 8 second delay from this point because all terminating operations + // (i.e. events that will eventually lead the app to enter suspended + // state if nothing else happens) calls this function to keep the loop + // running indefinitely. The 8 or less seconds delay was chosen to + // ensure the scan call is activated before the app naturally enters + // suspended state, but not so soon the loop runs too often. + scheduleScan("scan") + } + + /** + Schedule scan for beacons after a delay of 8 seconds to start scan again just before + state change from background to suspended. Scan is sufficient for finding Android + devices repeatedly in both foreground and background states. + */ + private func scheduleScan(_ source: String) { + scheduleScanQueue.sync { + scanTimer?.cancel() + scanTimer = DispatchSource.makeTimerSource(queue: scanTimerQueue) + scanTimer?.schedule(deadline: DispatchTime.now() + BLESensorConfiguration.notificationDelay) + scanTimer?.setEventHandler { [weak self] in + self?.scan("scheduleScan|"+source) + } + scanTimer?.resume() + } + } + + /** + Scan for peripherals advertising the beacon service. + */ + private func taskScanForPeripherals() { + // Scan for peripherals -> didDiscover + central.scanForPeripherals( + withServices: [BLESensorConfiguration.serviceUUID], + options: [CBCentralManagerScanOptionSolicitedServiceUUIDsKey: [BLESensorConfiguration.serviceUUID]]) + } + + /** + Register all connected peripherals advertising the sensor service as a device. + */ + private func taskRegisterConnectedPeripherals() { + central.retrieveConnectedPeripherals(withServices: [BLESensorConfiguration.serviceUUID]).forEach() { peripheral in + let targetIdentifier = TargetIdentifier(peripheral: peripheral) + let device = database.device(targetIdentifier) + if device.peripheral == nil || device.peripheral != peripheral { + logger.debug("taskRegisterConnectedPeripherals (device=\(device))") + _ = database.device(peripheral, delegate: self) + } + } + } + + /** + Resolve peripheral for all database devices. This enables the symmetric connection feature where connections from central to peripheral (BLETransmitter) registers the existence + of a potential peripheral for resolution by this central (BLEReceiver). + */ + private func taskResolveDevicePeripherals() { + let devicesToResolve = database.devices().filter { $0.peripheral == nil } + devicesToResolve.forEach() { device in + guard let identifier = UUID(uuidString: device.identifier) else { + return + } + let peripherals = central.retrievePeripherals(withIdentifiers: [identifier]) + if let peripheral = peripherals.last { + logger.debug("taskResolveDevicePeripherals (resolved=\(device))") + _ = database.device(peripheral, delegate: self) + } + } + } + + /** + Remove devices that have not been updated for over an hour, as the UUID is likely to have changed after being out of range for over 20 minutes, so it will require discovery. + */ + private func taskRemoveExpiredDevices() { + let devicesToRemove = database.devices().filter { Date().timeIntervalSince($0.lastUpdatedAt) > BluetraceConfig.PeripheralCleanInterval } + devicesToRemove.forEach() { device in + logger.debug("taskRemoveExpiredDevices (remove=\(device))") + database.delete(device.identifier) + if let peripheral = device.peripheral { + disconnect("taskRemoveExpiredDevices", peripheral) + } + } + } + + /** + Remove devices with the same payload data but different peripherals. + */ + private func taskRemoveDuplicatePeripherals() { + var index: [PayloadData:BLEDevice] = [:] + let devices = database.devices() + devices.forEach() { device in + guard let payloadData = device.payloadData else { + return + } + guard let duplicate = index[payloadData] else { + index[payloadData] = device + return + } + var keeping = device + if device.peripheral != nil, duplicate.peripheral == nil { + keeping = device + } else if duplicate.peripheral != nil, device.peripheral == nil { + keeping = duplicate + } else if device.payloadDataLastUpdatedAt > duplicate.payloadDataLastUpdatedAt { + keeping = device + } else { + keeping = duplicate + } + let discarding = (keeping.identifier == device.identifier ? duplicate : device) + index[payloadData] = keeping + database.delete(discarding.identifier) + self.logger.debug("taskRemoveDuplicatePeripherals (payload=\(payloadData.shortName),device=\(device.identifier),duplicate=\(duplicate.identifier),keeping=\(keeping.identifier))") + // CoreBluetooth will eventually give warning and disconnect actual duplicate silently. + // While calling disconnect here is cleaner but it will trigger didDiscover and + // retain the duplicates. Expect to see message : + // [CoreBluetooth] API MISUSE: Forcing disconnection of unused peripheral + // . + // Did you forget to cancel the connection? + } + } + + /** + Wake transmitter on all connected iOS devices + */ + private func taskWakeTransmitters() { + database.devices().forEach() { device in + guard device.operatingSystem == .ios, let peripheral = device.peripheral, peripheral.state == .connected else { + return + } + guard device.timeIntervalSinceLastUpdate < TimeInterval.minute else { + // Throttle back keep awake calls when out of range, issue pending connect instead + connect("taskWakeTransmitters", peripheral) + return + } + wakeTransmitter("taskWakeTransmitters", device) + } + } + + /** + Connect to devices and maintain concurrent connection quota + */ + private func taskConnect() { + // Get recently discovered devices + let didDiscover = taskConnectScanResults() + // Identify recently discovered devices with pending tasks : connect -> nextTask + let hasPendingTask = didDiscover.filter({ deviceHasPendingTask($0) }) + // Identify all connected (iOS) devices to trigger refresh : connect -> nextTask + let toBeRefreshed = database.devices().filter({ !hasPendingTask.contains($0) && $0.peripheral?.state == .connected }) + // Identify all unconnected devices with unknown operating system, these are + // created by ConcreteBLETransmitter on characteristic write, to ensure all + // centrals that connect to this peripheral are recorded, to enable this central + // to attempt connection to the peripheral, thus establishing a bi-directional + // connection. This is essential for iOS-iOS background detection, where the + // discovery of phoneB by phoneA, and a connection from A to B, will trigger + // B to connect to A, thus assuming location permission has been enabled, it + // will only require screen ON at either phone to trigger bi-directional connection. + let asymmetric = database.devices().filter({ !hasPendingTask.contains($0) + && $0.operatingSystem == .unknown + && $0.timeIntervalSinceLastUpdate < TimeInterval.minute + && $0.peripheral?.state != .connected }) + // Connect to recently discovered devices with pending tasks + hasPendingTask.forEach() { device in + guard let peripheral = device.peripheral else { + return + } + connect("taskConnect|hasPending", peripheral); + } + // Refresh connection to existing devices to trigger next task + toBeRefreshed.forEach() { device in + guard let peripheral = device.peripheral else { + return + } + connect("taskConnect|refresh", peripheral); + } + // Connect to unknown devices that have written to this peripheral + asymmetric.forEach() { device in + guard let peripheral = device.peripheral else { + return + } + connect("taskConnect|asymmetric", peripheral); + } + } + + /// Empty scan results to produce a list of recently discovered devices for connection and processing + private func taskConnectScanResults() -> [BLEDevice] { + var set: Set = [] + var list: [BLEDevice] = [] + while let device = scanResults.popLast() { + if set.insert(device).inserted, let peripheral = device.peripheral, peripheral.state != .connected { + list.append(device) + logger.debug("taskConnectScanResults, didDiscover (device=\(device))") + } + } + return list + } + + /// Check if device has pending task + private func deviceHasPendingTask(_ device: BLEDevice) -> Bool { + // Resolve operating system + if device.operatingSystem == .unknown || device.operatingSystem == .restored { + return true + } + // Read payload + if device.payloadData == nil { + return true + } + + // Payload update + if device.timeIntervalSinceLastPayloadDataUpdate > BluetraceConfig.PeripheralPayloadExpiry { + return true + } + + // iOS should always be connected + if device.operatingSystem == .ios, let peripheral = device.peripheral, peripheral.state != .connected { + return true + } + return false + } + + /// Check if iOS device is waiting for connection and free capacity if required + private func taskIosMultiplex() { + // Identify iOS devices + let devices = database.devices().filter({ $0.operatingSystem == .ios && $0.peripheral != nil }) + // Get a list of connected devices and uptime + let connected = devices.filter({ $0.peripheral?.state == .connected }).sorted(by: { $0.timeIntervalBetweenLastConnectedAndLastAdvert > $1.timeIntervalBetweenLastConnectedAndLastAdvert }) + // Get a list of connecting devices + let pending = devices.filter({ $0.peripheral?.state != .connected }).sorted(by: { $0.lastConnectRequestedAt < $1.lastConnectRequestedAt }) + logger.debug("taskIosMultiplex summary (connected=\(connected.count),pending=\(pending.count))") + connected.forEach() { device in + logger.debug("taskIosMultiplex, connected (device=\(device.description),upTime=\(device.timeIntervalBetweenLastConnectedAndLastAdvert))") + } + pending.forEach() { device in + logger.debug("taskIosMultiplex, pending (device=\(device.description),downTime=\(device.timeIntervalSinceLastConnectRequestedAt))") + } + // Retry all pending connections if there is surplus capacity + if connected.count < BLESensorConfiguration.concurrentConnectionQuota { + pending.forEach() { device in + guard let toBeConnected = device.peripheral else { + return + } + connect("taskIosMultiplex|retry", toBeConnected); + } + } + // Initiate multiplexing when capacity has been reached + guard connected.count > BLESensorConfiguration.concurrentConnectionQuota, pending.count > 0, let deviceToBeDisconnected = connected.first, let peripheralToBeDisconnected = deviceToBeDisconnected.peripheral, deviceToBeDisconnected.timeIntervalBetweenLastConnectedAndLastAdvert > TimeInterval.minute else { + return + } + logger.debug("taskIosMultiplex, multiplexing (toBeDisconnected=\(deviceToBeDisconnected.description))") + disconnect("taskIosMultiplex", peripheralToBeDisconnected) + pending.forEach() { device in + guard let toBeConnected = device.peripheral else { + return + } + connect("taskIosMultiplex|multiplex", toBeConnected); + } + } + + + /// Initiate next action on peripheral based on current state and information available + private func taskInitiateNextAction(_ source: String, peripheral: CBPeripheral) { + let targetIdentifier = TargetIdentifier(peripheral: peripheral) + let device = database.device(peripheral, delegate: self) + logger.debug("time since last payload=\(device.timeIntervalSinceLastPayloadDataUpdate)") + if device.rssi == nil { + // 1. RSSI + logger.debug("taskInitiateNextAction (goal=rssi,peripheral=\(targetIdentifier))") + readRSSI("taskInitiateNextAction|" + source, peripheral) + } else if (device.signalCharacteristic == nil || device.payloadCharacteristic == nil) && device.legacyPayloadCharacteristic == nil { + // 2. Characteristics + logger.debug("taskInitiateNextAction (goal=characteristics,peripheral=\(targetIdentifier))") + discoverServices("taskInitiateNextAction|" + source, peripheral) + } else if device.payloadData == nil { + // 3. Payload + logger.debug("taskInitiateNextAction (goal=payload,peripheral=\(targetIdentifier))") + readPayload("taskInitiateNextAction|" + source, device) + } else if device.timeIntervalSinceLastPayloadDataUpdate > BluetraceConfig.PeripheralPayloadExpiry { + // 4. Payload update + logger.debug("taskInitiateNextAction (goal=payloadUpdate,peripheral=\(targetIdentifier),elapsed=\(device.timeIntervalSinceLastPayloadDataUpdate))") + readPayload("taskInitiateNextAction|" + source, device) + } else if let delegatesToWrite = delegatesToWriteLegacyPayload(device: device) { + // 5. Write legacy payload + delegatesToWrite.forEach { (delegate) in + if let peripheral = device.peripheral { + writeLegacyPayload("didReadRSSI", peripheral: peripheral) + delegate.didWriteToLegacyDevice(device) + } + } + } else if device.operatingSystem != .ios { + // 6. Disconnect Android + logger.debug("taskInitiateNextAction (goal=disconnect|\(device.operatingSystem.rawValue),peripheral=\(targetIdentifier))") + disconnect("taskInitiateNextAction|" + source, peripheral) + } else { + // 7. Scan + logger.debug("taskInitiateNextAction (goal=scan,peripheral=\(targetIdentifier))") + scheduleScan("taskInitiateNextAction|" + source) + } + } + + /** + Connect peripheral. Scanning is stopped temporarily, as recommended by Apple documentation, before initiating connect, otherwise + pending scan operations tend to take priority and connect takes longer to start. Scanning is scheduled to resume later, to ensure scan + resumes, even if connect fails. + */ + private func connect(_ source: String, _ peripheral: CBPeripheral) { + let device = database.device(peripheral, delegate: self) + logger.debug("connect (source=\(source),device=\(device))") + guard central.state == .poweredOn else { + logger.fault("connect denied, central not powered on (source=\(source),device=\(device))") + return + } + queue.async { + device.lastConnectRequestedAt = Date() + self.central.retrievePeripherals(withIdentifiers: [peripheral.identifier]).forEach { + if $0.state != .connected { + // Check to see if Herald has initiated a connection attempt before + if let lastAttempt = device.lastConnectionInitiationAttempt { + // Has Herald already initiated a connect attempt? + if (Date() > lastAttempt + BLESensorConfiguration.connectionAttemptTimeout) { + // If timeout reached, force disconnect + self.logger.fault("connect, timeout forcing disconnect (source=\(source),device=\(device),elapsed=\(-lastAttempt.timeIntervalSinceNow))") + device.lastConnectionInitiationAttempt = nil + self.queue.async { self.central.cancelPeripheralConnection(peripheral) } + } else { + // If not timed out yet, keep trying + self.logger.debug("connect, retrying (source=\(source),device=\(device),elapsed=\(-lastAttempt.timeIntervalSinceNow))") + self.central.connect($0) + } + } else { + // If not, connect now + self.logger.debug("connect, initiation (source=\(source),device=\(device))") + device.lastConnectionInitiationAttempt = Date() + self.central.connect($0) + } + } else { + self.taskInitiateNextAction("connect|" + source, peripheral: $0) + } + } + } + scheduleScan("connect") + } + + /** + Disconnect peripheral. On didDisconnect, a connect request will be made for iOS devices to maintain an open connection; + there is no further action for Android. On didFailedToConnect, a connect request will be made for both iOS and Android + devices as the error is likely to be transient (as described in Apple documentation), except if the error is "Device in invalid" + then the peripheral is unregistered by removing it from the beacons table. + */ + private func disconnect(_ source: String, _ peripheral: CBPeripheral) { + let targetIdentifier = TargetIdentifier(peripheral: peripheral) + logger.debug("disconnect (source=\(source),peripheral=\(targetIdentifier))") + guard peripheral.state == .connected || peripheral.state == .connecting else { + logger.fault("disconnect denied, peripheral not connected or connecting (source=\(source),peripheral=\(targetIdentifier))") + return + } + queue.async { self.central.cancelPeripheralConnection(peripheral) } + } + + /// Read RSSI + private func readRSSI(_ source: String, _ peripheral: CBPeripheral) { + let targetIdentifier = TargetIdentifier(peripheral: peripheral) + logger.debug("readRSSI (source=\(source),peripheral=\(targetIdentifier))") + guard peripheral.state == .connected else { + logger.fault("readRSSI denied, peripheral not connected (source=\(source),peripheral=\(targetIdentifier))") + scheduleScan("readRSSI") + return + } + queue.async { peripheral.readRSSI() } + } + + /// Discover services + private func discoverServices(_ source: String, _ peripheral: CBPeripheral) { + let targetIdentifier = TargetIdentifier(peripheral: peripheral) + logger.debug("discoverServices (source=\(source),peripheral=\(targetIdentifier))") + guard peripheral.state == .connected else { + logger.fault("discoverServices denied, peripheral not connected (source=\(source),peripheral=\(targetIdentifier))") + scheduleScan("discoverServices") + return + } + queue.async { peripheral.discoverServices([BLESensorConfiguration.serviceUUID]) } + } + + /// Read payload data from device + private func readPayload(_ source: String, _ device: BLEDevice) { + logger.debug("readPayload (source=\(source),peripheral=\(device.identifier))") + guard let peripheral = device.peripheral, peripheral.state == .connected else { + logger.fault("readPayload denied, peripheral not connected (source=\(source),peripheral=\(device.identifier))") + return + } + guard let payloadCharacteristic = device.payloadCharacteristic != nil ? device.payloadCharacteristic : device.legacyPayloadCharacteristic else { + logger.fault("readPayload denied, device missing payload characteristic (source=\(source),peripheral=\(device.identifier))") + discoverServices("readPayload", peripheral) + return + } + // De-duplicate read payload requests from multiple asynchronous calls + let timeIntervalSinceLastReadPayloadRequestedAt = Date().timeIntervalSince(device.lastReadPayloadRequestedAt) + guard timeIntervalSinceLastReadPayloadRequestedAt > 2 else { + logger.fault("readPayload denied, duplicate request (source=\(source),peripheral=\(device.identifier),elapsed=\(timeIntervalSinceLastReadPayloadRequestedAt)") + return + } + // Initiate read payload + device.lastReadPayloadRequestedAt = Date() + if device.operatingSystem == .android, let peripheral = device.peripheral { + discoverServices("readPayload|android", peripheral) + } else { + queue.async { peripheral.readValue(for: payloadCharacteristic) } + } + } + + /// Retrieve delegates that are required to write legacy payload to for a specific device + private func delegatesToWriteLegacyPayload(device: BLEDevice) -> [SensorDelegate]? { + var delegatesToWriteLegacyPayload:[SensorDelegate] = [] + delegates.forEach { (delegate) in + if delegate.shouldWriteToLegacyDevice(device) { + delegatesToWriteLegacyPayload.append(delegate) + } + } + return delegatesToWriteLegacyPayload.count > 0 ? delegatesToWriteLegacyPayload : nil + } + + /// legacy covidsafe device, existing covidsafe code will have the central \ receiver write to the peripheral after it has requested to read its payload + private func writeLegacyPayload(_ source: String, peripheral: CBPeripheral) { + let device = database.device(peripheral, delegate: self) + logger.debug("writeLegacyPayload (source=\(source),peripheral=\(device.identifier))") + + guard device.rssi != nil else { + logger.fault("writeLegacyPayload denied (source=\(source), rssi should be present in \(device.identifier) before write") + return + } + guard let characteristic = device.legacyPayloadCharacteristic else { + logger.fault("writeLegacyPayload denied (source=\(source),peripheral=\(device.identifier) legacyPayloadCharacteristic not present)") + return + } + EncounterMessageManager.shared.getWritePayloadForCentral(device: device) { [weak self] (result) in + self?.queue.async { + guard let payloadToWrite = result else { + self?.logger.fault("writeLegacyPayload denied (source=\(source),peripheral=\(device.identifier) failed to obtain tempId)") + return + } + self?.logger.debug("writeLegacyPayload (source=\(source),peripheral=\(device.identifier) writing...)") + peripheral.writeValue(payloadToWrite, for: characteristic, type: .withResponse) + } + } + } + + /** + Wake transmitter by writing blank data to the beacon characteristic. This will trigger the transmitter to generate a data value update notification + in 8 seconds, which in turn will trigger this receiver to receive a didUpdateValueFor call to keep both the transmitter and receiver awake, while + maximising the time interval between bluetooth calls to minimise power usage. + */ + private func wakeTransmitter(_ source: String, _ device: BLEDevice) { + guard device.operatingSystem == .ios, let peripheral = device.peripheral, let characteristic = device.signalCharacteristic else { + return + } + logger.debug("wakeTransmitter (source=\(source),peripheral=\(device.identifier),write=\(characteristic.properties.contains(.write))") + queue.async { peripheral.writeValue(self.emptyData, for: characteristic, type: .withResponse) } + } + + // MARK:- BLEDatabaseDelegate + + func bleDatabase(didCreate device: BLEDevice) { + // FEATURE : Symmetric connection on write + // All CoreBluetooth delegate callbacks in BLETransmitter will register the central interacting with this peripheral + // in the database and generate a didCreate callback here to trigger scan, which includes a task for resolving all + // device identifiers to actual peripherals. + scheduleScan("bleDatabase:didCreate (device=\(device.identifier))") + } + + // MARK:- CBCentralManagerDelegate + + /// Reinstate devices following state restoration + func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { + // Restore -> Populate database + logger.debug("willRestoreState") + self.central = central + central.delegate = self + if let restoredPeripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] { + for peripheral in restoredPeripherals { + let targetIdentifier = TargetIdentifier(peripheral: peripheral) + let device = database.device(peripheral, delegate: self) + if device.operatingSystem == .unknown { + device.operatingSystem = .restored + } + if peripheral.state == .connected { + device.lastConnectedAt = Date() + } + logger.debug("willRestoreState (peripheral=\(targetIdentifier))") + } + } + // Reconnection check performed in scan following centralManagerDidUpdateState:central.state == .powerOn + } + + /// Start scan when bluetooth is on. + func centralManagerDidUpdateState(_ central: CBCentralManager) { + // Bluetooth on -> Scan + if (central.state == .poweredOn) { + logger.debug("Update state (state=poweredOn))") + delegateQueue.async { + self.delegates.forEach({ $0.sensor(.BLE, didUpdateState: .on) }) + self.connectionDelegate?.sensor(.BLE, didUpdateState: .on) + } + scan("updateState") + } else { + if #available(iOS 10.0, *) { + logger.debug("Update state (state=\(central.state.description))") + } else { + // Required for compatibility with iOS 9.3 + switch central.state { + case .poweredOff: + logger.debug("Update state (state=poweredOff)") + case .poweredOn: + logger.debug("Update state (state=poweredOn)") + case .resetting: + logger.debug("Update state (state=resetting)") + case .unauthorized: + logger.debug("Update state (state=unauthorized)") + case .unknown: + logger.debug("Update state (state=unknown)") + case .unsupported: + logger.debug("Update state (state=unsupported)") + default: + logger.debug("Update state (state=undefined)") + } + } + delegateQueue.async { + self.delegates.forEach({ $0.sensor(.BLE, didUpdateState: .off) }) + self.connectionDelegate?.sensor(.BLE, didUpdateState: .off) + } + } + } + + /// Share payload data across devices with the same pseudo device address + private func shareDataAcrossDevices(_ pseudoDeviceAddress: BLEPseudoDeviceAddress) { + // Get devices with the same pseudo address created recently + let devicesWithSamePseudoAddress = database.devices().filter({ pseudoDeviceAddress.address == $0.pseudoDeviceAddress?.address && $0.timeIntervalSinceCreated <= BLESensorConfiguration.androidAdvertRefreshTimeInterval }) + // Get device with most recent version of payload amongst these devices + guard let mostRecentDevice = devicesWithSamePseudoAddress.filter({ $0.payloadData != nil }).sorted(by: { $0.payloadDataLastUpdatedAt > $1.payloadDataLastUpdatedAt }).first, let payloadData = mostRecentDevice.payloadData else { + return + } + // Copy data to all devices with the same pseudo address + let payloadDataLastUpdatedAt = mostRecentDevice.payloadDataLastUpdatedAt + let devicesToCopyPayload = devicesWithSamePseudoAddress.filter({ $0.payloadData == nil }) + devicesToCopyPayload.forEach({ + $0.signalCharacteristic = mostRecentDevice.signalCharacteristic + $0.payloadCharacteristic = mostRecentDevice.payloadCharacteristic + $0.legacyPayloadCharacteristic = mostRecentDevice.legacyPayloadCharacteristic + // Only Android devices have a pseudo address + $0.operatingSystem = .android + $0.payloadData = payloadData + $0.payloadDataLastUpdatedAt = payloadDataLastUpdatedAt + logger.debug("shareDataAcrossDevices, copied payload data (from=\(mostRecentDevice.description),to=\($0.description))") + }) + // Get devices with the same payload + let devicesWithSamePayload = database.devices().filter({ payloadData == $0.payloadData }) + // Copy pseudo address to all devices with the same payload + let devicesToCopyAddress = devicesWithSamePayload.filter({ $0.pseudoDeviceAddress == nil }) + devicesToCopyAddress.forEach({ + $0.pseudoDeviceAddress = pseudoDeviceAddress + logger.debug("shareDataAcrossDevices, copied pseudo address (payloadData=\(payloadData.shortName),to=\($0.description))") + }) + } + + /// Device discovery will trigger connection to resolve operating system and read payload for iOS and Android devices. + /// Connection is kept active for iOS devices for on-going RSSI measurements, and closed for Android devices, as this + /// iOS device can rely on this discovery callback (triggered by regular scan calls) for on-going RSSI and TX power + /// updates, thus eliminating the need to keep connections open for Android devices that can cause stability issues for + /// Android devices. + func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { + + // Populate device database + let device = database.device(peripheral, delegate: self) + device.lastDiscoveredAt = Date() + device.rssi = BLE_RSSI(RSSI.intValue) + + // We set operating system to enable discovery with legacy apps + if let manuData = advertisementData[CBAdvertisementDataManufacturerDataKey] as? Data, manuData.count > 2 { + device.operatingSystem = .android + } else { + device.operatingSystem = .ios + } + + if let pseudoDeviceAddress = BLEPseudoDeviceAddress(fromAdvertisementData: advertisementData) { + device.pseudoDeviceAddress = pseudoDeviceAddress + shareDataAcrossDevices(pseudoDeviceAddress) + } + if let txPower = (advertisementData[CBAdvertisementDataTxPowerLevelKey] as? NSNumber)?.intValue { + device.txPower = BLE_TxPower(txPower) + } + logger.debug("didDiscover (device=\(device),rssi=\((String(describing: device.rssi))),txPower=\((String(describing: device.txPower))))") + if deviceHasPendingTask(device) { + connect("didDiscover", peripheral); + } else { + scanResults.append(device) + } + + // Schedule scan (actual connect is initiated from scan via prioritisation logic) + scheduleScan("didDiscover") + } + + /// Successful connection to a device will initate the next pending action. + func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { + // connect -> readRSSI -> discoverServices + let device = database.device(peripheral, delegate: self) + device.lastConnectedAt = Date() + logger.debug("didConnect (device=\(device))") + taskInitiateNextAction("didConnect", peripheral: peripheral) + } + + /// Failure to connect to a device will result in de-registration for invalid devices or reconnection attempt otherwise. + func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { + // Connect fail -> Delete | Connect + // Failure for peripherals advertising the beacon service should be transient, so try again. + // This is also where iOS reports invalidated devices if connect is called after restore, + // thus offers an opportunity for house keeping. + let device = database.device(peripheral, delegate: self) + logger.debug("didFailToConnect (device=\(device),error=\(String(describing: error)))") + if String(describing: error).contains("Device is invalid") { + logger.debug("Unregister invalid device (device=\(device))") + database.delete(device.identifier) + } else { + connect("didFailToConnect", peripheral) + } + } + + /// Graceful disconnection is usually caused by device going out of range or device changing identity, thus a reconnection call is initiated + /// here for iOS devices to resume connection where possible. This is unnecessary for Android devices as they can be rediscovered by + /// the regular scan calls. Please note, reconnection to iOS devices is likely to fail following prolonged period of being out of range as + /// the target device is likely to have changed identity after about 20 minutes. This requires rediscovery which is impossible if the iOS device + /// is in background state, hence the need for enabling location and screen on to trigger rediscovery (yes, its weird, but it works). + func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { + // Disconnected -> Connect if iOS + // Keep connection only for iOS, not necessary for Android as they are always detectable + let device = database.device(peripheral, delegate: self) + device.lastDisconnectedAt = Date() + logger.debug("didDisconnectPeripheral (device=\(device),error=\(String(describing: error)))") + if device.operatingSystem == .ios { + // Invalidate characteristics + device.signalCharacteristic = nil + device.payloadCharacteristic = nil + device.legacyPayloadCharacteristic = nil + // Reconnect + connect("didDisconnectPeripheral", peripheral) + } + } + + // MARK: - CBPeripheralDelegate + + /// Read RSSI for proximity estimation. + func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: Error?) { + // Read RSSI -> Read Code | Notify delegates -> Scan again + // This is the primary loop for iOS after initial connection and subscription to + // the notifying beacon characteristic. The loop is scan -> wakeTransmitter -> + // didUpdateValueFor -> readRSSI -> notifyDelegates -> scheduleScan -> scan + let device = database.device(peripheral, delegate: self) + device.rssi = BLE_RSSI(RSSI.intValue) + logger.debug("didReadRSSI (device=\(device),rssi=\(String(describing: device.rssi)),error=\(String(describing: error)))") + taskInitiateNextAction("didReadRSSI", peripheral: peripheral) + } + + /// Service discovery triggers characteristic discovery. + func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { + // Discover services -> Discover characteristics | Disconnect + let device = database.device(peripheral, delegate: self) + logger.debug("didDiscoverServices (device=\(device),error=\(String(describing: error)))") + guard let services = peripheral.services else { + disconnect("didDiscoverServices|serviceEmpty", peripheral) + return + } + for service in services { + if (service.uuid == BLESensorConfiguration.serviceUUID) { + logger.debug("didDiscoverServices, found sensor service (device=\(device))") + queue.async { + peripheral.discoverCharacteristics([BLESensorConfiguration.legacyCovidsafePayloadCharacteristicUUID, BLESensorConfiguration.androidSignalCharacteristicUUID, BLESensorConfiguration.payloadCharacteristicUUID, BLESensorConfiguration.iosSignalCharacteristicUUID], for: service) + } + return + } + } + disconnect("didDiscoverServices|serviceNotFound", peripheral) + // The disconnect calls here shall be handled by didDisconnect which determines whether to retry for iOS or stop for Android + } + + /// Characteristic discovery provides definitive classification and confirmation of device operating system to inform next actions. + func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { + // Discover characteristics -> Notify delegates -> Disconnect | Wake transmitter -> Scan again + let device = database.device(peripheral, delegate: self) + logger.debug("didDiscoverCharacteristicsFor (device=\(device),error=\(String(describing: error)))") + guard let characteristics = service.characteristics else { + disconnect("didDiscoverCharacteristicsFor|characteristicEmpty", peripheral) + return + } + for characteristic in characteristics { + switch characteristic.uuid { + case BLESensorConfiguration.androidSignalCharacteristicUUID: + device.operatingSystem = .android + device.signalCharacteristic = characteristic + logger.debug("didDiscoverCharacteristicsFor, found android signal characteristic (device=\(device))") + case BLESensorConfiguration.iosSignalCharacteristicUUID: + // Maintain connection with iOS devices for keep awake + let notify = characteristic.properties.contains(.notify) + let write = characteristic.properties.contains(.write) + device.operatingSystem = .ios + device.signalCharacteristic = characteristic + queue.async { + peripheral.setNotifyValue(true, for: characteristic) + } + logger.debug("didDiscoverCharacteristicsFor, found ios signal characteristic (device=\(device),notify=\(notify),write=\(write))") + case BLESensorConfiguration.payloadCharacteristicUUID: + device.payloadCharacteristic = characteristic + logger.debug("didDiscoverCharacteristicsFor, found payload characteristic (device=\(device))") + case BLESensorConfiguration.legacyCovidsafePayloadCharacteristicUUID: + // if we only have legacy characteristic, use it as will be a device with old version. Otherwise ignore and use new characteristics only. + if characteristics.count == 1 { + device.legacyPayloadCharacteristic = characteristic + logger.debug("didDiscoverCharacteristicsFor, found covidsafe legacy payload characteristic (device=\(device))") + } else { + logger.debug("didDiscoverCharacteristicsFor, found covidsafe legacy payload characteristic but discarding as there are more characteristics, assuming new ble (device=\(device))") + } + default: + logger.fault("didDiscoverCharacteristicsFor, found unknown characteristic (device=\(device),characteristic=\(characteristic.uuid))") + } + } + // Android -> Read payload + if device.operatingSystem == .android { + let payloadCharacteristic = device.payloadCharacteristic != nil ? device.payloadCharacteristic : device.legacyPayloadCharacteristic + if device.payloadData == nil || device.timeIntervalSinceLastPayloadDataUpdate > BluetraceConfig.PeripheralPayloadExpiry, let characteristicToRead = payloadCharacteristic { + device.lastReadPayloadRequestedAt = Date() + queue.async { peripheral.readValue(for: characteristicToRead) } + } else { + disconnect("didDiscoverCharacteristicsFor|android", peripheral) + } + } + // Always -> Scan again + // For initial connection, the scheduleScan call would have been made just before connect. + // It is called again here to extend the time interval between scans. + scheduleScan("didDiscoverCharacteristicsFor") + } + + /// This iOS device will write to connected iOS devices to keep them awake, and this call back provides a backup mechanism for keeping this + /// device awake for longer in the event that other devices are no longer responding or in range. + func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) { + // Wrote characteristic -> Scan again + let device = database.device(peripheral, delegate: self) + logger.debug("didWriteValueFor (device=\(device),error=\(String(describing: error)))") + // For all situations, scheduleScan would have been made earlier in the chain of async calls. + // It is called again here to extend the time interval between scans, as this is usually the + // last call made in all paths to wake the transmitter. + scheduleScan("didWriteValueFor") + } + + /// Other iOS devices may refresh (stop/restart) their adverts at regular intervals, thus triggering this service modification callback + /// to invalidate existing characteristics and reconnect to refresh the device data. + func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { + // iOS only + // Modified service -> Invalidate beacon -> Scan + let device = database.device(peripheral, delegate: self) + let characteristics = invalidatedServices.map { $0.characteristics }.count + logger.debug("didModifyServices (device=\(device),characteristics=\(characteristics))") + guard characteristics == 0 else { + return + } + device.signalCharacteristic = nil + device.payloadCharacteristic = nil + device.legacyPayloadCharacteristic = nil + if peripheral.state == .connected { + discoverServices("didModifyServices", peripheral) + } else if peripheral.state != .connecting { + connect("didModifyServices", peripheral) + } + } + + /// All read characteristic requests will trigger this call back to handle the response. + func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { + // Updated value -> Read RSSI | Read Payload + // Beacon characteristic is writable, primarily to enable non-transmitting Android devices to submit their + // beacon code and RSSI as data to the transmitter via GATT write. The characteristic is also notifying on + // iOS devices, to offer a mechanism for waking receivers. The process works as follows, (1) receiver writes + // blank data to transmitter, (2) transmitter broadcasts value update notification after 8 seconds, (3) + // receiver is woken up to handle didUpdateValueFor notification, (4) receiver calls readRSSI, (5) readRSSI + // call completes and schedules scan after 8 seconds, (6) scan writes blank data to all iOS transmitters. + // Process repeats to keep both iOS transmitters and receivers awake while maximising time interval between + // bluetooth calls to minimise power usage. + let device = database.device(peripheral, delegate: self) + logger.debug("didUpdateValueFor (device=\(device),characteristic=\(characteristic.uuid),error=\(String(describing: error)))") + switch characteristic.uuid { + case BLESensorConfiguration.iosSignalCharacteristicUUID: + // Wake up call from transmitter + logger.debug("didUpdateValueFor (device=\(device),characteristic=iosSignalCharacteristic,error=\(String(describing: error)))") + device.lastNotifiedAt = Date() + readRSSI("didUpdateValueFor", peripheral) + return + case BLESensorConfiguration.androidSignalCharacteristicUUID: + // Should not happen as Android signal is not notifying + logger.fault("didUpdateValueFor (device=\(device),characteristic=androidSignalCharacteristic,error=\(String(describing: error)))") + case BLESensorConfiguration.payloadCharacteristicUUID, BLESensorConfiguration.legacyCovidsafePayloadCharacteristicUUID: + // Read payload data + logger.debug("didUpdateValueFor (device=\(device),characteristic=payloadCharacteristic,error=\(String(describing: error)))") + if let data = characteristic.value { + device.payloadData = PayloadData(data) + } + if device.operatingSystem == .android { + disconnect("didUpdateValueFor|payload|android", peripheral) + } + default: + logger.fault("didUpdateValueFor, unknown characteristic (device=\(device),characteristic=\(characteristic.uuid),error=\(String(describing: error)))") + } + scheduleScan("didUpdateValueFor") + return + } +} + diff --git a/CovidSafe/Herald/Sensor/BLE/BLESensor.swift b/CovidSafe/Herald/Sensor/BLE/BLESensor.swift new file mode 100644 index 0000000..4a9534a --- /dev/null +++ b/CovidSafe/Herald/Sensor/BLE/BLESensor.swift @@ -0,0 +1,213 @@ +// +// BLESensor.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import CoreBluetooth + +protocol BLESensor : Sensor { +} + +/// Defines BLE sensor configuration data, e.g. service and characteristic UUIDs +struct BLESensorConfiguration { + #if DEBUG + static let logLevel: SensorLoggerLevel = .debug; + #else + static let logLevel: SensorLoggerLevel = .fault; + #endif + /** + Service UUID for beacon service. This is a fixed UUID to enable iOS devices to find each other even + in background mode. Android devices will need to find Apple devices first using the manufacturer code + then discover services to identify actual beacons. + */ + static let serviceUUID = BluetraceConfig.BluetoothServiceID + ///Signaling characteristic for controlling connection between peripheral and central, e.g. keep each other from suspend state + ///- Characteristic UUID is randomly generated V4 UUIDs that has been tested for uniqueness by conducting web searches to ensure it returns no results. + public static var androidSignalCharacteristicUUID = CBUUID(string: "f617b813-092e-437a-8324-e09a80821a11") + ///Signaling characteristic for controlling connection between peripheral and central, e.g. keep each other from suspend state + ///- Characteristic UUID is randomly generated V4 UUIDs that has been tested for uniqueness by conducting web searches to ensure it returns no results. + public static var iosSignalCharacteristicUUID = CBUUID(string: "0eb0d5f2-eae4-4a9a-8af3-a4adb02d4363") + ///Primary payload characteristic (read) for distributing payload data from peripheral to central, e.g. identity data + ///- Characteristic UUID is randomly generated V4 UUIDs that has been tested for uniqueness by conducting web searches to ensure it returns no results. + public static var payloadCharacteristicUUID = CBUUID(string: "3e98c0f8-8f05-4829-a121-43e38f8933e7") + static let legacyCovidsafePayloadCharacteristicUUID = BluetraceConfig.BluetoothServiceID + /// Time delay between notifications for subscribers. + static let notificationDelay = DispatchTimeInterval.seconds(8) + /// Time delay between advert restart + static let advertRestartTimeInterval = TimeInterval.hour + /// Herald internal connection expiry timeout + static let connectionAttemptTimeout = TimeInterval(12) + /// Expiry time for shared payloads, to ensure only recently seen payloads are shared + /// Must be > payloadSharingTimeInterval to share pending payloads + static let payloadSharingExpiryTimeInterval = TimeInterval.minute * 5 + /// Maximum number of concurrent BLE connections + static let concurrentConnectionQuota = 12 + /// Manufacturer data is being used on Android to store pseudo device address + static let manufacturerIdForSensor = UInt16(65530); + /// Advert refresh time interval on Android devices + static let androidAdvertRefreshTimeInterval = TimeInterval.minute * 15; + // Filter duplicate payload data and suppress sensor(didRead:fromTarget) delegate calls + /// - Set to .never to disable this feature + /// - Set time interval N to filter duplicate payload data seen in last N seconds + /// - Example : 60 means filter duplicates in last minute + /// - Filters all occurrences of payload data from all targets + public static var filterDuplicatePayloadData = TimeInterval(30 * 60) + + + /// Signal characteristic action code for write payload, expect 1 byte action code followed by 2 byte little-endian Int16 integer value for payload data length, then payload data + static let signalCharacteristicActionWritePayload = UInt8(1) + /// Signal characteristic action code for write RSSI, expect 1 byte action code followed by 4 byte little-endian Int32 integer value for RSSI value + static let signalCharacteristicActionWriteRSSI = UInt8(2) + /// Signal characteristic action code for write payload, expect 1 byte action code followed by 2 byte little-endian Int16 integer value for payload sharing data length, then payload sharing data + static let signalCharacteristicActionWritePayloadSharing = UInt8(3) + + /// Are Location Permissions enabled in the app, and thus awake on screen on enabled + public static var awakeOnLocationEnabled: Bool = true +} + + +/** +BLE sensor based on CoreBluetooth +Requires : Signing & Capabilities : BackgroundModes : Uses Bluetooth LE accessories = YES +Requires : Signing & Capabilities : BackgroundModes : Acts as a Bluetooth LE accessory = YES +Requires : Info.plist : Privacy - Bluetooth Always Usage Description +Requires : Info.plist : Privacy - Bluetooth Peripheral Usage Description +*/ +class ConcreteBLESensor : NSObject, BLESensor, BLEDatabaseDelegate { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "BLE.ConcreteBLESensor") + private let sensorQueue = DispatchQueue(label: "Sensor.BLE.ConcreteBLESensor.SensorQueue") + private let delegateQueue = DispatchQueue(label: "Sensor.BLE.ConcreteBLESensor.DelegateQueue") + private var delegates: [SensorDelegate] = [] + private let database: BLEDatabase + private let transmitter: BLETransmitter + private let receiver: BLEReceiver + // Record payload data to enable de-duplication + private var didReadPayloadData: [PayloadData:Date] = [:] + + init(_ payloadDataSupplier: PayloadDataSupplier) { + database = ConcreteBLEDatabase() + transmitter = ConcreteBLETransmitter(queue: sensorQueue, delegateQueue: delegateQueue, database: database, payloadDataSupplier: payloadDataSupplier) + receiver = ConcreteBLEReceiver(queue: sensorQueue,delegateQueue: delegateQueue, database: database, payloadDataSupplier: payloadDataSupplier) + super.init() + database.add(delegate: self) + } + + func start() { + logger.debug("start") + + var permissionRequested = false + if #available(iOS 13.1, *) { + permissionRequested = (CBManager.authorization != .notDetermined) + } else { + permissionRequested = CBPeripheralManager.authorizationStatus() != .notDetermined + } + + if let receiver = receiver as? ConcreteBLEReceiver, !permissionRequested { + // BLE receivers start on powerOn event, on status change the transmitter will be started. + // This is to request permissions and turn on dialogs sequentially when registering + receiver.addConnectionDelegate(delegate: self) + } + receiver.start() + + // if permissions have been requested start transmitter immediately + if permissionRequested { + transmitter.start() + } + } + + func stop() { + logger.debug("stop") + transmitter.stop() + receiver.stop() + // BLE transmitter and receivers stops on powerOff event + } + + func add(delegate: SensorDelegate) { + delegates.append(delegate) + transmitter.add(delegate: delegate) + receiver.add(delegate: delegate) + } + + // MARK:- BLEDatabaseDelegate + + func bleDatabase(didCreate device: BLEDevice) { + logger.debug("didDetect (device=\(device.identifier),payloadData=\(device.payloadData?.shortName ?? "nil"))") + delegateQueue.async { + self.delegates.forEach { $0.sensor(.BLE, didDetect: device.identifier) } + } + } + + func bleDatabase(didUpdate device: BLEDevice, attribute: BLEDeviceAttribute) { + switch attribute { + case .rssi: + guard let rssi = device.rssi else { + return + } + let proximity = Proximity(unit: .RSSI, value: Double(rssi)) + logger.debug("didMeasure (device=\(device.identifier),payloadData=\(device.payloadData?.shortName ?? "nil"),proximity=\(proximity.description))") + delegateQueue.async { + self.delegates.forEach { $0.sensor(.BLE, didMeasure: proximity, fromTarget: device.identifier) } + } + guard let payloadData = device.payloadData else { + return + } + delegateQueue.async { + self.delegates.forEach { $0.sensor(.BLE, didMeasure: proximity, fromTarget: device.identifier, withPayload: payloadData, forDevice: device) } + } + case .payloadData: + guard let payloadData = device.payloadData else { + return + } + guard device.lastReadPayloadRequestedAt != Date.distantPast else { + logger.debug("didRead payload. lastReadPayloadRequestedAt is not set and payload has been updated. This is an android data share/copy and is ignored.") + return + } + logger.debug("didRead (device=\(device.identifier),payloadData=\(payloadData.shortName))") + guard let rssi = device.rssi else { + logger.debug("didRead rssi is nil, not proceeding") + return + } + // De-duplicate payload in recent time + if BLESensorConfiguration.filterDuplicatePayloadData != .never { + let removePayloadDataBefore = Date() - BLESensorConfiguration.filterDuplicatePayloadData + let recentDidReadPayloadData = didReadPayloadData.filter({ $0.value >= removePayloadDataBefore }) + didReadPayloadData = recentDidReadPayloadData + if let lastReportedAt = didReadPayloadData[payloadData] { + logger.debug("didRead, filtered duplicate (device=\(device.identifier),payloadData=\(payloadData.shortName),lastReportedAt=\(lastReportedAt.description))") + return + } + didReadPayloadData[payloadData] = Date() + } + + let proximity = Proximity(unit: .RSSI, value: Double(rssi)) + delegateQueue.async { + self.delegates.forEach { $0.sensor(.BLE, didRead: payloadData, fromTarget: device.identifier, atProximity: proximity, withTxPower: device.txPower) } + } + default: + return + } + } + +} + +extension ConcreteBLESensor: SensorDelegate { + func sensor(_ sensor: SensorType, didUpdateState: SensorState) { + guard let receiver = receiver as? ConcreteBLEReceiver else { + return + } + receiver.removeConnectionDelegate() + transmitter.start() + } +} + +extension TargetIdentifier { + init(peripheral: CBPeripheral) { + self.init(peripheral.identifier.uuidString) + } + init(central: CBCentral) { + self.init(central.identifier.uuidString) + } +} diff --git a/CovidSafe/Herald/Sensor/BLE/BLETransmitter.swift b/CovidSafe/Herald/Sensor/BLE/BLETransmitter.swift new file mode 100644 index 0000000..d0b8fe8 --- /dev/null +++ b/CovidSafe/Herald/Sensor/BLE/BLETransmitter.swift @@ -0,0 +1,553 @@ +// +// BLETransmitter.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import CoreBluetooth + +/** + Beacon transmitter broadcasts a fixed service UUID to enable background scan by iOS. When iOS + enters background mode, the UUID will disappear from the broadcast, so Android devices need to + search for Apple devices and then connect and discover services to read the UUID. +*/ +protocol BLETransmitter : Sensor { +} + +/** + Transmitter offers two services: + 1. Signal characteristic for maintaining connection between iOS devices and also enable non-transmitting Android devices (receive only, + like the Samsung J6) to make their presence known by writing their beacon code and RSSI as data to this characteristic. + 2. Payload characteristic for publishing beacon identity data. + + Keeping the transmitter and receiver working in iOS background mode is a major challenge, in particular when both + iOS devices are in background mode. The transmitter on iOS offers a notifying beacon characteristic that is triggered + by writing anything to the characteristic. On characteristic write, the transmitter will call updateValue after 8 seconds + to notify the receivers, to wake up the receivers with a didUpdateValueFor call. The process can repeat as a loop + between the transmitter and receiver to keep both devices awake. This is unnecessary for Android-Android and also + Android-iOS and iOS-Android detection, which can rely solely on scanForPeripherals for detection. + + The notification based wake up method relies on an open connection which seems to be fine for iOS but may cause + problems for Android. Experiments have found that Android devices cannot accept new connections (without explicit + disconnect) indefinitely and the bluetooth stack ceases to function after around 500 open connections. The device + will need to be rebooted to recover. However, if each connection is disconnected, the bluetooth stack can work + indefinitely, but frequent connect and disconnect can still cause the same problem. The recommendation is to + (1) always disconnect from Android as soon as the work is complete, (2) minimise the number of connections to + an Android device, and (3) maximise time interval between connections. With all these in mind, the transmitter + on Android does not support notify and also a connect is only performed on first contact to get the bacon code. + */ +class ConcreteBLETransmitter : NSObject, BLETransmitter, CBPeripheralManagerDelegate { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "BLE.ConcreteBLETransmitter") + private var delegates: [SensorDelegate] = [] + /// Dedicated sequential queue for all beacon transmitter and receiver tasks. + private let queue: DispatchQueue + private let delegateQueue: DispatchQueue + private let database: BLEDatabase + /// Beacon code generator for creating cryptographically secure public codes that can be later used for on-device matching. + private let payloadDataSupplier: PayloadDataSupplier + /// Peripheral manager for managing all connections, using a single manager for simplicity. + private var peripheral: CBPeripheralManager! + /// Beacon service and characteristics being broadcasted by the transmitter. + private var signalCharacteristic: CBMutableCharacteristic? + private var payloadCharacteristic: CBMutableCharacteristic? + private var legacyCovidPayloadCharacteristic: CBMutableCharacteristic? + private var advertisingStartedAt: Date = Date.distantPast + /// Dummy data for writing to the receivers to trigger state restoration or resume from suspend state to background state. + private let emptyData = Data(repeating: 0, count: 0) + /** + Shifting timer for triggering notify for subscribers several seconds after resume from suspend state to background state, + but before re-entering suspend state. The time limit is under 10 seconds as desribed in Apple documentation. + */ + private var notifyTimer: DispatchSourceTimer? + /// Dedicated sequential queue for the shifting timer. + private let notifyTimerQueue = DispatchQueue(label: "Sensor.BLE.ConcreteBLETransmitter.Timer") + + /** + Create a transmitter that uses the same sequential dispatch queue as the receiver. + Transmitter starts automatically when Bluetooth is enabled. + */ + init(queue: DispatchQueue, delegateQueue: DispatchQueue, database: BLEDatabase, payloadDataSupplier: PayloadDataSupplier) { + self.queue = queue + self.delegateQueue = delegateQueue + self.database = database + self.payloadDataSupplier = payloadDataSupplier + super.init() + + } + + func add(delegate: SensorDelegate) { + delegates.append(delegate) + } + + func start() { + logger.debug("start") + + // Create a peripheral that supports state restoration + if peripheral == nil { + self.peripheral = CBPeripheralManager(delegate: self, queue: queue, options: [ + CBPeripheralManagerOptionRestoreIdentifierKey : "Sensor.BLE.ConcreteBLETransmitter", + CBPeripheralManagerOptionShowPowerAlertKey : true + ]) + } + + guard peripheral.state == .poweredOn else { + logger.fault("start denied, not powered on") + return + } + if signalCharacteristic != nil, payloadCharacteristic != nil, legacyCovidPayloadCharacteristic != nil { + logger.debug("starting advert with existing characteristics") + if !peripheral.isAdvertising { + startAdvertising(withNewCharacteristics: false) + } else { + queue.async { + self.peripheral.stopAdvertising() + self.peripheral.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [BLESensorConfiguration.serviceUUID]]) + } + } + logger.debug("start successful, for existing characteristics") + } else { + startAdvertising(withNewCharacteristics: true) + logger.debug("start successful, for new characteristics") + } + signalCharacteristic?.subscribedCentrals?.forEach() { central in + // FEATURE : Symmetric connection on subscribe + _ = database.device(central.identifier.uuidString) + } + notifySubscribers("start") + } + + func stop() { + logger.debug("stop") + guard peripheral != nil else { + return + } + guard peripheral.isAdvertising else { + logger.fault("stop denied, already stopped (source=%s)") + self.peripheral = nil + return + } + stopAdvertising() + } + + private func startAdvertising(withNewCharacteristics: Bool) { + logger.debug("startAdvertising (withNewCharacteristics=\(withNewCharacteristics))") + if withNewCharacteristics || signalCharacteristic == nil || payloadCharacteristic == nil || legacyCovidPayloadCharacteristic == nil { + signalCharacteristic = CBMutableCharacteristic(type: BLESensorConfiguration.iosSignalCharacteristicUUID, properties: [.write, .notify], value: nil, permissions: [.writeable]) + payloadCharacteristic = CBMutableCharacteristic(type: BLESensorConfiguration.payloadCharacteristicUUID, properties: [.read], value: nil, permissions: [.readable]) + legacyCovidPayloadCharacteristic = CBMutableCharacteristic(type: BluetraceConfig.BluetoothServiceID, properties: [.read, .write, .writeWithoutResponse], value: nil, permissions: [.readable, .writeable]) + } + let service = CBMutableService(type: BLESensorConfiguration.serviceUUID, primary: true) + signalCharacteristic?.value = nil + payloadCharacteristic?.value = nil + legacyCovidPayloadCharacteristic?.value = nil + service.characteristics = [signalCharacteristic!, payloadCharacteristic!, legacyCovidPayloadCharacteristic!] + queue.async { + self.peripheral.stopAdvertising() + self.peripheral.removeAllServices() + self.peripheral.add(service) + self.peripheral.startAdvertising([CBAdvertisementDataServiceUUIDsKey : [BLESensorConfiguration.serviceUUID]]) + } + } + + private func stopAdvertising() { + logger.debug("stopAdvertising()") + queue.async { + self.peripheral.stopAdvertising() + self.peripheral = nil + } + notifyTimer?.cancel() + notifyTimer = nil + } + + /// All work starts from notify subscribers loop. + /// Generate updateValue notification after 8 seconds to notify all subscribers and keep the iOS receivers awake. + private func notifySubscribers(_ source: String) { + notifyTimer?.cancel() + notifyTimer = DispatchSource.makeTimerSource(queue: notifyTimerQueue) + notifyTimer?.schedule(deadline: DispatchTime.now() + BLESensorConfiguration.notificationDelay) + notifyTimer?.setEventHandler { [weak self] in + guard let s = self, let logger = self?.logger, let signalCharacteristic = self?.signalCharacteristic else { + return + } + // Notify subscribers to keep them awake + s.queue.async { + logger.debug("notifySubscribers (source=\(source))") + s.peripheral.updateValue(s.emptyData, for: signalCharacteristic, onSubscribedCentrals: nil) + } + // Restart advert if required + let advertUpTime = Date().timeIntervalSince(s.advertisingStartedAt) + if s.peripheral.isAdvertising, advertUpTime > BLESensorConfiguration.advertRestartTimeInterval { + logger.debug("advertRestart (upTime=\(advertUpTime))") + s.startAdvertising(withNewCharacteristics: true) + } + } + notifyTimer?.resume() + } + + // MARK:- CBPeripheralManagerDelegate + + /// Restore advert and reinstate advertised characteristics. + func peripheralManager(_ peripheral: CBPeripheralManager, willRestoreState dict: [String : Any]) { + logger.debug("willRestoreState") + self.peripheral = peripheral + peripheral.delegate = self + if let services = dict[CBPeripheralManagerRestoredStateServicesKey] as? [CBMutableService] { + for service in services { + logger.debug("willRestoreState (service=\(service.uuid.uuidString))") + if let characteristics = service.characteristics { + for characteristic in characteristics { + logger.debug("willRestoreState (characteristic=\(characteristic.uuid.uuidString))") + switch characteristic.uuid { + case BLESensorConfiguration.androidSignalCharacteristicUUID: + if let mutableCharacteristic = characteristic as? CBMutableCharacteristic { + signalCharacteristic = mutableCharacteristic + logger.debug("willRestoreState (androidSignalCharacteristic=\(characteristic.uuid.uuidString))") + } else { + logger.fault("willRestoreState characteristic not mutable (androidSignalCharacteristic=\(characteristic.uuid.uuidString))") + } + case BLESensorConfiguration.iosSignalCharacteristicUUID: + if let mutableCharacteristic = characteristic as? CBMutableCharacteristic { + signalCharacteristic = mutableCharacteristic + logger.debug("willRestoreState (iosSignalCharacteristic=\(characteristic.uuid.uuidString))") + } else { + logger.fault("willRestoreState characteristic not mutable (iosSignalCharacteristic=\(characteristic.uuid.uuidString))") + } + case BLESensorConfiguration.payloadCharacteristicUUID: + if let mutableCharacteristic = characteristic as? CBMutableCharacteristic { + payloadCharacteristic = mutableCharacteristic + logger.debug("willRestoreState (payloadCharacteristic=\(characteristic.uuid.uuidString))") + } else { + logger.fault("willRestoreState characteristic not mutable (payloadCharacteristic=\(characteristic.uuid.uuidString))") + } + default: + logger.debug("willRestoreState (unknownCharacteristic=\(characteristic.uuid.uuidString))") + } + } + } + } + } + } + + /// Start advertising on bluetooth power on. + func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) { + // Bluetooth on -> Advertise + if (peripheral.state == .poweredOn) { + logger.debug("Update state (state=poweredOn)") + start() + } else { + if #available(iOS 10.0, *) { + logger.debug("Update state (state=\(peripheral.state.description))") + } else { + // Required to support iOS 9.3 + switch peripheral.state { + case .poweredOff: + logger.debug("Update state (state=poweredOff)") + case .poweredOn: + logger.debug("Update state (state=poweredOn)") + case .resetting: + logger.debug("Update state (state=resetting)") + case .unauthorized: + logger.debug("Update state (state=unauthorized)") + case .unknown: + logger.debug("Update state (state=unknown)") + case .unsupported: + logger.debug("Update state (state=unsupported)") + default: + logger.debug("Update state (state=undefined)") + } + } + } + } + + func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) { + logger.debug("peripheralManagerDidStartAdvertising (error=\(String(describing: error)))") + if error == nil { + advertisingStartedAt = Date() + } + } + + /** + Write request offers a mechanism for non-transmitting BLE devices (e.g. Samsung J6 can only receive) to make + its presence known by submitting its beacon code and RSSI as data. This also offers a mechanism for iOS to + write blank data to transmitter to keep bringing it back from suspended state to background state which increases + its chance of background scanning over a long period without being killed off. Payload sharing is also based on + write characteristic to enable Android peers to act as a bridge for sharing iOS device payloads, thus enabling + iOS - iOS background detection without location permission or screen on, as background detection and tracking method. + */ + func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) { + // Write -> Notify delegates -> Write response -> Notify subscribers + for request in requests { + let targetIdentifier = TargetIdentifier(central: request.central) + // FEATURE : Symmetric connection on write + let targetDevice = database.device(targetIdentifier) + logger.debug("didReceiveWrite (central=\(targetIdentifier))") + if let data = request.value { + guard request.characteristic.uuid != legacyCovidPayloadCharacteristic?.uuid else { + logger.debug("didReceiveWrite (central=\(targetIdentifier),action=writeLegacyCovidPayload)") + + // we don't do anything with the payload. + // Herald relies only on reads. Therefore when legacy writes we ignore. + // However, to maintain legacy data as expected, payload is still written after read. + // See BLEReceiver writeLegacyPayload + queue.async { peripheral.respond(to: request, withResult: .success) } + continue + } + if data.count == 0 { + // Receiver writes blank data on detection of transmitter to bring iOS transmitter back from suspended state + logger.debug("didReceiveWrite (central=\(targetIdentifier),action=wakeTransmitter)") + queue.async { peripheral.respond(to: request, withResult: .success) } + } else if let actionCode = data.uint8(0) { + switch actionCode { + case BLESensorConfiguration.signalCharacteristicActionWritePayload: + // Receive-only Android device writing its payload to make its presence known + logger.debug("didReceiveWrite (central=\(targetIdentifier),action=writePayload)") + // writePayload data format + // 0-0 : actionCode + // 1-2 : payload data count in bytes (Int16) + // 3.. : payload data + if let payloadDataCount = data.int16(1) { + logger.debug("didReceiveWrite -> didDetect=\(targetIdentifier)") + delegateQueue.async { + self.delegates.forEach { $0.sensor(.BLE, didDetect: targetIdentifier) } + } + if data.count == (3 + payloadDataCount) { + let payloadData = PayloadData(data.subdata(in: 3.. didRead=\(payloadData.shortName),fromTarget=\(targetIdentifier)") + targetDevice.operatingSystem = .android + targetDevice.receiveOnly = true + targetDevice.payloadData = payloadData + queue.async { peripheral.respond(to: request, withResult: .success) } + } else { + logger.fault("didReceiveWrite, invalid payload (central=\(targetIdentifier),action=writePayload)") + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + } + } else { + logger.fault("didReceiveWrite, invalid request (central=\(targetIdentifier),action=writePayload)") + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + + } + case BLESensorConfiguration.signalCharacteristicActionWriteRSSI: + // Receive-only Android device writing its RSSI to make its proximity known + logger.debug("didReceiveWrite (central=\(targetIdentifier),action=writeRSSI)") + // writeRSSI data format + // 0-0 : actionCode + // 1-2 : rssi value (Int16) + if let rssi = data.int16(1) { + let proximity = Proximity(unit: .RSSI, value: Double(rssi)) + logger.debug("didReceiveWrite -> didMeasure=\(proximity.description),fromTarget=\(targetIdentifier)") + targetDevice.operatingSystem = .android + targetDevice.receiveOnly = true + targetDevice.rssi = BLE_RSSI(rssi) + queue.async { peripheral.respond(to: request, withResult: .success) } + } else { + logger.fault("didReceiveWrite, invalid request (central=\(targetIdentifier),action=writeRSSI)") + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + } + case BLESensorConfiguration.signalCharacteristicActionWritePayloadSharing: + // Android device sharing detected iOS devices with this iOS device to enable background detection + logger.debug("didReceiveWrite (central=\(targetIdentifier),action=writePayloadSharing)") + // writePayloadSharing data format + // 0-0 : actionCode + // 1-2 : rssi value (Int16) + // 3-4 : payload sharing data count in bytes (Int16) + // 5.. : payload sharing data (to be parsed by payload data supplier) + if let rssi = data.int16(1), let payloadDataCount = data.int16(3) { + // skip if a payload with length 0 is sent + if data.count == (5 + payloadDataCount) && payloadDataCount > 0 { + let payloadSharingData = payloadDataSupplier.payload(data.subdata(in: 5.. didShare=\(payloadSharingData.description),fromTarget=\(targetIdentifier)") + let proximity = Proximity(unit: .RSSI, value: Double(rssi)) + + var filteredPayloadSharingData: [PayloadData] + if let cachedPayload = EncounterMessageManager.shared.getLastKnownAdvertisementPayload(identifier: request.central.identifier) { + // check that the shared data is not the data sent to devices we are receiving from and it does not exist already + filteredPayloadSharingData = payloadSharingData.filter({ (dataToCheck) -> Bool in + return dataToCheck != cachedPayload && !self.database.hasDevice(dataToCheck) + }) + } else { + // check that it does not exist already + filteredPayloadSharingData = payloadSharingData.filter({ (dataToCheck) -> Bool in + return !self.database.hasDevice(dataToCheck) + }) + } + + self.logger.debug("didReceiveWrite -> filtered didShare=\(filteredPayloadSharingData.description),fromTarget=\(targetIdentifier)") + + queue.async { peripheral.respond(to: request, withResult: .success) } + + + targetDevice.operatingSystem = .android + targetDevice.rssi = BLE_RSSI(rssi) + filteredPayloadSharingData.forEach() { payloadData in + logger.debug("didReceiveWrite, storing device with shared payload=\(payloadData.shortName)") + let sharedDevice = self.database.device(payloadData) + if sharedDevice.operatingSystem == .unknown { + sharedDevice.operatingSystem = .shared + } + sharedDevice.rssi = BLE_RSSI(rssi) + + self.delegateQueue.async { + self.delegates.forEach { + $0.sensor(.BLE, didShare: filteredPayloadSharingData, fromTarget: sharedDevice.identifier, atProximity: proximity) + } + } + } + + } else { + logger.fault("didReceiveWrite, invalid payload (central=\(targetIdentifier),action=writePayloadSharing)") + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + } + } else { + logger.fault("didReceiveWrite, invalid request (central=\(targetIdentifier),action=writePayloadSharing)") + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + } + default: + logger.fault("didReceiveWrite (central=\(targetIdentifier),action=unknown,actionCode=\(actionCode))") + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + } + } + } else { + queue.async { peripheral.respond(to: request, withResult: .invalidAttributeValueLength) } + } + } + notifySubscribers("didReceiveWrite") + } + + /// Read request from central for obtaining payload data from this peripheral. + func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) { + // Read -> Notify subscribers + let central = database.device(TargetIdentifier(request.central.identifier.uuidString)) + switch request.characteristic.uuid { + case BLESensorConfiguration.payloadCharacteristicUUID, BLESensorConfiguration.legacyCovidsafePayloadCharacteristicUUID: + logger.debug("Read received (central=\(central.description),characteristic=payload,offset=\(request.offset))") + payloadDataSupplier.payload(request.central.identifier, + offset: request.offset) { [self] (payloadData) in + queue.async { + guard let data = payloadData else { + peripheral.respond(to: request, withResult: .unlikelyError) + return + } + logger.debug("Read received (central=\(central.description),characteristic=\(request.characteristic.uuid),payload=\(data.shortName))") + guard request.offset < data.count else { + logger.fault("Read, invalid offset (central=\(central.description),characteristic=payload,offset=\(request.offset),data=\(data.count))") + peripheral.respond(to: request, withResult: .invalidOffset) + return + } + guard request.offset != data.count else { + // the receiver already read all the data in its last read request + peripheral.respond(to: request, withResult: .success) + return + } + request.value = (request.offset == 0 ? data : data.subdata(in: request.offset.. Notify subscribers + // iOS receiver subscribes to the signal characteristic on first contact. This ensures the first call keeps + // the transmitter and receiver awake. Future loops will rely on didReceiveWrite as the trigger. + logger.debug("Subscribe (central=\(central.identifier.uuidString))") + // FEATURE : Symmetric connection on subscribe + _ = database.device(central.identifier.uuidString) + notifySubscribers("didSubscribeTo") + } + + func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) { + // Unsubscribe -> Notify subscribers + logger.debug("Unsubscribe (central=\(central.identifier.uuidString))") + // FEATURE : Symmetric connection on unsubscribe + _ = database.device(central.identifier.uuidString) + notifySubscribers("didUnsubscribeFrom") + } +} + +extension Data { + /// Get Int8 from byte array (little-endian). + func int8(_ index: Int) -> Int8? { + guard let value = uint8(index) else { + return nil + } + return Int8(bitPattern: value) + } + + /// Get UInt8 from byte array (little-endian). + func uint8(_ index: Int) -> UInt8? { + let bytes = [UInt8](self) + guard index < bytes.count else { + return nil + } + return bytes[index] + } + + /// Get Int16 from byte array (little-endian). + func int16(_ index: Int) -> Int16? { + guard let value = uint16(index) else { + return nil + } + return Int16(bitPattern: value) + } + + /// Get UInt16 from byte array (little-endian). + func uint16(_ index: Int) -> UInt16? { + let bytes = [UInt8](self) + guard index < (bytes.count - 1) else { + return nil + } + return UInt16(bytes[index]) | + UInt16(bytes[index + 1]) << 8 + } + + /// Get Int32 from byte array (little-endian). + func int32(_ index: Int) -> Int32? { + guard let value = uint32(index) else { + return nil + } + return Int32(bitPattern: value) + } + + /// Get UInt32 from byte array (little-endian). + func uint32(_ index: Int) -> UInt32? { + let bytes = [UInt8](self) + guard index < (bytes.count - 3) else { + return nil + } + return UInt32(bytes[index]) | + UInt32(bytes[index + 1]) << 8 | + UInt32(bytes[index + 2]) << 16 | + UInt32(bytes[index + 3]) << 24 + } + + /// Get Int64 from byte array (little-endian). + func int64(_ index: Int) -> Int64? { + guard let value = uint64(index) else { + return nil + } + return Int64(bitPattern: value) + } + + /// Get UInt64 from byte array (little-endian). + func uint64(_ index: Int) -> UInt64? { + let bytes = [UInt8](self) + guard index < (bytes.count - 7) else { + return nil + } + return UInt64(bytes[index]) | + UInt64(bytes[index + 1]) << 8 | + UInt64(bytes[index + 2]) << 16 | + UInt64(bytes[index + 3]) << 24 | + UInt64(bytes[index + 4]) << 32 | + UInt64(bytes[index + 5]) << 40 | + UInt64(bytes[index + 6]) << 48 | + UInt64(bytes[index + 7]) << 56 + } +} diff --git a/CovidSafe/Herald/Sensor/BLE/BLEUtilities.swift b/CovidSafe/Herald/Sensor/BLE/BLEUtilities.swift new file mode 100644 index 0000000..29c453e --- /dev/null +++ b/CovidSafe/Herald/Sensor/BLE/BLEUtilities.swift @@ -0,0 +1,195 @@ +// +// BLEUtilities.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import CoreBluetooth + +/** + Extension to make the state human readable in logs. + */ +@available(iOS 10.0, *) +extension CBManagerState: CustomStringConvertible { + /** + Get plain text description of state. + */ + public var description: String { + switch self { + case .poweredOff: return ".poweredOff" + case .poweredOn: return ".poweredOn" + case .resetting: return ".resetting" + case .unauthorized: return ".unauthorized" + case .unknown: return ".unknown" + case .unsupported: return ".unsupported" + @unknown default: return "undefined" + } + } +} + +extension CBPeripheralManagerState : CustomStringConvertible { + /** + Get plain text description of state. + */ + public var description: String { + switch self { + case .poweredOff: return ".poweredOff" + case .poweredOn: return ".poweredOn" + case .resetting: return ".resetting" + case .unauthorized: return ".unauthorized" + case .unknown: return ".unknown" + case .unsupported: return ".unsupported" + @unknown default: return "undefined" + } + } +} + +extension CBCentralManagerState : CustomStringConvertible { + /** + Get plain text description of state. + */ + public var description: String { + switch self { + case .poweredOff: return ".poweredOff" + case .poweredOn: return ".poweredOn" + case .resetting: return ".resetting" + case .unauthorized: return ".unauthorized" + case .unknown: return ".unknown" + case .unsupported: return ".unsupported" + @unknown default: return "undefined" + } + } +} + + +/** + Extension to make the state human readable in logs. + */ +extension CBPeripheralState: CustomStringConvertible { + /** + Get plain text description fo state. + */ + public var description: String { + switch self { + case .connected: return ".connected" + case .connecting: return ".connecting" + case .disconnected: return ".disconnected" + case .disconnecting: return ".disconnecting" + @unknown default: return "undefined" + } + } +} + +/** + Extension to make the time intervals more human readable in code. + */ +extension TimeInterval { + static var day: TimeInterval { get { TimeInterval(86400) } } + static var hour: TimeInterval { get { TimeInterval(3600) } } + static var minute: TimeInterval { get { TimeInterval(60) } } + static var never: TimeInterval { get { TimeInterval(Int.max) } } +} + +/** + Sample statistics. + */ +class Sample { + private var n:Int64 = 0 + private var m1:Double = 0.0 + private var m2:Double = 0.0 + private var m3:Double = 0.0 + private var m4:Double = 0.0 + + /** + Minimum sample value. + */ + var min:Double? = nil + /** + Maximum sample value. + */ + var max:Double? = nil + /** + Sample size. + */ + var count:Int64 { get { n } } + /** + Mean sample value. + */ + var mean:Double? { get { n > 0 ? m1 : nil } } + /** + Sample variance. + */ + var variance:Double? { get { n > 1 ? m2 / Double(n - 1) : nil } } + /** + Sample standard deviation. + */ + var standardDeviation:Double? { get { n > 1 ? sqrt(m2 / Double(n - 1)) : nil } } + /** + String representation of mean, standard deviation, min and max + */ + var description: String { get { + let sCount = n.description + let sMean = (mean == nil ? "-" : mean!.description) + let sStandardDeviation = (standardDeviation == nil ? "-" : standardDeviation!.description) + let sMin = (min == nil ? "-" : min!.description) + let sMax = (max == nil ? "-" : max!.description) + return "count=" + sCount + ",mean=" + sMean + ",sd=" + sStandardDeviation + ",min=" + sMin + ",max=" + sMax + } } + + /** + Add sample value. + */ + func add(_ x:Double) { + // Sample value accumulation algorithm avoids reiterating sample to compute variance. + let n1 = n + n += 1 + let d = x - m1 + let d_n = d / Double(n) + let d_n2 = d_n * d_n; + let t = d * d_n * Double(n1); + m1 += d_n; + m4 += t * d_n2 * Double(n * n - 3 * n + 3) + 6 * d_n2 * m2 - 4 * d_n * m3; + m3 += t * d_n * Double(n - 2) - 3 * d_n * m2; + m2 += t; + if min == nil || x < min! { + min = x; + } + if max == nil || x > max! { + max = x; + } + } +} + +/** + Time interval samples for collecting elapsed time statistics. + */ +class TimeIntervalSample : Sample { + private var startTime: Date? + private var timestamp: Date? + var period: TimeInterval? { get { + (startTime == nil ? nil : timestamp?.timeIntervalSince(startTime!)) + }} + + override var description: String { get { + let sPeriod = (period == nil ? "-" : period!.description) + return super.description + ",period=" + sPeriod + }} + + /** + Add elapsed time since last call to add() as sample. + */ + func add() { + guard timestamp != nil else { + timestamp = Date() + startTime = timestamp + return + } + let now = Date() + if let timestamp = timestamp { + add(now.timeIntervalSince(timestamp)) + } + timestamp = now + } +} diff --git a/CovidSafe/Herald/Sensor/Data/BatteryLog.swift b/CovidSafe/Herald/Sensor/Data/BatteryLog.swift new file mode 100644 index 0000000..2a031ec --- /dev/null +++ b/CovidSafe/Herald/Sensor/Data/BatteryLog.swift @@ -0,0 +1,50 @@ +// +// BatteryLog.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import UIKit +import NotificationCenter +import os + +/// Battery log for monitoring battery level over time +class BatteryLog { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "BatteryLog") + private let textFile: TextFile + private let dateFormatter = DateFormatter() + private let updateInterval = TimeInterval(30) + + init(filename: String) { + textFile = TextFile(filename: filename) + if textFile.empty() { + textFile.write("time,source,level") + } + dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + UIDevice.current.isBatteryMonitoringEnabled = true + NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelDidChange), name: UIDevice.batteryLevelDidChangeNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(batteryStateDidChange), name: UIDevice.batteryStateDidChangeNotification, object: nil) + let _ = Timer.scheduledTimer(timeInterval: updateInterval, target: self, selector: #selector(update), userInfo: nil, repeats: true) + } + + private func timestamp() -> String { + let timestamp = dateFormatter.string(from: Date()) + return timestamp + } + + @objc func update() { + let powerSource = (UIDevice.current.batteryState == .unplugged ? "battery" : "external") + let batteryLevel = Float(UIDevice.current.batteryLevel * 100).description + textFile.write(timestamp() + "," + powerSource + "," + batteryLevel) + logger.debug("update (powerSource=\(powerSource),batteryLevel=\(batteryLevel))"); + } + + @objc func batteryLevelDidChange(_ sender: NotificationCenter) { + update() + } + + @objc func batteryStateDidChange(_ sender: NotificationCenter) { + update() + } +} diff --git a/CovidSafe/Herald/Sensor/Data/ContactLog.swift b/CovidSafe/Herald/Sensor/Data/ContactLog.swift new file mode 100644 index 0000000..71ec906 --- /dev/null +++ b/CovidSafe/Herald/Sensor/Data/ContactLog.swift @@ -0,0 +1,57 @@ +// +// ContactLog.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation + +/// CSV contact log for post event analysis and visualisation +class ContactLog: NSObject, SensorDelegate { + private let textFile: TextFile + private let dateFormatter = DateFormatter() + + init(filename: String) { + textFile = TextFile(filename: filename) + if textFile.empty() { + textFile.write("time,sensor,id,detect,read,measure,share,visit,data") + } + dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + } + + private func timestamp() -> String { + let timestamp = dateFormatter.string(from: Date()) + return timestamp + } + + private func csv(_ value: String) -> String { + return TextFile.csv(value) + } + + // MARK:- SensorDelegate + + func sensor(_ sensor: SensorType, didDetect: TargetIdentifier) { + textFile.write(timestamp() + "," + sensor.rawValue + "," + csv(didDetect) + ",1,,,,,") + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier) { + textFile.write(timestamp() + "," + sensor.rawValue + "," + csv(fromTarget) + ",,2,,,," + csv(didRead.shortName)) + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier, atProximity: Proximity, withTxPower: Int?) { + textFile.write(timestamp() + "," + sensor.rawValue + "," + csv(fromTarget) + ",,2,,,," + csv(didRead.shortName)) + } + + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier) { + textFile.write(timestamp() + "," + sensor.rawValue + "," + csv(fromTarget) + ",,,3,,," + csv(didMeasure.description)) + } + + func sensor(_ sensor: SensorType, didShare: [PayloadData], fromTarget: TargetIdentifier, atProximity: Proximity) { + let prefix = timestamp() + "," + sensor.rawValue + "," + csv(fromTarget) + didShare.forEach() { payloadData in + textFile.write(prefix + ",,,,4,," + csv(payloadData.shortName)) + } + } + +} diff --git a/CovidSafe/Herald/Sensor/Data/DetectionLog.swift b/CovidSafe/Herald/Sensor/Data/DetectionLog.swift new file mode 100644 index 0000000..85cb368 --- /dev/null +++ b/CovidSafe/Herald/Sensor/Data/DetectionLog.swift @@ -0,0 +1,88 @@ +// +// DetectionLog.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import UIKit + +/// CSV contact log for post event analysis and visualisation +class DetectionLog: NSObject, SensorDelegate { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "Data.DetectionLog") + private let textFile: TextFile + private let payloadData: PayloadData + private let deviceName = UIDevice.current.name + private let deviceOS = UIDevice.current.systemVersion + private var payloads: Set = [] + private let queue = DispatchQueue(label: "Sensor.Data.DetectionLog.Queue") + + init(filename: String, payloadData: PayloadData) { + textFile = TextFile(filename: filename) + self.payloadData = payloadData + super.init() + write() + } + + private func csv(_ value: String) -> String { + return TextFile.csv(value) + } + + private func write() { + var content = "\(csv(deviceName)),iOS,\(csv(deviceOS)),\(csv(payloadData.shortName))" + var payloadList: [String] = [] + payloads.forEach() { payload in + guard payload != payloadData.shortName else { + return + } + payloadList.append(payload) + } + payloadList.sort() + payloadList.forEach() { payload in + content.append(",") + content.append(csv(payload)) + } + logger.debug("write (content=\(content))") + content.append("\n") + textFile.overwrite(content) + } + + // MARK:- SensorDelegate + + func sensor(_ sensor: SensorType, didDetect: TargetIdentifier) { + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier) { + queue.async { + if self.payloads.insert(didRead.shortName).inserted { + self.logger.debug("didRead (payload=\(didRead.shortName))") + self.write() + } + } + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier, atProximity: Proximity, withTxPower: Int?) { + queue.async { + if self.payloads.insert(didRead.shortName).inserted { + self.logger.debug("didRead (payload=\(didRead.shortName))") + self.write() + } + } + } + + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier) { + } + + func sensor(_ sensor: SensorType, didShare: [PayloadData], fromTarget: TargetIdentifier, atProximity: Proximity) { + didShare.forEach() { payloadData in + queue.async { + if self.payloads.insert(payloadData.shortName).inserted { + self.logger.debug("didShare (payload=\(payloadData.shortName))") + self.write() + } + } + } + } + +} diff --git a/CovidSafe/Herald/Sensor/Data/SensorLogger.swift b/CovidSafe/Herald/Sensor/Data/SensorLogger.swift new file mode 100644 index 0000000..bf7708d --- /dev/null +++ b/CovidSafe/Herald/Sensor/Data/SensorLogger.swift @@ -0,0 +1,96 @@ +// +// Logger.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import UIKit +import os + +protocol SensorLogger { + init(subsystem: String, category: String) + + func log(_ level: SensorLoggerLevel, _ message: String) + + func debug(_ message: String) + + func info(_ message: String) + + func fault(_ message: String) +} + +enum SensorLoggerLevel: String { + case debug, info, fault +} + +class ConcreteSensorLogger: NSObject, SensorLogger { + private let subsystem: String + private let category: String + private let dateFormatter = DateFormatter() + private let log: OSLog? + private static let logFile = TextFile(filename: "log.txt") + + required init(subsystem: String, category: String) { + self.subsystem = subsystem + self.category = category + dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" + if #available(iOS 10.0, *) { + log = OSLog(subsystem: subsystem, category: category) + } else { + log = nil + } + } + + private func suppress(_ level: SensorLoggerLevel) -> Bool { + switch level { + case .debug: + return (BLESensorConfiguration.logLevel == .info || BLESensorConfiguration.logLevel == .fault); + case .info: + return (BLESensorConfiguration.logLevel == .fault); + default: + return false; + } + } + + func log(_ level: SensorLoggerLevel, _ message: String) { + guard !suppress(level) else { + return + } + // Write to unified os log if available, else print to console + let timestamp = dateFormatter.string(from: Date()) + let csvMessage = message.replacingOccurrences(of: "\"", with: "'") + let quotedMessage = (message.contains(",") ? "\"" + csvMessage + "\"" : csvMessage) + let entry = timestamp + "," + level.rawValue + "," + subsystem + "," + category + "," + quotedMessage + ConcreteSensorLogger.logFile.write(entry) + guard let log = log else { + print(entry) + return + } + if #available(iOS 10.0, *) { + switch (level) { + case .debug: + os_log("%s", log: log, type: .debug, message) + case .info: + os_log("%s", log: log, type: .info, message) + case .fault: + os_log("%s", log: log, type: .fault, message) + } + return + } + } + + func debug(_ message: String) { + log(.debug, message) + } + + func info(_ message: String) { + log(.debug, message) + } + + func fault(_ message: String) { + log(.debug, message) + } + +} diff --git a/CovidSafe/Herald/Sensor/Data/StatisticsLog.swift b/CovidSafe/Herald/Sensor/Data/StatisticsLog.swift new file mode 100644 index 0000000..3ab3495 --- /dev/null +++ b/CovidSafe/Herald/Sensor/Data/StatisticsLog.swift @@ -0,0 +1,95 @@ +// +// StatisticsLog.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation + +/// CSV contact log for post event analysis and visualisation +class StatisticsLog: NSObject, SensorDelegate { + private let textFile: TextFile + private let payloadData: PayloadData + private var identifierToPayload: [TargetIdentifier:String] = [:] + private var payloadToTime: [String:Date] = [:] + private var payloadToSample: [String:Sample] = [:] + + init(filename: String, payloadData: PayloadData) { + textFile = TextFile(filename: filename) + self.payloadData = payloadData + } + + private func csv(_ value: String) -> String { + return TextFile.csv(value) + } + + private func add(identifier: TargetIdentifier) { + guard let payload = identifierToPayload[identifier] else { + return + } + add(payload: payload) + } + + private func add(payload: String) { + guard let time = payloadToTime[payload], let sample = payloadToSample[payload] else { + payloadToTime[payload] = Date() + payloadToSample[payload] = Sample() + return + } + let now = Date() + payloadToTime[payload] = now + sample.add(Double(now.timeIntervalSince(time))) + write() + } + + private func write() { + var content = "payload,count,mean,sd,min,max\n" + var payloadList: [String] = [] + payloadToSample.keys.forEach() { payload in + guard payload != payloadData.shortName else { + return + } + payloadList.append(payload) + } + payloadList.sort() + payloadList.forEach() { payload in + guard let sample = payloadToSample[payload] else { + return + } + guard let mean = sample.mean, let sd = sample.standardDeviation, let min = sample.min, let max = sample.max else { + return + } + content.append("\(csv(payload)),\(sample.count),\(mean),\(sd),\(min),\(max)\n") + } + textFile.overwrite(content) + } + + + // MARK:- SensorDelegate + + func sensor(_ sensor: SensorType, didDetect: TargetIdentifier) { + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier) { + identifierToPayload[fromTarget] = didRead.shortName + add(identifier: fromTarget) + } + + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier, atProximity: Proximity, withTxPower: Int?) { + identifierToPayload[fromTarget] = didRead.shortName + add(identifier: fromTarget) + } + + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier) { + add(identifier: fromTarget) + } + + func sensor(_ sensor: SensorType, didShare: [PayloadData], fromTarget: TargetIdentifier, atProximity: Proximity) { + didShare.forEach() { payloadData in + add(payload: payloadData.shortName) + } + } + + +} diff --git a/CovidSafe/Herald/Sensor/Data/TextFile.swift b/CovidSafe/Herald/Sensor/Data/TextFile.swift new file mode 100644 index 0000000..f741c7e --- /dev/null +++ b/CovidSafe/Herald/Sensor/Data/TextFile.swift @@ -0,0 +1,71 @@ +// +// TextFile.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation + +class TextFile { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "Data.TextFile") + private var file: URL? + private let queue: DispatchQueue + + init(filename: String) { + file = try? FileManager.default + .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true) + .appendingPathComponent(filename) + queue = DispatchQueue(label: "Sensor.Data.TextFile(\(filename))") + } + + func empty() -> Bool { + guard let file = file else { + return true + } + return !FileManager.default.fileExists(atPath: file.path) + } + + /// Append line to new or existing file + func write(_ line: String) { + queue.sync { + guard let file = file else { + return + } + guard let data = (line+"\n").data(using: .utf8) else { + return + } + if FileManager.default.fileExists(atPath: file.path) { + if let fileHandle = try? FileHandle(forWritingTo: file) { + fileHandle.seekToEndOfFile() + fileHandle.write(data) + fileHandle.closeFile() + } + } else { + try? data.write(to: file, options: .atomicWrite) + } + } + } + + /// Overwrite file content + func overwrite(_ content: String) { + queue.sync { + guard let file = file else { + return + } + guard let data = content.data(using: .utf8) else { + return + } + try? data.write(to: file, options: .atomicWrite) + } + } + + /// Quote value for CSV output if required. + static func csv(_ value: String) -> String { + guard value.contains(",") || value.contains("\"") || value.contains("'") || value.contains("’") else { + return value + } + return "\"" + value + "\"" + + } +} diff --git a/CovidSafe/Herald/Sensor/Location/AwakeSensor.swift b/CovidSafe/Herald/Sensor/Location/AwakeSensor.swift new file mode 100644 index 0000000..c1ba8ff --- /dev/null +++ b/CovidSafe/Herald/Sensor/Location/AwakeSensor.swift @@ -0,0 +1,122 @@ +// +// AwakeSensor.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import CoreLocation + +protocol AwakeSensor : Sensor { +} + +/** + Screen awake sensor based on CoreLocation. Does NOT make use of the GPS position + Requires : Signing & Capabilities : BackgroundModes : LocationUpdates = YES + Requires : Info.plist : Privacy - Location When In Use Usage Description + Requires : Info.plist : Privacy - Location Always and When In Use Usage Description + */ +class ConcreteAwakeSensor : NSObject, AwakeSensor, CLLocationManagerDelegate { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "ConcreteAwakeSensor") + private var delegates: [SensorDelegate] = [] + private let locationManager = CLLocationManager() + private let rangeForBeacon: UUID? + + init(desiredAccuracy: CLLocationAccuracy = kCLLocationAccuracyThreeKilometers, distanceFilter: CLLocationDistance = CLLocationDistanceMax, rangeForBeacon: UUID? = nil) { + logger.debug("init(desiredAccuracy=\(desiredAccuracy == kCLLocationAccuracyThreeKilometers ? "3km" : desiredAccuracy.description),distanceFilter=\(distanceFilter == CLLocationDistanceMax ? "max" : distanceFilter.description),rangeForBeacon=\(rangeForBeacon == nil ? "disabled" : rangeForBeacon!.description))") + self.rangeForBeacon = rangeForBeacon + super.init() + locationManager.delegate = self + locationManager.requestAlwaysAuthorization() + locationManager.pausesLocationUpdatesAutomatically = false + locationManager.desiredAccuracy = desiredAccuracy + locationManager.distanceFilter = distanceFilter + locationManager.allowsBackgroundLocationUpdates = true + if #available(iOS 11.0, *) { + logger.debug("init(ios>=11.0)") + locationManager.showsBackgroundLocationIndicator = false + } else { + logger.debug("init(ios<11.0)") + } + } + + func add(delegate: SensorDelegate) { + delegates.append(delegate) + } + + func start() { + logger.debug("start") + locationManager.startUpdatingLocation() + logger.debug("startUpdatingLocation") + + // Start beacon ranging + guard let beaconUUID = rangeForBeacon else { + return + } + if #available(iOS 13.0, *) { + locationManager.startRangingBeacons(satisfying: CLBeaconIdentityConstraint(uuid: beaconUUID)) + logger.debug("startRangingBeacons(ios>=13.0,beaconUUID=\(beaconUUID.description))") + } else { + let beaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconUUID.uuidString) + locationManager.startRangingBeacons(in: beaconRegion) + logger.debug("startRangingBeacons(ios<13.0,beaconUUID=\(beaconUUID.uuidString)))") + } + + + } + + func stop() { + logger.debug("stop") + locationManager.stopUpdatingLocation() + logger.debug("stopUpdatingLocation") + // Start beacon ranging + guard let beaconUUID = rangeForBeacon else { + return + } + if #available(iOS 13.0, *) { + locationManager.stopRangingBeacons(satisfying: CLBeaconIdentityConstraint(uuid: beaconUUID)) + logger.debug("stopRangingBeacons(ios>=13.0,beaconUUID=\(beaconUUID.description))") + } else { + let beaconRegion = CLBeaconRegion(proximityUUID: beaconUUID, identifier: beaconUUID.uuidString) + locationManager.stopRangingBeacons(in: beaconRegion) + logger.debug("stopRangingBeacons(ios<13.0,beaconUUID=\(beaconUUID.description))") + } + } + + // MARK:- CLLocationManagerDelegate + func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { + var state = SensorState.off + + if status == CLAuthorizationStatus.authorizedWhenInUse || + status == CLAuthorizationStatus.authorizedAlways { + state = .on + } + if status == CLAuthorizationStatus.notDetermined { + locationManager.requestAlwaysAuthorization() + locationManager.stopUpdatingLocation() + locationManager.startUpdatingLocation() + } + if status != CLAuthorizationStatus.notDetermined { + delegates.forEach({ $0.sensor(.AWAKE, didUpdateState: state) }) + } + } + + @available(iOS 14.0, *) + func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { + var state = SensorState.off + if manager.authorizationStatus == CLAuthorizationStatus.authorizedWhenInUse || + manager.authorizationStatus == CLAuthorizationStatus.authorizedAlways { + state = .on + } + if manager.authorizationStatus == CLAuthorizationStatus.notDetermined { + locationManager.requestAlwaysAuthorization() + locationManager.stopUpdatingLocation() + locationManager.startUpdatingLocation() + } + if manager.authorizationStatus != CLAuthorizationStatus.notDetermined { + delegates.forEach({ $0.sensor(.AWAKE, didUpdateState: state) }) + } + } + +} diff --git a/CovidSafe/Herald/Sensor/PayloadDataSupplier.swift b/CovidSafe/Herald/Sensor/PayloadDataSupplier.swift new file mode 100644 index 0000000..9335fa9 --- /dev/null +++ b/CovidSafe/Herald/Sensor/PayloadDataSupplier.swift @@ -0,0 +1,53 @@ +// +// PayloadDataSupplier.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation + +/// Payload data supplier for generating payload data that is shared with other devices to provide device identity information while maintaining privacy and security. +/// Implement this to integration your solution with this transport. +public protocol PayloadDataSupplier { + /// Get payload for given timestamp. Use this for integration with any payload generator. + func payload(_ timestamp: PayloadTimestamp) -> PayloadData + + /// Get payload for given identifier. Use this for integration with any payload generator. + func payload(_ identifier: UUID, offset: Int, onComplete: @escaping (PayloadData?) -> Void) -> Void + + /// Parse raw data into payloads. This is used to split concatenated payloads that are transmitted via share payload. The default implementation assumes payload data is fixed length. + func payload(_ data: Data) -> [PayloadData] +} + +/// Implements payload splitting function, assuming fixed length payloads. +public extension PayloadDataSupplier { + /// Default implementation assumes fixed length payload data. + func payload(_ data: Data) -> [PayloadData] { + // Get example payload to determine length + let fixedLengthPayload = payload(PayloadTimestamp()) + let payloadLength = fixedLengthPayload.count + // Split data into payloads based on fixed length + var payloads: [PayloadData] = [] + var indexStart = 0, indexEnd = payloadLength + while indexEnd <= data.count { + let payload = PayloadData(data.subdata(in: indexStart.. Void) -> Void { + onComplete(payload(PayloadTimestamp())) + } +} + +/// Payload timestamp, should normally be Date, but it may change to UInt64 in the future to use server synchronised relative timestamp. +public typealias PayloadTimestamp = Date + +/// Encrypted payload data received from target. This is likely to be an encrypted datagram of the target's actual permanent identifier. +public typealias PayloadData = Data + diff --git a/CovidSafe/Herald/Sensor/Sensor.swift b/CovidSafe/Herald/Sensor/Sensor.swift new file mode 100644 index 0000000..1cab21e --- /dev/null +++ b/CovidSafe/Herald/Sensor/Sensor.swift @@ -0,0 +1,21 @@ +// +// Sensor.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation + +/// Sensor for detecting and tracking various kinds of disease transmission vectors, e.g. contact with people, time at location. +public protocol Sensor { + /// Add delegate for responding to sensor events. + func add(delegate: SensorDelegate) + + /// Start sensing. + func start() + + /// Stop sensing. + func stop() +} + diff --git a/CovidSafe/Herald/Sensor/SensorArray.swift b/CovidSafe/Herald/Sensor/SensorArray.swift new file mode 100644 index 0000000..028df0a --- /dev/null +++ b/CovidSafe/Herald/Sensor/SensorArray.swift @@ -0,0 +1,59 @@ +// +// SensorArray.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation +import UIKit + +/// Sensor array for combining multiple detection and tracking methods. +public class SensorArray : NSObject, Sensor { + private let logger = ConcreteSensorLogger(subsystem: "Sensor", category: "SensorArray") + private var sensorArray: [Sensor] = [] + private var sensorDelegates: [SensorDelegate] = [] + public let payloadData: PayloadData + public static let deviceDescription = "\(UIDevice.current.name) (iOS \(UIDevice.current.systemVersion))" + + public init(_ payloadDataSupplier: PayloadDataSupplier) { + logger.debug("init") + // BLE sensor for detecting and tracking proximity + sensorArray.append(ConcreteBLESensor(payloadDataSupplier)) + // Payload data at initiation time for identifying this device in the logs + payloadData = payloadDataSupplier.payload(PayloadTimestamp()) + super.init() + + // Loggers + #if DEBUG + add(delegate: ContactLog(filename: "contacts.csv")) + add(delegate: StatisticsLog(filename: "statistics.csv", payloadData: payloadData)) + add(delegate: DetectionLog(filename: "detection.csv", payloadData: payloadData)) + _ = BatteryLog(filename: "battery.csv") + #endif + logger.info("DEVICE (payloadPrefix=\(payloadData.shortName),description=\(SensorArray.deviceDescription))") + } + + public func add(delegate: SensorDelegate) { + sensorDelegates.append(delegate) + sensorArray.forEach { $0.add(delegate: delegate) } + } + + public func start() { + logger.debug("start") + sensorArray.forEach { $0.start() } + } + + public func stop() { + logger.debug("stop") + sensorArray.forEach { $0.stop() } + } + + public func startAwakeSensor() { + // Location sensor is necessary for enabling background BLE advert detection + let awakeSensor = ConcreteAwakeSensor(rangeForBeacon: UUID(uuidString: BLESensorConfiguration.serviceUUID.uuidString)) + sensorDelegates.forEach { awakeSensor.add(delegate: $0) } + sensorArray.append(awakeSensor) + awakeSensor.start() + } +} diff --git a/CovidSafe/Herald/Sensor/SensorDelegate.swift b/CovidSafe/Herald/Sensor/SensorDelegate.swift new file mode 100644 index 0000000..4dd3bfa --- /dev/null +++ b/CovidSafe/Herald/Sensor/SensorDelegate.swift @@ -0,0 +1,109 @@ +// +// SensorDelegate.swift +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +import Foundation + +/// Sensor delegate for receiving sensor events. +public protocol SensorDelegate { + /// Detection of a target with an ephemeral identifier, e.g. BLE central detecting a BLE peripheral. + func sensor(_ sensor: SensorType, didDetect: TargetIdentifier) + + /// Read payload data from target, e.g. encrypted device identifier from BLE peripheral after successful connection. + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier) + + /// Read payload data of other targets recently acquired by a target, e.g. Android peripheral sharing payload data acquired from nearby iOS peripherals. + func sensor(_ sensor: SensorType, didShare: [PayloadData], fromTarget: TargetIdentifier, atProximity: Proximity) + + /// Measure proximity to target, e.g. a sample of RSSI values from BLE peripheral. + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier) + + /// Measure proximity to target with payload data. Combines didMeasure and didRead into a single convenient delegate method + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier, withPayload: PayloadData) + + /// Measure proximity to target with payload data. Combines didMeasure and didRead into a single convenient delegate method + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier, withPayload: PayloadData, forDevice: BLEDevice) + + /// Measure proximity to target with payload data. Combines didMeasure and didRead into a single convenient delegate method + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier, atProximity: Proximity, withTxPower: Int?) + + /// Sensor state update + func sensor(_ sensor: SensorType, didUpdateState: SensorState) + + /// Check if backwards compatibility legacy payload should be written to given device + func shouldWriteToLegacyDevice(_ device: BLEDevice) -> Bool + + /// Did write backwards compatibility legacy payload to given device + func didWriteToLegacyDevice(_ device: BLEDevice) +} + +/// Sensor delegate functions are all optional. +public extension SensorDelegate { + func sensor(_ sensor: SensorType, didDetect: TargetIdentifier) {} + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier) {} + func sensor(_ sensor: SensorType, didShare: [PayloadData], fromTarget: TargetIdentifier, atProximity: Proximity) {} + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier) {} + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier, withPayload: PayloadData) {} + func sensor(_ sensor: SensorType, didMeasure: Proximity, fromTarget: TargetIdentifier, withPayload: PayloadData, forDevice: BLEDevice) {} + func sensor(_ sensor: SensorType, didUpdateState: SensorState) {} + func sensor(_ sensor: SensorType, didRead: PayloadData, fromTarget: TargetIdentifier, atProximity: Proximity, withTxPower: Int?) {} + + func shouldWriteToLegacyDevice(_ device: BLEDevice) -> Bool { return false } + func didWriteToLegacyDevice(_ device: BLEDevice) {} +} + +// MARK:- SensorDelegate data + +/// Sensor type as qualifier for target identifier. +public enum SensorType : String { + /// Bluetooth Low Energy (BLE) + case BLE + /// Awake location sensor - uses Location API to be alerted to screen on events + case AWAKE + /// GPS location sensor - not used by default in Herald + case GPS + /// Physical beacon, e.g. iBeacon + case BEACON + /// Ultrasound audio beacon. + case ULTRASOUND +} + +/// Sensor state +public enum SensorState : String { + /// Sensor is powered on, active and operational + case on + /// Sensor is powered off, inactive and not operational + case off + /// Sensor is not available + case unavailable +} + +/// Ephemeral identifier for detected target (e.g. smartphone, beacon, place). This is likely to be an UUID but using String for variable identifier length. +public typealias TargetIdentifier = String + +// MARK:- Proximity data + +/// Raw data for estimating proximity between sensor and target, e.g. RSSI for BLE. +public struct Proximity { + /// Unit of measurement, e.g. RSSI + let unit: ProximityMeasurementUnit + /// Measured value, e.g. raw RSSI value. + let value: Double + /// Get plain text description of proximity data + public var description: String { get { + unit.rawValue + ":" + value.description + }} +} + +/// Measurement unit for interpreting the proximity data values. +public enum ProximityMeasurementUnit : String { + /// Received signal strength indicator, e.g. BLE signal strength as proximity estimator. + case RSSI + /// Roundtrip time, e.g. Audio signal echo time duration as proximity estimator. + case RTT +} + + diff --git a/CovidSafe/Herald/herald.h b/CovidSafe/Herald/herald.h new file mode 100644 index 0000000..11b8a38 --- /dev/null +++ b/CovidSafe/Herald/herald.h @@ -0,0 +1,18 @@ +// +// Herald.h +// +// Copyright 2020 VMware, Inc. +// SPDX-License-Identifier: MIT +// + +#import + +//! Project version number for Herald. +FOUNDATION_EXPORT double HeraldVersionNumber; + +//! Project version string for Herald. +FOUNDATION_EXPORT const unsigned char HeraldVersionString[]; + +// In this header, you should import all the public headers of your framework using statements like #import + + diff --git a/CovidSafe/HomeView.xib b/CovidSafe/HomeView.xib index 65d7c3c..afb3745 100644 --- a/CovidSafe/HomeView.xib +++ b/CovidSafe/HomeView.xib @@ -1,9 +1,9 @@ - + - + @@ -23,6 +23,7 @@ + @@ -42,6 +43,11 @@ + + + + + @@ -165,19 +171,19 @@ - + - + - + - + - + @@ -367,7 +373,7 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -443,7 +517,7 @@ - + @@ -562,7 +636,7 @@ - + @@ -580,7 +654,7 @@ - + @@ -713,7 +787,7 @@ - + @@ -846,7 +920,7 @@ - + @@ -957,7 +1031,7 @@ - + @@ -1077,7 +1151,7 @@ - +