#!/usr/bin/env python

# smartPlug AWOX control with Bluez
#
# Control an AWOX smartPlug (BLE electrical plug with relay) from command line
# sample: './smart_plug_ctl.py 98:7B:F3:34:78:52 on' to turn on the plug
#
# needs: bluez installed with gatttool utility
#
# license: MIT

import sys
import subprocess
import argparse

# parse args
parser = argparse.ArgumentParser()
parser.add_argument('ble_addr', type=str, 
                    help='plug bluetooth LE address (like 98:7b:f3:34:78:52)')
parser.add_argument('state', type=str, choices=['on', 'off'],
                    help='plug state to set')
args = parser.parse_args()

# format gatttool command
cmd = 'gatttool -b {0}'.format(args.ble_addr)
plug_on_opt = ' --char-write -a 0x2b -n 0f06030001000005ffff'
plug_off_opt = ' --char-write -a 0x2b -n 0f06030000000004ffff'
cmd += plug_on_opt if args.state == 'on' else plug_off_opt
cmd += ' 2>/dev/null'

# do it
return_code = subprocess.call(cmd, shell=True)

# return gatttool error code
sys.exit(return_code)

@@ -277,18 +277,68 @@
 IT%0A%0A
-import sys
+from __future__ import print_function%0Aimport sys%0Aimport time
 %0Aimp
@@ -962,16 +962,45 @@
 # do it%0A
+do_retry = 3%0Awhile True:%0A    
 return_c
@@ -1038,16 +1038,392 @@
 l=True)%0A
+    do_retry -= 1%0A    # exit if cmd is ok or too retry%0A    if return_code == 0 or do_retry %3C 1:%0A        break%0A    else:%0A        print('error, do another try', file=sys.stderr)%0A    # wait before next try%0A    time.sleep(0.2)%0A%0A# print status%0Aif return_code == 0:%0A    print('smartPlug is set %7B0%7D'.format(args.state))%0Aelse:%0A    print('unable to contact smartPlug', file=sys.stderr)
 %0A# retur
@@ -1423,25 +1423,16 @@
 # return
- gatttool
  error c

add auto retry if com fail, add msg status