Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bug fix #6

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.pyc
79 changes: 45 additions & 34 deletions debugEvent.py
Original file line number Diff line number Diff line change
@@ -1,34 +1,45 @@
#!/usr/bin/env python
###########################################################################
# obd_sensors.py
#
# Copyright 2004 Donour Sizemore ([email protected])
# Copyright 2009 Secons Ltd. (www.obdtester.com)
#
# This file is part of pyOBD.
#
# pyOBD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# pyOBD is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pyOBD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
###########################################################################
import wx

EVT_DEBUG_ID = 1010

class DebugEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_DEBUG_ID)
self.data = data
#!/usr/bin/env python
###########################################################################
# obd_sensors.py
#
# Copyright 2004 Donour Sizemore ([email protected])
# Copyright 2009 Secons Ltd. (www.obdtester.com)
#
# This file is part of pyOBD.
#
# pyOBD is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# pyOBD is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pyOBD; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
###########################################################################
try:
import wx

EVT_DEBUG_ID = 1010

def debug_display(window, position, message):
if window is None:
print message
else:
wx.PostEvent(window, DebugEvent([position, message]))

class DebugEvent(wx.PyEvent):
"""Simple event to carry arbitrary result data."""
def __init__(self, data):
"""Init Result Event."""
wx.PyEvent.__init__(self)
self.SetEventType(EVT_DEBUG_ID)
self.data = data
except ImportError as e:
def debug_display(window, position, message):
print message

64 changes: 45 additions & 19 deletions obd_io.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
import string
import time
from math import ceil
import wx #due to debugEvent messaging
from datetime import datetime

import obd_sensors

Expand All @@ -36,7 +36,7 @@
CLEAR_DTC_COMMAND = "04"
GET_FREEZE_DTC_COMMAND = "07"

from debugEvent import *
from debugEvent import debug_display

#__________________________________________________________________________
def decrypt_dtc_code(code):
Expand Down Expand Up @@ -74,16 +74,17 @@ class OBDPort:
def __init__(self,portnum,_notify_window,SERTIMEOUT,RECONNATTEMPTS):
"""Initializes port by resetting device and gettings supported PIDs. """
# These should really be set by the user.
baud = 9600
baud = 38400
databits = 8
par = serial.PARITY_NONE # parity
sb = 1 # stop bits
to = SERTIMEOUT
self.ELMver = "Unknown"
self.State = 1 #state SERIAL is 1 connected, 0 disconnected (connection failed)
self.port = None

self._notify_window=_notify_window
wx.PostEvent(self._notify_window, DebugEvent([1,"Opening interface (serial port)"]))
debug_display(self._notify_window, 1, "Opening interface (serial port)")

try:
self.port = serial.Serial(portnum,baud, \
Expand All @@ -94,22 +95,32 @@ def __init__(self,portnum,_notify_window,SERTIMEOUT,RECONNATTEMPTS):
self.State = 0
return None

wx.PostEvent(self._notify_window, DebugEvent([1,"Interface successfully " + self.port.portstr + " opened"]))
wx.PostEvent(self._notify_window, DebugEvent([1,"Connecting to ECU..."]))
debug_display(self._notify_window, 1, "Interface successfully " + self.port.portstr + " opened")
debug_display(self._notify_window, 1, "Connecting to ECU...")

try:
self.send_command("atz") # initialize
time.sleep(1)
except serial.SerialException:
self.State = 0
return None

self.ELMver = self.get_result()
wx.PostEvent(self._notify_window, DebugEvent([2,"atz response:" + self.ELMver]))
if(self.ELMver is None):
self.State = 0
return None

debug_display(self._notify_window, 2, "atz response:" + self.ELMver)
self.send_command("ate0") # echo off
wx.PostEvent(self._notify_window, DebugEvent([2,"ate0 response:" + self.get_result()]))
debug_display(self._notify_window, 2, "ate0 response:" + self.get_result())
self.send_command("0100")
ready = self.get_result()
wx.PostEvent(self._notify_window, DebugEvent([2,"0100 response:" + ready]))

if(ready is None):
self.State = 0
return None

debug_display(self._notify_window, 2, "0100 response:" + ready)
return None

def close(self):
Expand All @@ -130,7 +141,7 @@ def send_command(self, cmd):
for c in cmd:
self.port.write(c)
self.port.write("\r\n")
wx.PostEvent(self._notify_window, DebugEvent([3,"Send command:" + cmd]))
#debug_display(self._notify_window, 3, "Send command:" + cmd)

def interpret_result(self,code):
"""Internal use only: not a public interface"""
Expand Down Expand Up @@ -161,20 +172,34 @@ def interpret_result(self,code):

def get_result(self):
"""Internal use only: not a public interface"""
time.sleep(0.1)
if self.port:
#time.sleep(0.01)
repeat_count = 0
if self.port is not None:
buffer = ""
while 1:
c = self.port.read(1)
if c == '\r' and len(buffer) > 0:
break
else:
if buffer != "" or c != ">": #if something is in buffer, add everything
buffer = buffer + c
wx.PostEvent(self._notify_window, DebugEvent([3,"Get result:" + buffer]))
if len(c) == 0:
if(repeat_count == 5):
break
print "Got nothing\n"
repeat_count = repeat_count + 1
continue

if c == '\r':
continue

if c == ">":
break;

if buffer != "" or c != ">": #if something is in buffer, add everything
buffer = buffer + c

#debug_display(self._notify_window, 3, "Get result:" + buffer)
if(buffer == ""):
return None
return buffer
else:
wx.PostEvent(self._notify_window, DebugEvent([3,"NO self.port!" + buffer]))
debug_display(self._notify_window, 3, "NO self.port!")
return None

# get sensor value from command
Expand All @@ -190,6 +215,7 @@ def get_sensor_value(self,sensor):
data = sensor.value(data)
else:
return "NORESPONSE"

return data

# return string of sensor name and value from sensor index
Expand Down
99 changes: 99 additions & 0 deletions obd_recorder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
#!/usr/bin/env python

import obd_io
import serial
import platform
import obd_sensors
from datetime import datetime
import time

from obd_utils import scanSerial

class OBD_Recorder():
def __init__(self, path, log_items):
self.port = None
self.sensorlist = []
localtime = time.localtime(time.time())
filename = path+"bike-"+str(localtime[0])+"-"+str(localtime[1])+"-"+str(localtime[2])+"-"+str(localtime[3])+"-"+str(localtime[4])+"-"+str(localtime[5])+".log"
self.log_file = open(filename, "w", 128)
self.log_file.write("Time,RPM,MPH,Throttle,Load,Gear\n");

for item in log_items:
self.add_log_item(item)

self.gear_ratios = [34/13, 39/21, 36/23, 27/20, 26/21, 25/22]
#log_formatter = logging.Formatter('%(asctime)s.%(msecs).03d,%(message)s', "%H:%M:%S")

def connect(self):
portnames = scanSerial()
#portnames = ['COM10']
print portnames
for port in portnames:
self.port = obd_io.OBDPort(port, None, 2, 2)
if(self.port.State == 0):
self.port.close()
self.port = None
else:
break

if(self.port):
print "Connected to "+self.port.port.name

def is_connected(self):
return self.port

def add_log_item(self, item):
for index, e in enumerate(obd_sensors.SENSORS):
if(item == e.shortname):
self.sensorlist.append(index)
print "Logging item: "+e.name
break


def record_data(self):
if(self.port is None):
return None

print "Logging started"

while 1:
localtime = datetime.now()
current_time = str(localtime.hour)+":"+str(localtime.minute)+":"+str(localtime.second)+"."+str(localtime.microsecond)
log_string = current_time
results = {}
for index in self.sensorlist:
(name, value, unit) = self.port.sensor(index)
log_string = log_string + ","+str(value)
results[obd_sensors.SENSORS[index].shortname] = value;

gear = self.calculate_gear(results["rpm"], results["speed"])
log_string = log_string + "," + str(gear)
self.log_file.write(log_string+"\n")

def calculate_gear(self, rpm, speed):
if speed == "" or speed == 0:
return 0
if rpm == "" or rpm == 0:
return 0

rps = rpm/60
mps = (speed*1.609*1000)/3600

primary_gear = 85/46 #street triple
final_drive = 47/16

tyre_circumference = 1.978 #meters

current_gear_ratio = (rps*tyre_circumference)/(mps*primary_gear*final_drive)

print current_gear_ratio
gear = min((abs(current_gear_ratio - i), i) for i in self.gear_ratios)[1]
return gear


logitems = ["rpm", "speed", "throttle_pos", "load"]
o = OBD_Recorder('/home/pi/logs/', logitems)
o.connect()
if not o.is_connected():
print "Not connected"
o.record_data()
Loading