Skip to content

Commit

Permalink
Fixing linting errors
Browse files Browse the repository at this point in the history
  • Loading branch information
jeroenterheerdt committed Oct 22, 2018
1 parent 7c62cd2 commit d214790
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 31 deletions.
51 changes: 35 additions & 16 deletions neatoserial.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import time
import RPi.GPIO as GPIO


class NeatoSerial:
"""Serial interface to Neato."""

Expand All @@ -31,7 +32,8 @@ def connect(self):
print("Connected to Neato at "+dev)
return
except:
print("Could not connect to device "+dev+". Trying next device.")
print("Could not connect to device "+dev+". "
+ "Trying next device.")

def open(self):
"""Open serial port and flush the input."""
Expand Down Expand Up @@ -59,10 +61,26 @@ def read_all(self, port, chunk_size=200):
break
return read_buffer

def toggleusb(self):
"""Toggle USB connection to Neato."""
if settings['serial']['usb_switch_mode'] == 'direct':
print("Direct connection specified.")
# disable and re-enable usb ports to trigger clean
os.system('sudo ./hub-ctrl -h 0 -P 2 -p 0 ; sleep 1; '
+ 'sudo ./hub-ctrl -h 0 -P 2 -p 1 ')
elif settings['serial']['usb_switch_mode'] == 'relay':
print("Relay connection specified")
# use relay to temporarily disconnect neato to trigger clean
GPIO.output(self.pin, GPIO.LOW)
time.sleep(1)
GPIO.output(self.pin, GPIO.HIGH)
if settings['serial']['reboot_after_usb_switch']:
os.system('sudo reboot')

def write(self, msg):
"""Write message to serial and return output."""
print("Message received for writing: "+msg)
print("Sending wake-up message" )
print("Sending wake-up message")
# wake up neato by sending something random
self.ser.write("wake-up\n".encode('utf-8'))
time.sleep(1)
Expand All @@ -77,20 +95,9 @@ def write(self, msg):
if msg == "Clean":
# toggle usb
print("Message was 'Clean' so toggling USB")
if settings['serial']['usb_switch_mode'] == 'direct':
print("Direct connection specified.")
# disable and re-enable usb ports to trigger clean
os.system('sudo ./hub-ctrl -h 0 -P 2 -p 0 ; sleep 1; '
+ 'sudo ./hub-ctrl -h 0 -P 2 -p 1 ')
elif settings['serial']['usb_switch_mode'] == 'relay':
print("Relay connection specified")
# use relay to temporarily disconnect neato to trigger clean
GPIO.output(self.pin, GPIO.LOW)
time.sleep(1)
GPIO.output(self.pin, GPIO.HIGH)
if settings['serial']['reboot_after_usb_switch']:
os.system('sudo reboot')
#the device might have changed with the usb toggle, so let's close and reconnect
self.toggleusb()
# the device might have changed with the usb toggle,
# so let's close and reconnect
print("Reconnecting to Neato")
time.sleep(5)
self.close()
Expand All @@ -106,6 +113,18 @@ def write(self, msg):
if out != '':
return out

def getError(self):
"""Return error message if available."""
output = self.write("GetErr")
if output is not None:
outputsplit = output.split('\r\n')
if len(outputsplit) == 3:
return outputsplit[1]
else:
return None
else:
return None

def getBatteryLevel(self):
"""Return battery level."""
return int(self.getCharger()["FuelPercent"])
Expand Down
29 changes: 23 additions & 6 deletions neatoserialmqtt.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@

"""MQTT interface for Neato Serial."""
from config import settings
import json
import time
import logging
from systemd.journal import JournalHandler
import paho.mqtt.client as mqtt
from neatoserial import NeatoSerial

Expand All @@ -15,18 +18,21 @@ def on_message(client, userdata, msg):
print("Feedback from device: "+feedback)


print("Starting")
log = logging.getLogger('NeatoSerialMQTT')
log.addHandler(JournalHandler())
log.setLevel(logging.INFO)
log.info("Starting")
client = mqtt.Client()
client.on_message = on_message
client.username_pw_set(settings['mqtt']['username'],
settings['mqtt']['password'])
print("Connecting")
log.info("Connecting")
client.connect(settings['mqtt']['host'], settings['mqtt']['port'])
client.subscribe(settings['mqtt']['command_topic'], qos=1)
print("Setting up serial")
log.info("Setting up serial")
ns = NeatoSerial()

print("Ready")
log.info("Ready")
client.loop_start()
while True:
try:
Expand All @@ -36,8 +42,19 @@ def on_message(client, userdata, msg):
data["cleaning"] = ns.getCleaning()
data["charging"] = ns.getChargingActive()
data["fan_speed"] = ns.getVacuumRPM()
error = ns.getError()
errorsplit = error.split(' - ')
log.info("Error from Neato: "+str(errorsplit))
if len(errorsplit) == 2:
# handle error 220 - which means we need to toggle the usb
# to trigger a clean
if int(errorsplit[0]) == 220:
ns.toggleusb()
data["error"] = errorsplit[1]
else:
data["error"] = error
json_data = json.dumps(data)
client.publish(settings['mqtt']['state_topic'], json_data)
time.sleep(settings['mqtt']['publish_wait_seconds'])
except:
print("Error getting status.")
except Exception as ex:
log.info("Error getting status: "+ex)
18 changes: 9 additions & 9 deletions relaytest.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
"""Simple test class for testing relay."""
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
pins = [2, 3, 4, 17]
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.HIGH)
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.HIGH)
print("All pins set to high")
while 1:
inp = input("Enter pin number (2,3,4 or 17) and high or low: ")
inpslit = inp.split(' ')
to = GPIO.HIGH
if inpslit[1] == 'low':
to = GPIO.LOW
GPIO.output(int(inpslit[0]),to)
inp = input("Enter pin number (2,3,4 or 17) and high or low: ")
inpslit = inp.split(' ')
to = GPIO.HIGH
if inpslit[1] == 'low':
to = GPIO.LOW
GPIO.output(int(inpslit[0]), to)

0 comments on commit d214790

Please sign in to comment.