YOGYUI

LG ThinQ REST API::공기청정기 제어 본문

홈네트워크(IoT)/일반

LG ThinQ REST API::공기청정기 제어

요겨 2023. 10. 31. 17:37
반응형

LG ThinQ REST API - Control Air Purifier

 

1년전 LG전자 로봇청소기의 가동 상태를 얻기 위해 ThinQ API(AWS IoT, MQTT)를 Python으로 연동한 바 있다

LG ThinQ REST API::파이썬 연동

 

LG ThinQ REST API::파이썬 연동

Access LG ThinQ API using Python 지난 글에서 Homebridge에 LG ThinQ 디바이스를 연동하는 방법에 대해 알아본 바 있다 Homebridge - LG ThinQ 연동하기 (애플 홈 연동) Homebridge - LG ThinQ 연동하기 (애플 홈 연동) Homebr

yogyui.tistory.com

별 문제없이 잘 쓰고 있었는데, 최근 해당 글에 다음과 같은 댓글이 달렸다

나도 ThinQ 디바이스의 현재 상태만 모니터링했지, ThinQ API를 통해 기기를 별도로 제어한 경험은 없었기에 이번 기회를 통해 REST API를 통해 기기를 제어하는 방법에 대해 알아보고 테스트해봤다

(기기 종류가 워낙에 많기 때문에, 댓글대로 공기청정기에 대해서만 우선 구현해봤다.. 추가 요구사항이 있으면 추가로 블로그 포스팅을 할 예정 ^^)

 

LG전자 ThinQ 개발자 프로그램에 개인 개발자 자격으로는 등록하기가 어렵기 때문에, 지난번과 마찬가지로 Homebridge의 ThinQ 플러그인 소스코드를 참고했다 (https://github.com/nVuln/homebridge-lg-thinq)

글이 너무 길어질 것 같아 개발 과정은 생략하고 결과만 포스팅하도록 한다
[참고]
- ThinQ Version 1 제어는 다루지 않음
- 테스트에 사용한 기기는 LG PuriCare 360˚(AS300DNPA) 모델이며, 다른 기기는 테스트해보지 않았다 (해볼 수가 없다 ㅠ)

1. 기기 제어 공통 사항

기기 제어를 위해서는 HTTP Request를 사용해야 하며, HTTP Method로는 POST를 사용해야 한다

Request시 사용할 URL에는 Thinq2 URI와 제어하고자 하는 기기의 고유 식별자인 Device ID가 필요하다

(ThinQ2 URI와 Device ID를 얻는 방법은 이전 글에 자세히 소개되어있으니 참고)

 

기기 제어를 위한 HTTP URI의 기본 포맷은 다음과 같다

https://kic-service.lgthinq.com:46030/v1/service/devices/{device_id}/control-sync

request시 함께 전송해야 할 페이로드(payload)는 다음과 같이 형식의 json 포맷을 보내면 된다

{
    "ctrlKey": "basicCtrl",
    "command": "Set",
    "dataKey": "제어 카테고리(문자열)",
    "dataValue": 제어값 (정수, 실수, 문자열 등)
}

또한 request시 함께 전송해야 할 HTTP 헤더(header)는 다음과 같은 포맷을 가져야 한다

(헤더는 홈브릿지 플러그인 소스코드에서 그대로 가져온 것으로, 반드시 이 포맷이어야 할 필요는 없을 것 같다)

중요한 건 API Key, Client ID, User No, Access Token 등을 함께 헤더로 전송해야 되는데, 이 값들을 얻는 방법은 이전 글에서 참고할 수 있다

{
    "x-api-key": "별도로 얻은 API key 문자열",
    "x-thinq-app-ver": "3.6.1200",
    "x-thinq-app-type": "NUTS",
    "x-thinq-app-level": "PRD",
    "x-thinq-app-os": "ANDROID",
    "x-thinq-app-logintype": "LGE",
    "x-service-code": "SVC202",
    "x-country-code": "KR",
    "x-language-code": "ko-KR",
    "x-service-phase": "OP",
    "x-origin": "app-native",
    "x-model-name": "samsung/SM-G930L",
    "x-os-version": "AOS/7.1.2",
    "x-app-version": "LG ThinQ/3.6.12110",
    "x-message-id": "22글자의 랜덤 문자열",
    "user-agent": "okhttp/3.14.9",
    "x-client-id": "별도로 얻은 Client ID 문자열",
    "x-user-no": "별도로 얻은 User Number 문자열",
    "x-emp-token": "별도로 얻은 Access 토큰 문자열"
}

2. 테스트 UI 개발

이것저것 테스트해보기 위해 PyQT를 사용해 간단한 테스트 UI를 만든 뒤 GitHub에 저장소를 생성했다

https://github.com/YOGYUI/python_thinq_api_tester

 

GitHub - YOGYUI/python_thinq_api_tester

Contribute to YOGYUI/python_thinq_api_tester development by creating an account on GitHub.

github.com

POST request 의사코드(psuedo-code)는 아래와 같으며, 자세한 건 깃허브 소스코드를 참고

import requests
from typing import Any, Literal

uri_thinq2 = 'https://kic-service.lgthinq.com:46030/v1'

def sendCommandToDevice(device_id: str, dataKey: str, dataValue: Any, command: Literal['Set', 'Operation'] = 'Set', ctrlKey: str = 'basicCtrl'):
    url = uri_thinq2 + f'/service/devices/{device_id}/control-sync'
    data = {
        'ctrlKey': ctrlKey,
        'command': command,
        'dataKey': dataKey,
        'dataValue': dataValue,
    }
    requests.post(url, json=data, headers=generate_default_header())

3. 공기청정기 제어를 위한 페이로드(payload)

※ PuriCare 360˚ 공기청정기의 디바이스 타입(deviceType) 아이디는 402

ThinQ API 초기화 단계에서 device list up할 때 공기청정기 디바이스의 'snapshot' 키에 저장된 딕셔너리는 다음과 같았다

'snapshot': {
  'airState.windStrength': 2.0, 
  'airState.miscFuncState.airFast': 0.0, 
  'airState.tempState.unit': 0.0, 
  'airState.diagCode': 0.0, 
  'mid': 902592461.0, 
  'airState.miscFuncState.watertankLight': 0.0, 
  'airState.lightingState.signal': 1.0, 
  'airState.quality.sensorMon': 1.0, 
  'airState.miscFuncState.antiBugs': 0.0, 
  'airState.quality.odor': 1.0, 
  'airState.tempState.target': 0.0, 
  'airState.humidity.current': 30.0, 
  'airState.filterMngStates.useTimeTop': 1636.0, 
  'airState.miscFuncState.airUVDisinfection': 0.0, 
  'airState.operation': 1.0, 
  'airState.wMode.humidification': 0.0, 
  'timestamp': 1698756231782.0, 
  'airState.quality.PM10': 20.0, 
  'airState.notification': 256.0, 
  'static': {'deviceType': '402', 'countryCode': 'KR'}, 
  'airState.filterMngStates.maxTimeTop': 4000.0, 
  'airState.quality.overall': 2.0, 
  'airState.tempState.current': 40.0, 
  'airState.miscFuncState.airRemoval': 0.0, 
  'airState.reservation.sleepTime': 0.0, 
  'airState.filterMngStates.desorption': 0.0, 
  'airState.miscFuncState.cleanDry': 0.0, 
  'airState.miscFuncState.petMode': 0.0, 
  'airState.reservation.targetTimeToStart': 0.0, 
  'meta': {'allDeviceInfoUpdate': False, 'messageId': 'J2CgmY8NRGehi5c-riJZaA'}, 
  'airState.quality.PM1': 16.0, 
  'airState.circulate.rotate': 0.0, 
  'airState.quality.PM2': 19.0, 
  'online': True, 
  'airState.opMode': 13.0, 
  'airState.reservation.targetTimeToStop': 0.0, 
  'airState.filterMngStates.maxTime': 4000.0, 
  'airState.filterMngStates.useTime': 657.0, 
  'airState.circulate.strength': 2.0, 
  'airState.notificationExt': 0.0
}

이 중 일부 키들이 HTTP Post request 시 json 페이로드 중 "dataKey" 키에 입력해야 하는 값이 된다

(예시: 전원 On/Off 시 사용할 키는 airState.operation)

3.1. 전원 On/Off

  • dataKey: "airState.operation"
  • dataValue: 0 혹은 1 (정수형, 0 = 전원 Off, 1 = 전원 On)

전원 On/Off에 대해서만 데모 동영상을 찍어봤다

3.2. 청정표시등 (LED) On/Off

  • dataKey: "airState.lightingState.signal"
  • dataValue: 0 혹은 1 (정수형, 0 = LED Off, 1 = LED On)

3.3. 순환팬 회전

  • dataKey: "airState.circulate.rotate"
  • dataValue: 0 혹은 1 (정수형, 0 = 순환팬 정지, 1 = 순환팬 회전)

3.4. 펫(Pet)모드 On/Off

  • dataKey: "airState.miscFuncState.petMode"
  • dataValue: 0 혹은 1 (정수형, 0 = 펫모드 Off, 1 = 펫모드 On)

3.5. 청정 세기

  • dataKey: "airState.windStrength"
  • dataValue: 정수형 (1 ~ 8)
    2 = 약, 4 = 중, 6 = 강, 7 = 터보, 8 = 자동

3.6. 순환팬 세기

  • dataKey: "airState.circulate.strength"
  • dataValue: 정수형 (1 ~ 8)
    2 = 약, 4 = 중, 6 = 강, 7 = 터보, 8 = 자동

3.7. 운전모드

  • dataKey: "airState.opMode"
  • dataValue: 정수형 (13 ~ 16)
    13 = 클린부스터, 14 = 싱글청정, 15=듀얼청정, 16 = 오토모드

이 외에도 UV 살균 (airState.miscFuncState.airUVDisinfection), 벌레 방지?(airState.miscFuncState.antiBugs), 취침 예약(airState.reservation.sleepTime) 등 이것저것 잡다한 제어항목이 많아보인다 ㅋㅋ

4. 마무리

공기청정기 외 다른 종류의 기기(에어컨, 로봇청소기, 세탁기, 건조기 등)의 제어를 위한 페이로드에 대해 알고 싶다면 댓글로 달아주시길 바랍니다~

반응형
Comments