[
  {
    "path": ".gitignore",
    "content": "*.pyc\n*.log\nheartrate_*.*\n.env\nenv\n"
  },
  {
    "path": "LICENSE",
    "content": "Creative Commons Legal Code\n\nCC0 1.0 Universal\n\n    CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE\n    LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN\n    ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS\n    INFORMATION ON AN \"AS-IS\" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES\n    REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS\n    PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM\n    THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED\n    HEREUNDER.\n\nStatement of Purpose\n\nThe laws of most jurisdictions throughout the world automatically confer\nexclusive Copyright and Related Rights (defined below) upon the creator\nand subsequent owner(s) (each and all, an \"owner\") of an original work of\nauthorship and/or a database (each, a \"Work\").\n\nCertain owners wish to permanently relinquish those rights to a Work for\nthe purpose of contributing to a commons of creative, cultural and\nscientific works (\"Commons\") that the public can reliably and without fear\nof later claims of infringement build upon, modify, incorporate in other\nworks, reuse and redistribute as freely as possible in any form whatsoever\nand for any purposes, including without limitation commercial purposes.\nThese owners may contribute to the Commons to promote the ideal of a free\nculture and the further production of creative, cultural and scientific\nworks, or to gain reputation or greater distribution for their Work in\npart through the use and efforts of others.\n\nFor these and/or other purposes and motivations, and without any\nexpectation of additional consideration or compensation, the person\nassociating CC0 with a Work (the \"Affirmer\"), to the extent that he or she\nis an owner of Copyright and Related Rights in the Work, voluntarily\nelects to apply CC0 to the Work and publicly distribute the Work under its\nterms, with knowledge of his or her Copyright and Related Rights in the\nWork and the meaning and intended legal effect of CC0 on those rights.\n\n1. Copyright and Related Rights. A Work made available under CC0 may be\nprotected by copyright and related or neighboring rights (\"Copyright and\nRelated Rights\"). Copyright and Related Rights include, but are not\nlimited to, the following:\n\n  i. the right to reproduce, adapt, distribute, perform, display,\n     communicate, and translate a Work;\n ii. moral rights retained by the original author(s) and/or performer(s);\niii. publicity and privacy rights pertaining to a person's image or\n     likeness depicted in a Work;\n iv. rights protecting against unfair competition in regards to a Work,\n     subject to the limitations in paragraph 4(a), below;\n  v. rights protecting the extraction, dissemination, use and reuse of data\n     in a Work;\n vi. database rights (such as those arising under Directive 96/9/EC of the\n     European Parliament and of the Council of 11 March 1996 on the legal\n     protection of databases, and under any national implementation\n     thereof, including any amended or successor version of such\n     directive); and\nvii. other similar, equivalent or corresponding rights throughout the\n     world based on applicable law or treaty, and any national\n     implementations thereof.\n\n2. Waiver. To the greatest extent permitted by, but not in contravention\nof, applicable law, Affirmer hereby overtly, fully, permanently,\nirrevocably and unconditionally waives, abandons, and surrenders all of\nAffirmer's Copyright and Related Rights and associated claims and causes\nof action, whether now known or unknown (including existing as well as\nfuture claims and causes of action), in the Work (i) in all territories\nworldwide, (ii) for the maximum duration provided by applicable law or\ntreaty (including future time extensions), (iii) in any current or future\nmedium and for any number of copies, and (iv) for any purpose whatsoever,\nincluding without limitation commercial, advertising or promotional\npurposes (the \"Waiver\"). Affirmer makes the Waiver for the benefit of each\nmember of the public at large and to the detriment of Affirmer's heirs and\nsuccessors, fully intending that such Waiver shall not be subject to\nrevocation, rescission, cancellation, termination, or any other legal or\nequitable action to disrupt the quiet enjoyment of the Work by the public\nas contemplated by Affirmer's express Statement of Purpose.\n\n3. Public License Fallback. Should any part of the Waiver for any reason\nbe judged legally invalid or ineffective under applicable law, then the\nWaiver shall be preserved to the maximum extent permitted taking into\naccount Affirmer's express Statement of Purpose. In addition, to the\nextent the Waiver is so judged Affirmer hereby grants to each affected\nperson a royalty-free, non transferable, non sublicensable, non exclusive,\nirrevocable and unconditional license to exercise Affirmer's Copyright and\nRelated Rights in the Work (i) in all territories worldwide, (ii) for the\nmaximum duration provided by applicable law or treaty (including future\ntime extensions), (iii) in any current or future medium and for any number\nof copies, and (iv) for any purpose whatsoever, including without\nlimitation commercial, advertising or promotional purposes (the\n\"License\"). The License shall be deemed effective as of the date CC0 was\napplied by Affirmer to the Work. Should any part of the License for any\nreason be judged legally invalid or ineffective under applicable law, such\npartial invalidity or ineffectiveness shall not invalidate the remainder\nof the License, and in such case Affirmer hereby affirms that he or she\nwill not (i) exercise any of his or her remaining Copyright and Related\nRights in the Work or (ii) assert any associated claims and causes of\naction with respect to the Work, in either case contrary to Affirmer's\nexpress Statement of Purpose.\n\n4. Limitations and Disclaimers.\n\n a. No trademark or patent rights held by Affirmer are waived, abandoned,\n    surrendered, licensed or otherwise affected by this document.\n b. Affirmer offers the Work as-is and makes no representations or\n    warranties of any kind concerning the Work, express, implied,\n    statutory or otherwise, including without limitation warranties of\n    title, merchantability, fitness for a particular purpose, non\n    infringement, or the absence of latent or other defects, accuracy, or\n    the present or absence of errors, whether or not discoverable, all to\n    the greatest extent permissible under applicable law.\n c. Affirmer disclaims responsibility for clearing rights of other persons\n    that may apply to the Work or any use thereof, including without\n    limitation any person's Copyright and Related Rights in the Work.\n    Further, Affirmer disclaims responsibility for obtaining any necessary\n    consents, permissions or other rights required for any use of the\n    Work.\n d. Affirmer understands and acknowledges that Creative Commons is not a\n    party to this document and has no duty or obligation with respect to\n    this CC0 or use of the Work.\n"
  },
  {
    "path": "README.md",
    "content": "# MiBand2\nLibrary to work with Xiaomi MiBand 2 (Support python2/python3)\n[Read the Article here](https://medium.com/@a.nikishaev/how-i-hacked-xiaomi-miband-2-to-control-it-from-linux-a5bd2f36d3ad)\n\n# Contributors & Info Sources\n1) Base lib provided by [Leo Soares](https://github.com/leojrfs/miband2)\n2) Additional debug & fixes was made by my friend [Volodymyr Shymanskyy](https://github.com/vshymanskyy/miband2-python-test)\n3) Some info that really helped i got from [Freeyourgadget team](https://github.com/Freeyourgadget/Gadgetbridge/tree/master/app/src/main/java/nodomain/freeyourgadget/gadgetbridge/service/devices/huami/miband2)\n\n## Interesting stuff\n[More interesing stuff about Software Developing](http://t.me/devs_world)\n\n# Run \n\n1) Install dependencies\n```sh\npip install -r requirements.txt\n```\n2) Turn on your Bluetooth\n3) Unpair you MiBand2 from current mobile apps\n4) Find out you MiBand2 MAC address\n```sh\nsudo hcitool lescan\n```\n5) Run this to auth device\n```sh\npython example.py --mac MAC_ADDRESS --init\n```\n6) Run this to call demo functions\n```sh\npython example.py --standard --mac MAC_ADDRESS\npython example.py --help\n```\n7) If you having problems(BLE can glitch sometimes) try this and repeat from 4)\n```sh\nsudo hciconfig hci0 reset\n```\nAlso there is cool JS library that made Volodymyr Shymansky https://github.com/vshymanskyy/miband-js\n\n# Donate\nIf you like what im doing, you can send me some money for pepsi(i dont drink alcohol). https://patreon.com/mlworld\n\n<p xmlns:dct=\"http://purl.org/dc/terms/\">\n  <a rel=\"license\"\n     href=\"http://creativecommons.org/publicdomain/zero/1.0/\">\n    <img src=\"http://i.creativecommons.org/p/zero/1.0/88x31.png\" style=\"border-style: none;\" alt=\"CC0\" />\n  </a>\n  <br />\n  To the extent possible under law,\n  <a rel=\"dct:publisher\"\n     href=\"http://medium.com/@a.nikishaev\">\n    <span property=\"dct:title\">Andrey Nikishaev</span></a>\n  has waived all copyright and related or neighboring rights to\n  <span property=\"dct:title\">Library to work with Xiaomi MiBand 2 </span>.\n</p>\n"
  },
  {
    "path": "base.py",
    "content": "import struct\nimport time\nimport logging\nfrom datetime import datetime, timedelta\nfrom Crypto.Cipher import AES\ntry:\n    from Queue import Queue, Empty\nexcept ImportError:\n    from queue import Queue, Empty\nfrom bluepy.btle import Peripheral, DefaultDelegate, ADDR_TYPE_RANDOM, BTLEException\n\n\nfrom constants import UUIDS, AUTH_STATES, ALERT_TYPES, QUEUE_TYPES\n\n\nclass AuthenticationDelegate(DefaultDelegate):\n\n    \"\"\"This Class inherits DefaultDelegate to handle the authentication process.\"\"\"\n\n    def __init__(self, device):\n        DefaultDelegate.__init__(self)\n        self.device = device\n\n    def handleNotification(self, hnd, data):\n        # Debug purposes\n        if hnd == self.device._char_auth.getHandle():\n            if data[:3] == b'\\x10\\x01\\x01':\n                self.device._req_rdn()\n            elif data[:3] == b'\\x10\\x01\\x04':\n                self.device.state = AUTH_STATES.KEY_SENDING_FAILED\n            elif data[:3] == b'\\x10\\x02\\x01':\n                # 16 bytes\n                random_nr = data[3:]\n                self.device._send_enc_rdn(random_nr)\n            elif data[:3] == b'\\x10\\x02\\x04':\n                self.device.state = AUTH_STATES.REQUEST_RN_ERROR\n            elif data[:3] == b'\\x10\\x03\\x01':\n                self.device.state = AUTH_STATES.AUTH_OK\n            elif data[:3] == b'\\x10\\x03\\x04':\n                self.device.status = AUTH_STATES.ENCRIPTION_KEY_FAILED\n                self.device._send_key()\n            else:\n                self.device.state = AUTH_STATES.AUTH_FAILED\n        elif hnd == self.device._char_heart_measure.getHandle():\n            self.device.queue.put((QUEUE_TYPES.HEART, data))\n        elif hnd == 0x38:\n            # Not sure about this, need test\n            if len(data) == 20 and struct.unpack('b', data[0:1])[0] == 1:\n                self.device.queue.put((QUEUE_TYPES.RAW_ACCEL, data))\n            elif len(data) == 16:\n                self.device.queue.put((QUEUE_TYPES.RAW_HEART, data))\n        # The fetch characteristic controls the communication with the activity characteristic.\n        # It can trigger the communication.\n        elif hnd == self.device._char_fetch.getHandle():\n            if data[:3] == b'\\x10\\x01\\x01':\n                # get timestamp from what date the data actually is received\n                year = struct.unpack(\"<H\", data[7:9])[0]\n                month = struct.unpack(\"b\", data[9:10])[0]\n                day = struct.unpack(\"b\", data[10:11])[0]\n                hour = struct.unpack(\"b\", data[11:12])[0]\n                minute = struct.unpack(\"b\", data[12:13])[0]\n                self.device.first_timestamp = datetime(year, month, day, hour, minute)\n                print(\"Fetch data from {}-{}-{} {}:{}\".format(year, month, day, hour, minute))\n                self.device._char_fetch.write(b'\\x02', False)\n            elif data[:3] == b'\\x10\\x02\\x01':\n                self.device.active = False\n                return\n            else:\n                print(\"Unexpected data on handle \" + str(hnd) + \": \" + data.hex())\n                return\n         # The activity characteristic sends the previews recorded information\n         # from one given timestamp until now.\n        elif hnd == self.device._char_activity.getHandle():\n            if len(data) % 4 is not 1:\n                if self.device.last_timestamp > datetime.now() - timedelta(minutes=1):\n                    self.device.active = False\n                    return\n                print(\"Trigger more communication\")\n                time.sleep(1)\n                t = self.device.last_timestamp + timedelta(minutes=1)\n                self.device.start_get_previews_data(t)\n            else:\n                pkg = self.device.pkg\n                self.device.pkg += 1\n                i = 1\n                while i < len(data):\n                    index = int(pkg) * 4 + (i - 1) / 4\n                    timestamp = self.device.first_timestamp + timedelta(minutes=index)\n                    self.device.last_timestamp = timestamp\n                    # category = int.from_bytes(data[i:i + 1], byteorder='little')\n                    category = struct.unpack(\"<B\", data[i:i + 1])\n                    intensity = struct.unpack(\"B\", data[i + 1:i + 2])[0]\n                    steps = struct.unpack(\"B\", data[i + 2:i + 3])[0]\n                    heart_rate = struct.unpack(\"B\", data[i + 3:i + 4])[0]\n\n                    print(\"{}: category: {}; acceleration {}; steps {}; heart rate {};\".format(\n                        timestamp.strftime('%d.%m - %H:%M'),\n                        category,\n                        intensity,\n                        steps,\n                        heart_rate)\n                    )\n                    if self.device.outfile:\n                        self.device.outfile.write(f\"{timestamp.strftime('%d.%m.%Y - %H:%M')},{category},{intensity},{steps},{heart_rate}\\n\")\n\n                    i += 4\n\n                    d = datetime.now().replace(second=0, microsecond=0) - timedelta(minutes=1)\n                    if timestamp == d:\n                        self.device.active = False\n                        return\n        else:\n            self.device._log.error(\"Unhandled Response \" + hex(hnd) + \": \" +\n                                   str(data.encode(\"hex\")) + \" len:\" + str(len(data)))\n\n\nclass MiBand2(Peripheral):\n    # _KEY = b'\\x30\\x31\\x32\\x33\\x34\\x35\\x36\\x37\\x38\\x39\\x40\\x41\\x42\\x43\\x44\\x45'\n    # _send_key_cmd = struct.pack('<18s', b'\\x01\\x08' + _KEY)\n    # _send_rnd_cmd = struct.pack('<2s', b'\\x02\\x08')\n    # _send_enc_key = struct.pack('<2s', b'\\x03\\x08')\n    _KEY = b'\\xf5\\xd2\\x29\\x87\\x65\\x0a\\x1d\\x82\\x05\\xab\\x82\\xbe\\xb9\\x38\\x59\\xcf'\n    _send_key_cmd = struct.pack('<18s', b'\\x01\\x00' + _KEY)\n    _send_rnd_cmd = struct.pack('<2s', b'\\x02\\x00')\n    _send_enc_key = struct.pack('<2s', b'\\x03\\x00')\n    pkg = 0\n\n    def __init__(self, mac_address, timeout=0.5, debug=False):\n        FORMAT = '%(asctime)-15s %(name)s (%(levelname)s) > %(message)s'\n        logging.basicConfig(format=FORMAT)\n        log_level = logging.WARNING if not debug else logging.DEBUG\n        self._log = logging.getLogger(self.__class__.__name__)\n        self._log.setLevel(log_level)\n\n        self._log.info('Connecting to ' + mac_address)\n        Peripheral.__init__(self, mac_address, addrType=ADDR_TYPE_RANDOM)\n        self._log.info('Connected')\n\n        self.outfile = None\n\n        self.timeout = timeout\n        self.mac_address = mac_address\n        self.state = None\n        self.queue = Queue()\n        self.heart_measure_callback = None\n        self.heart_raw_callback = None\n        self.accel_raw_callback = None\n\n        self.svc_1 = self.getServiceByUUID(UUIDS.SERVICE_MIBAND1)\n        self.svc_2 = self.getServiceByUUID(UUIDS.SERVICE_MIBAND2)\n        self.svc_heart = self.getServiceByUUID(UUIDS.SERVICE_HEART_RATE)\n\n        self._char_auth = self.svc_2.getCharacteristics(UUIDS.CHARACTERISTIC_AUTH)[0]\n        self._desc_auth = self._char_auth.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n\n        self._char_heart_ctrl = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_CONTROL)[0]\n        self._char_heart_measure = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_MEASURE)[0]\n\n        # Recorded information\n        self._char_fetch = self.getCharacteristics(uuid=UUIDS.CHARACTERISTIC_FETCH)[0]\n        self._desc_fetch = self._char_fetch.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n        self._char_activity = self.getCharacteristics(uuid=UUIDS.CHARACTERISTIC_ACTIVITY_DATA)[0]\n        self._desc_activity = self._char_activity.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n\n        # Enable auth service notifications on startup\n        self._auth_notif(True)\n        # Let MiBand2 to settle\n        self.waitForNotifications(0.1)\n\n    # Auth helpers ######################################################################\n\n    def _auth_notif(self, enabled):\n        if enabled:\n            self._log.info(\"Enabling Auth Service notifications status...\")\n            self._desc_auth.write(b\"\\x01\\x00\", True)\n        elif not enabled:\n            self._log.info(\"Disabling Auth Service notifications status...\")\n            self._desc_auth.write(b\"\\x00\\x00\", True)\n        else:\n            self._log.error(\"Something went wrong while changing the Auth Service notifications status...\")\n\n    def _auth_previews_data_notif(self, enabled):\n        if enabled:\n            self._log.info(\"Enabling Fetch Char notifications status...\")\n            self._desc_fetch.write(b\"\\x01\\x00\", True)\n            self._log.info(\"Enabling Activity Char notifications status...\")\n            self._desc_activity.write(b\"\\x01\\x00\", True)\n        elif not enabled:\n            self._log.info(\"Disabling Fetch Char notifications status...\")\n            self._desc_fetch.write(b\"\\x00\\x00\", True)\n            self._log.info(\"Disabling Activity Char notifications status...\")\n            self._desc_activity.write(b\"\\x00\\x00\", True)\n        else:\n            self._log.error(\"Something went wrong while changing the Fetch and Activity notifications status...\")\n\n    def _encrypt(self, message):\n        aes = AES.new(self._KEY, AES.MODE_ECB)\n        return aes.encrypt(message)\n\n    def _send_key(self):\n        self._log.info(\"Sending Key...\")\n        self._char_auth.write(self._send_key_cmd)\n        self.waitForNotifications(self.timeout)\n\n    def _req_rdn(self):\n        self._log.info(\"Requesting random number...\")\n        self._char_auth.write(self._send_rnd_cmd)\n        self.waitForNotifications(self.timeout)\n\n    def _send_enc_rdn(self, data):\n        self._log.info(\"Sending encrypted random number\")\n        cmd = self._send_enc_key + self._encrypt(data)\n        send_cmd = struct.pack('<18s', cmd)\n        self._char_auth.write(send_cmd)\n        self.waitForNotifications(self.timeout)\n\n    # Parse helpers ###################################################################\n\n    def _parse_raw_accel(self, bytes):\n        res = []\n        for i in range(3):\n            g = struct.unpack('hhh', bytes[2 + i * 6:8 + i * 6])\n            res.append({'x': g[0], 'y': g[1], 'wtf': g[2]})\n        # WTF\n        # if len(bytes) == 20 and struct.unpack('b', bytes[0])[0] == 2:\n        #     print struct.unpack('B', bytes[1])\n        #     print \"Accel x: %s y: %s z: %s\" % struct.unpack('hhh', bytes[2:8])\n        #     print \"Accel x: %s y: %s z: %s\" % struct.unpack('hhh', bytes[8:14])\n        #     print \"Accel x: %s y: %s z: %s\" % struct.unpack('hhh', bytes[14:])\n        return res\n\n    def _parse_raw_heart(self, bytes):\n        res = struct.unpack('HHHHHHH', bytes[2:])\n        return res\n\n    @staticmethod\n    def _parse_date(bytes):\n        year = struct.unpack('h', bytes[0:2])[0] if len(bytes) >= 2 else None\n        month = struct.unpack('b', bytes[2:3])[0] if len(bytes) >= 3 else None\n        day = struct.unpack('b', bytes[3:4])[0] if len(bytes) >= 4 else None\n        hours = struct.unpack('b', bytes[4:5])[0] if len(bytes) >= 5 else None\n        minutes = struct.unpack('b', bytes[5:6])[0] if len(bytes) >= 6 else None\n        seconds = struct.unpack('b', bytes[6:7])[0] if len(bytes) >= 7 else None\n        day_of_week = struct.unpack('b', bytes[7:8])[0] if len(bytes) >= 8 else None\n        fractions256 = struct.unpack('b', bytes[8:9])[0] if len(bytes) >= 9 else None\n\n        return {\"date\": datetime(*(year, month, day, hours, minutes, seconds)), \"day_of_week\": day_of_week, \"fractions256\": fractions256}\n\n    @staticmethod\n    def create_date_data(date):\n        data = struct.pack( 'hbbbbbbbxx', date.year, date.month, date.day, date.hour, date.minute, date.second, date.weekday(), 0 )\n        return data\n\n    def _parse_battery_response(self, bytes):\n        level = struct.unpack('b', bytes[1:2])[0] if len(bytes) >= 2 else None\n        last_level = struct.unpack('b', bytes[19:20])[0] if len(bytes) >= 20 else None\n        status = 'normal' if struct.unpack('b', bytes[2:3])[0] == 0 else \"charging\"\n        datetime_last_charge = self._parse_date(bytes[11:18])\n        datetime_last_off = self._parse_date(bytes[3:10])\n\n        # WTF?\n        # struct.unpack('b', bytes[10])\n        # struct.unpack('b', bytes[18])\n        # print struct.unpack('b', bytes[10]), struct.unpack('b', bytes[18])\n\n        res = {\n            \"status\": status,\n            \"level\": level,\n            \"last_level\": last_level,\n            \"last_charge\": datetime_last_charge,\n            \"last_off\": datetime_last_off\n        }\n        return res\n\n    # Queue ###################################################################\n\n    def _get_from_queue(self, _type):\n        try:\n            res = self.queue.get(False)\n        except Empty:\n            return None\n        if res[0] != _type:\n            self.queue.put(res)\n            return None\n        return res[1]\n\n    def _parse_queue(self):\n        while True:\n            try:\n                res = self.queue.get(False)\n                _type = res[0]\n                if self.heart_measure_callback and _type == QUEUE_TYPES.HEART:\n                    self.heart_measure_callback(struct.unpack('bb', res[1])[1])\n                elif self.heart_raw_callback and _type == QUEUE_TYPES.RAW_HEART:\n                    self.heart_raw_callback(self._parse_raw_heart(res[1]))\n                elif self.accel_raw_callback and _type == QUEUE_TYPES.RAW_ACCEL:\n                    self.accel_raw_callback(self._parse_raw_accel(res[1]))\n            except Empty:\n                break\n\n    # API ####################################################################\n\n    def initialize(self):\n        self.setDelegate(AuthenticationDelegate(self))\n        self._send_key()\n\n        while True:\n            self.waitForNotifications(0.1)\n            if self.state == AUTH_STATES.AUTH_OK:\n                self._log.info('Initialized')\n                self._auth_notif(False)\n                return True\n            elif self.state is None:\n                continue\n\n            self._log.error(self.state)\n            return False\n\n    def authenticate(self):\n        self.setDelegate(AuthenticationDelegate(self))\n        self._req_rdn()\n\n        while True:\n            self.waitForNotifications(0.1)\n            if self.state == AUTH_STATES.AUTH_OK:\n                self._log.info('Authenticated')\n                return True\n            elif self.state is None:\n                continue\n\n            self._log.error(self.state)\n            return False\n\n    def get_battery_info(self):\n        char = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_BATTERY)[0]\n        return self._parse_battery_response(char.read())\n\n    def get_current_time(self):\n        char = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_CURRENT_TIME)[0]\n        return self._parse_date(char.read()[0:9])\n\n    def set_current_time(self, date):\n        char = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_CURRENT_TIME)[0]\n        return char.write(self.create_date_data(date), True)\n\n    def get_revision(self):\n        svc = self.getServiceByUUID(UUIDS.SERVICE_DEVICE_INFO)\n        char = svc.getCharacteristics(UUIDS.CHARACTERISTIC_REVISION)[0]\n        data = char.read()\n        revision = struct.unpack('9s', data[-9:])[0] if len(data) == 9 else None\n        return revision\n\n    def get_hrdw_revision(self):\n        svc = self.getServiceByUUID(UUIDS.SERVICE_DEVICE_INFO)\n        char = svc.getCharacteristics(UUIDS.CHARACTERISTIC_HRDW_REVISION)[0]\n        data = char.read()\n        revision = struct.unpack('8s', data[-8:])[0] if len(data) == 8 else None\n        return revision\n\n    def set_encoding(self, encoding=\"en_US\"):\n        char = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_CONFIGURATION)[0]\n        packet = struct.pack('5s', encoding)\n        packet = b'\\x06\\x17\\x00' + packet\n        return char.write(packet)\n\n    def set_heart_monitor_sleep_support(self, enabled=True, measure_minute_interval=1):\n        char_m = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_MEASURE)[0]\n        char_d = char_m.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n        char_d.write(b'\\x01\\x00', True)\n        self._char_heart_ctrl.write(b'\\x15\\x00\\x00', True)\n        # measure interval set to off\n        self._char_heart_ctrl.write(b'\\x14\\x00', True)\n        if enabled:\n            if measure_minute_interval > 120:\n                measure_minute_interval = 120\n            self._char_heart_ctrl.write(b'\\x15\\x00\\x01', True)\n            # measure interval set\n            self._char_heart_ctrl.write(b'\\x14' + bytes([measure_minute_interval]), True)\n        char_d.write(b'\\x00\\x00', True)\n\n    def set_heart_monitor_measurement_interval(self, enabled=True, measure_minute_interval=1):\n        if enabled:\n            if measure_minute_interval > 120:\n                measure_minute_interval = 120\n            self._char_heart_ctrl.write(b'\\x14' + bytes([measure_minute_interval]), True)\n        else:\n            self._char_heart_ctrl.write(b'\\x14\\x00', True)\n\n    def get_serial(self):\n        svc = self.getServiceByUUID(UUIDS.SERVICE_DEVICE_INFO)\n        char = svc.getCharacteristics(UUIDS.CHARACTERISTIC_SERIAL)[0]\n        data = char.read()\n        serial = struct.unpack('12s', data[-12:])[0] if len(data) == 12 else None\n        return serial\n\n    def get_steps(self):\n        char = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_STEPS)[0]\n        a = char.read()\n        steps = struct.unpack('h', a[1:3])[0] if len(a) >= 3 else None\n        meters = struct.unpack('h', a[5:7])[0] if len(a) >= 7 else None\n        fat_grams = struct.unpack('h', a[2:4])[0] if len(a) >= 4 else None\n        # why only 1 byte??\n        calories = struct.unpack('b', a[9:10])[0] if len(a) >= 10 else None\n        return {\n            \"steps\": steps,\n            \"meters\": meters,\n            \"fat_grams\": fat_grams,\n            \"calories\": calories\n\n        }\n\n    def send_alert(self, _type):\n        svc = self.getServiceByUUID(UUIDS.SERVICE_ALERT)\n        char = svc.getCharacteristics(UUIDS.CHARACTERISTIC_ALERT)[0]\n        char.write(_type)\n\n    def get_heart_rate_one_time(self):\n        # stop continous\n        self._char_heart_ctrl.write(b'\\x15\\x01\\x00', True)\n        # stop manual\n        self._char_heart_ctrl.write(b'\\x15\\x02\\x00', True)\n        # start manual\n        self._char_heart_ctrl.write(b'\\x15\\x02\\x01', True)\n        res = None\n        while not res:\n            self.waitForNotifications(self.timeout)\n            res = self._get_from_queue(QUEUE_TYPES.HEART)\n\n        rate = struct.unpack('bb', res)[1]\n        return rate\n\n    def start_heart_rate_realtime(self, heart_measure_callback):\n        char_m = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_MEASURE)[0]\n        char_d = char_m.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n        char_ctrl = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_CONTROL)[0]\n\n        self.heart_measure_callback = heart_measure_callback\n\n        # stop heart monitor continues & manual\n        char_ctrl.write(b'\\x15\\x02\\x00', True)\n        char_ctrl.write(b'\\x15\\x01\\x00', True)\n        # enable heart monitor notifications\n        char_d.write(b'\\x01\\x00', True)\n        # start hear monitor continues\n        char_ctrl.write(b'\\x15\\x01\\x01', True)\n        t = time.time()\n        while True:\n            self.waitForNotifications(0.5)\n            self._parse_queue()\n            # send ping request every 12 sec\n            if (time.time() - t) >= 12:\n                char_ctrl.write(b'\\x16', True)\n                t = time.time()\n\n    def start_raw_data_realtime(self, heart_measure_callback=None, heart_raw_callback=None, accel_raw_callback=None):\n        char_m = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_MEASURE)[0]\n        char_d = char_m.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n        char_ctrl = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_CONTROL)[0]\n\n        if heart_measure_callback:\n            self.heart_measure_callback = heart_measure_callback\n        if heart_raw_callback:\n            self.heart_raw_callback = heart_raw_callback\n        if accel_raw_callback:\n            self.accel_raw_callback = accel_raw_callback\n\n        char_sensor = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_SENSOR)[0]\n        # char_sens_d = char_sensor1.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n\n        # char_sensor2 = self.svc_1.getCharacteristics('000000010000351221180009af100700')[0]\n        # char_sens_d2 = char_sensor2.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n\n        # char_sensor3 = self.svc_1.getCharacteristics('000000070000351221180009af100700')[0]\n        # char_sens_d3 = char_sensor3.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n\n        # char_sens_d1.write(b'\\x01\\x00', True)\n        # char_sens_d2.write(b'\\x01\\x00', True)\n        # char_sensor2.write(b'\\x01\\x03\\x19')\n        # char_sens_d2.write(b'\\x00\\x00', True)\n        # char_d.write(b'\\x01\\x00', True)\n        # char_ctrl.write(b'\\x15\\x01\\x01', True)\n        # char_sensor2.write(b'\\x02')\n\n        # stop heart monitor continues & manual\n        char_ctrl.write(b'\\x15\\x02\\x00', True)\n        char_ctrl.write(b'\\x15\\x01\\x00', True)\n        # WTF\n        # char_sens_d1.write(b'\\x01\\x00', True)\n        # enabling accelerometer & heart monitor raw data notifications\n        char_sensor.write(b'\\x01\\x03\\x19')\n        # IMO: enablee heart monitor notifications\n        char_d.write(b'\\x01\\x00', True)\n        # start hear monitor continues\n        char_ctrl.write(b'\\x15\\x01\\x01', True)\n        # WTF\n        char_sensor.write(b'\\x02')\n        t = time.time()\n        while True:\n            self.waitForNotifications(0.5)\n            self._parse_queue()\n            # send ping request every 12 sec\n            if (time.time() - t) >= 12:\n                char_ctrl.write(b'\\x16', True)\n                t = time.time()\n\n    def stop_realtime(self):\n        char_m = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_MEASURE)[0]\n        char_d = char_m.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n        char_ctrl = self.svc_heart.getCharacteristics(UUIDS.CHARACTERISTIC_HEART_RATE_CONTROL)[0]\n\n        char_sensor1 = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_HZ)[0]\n        char_sens_d1 = char_sensor1.getDescriptors(forUUID=UUIDS.NOTIFICATION_DESCRIPTOR)[0]\n\n        char_sensor2 = self.svc_1.getCharacteristics(UUIDS.CHARACTERISTIC_SENSOR)[0]\n\n        # stop heart monitor continues\n        char_ctrl.write(b'\\x15\\x01\\x00', True)\n        char_ctrl.write(b'\\x15\\x01\\x00', True)\n        # IMO: stop heart monitor notifications\n        char_d.write(b'\\x00\\x00', True)\n        # WTF\n        char_sensor2.write(b'\\x03')\n        # IMO: stop notifications from sensors\n        char_sens_d1.write(b'\\x00\\x00', True)\n\n        self.heart_measure_callback = None\n        self.heart_raw_callback = None\n        self.accel_raw_callback = None\n\n    def start_get_previews_data(self, start_timestamp):\n        self._auth_previews_data_notif(True)\n        self.waitForNotifications(0.1)\n        print(\"Trigger activity communication\")\n        year = struct.pack(\"<H\", start_timestamp.year)\n        month = bytes([struct.pack(\"<H\", start_timestamp.month)[0]])\n        day = bytes([struct.pack(\"<H\", start_timestamp.day)[0]])\n        hour = bytes([struct.pack(\"<H\", start_timestamp.hour)[0]])\n        minute = bytes([struct.pack(\"<H\", start_timestamp.minute)[0]])\n        ts = year + month + day + hour + minute\n        trigger = b'\\x01\\x01' + ts + b'\\x00\\x08'\n        self._char_fetch.write(trigger, False)\n        self.active = True\n\n"
  },
  {
    "path": "constants.py",
    "content": "___all__ = ['UUIDS']\n\n\nclass Immutable(type):\n\n    def __call__(*args):\n        raise Exception(\"You can't create instance of immutable object\")\n\n    def __setattr__(*args):\n        raise Exception(\"You can't modify immutable object\")\n\n\nclass UUIDS(object):\n\n    __metaclass__ = Immutable\n\n    BASE = \"0000%s-0000-1000-8000-00805f9b34fb\"\n\n    SERVICE_MIBAND1 = BASE % 'fee0'\n    SERVICE_MIBAND2 = BASE % 'fee1'\n\n    SERVICE_ALERT = BASE % '1802'\n    SERVICE_ALERT_NOTIFICATION = BASE % '1811'\n    SERVICE_HEART_RATE = BASE % '180d'\n    SERVICE_DEVICE_INFO = BASE % '180a'\n\n    CHARACTERISTIC_HZ = \"00000002-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_SENSOR = \"00000001-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_AUTH = \"00000009-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_HEART_RATE_MEASURE = \"00002a37-0000-1000-8000-00805f9b34fb\"\n    CHARACTERISTIC_HEART_RATE_CONTROL = \"00002a39-0000-1000-8000-00805f9b34fb\"\n    CHARACTERISTIC_ALERT = \"00002a06-0000-1000-8000-00805f9b34fb\"\n    CHARACTERISTIC_BATTERY = \"00000006-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_STEPS = \"00000007-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_LE_PARAMS = BASE % \"FF09\"\n    CHARACTERISTIC_REVISION = 0x2a28\n    CHARACTERISTIC_SERIAL = 0x2a25\n    CHARACTERISTIC_HRDW_REVISION = 0x2a27\n    CHARACTERISTIC_CONFIGURATION = \"00000003-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_DEVICEEVENT = \"00000010-0000-3512-2118-0009af100700\"\n\n    CHARACTERISTIC_CURRENT_TIME = BASE % '2A2B'\n    CHARACTERISTIC_AGE = BASE % '2A80'\n    CHARACTERISTIC_USER_SETTINGS = \"00000008-0000-3512-2118-0009af100700\"\n\n    CHARACTERISTIC_ACTIVITY_DATA = \"00000005-0000-3512-2118-0009af100700\"\n    CHARACTERISTIC_FETCH = \"00000004-0000-3512-2118-0009af100700\"\n\n    NOTIFICATION_DESCRIPTOR = 0x2902\n\n\nclass AUTH_STATES(object):\n\n    __metaclass__ = Immutable\n\n    AUTH_OK = \"Auth ok\"\n    AUTH_FAILED = \"Auth failed\"\n    ENCRIPTION_KEY_FAILED = \"Encryption key auth fail, sending new key\"\n    KEY_SENDING_FAILED = \"Key sending failed\"\n    REQUEST_RN_ERROR = \"Something went wrong when requesting the random number\"\n\n\nclass ALERT_TYPES(object):\n\n    __metaclass__ = Immutable\n\n    NONE = b'\\x00'\n    MESSAGE = b'\\x01'\n    PHONE = b'\\x02'\n    FIND_DEVICE = b'\\x03'\n    FOCUS_MESSAGE = b'\\xfe'\n\n\nclass QUEUE_TYPES(object):\n\n    __metaclass__ = Immutable\n\n    HEART = 'heart'\n    RAW_ACCEL = 'raw_accel'\n    RAW_HEART = 'raw_heart'\n"
  },
  {
    "path": "dump.py",
    "content": "import sys\nimport os\nimport time\nfrom base import MiBand2\nfrom bluepy.btle import BTLEException\n\nMAC = sys.argv[1]\nfilepath = sys.argv[2]\nif os.path.exists(sys.argv[2]):\n    os.remove(sys.argv[2])\nfp = open(filepath, 'a')\nfp.write('time, heartrate\\n')\n\n\ndef log(rate):\n    data = \"%s, %s\\n\" % (int(time.time()), rate)\n    fp.write(data)\n    print(data)\n\nwhile True:\n    try:\n        band = MiBand2(MAC, debug=True)\n        band.setSecurityLevel(level=\"medium\")\n        band.authenticate()\n        band.start_heart_rate_realtime(heart_measure_callback=log)\n        band.disconnect()\n    except BTLEException:\n        pass\n"
  },
  {
    "path": "example.py",
    "content": "import sys\nimport time\nimport argparse\nfrom datetime import datetime\nfrom base import MiBand2\nfrom constants import ALERT_TYPES\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-s', '--standard',  action='store_true',help='Shows device information')\nparser.add_argument('-r', '--recorded',  action='store_true',help='Shows previews recorded data')\nparser.add_argument('-l', '--live',  action='store_true',help='Measures live heart rate')\nparser.add_argument('-i', '--init',  action='store_true',help='Initializes the device')\nparser.add_argument('-m', '--mac', required=True, help='Mac address of the device')\nparser.add_argument('-t', '--set_current_time', action='store_true',help='Set time')\nargs = parser.parse_args()\n\nMAC = args.mac # sys.argv[1]\n\nband = MiBand2(MAC, debug=True)\nband.setSecurityLevel(level=\"medium\")\n\nif  args.init:\n    if band.initialize():\n        print(\"Init OK\")\n    band.set_heart_monitor_sleep_support(enabled=False)\n    band.disconnect()\n    sys.exit(0)\nelse:\n    band.authenticate()\n\nif args.recorded:\n    print('Print previews recorded data')\n    band._auth_previews_data_notif(True)\n    start_time = datetime.strptime(\"12.03.2018 01:01\", \"%d.%m.%Y %H:%M\")\n    band.start_get_previews_data(start_time)\n    while band.active:\n        band.waitForNotifications(0.1)\n\nif args.standard:\n    print ('Message notif')\n    band.send_alert(ALERT_TYPES.MESSAGE)\n    time.sleep(3)\n    # this will vibrate till not off\n    print ('Phone notif')\n    band.send_alert(ALERT_TYPES.PHONE)\n    time.sleep(8)\n    print ('OFF')\n    band.send_alert(ALERT_TYPES.NONE)\n    print ('Soft revision:',band.get_revision())\n    print ('Hardware revision:',band.get_hrdw_revision())\n    print ('Serial:',band.get_serial())\n    print ('Battery:', band.get_battery_info())\n    print ('Time:', band.get_current_time())\n    print ('Steps:', band.get_steps())\n    print ('Heart rate oneshot:', band.get_heart_rate_one_time())\n   \nif args.set_current_time:\n    now = datetime.now()\n    print ('Set time to:', now)\n    print ('Returned: ', band.set_current_time(now))\n    print ('Time:', band.get_current_time())\n\ndef l(x):\n    print ('Realtime heart:', x)\n\n\ndef b(x):\n    print ('Raw heart:', x)\n\n\ndef f(x):\n    print ('Raw accel heart:', x)\n\nif args.live:\n    # band.start_heart_rate_realtime(heart_measure_callback=l)\n    band.start_raw_data_realtime(\n            heart_measure_callback=l,\n            heart_raw_callback=b,\n            accel_raw_callback=f)\n\nband.disconnect()\n"
  },
  {
    "path": "plot.py",
    "content": "import numpy as np\nimport pandas as pd\nimport sys\nfrom stockstats import StockDataFrame\nimport matplotlib.pyplot as plt\n\ndf = pd.DataFrame.from_csv(sys.argv[1], index_col=None)\nprint (df.head())\ndf['time'] = pd.to_datetime(df['time'], unit='s')\ndf = df.set_index('time')\nprint (df.describe())\n# plt.subplot('111')\n# df.plot(kind='line')\n# plt.subplot('122')\n# df.plot(kind='histogram')\ndf.rolling('120s').mean().plot()\nplt.show()\n"
  },
  {
    "path": "requirements.txt",
    "content": "bluepy==1.3.0\npycrypto==2.6.1\n"
  }
]