Skip to content

Commit

Permalink
Add logging
Browse files Browse the repository at this point in the history
  • Loading branch information
pfink committed Dec 25, 2017
1 parent 6bfbbef commit 9762a20
Show file tree
Hide file tree
Showing 8 changed files with 50 additions and 32 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ A short button click sends a TOGGLE command to switches while the wheel will con
- [ ] Add support for `Setpoint`s
- [ ] Add support for the FLY_UPDOWN gesture
- [ ] Add more alternative key mapping examples and introduction video for the recommended key mapping
- [ ] Logging
- [x] Logging
- [x] Support icon sets
- [x] Nuimo should be bound on a sitemap instead to the *Nuimo* group item. This will make the configuration more flexible and robust.
- [x] It should be possible to "jump into" a group so that you can navigate with the Nuimo similar to other UIs
- [ ] Improve stability & robustness
- [x] Improve stability & robustness
4 changes: 4 additions & 0 deletions config.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ nuimo_mac_address: "96:EC:C6:4D:05:BA"
bluetooth_adapter: hci0
rotation_icon: circle

log_file: "nuimo-openhab.log"
log_level: INFO
log_stdout: true

# The key mapping in this example file contains 2 modes:
# - the default mode which is used to control the currently the selected app / item
# - the menue mode which allows to select other apps / items
Expand Down
9 changes: 5 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ def __init__(self, main):
self.main = main
def controller_discovered(self, controller):
self.main.controller = controller
print("Discovered Nuimo controller:", controller.mac_address)
logging.info("Discovered Nuimo controller: %s", controller.mac_address)
if (controller.mac_address == str(config["nuimo_mac_address"]).lower()):
print("Found configured Nuimo with MAC address " + config["nuimo_mac_address"])
logging.info("Found configured Nuimo with MAC address " + config["nuimo_mac_address"])
# Initialize App
menue = NuimoMenue(apps=apps, controller=controller)
controller.listener = NuimoMenueControllerListener(menue)
controller.connect()
menue.showIcon()
else:
print("Discovered Nuimo " + controller.mac_address + " does not match with configured " + config[
logging.info("Discovered Nuimo " + controller.mac_address + " does not match with configured " + config[
"nuimo_mac_address"] + ". Continue discovery...")

manager.listener = ControllerManagerDiscoveryListener(self)
Expand All @@ -45,8 +45,9 @@ def controller_discovered(self, controller):

def exit_gracefully(self):
if hasattr(self, 'controller'):
print('Disconnecting...')
logging.info('Disconnecting...')
self.controller.disconnect()
logging.shutdown()
sys.exit(0)


Expand Down
21 changes: 11 additions & 10 deletions nuimo_menue/listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
from nuimo_menue.model import NuimoMenue
from nuimo_openhab.util import config
from util.button import *
import logging


class NuimoMenueControllerListener(nuimo.ControllerListener):
Expand Down Expand Up @@ -34,8 +35,8 @@ def handle_gesture_event(self, event):
if mappedCommands:
mappedCommand = mappedCommands[0]

print("Current Mode: " + str(self.nuimoMenue.currentMode))
print("Mapped Command: " + str(mappedCommand))
logging.debug("Current Mode: " + str(self.nuimoMenue.currentMode))
logging.debug("Mapped Command: " + str(mappedCommand))

if "CHANGEMODE" in mappedCommand:
self.nuimoMenue.currentMode = mappedCommand.split("=")[1]
Expand All @@ -48,7 +49,7 @@ def handle_gesture_event(self, event):
elif mappedCommand == "PREVIOUS":
self.nuimoMenue.navigateToPreviousApp()
elif mappedCommand == "SHOWAPP":
print("Name: "+self.nuimoMenue.getCurrentApp().getName())
logging.debug("Name: "+self.nuimoMenue.getCurrentApp().getName())
self.nuimoMenue.showIcon()
elif mappedCommand == "WHEELNAVIGATION":
self.wheelNavigation(event)
Expand All @@ -68,8 +69,8 @@ def show_command_icon(self, fqCommand: str):
if config["command_icon_mapping"][fqCommand] in icons:
icon = icons[config["command_icon_mapping"][fqCommand]]
self.nuimoMenue.controller.display_matrix(nuimo.LedMatrix(icon))
else: raise RuntimeWarning("Icon '"+config["command_icon_mapping"][fqCommand]+"' mapped to command '"+fqCommand+"' does not exist")
else: raise RuntimeWarning("No icon mapped to'"+fqCommand+"'")
else: logging.warning("Icon '"+config["command_icon_mapping"][fqCommand]+"' mapped to command '"+fqCommand+"' does not exist")
else: logging.warning("No icon mapped to'"+fqCommand+"'")
#if event.gesture == ButtonEvents.BUTTON_CLICK:
# "play"]))
#if event.gesture == nuimo.Gesture.TOUCH_BOTTOM:
Expand All @@ -81,22 +82,22 @@ def show_command_icon(self, fqCommand: str):


def started_connecting(self):
print("Connecting...")
logging.info("Connecting...")

def connect_succeeded(self):
self.connected = True
print("Connecting succeeded!")
logging.info("Connecting succeeded!")

def connect_failed(self, error):
print("Connecting failed!")
logging.info("Connecting failed!")

def started_disconnecting(self):
print("Disconnecting...")
logging.info("Disconnecting...")

def disconnect_succeeded(self):
self.connected = False
self.attempt_reconnect()
print("Nuimo disconnected!")
logging.info("Nuimo disconnected!")

def attempt_reconnect(self):
while (not self.connected):
Expand Down
4 changes: 2 additions & 2 deletions nuimo_menue/model.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import nuimo

import logging

class AppListener(nuimo.ControllerListener):
def __init__(self, app):
Expand All @@ -8,7 +8,7 @@ def __init__(self, app):

class App:
def __init__(self, name, icon: nuimo.LedMatrix, appListener: AppListener, parent = None):
print("Create app: " + name + "(parent: "+ str(parent)+ ")")
logging.info("Create app: " + name + "(parent: "+ str(parent)+ ")")
self.appListener = appListener
self.icon = icon
self.name = name
Expand Down
15 changes: 8 additions & 7 deletions nuimo_openhab/listener.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import sys
import logging
import time

import nuimo
Expand Down Expand Up @@ -41,7 +42,7 @@ def handleCommonGesture(self, event):
for widget in self.widgets:
namespace = "OPENHAB." + widget["type"]
mappedCommands = config.get_mapped_commands(gesture=event.gesture, namespace=namespace)
print("Mapped command openHAB: " + str(mappedCommands) + "(requested namespace: "+namespace+")")
logging.debug("Mapped command openHAB: " + str(mappedCommands) + "(requested namespace: "+namespace+")")

for command in mappedCommands:

Expand All @@ -66,7 +67,7 @@ def handleCommonGesture(self, event):
if state in config["toggle_mapping"]:
command = config["toggle_mapping"][state]
else:
raise RuntimeWarning("There is no toggle counterpart known for state '"+state+"'. Skip TOGGLE command.")
logging.warning("There is no toggle counterpart known for state '"+state+"'. Skip TOGGLE command.")

if not noMappingFound:
self.openhab.req_post("/items/" + widget["item"]["name"], command)
Expand All @@ -81,7 +82,7 @@ def handleRotation(self, event):
self.reminder += valueChange
if (abs(self.reminder) >= 1):
self.openhab.req_post("/items/" + widget["item"]["name"], "REFRESH")
print(self.openhab.base_url + widget["item"]["name"] + "/state")
logging.debug(self.openhab.base_url + widget["item"]["name"] + "/state")
try:
currentTimestamp = int(round(time.time() * 1000))
if (self.lastDimmerItemTimestamp < currentTimestamp-3000):
Expand All @@ -92,25 +93,25 @@ def handleRotation(self, event):
if (currentState < 1):
currentState *= 100
currentState = int(currentState)
print("Raw item state: "+itemStateRaw)
logging.debug("Raw item state: "+itemStateRaw)
else:
currentState = self.lastDimmerItemState
print("Old state: " + str(currentState))
logging.debug("Old state: " + str(currentState))
newState = currentState+round(self.reminder)
if (newState < 0):
newState = 0
if (newState > 100):
newState = 100

print("New state: " + str(newState))
logging.debug("New state: " + str(newState))

self.lastDimmerItemState = newState
self.lastDimmerItemTimestamp = currentTimestamp

self.openhab.req_post("/items/" + widget["item"]["name"], str(newState))
except Exception:
newState = 0
print(sys.exc_info())
logging.error(sys.exc_info())
finally:
self.reminder = 0
return self.lastDimmerItemState
12 changes: 11 additions & 1 deletion nuimo_openhab/util/config.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import sys
import logging
from nuimo_menue.config import NuimoMenueConfiguration
import yaml

Expand All @@ -18,5 +19,14 @@ def __getitem__(self, item):

with open(NUIMO_OPENHAB_CONFIG_PATH, 'r') as ymlfile:
rawConfig = yaml.safe_load(ymlfile)
print(rawConfig)

loggers = []
if rawConfig["log_file"]: loggers.append(logging.FileHandler(filename=rawConfig["log_file"]))
if rawConfig["log_stdout"]: loggers.append(logging.StreamHandler(stream=sys.stdout))
formatter = logging.Formatter('%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',
"%Y-%m-%d %H:%M:%S")
for logger in loggers: logger.setFormatter(formatter)
if loggers: logging.basicConfig(handlers=loggers, level=rawConfig["log_level"])

logging.info("Loaded config file from "+ NUIMO_OPENHAB_CONFIG_PATH)
sys.modules[__name__] = NuimoOpenHabConfiguration(rawConfig)
13 changes: 7 additions & 6 deletions nuimo_openhab/util/printing_controller_listener.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import nuimo
import logging

class PrintingControllerListener(nuimo.ControllerListener):
def received_gesture_event(self, event):
if isinstance(event, nuimo.GestureEvent):
print(event.value)
logging.info("Received gesture: %s", event.value)

def started_connecting(self):
print("Connecting...")
logging.info("Connecting...")

def connect_succeeded(self):
print("Connecting succeeded!")
logging.info("Connecting succeeded!")

def connect_failed(self, error):
print("Connecting failed!")
logging.info("Connecting failed!")

def started_disconnecting(self):
print("Disconnecting...")
logging.info("Disconnecting...")

def disconnect_succeeded(self):
print("Nuimo disconnected!")
logging.info("Nuimo disconnected!")

0 comments on commit 9762a20

Please sign in to comment.