#!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 import sys, getopt, httplib, urllib, json, os 5 import oauth.oauth as oauth 6 from configobj import ConfigObj 7 8 PUBLIC_KEY = '' 9 PRIVATE_KEY = '' 10 11 TELLSTICK_TURNON = 1 12 TELLSTICK_TURNOFF = 2 13 TELLSTICK_BELL = 4 14 TELLSTICK_DIM = 16 15 TELLSTICK_UP = 128 16 TELLSTICK_DOWN = 256 17 18 SUPPORTED_METHODS = TELLSTICK_TURNON | TELLSTICK_TURNOFF | TELLSTICK_BELL | TELLSTICK_DIM | TELLSTICK_UP | TELLSTICK_DOWN; 19 20 def printUsage(): 21 print("Usage: %s [ options ]" % sys.argv[0]) 22 print("") 23 print("Options:") 24 print(" -[lnfdbvh] [ --list ] [ --help ]") 25 print(" [ --on device ] [ --off device ] [ --bell device ]") 26 print(" [ --dimlevel level --dim device ]") 27 print(" [ --up device --down device ]") 28 print("") 29 print(" --list (-l short option)") 30 print(" List currently configured devices.") 31 print("") 32 print(" --help (-h short option)") 33 print(" Shows this screen.") 34 print("") 35 print(" --on device (-n short option)") 36 print(" Turns on device. 'device' must be an integer of the device-id") 37 print(" Device-id and name is outputed with the --list option") 38 print("") 39 print(" --off device (-f short option)") 40 print(" Turns off device. 'device' must be an integer of the device-id") 41 print(" Device-id and name is outputed with the --list option") 42 print("") 43 print(" --dim device (-d short option)") 44 print(" Dims device. 'device' must be an integer of the device-id") 45 print(" Device-id and name is outputed with the --list option") 46 print(" Note: The dimlevel parameter must be set before using this option.") 47 print("") 48 print(" --dimlevel level (-v short option)") 49 print(" Set dim level. 'level' should an integer, 0-255.") 50 print(" Note: This parameter must be set before using dim.") 51 print("") 52 print(" --bell device (-b short option)") 53 print(" Sends bell command to devices supporting this. 'device' must") 54 print(" be an integer of the device-id") 55 print(" Device-id and name is outputed with the --list option") 56 print("") 57 print(" --up device") 58 print(" Sends up command to devices supporting this. 'device' must") 59 print(" be an integer of the device-id") 60 print(" Device-id and name is outputed with the --list option") 61 print("") 62 print(" --down device") 63 print(" Sends down command to devices supporting this. 'device' must") 64 print(" be an integer of the device-id") 65 print(" Device-id and name is outputed with the --list option") 66 print("") 67 print("Report bugs to <info.tech@telldus.se>") 68 69 def listDevices(): 70 response = doRequest('devices/list', {'supportedMethods': SUPPORTED_METHODS}) 71 print("Number of devices: %i" % len(response['device'])); 72 for device in response['device']: 73 if (device['state'] == TELLSTICK_TURNON): 74 state = 'ON' 75 elif (device['state'] == TELLSTICK_TURNOFF): 76 state = 'OFF' 77 elif (device['state'] == TELLSTICK_DIM): 78 state = "DIMMED" 79 elif (device['state'] == TELLSTICK_UP): 80 state = "UP" 81 elif (device['state'] == TELLSTICK_DOWN): 82 state = "DOWN" 83 else: 84 state = 'Unknown state' 85 86 print("%s\t%s\t%s" % (device['id'], device['name'], state)); 87 88 def doMethod(deviceId, methodId, methodValue = 0): 89 response = doRequest('device/info', {'id': deviceId}) 90 91 if (methodId == TELLSTICK_TURNON): 92 method = 'on' 93 elif (methodId == TELLSTICK_TURNOFF): 94 method = 'off' 95 elif (methodId == TELLSTICK_BELL): 96 method = 'bell' 97 elif (methodId == TELLSTICK_UP): 98 method = 'up' 99 elif (methodId == TELLSTICK_DOWN): 100 method = 'down' 101 102 if ('error' in response): 103 name = '' 104 retString = response['error'] 105 else: 106 name = response['name'] 107 response = doRequest('device/command', {'id': deviceId, 'method': methodId, 'value': methodValue}) 108 if ('error' in response): 109 retString = response['error'] 110 else: 111 retString = response['status'] 112 113 if (methodId in (TELLSTICK_TURNON, TELLSTICK_TURNOFF)): 114 print("Turning %s device %s, %s - %s" % ( method, deviceId, name, retString)); 115 elif (methodId in (TELLSTICK_BELL, TELLSTICK_UP, TELLSTICK_DOWN)): 116 print("Sending %s to: %s %s - %s" % (method, deviceId, name, retString)) 117 elif (methodId == TELLSTICK_DIM): 118 print("Dimming device: %s %s to %s - %s" % (deviceId, name, methodValue, retString)) 119 120 121 def doRequest(method, params): 122 global config 123 consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY) 124 token = oauth.OAuthToken(config['token'], config['tokenSecret']) 125 126 oauth_request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET', http_url="http://api.telldus.com/json/" + method, parameters=params) 127 oauth_request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token) 128 headers = oauth_request.to_header() 129 headers['Content-Type'] = 'application/x-www-form-urlencoded' 130 131 conn = httplib.HTTPConnection("api.telldus.com:80") 132 conn.request('GET', "/json/" + method + "?" + urllib.urlencode(params, True).replace('+', '%20'), headers=headers) 133 134 response = conn.getresponse() 135 return json.load(response) 136 137 def requestToken(): 138 global config 139 consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY) 140 request = oauth.OAuthRequest.from_consumer_and_token(consumer, http_url='http://api.telldus.com/oauth/requestToken') 141 request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, None) 142 conn = httplib.HTTPConnection('api.telldus.com:80') 143 conn.request(request.http_method, '/oauth/requestToken', headers=request.to_header()) 144 145 resp = conn.getresponse().read() 146 token = oauth.OAuthToken.from_string(resp) 147 print 'Open the following url in your webbrowser:\nhttp://api.telldus.com/oauth/authorize?oauth_token=%s\n' % token.key 148 print 'After logging in and accepting to use this application run:\n%s --authenticate' % (sys.argv[0]) 149 config['requestToken'] = str(token.key) 150 config['requestTokenSecret'] = str(token.secret) 151 saveConfig() 152 153 def getAccessToken(): 154 global config 155 consumer = oauth.OAuthConsumer(PUBLIC_KEY, PRIVATE_KEY) 156 token = oauth.OAuthToken(config['requestToken'], config['requestTokenSecret']) 157 request = oauth.OAuthRequest.from_consumer_and_token(consumer, token=token, http_method='GET', http_url='http://api.telldus.com/oauth/accessToken') 158 request.sign_request(oauth.OAuthSignatureMethod_HMAC_SHA1(), consumer, token) 159 conn = httplib.HTTPConnection('api.telldus.com:80') 160 conn.request(request.http_method, request.to_url(), headers=request.to_header()) 161 162 resp = conn.getresponse() 163 if resp.status != 200: 164 print 'Error retreiving access token, the server replied:\n%s' % resp.read() 165 return 166 token = oauth.OAuthToken.from_string(resp.read()) 167 config['requestToken'] = None 168 config['requestTokenSecret'] = None 169 config['token'] = str(token.key) 170 config['tokenSecret'] = str(token.secret) 171 print 'Authentication successful, you can now use tdtool' 172 saveConfig() 173 174 def authenticate(): 175 try: 176 opts, args = getopt.getopt(sys.argv[1:], '', ['authenticate']) 177 for opt, arg in opts: 178 if opt in ('--authenticate'): 179 getAccessToken() 180 return 181 except getopt.GetoptError: 182 pass 183 requestToken() 184 185 def saveConfig(): 186 global config 187 try: 188 os.makedirs(os.environ['HOME'] + '/.config/Telldus') 189 except: 190 pass 191 config.write() 192 193 def main(argv): 194 global config 195 if ('token' not in config or config['token'] == ''): 196 authenticate() 197 return 198 try: 199 opts, args = getopt.getopt(argv, "ln:f:d:b:v:h", ["list", "on=", "off=", "dim=", "bell=", "dimlevel=", "up=", "down=", "help"]) 200 except getopt.GetoptError: 201 printUsage() 202 sys.exit(2) 203 204 dimlevel = -1 205 206 for opt, arg in opts: 207 if opt in ("-h", "--help"): 208 printUsage() 209 210 elif opt in ("-l", "--list"): 211 listDevices() 212 213 elif opt in ("-n", "--on"): 214 doMethod(arg, TELLSTICK_TURNON) 215 216 elif opt in ("-f", "--off"): 217 doMethod(arg, TELLSTICK_TURNOFF) 218 219 elif opt in ("-b", "--bell"): 220 doMethod(arg, TELLSTICK_BELL) 221 222 elif opt in ("-d", "--dim"): 223 if (dimlevel < 0): 224 print("Dimlevel must be set with --dimlevel before --dim") 225 else: 226 doMethod(arg, TELLSTICK_DIM, dimlevel) 227 228 elif opt in ("-v", "--dimlevel"): 229 dimlevel = arg 230 231 elif opt in ("--up"): 232 doMethod(arg, TELLSTICK_UP) 233 234 elif opt in ("--down"): 235 doMethod(arg, TELLSTICK_DOWN) 236 237 if __name__ == "__main__": 238 config = ConfigObj(os.environ['HOME'] + '/.config/Telldus/tdtool.conf') 239 main(sys.argv[1:])
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question