MotionEntropyCollector.m 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // _____ _
  2. // |_ _| |_ _ _ ___ ___ _ __ __ _
  3. // | | | ' \| '_/ -_) -_) ' \/ _` |_
  4. // |_| |_||_|_| \___\___|_|_|_\__,_(_)
  5. //
  6. // Threema iOS Client
  7. // Copyright (c) 2015-2020 Threema GmbH
  8. //
  9. // This program is free software: you can redistribute it and/or modify
  10. // it under the terms of the GNU Affero General Public License, version 3,
  11. // as published by the Free Software Foundation.
  12. //
  13. // This program is distributed in the hope that it will be useful,
  14. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. // GNU Affero General Public License for more details.
  17. //
  18. // You should have received a copy of the GNU Affero General Public License
  19. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  20. #import "MotionEntropyCollector.h"
  21. #import <CoreMotion/CoreMotion.h>
  22. #import <CommonCrypto/CommonDigest.h>
  23. #define ACCELEROMETER_UPDATE_INTERVAL 0.05
  24. @implementation MotionEntropyCollector {
  25. CMMotionManager *motionManager;
  26. NSOperationQueue *queue;
  27. BOOL running;
  28. unsigned char digest[CC_SHA256_DIGEST_LENGTH];
  29. }
  30. - (instancetype)init
  31. {
  32. self = [super init];
  33. if (self) {
  34. motionManager = [[CMMotionManager alloc] init];
  35. queue = [[NSOperationQueue alloc] init];
  36. motionManager.accelerometerUpdateInterval = ACCELEROMETER_UPDATE_INTERVAL;
  37. }
  38. return self;
  39. }
  40. - (void)start {
  41. if (running)
  42. return;
  43. running = YES;
  44. [motionManager startAccelerometerUpdatesToQueue:queue withHandler:^(CMAccelerometerData *accelerometerData, NSError *error) {
  45. CC_SHA256_CTX ctx;
  46. CC_SHA256_Init(&ctx);
  47. /* add last digest */
  48. CC_SHA256_Update(&ctx, digest, sizeof(digest));
  49. /* add content of this update */
  50. double x = accelerometerData.acceleration.x;
  51. double y = accelerometerData.acceleration.y;
  52. double z = accelerometerData.acceleration.z;
  53. NSTimeInterval timestamp = accelerometerData.timestamp;
  54. CC_SHA256_Update(&ctx, &x, sizeof(double));
  55. CC_SHA256_Update(&ctx, &y, sizeof(double));
  56. CC_SHA256_Update(&ctx, &z, sizeof(double));
  57. CC_SHA256_Update(&ctx, &timestamp, sizeof(timestamp));
  58. CC_SHA256_Final(digest, &ctx);
  59. }];
  60. }
  61. - (NSData*)stop {
  62. if (running) {
  63. [motionManager stopAccelerometerUpdates];
  64. running = NO;
  65. }
  66. return [NSData dataWithBytes:digest length:sizeof(digest)];
  67. }
  68. - (void)dealloc {
  69. [self stop];
  70. }
  71. @end