From f6931c106e0ce2b1db0489d276082c8037a15838 Mon Sep 17 00:00:00 2001 From: Christopher Stone Date: Sat, 10 Mar 2018 07:36:46 +0000 Subject: [PATCH] Many minor changes for pep8 compliance, but inadvertently brok e line plotting. Code runs, but lines do not appear! --- robots/little_john/telemetry/code/monitor/version1/colours.py | 2 +- robots/little_john/telemetry/code/monitor/version1/getdata.py | 17 ++++++++--------- robots/little_john/telemetry/code/monitor/version1/main.py | 27 +++++++++++++++++---------- robots/little_john/telemetry/code/monitor/version1/plot.py | 120 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------------------------------- robots/little_john/telemetry/code/monitor/version1/serialselect.py | 34 ++++++++++++++++++---------------- robots/little_john/telemetry/code/monitor/version1/series.py | 14 ++++++++------ 6 files changed, 125 insertions(+), 89 deletions(-) diff --git a/robots/little_john/telemetry/code/monitor/version1/colours.py b/robots/little_john/telemetry/code/monitor/version1/colours.py index bd6601d..8415f7f 100644 --- a/robots/little_john/telemetry/code/monitor/version1/colours.py +++ b/robots/little_john/telemetry/code/monitor/version1/colours.py @@ -2,4 +2,4 @@ WHITE = (255, 255, 255, 255) BLACK = (0, 0, 0, 255) RED = (255, 0, 0, 255) GREEN = (0, 255, 0, 255) -BLUE = (0, 0, 255, 255) \ No newline at end of file +BLUE = (0, 0, 255, 255) diff --git a/robots/little_john/telemetry/code/monitor/version1/getdata.py b/robots/little_john/telemetry/code/monitor/version1/getdata.py index 6a18f29..db7c5c6 100644 --- a/robots/little_john/telemetry/code/monitor/version1/getdata.py +++ b/robots/little_john/telemetry/code/monitor/version1/getdata.py @@ -6,16 +6,17 @@ import logging import os import time import serial -#from serialselect import selectserial + def getData(starttime, datafeed, testseries, testseries2, fake=False): """Check serial port for incoming data""" # Note: 'elapsed' is time since last call of this function - # This works, but it might be better for performance to have two seperate functions, only one of which is run. + # This works, but it might be better for performance to have two + # seperate functions, only one of which is run. if fake: timefromstart = (time.time()-starttime) values = [timefromstart, 100*math.sin(timefromstart)] - #logging.info("Generated test data: " + str(values)) + # logging.info("Generated test data: " + str(values)) testseries.addpoint(values) testseries2.addpoint(values) else: @@ -23,9 +24,9 @@ def getData(starttime, datafeed, testseries, testseries2, fake=False): incoming = datafeed.readline() except: logging.error("Failed to read input data") - + try: - if os=='Windows': + if os == 'Windows': values = incoming.strip().split(b", ") else: values = incoming.strip() @@ -33,15 +34,13 @@ def getData(starttime, datafeed, testseries, testseries2, fake=False): except: logging.error("Failed to parse input data") return - + try: for n, value in enumerate(values): values[n] = float(value) except: logging.error("Failed to convert input to float") return - #logging.info("Recieved data: " + str(values)) + # logging.info("Recieved data: " + str(values)) testseries.addpoint([time.time()-starttime] + values) testseries2.addpoint(values) - - diff --git a/robots/little_john/telemetry/code/monitor/version1/main.py b/robots/little_john/telemetry/code/monitor/version1/main.py index 5e4034a..eb8f72e 100755 --- a/robots/little_john/telemetry/code/monitor/version1/main.py +++ b/robots/little_john/telemetry/code/monitor/version1/main.py @@ -9,7 +9,6 @@ import math import time -#import serial import pyglet import numpy @@ -31,32 +30,40 @@ starttime = time.time() datafeed = selectserial() -if datafeed == None: +if datafeed is None: logging.critical("Failed to open serial port") sys.exit() - -if platform.system()=='Windows': - os='Windows' + +if platform.system() == 'Windows': + os = 'Windows' else: - os='Other' + os = 'Other' logging.info('OS = ' + os) testseries = Series(points=150, xauto=True, ylimits=(0, 1024), - title="Data from serial (time)", xname="Time (s)", yname="ADC output") + title="Data from serial (time)", + xname="Time (s)", yname="ADC output") testseries2 = Series(points=150, xlimits=(0, 1024), ylimits=(0, 1024), - title="Data from serial (xy)", xname="ADC0 output", yname="ADC7 output") + title="Data from serial (xy)", + xname="ADC0 output", yname="ADC7 output") plots = [] plots.append(Plot(testseries)) plots.append(Plot(testseries2)) -# Yes I know these are absurd placeholder names. I'm leaving it like that for the moment because I'm not sure if this is really the only (or best) way to achive the desired result. clock.schedule_interval takes a function, not the result of the function as its argument, so how can you pass arguments to it? def shrubbery(ni): + """ Yes I know these are absurd placeholder names. I'm leaving it like + that for the moment because I'm not sure if this is really the only + (or best) way to achive the desired result. clock.schedule_interval takes + a function, not the result of the function as its argument, so how can + you pass arguments to it? """ getData(starttime, datafeed, testseries, testseries2) -# Pyglet looks after the main event loop, but this ensures that data keeps being read in + +# Pyglet looks after the main event loop, +# but this ensures that data keeps being read pyglet.clock.schedule_interval(shrubbery, 0.01) pyglet.app.run() diff --git a/robots/little_john/telemetry/code/monitor/version1/plot.py b/robots/little_john/telemetry/code/monitor/version1/plot.py index c453357..76d0070 100644 --- a/robots/little_john/telemetry/code/monitor/version1/plot.py +++ b/robots/little_john/telemetry/code/monitor/version1/plot.py @@ -7,31 +7,38 @@ import numpy import logging from colours import * + class Plot(pyglet.window.Window): def __init__(self, series): """Setup a the details of a plot, and create a corresponding window""" pyglet.window.Window.__init__(self, resizable=True) self.set_icon(pyglet.image.load('32x32.png')) - self.set_minimum_size(320,320) + self.set_minimum_size(320, 320) self.series = series self.font = 'Arkhip' - self.margins = (0.09, 0.08) # Fractions of window size + self.margins = (0.09, 0.08) # Fractions of window size self.lines = (10, 8) - #self.resizable = True + # self.resizable = True self.set_caption(self.series.title) def on_resize(self, width, height): """Handle a resize event from the pyglet event loop""" try: - self.bounds = ((int(self.width * self.margins[0]), int(self.width * (1 - self.margins[0]))), - (int(self.height * self.margins[1]), int(self.height * (1 - self.margins[1])))) + self.bounds = ((int(self.width * self.margins[0]), + int(self.width * (1 - self.margins[0]))), + (int(self.height * self.margins[1]), + int(self.height * (1 - self.margins[1])))) except Exception as e: logging.critical(str(e)) self.close() logging.critical('Instance closed') sys.exit() - self.tag_size = min(self.height*self.margins[1]*0.3,self.width*self.margins[0]*0.3) - # This sometimes seems to throw an error ('AttributeError: 'Plot' object has no attribute 'margins') when started for a second time from the same instance. Interesting. Causes the plot windows to freeze + self.tag_size = min(self.height*self.margins[1]*0.3, + self.width*self.margins[0]*0.3) + # This sometimes seems to throw an error + # ('AttributeError: 'Plot' object has no attribute 'margins') + # when started for a second time from the same instance. + # Interesting. Causes the plot windows to freeze pyglet.window.Window.on_resize(self, width, height) def on_draw(self): @@ -44,49 +51,56 @@ class Plot(pyglet.window.Window): def drawBackground(self): """Draw the graph background, currently a plain colour""" - pyglet.image.SolidColorImagePattern(WHITE).create_image(self.width, self.height).blit(0, 0) + #whitepattern = pyglet.image.SolidColorImagePattern(WHITE) + #whitepattern.create_image(self.width, self.height).blit(0, 0) + pyglet.image.SolidColorImagePattern(RED).create_image(self.width, self.height).blit(0, 0) def drawHeading(self): - """Draw a title for the graph (duplicated in the window titlebar, if present""" + """Draw a title for the graph (duplicated in the window titlebar""" heading = pyglet.text.Label(self.series.title, color=BLACK, - font_name=self.font, font_size=self.height*self.margins[0]*0.5, - x=self.width/2, y=self.height-(self.margins[1]), - anchor_x='center', anchor_y='top') + font_name=self.font, + font_size=self.height*self.margins[0]*0.5, + x=self.width/2, + y=self.height-(self.margins[1]), + anchor_x='center', anchor_y='top') heading.draw() def drawLines(self, series): - xscale = float(self.series.xlimits[1]-self.series.xlimits[0])/(self.bounds[0][1]-self.bounds[0][0]) - yscale = float(self.series.ylimits[1]-self.series.ylimits[0])/(self.bounds[1][1]-self.bounds[1][0]) + xscale = float(self.series.xlimits[1]-self.series.xlimits[0] / (self.bounds[0][1]-self.bounds[0][0])) + yscale = float(self.series.ylimits[1]-self.series.ylimits[0] / (self.bounds[1][1]-self.bounds[1][0])) + lmar = int(self.width * self.margins[0]) rmar = int(self.width * self.margins[1]) tmar = int(self.height * self.margins[0]) bmar = int(self.height * self.margins[1]) - + pyglet.gl.glLineWidth(2) - - linecolours = [(255, 0, 0, 255, 0, 0), (0, 220, 0, 0, 220, 0), (0, 0, 255, 0, 0, 255)] - + + linecolours = [(255, 0, 0, 255, 0, 0), + (0, 220, 0, 0, 220, 0), + (0, 0, 255, 0, 0, 255)] + try: for m in range(len(series.data[0])-1): for n in range(len(series.data) - 1): - x1, y1 = series.data[n][0]-series.xlimits[0], series.data[n][m+1]-series.ylimits[0] - x2, y2 = series.data[n+1][0]-series.xlimits[0], series.data[n+1][m+1]-series.ylimits[0] + x1 = series.data[n][0]-series.xlimits[0] + y1 = series.data[n][m+1]-series.ylimits[0] + x2 = series.data[n+1][0]-series.xlimits[0] + y2 = series.data[n+1][m+1]-series.ylimits[0] x1 = int((x1/xscale)+lmar) y1 = int((y1/yscale)+bmar) x2 = int((x2/xscale)+lmar) y2 = int((y2/yscale)+bmar) pyglet.graphics.draw(2, pyglet.gl.GL_LINES, - ('v2i', (x1, y1, x2, y2)), - ('c3B', linecolours[m])) + ('v2i', (x1, y1, x2, y2)), + ('c3B', linecolours[m])) except: - logging.error("Failed to plot lines, possibly due to corrupt/missing data. (This happens at startup)") - - pyglet.gl.glLineWidth(1) - + logging.error("Failed to plot lines: corrupt/missing data?") + pyglet.gl.glLineWidth(1) - def drawAxis(self, axis): # axis=0 is x, 1 is y - """Draw the gridlines and labels for one axis, specified in the last argument""" + def drawAxis(self, axis): # axis=0 is x, 1 is y + """Draw gridlines & labels for one axis, specified as an argument""" limita = self.bounds[1-axis][1] limitb = self.bounds[1-axis][0] start = self.bounds[axis][0] @@ -95,37 +109,49 @@ class Plot(pyglet.window.Window): for pos in numpy.arange(start, stop+1, increment): # Using fp arithmetic to avoid intermittent fencepost errors pos = int(pos) - if axis==0: # x axis, vertical lines - scale = float(self.series.xlimits[1]-self.series.xlimits[0])/(stop-start) + if axis == 0: # x axis, vertical lines + scale = float(self.series.xlimits[1]-self.series.xlimits[0]) + scale /= (stop-start) tagvalue = ((pos-start) * scale) + self.series.xlimits[0] tagtext = str(int(tagvalue)) - pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (pos, limita, pos, limitb)), - ('c3B', (0, 0, 0, 0, 0, 0))) + pyglet.graphics.draw(2, pyglet.gl.GL_LINES, + ('v2i', (pos, limita, pos, limitb)), + ('c3B', (0, 0, 0, 0, 0, 0))) tag = pyglet.text.Label(tagtext, color=BLACK, - font_name=self.font, font_size=self.tag_size, + font_name=self.font, + font_size=self.tag_size, x=pos, y=self.height*self.margins[1], anchor_x='left', anchor_y='top') axistitle = pyglet.text.Label(self.series.xname, color=BLACK, - font_name=self.font, font_size=self.tag_size, - x=self.width/2, y=0, - anchor_x='center', anchor_y='bottom') + font_name=self.font, + font_size=self.tag_size, + x=self.width/2, y=0, + anchor_x='center', + anchor_y='bottom') axistitle.draw() - if axis==1: # y axis, horizontal lines - scale = float(self.series.ylimits[1]-self.series.ylimits[0])/(stop-start) + if axis == 1: # y axis, horizontal lines + scale = float(self.series.ylimits[1]-self.series.ylimits[0]) + scale /= (stop-start) tagvalue = ((pos-start) * scale) + self.series.ylimits[0] tagtext = str(int(tagvalue)) - pyglet.graphics.draw(2, pyglet.gl.GL_LINES, ('v2i', (limita, pos, limitb, pos)), - ('c3B', (0, 0, 0, 0, 0, 0))) + pyglet.graphics.draw(2, pyglet.gl.GL_LINES, + ('v2i', (limita, pos, limitb, pos)), + ('c3B', (0, 0, 0, 0, 0, 0))) tag = pyglet.text.Label(tagtext, color=BLACK, - font_name=self.font, font_size=self.tag_size, - x=self.width*self.margins[0]*0.9, y=pos, + font_name=self.font, + font_size=self.tag_size, + x=self.width*self.margins[0]*0.9, + y=pos, anchor_x='right', anchor_y='center') axistitle = pyglet.text.Label(self.series.yname, color=BLACK, - font_name=self.font, font_size=self.tag_size, - x=0, y=self.height/2, - anchor_x='center', anchor_y='top') - pyglet.gl.glPushMatrix() # Set up a new context to avoid confusing the main one - # Tranformation to rotate label, and ensure it ends up in the right place + font_name=self.font, + font_size=self.tag_size, + x=0, y=self.height/2, + anchor_x='center', + anchor_y='top') + # Set up a new context to avoid confusing the main one + pyglet.gl.glPushMatrix() + # Tranformation to move label to the right place pyglet.gl.glTranslatef(self.height//2, self.height//2, 0.0) pyglet.gl.glRotatef(90.0, 0.0, 0.0, 1.0) # Draw the axis title using the rotated coordinate system diff --git a/robots/little_john/telemetry/code/monitor/version1/serialselect.py b/robots/little_john/telemetry/code/monitor/version1/serialselect.py index 91ef300..fe58313 100644 --- a/robots/little_john/telemetry/code/monitor/version1/serialselect.py +++ b/robots/little_john/telemetry/code/monitor/version1/serialselect.py @@ -2,27 +2,29 @@ # Written as a telemetry tool by: # The UoN Robot Wars Project, 2018 + def selectserial(): - """Cross-platform function to find appropriate serial ports, query the user if necessary, and open one of them""" + """Cross-platform function to find appropriate serial ports, query the + user if necessary, and open one of them""" import platform import serial import os import easygui import logging - + devpatterns = ['ttyACM', 'ttyUSB', 'rfcomm'] targetdevs = [] - if platform.system()=='Windows': + if platform.system() == 'Windows': com_ports = ['COM%s' % (i + 1) for i in range(256)] for port in com_ports: try: s = serial.Serial(port) s.close() targetdevs.append(port) - # Temporarily broadened exception in attempt to make this work on uni PCs - except: # (OSError, serial.SerialException): + # Temporarily broadened exception to make this work on uni PCs + except: # (OSError, serial.SerialException): pass - os='Windows' #may be useful + os = 'Windows' # may be useful else: alldevs = os.listdir("/dev/") targetdevs = [] @@ -30,7 +32,7 @@ def selectserial(): for pattern in devpatterns: if pattern in dev: targetdevs.append("/dev/" + dev) - os='Other' #may be useful + os = 'Other' # may be useful if len(targetdevs) == 0: logging.info("No serial device found.") @@ -42,22 +44,22 @@ def selectserial(): message = "Please choose a serial port to recieve data through:" title = "Found multiple serial ports!" serialport = easygui.choicebox(message, title, targetdevs) - if serialport == None: + if serialport is None: logging.info("User cancelled selection dialogue") return None else: logging.info("Only found one likely serial device: " + targetdevs[0]) serialport = targetdevs[0] - + try: datafeed = serial.Serial( - port=serialport, - baudrate = 9600, - parity=serial.PARITY_NONE, - stopbits=serial.STOPBITS_ONE, - bytesize=serial.EIGHTBITS, - timeout=1 - ) + port=serialport, + baudrate=9600, + parity=serial.PARITY_NONE, + stopbits=serial.STOPBITS_ONE, + bytesize=serial.EIGHTBITS, + timeout=1 + ) logging.info("Sucessfully opened " + serialport + " as data source!") return datafeed diff --git a/robots/little_john/telemetry/code/monitor/version1/series.py b/robots/little_john/telemetry/code/monitor/version1/series.py index 0bfd962..180bc16 100644 --- a/robots/little_john/telemetry/code/monitor/version1/series.py +++ b/robots/little_john/telemetry/code/monitor/version1/series.py @@ -4,10 +4,12 @@ import logging + class Series: def __init__(self, points=100, xlimits=(0, 100), ylimits=(0, 100), xauto=False, yauto=False, - title="Series title", xname="x-axis name", yname="y-axis name"): + title="Series title", + xname="x-axis name", yname="y-axis name"): """Set up an object to store a 2D data series""" # Proposal: # In order to neatly handle multiple lines on the same graph @@ -28,9 +30,9 @@ class Series: self.points = points self.xauto = xauto self.yauto = yauto - + logging.info("Created series: " + title) - + def addpoint(self, point): """Add a point to the dataset, and remove the oldest, if necessary""" self.data.append(point) @@ -43,15 +45,15 @@ class Series: self.autoscale(1) except: logging.error("Series autoscale failed") - - def autoscale(self, axis): # axis=0 is x, 1 is y + + def autoscale(self, axis): # axis=0 is x, 1 is y minval = self.data[0][axis] maxval = self.data[0][axis] for value in self.data: if value[axis] < minval: minval = value[axis] if value[axis] > maxval: - maxval = value[axis] + maxval = value[axis] if axis == 0: self.xlimits = (minval, maxval) else: -- libgit2 0.21.2