Changeset 6f09609 for src/python
- Timestamp:
- Aug 6, 2017, 3:53:21 PM (9 years ago)
- Branches:
- 0.5, app-cordova, debian/bullseye, debian/jessie, master
- Children:
- 37d2e9d, 8befa17, d51c76c
- Parents:
- 1efcac7
- Location:
- src/python
- Files:
-
- 5 edited
-
bin/gnuboat (modified) (2 diffs)
-
bin/gnuboat-splashscreen (modified) (1 diff)
-
gnuboat/daemon/displayhandler.py (modified) (1 diff)
-
gnuboat/daemon/gpsdpoller.py (modified) (1 diff)
-
gnuboat/daemon/n2kdpoller.py (modified) (1 diff)
Legend:
- Unmodified
- Added
- Removed
-
src/python/bin/gnuboat
r1efcac7 r6f09609 33 33 from gnuboat import daemon 34 34 35 WHITE =136 BLACK =035 WHITE = 1 36 BLACK = 0 37 37 marginVertical = 10 38 38 marginHorizontal = marginVertical … … 48 48 nmeafile = None 49 49 50 50 51 def rraRows(duration, resolution, step): 51 52 return int(round(float(duration) / rraSteps(resolution, float(step)) / float(step))) 52 53 54 53 55 def rraSteps(resolution, step): 54 56 return int(round(float(resolution) / float(step))) 55 57 58 56 59 def createDatabase(databaseFile): 57 rrdDataSources = [ 'DS:latitude:GAUGE:15:-90:90', 58 'DS:longitude:GAUGE:15:-180:180', 59 'DS:speedthroughwater:GAUGE:15:U:U', 60 'DS:speedoverground:GAUGE:15:U:U', 61 'DS:waterdepth:GAUGE:15:0:10000', 62 'DS:watertemperature:GAUGE:15:-10:50', 63 'DS:gpsfix:GAUGE:15:-999:3' ] 64 65 step = logperiod 66 # durations: each archive should contain values for in seconds 67 archives = [ 68 {"duration": 240, "resolution": 2}, 69 {"duration": 3600, "resolution": 10}, 70 {"duration": 86400, "resolution": 60}, 71 ] 72 rrdArchives = [] 73 for i in range(0, len(archives)): 74 rrdArchives += ['RRA:AVERAGE:0.5:%d:%d' % (rraSteps(archives[i]["resolution"], step), rraRows(archives[i]["duration"], archives[i]["resolution"], step))] 75 76 if not os.path.isfile(databaseFile): 77 rrdtool.create(databaseFile, 78 "--start", 79 "N", 80 "--step", 81 str(step), 82 rrdDataSources, 83 rrdArchives) 60 rrdDataSources = ['DS:latitude:GAUGE:15:-90:90', 61 'DS:longitude:GAUGE:15:-180:180', 62 'DS:speedthroughwater:GAUGE:15:U:U', 63 'DS:speedoverground:GAUGE:15:U:U', 64 'DS:waterdepth:GAUGE:15:0:10000', 65 'DS:watertemperature:GAUGE:15:-10:50', 66 'DS:gpsfix:GAUGE:15:-999:3'] 67 68 step = logperiod 69 # durations: each archive should contain values for in seconds 70 archives = [ 71 {"duration": 240, "resolution": 2}, 72 {"duration": 3600, "resolution": 10}, 73 {"duration": 86400, "resolution": 60}, 74 ] 75 rrdArchives = [] 76 for i in range(0, len(archives)): 77 rrdArchives += ['RRA:AVERAGE:0.5:%d:%d' % (rraSteps(archives[i]["resolution"], step), rraRows( 78 archives[i]["duration"], archives[i]["resolution"], step))] 79 80 if not os.path.isfile(databaseFile): 81 rrdtool.create(databaseFile, 82 "--start", 83 "N", 84 "--step", 85 str(step), 86 rrdDataSources, 87 rrdArchives) 88 84 89 85 90 def checkShutdownRequest(shutdownFile): 86 global shutdownRequested 87 # have look for new shutdown requests 88 if os.path.isfile(shutdownFile): 89 with open(shutdownFile, "r") as fileHandler: 90 shutdownStart = fileHandler.read().strip() 91 os.remove(shutdownFile) 92 shutdownRequested = dateutil.parser.parse(shutdownStart) 93 # check existing shutdown requests 94 if shutdownRequested is not None: 95 currentTime = datetime.datetime.now() 96 currentTime = currentTime.replace(tzinfo=pytz.utc) 97 if (currentTime - shutdownRequested) > datetime.timedelta(seconds = 0): 98 os.system("sudo shutdown -h now") 91 global shutdownRequested 92 # have look for new shutdown requests 93 if os.path.isfile(shutdownFile): 94 with open(shutdownFile, "r") as fileHandler: 95 shutdownStart = fileHandler.read().strip() 96 os.remove(shutdownFile) 97 shutdownRequested = dateutil.parser.parse(shutdownStart) 98 # check existing shutdown requests 99 if shutdownRequested is not None: 100 currentTime = datetime.datetime.now() 101 currentTime = currentTime.replace(tzinfo=pytz.utc) 102 if (currentTime - shutdownRequested) > datetime.timedelta(seconds=0): 103 os.system("sudo shutdown -h now") 104 99 105 100 106 def usage(): 101 print "Usage of gnuboat daemon:" 102 print " gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD] [-o PATH_TO_NMEA1983_LOG]" 103 print "" 104 print " -h --help Display this help" 105 print " -r --rrdfile Path to the rrd database used by the webservice to serve the clients" 106 print " -s --shutdownfile Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat" 107 print " -l --logperiod Time in seconds to update the logs" 108 print " -d --displayperiod Timein seconds to update the display" 109 print " -o --output File where the NMEA1983 log is stored" 107 print "Usage of gnuboat daemon:" 108 print " gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD] [-o PATH_TO_NMEA1983_LOG]" 109 print "" 110 print " -h --help Display this help" 111 print " -r --rrdfile Path to the rrd database used by the webservice to serve the clients" 112 print " -s --shutdownfile Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat" 113 print " -l --logperiod Time in seconds to update the logs" 114 print " -d --displayperiod Timein seconds to update the display" 115 print " -o --output File where the NMEA1983 log is stored" 116 110 117 111 118 def main(argv): 112 global rrdfile 113 global shutdownfile 114 global logperiod 115 global displayperiod 116 global logfile 117 global nmeafile 118 119 try: 120 opts, args = getopt.getopt(argv, "hr:s:l:d:o:", ["help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="]) 121 except getopt.GetoptError: 122 usage() 123 sys.exit(2) 124 125 for option, argument in opts: 126 if option == ("-h", "--help"): 127 usage() 128 sys.exit() 129 elif option in ("-r", "--rrdfile"): 130 rrdfile = argument 131 elif option in ("-s", "--shutdownfile"): 132 shutdownfile = argument 133 elif option in ("-l", "--logperiod"): 134 logperiod = argument 135 elif option in ("-d", "--displayperiod"): 136 displayperiod = argument 137 elif option in ("-o", "--output"): 138 logfile = argument 139 else: 140 assert False, "unhandled option" 141 142 if not os.path.exists(os.path.dirname(rrdfile)): 143 print "rrd database directory not found %s" % os.path.dirname(rrdfile) 144 print "" 145 usage() 146 sys.exit(2) 147 148 if not os.path.exists(os.path.dirname(shutdownfile)): 149 print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile) 150 print "" 151 usage() 152 sys.exit(2) 153 154 if logperiod < 1: 155 print "Log period must be >= 1" 156 print "" 157 usage() 158 sys.exit(2) 159 160 if displayperiod < 1 or displayperiod < logperiod: 161 print "Display period must be >= 1 and could not be faster than log period" 162 print "" 163 usage() 164 sys.exit(2) 165 166 createDatabase(rrdfile) 167 168 try: 169 nmeafile = open(logfile, 'a', 0) 170 except IOError as error: 171 print "Could not open the logfile: %s" % error 172 sys.exit(2) 173 174 displayHandler = daemon.DisplayHandler(displayperiod) 175 176 gpsp = daemon.GpsdPoller(logperiod) 177 n2kd = daemon.N2kdPoller(logperiod) 178 try: 179 gpsp.start() 180 n2kd.start() 181 while True: 182 # In the main thread, every logPeriod seconds print the current value 183 time.sleep(logperiod) 184 latitude = gpsp.latitude() 185 longitude = gpsp.longitude() 186 speedThroughWater = n2kd.speedThroughWater() 187 speedOverGround = gpsp.speedOverGround() 188 waterDepth = n2kd.waterDepth() 189 waterTemperature = n2kd.waterTemperature() 190 gpsFix = gpsp.gpsFix() 191 192 # update rrd database for the webservice 193 rrdtool.update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s" % (latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)) 194 195 # append to log 196 if gpsp.gpsFix() >= 2: 197 timeUtc = gpsp.timeUtc() 198 status = gpsp.status() 199 latitudeDirection = gpsp.latitudeDirection() 200 longitudeDirection = gpsp.longitudeDirection() 201 courseOverGround = gpsp.courseOverGround() 202 203 mode = 'N' 204 if gpsFix >= 2: 205 mode = 'A' 206 207 nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC', 208 ( timeUtc.strftime("%H%M%S"), status, '$%04.3f' % latitude, 209 latitudeDirection, '$%05.3f' % longitude, longitudeDirection, 210 '$%02.1f' % speedOverGround, '$%02.1f' % courseOverGround, 211 timeUtc.strftime("%d%m%y"), '', '', mode )))) 212 if n2kd.waterDepthValid(): 213 nmeafile.write("%\r\n" % str(pynmea2.DPT('SD', 'DPT', 214 ( '%02.2f' % waterDepth, '00.00' )))) 215 216 # display data 217 displayHandler.setValues(speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix) 218 219 #check for shutdown request 220 checkShutdownRequest(shutdownfile) 221 222 except (KeyboardInterrupt, SystemExit): #when you press ctrl+c 223 if nmeafile: 224 nmeafile.close() 225 if gpsp.ident is not None: 226 gpsp.stop() 227 gpsp.join() # wait for the thread to finish what it's doing 228 if n2kd.ident is not None: 229 n2kd.stop() 230 n2kd.join() 231 if displayHandler.ident is not None: 232 displayHandler.stop() 233 displayHandler.join() # wait for the thread to finish what it's doing 119 global rrdfile 120 global shutdownfile 121 global logperiod 122 global displayperiod 123 global logfile 124 global nmeafile 125 126 try: 127 opts, args = getopt.getopt(argv, "hr:s:l:d:o:", [ 128 "help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="]) 129 except getopt.GetoptError: 130 usage() 131 sys.exit(2) 132 133 for option, argument in opts: 134 if option == ("-h", "--help"): 135 usage() 136 sys.exit() 137 elif option in ("-r", "--rrdfile"): 138 rrdfile = argument 139 elif option in ("-s", "--shutdownfile"): 140 shutdownfile = argument 141 elif option in ("-l", "--logperiod"): 142 logperiod = argument 143 elif option in ("-d", "--displayperiod"): 144 displayperiod = argument 145 elif option in ("-o", "--output"): 146 logfile = argument 147 else: 148 assert False, "unhandled option" 149 150 if not os.path.exists(os.path.dirname(rrdfile)): 151 print "rrd database directory not found %s" % os.path.dirname(rrdfile) 152 print "" 153 usage() 154 sys.exit(2) 155 156 if not os.path.exists(os.path.dirname(shutdownfile)): 157 print "Shutdown request directory not found %s" % os.path.dirname(shutdownfile) 158 print "" 159 usage() 160 sys.exit(2) 161 162 if logperiod < 1: 163 print "Log period must be >= 1" 164 print "" 165 usage() 166 sys.exit(2) 167 168 if displayperiod < 1 or displayperiod < logperiod: 169 print "Display period must be >= 1 and could not be faster than log period" 170 print "" 171 usage() 172 sys.exit(2) 173 174 createDatabase(rrdfile) 175 176 try: 177 nmeafile = open(logfile, 'a', 0) 178 except IOError as error: 179 print "Could not open the logfile: %s" % error 180 sys.exit(2) 181 182 displayHandler = daemon.DisplayHandler(displayperiod) 183 184 gpsp = daemon.GpsdPoller(logperiod) 185 n2kd = daemon.N2kdPoller(logperiod) 186 try: 187 gpsp.start() 188 n2kd.start() 189 while True: 190 # In the main thread, every logPeriod seconds print the current 191 # value 192 time.sleep(logperiod) 193 latitude = gpsp.latitude() 194 longitude = gpsp.longitude() 195 speedThroughWater = n2kd.speedThroughWater() 196 speedOverGround = gpsp.speedOverGround() 197 waterDepth = n2kd.waterDepth() 198 waterTemperature = n2kd.waterTemperature() 199 gpsFix = gpsp.gpsFix() 200 201 # update rrd database for the webservice 202 rrdtool.update(rrdfile, "N:%s:%s:%s:%s:%s:%s:%s" % ( 203 latitude, longitude, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix)) 204 205 # append to log 206 if gpsp.gpsFix() >= 2: 207 timeUtc = gpsp.timeUtc() 208 status = gpsp.status() 209 latitudeDirection = gpsp.latitudeDirection() 210 longitudeDirection = gpsp.longitudeDirection() 211 courseOverGround = gpsp.courseOverGround() 212 213 mode = 'N' 214 if gpsFix >= 2: 215 mode = 'A' 216 217 nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC', 218 (timeUtc.strftime("%H%M%S"), status, '$%04.3f' % latitude, 219 latitudeDirection, '$%05.3f' % longitude, longitudeDirection, 220 '$%02.1f' % speedOverGround, '$%02.1f' % courseOverGround, 221 timeUtc.strftime("%d%m%y"), '', '', mode)))) 222 if n2kd.waterDepthValid(): 223 nmeafile.write("%\r\n" % str(pynmea2.DPT('SD', 'DPT', 224 ('%02.2f' % waterDepth, '00.00')))) 225 226 # display data 227 displayHandler.setValues( 228 speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix) 229 230 # check for shutdown request 231 checkShutdownRequest(shutdownfile) 232 233 except (KeyboardInterrupt, SystemExit): # when you press ctrl+c 234 if nmeafile: 235 nmeafile.close() 236 if gpsp.ident is not None: 237 gpsp.stop() 238 gpsp.join() # wait for the thread to finish what it's doing 239 if n2kd.ident is not None: 240 n2kd.stop() 241 n2kd.join() 242 if displayHandler.ident is not None: 243 displayHandler.stop() 244 # wait for the thread to finish what it's doing 245 displayHandler.join() 234 246 235 247 if __name__ == "__main__": 236 main(sys.argv[1:])248 main(sys.argv[1:]) -
src/python/bin/gnuboat-splashscreen
r1efcac7 r6f09609 21 21 import getopt 22 22 try: 23 from PIL import Image24 from PIL import ImageOps25 from EPD import EPD26 epdEnabled = True23 from PIL import Image 24 from PIL import ImageOps 25 from EPD import EPD 26 epdEnabled = True 27 27 except: 28 epdEnabled = False 28 epdEnabled = False 29 29 30 30 31 def displayImage(epd, imageFilePath): 31 image = Image.open(imageFilePath) 32 image = ImageOps.grayscale(image) 33 imageResized = image.resize((epd.width, epd.height)) 34 imageBlackWhite = imageResized.convert("1", dither=Image.FLOYDSTEINBERG) 35 epd.display(imageBlackWhite) 36 epd.update() 32 image = Image.open(imageFilePath) 33 image = ImageOps.grayscale(image) 34 imageResized = image.resize((epd.width, epd.height)) 35 imageBlackWhite = imageResized.convert("1", dither=Image.FLOYDSTEINBERG) 36 epd.display(imageBlackWhite) 37 epd.update() 38 37 39 38 40 def usage(): 39 print "Usage of gnuboat-splashscreen:"40 print " gnuboat-splashscreen [-h] -i PATH_TO_IMAGE_TO_DISPLAY"41 print ""42 print " -h --help Print this help"43 print " -i --image Path to the image, which should be displayed"44 sys.exit()41 print "Usage of gnuboat-splashscreen:" 42 print " gnuboat-splashscreen [-h] -i PATH_TO_IMAGE_TO_DISPLAY" 43 print "" 44 print " -h --help Print this help" 45 print " -i --image Path to the image, which should be displayed" 46 sys.exit() 45 47 46 def main(argv):47 image = ""48 try:49 opts, args = getopt.getopt(argv, "hi:", ["help", "image="])50 except getopt.GetoptError:51 usage()52 sys.exit(2)53 48 54 for option, argument in opts: 55 if option == ("-h", "--help"): 56 usage() 57 sys.exit() 58 elif option in ("-i", "--image"): 59 image = argument 60 else: 61 assert False, "unhandled option" 49 def main(argv): 50 image = "" 51 try: 52 opts, args = getopt.getopt(argv, "hi:", ["help", "image="]) 53 except getopt.GetoptError: 54 usage() 55 sys.exit(2) 62 56 63 if not os.path.exists(image): 64 print "Image %s not found" % image 65 print "" 66 usage() 67 sys.exit(2) 57 for option, argument in opts: 58 if option == ("-h", "--help"): 59 usage() 60 sys.exit() 61 elif option in ("-i", "--image"): 62 image = argument 63 else: 64 assert False, "unhandled option" 68 65 69 if not epdEnabled: 70 print "Could not initialize EPD or PIL python packages" 71 sys.exit(2) 66 if not os.path.exists(image): 67 print "Image %s not found" % image 68 print "" 69 usage() 70 sys.exit(2) 72 71 73 epd = EPD() 74 epd.clear() 75 displayImage(epd, image) 72 if not epdEnabled: 73 print "Could not initialize EPD or PIL python packages" 74 sys.exit(2) 75 76 epd = EPD() 77 epd.clear() 78 displayImage(epd, image) 76 79 77 80 if __name__ == "__main__": 78 main(sys.argv[1:])81 main(sys.argv[1:]) -
src/python/gnuboat/daemon/displayhandler.py
r1efcac7 r6f09609 21 21 22 22 try: 23 from EPD import EPD24 from PIL import Image25 from PIL import ImageDraw26 from PIL import ImageFont27 epdEnabled = True23 from EPD import EPD 24 from PIL import Image 25 from PIL import ImageDraw 26 from PIL import ImageFont 27 epdEnabled = True 28 28 except: 29 epdEnabled = False29 epdEnabled = False 30 30 31 31 """@class DisplayHandler 32 32 """ 33 34 33 35 class DisplayHandler(threading.Thread): 34 def __init__(self, displayperiod):35 threading.Thread.__init__(self)36 try:37 self._epd = EPD()38 except:39 epdEnabled = False40 return41 self._epd.clear()42 self._updatePeriod = displayperiod43 self._running = True44 self._speedThroughWater = None45 self._speedOverGround = None46 self._waterDepth = None47 self._waterTemperature = None48 self._gpsFix = None49 50 def setSpeedThroughWater(self, speed):51 self._speedThroughWater = speed52 36 53 def setSpeedOverGround(self, speed): 54 self._speedOverGround = speed 55 56 def setWaterDepth(self, depth): 57 self._waterDepth = depth 58 59 def setWaterTemperature(self, temperature): 60 self._waterTemperature = temperature 37 def __init__(self, displayperiod): 38 threading.Thread.__init__(self) 39 try: 40 self._epd = EPD() 41 except: 42 epdEnabled = False 43 return 44 self._epd.clear() 45 self._updatePeriod = displayperiod 46 self._running = True 47 self._speedThroughWater = None 48 self._speedOverGround = None 49 self._waterDepth = None 50 self._waterTemperature = None 51 self._gpsFix = None 61 52 62 def setGpsFix(self, fix): 63 self._gpsFix = fix 64 65 def setValues(self, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix): 66 self.setSpeedThroughWater(speedThroughWater) 67 self.setSpeedOverGround(speedOverGround) 68 self.setWaterDepth(waterDepth) 69 self.setWaterTemperature(waterTemperature) 70 self.setGpsFix(gpsFix) 53 def setSpeedThroughWater(self, speed): 54 self._speedThroughWater = speed 71 55 72 def stop(self): 73 self._running = False 74 75 def run(self): 76 if not epdEnabled: 77 return 78 try: 79 while self._running: 80 self.displayValues(self._epd, self._speedThroughWater, self._speedOverGround, self._waterDepth, self._waterTemperature, self._gpsFix) 81 time.sleep(self._updatePeriod) 82 except StopIteration: 83 pass 56 def setSpeedOverGround(self, speed): 57 self._speedOverGround = speed 84 58 85 def displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix): 86 if not epdEnabled: 87 return 59 def setWaterDepth(self, depth): 60 self._waterDepth = depth 88 61 89 # requires dejavu package!!!! 90 fontValues = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34) 91 fontTitles = ImageFont.truetype('/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24) 62 def setWaterTemperature(self, temperature): 63 self._waterTemperature = temperature 92 64 93 # initially set all white background 94 image = Image.new('1', epd.size, WHITE) 95 width, height = image.size 65 def setGpsFix(self, fix): 66 self._gpsFix = fix 96 67 97 rowHeightTitles = 25 98 rowHeightValues = float(height - 2 * rowHeightTitles - 3 * marginVertical) / 2.0 99 columnWidthUnit = 30 100 columnWidthValues = int(float(width - 3 * marginHorizontal - 2 * columnWidthUnit) / 2.0) 68 def setValues(self, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix): 69 self.setSpeedThroughWater(speedThroughWater) 70 self.setSpeedOverGround(speedOverGround) 71 self.setWaterDepth(waterDepth) 72 self.setWaterTemperature(waterTemperature) 73 self.setGpsFix(gpsFix) 101 74 102 d raw = ImageDraw.Draw(image)103 # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE)75 def stop(self): 76 self._running = False 104 77 105 x = marginHorizontal 106 y = marginVertical 107 draw.text((x, y), "STW", fill=BLACK, font=fontTitles) 108 if speedThroughWater is not None: 109 draw.text((x, y + rowHeightTitles), str(speedThroughWater), fill=BLACK, font=fontValues) 110 draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles) 78 def run(self): 79 if not epdEnabled: 80 return 81 try: 82 while self._running: 83 self.displayValues(self._epd, self._speedThroughWater, self._speedOverGround, 84 self._waterDepth, self._waterTemperature, self._gpsFix) 85 time.sleep(self._updatePeriod) 86 except StopIteration: 87 pass 111 88 112 x = x + marginHorizontal + columnWidthValues + columnWidthUnit 113 draw.text((x, y), "SOG", fill=BLACK, font=fontTitles) 114 if speedOverGround is not None: 115 draw.text((x, y + rowHeightTitles), str(speedOverGround), fill=BLACK, font=fontValues) 116 draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), "kts", fill=BLACK, font=fontTitles) 89 def displayValues(epd, speedThroughWater, speedOverGround, waterDepth, waterTemperature, gpsFix): 90 if not epdEnabled: 91 return 117 92 118 x = marginHorizontal 119 y = y + rowHeightTitles + rowHeightValues + marginVertical 120 draw.text((x, y), "Depth", fill=BLACK, font=fontTitles) 121 if waterDepth is not None: 122 draw.text((x, y + rowHeightTitles), str(waterDepth), fill=BLACK, font=fontValues) 123 draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "m", fill=BLACK, font=fontTitles) 93 # requires dejavu package!!!! 94 fontValues = ImageFont.truetype( 95 '/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf', 34) 96 fontTitles = ImageFont.truetype( 97 '/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf', 24) 124 98 125 x = x + marginHorizontal + columnWidthValues + columnWidthUnit 126 draw.text((x, y), "Water", fill=BLACK, font=fontTitles) 127 if waterTemperature is not None: 128 draw.text((x, y + rowHeightTitles), str(waterTemperature), fill=BLACK, font=fontValues) 129 draw.text((x + int(float(columnWidthValues) / 1.5), y + rowHeightTitles * 1.4), "C", fill=BLACK, font=fontTitles) 99 # initially set all white background 100 image = Image.new('1', epd.size, WHITE) 101 width, height = image.size 130 102 131 x = int((x + marginHorizontal + columnWidthValues) * 0.93) 132 draw.text((x, y), "Fix", fill=BLACK, font=fontTitles) 133 if gpsFix is not None: 134 draw.text((x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues) 135 136 epd.display(image) 137 epd.update() 103 rowHeightTitles = 25 104 rowHeightValues = float( 105 height - 2 * rowHeightTitles - 3 * marginVertical) / 2.0 106 columnWidthUnit = 30 107 columnWidthValues = int( 108 float(width - 3 * marginHorizontal - 2 * columnWidthUnit) / 2.0) 109 110 draw = ImageDraw.Draw(image) 111 # draw.rectangle((0, 0, width, height), fill=WHITE, outline=WHITE) 112 113 x = marginHorizontal 114 y = marginVertical 115 draw.text((x, y), "STW", fill=BLACK, font=fontTitles) 116 if speedThroughWater is not None: 117 draw.text( 118 (x, y + rowHeightTitles), str(speedThroughWater), fill=BLACK, font=fontValues) 119 draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), 120 "kts", fill=BLACK, font=fontTitles) 121 122 x = x + marginHorizontal + columnWidthValues + columnWidthUnit 123 draw.text((x, y), "SOG", fill=BLACK, font=fontTitles) 124 if speedOverGround is not None: 125 draw.text((x, y + rowHeightTitles), str(speedOverGround), 126 fill=BLACK, font=fontValues) 127 draw.text((x + columnWidthValues, y + rowHeightTitles * 1.4), 128 "kts", fill=BLACK, font=fontTitles) 129 130 x = marginHorizontal 131 y = y + rowHeightTitles + rowHeightValues + marginVertical 132 draw.text((x, y), "Depth", fill=BLACK, font=fontTitles) 133 if waterDepth is not None: 134 draw.text( 135 (x, y + rowHeightTitles), str(waterDepth), fill=BLACK, font=fontValues) 136 draw.text((x + int(float(columnWidthValues) / 1.5), 137 y + rowHeightTitles * 1.4), "m", fill=BLACK, font=fontTitles) 138 139 x = x + marginHorizontal + columnWidthValues + columnWidthUnit 140 draw.text((x, y), "Water", fill=BLACK, font=fontTitles) 141 if waterTemperature is not None: 142 draw.text( 143 (x, y + rowHeightTitles), str(waterTemperature), fill=BLACK, font=fontValues) 144 draw.text((x + int(float(columnWidthValues) / 1.5), 145 y + rowHeightTitles * 1.4), "C", fill=BLACK, font=fontTitles) 146 147 x = int((x + marginHorizontal + columnWidthValues) * 0.93) 148 draw.text((x, y), "Fix", fill=BLACK, font=fontTitles) 149 if gpsFix is not None: 150 draw.text( 151 (x, y + rowHeightTitles), str(gpsFix), fill=BLACK, font=fontValues) 152 153 epd.display(image) 154 epd.update() 138 155 139 156 if __name__ == "__main__": -
src/python/gnuboat/daemon/gpsdpoller.py
r1efcac7 r6f09609 24 24 25 25 # Copied from https://gist.github.com/wolfg1969/4653340 26 27 26 28 class GpsdPoller(threading.Thread): 27 def __init__(self, logperiod):28 threading.Thread.__init__(self)29 try:30 self._session = gps.gps(mode=gps.WATCH_ENABLE)31 except:32 self._session = None33 self._running = False34 return35 self._currentValue = None36 self._running = True37 self._logperiod = logperiod38 29 39 def latitude(self): 40 if self._session == None or self.gpsFix() < 2: 41 return 0 42 return self._session.fix.latitude 43 44 def latitudeDirection(self): 45 return "N" 46 47 def longitude(self): 48 if self._session == None or self.gpsFix() < 2: 49 return 0 50 return self._session.fix.longitude 30 def __init__(self, logperiod): 31 threading.Thread.__init__(self) 32 try: 33 self._session = gps.gps(mode=gps.WATCH_ENABLE) 34 except: 35 self._session = None 36 self._running = False 37 return 38 self._currentValue = None 39 self._running = True 40 self._logperiod = logperiod 51 41 52 def longitudeDirection(self): 53 return "E" 42 def latitude(self): 43 if self._session == None or self.gpsFix() < 2: 44 return 0 45 return self._session.fix.latitude 54 46 55 def speedOverGround(self): 56 if self._session == None or self.gpsFix() < 2: 57 return 0 58 return self._session.fix.speed 47 def latitudeDirection(self): 48 return "N" 59 49 60 def courseOverGround(self): 61 if self._session == None or self.gpsFix() < 2: 62 return 0 63 return self._session.fix.track 64 65 def gpsFix(self): 66 if self._session == None: 67 return 0 68 return self._session.fix.mode 50 def longitude(self): 51 if self._session == None or self.gpsFix() < 2: 52 return 0 53 return self._session.fix.longitude 69 54 70 def status(self): 71 if self._session == None or self.gpsFix() < 2: 72 return "V" 73 return "A" 55 def longitudeDirection(self): 56 return "E" 74 57 75 def timeUtc(self): 76 if self._session == None or self.gpsFix() < 2: 77 return None 78 currentTime = self._session.fix.time 79 if isinstance(currentTime, float): 80 return datetime.datetime.fromtimestamp(currentTime) 81 return dateutil.parser.parse(self._session.fix.time) 58 def speedOverGround(self): 59 if self._session == None or self.gpsFix() < 2: 60 return 0 61 return self._session.fix.speed 82 62 83 def stop(self): 84 self._running = False 85 86 def run(self): 87 try: 88 while self._running: 89 self._currentValue = self._session.next() 90 time.sleep(float(self._logperiod)/2.0) 91 except StopIteration: 92 pass 63 def courseOverGround(self): 64 if self._session == None or self.gpsFix() < 2: 65 return 0 66 return self._session.fix.track 67 68 def gpsFix(self): 69 if self._session == None: 70 return 0 71 return self._session.fix.mode 72 73 def status(self): 74 if self._session == None or self.gpsFix() < 2: 75 return "V" 76 return "A" 77 78 def timeUtc(self): 79 if self._session == None or self.gpsFix() < 2: 80 return None 81 currentTime = self._session.fix.time 82 if isinstance(currentTime, float): 83 return datetime.datetime.fromtimestamp(currentTime) 84 return dateutil.parser.parse(self._session.fix.time) 85 86 def stop(self): 87 self._running = False 88 89 def run(self): 90 try: 91 while self._running: 92 self._currentValue = self._session.next() 93 time.sleep(float(self._logperiod) / 2.0) 94 except StopIteration: 95 pass 93 96 94 97 if __name__ == "__main__": -
src/python/gnuboat/daemon/n2kdpoller.py
r1efcac7 r6f09609 24 24 """@class N2kdPoller 25 25 """ 26 27 26 28 class N2kdPoller(threading.Thread): 27 def __init__(self, logperiod):28 threading.Thread.__init__(self)29 self._serverHost = "127.0.0.1"30 self._serverPort = 259731 self._timeout = 1.532 self._speedThroughWater = 033 self._distanceLog = 034 self._distanceLogTrip = 035 self._waterDepth = 036 self._waterDepthValid = False37 self._waterTemperature = 038 self._running = True39 self._logperiod = logperiod40 self._connectErrorPrinted = False41 29 42 def speedThroughWater(self): 43 return self._speedThroughWater 44 45 def distanceLog(self): 46 return self._distanceLog 30 def __init__(self, logperiod): 31 threading.Thread.__init__(self) 32 self._serverHost = "127.0.0.1" 33 self._serverPort = 2597 34 self._timeout = 1.5 35 self._speedThroughWater = 0 36 self._distanceLog = 0 37 self._distanceLogTrip = 0 38 self._waterDepth = 0 39 self._waterDepthValid = False 40 self._waterTemperature = 0 41 self._running = True 42 self._logperiod = logperiod 43 self._connectErrorPrinted = False 47 44 48 def distanceLogTrip(self):49 return self._distanceLogTrip45 def speedThroughWater(self): 46 return self._speedThroughWater 50 47 51 def waterDepth(self):52 return self._waterDepth48 def distanceLog(self): 49 return self._distanceLog 53 50 54 def waterDepthValid(self): 55 return self._waterDepthValid 56 57 def waterTemperature(self): 58 return self._waterTemperature 51 def distanceLogTrip(self): 52 return self._distanceLogTrip 59 53 60 def _loadData(self): 61 n2kdSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 62 n2kdSocket.settimeout(float(self._logperiod)/2.0) 63 try: 64 n2kdSocket.connect((self._serverHost, self._serverPort)) 65 except socket.error as error: 66 if not self._connectErrorPrinted: 67 print "Failed to connect to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error) 68 self._connectErrorPrinted = True 69 self._waterDepthValid = False 70 return 71 if self._connectErrorPrinted: 72 print "Connected to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error) 73 self._connectErrorPrinted = False 54 def waterDepth(self): 55 return self._waterDepth 74 56 75 response = "" 76 while 1: 77 data = n2kdSocket.recv(1024) 78 if not data: 79 break 80 response += data 81 n2kdSocket.close() 82 data = json.loads(response) 83 84 descriptions = [ "Water Depth", "Speed", "Environmental Parameters", "Distance Log" ] 85 86 for key in data: 87 entryKeys = data[key].keys() 88 if len(entryKeys) != 2: 89 print "Malformed json n2kd response? %s" % response 90 else: 91 if data[key]["description"] in descriptions: 92 entryKey = entryKeys[1] 93 lineKeys = data[key][entryKey].keys() 94 if "fields" not in lineKeys: 95 print "No fields entry. Malformed json n2kd response in %s" % data[key][entryKey] 96 else: 97 fields = data[key][entryKey]["fields"] 98 # try water depth (NEED TO APPLY OFFSET?) 99 if "Depth" in fields: 100 if data[key][entryKey]["description"] == "Water Depth": 101 self._waterDepth = fields["Depth"] 102 self._waterDepthValid = True 103 # try speed 104 if "Speed Water Referenced" in fields: 105 self._speedThroughWater = fields["Speed Water Referenced"] 106 # try sea temperature 107 if "Temperature Source" in fields and "Temperature" in fields: 108 if fields["Temperature Source"] == "Sea Temperature": 109 self._waterTemperature = fields["Temperature"] 110 # try log 111 if "Log" in fields: 112 self._distanceLog = fields["Log"] 113 if "Trip Log" in fields: 114 self._distanceLogTrip = fields["Trip Log"] 115 116 def _serverUrl(self): 117 return "http://%s:%d/" % (self._serverHost, self._serverPort) 118 119 def stop(self): 120 self._running = False 121 122 def run(self): 123 try: 124 while self._running: 125 self._loadData() 126 time.sleep(float(self._logperiod)/2.0) 127 except StopIteration: 128 pass 57 def waterDepthValid(self): 58 return self._waterDepthValid 59 60 def waterTemperature(self): 61 return self._waterTemperature 62 63 def _loadData(self): 64 n2kdSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 65 n2kdSocket.settimeout(float(self._logperiod) / 2.0) 66 try: 67 n2kdSocket.connect((self._serverHost, self._serverPort)) 68 except socket.error as error: 69 if not self._connectErrorPrinted: 70 print "Failed to connect to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error) 71 self._connectErrorPrinted = True 72 self._waterDepthValid = False 73 return 74 if self._connectErrorPrinted: 75 print "Connected to n2kd server at %s:%s: %s" % (self._serverHost, self._serverPort, error) 76 self._connectErrorPrinted = False 77 78 response = "" 79 while 1: 80 data = n2kdSocket.recv(1024) 81 if not data: 82 break 83 response += data 84 n2kdSocket.close() 85 data = json.loads(response) 86 87 descriptions = [ 88 "Water Depth", "Speed", "Environmental Parameters", "Distance Log"] 89 90 for key in data: 91 entryKeys = data[key].keys() 92 if len(entryKeys) != 2: 93 print "Malformed json n2kd response? %s" % response 94 else: 95 if data[key]["description"] in descriptions: 96 entryKey = entryKeys[1] 97 lineKeys = data[key][entryKey].keys() 98 if "fields" not in lineKeys: 99 print "No fields entry. Malformed json n2kd response in %s" % data[key][entryKey] 100 else: 101 fields = data[key][entryKey]["fields"] 102 # try water depth (NEED TO APPLY OFFSET?) 103 if "Depth" in fields: 104 if data[key][entryKey]["description"] == "Water Depth": 105 self._waterDepth = fields["Depth"] 106 self._waterDepthValid = True 107 # try speed 108 if "Speed Water Referenced" in fields: 109 self._speedThroughWater = fields[ 110 "Speed Water Referenced"] 111 # try sea temperature 112 if "Temperature Source" in fields and "Temperature" in fields: 113 if fields["Temperature Source"] == "Sea Temperature": 114 self._waterTemperature = fields["Temperature"] 115 # try log 116 if "Log" in fields: 117 self._distanceLog = fields["Log"] 118 if "Trip Log" in fields: 119 self._distanceLogTrip = fields["Trip Log"] 120 121 def _serverUrl(self): 122 return "http://%s:%d/" % (self._serverHost, self._serverPort) 123 124 def stop(self): 125 self._running = False 126 127 def run(self): 128 try: 129 while self._running: 130 self._loadData() 131 time.sleep(float(self._logperiod) / 2.0) 132 except StopIteration: 133 pass 129 134 130 135 if __name__ == "__main__":
Note:
See TracChangeset
for help on using the changeset viewer.
