Hexoskin을 통해 심전기, 호흡, 가속도 정보를 얻기(Getting Started with Hexoskin)

16578 단어 HexoskinPython

개시하다


석사 논문 연구에는 Hexoskin을 사용했다.
다만, 헥소스킨 사용법에 대한 기사는 큐타나 다른 블로그에도 없어 힘들었다.
이에 따라 이번에는 같은 신산을 맛보는 이들을 줄이기 위해 헥소스킨과 헥소스킨 API의 도입에 관한 기사를 썼다.

이른바 Hexoskin


카레 테크놀로지(캐나다)가 만든 센서가 달린 스마트 셔츠.
가격은 한 세트에 약 7만 엔이다.

입기만 하면 구름 위에 아래 데이터를 기록할 수 있다.
  • 심장 박동 정보(심전도, 심장 박동수, 심장 박동 간격 등)
  • 호흡 정보(호흡수, 호흡률, 산소 소모량 등)
  • 활동 정보(보수, 보행률, 가속도 등)
  • Hexoskin의 구성도


    전용 애플리케이션을 통해 Hexoskin사의 클라우드에 데이터를 순차적으로 전송합니다.
  • 참조 링크

  • 공식 사이트(영어)

  • 수입 판매 사이트(일본어)
  • Hexoskin의 데이터를 얻다


    이번엔 익스프레스의 초기 설정부터 익스프레스 API까지 클라우드에서 데이터를 받아보기로 했다.

    1. 초기 설정


    QUICK START(공식)를 보면서 초기 설정을 하세요.
    중요한 것은
    ① 로거 충전
    ② 계좌 등록, 설정https://my.hexoskin.com/en/signup
    ③ 모바일 터미널에 전용 앱 설치
    ④ Bluetooth 쌍 설정(로거 및 모바일 터미널)

    2. API 준비


    Hexoskin API는 Oauth2(및 Oauth1)로 승인됩니다.
    https://api.hexoskin.com/docs/index.html#before-getting-started
    또 Hexoskin에서 Outh2의 인증 정보(ID와 secret key)를 취득하기 위해서는 개발자에게 이메일을 보내야 한다.
    https://www.hexoskin.com/pages/developers
    따라서 위 URL에 기재된 메일 주소로 다음 메일을 보내주세요.
    Hello,
    
    Please send me API keys, I'm eager to start developing an API to access Hexoskin data.
    My account information to use API key is as follows.
    
    ******
    Account email:
    First name:
    Last name:
    Time zone:
    ******
    (▲ 1.の②(https://my.hexoskin.com)で登録した情報を書く)
    
    And just in case you need, additional information are described below.
    
    ******
    My organization is:
    Our project name is:
    Our project summary:
    ******
    (▲ APIの使用用途について(決まっていれば)書く)
    
    Please let me know if there is missing information.
    If not, please send me the API key.
    
    Thanks a lot,
    
    ■-----------------------------------
    (署名など)
    -----------------------------------■
    
    이따가 이런 답장이 올 거예요.
    (Your Name),
    
    Your OAuth2 information is:
     client id: **********
     secret: **********
    
    You can update your client (to add redirect URIs, for example) using the API at this endpoint:
    https://api.hexoskin.com/api/oauthclient/359/
    
    OAuth2 is our preferred method of authentication.  There's a section on our OAuth2 implementation here that I recommend you start with:
    https://api.hexoskin.com/docs/page/oauth2/
    
    We have a developer group here which we watch closely:
    https://groups.google.com/forum/#!forum/hexoskin-developer
    
    The rest of the API documentation is here:
    https://api.hexoskin.com/docs/
    
    There's a Python client available here:
    https://bitbucket.org/carre/hexoskin-api-python-client
    
    Don't hesitate to post to the list if you need a hand with something.  Happy coding!
    
    인증 정보 외에도 문서와 개발자 그룹 등의 공식 정보를 알릴 수 있어 예의 바르다.
    그럼 여기까지 하면 API의 준비가 완료됩니다.

    3. API에서 데이터 가져오기


    그러면 드디어 Hexoskin API를 통해 클라우드에서 데이터를 얻을 수 있습니다.
    이번에 소개한 것은 Hexoskin API공식 Python 클라이언트에 쉽게 접근할 수 있는 소스 코드를 사용한 것이다.
    다음 링크를 통해 클론이나download를 진행하십시오.
  • 파이톤 클라이언트 - https://github.com/lguerdan/HexoBio
  • 또 이때 헥소스킨을 사용하지 않은 상태에서 입어보고 테스트 데이터를 제작할 수 있다.

    실행 환경(작업 확인 완료)

  • OS: macOS High Sierra
  • Python: 2.7.14
  • 사전 준비 ①: 외부 라이브러리 설치


    다음 프로그램 라이브러리를 설치하십시오.
    Terminal
    $ pip install requests urllib numpy pandas jupyter
    

    사전준비 ②: 인증 정보 등을 취합한다


    이번에는 인증 정보 등을 외부 문서에 취합해 관리한다.
    credentials.json
    {
        "HexAPIkey": "「2. APIの準備」で取得したclient id",
        "HexAPIsecret": "「2. APIの準備」で取得したsecret",
        "HexUserName":  "「1.の②」で登録したEmail",
        "HexPassword": "「1.の②」で登録したPassword"
    }
    

    파일 구조

    HexoBio
    ├── credentials.json
    ├── get_rrinterval.ipynb
    ├── HxApi2_0.py
    └── ...
    

    실행 프로그램


    프로그램 라이브러리의 설치와 파일 구조에 주의를 기울였을 것입니다. 이번 인코딩은 Jupter Notebook을 사용했습니다.
    예를 들어'rrinterval(심장 박동률 간격)'데이터 프레임을 출력할 때까지 코드를 나타낸다.
    get_rrinterval.ipynb
    # -*- coding: utf-8 -*-
    
    import HxApi2_0
    import hexoskin.client
    import urllib, json
    import numpy as np
    import pandas as pd
    %matplotlib inline
    
    # JSONから認証情報を読み込む
    with open("credentials.json", "r") as f:
        credentials = json.load(f)
    username = credentials["HexUserName"]
    password = credentials["HexPassword"]
    publicKey = credentials["HexAPIkey"]
    privateKey = credentials["HexAPIsecret"]
    
    # userIDを取得
    userURL = "https://" + username + ":" + password + "@api.hexoskin.com/api/user/"
    userInfo = urllib.urlopen(userURL).read()
    userInfoJSON = json.loads(userInfo)
    userID = userInfoJSON["objects"][0]["id"]
    
    # OAuth2.0認証を行なう
    auth = HxApi2_0.SessionInfo(publicKey=publicKey,privateKey=privateKey,username=username,password=password)
    
    # 記録したActivityのIDを取得
    records = HxApi2_0.getRecordList(auth, limit = "2000")
    all_recordID = [record['id'] for record in records]
    last_recordID = all_recordID[len(all_recordID)-1]   # 直近のActivityのID
    
    # 直近のActivityのデータを取得
    dataset = HxApi2_0.getRecordData(auth,recordID=last_recordID)
    
    # rrinterval(心拍間隔)を選択
    target = "rrinterval"
    
    # numpyで配列を作成
    np_data = np.array(dataset[target])
    print np_data
    
    # pandasのデータフレームを作成
    df_data = pd.DataFrame(np_data)
    
    # データフレームを整形
    df_data = df_data.rename(columns={0: "ts", 1: "value"}) # カラムを設定
    df_data = df_data.set_index("ts") # インデックスを設定
    df_data = df_data.astype(float) # floatに型変換
    df_data.drop(df_data.index[df_data["value"] == 0], inplace=True) # 値が0の行を削除
    
    # 冒頭5行を出力
    df_data.head(5)
    

    참고로 줄거리의 결과는 이렇다.
    # データをプロット
    df_data.plot()
    

    또한 rrinterval (심장 박동 간격) 이외의 내용을 가져오려면 파이톤 클라이언트 HxApi2_0.py 의 아래 부분 (20~40 줄) 에서 주석을 삭제하십시오.
    HxApi2_0.py
    # Datatypes definitions
    if MODEL == 'Hexoskin':
        raw_datatypes = {#'acc':[4145,4146,4147],
            #'ecg':[4113],
            #'resp':[4129,4130]
            }
        datatypes = {#'activity':[49],
            #'cadence':[53],
            #'heartrate':[19],
            #'minuteventilation':[36],
            #'vt':[37],
            #'breathingrate':[33],
            #'hr_quality':[1000],
            #'br_quality':[1001],
            #'inspiration':[34],
            #'expiration':[35],
            #'batt':[247],
            #'step':[52],
            'rrinterval':[18],
            #'qrs':[22],
        }
    
    이렇게 하면 삭제된 주석 출력에 대응하는 데이터를 target = "rrinterval"의 오른쪽으로 바꾸면 그 데이터를 얻을 수 있다.
    다음 문서에서 각 데이터의 상세한 내용을 확인하세요.
  • Hexostore API Documentation - Data type
    https://api.hexoskin.com/docs/resource/datatype/
  • 끝맺다


    이번에 익스프레스킨과 익스프레스킨 API를 빠르게 테스트하는 방법을 정리했다.
    만약 이 보도가 헥슨 입문자를 도울 수 있다면 나는 매우 기쁠 것이다.
    참고로 현 단계에서 다음 세 가지는 유일하고 가장 유력한 학습 자원이다.(2018년 03월 01일 기준)
  • 공식 문서
  • 개발자 그룹
  • Python 클라이언트 README.md
  • API를 더 잘 사용하려면 여기를 참고하세요.

    좋은 웹페이지 즐겨찾기