devicemotion.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. * Copyright 2018 Scytl Secure Electronic Voting SA
  3. *
  4. * All rights reserved
  5. *
  6. * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
  7. */
  8. /* jshint node:true */
  9. 'use strict';
  10. var math = require('./math');
  11. module.exports = DeviceMotionCollector;
  12. var motionX_, motionY_, motionZ_;
  13. var collectEntropy_ = function() {};
  14. function DeviceMotionCollector(collectEntropyCallback) {
  15. collectEntropy_ = collectEntropyCallback;
  16. }
  17. DeviceMotionCollector.prototype = {
  18. handleEvent: function(ev) {
  19. ev = ev || window.event;
  20. var acceleration = ev.accelerationIncludingGravity;
  21. var currentX = (math.entropyRound(acceleration.x) || 0);
  22. var currentY = (math.entropyRound(acceleration.y) || 0);
  23. var currentZ = (math.entropyRound(acceleration.z) || 0);
  24. var rotation = ev.rotationRate;
  25. if (rotation !== null) {
  26. currentX += math.entropyRound(rotation.alpha);
  27. currentY += math.entropyRound(rotation.beta);
  28. currentZ += math.entropyRound(rotation.gamma);
  29. }
  30. // The API detects and delivers accelerometer data 50 times per
  31. // second
  32. // even if there is any event related, so this is
  33. // a way to control if it really changed or not
  34. if ((motionX_ === null) || (motionY_ === null) || (motionZ_ === null) ||
  35. (motionX_ !== currentX) || (motionY_ !== currentY) ||
  36. (motionZ_ !== currentZ)) {
  37. motionX_ = currentX;
  38. motionY_ = currentY;
  39. motionZ_ = currentZ;
  40. collectEntropy_(currentX + currentY + currentZ + (+new Date()), 1);
  41. }
  42. }
  43. };