0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概要

elm327の研究。
atコマンドをそのまま打つのは、むずいので、アセンブラを考案してみた。
ELM327をCPUと見立てて、ニーモニックを組み立てた。
まずは、ECUシミュレータ組んで、動作を確認する。
41が返るのは、ライブデータなので、対応する。
NeoLuaを導入する。

動作確認

>elmlua2
--- Neo.IronLua ELM327 ホスト起動 ---
shell.lua が見つからないため、インライン起動します。
--- ELM327 Lua Shell Loaded ---
[使い方] ニーモニックを入力してください。(例: RESET, RDV, REQ 010C)
[終了] EXIT と入力すると終了します。
ELM327_LUA> RESET
ELM327 v1.5
ELM327_LUA> RDV
12.4V
ELM327_LUA> RDI
ELM327 v1.5
ELM327_LUA> EXIT

サンプルコード



using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text.RegularExpressions;
using System.IO;
using Neo.IronLua;

namespace Elm327App
{
	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) + " ";
			}
			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 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 double? DecodeRpm(string response) {
			Match match = RpmRegex.Match(response);
			if (match.Success)
				return Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16) / 4.0;
			return null;
		}
		public static int? DecodeSpeed(string response) {
			Match match = SpeedRegex.Match(response);
			if (match.Success)
				return Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16);
			return null;
		}
		public static int? DecodeCoolantTemperature(string response) {
			Match match = CoolantRegex.Match(response);
			if (match.Success)
				return Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16) - 40;
			return null;
		}
		public static double? DecodeEngineLoad(string response) {
			Match match = LoadRegex.Match(response);
			if (match.Success)
				return Math.Round((Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16) * 100.0) / 255.0, 1);
			return null;
		}
		public static double? DecodeThrottlePosition(string response) {
			Match match = ThrottleRegex.Match(response);
			if (match.Success)
				return Math.Round((Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16) * 100.0) / 255.0, 1);
			return null;
		}
		public static int? DecodeIntakeAirTemperature(string response) {
			Match match = IatRegex.Match(response);
			if (match.Success)
				return Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16) - 40;
			return null;
		}
		public static double? DecodeFuelTrim(string response) {
			Match match = FuelTrimRegex.Match(response);
			if (match.Success)
				return Math.Round(((Convert.ToInt32(match.Groups[1].Value.Replace(" ", ""), 16) - 128) * 100.0) / 128.0, 2);
			return null;
		}
	}
	public class Elm327Cpu : IDisposable {
		private readonly ECUsim _sim;
		private bool _disposed;
		private bool _isConnected;
		public bool IsConnected {
			get {
				return _isConnected;
			}
			private set {
				_isConnected = value;
			}
		}
		public Elm327Cpu(string portName, int baudRate = 38400) {
			_sim = new ECUsim();
		}
		public string ExecuteMnemonic(string cmd, string arg = null) {
			var method = this.GetType().GetMethod(cmd, System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
			if (method == null) 
				return string.Format("Unknown Mnemonic: {0}", cmd); 
			var parameters = method.GetParameters();
			if (parameters.Length == 0)
			{
				var result = method.Invoke(this, null);
				return result != null ? result.ToString() : null;
			}
			else if (parameters.Length == 1 && arg != null)
			{
				var result = method.Invoke(this, new object[] { arg });
				return result != null ? result.ToString() : null;
			}
			return "Invalid arguments count";
		}
		public bool Connect() {
			_isConnected = true;
			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) {
			if (_disposed) 
				throw new ObjectDisposedException("Elm327Cpu");
			try
			{
				string response = _sim.talk(command);
				if (response == null) 
					return "ERROR";
				return response.Replace(">", "").Trim();
			}
			catch
			{
				return "ERROR";
			}
		}
		public void Dispose() {
			Dispose(true);
			GC.SuppressFinalize(this);
		}
		protected virtual void Dispose(bool disposing) {
			if (!_disposed)
			{
				if (disposing)
				{
					IDisposable disposableSim = _sim as IDisposable;
					if (disposableSim != null)
					{
						disposableSim.Dispose();
					}
				}
				_disposed = true;
				_isConnected = false;
			}
		}
	}
	class Program {
		private static readonly string DefaultLuaScript = @"
-- shell.lua
print('--- ELM327 Lua Shell Loaded ---')
print('[使い方] ニーモニックを入力してください。(例: RESET, RDV, REQ 010C)')
print('[終了] EXIT と入力すると終了します。')
-- local cpu = cpu or host or elm or elm327
local cpu = elm
while true do
	io.write('ELM327_LUA> ')
	local input = io.read()
	if input == nil or input == 'EXIT' then
		break
	end
	-- インラインスクリプト内の while ループ内修正版
	if input ~= '' then
		local args = {}
		for word in string.gmatch(input, '%S+') do
			table.insert(args, word)
		end
		local cmd = args[1]
		local arg = args[2] -- なければ nil になる
		-- コマンドが大文字小文字混じりの場合、一応ここで EXIT 判定
		if cmd == 'EXIT' then
			break
		end
		if cpu then
			-- 修正:コロン構文を使い、pcall には関数と引数をそのまま渡す
			local status, result = pcall(function() return cpu:ExecuteMnemonic(cmd, arg) end)
			if status then
				print(result)
			else
				print('ERROR (Lua Execution): ' .. tostring(result))
			end
		else
			print('Error: cpu object is not registered.')
		end
	end
end
		";
		static void Main(string[] args) {
			using (Lua lua = new Lua())
			{
				LuaGlobal env = lua.CreateEnvironment();
				using (Elm327Cpu elm = new Elm327Cpu("COM3", 38400))
				{
					if (!elm.Connect())
					{
						Console.WriteLine("接続に失敗しました。");
						return;
					}
					env["elm"] = elm;
					env["Decoder"] = typeof(Elm327Decoder);
					Console.WriteLine("--- Neo.IronLua ELM327 ホスト起動 ---");
					string luaScriptPath = "shell.lua";
					if (File.Exists(luaScriptPath))
					{
						env.DoChunk(luaScriptPath);
					}
					else
					{
						Console.WriteLine(string.Format("{0} が見つからないため、インライン起動します。", luaScriptPath));
						env.DoChunk(DefaultLuaScript, "inline.lua");
					}
				}
			}
		}
	}
}



-

以上。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?