View Single Post
Old 08-02-2007, 10:38 PM   #12
impala454
Newbie
 
impala454's Avatar
 
Join Date: Aug 2007
Location: Houston, TX
Posts: 35
Well it's definitely more fun to look at dirty code than no code

here's a quick file I put together, doesn't quite work but you get the idea. I just got my feet wet with this tonight so hopefully I'll get the hang of it after a while.

Code:
using System; using System.IO.Ports; using System.Text; using System.Threading; using System.IO; namespace TestObdScanner { public class ObdDevice { private string PortName; private int BaudRate; private int ReadTimeOut; private SerialPort Port; public ObdDevice(string portName, int baudRate) { PortName = portName; BaudRate = baudRate; ReadTimeOut = 1000; Port = new SerialPort(PortName, BaudRate); } public ObdDevice(string portName, int baudRate, int readTimeOut) { PortName = portName; BaudRate = baudRate; ReadTimeOut = readTimeOut; Port = new SerialPort(PortName, BaudRate); } public bool Connect() { if (Port != null) { try { Port.Open(); Port.DataReceived += new SerialDataReceivedEventHandler(Port_DataReceived); } catch (Exception OpenExcep) { Console.WriteLine(OpenExcep.Message); return false; } } else { Console.WriteLine("Error: Tried to connect with a null port"); } return true; } public void TestAllPids() { int MaxDecimalPid = 78; StringBuilder Command = new StringBuilder(6); for (int i = 1; i <= MaxDecimalPid; i++) { Command.AppendFormat("01 {0}", i.ToString("X2")); Console.WriteLine(Command.ToString()); WriteLogFile(Command.ToString()); Port.WriteLine(Command.ToString()); Thread.Sleep(ReadTimeOut); Command.Remove(0, Command.Length); } } private void Port_DataReceived(object sender, SerialDataReceivedEventArgs args) { string RawData = Port.ReadExisting(); // Update some publicly accessible data structure to make this useful Console.WriteLine(RawData); WriteLogFile(RawData); } private void WriteLogFile(string message) { StreamWriter sw = new StreamWriter("log.txt", true); sw.WriteLine(message); sw.Close(); } } }

with the usage of the class like:
Code:
using System; using TestObdScanner; namespace ObdConsoleTest { class Program { static void Main(string[] args) { ObdDevice dev = new ObdDevice("COM1", 9600); if (dev.Connect()) dev.TestAllPids(); } } }

the callback is happening, just not seeing the data I'm expecting to see, the log ends up repeating the command sent.
impala454 is offline   Reply With Quote