Switchbotをpython3で操作&情報取得してみた

WEBでSETTINGSボタンを押した結果はこんな感じです。

ステップ1 switchbot.pyをWEBの公開フォルダの外に作成する

#!/usr/bin/python3
# -*- coding: utf-8 -*-

# Copyright 2017-present WonderLabs, Inc. <support@wondertechlabs.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# refs. https://github.com/OpenWonderLabs/python-host/blob/master/switchbot_meter_py3.py
# refs. https://github.com/kanon700/python-host/blob/feature/add_get_settings/switchbot_meter_py3.py

# Setup Raspberry pi 3
# apt-get install python3-pip
# pip3 install bluepy
# crontab -e
#55 6 * * * (非公開フォルダ)/switchbot.py settings &> /dev/null
#0 7 * * * (非公開フォルダ)/switchbot.py turn_on &> /dev/null

import binascii
from bluepy import btle
from socket import gethostname
import json
import requests
import sys
import traceback

COMMANDS = {
  'settings' : '5702',
  'press'    : '570100',
  'turn_on'  : '570101',
  'turn_off' : '570102',
  'down'     : '570103',
  'up'       : '570104',
}
EXIT_FAILURE=1
EXIT_SUCCESS=0
HANDLE_READ=0x13
HANDLE_WRITE=0x16
MAC_ADDRESS='00:00:00:00:00:00'   # switchbot mac address
TIMEOUT_SECONDS_NOTIFICATIONS=1
UUID_SERVICE='cba20d00-224d-11e6-9fb8-0002a5d5c51b'
UUID_SPECIFIED_CHARACTERISTIC='cba20002-224d-11e6-9fb8-0002a5d5c51b'
URL_WEBHOOK='(Discord webhook url)'

if __name__ == '__main__':
  if len(sys.argv) != 2:
    print('Usage: ./switchbot (settings|press|turn_on|turn_off|down|up)')
    sys.exit(EXIT_FAILURE)

  if sys.argv[1] not in COMMANDS:
    print('Unknown parameter.')
    sys.exit(EXIT_FAILURE)
  key=sys.argv[1]

  try:
    p = btle.Peripheral(MAC_ADDRESS, btle.ADDR_TYPE_RANDOM)
    p.waitForNotifications(TIMEOUT_SECONDS_NOTIFICATIONS)
    svc = p.getServiceByUUID(UUID_SERVICE)
    ch = svc.getCharacteristics(UUID_SPECIFIED_CHARACTERISTIC)[0]
    p.writeCharacteristic(HANDLE_WRITE, binascii.a2b_hex(COMMANDS[key]), True)
    value = p.readCharacteristic(HANDLE_READ)
    result = {}
    if key == 'settings':
      result['battery'] = value[1]
      result['firmware'] = value[2] / 10.0
      result['n_timers'] = value[8]
      result['dual_state_mode'] = bool(value[9] & 16)
      result['inverse_direction'] = bool(value[9] & 1)
      result['hold_seconds'] = value[10]

      # alert battery
      if result['battery'] <= 30:
        requests.post(URL_WEBHOOK, json.dumps({'content': '[switchbot] Low power. (hostname: ' + gethostname() + ')'}), headers={'Content-Type': 'application/json'})
    else:
      result['return_code'] = binascii.b2a_hex(value).decode()

    print(str(result))
    p.disconnect()

  except Exception as e:
    print(traceback.format_exc())
    sys.exit(EXIT_FAILURE)

sys.exit(EXIT_SUCCESS)

ステップ2 WEBの公開フォルダにindex.phpを作成する

<?php
// Setup Raspberry pi 3
// apt-get install nginx
// apt-get install php php-fpm
// systemctl enable nginx
// systemctl enable php-fpm
// systemctl start nginx
// systemctl start php-fpm
?>
<html>
  <head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no, minimal-ui">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <title>Switchbot</title>
    <style type="text/css">
    * {
      background-color:#505050;
      color: #DDDDDC;
      font-family: -apple-system, blinkMacSystemFont,
        'Helvetica Neue',
        'Segoe UI',
        'Hiragino Kaku Gothic ProN',
        Meiryo,
        sans-serif;
    }
    a {
      text-decoration: none;
    }
    textarea, input[type=submit] {
      width:100%;
      height:10%
    }
    </style>
  </head>
  <body>
    <a href="/"><h1>Switchbot</h1></a>
    <hr />
    <form action="./index.php" method="post">
      <input type="hidden" name="action" value="turn_on">
      <input type="submit" value="ON">
      <?php
        if(@$_POST['action'] == 'turn_on'){
          echo '<textarea>';
          echo exec('(非公開フォルダ)/switchbot.py turn_on');
          echo '</textarea>';
        }
      ?>
    </form>
    <form action="./index.php" method="post">
      <input type="hidden" name="action" value="turn_off">
      <input type="submit" value="OFF">
      <?php
        if(@$_POST['action'] == 'turn_off'){
          echo '<textarea>';
          echo exec('(非公開フォルダ)/switchbot.py turn_off');
          echo '</textarea>';
        }
      ?>
    </form>
    <form action="./index.php" method="post">
      <input type="hidden" name="action" value="settings">
      <input type="submit" value="SETTINGS">
      <?php
        if(@$_POST['action'] == 'settings'){
          echo '<textarea>';
          echo exec('(非公開フォルダ)/switchbot.py settings');
          echo '</textarea>';
        }
      ?>
    </form>
  </body>
</html>

WEBでON/OFFや情報が見れて、crontabでスケジュール設定もでき、なおかつ、バッテリーが切れそうなときはdiscordなどに通知を飛ばしたりできるはず。

※セキュリティーは全然設定してないのでプライベートネットワーク限定です。Wi-FiとBluetoothは無効にしておかなきゃ危ないかも(;’∀’)

コメントを残す

メールアドレスが公開されることはありません。