概要
elm327の研究。
atコマンドをそのまま打つのは、むずいので、アセンブラを考案してみた。
ELM327をCPUと見立てて、ニーモニックを組み立てた。
まずは、ECUシミュレータ組んで、動作を確認する。
41が返るのは、ライブデータなので、対応する。
動作確認
>elmasm3
==================================================
ELM327 アセンブラ・シェル型インタプリタ (.NET 4互換)
[使い方] ニーモニックを入力してください。(例: RESET, RDV, REQ 010C)
[終了] EXIT と入力すると終了します。
==================================================
ELM327_ASM> reset
REQ: AT Z
-> [Raw Response]: ELM327 v1.5
ELM327_ASM> rdi
REQ: AT I
-> [Raw Response]: ELM327 v1.5
ELM327_ASM> rdv
REQ: AT RV
-> [Raw Response]: 12.6V
=> [自動解析] 電圧: 12.60 V
ELM327_ASM> req 01 0c
REQ: 01 0c
-> [Raw Response]: 41 0C 1F 40
=> [自動解析] エンジン回転数: 2000 RPM
ELM327_ASM> rdign
REQ: AT IGN
-> [Raw Response]: ELM327 v1.5
ELM327_ASM> rddsc
REQ: AT @1
-> [Raw Response]: OBDII to RS232 Interpreter
ELM327_ASM> req 01 0d
REQ: 01 0d
-> [Raw Response]: 41 0D 3C
=> [自動解析] 車速: 60 km/h
ELM327_ASM> req 01 0f
REQ: 01 0f
-> [Raw Response]: 41 0F 4B
=> [自動解析] 吸気温度: 35 °C
ELM327_ASM> req 01 11
REQ: 01 11
-> [Raw Response]: 41 11 33
=> [自動解析] スロットル開度: 20.0 %
ELM327_ASM> exit
サンプルコード
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO.Ports;
using System.Text.RegularExpressions;
namespace Elm327MnemonicApp
{
public class ECUsim {
private readonly Random _rand = new Random();
private bool StartsWith(string target, string value)
{
return target.StartsWith(value, StringComparison.OrdinalIgnoreCase);
}
public string talk(string a) {
if (string.IsNullOrEmpty(a))
return ">";
a = a.Trim();
string res = "";
string ans = "";
if (a.Length >= 2)
{
ans = "4" + a.Substring(1, 1) + " ";
}
Console.WriteLine("REQ: " + a);
if (StartsWith(a, "AT Z") || StartsWith(a, "AT I"))
{
res = "ELM327 v1.5";
}
else if (StartsWith(a, "AT @1"))
{
res = "OBDII to RS232 Interpreter";
}
else if (StartsWith(a, "AT RV"))
{
double mockVolt = 12.3 + (_rand.NextDouble() * 0.4);
res = mockVolt.ToString("F1") + "V";
}
else if (StartsWith(a, "AT IGN"))
{
res = "ON";
}
else if (StartsWith(a, "AT"))
{
res = "OK";
}
else if (StartsWith(a, "01 00") || StartsWith(a, "01 20") || StartsWith(a, "01 40") || StartsWith(a, "01 60") || StartsWith(a, "01 80") || StartsWith(a, "01 A0") || StartsWith(a, "01 C0"))
{
res = "41 " + a.Substring(3, 2) + " FF FF FF FF";
}
else if (StartsWith(a, "01 01"))
{
res = "41 01 84 07 00 00";
}
else if (StartsWith(a, "01 04"))
{
res = "41 04 64";
}
else if (StartsWith(a, "01 05"))
{
res = "41 05 82";
}
else if (StartsWith(a, "01 06") || StartsWith(a, "01 07") || StartsWith(a, "01 08") || StartsWith(a, "01 09"))
{
res = "41 " + a.Substring(3, 2) + " 80";
}
else if (StartsWith(a, "01 0C"))
{
res = "41 0C 1F 40";
}
else if (StartsWith(a, "01 0D"))
{
res = "41 0D 3C";
}
else if (StartsWith(a, "01 0F"))
{
res = "41 0F 4B";
}
else if (StartsWith(a, "01 11"))
{
res = "41 11 33";
}
else if (StartsWith(a, "01"))
{
res = ans + "00 00";
}
else if (StartsWith(a, "03"))
{
res = "43 03 00 03";
}
else if (StartsWith(a, "09 02"))
{
res = "49 02 1Z376";
}
else
{
res = ans + "NO DATA";
}
return res + "\n>";
}
}
public struct ProgramParameter {
public string Number {
get;
set;
}
public string Value {
get;
set;
}
public bool IsEnabled {
get;
set;
}
}
public struct ProtocolInfo {
public string Name {
get;
set;
}
public int Number {
get;
set;
}
public bool IsAuto {
get;
set;
}
}
public static class Elm327Decoder {
private static readonly Regex VoltageRegex = new Regex(@"(\d+(?:\.\d+)?)V?", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex PpRegex = new Regex(@"([0-9A-Fa-f]{2}):([0-9A-Fa-f]{2})\s+(ON|OFF)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex RpmRegex = new Regex(@"41\s*0C\s*([0-9A-Fa-f\s]{4,5})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex SpeedRegex = new Regex(@"41\s*0D\s*([0-9A-Fa-f\s]{2,3})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex CoolantRegex = new Regex(@"41\s*05\s*([0-9A-Fa-f\s]{2,3})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex LoadRegex = new Regex(@"41\s*04\s*([0-9A-Fa-f\s]{2,3})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex ThrottleRegex = new Regex(@"41\s*11\s*([0-9A-Fa-f\s]{2,3})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex IatRegex = new Regex(@"41\s*0F\s*([0-9A-Fa-f\s]{2,3})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
private static readonly Regex FuelTrimRegex = new Regex(@"41\s*(?:06|07|08|09)\s*([0-9A-Fa-f\s]{2,3})", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static double? ParseVoltage(string response) {
Match match = VoltageRegex.Match(response);
double val;
if (match.Success && double.TryParse(match.Groups[1].Value, NumberStyles.Any, CultureInfo.InvariantCulture, out val))
{
return val;
}
return null;
}
public static bool? ParseIgnition(string response) {
if (response.Contains("ON") || response.Contains("HIGH"))
return true;
if (response.Contains("OFF") || response.Contains("LOW"))
return false;
return null;
}
public static ProtocolInfo? ParseProtocol(string response) {
if (string.IsNullOrEmpty(response) || string.IsNullOrEmpty(response.Trim()))
return null;
ProtocolInfo info = new ProtocolInfo();
if (response.StartsWith("A", StringComparison.OrdinalIgnoreCase))
{
info.IsAuto = true;
response = response.Replace("AUTO,", "").Replace("AUTO", "").Trim();
}
int num;
if (int.TryParse(response, out num))
{
info.Number = num;
return info;
}
info.Name = response;
return info;
}
public static List<ProgramParameter> ParseProgramParameters(string response) {
List<ProgramParameter> list = new List<ProgramParameter>();
string[] lines = response.Split(new[] {
'\n',
'\r'
}, StringSplitOptions.RemoveEmptyEntries);
foreach (string line in lines)
{
Match match = PpRegex.Match(line.Trim());
if (match.Success)
{
ProgramParameter pp = new ProgramParameter();
pp.Number = match.Groups[1].Value;
pp.Value = match.Groups[2].Value;
pp.IsEnabled = (match.Groups[3].Value == "ON");
list.Add(pp);
}
}
return list;
}
public static int? ParseActivityCount(string response) {
int count;
if (int.TryParse(response.Trim(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out count))
{
return count;
}
return null;
}
public static double? DecodeRpm(string response) {
Match match = RpmRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
int hexVal = Convert.ToInt32(hexStr, 16);
return hexVal / 4.0;
}
return null;
}
public static int? DecodeSpeed(string response) {
Match match = SpeedRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
return Convert.ToInt32(hexStr, 16);
}
return null;
}
public static int? DecodeCoolantTemperature(string response) {
Match match = CoolantRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
return Convert.ToInt32(hexStr, 16) - 40;
}
return null;
}
public static double? DecodeEngineLoad(string response) {
Match match = LoadRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
int hexVal = Convert.ToInt32(hexStr, 16);
return Math.Round((hexVal * 100.0) / 255.0, 1);
}
return null;
}
public static double? DecodeThrottlePosition(string response) {
Match match = ThrottleRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
int hexVal = Convert.ToInt32(hexStr, 16);
return Math.Round((hexVal * 100.0) / 255.0, 1);
}
return null;
}
public static int? DecodeIntakeAirTemperature(string response) {
Match match = IatRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
return Convert.ToInt32(hexStr, 16) - 40;
}
return null;
}
public static double? DecodeFuelTrim(string response) {
Match match = FuelTrimRegex.Match(response);
if (match.Success)
{
string hexStr = match.Groups[1].Value.Replace(" ", "");
int hexVal = Convert.ToInt32(hexStr, 16);
return Math.Round(((hexVal - 128) * 100.0) / 128.0, 2);
}
return null;
}
}
public class Elm327Cpu: IDisposable {
public Elm327Cpu(string portName, int baudRate = 38400) {
}
public void Dispose() {
}
public bool Connect() {
return true;
}
public string RESET() {
return Execute("AT Z");
}
public string WST() {
return Execute("AT WS");
}
public string SETD() {
return Execute("AT D");
}
public string LPM() {
return Execute("AT LP");
}
public string CLRE() {
return Execute("AT FE");
}
public string ECHO(int mode) {
return Execute(string.Format("AT E{0}", mode));
}
public string LFEN(int mode) {
return Execute(string.Format("AT L{0}", mode));
}
public string MEM(int mode) {
return Execute(string.Format("AT M{0}", mode));
}
public string SPCO(int mode) {
return Execute(string.Format("AT S{0}", mode));
}
public string RESP(int mode) {
return Execute(string.Format("AT R{0}", mode));
}
public string RDI() {
return Execute("AT I");
}
public string RDIGN() {
return Execute("AT IGN");
}
public string RDV() {
return Execute("AT RV");
}
public string RDDSC() {
return Execute("AT @1");
}
public string RDID() {
return Execute("AT @2");
}
public string MEMID(string text12Char) {
return Execute(string.Format("AT @3 {0}", text12Char));
}
public string BRD(string hexHh) {
return Execute(string.Format("AT BRD {0}", hexHh));
}
public string BRT(string hexHh) {
return Execute(string.Format("AT BRT {0}", hexHh));
}
public string STDAT(string hexHh) {
return Execute(string.Format("AT SD {0}", hexHh));
}
public string RDDAT() {
return Execute("AT RD");
}
public string PPSET(string hexXx, string mode) {
return Execute(string.Format("AT PP {0} {1}", hexXx, mode));
}
public string PPSET_VAL(string hexXx, string hexYy) {
return Execute(string.Format("AT PP {0} SV {1}", hexXx, hexYy));
}
public string RD_PPS() {
return Execute("AT PPS");
}
public string CALV(string dddd) {
return Execute(string.Format("AT CV {0}", dddd));
}
public string SETP(string h) {
return Execute(string.Format("AT SP {0}", h));
}
public string SETPA(string h) {
return Execute(string.Format("AT SP A{0}", h));
}
public string DELP() {
return Execute("AT SP 00");
}
public string TRYP(string h) {
return Execute(string.Format("AT TP {0}", h));
}
public string TRYPA(string h) {
return Execute(string.Format("AT TP A{0}", h));
}
public string GETP() {
return Execute("AT DP");
}
public string GETPN() {
return Execute("AT DPN");
}
public string ENDP() {
return Execute("AT PC");
}
public string STDS() {
return Execute("AT SS");
}
public string ADPT(int mode) {
return Execute(string.Format("AT AT{0}", mode));
}
public string SETTO(string hexHh) {
return Execute(string.Format("AT ST {0}", hexHh));
}
public string HDREN(int mode) {
return Execute(string.Format("AT H{0}", mode));
}
public string STHDR(string hexId) {
return Execute(string.Format("AT SH {0}", hexId));
}
public string STRA(string hexHh) {
return Execute(string.Format("AT RA {0}", hexHh));
}
public string SRX(string hexHh) {
return Execute(string.Format("AT SR {0}", hexHh));
}
public string STTA(string hexHh) {
return Execute(string.Format("AT TA {0}", hexHh));
}
public string LENL() {
return Execute("AT AL");
}
public string LENN() {
return Execute("AT NL");
}
public string MONA() {
return Execute("AT MA");
}
public string MONR(string hexHh) {
return Execute(string.Format("AT MR {0}", hexHh));
}
public string MONT(string hexHh) {
return Execute(string.Format("AT MT {0}", hexHh));
}
public string RDAMC() {
return Execute("AT AMC");
}
public string STAMT(string hexHh) {
return Execute(string.Format("AT AMT {0}", hexHh));
}
public string DMPB() {
return Execute("AT BD");
}
public string BYPI() {
return Execute("AT BI");
}
public string REQ(string obdPidCommand) {
return Execute(obdPidCommand);
}
private string Execute(string command) {
try
{
ECUsim sim = new ECUsim();
string response = sim.talk(command);
return response.Replace(">", "").Trim();
}
catch
{
return "ERROR";
}
}
}
class Program {
static void Main(string[] args) {
using (Elm327Cpu elm = new Elm327Cpu("COM3", 38400))
{
if (!elm.Connect())
{
Console.WriteLine("接続に失敗しました。エンターキーで終了します。");
Console.ReadLine();
return;
}
//Console.WriteLine(" ELM327 アセンブラ・シェル型インタプリタ (.NET 4互換)");
Console.WriteLine(" [使い方] ニーモニックを入力してください。(例: RESET, RDV, REQ 010C)");
Console.WriteLine(" [終了] EXIT と入力すると終了します。");
while (true)
{
Console.Write("\nELM327_ASM> ");
string input = Console.ReadLine();
if (input == null)
continue;
input = input.Trim();
if (string.IsNullOrEmpty(input))
continue;
if (input.Equals("EXIT", StringComparison.OrdinalIgnoreCase))
break;
ExecuteMnemonicLine(elm, input);
}
}
}
static void ExecuteMnemonicLine(Elm327Cpu elm, string inputLine) {
string[] parts = inputLine.Split(new[] {
' '
}, 2, StringSplitOptions.RemoveEmptyEntries);
string mnemonic = parts[0].ToUpper();
string argument = parts.Length > 1 ? parts[1].Trim() : string.Empty;
string rawResponse = "";
try
{
switch (mnemonic)
{
case "RESET":
rawResponse = elm.RESET();
break;
case "WST":
rawResponse = elm.WST();
break;
case "SETD":
rawResponse = elm.SETD();
break;
case "LPM":
rawResponse = elm.LPM();
break;
case "CLRE":
rawResponse = elm.CLRE();
break;
case "RDI":
rawResponse = elm.RDI();
break;
case "RDIGN":
rawResponse = elm.RDIGN();
break;
case "RDV":
rawResponse = elm.RDV();
break;
case "RDDSC":
rawResponse = elm.RDDSC();
break;
case "RDID":
rawResponse = elm.RDID();
break;
case "RDDAT":
rawResponse = elm.RDDAT();
break;
case "RD_PPS":
rawResponse = elm.RD_PPS();
break;
case "GETP":
rawResponse = elm.GETP();
break;
case "GETPN":
rawResponse = elm.GETPN();
break;
case "ENDP":
rawResponse = elm.ENDP();
break;
case "STDS":
rawResponse = elm.STDS();
break;
case "LENL":
rawResponse = elm.LENL();
break;
case "LENN":
rawResponse = elm.LENN();
break;
case "MONA":
rawResponse = elm.MONA();
break;
case "RDAMC":
rawResponse = elm.RDAMC();
break;
case "DMPB":
rawResponse = elm.DMPB();
break;
case "BYPI":
rawResponse = elm.BYPI();
break;
case "ECHO":
rawResponse = elm.ECHO(int.Parse(argument));
break;
case "LFEN":
rawResponse = elm.LFEN(int.Parse(argument));
break;
case "MEM":
rawResponse = elm.MEM(int.Parse(argument));
break;
case "SPCO":
rawResponse = elm.SPCO(int.Parse(argument));
break;
case "RESP":
rawResponse = elm.RESP(int.Parse(argument));
break;
case "HDREN":
rawResponse = elm.HDREN(int.Parse(argument));
break;
case "ADPT":
rawResponse = elm.ADPT(int.Parse(argument));
break;
case "SETP":
rawResponse = elm.SETP(argument);
break;
case "SETPA":
rawResponse = elm.SETPA(argument);
break;
case "TRYP":
rawResponse = elm.TRYP(argument);
break;
case "TRYPA":
rawResponse = elm.TRYPA(argument);
break;
case "BRD":
rawResponse = elm.BRD(argument);
break;
case "BRT":
rawResponse = elm.BRT(argument);
break;
case "STDAT":
rawResponse = elm.STDAT(argument);
break;
case "CALV":
rawResponse = elm.CALV(argument);
break;
case "SETTO":
rawResponse = elm.SETTO(argument);
break;
case "STHDR":
rawResponse = elm.STHDR(argument);
break;
case "STRA":
rawResponse = elm.STRA(argument);
break;
case "SRX":
rawResponse = elm.SRX(argument);
break;
case "STTA":
rawResponse = elm.STTA(argument);
break;
case "MONR":
rawResponse = elm.MONR(argument);
break;
case "MONT":
rawResponse = elm.MONT(argument);
break;
case "STAMT":
rawResponse = elm.STAMT(argument);
break;
case "MEMID":
rawResponse = elm.MEMID(argument);
break;
case "REQ":
rawResponse = elm.REQ(argument);
break;
case "PPSET":
string[] ppArgs = argument.Split(new[] {
' '
}, 2);
if (ppArgs[1].ToUpper() == "SV")
{
string[] svArgs = ppArgs[1].Split(new[] {
' '
}, 2);
rawResponse = elm.PPSET_VAL(ppArgs[0], svArgs[1]);
}
else
{
rawResponse = elm.PPSET(ppArgs[0], ppArgs[1].ToUpper());
}
break;
default:
Console.WriteLine(string.Format("[エラー] 未知のニーモニック命令です: '{0}'", mnemonic));
return;
}
PrintResponseWithDecode(mnemonic, rawResponse);
}
catch (Exception ex)
{
Console.WriteLine(string.Format("[パースエラー] 入力形式を確認してください: {0}", ex.Message));
}
}
static void PrintResponseWithDecode(string mnemonic, string rawResponse) {
Console.WriteLine(string.Format("-> [Raw Response]: {0}", rawResponse.Replace("\n", " / ")));
switch (mnemonic)
{
case "RDV":
double? v = Elm327Decoder.ParseVoltage(rawResponse);
if (v.HasValue)
Console.WriteLine(string.Format(" => [自動解析] 電圧: {0:F2} V", v.Value));
break;
case "RDIGN":
bool? ign = Elm327Decoder.ParseIgnition(rawResponse);
if (ign.HasValue)
Console.WriteLine(string.Format(" => [自動解析] イグニッション: {0}", ign.Value ? "ON" : "OFF"));
break;
case "GETP":
case "GETPN":
ProtocolInfo? proto = Elm327Decoder.ParseProtocol(rawResponse);
if (proto.HasValue)
Console.WriteLine(string.Format(" => [自動解析] プロトコル: {0} (Auto:{1})", proto.Value.Name, proto.Value.IsAuto));
break;
case "REQ":
string compacted = rawResponse.Replace(" ", "");
if (compacted.Contains("410C"))
{
double? rpm = Elm327Decoder.DecodeRpm(rawResponse);
if (rpm.HasValue)
Console.WriteLine(string.Format(" => [自動解析] エンジン回転数: {0:F0} RPM", rpm.Value));
}
else if (compacted.Contains("410D"))
{
int? speed = Elm327Decoder.DecodeSpeed(rawResponse);
if (speed.HasValue)
Console.WriteLine(string.Format(" => [自動解析] 車速: {0} km/h", speed.Value));
}
else if (compacted.Contains("4105"))
{
int? coolant = Elm327Decoder.DecodeCoolantTemperature(rawResponse);
if (coolant.HasValue)
Console.WriteLine(string.Format(" => [自動解析] エンジン水温: {0} °C", coolant.Value));
}
else if (compacted.Contains("4104"))
{
double? load = Elm327Decoder.DecodeEngineLoad(rawResponse);
if (load.HasValue)
Console.WriteLine(string.Format(" => [自動解析] エンジン負荷: {0:F1} %", load.Value));
}
else if (compacted.Contains("4111"))
{
double? throttle = Elm327Decoder.DecodeThrottlePosition(rawResponse);
if (throttle.HasValue)
Console.WriteLine(string.Format(" => [自動解析] スロットル開度: {0:F1} %", throttle.Value));
}
else if (compacted.Contains("410F"))
{
int? iat = Elm327Decoder.DecodeIntakeAirTemperature(rawResponse);
if (iat.HasValue)
Console.WriteLine(string.Format(" => [自動解析] 吸気温度: {0} °C", iat.Value));
}
else if (compacted.Contains("4106") || compacted.Contains("4107") || compacted.Contains("4108") || compacted.Contains("4109"))
{
double? fuelTrim = Elm327Decoder.DecodeFuelTrim(rawResponse);
if (fuelTrim.HasValue)
Console.WriteLine(string.Format(" => [自動解析] 燃料トリム: {0:F2} %", fuelTrim.Value));
}
break;
}
}
}
}
以上。