Skip to content

Commit

Permalink
fix more flake8 issues
Browse files Browse the repository at this point in the history
  • Loading branch information
whoenig committed Oct 23, 2023
1 parent 24bc57b commit 92664ff
Show file tree
Hide file tree
Showing 8 changed files with 115 additions and 104 deletions.
2 changes: 1 addition & 1 deletion crazyflie_py/crazyflie_py/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
from .crazyswarm_py import Crazyswarm

__all__ = ["Crazyswarm"]
__all__ = ['Crazyswarm']
137 changes: 69 additions & 68 deletions crazyflie_py/crazyflie_py/crazyflie.py

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion crazyflie_py/crazyflie_py/crazyswarm_py.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import rclpy

from . import genericJoystick
from .crazyflie import TimeHelper, CrazyflieServer
from .crazyflie import CrazyflieServer, TimeHelper


class Crazyswarm:

def __init__(self):
rclpy.init()

Expand Down
10 changes: 6 additions & 4 deletions crazyflie_py/crazyflie_py/genericJoystick.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import copy
# import pyglet

from . import keyboard

# class JoyStickHandler:
Expand All @@ -21,6 +22,7 @@


class Joystick:

def __init__(self, timeHelper):
# joysticks = pyglet.input.get_joysticks()
# joystick = joysticks[0]
Expand All @@ -35,14 +37,14 @@ def __init__(self, timeHelper):
self.js = linuxjsdev.Joystick()
devices = self.js.devices()
if len(devices) == 0:
print("Warning: No joystick found!")
print('Warning: No joystick found!')
else:
ids = [dev["id"] for dev in devices]
ids = [dev['id'] for dev in devices]
# For backwards compatibility, always choose device 0 if available.
self.joyID = 0 if 0 in ids else devices[0]["id"]
self.joyID = 0 if 0 in ids else devices[0]['id']
self.js.open(self.joyID)
except ImportError:
print("Warning: Joystick only supported on Linux.")
print('Warning: Joystick only supported on Linux.')

# def on_joybutton_press(joystick, button):
# print(button)
Expand Down
4 changes: 3 additions & 1 deletion crazyflie_py/crazyflie_py/joystick.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import time

import rospy
from sensor_msgs.msg import Joy


class Joystick:

def __init__(self):
self.lastButtonState = 0
self.buttonWasPressed = False
rospy.Subscriber("/joy", Joy, self.joyChanged)
rospy.Subscriber('/joy', Joy, self.joyChanged)

def joyChanged(self, data):
if (not self.buttonWasPressed and
Expand Down
5 changes: 3 additions & 2 deletions crazyflie_py/crazyflie_py/keyboard.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import sys
import select
import sys
import termios


class KeyPoller():

def __enter__(self):
# Save the terminal settings
self.fd = sys.stdin.fileno()
Expand All @@ -16,7 +17,7 @@ def __enter__(self):

return self

def __exit__(self, type, value, traceback):
def __exit__(self, type, value, traceback): # noqa A002
termios.tcsetattr(self.fd, termios.TCSAFLUSH, self.old_term)

def poll(self):
Expand Down
46 changes: 23 additions & 23 deletions crazyflie_py/crazyflie_py/linuxjsdev.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,19 +37,19 @@
import sys

if not sys.platform.startswith('linux'):
raise ImportError("Only supported on Linux")
raise ImportError('Only supported on Linux')

try:
import fcntl
except ImportError as e:
raise Exception("fcntl library probably not installed ({})".format(e))
raise Exception('fcntl library probably not installed ({})'.format(e))

__author__ = 'Bitcraze AB'
__all__ = ['Joystick']

logger = logging.getLogger(__name__)

JS_EVENT_FMT = "@IhBB"
JS_EVENT_FMT = '@IhBB'
JE_TIME = 0
JE_VALUE = 1
JE_TYPE = 2
Expand All @@ -63,8 +63,8 @@
JSIOCGAXES = 0x80016a11
JSIOCGBUTTONS = 0x80016a12

MODULE_MAIN = "Joystick"
MODULE_NAME = "linuxjsdev"
MODULE_MAIN = 'Joystick'
MODULE_NAME = 'linuxjsdev'


class JEvent(object):
Expand All @@ -76,7 +76,7 @@ def __init__(self, evt_type, number, value):
self.value = value

def __repr__(self):
return "JEvent(type={}, number={}, value={})".format(
return 'JEvent(type={}, number={}, value={})'.format(
self.type, self.number, self.value)


Expand All @@ -90,44 +90,44 @@ class _JS():
def __init__(self, num, name):
self.num = num
self.name = name
self._f_name = "/dev/input/js{}".format(num)
self._f_name = '/dev/input/js{}'.format(num)
self._f = None

self.opened = False
self.buttons = []
self.axes = []
self._prev_pressed = {}

def open(self):
def open(self): # noqa: A003
if self._f:
raise Exception("{} at {} is already "
"opened".format(self.name, self._f_name))
raise Exception('{} at {} is already '
'opened'.format(self.name, self._f_name))

self._f = open("/dev/input/js{}".format(self.num), "rb")
self._f = open('/dev/input/js{}'.format(self.num), 'rb')
fcntl.fcntl(self._f.fileno(), fcntl.F_SETFL, os.O_NONBLOCK)

# Get number of axis and button
val = ctypes.c_int()
if fcntl.ioctl(self._f.fileno(), JSIOCGAXES, val) != 0:
self._f.close()
self._f = None
raise Exception("Failed to read number of axes")
raise Exception('Failed to read number of axes')

self.axes = list(0 for i in range(val.value))
self.axes = [0 for i in range(val.value)]
if fcntl.ioctl(self._f.fileno(), JSIOCGBUTTONS, val) != 0:
self._f.close()
self._f = None
raise Exception("Failed to read number of axes")
raise Exception('Failed to read number of axes')

self.buttons = list(0 for i in range(val.value))
self.buttons = [0 for i in range(val.value)]
self.__initvalues()

def close(self):
"""Open the joystick device."""
if not self._f:
return

logger.info("Closed {} ({})".format(self.name, self.num))
logger.info('Closed {} ({})'.format(self.name, self.num))

self._f.close()
self._f = None
Expand Down Expand Up @@ -170,7 +170,7 @@ def _read_all_events(self):
logger.info(str(e))
self._f.close()
self._f = None
raise IOError("Device has been disconnected")
raise IOError('Device has been disconnected')
except TypeError:
pass
except ValueError:
Expand All @@ -184,7 +184,7 @@ def _read_all_events(self):
def read(self):
"""Return a list of all joystick event since the last call."""
if not self._f:
raise Exception("Joystick device not opened")
raise Exception('Joystick device not opened')

self._read_all_events()

Expand All @@ -201,23 +201,23 @@ def __init__(self):

def devices(self):
"""
Return a list containing an {"id": id, "name": name} dict for each detected device.
Return a list containing an {'id': id, 'name': name} dict for each detected device.
Result is cached once one or more devices are found.
"""
if len(self._devices) == 0:
syspaths = glob.glob("/sys/class/input/js*")
syspaths = glob.glob('/sys/class/input/js*')

for path in syspaths:
device_id = int(os.path.basename(path)[2:])
with open(path + "/device/name") as namefile:
with open(path + '/device/name') as namefile:
name = namefile.read().strip()
self._js[device_id] = _JS(device_id, name)
self._devices.append({"id": device_id, "name": name})
self._devices.append({'id': device_id, 'name': name})

return self._devices

def open(self, device_id):
def open(self, device_id): # noqa: A003
"""Open the joystick device. The device_id is given by available_devices."""
self._js[device_id].open()

Expand Down
12 changes: 8 additions & 4 deletions crazyflie_py/crazyflie_py/uav_trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@ def normalize(v):


class Polynomial:

def __init__(self, p):
self.p = p

# evaluate a polynomial using horner's rule
def eval(self, t):
def eval(self, t): # noqa: A003
assert t >= 0
x = 0.0
for i in range(0, len(self.p)):
Expand All @@ -27,6 +28,7 @@ def derivative(self):


class TrajectoryOutput:

def __init__(self):
self.pos = None # position [m]
self.vel = None # velocity [m/s]
Expand All @@ -37,6 +39,7 @@ def __init__(self):

# 4d single polynomial piece for x-y-z-yaw, includes duration.
class Polynomial4D:

def __init__(self, duration, px, py, pz, pyaw):
self.duration = duration
self.px = Polynomial(px)
Expand All @@ -53,7 +56,7 @@ def derivative(self):
self.pz.derivative().p,
self.pyaw.derivative().p)

def eval(self, t):
def eval(self, t): # noqa: A003
result = TrajectoryOutput()
# flat variables
result.pos = np.array([self.px.eval(t), self.py.eval(t), self.pz.eval(t)])
Expand Down Expand Up @@ -93,6 +96,7 @@ def eval(self, t):


class Trajectory:

def __init__(self):
self.polynomials = None
self.duration = None
Expand All @@ -101,12 +105,12 @@ def n_pieces(self):
return len(self.polynomials)

def loadcsv(self, filename):
data = np.loadtxt(filename, delimiter=",", skiprows=1, usecols=range(33))
data = np.loadtxt(filename, delimiter=',', skiprows=1, usecols=range(33))
self.polynomials = [Polynomial4D(row[0], row[1:9],
row[9:17], row[17:25], row[25:33]) for row in data]
self.duration = np.sum(data[:, 0])

def eval(self, t):
def eval(self, t): # noqa: A003
assert t >= 0
assert t <= self.duration

Expand Down

0 comments on commit 92664ff

Please sign in to comment.