Git Product home page Git Product logo

homescript's Introduction

HomeScript

Donate

Python script for command line control of HomeBridge (HomeKit)

Used to toggle Homebridge accessories On or Off via python script, no Home app required. You can set up a cronjob to enable automation, scripting and mimic other HomeKit functionalities

Note: as of HomeScript 4.1 the minimum requirement is Python3+ and HomeBridge 1.x.x+

Examples

hs.py -s MainLight 0 | Switch off
hs.py -s MainLight 1 | Switch on
hs.py -s MainLight | Toggle
hs.py -s lifx -hue 140 | RGB Lights Support (brightness, hue, saturation, temperature)
hs.py -s desk -b +10 | Increment/Decrement values

Easy Match

The script doesn't require full names of the accessories.

For example, if your light is called "MainLight", you can run:
hs.py -s MainLight 0 or
hs.py -s main 0
The script will automatically search for matching substrings and set the accessory value

Group Actions

You can set multiple accessories (of the same type) in a single command:
hs.py -s all lights 1
hs.py -s all switches 0

Looking for maintainers: If you are interested in maintaining this project, feel free to reach out.

Setup

Important: HomeBridge must be run in insecure mode for this script to work!

Running HomeBridge in Insecure Mode

  • via Command Line
homebridge -I
  • via Systemd
HOMEBRIDGE_OPTS=-U /var/lib/homebridge -I
  • via pm2
pm2 stop homebridge; pm2 delete homebridge; pm2 start homebridge -- -I

Installation

  • Install the HomeScript API pip install homescript or pip3 install homescript
  • On your client computer: Download hs.py and move it to a convenient location
    • Edit the script to include your homebridge URL, port and authorization key
    • Change permissions chmod +x /path/to/hs.py (on linux)

Usage

Usage: hs.py [option] [value]

Options:

  • -l, --list : Lists all available HomeKit accessories
  • Usage: hs.py -l [argument]
  • Arguments:
    • <none> : lists accessory names
    • aid : lists accessory names with AID value
    • iid : lists accessory names with IID value
    • id : lists accessory names with AID and IID
    • type : lists accessory names with type
    • value : lists accessory names current state
  • -g, --get : [EasyMatch] gets current value of accessory
    • Usage: hs.py -g <accessory-name>
  • -s, --set : [EasyMatch] toggles the accessory On or Off, or sets to the specified value
    • Usage: hs.py -s <accessory-name> [value]
    • Arguments:
      • <accessory-name> : accessory that you want to change
      • -b : adjusts accessory brightness
      • -hue : adjusts accessory hue
      • -sat : adjusts accessory saturation
      • -t : adjusts accessory color temperature
      • [value] : value that you want to set it to. Prefix +/- to inc/dec
  • all : Gets or sets value of multiple HomeKit accessories
    • Usage: hs.py -g all <accessory-type> hs.py -s all <accessory-type> value
  • -d, --debug : generates debug log file.
    • Usage: hs.py -d <command>
    • Eg: hs.py -d -s all lights 0
  • -h, --help : prints usage info
  • -v, --version : prints HomeScript version

API

As of v5.1+ HomeScript is now a fully importable API

import homescript

# Initialize with hostname, port and auth code. Debug and sys.argv are optional
hs = homescript.HomeScript(hostname, port, auth, [debug], [sys.argv])

# Select an accessory or group of accessories. Any get/set/print operation requires accessories to be selected first.
hs.selectAccessory('mainlight')
hs.selectGroup('lights')

hs.printSelectedItems()

# Operates on all selected items
hs.setStates(1)
hs.setValues('Brightness',250)
Function Description
HomeScript( hostname: str, port: str, auth: str, debug: Boolean, argv: list ) Constructor to initialize HomeBridge Connection. Debug: Set to True if you want to create debug and exception logfile. Default: None. argv: Only required if debug is True
getAccessories() Returns raw list of all available accessories on the Bridge
selectAccessories( searchString: str ) Saves matching accessory into selectedAccessories and returns them
selectGroup( searchString: str ) Saves all matching accessories into selectedAccessories and returns them
printAccessories() Prints all available accessories on the Bridge
printSelectedItems() Prints selectedAccessories
getSelectedItems() Returns selectedAccessories
setStates(state: Boolean) Sets state as the on/off value of all item(s) in selectedAccessories. If no argument is specified it toggles the state of all selectedAccessories
setValues(attribute: str, value: int) Sets numeric value to attribute of the item(s) in selectedAccessories. Attrubute: Brightness/Hue/Saturation/Color Temperature
getVersion() Does what it says on the can...

Troubleshooting/Error Reporting/Contributing

The debug option helps generate a logfile for troubleshooting and error detection.

  • If you face an error, open a new issue on this repo prefixed by [Error] describing the error and attach your both your debug log and your exception log, along with any other outputs you receive.
  • If you would like to help improve the tool or request features, open an issue prefixed by [Feature Request] describing the functionality.
  • You must attach your debug log or else your issue will be closed. A simple debug log can be obtained from hs.py -d -l

PRs and Commit Template

PRs and commits that you make to this repo must include the following:

  • Type: bug-fix or enhancement
  • Description: Brief description about what the commit achieves
  • Notes: (heads ups/pointers to other developers if necessary)

To Do

☑️ Color control for RGB and Hue Lights
⬜️ Control for PositionOpeners, GarageDoorOpener, LockMechanism
⬜️ WebColors
☑️ Increment/Decrement values
☑️ Querying API interface to return status of devices to stdout
☑️ Automation creation, viewing and monitoring without Home Hub


Changelog

v5.2

  • Added support for Increment/Decrement values
  • HS Automations and HS Apps are now deprecated

v5.1.1

  • Fixed import bug

v5.1

  • Rewritten from the ground up to be object oriented
  • Now features an importable API

v5.0

  • Support for RGB lights! Now lets you control brightness, hue, saturation and color temperature of your lights!
  • Added additional value format recognition
  • Device type detection
  • Updated accessory structure
  • Added smart toggle support for integer values
  • Added validity checks for integer values
  • Ignore bridge in accessory list
  • Updated listing format
  • Finer control over listing parameters for devices with multiple interfaces
  • Updated exclusive value-only listing for easier interfacing in programs
  • Cleaned up accessory name recognition
  • Backward compatibility with v4.x syntax for all devices

v4.1

  • Update to python 3
  • Update to support HomeBridge v1.0+

v4.0

  • Syntax update to be POSIX compliant
  • Get option to return item status
  • Introducing Automation and scripting support
  • Modularity and Third-party HomeScript Apps
  • Version logging
  • Improved Debugging Note: Some parts of release withheld until the next minor release

v3.0.2

  • Bug fix: HomeBridge was displayed as "0"

v3.0.1

  • Added debug support

v3.0

  • Added group actions. You can now set values for all matching accessory types

v2.2

  • Added json listing support

v2.1

  • Added type support to identify accessory type
  • Updated help doc

v2.0

  • List of accessories are now automatically fetched from the homebridge, instead of having to manually set them up in the script

v1.3

  • Added easy name matching

v1.2

  • Added help doc
  • Added listing

v1.1

  • Added toggling

v1.0

  • Initial release

homescript's People

Contributors

kylemikableh avatar menahishayan avatar nikelect avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

homescript's Issues

AttributeError: 'HomeScript' object has no attribute 'debug'

No matter what I do, whenever I run hs.py or us the API I get this error:

Traceback (most recent call last):
  File "/home/pi/Desktop/hs.py", line 56, in <module>
    hs = homescript.HomeScript(__HOSTNAME__,__PORT__,__AUTH__, args.debug, sys.argv)
  File "/home/pi/.local/lib/python3.9/site-packages/homescript/__init__.py", line 24, in __init__
    self.getAccessories()
  File "/home/pi/.local/lib/python3.9/site-packages/homescript/__init__.py", line 51, in getAccessories
    if self.debug:
AttributeError: 'HomeScript' object has no attribute 'debug'

installation issues

Hi, I'm trying to install this on an ubuntu VM but pip won't install complaining that "Could not find a version that satisfies the requirements."

My setup:
Ubuntu 18.04.6
pip 9.0.1
python 3.6.9

Any ideas?
Thank you.

Error when running homescript to toggle wemo switch

D:\bin\HomeScript\HomeScript-master>py hs.py -s Food
Traceback (most recent call last):
File "D:\bin\HomeScript\HomeScript-master\hs.py", line 91, in
hs.setStates(sys.argv[argumentLength-1] or None)
File "D:\bin\HomeScript\HomeScript-master\homescript_init_.py", line 123, in setStates
elif item['value'][0]['value'] == 0 or item['value'][0]['value'] == False:
IndexError: list index out of range

AttributeError: 'HomeScript' object has no attribute 'debug'

Hello,

I am facing the below issue:

$python3 hs.py -s Tapo Lamp 0

Traceback (most recent call last):
File "/Users/HomeScript/homescript/init.py", line 45, in getAccessories
interfaces.append({'iid':i['iid'],'description': #i['description'],'maxValue': i['maxValue'],'minValue': i['minValue'],'minStep': i['minStep'], 'value': i['value']})
KeyError: 'maxValue'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Users/HomeScript/hs.py", line 56, in
hs = homescript.HomeScript(HOSTNAME,PORT,AUTH, args.debug, sys.argv)
File "/Users/HomeScript/homescript/init.py", line 24, in init
self.getAccessories()
File "/Users/HomeScript/homescript/init.py", line 51, in getAccessories
if self.debug:
AttributeError: 'HomeScript' object has no attribute 'debug'

Any ideas?
Thanks :)

Error executing script

Hi, I'm executing your script but I'm receiving some errors.

following the setting in the script:

**url = 'http://homebridgea.local:51827/'

headers = {'Content-Type': 'Application/json','authorization': '031-45-154',}**

(fyi I can ping "homebridgea")

and following the first lines in config.json:

**"bridge": {

"name": "Homebridgea",

"username": "xx:xx:xx:xx:xx:xx",

"port": 51827,

"pin": "031-45-154"

},**

I'm receiving the following error also executing the script with the "list" parameter:
pi@homebridgea:~ $ python homescript.py list
Traceback (most recent call last):
File "homescript.py", line 88, in
getAccessories()
File "homescript.py", line 24, in getAccessories
accessories.update({str(item['services'][1]['characteristics'][0]['value']) : {'aid':item['aid'],'iid':item['services'][1]['characteristics'][1]['iid'],'type':item['services'][0]['characteristics'][2]['value'],'value':item['services'][1]['characteristics'][1]['value']}})
IndexError: list index out of range

Please, let me know.

Thanks

PS: I'm executing HB in insecure mode:
HOMEBRIDGE_OPTS=-I -U /var/homebridge

[Error] IndexError: list index out of range

getting an index out of range error with my homebridge configuration.

Traceback (most recent call last):
File "./homeScriptO.py", line 40, in getAccessories
accessories.update({str(item['services'][1]['characteristics'][0]['value'] or item['services'][0]['characteristics'][2]['value']).replace(' ','_') : {'aid':item['aid'],'iid':item['services'][1]['characteristics'][1]['iid'],'type':item['services'][0]['characteristics'][2]['value'],'value':item['services'][1]['characteristics'][1]['value']}})
IndexError: list index out of range

got around it by adding another try/except block in getAccessories:

def getAccessories():
global getAcc
try:
getAcc = requests.get(url + 'accessories', headers=headers)
for item in getAcc.json()['accessories']:
try:
accessories.update({str(item['services'][1]['characteristics'][0]['value'] or item['services'][0]['characteristics'][2]['value']).replace(' ','_') : {'aid':item['aid'],'iid':item['services'][1]['characteristics'][1]['iid'],'type':item['services'][0]['characteristics'][2]['value'],'value':item['services'][1]['characteristics'][1]['value']}})
except:
print '!accessory exception!'
except:
# print(sys.exc_info()[0])
if sys.argv[1] == '-d' or sys.argv[1] == '--debug':
# debugHandler(str(sys.exc_info()[0]))
logging.error(Exception, exc_info=True)
print 'Exception logged: ' + exceptionFile
return accessories

homescript_debug_2020.07.18.log
homescript_exception_2020.07.18.log

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Whenever I try to run py homeScript.py -l or any other command, I get the error json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0). More specifically, the error is:

DEBUG:urllib3.connectionpool:Starting new HTTP connection (1): 192.168.2.42:8581
DEBUG:urllib3.connectionpool:http://192.168.2.42:8581 "GET /accessories HTTP/1.1" 200 1608
ERROR:root:<class 'Exception'>
Traceback (most recent call last):
  File "homeScript.py", line 40, in getAccessories
    getAcc = getAcc.json()
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\site-packages\requests\models.py", line 900, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\USER\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Incomplete list of Accessories?

First of all, thank you very much for this project!

I am a new user of Homebridge and Homescript. I have recently installed a Nest thermostat and I'm working on a way of automating the hot water activation by way of readings received from a wireless temperature sensor attached to my hot water cylinder.

My Homebridge installation, with Homebridge-nest plugin, displays four Accessories in the web interface: the thermostat itself, Eco Mode, Hot Water and Home Occupied. However, when I run hs.py -l, only the thermostat and the Home Occupied Accessories are listed. I don't really care about Eco Mode, but I need to be able to see the Hot Water Accessory.

Any ideas why that one is not appearing through Homescript?

EDIT:

So I have done some more digging. I think the reason the Eco Mode and Hot Water are not showing up is because they are not their own Accessories as defined within Homebridge-nest. Rather, they are added as services to the thermostat Accessory if the appropriate booleans are set.

Within Homescript, in the getAccessories function it only parses "item['services'][1]' whereas in my installation, Eco mode appears to be item['services'][2] and hot water appears to be item['services'][2].

(Separately, I noticed when parsing from ['characteristics'][1] onward, it misses out ['characteristics'][0] (by definition) which is the current thermostat heating/cooling state. is it necessary to skip that for any reason?)

object has no attribute 'debug'

Can you tell me what is wrong? Port and pin are correct from hb setting.

opiz:~:# python3 hs.py -l
Traceback (most recent call last):
File "/usr/local/lib/python3.7/dist-packages/homescript/init.py", line 45, in getAccessories
interfaces.append({'iid':i['iid'],'description': i['description'],'maxValue': i['maxValue'],'minValue': i['minValue'],'minStep': i['minStep'], 'value': i['value']})
KeyError: 'minStep'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "hs.py", line 56, in
hs = homescript.HomeScript(HOSTNAME,PORT,AUTH, args.debug, sys.argv)
File "/usr/local/lib/python3.7/dist-packages/homescript/init.py", line 24, in init
self.getAccessories()
File "/usr/local/lib/python3.7/dist-packages/homescript/init.py", line 51, in getAccessories
if self.debug:
AttributeError: 'HomeScript' object has no attribute 'debug'
opiz:~:#
`

Feature Request: Brightness Up / Down

I've written a pretty terrible bash script that gets the current brightness and then adjusts it up / down depending on the script I run:

#!/bin/bash

CURRENT=$(~/homeScript/homeScript.py -g desk | awk '{print $19}' | tr -d "},")
NEW=$(expr $CURRENT - 10)

~/homeScript/homeScript.py -s desk -b $NEW

I was wondering if there was a more elegant way to do this directly with the -b option ?
My use case in case you're curious is having them mapped to F keys on my keyboard for brightness up / down.

thanks again for a fantastic script :)

Homescript and homebridge are not communicating correctly

[EDIT] I had posted an issue, but I had a corrupted version of hs.py and re-installed it, and the problem changed to this:

python3 ./hs.py -s Crafting_Tables 1
Traceback (most recent call last):
File "/home/bsb/HomeScript-master/./hs.py", line 91, in
hs.setStates(sys.argv[argumentLength-1] or None)
File "/home/bsb/HomeScript-master/homescript/init.py", line 122, in setStates
item['value'][0]['value'] = int(value)
IndexError: list index out of range

[Error] Unable to set wemo smart plug

When I use hs.py to set wemo smart plug on/off, I got this exception
Traceback (most recent call last):
File "/root/hs.py", line 91, in
hs.setStates(sys.argv[argumentLength-1] or None)
File "/usr/local/lib/python3.9/dist-packages/homescript/init.py", line 124, in setStates
item['value'][0]['value'] = int(value)
IndexError: list index out of range.

I try to debug the problem, and I found if I make minor change to "/usr/local/lib/python3.9/dist-packages/homescript/init.py" file, it fixes the issue. See attached modified init.py, I am not sure if there is any other place that need to modify.

homescript_debug_2022.03.09.log
init.py.gz

.selectGroup() seems to be required. Is it?

First, thank you for this excellent thing! :)

If I run...

hs.selectAccessory('Floor_Light')
hs.printSelectedItems()
hs.setStates("0")

No Accessories are returned and the setStates() does not work (logs attached), even though the accessory name provided comes straight out of "printAccessories()".

If I add in selectGroup('lights') as follows, two lights are returned and the action is properly executed on both...

hs.selectAccessory('Floor_Light')
hs.selectGroup('lights')
hs.printSelectedItems()
hs.setStates("0")

I've also included the super simple test python file ("Homebridge_ctl.txt").

Can't quite figure what I'm doing wrong here. THANKS for any help!

Alex

homescript_debug_2022.01.20.log
homescript_exception_2022.01.20.log
Homebridge_ctl.txt

Error 207 on Ring set value (alarm)

Hello

I'm using ring plugin under hombridge i'ts ok

Now I want to automate my alarm mode via script and i'm using homescript

It is correctly installed because when I run python3 hs.py -l I get all my accessories :
pi@domoticz:~$ python3 hs.py -l
Accessory/Group not found.
Here are a list of accessories:

Alarm security-panel
Base_Station hub.redsky
Baie_vitree sensor.contact
Pavé_numérique_entree security-keypad
Salle_à_manger sensor.motion
Salon Indoor Cam (stickup_cam_mini)

Now I can get the mode for Alarm :
pi@domoticz:~$ python3 hs.py -g Alarm
Alarm [{'iid': 10, 'description': 'Security System Current State', 'value': 3}, {'iid': 11, 'description': 'Security System Target State', 'value': 3}]

But now i don't now how to set the value for alarm mode (target state i believe)
I get the value for each mode :
Disarm : 3
Home: 0
Away : 1

I tried multiple things but I get every time this

<Response [207]>
Alarm Error: -70404

thans for all

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.