Made code pep8 compliant once again

pull/3/head
Alve Svarén 5 years ago
parent ef7d48d29e
commit c0ad5ce2d7
  1. 2
      hue_cmd.py
  2. 1
      modules/configloader/__init__.py
  3. 1
      modules/configloader/loader.py
  4. 91
      modules/hue/hue_controller.py
  5. 75
      modules/hue/hue_remote.py
  6. 9
      modules/hue/lib/func.py
  7. 22
      modules/speech/speech.py
  8. 10
      speech_daemon.py

@ -3,10 +3,12 @@
from modules.hue.hue_controller import controller from modules.hue.hue_controller import controller
from modules.hue.hue_remote import parseCommandline from modules.hue.hue_remote import parseCommandline
def init(): def init():
controller.init() # very important to initialize the controller controller.init() # very important to initialize the controller
parseCommandline() parseCommandline()
controller.end() # also to end it controller.end() # also to end it
if __name__ == "__main__": if __name__ == "__main__":
init() init()

@ -1,5 +1,6 @@
import json import json
def readconfig(path): def readconfig(path):
try: try:
with open(path) as cfg: with open(path) as cfg:

@ -17,16 +17,18 @@ PRE_URL = "" # prefix
loop = asyncio.get_event_loop() # ASync loop loop = asyncio.get_event_loop() # ASync loop
def genUrl(params: str): def genUrl(params: str):
return PRE_URL + params return PRE_URL + params
class APIrequest: class APIrequest:
# Get Req # Get Req
async def get( dest: str="", payload: str="" ): async def get(dest: str = "", payload: str = ""):
try: try:
apiReq = req.get( genUrl(dest), data = payload ) apiReq = req.get(genUrl(dest), data=payload)
if( apiReq.status_code != 200 ): # print out the error if the status code is not 200 if(apiReq.status_code != 200): # print out the error if the status code is not 200
print(apiReq) print(apiReq)
print(apiReq.text) print(apiReq.text)
@ -36,11 +38,11 @@ class APIrequest:
print(err) print(err)
# PUT Req # PUT Req
async def put( dest: str="", payload: str="" ): async def put(dest: str = "", payload: str = ""):
try: try:
apiReq = req.put( genUrl(dest), data = payload ) # send the payload apiReq = req.put(genUrl(dest), data=payload) # send the payload
if( apiReq.status_code != 200 ): if(apiReq.status_code != 200):
print(apiReq) print(apiReq)
print(apiReq.text) print(apiReq.text)
@ -56,30 +58,32 @@ class controller:
async def getLights(): async def getLights():
return await APIrequest.get("/lights") return await APIrequest.get("/lights")
async def getLight(index: int=1): async def getLight(index: int = 1):
return await APIrequest.get( "/lights/" + str(index) ) return await APIrequest.get("/lights/" + str(index))
# Lower level light manipulation (async) # Lower level light manipulation (async)
async def toggleLight(index: int=1, isOn: bool=True): async def toggleLight(index: int = 1, isOn: bool = True):
await APIrequest.put( "/lights/" + str(index) + "/state", '{"on":' + boolToString(isOn) + '}' ) await APIrequest.put("/lights/" + str(index) + "/state", '{"on":' + boolToString(isOn) + '}')
async def toggleLights(isOn: bool=True): async def toggleLights(isOn: bool = True):
for key in LIGHTS: for key in LIGHTS:
await controller.toggleLight(key, isOn) await controller.toggleLight(key, isOn)
async def setLightRGB( index: int, r:int, g:int, b:int ): async def setLightRGB(index: int, r: int, g: int, b: int):
h, s, v = rgbToHsv(r, g, b) h, s, v = rgbToHsv(r, g, b)
payload = '{"sat":' + str(s) + ', "bri":' + str(v) + ', "hue":' + str(h) + '}' payload = '{"sat":' + str(s) + ', "bri":' + \
str(v) + ', "hue":' + str(h) + '}'
await APIrequest.put( "/lights/" + str(index) + "/state", payload ) await APIrequest.put("/lights/" + str(index) + "/state", payload)
# Normal functions # Normal functions
def switchLight( index: int=1 ): def switchLight(index: int = 1):
key = LIGHTS.get(str(index)) key = LIGHTS.get(str(index))
if(key): if(key):
if( key.get("state") ): if(key.get("state")):
curPower = LIGHTS[str(index)]["state"]["on"] curPower = LIGHTS[str(index)]["state"]["on"]
loop.run_until_complete( controller.toggleLight(index, not curPower)) loop.run_until_complete(
controller.toggleLight(index, not curPower))
else: else:
print("Error: Light index '" + str(index) + "' out of range") print("Error: Light index '" + str(index) + "' out of range")
@ -88,55 +92,56 @@ class controller:
controller.switchLight(key) controller.switchLight(key)
# Light control # Light control
def setLightColor( index:int, r:int, g:int, b:int ): def setLightColor(index: int, r: int, g: int, b: int):
if( LIGHTS.get(str(index)) ): if(LIGHTS.get(str(index))):
loop.run_until_complete( controller.setLightRGB(index, r, g, b) ) loop.run_until_complete(controller.setLightRGB(index, r, g, b))
else: else:
print("Error: Light index '" + str(index) + "' out of range") print("Error: Light index '" + str(index) + "' out of range")
def setLightBrightness( index:int, b:int ): def setLightBrightness(index: int, b: int):
if( LIGHTS.get(str(index)) ): if(LIGHTS.get(str(index))):
payload = '{"bri":' + str(b) + '}' payload = '{"bri":' + str(b) + '}'
loop.run_until_complete( APIrequest.put( "/lights/" + str(index) + "/state", payload ) ) loop.run_until_complete(APIrequest.put(
"/lights/" + str(index) + "/state", payload))
else: else:
print("Error: Light index '" + str(index) + "' out of range") print("Error: Light index '" + str(index) + "' out of range")
def setBrightness( b:int ): def setBrightness(b: int):
for key in LIGHTS: for key in LIGHTS:
controller.setLightBrightness( key, b ) controller.setLightBrightness(key, b)
def setAllLightsColor( r:int, g:int, b:int ): def setAllLightsColor(r: int, g: int, b: int):
for key in LIGHTS: for key in LIGHTS:
controller.setLightColor( key, r, g, b ) controller.setLightColor(key, r, g, b)
def Power(isOn:bool=True): # Controlling the power of the lights def Power(isOn: bool = True): # Controlling the power of the lights
loop.run_until_complete( controller.toggleLights(isOn) ) loop.run_until_complete(controller.toggleLights(isOn))
def powerLight( index:int, isOn:bool=True ): def powerLight(index: int, isOn: bool = True):
loop.run_until_complete( controller.toggleLight( index, isOn ) ) loop.run_until_complete(controller.toggleLight(index, isOn))
# Presets # Presets
def setLightPreset( index:int, p:str ): def setLightPreset(index: int, p: str):
if( LIGHTS.get(str(index)) ): if(LIGHTS.get(str(index))):
if( PRESETS.get(p) ): if(PRESETS.get(p)):
preset = PRESETS[p] preset = PRESETS[p]
r, g, b = preset["color"] r, g, b = preset["color"]
brightness = preset["brightness"] brightness = preset["brightness"]
controller.setLightColor( index, r, g, b ) controller.setLightColor(index, r, g, b)
controller.setLightBrightness( index, brightness ) controller.setLightBrightness(index, brightness)
else: else:
print("Error: Unknown preset '" + p + "'") print("Error: Unknown preset '" + p + "'")
else: else:
print("Error: Light index '" + str(index) + "' out of range") print("Error: Light index '" + str(index) + "' out of range")
def setPreset( presetID:str, index:int=-1 ): def setPreset(presetID: str, index: int = -1):
if( PRESETS.get(presetID) ): if(PRESETS.get(presetID)):
if( index == -1 ): if(index == -1):
for key in LIGHTS: for key in LIGHTS:
controller.setLightPreset( key, presetID ) controller.setLightPreset(key, presetID)
else: else:
controller.setLightPreset( index, presetID ) controller.setLightPreset(index, presetID)
else: else:
print("Error: Unknown preset '" + presetID + "'") print("Error: Unknown preset '" + presetID + "'")
@ -144,10 +149,10 @@ class controller:
return len(LIGHTS) return len(LIGHTS)
# Controller "system" functions # Controller "system" functions
def delay(n:int): def delay(n: int):
time.sleep(n) time.sleep(n)
def init( cfgPath="{0}/.config/roomcomputer/config.json".format(homedir), presetPath="{0}/.config/roomcomputer/presets.json".format(homedir) ): def init(cfgPath="{0}/.config/roomcomputer/config.json".format(homedir), presetPath="{0}/.config/roomcomputer/presets.json".format(homedir)):
config = readconfig(cfgPath) config = readconfig(cfgPath)
presets = readconfig(presetPath) presets = readconfig(presetPath)

@ -7,23 +7,26 @@ from modules.hue import hue_controller as hue # Actual controller
cmd = "hue" cmd = "hue"
def help(): def help():
print("--Help page--") print("--Help page--")
print( "'" + cmd + "' : Display this help page" ) print("'" + cmd + "' : Display this help page")
print( "'" + cmd + " light (index)' ... : Specify light target, from 1-" + str(hue.controller.countLights()) ) print("'" + cmd + " light (index)' ... : Specify light target, from 1-" +
print( "'" + cmd + " lights' ... : Specify all lights\n" ) str(hue.controller.countLights()))
print("'" + cmd + " lights' ... : Specify all lights\n")
print("--Commands--") print("--Commands--")
print( "'on'/'off' : Turn light(s) on/off" ) print("'on'/'off' : Turn light(s) on/off")
print( "'switch' : Switch the light(s) power" ) print("'switch' : Switch the light(s) power")
print( "'set ...'" ) print("'set ...'")
print( " 'preset (preset ID)' : Set the preset (from presets.py)" ) print(" 'preset (preset ID)' : Set the preset (from presets.py)")
print( " 'color (red) (green) (blue)' : Set the color, from 0-255" ) print(" 'color (red) (green) (blue)' : Set the color, from 0-255")
print( " 'brightness (brightness)' : Set the brightness, from 0-255" ) print(" 'brightness (brightness)' : Set the brightness, from 0-255")
print("\nExamples:\n'hue light 2 on' : Turn on light 2\n'hue lights set color 255 255 255' : Set all lights colors to white") print("\nExamples:\n'hue light 2 on' : Turn on light 2\n'hue lights set color 255 255 255' : Set all lights colors to white")
boolConvert = { boolConvert = {
"on": True, "on": True,
"off": False "off": False
@ -31,17 +34,18 @@ boolConvert = {
# this is the most spaghetti-ish code I have ever written but it works # this is the most spaghetti-ish code I have ever written but it works
def parseCommand( cmd:list, pos:int, index=-1, displayHelp=True ):
def parseCommand(cmd: list, pos: int, index=-1, displayHelp=True):
try: try:
if( cmd[pos] == "on" or cmd[pos] == "off" ): if(cmd[pos] == "on" or cmd[pos] == "off"):
if( index == -1 ): if(index == -1):
hue.controller.Power( boolConvert[cmd[pos]] ) hue.controller.Power(boolConvert[cmd[pos]])
else: else:
hue.controller.powerLight( index, boolConvert[cmd[pos]] ) hue.controller.powerLight(index, boolConvert[cmd[pos]])
return return
elif( cmd[pos] == "switch" ): elif(cmd[pos] == "switch"):
if(index == -1): if(index == -1):
hue.controller.switchLights() hue.controller.switchLights()
else: else:
@ -49,33 +53,34 @@ def parseCommand( cmd:list, pos:int, index=-1, displayHelp=True ):
return return
elif( cmd[pos] == "set" ): elif(cmd[pos] == "set"):
if( cmd[pos+1] == "preset" ): if(cmd[pos+1] == "preset"):
hue.controller.setPreset( cmd[pos+2], index ) hue.controller.setPreset(cmd[pos+2], index)
return return
elif( cmd[pos+1] == "color" ): elif(cmd[pos+1] == "color"):
if( len(cmd) > pos+4 ): if(len(cmd) > pos+4):
r, g, b = int(cmd[pos+2]), int(cmd[pos+3]), int(cmd[pos+4]) r, g, b = int(cmd[pos+2]), int(cmd[pos+3]), int(cmd[pos+4])
if( index == -1 ): if(index == -1):
hue.controller.setAllLightsColor( r, g, b ) # this code is bad hue.controller.setAllLightsColor(
r, g, b) # this code is bad
else: else:
hue.controller.setLightColor( index, r, g, b ) hue.controller.setLightColor(index, r, g, b)
return return
else: else:
print("Error: Missing parameters") print("Error: Missing parameters")
help() help()
elif( cmd[pos+1] == "brightness" ): elif(cmd[pos+1] == "brightness"):
if( len(cmd) > pos+2 ): if(len(cmd) > pos+2):
bri = int(cmd[pos+2]) bri = int(cmd[pos+2])
if( index == -1 ): if(index == -1):
hue.controller.setBrightness(bri) hue.controller.setBrightness(bri)
else: else:
hue.controller.setLightBrightness( index, bri ) hue.controller.setLightBrightness(index, bri)
return return
help() # display help if function did nothing help() # display help if function did nothing
@ -84,15 +89,15 @@ def parseCommand( cmd:list, pos:int, index=-1, displayHelp=True ):
if(displayHelp): if(displayHelp):
help() # display the help page if parameters are missing (it will give out an IndexError) help() # display the help page if parameters are missing (it will give out an IndexError)
print( "\n\nError: " + str(err) ) print("\n\nError: " + str(err))
def parseCommandline( cmd=sys.argv, needHelp=True ): def parseCommandline(cmd=sys.argv, needHelp=True):
if( len(cmd) > 1 ): if(len(cmd) > 1):
if( cmd[1] == "light" ): if(cmd[1] == "light"):
parseCommand( cmd, 3, cmd[2], displayHelp=needHelp ) parseCommand(cmd, 3, cmd[2], displayHelp=needHelp)
elif( cmd[1] == "lights" ): elif(cmd[1] == "lights"):
parseCommand( cmd, 2, displayHelp=needHelp ) parseCommand(cmd, 2, displayHelp=needHelp)
elif( needHelp ): elif(needHelp):
help() help()

@ -5,19 +5,24 @@ boolStr = {
False: "false" False: "false"
} }
def boolToString(v: bool): # To fix the dumb python syntax def boolToString(v: bool): # To fix the dumb python syntax
return boolStr[v] return boolStr[v]
def rgbToDecimal( r:int, g:int, b:int ):
def rgbToDecimal(r: int, g: int, b: int):
return round(r/255, 1), round(g/255, 1), round(b/255, 1) return round(r/255, 1), round(g/255, 1), round(b/255, 1)
def svNumFix(n: float): def svNumFix(n: float):
return int(round(n*254, 0)) return int(round(n*254, 0))
def hueNumFix(n: float): def hueNumFix(n: float):
return int(round(n*65535, 0)) return int(round(n*65535, 0))
def rgbToHsv( r:int, g:int, b:int ):
def rgbToHsv(r: int, g: int, b: int):
R, G, B = rgbToDecimal(r, g, b) R, G, B = rgbToDecimal(r, g, b)
H, S, V = colorsys.rgb_to_hsv(R, G, B) H, S, V = colorsys.rgb_to_hsv(R, G, B)
return hueNumFix(H), svNumFix(S), svNumFix(V) return hueNumFix(H), svNumFix(S), svNumFix(V)

@ -1,5 +1,6 @@
import speech_recognition as sr import speech_recognition as sr
class voiceInput(object): class voiceInput(object):
recognizer = sr.Recognizer() recognizer = sr.Recognizer()
@ -9,14 +10,15 @@ class voiceInput(object):
what = "??" what = "??"
error = "ERROR" error = "ERROR"
def start( self, deviceIndex=30 ): # a generator for everything that is said def start(self, deviceIndex=30): # a generator for everything that is said
while( True ): # loop while(True): # loop
try: try:
if( not self.muted ): # this thing is not the NSA if(not self.muted): # this thing is not the NSA
with sr.Microphone( deviceIndex ) as src: with sr.Microphone(deviceIndex) as src:
self.recognizer.adjust_for_ambient_noise( src, 0.2 ) self.recognizer.adjust_for_ambient_noise(src, 0.2)
print("Listening...") print("Listening...")
audio = self.recognizer.listen( src, phrase_time_limit=5 ) audio = self.recognizer.listen(
src, phrase_time_limit=5)
print("Thinking...") print("Thinking...")
text = self.recognizer.recognize_google(audio) text = self.recognizer.recognize_google(audio)
yield text yield text
@ -28,10 +30,8 @@ class voiceInput(object):
except sr.UnknownValueError: except sr.UnknownValueError:
yield self.what yield self.what
def setMuted(self, setm: bool = True):
def setMuted( self, setm: bool=True ):
self.muted = setm self.muted = setm
def switchMute( self ): def switchMute(self):
self.setMuted( not self.muted ) self.setMuted(not self.muted)

@ -13,6 +13,7 @@ homedir = expanduser("~")
CONFIG = {} CONFIG = {}
class speech_daemon(object): class speech_daemon(object):
voiceInpObj = None voiceInpObj = None
deviceIndex = 30 deviceIndex = 30
@ -28,7 +29,7 @@ class speech_daemon(object):
# if no config path is # if no config path is
# specified then choose the users default # specified then choose the users default
if( len(sys.argv) > 1 ): if(len(sys.argv) > 1):
path = sys.argv[1] path = sys.argv[1]
cfg = readconfig(path) # read the config cfg = readconfig(path) # read the config
@ -39,14 +40,15 @@ class speech_daemon(object):
def start(self): def start(self):
controller.init() controller.init()
for inp in self.voiceInpObj.start( self.deviceIndex ): for inp in self.voiceInpObj.start(self.deviceIndex):
cmdBuf = inp.lower().split(" ") cmdBuf = inp.lower().split(" ")
if( cmdBuf[0] in CONFIG["speech"]["prefixes"] ): if(cmdBuf[0] in CONFIG["speech"]["prefixes"]):
print("CMD:", cmdBuf) print("CMD:", cmdBuf)
parseCommandline( cmdBuf, False ) parseCommandline(cmdBuf, False)
controller.end() controller.end()
if __name__ == "__main__": if __name__ == "__main__":
daemon = speech_daemon() daemon = speech_daemon()
daemon.loadconfig() daemon.loadconfig()

Loading…
Cancel
Save