summaryrefslogtreecommitdiff
path: root/obdlogger/OBD.cpp
blob: 55f31e66e5c89675ce130442d9079dd73324c708 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
/*************************************************************************
* OBD-II (ELM327) data accessing library for Arduino
* Distributed under GPL v2.0
* Copyright (c) 2012 Stanley Huang <stanleyhuangyc@gmail.com>
* All rights reserved.
*************************************************************************/

#include <Arduino.h>
#include <avr/pgmspace.h>
#include "OBD.h"

#define INIT_CMD_COUNT 4
#define MAX_CMD_LEN 6

const char PROGMEM s_initcmd[INIT_CMD_COUNT][MAX_CMD_LEN] = {"ATZ\r","ATE0\r","ATL1\r","ATI\r"};
const char PROGMEM s_searching[] = "SEARCHING";
const char PROGMEM s_cmd_fmt[] = "%02X%02X 1\r";
const char PROGMEM s_cmd_sleep[] = "atlp\r";
const char PROGMEM s_cmd_vin[] = "0902\r";
const char PROGMEM s_response_begin[] = "41 ";

unsigned int hex2uint16(const char *p)
{
	char c = *p;
	unsigned int i = 0;
	for (char n = 0; c && n < 4; c = *(++p)) {
		if (c >= 'A' && c <= 'F') {
			c -= 7;
		} else if (c>='a' && c<='f') {
			c -= 39;
        } else if (c == ' ') {
            continue;
        } else if (c < '0' || c > '9') {
			break;
        }
		i = (i << 4) | (c & 0xF);
		n++;
	}
	return i;
}

unsigned char hex2uint8(const char *p)
{
	unsigned char c1 = *p;
	unsigned char c2 = *(p + 1);
	if (c1 >= 'A' && c1 <= 'F')
		c1 -= 7;
	else if (c1 >='a' && c1 <= 'f')
	    c1 -= 39;
	else if (c1 < '0' || c1 > '9')
		return 0;

	if (c2 >= 'A' && c2 <= 'F')
		c2 -= 7;
	else if (c2 >= 'a' && c2 <= 'f')
	    c2 -= 39;
	else if (c2 < '0' || c2 > '9')
		return 0;

	return c1 << 4 | (c2 & 0xf);
}

void COBD::Query(unsigned char pid)
{
	char cmd[8];
	sprintf_P(cmd, s_cmd_fmt, dataMode, pid);
	write(cmd);
}

bool COBD::ReadSensor(byte pid, int& result, bool passive)
{
	// send a query command
	Query(pid);
	// wait for reponse
	bool hasData;
	unsigned long tick = millis();
	do {
		DataIdleLoop();
	} while (!(hasData = available()) && millis() - tick < OBD_TIMEOUT_SHORT);
	if (!hasData) {
		errors++;
		return false;
	}
	// receive and parse the response
	return GetResponseParsed(pid, result);
}

bool COBD::available()
{
	return OBDUART.available();
}

char COBD::read()
{
	return OBDUART.read();
}

void COBD::write(const char* s)
{
	OBDUART.write(s);
}

void COBD::write(const char c)
{
	OBDUART.write(c);
}

int COBD::GetConvertedValue(byte pid, char* data)
{
	int result;
	switch (pid) {
	case PID_RPM:
		result = GetLargeValue(data) >> 2;
		break;
	case PID_FUEL_PRESSURE:
		result = GetSmallValue(data) * 3;
		break;
	case PID_COOLANT_TEMP:
	case PID_INTAKE_TEMP:
	case PID_AMBIENT_TEMP:
		result = GetTemperatureValue(data);
		break;
	case PID_ABS_ENGINE_LOAD:
		result = GetLargeValue(data) * 100 / 255;
		break;
	case PID_MAF_FLOW:
		result = GetLargeValue(data) / 100;
		break;
	case PID_THROTTLE:
	case PID_ENGINE_LOAD:
	case PID_FUEL_LEVEL:
		result = GetPercentageValue(data);
		break;
	case PID_TIMING_ADVANCE:
		result = (GetSmallValue(data) - 128) >> 1;
		break;
	case PID_DISTANCE:
	case PID_RUNTIME:
		result = GetLargeValue(data);
		break;
	default:
		result = GetSmallValue(data);
	}
	return result;
}

char* COBD::GetResponse(byte& pid, char* buffer)
{
	unsigned long startTime = millis();
	byte i = 0;

	for (;;) {
		if (available()) {
			char c = read();
			buffer[i] = c;
			if (++i == OBD_RECV_BUF_SIZE - 1) {
			    // buffer overflow
			    break;
			}
			if (c == '>' && i > 6) {
				// prompt char reached
				break;
			}
		} else {
			buffer[i] = 0;
			unsigned int timeout;
			if (dataMode != 1 || strstr_P(buffer, s_searching)) {
				timeout = OBD_TIMEOUT_LONG;
			} else {
				timeout = OBD_TIMEOUT_SHORT;
			}
			if (millis() - startTime > timeout) {
				// timeout
				errors++;
				break;
			}
			DataIdleLoop();
		}
	}
	buffer[i] = 0;

	char *p = buffer;
	while ((p = strstr_P(p, s_response_begin))) {
		p += 3;
		byte curpid = hex2uint8(p);
		if (pid == 0) pid = curpid;
		if (curpid == pid) {
			errors = 0;
			p += 2;
			if (*p == ' ')
			    return p + 1;
		}
	}
	return 0;
}

bool COBD::GetResponseParsed(byte& pid, int& result)
{
	char buffer[OBD_RECV_BUF_SIZE];
	char* data = GetResponse(pid, buffer);
	if (!data) {
		// try recover next time
		write('\r');
		return false;
	}
	result = GetConvertedValue(pid, data);
	return true;
}

void COBD::Sleep(int seconds)
{
	char cmd[MAX_CMD_LEN];
	strcpy_P(cmd, s_cmd_sleep);
	write(cmd);
	if (seconds) {
		delay((unsigned long)seconds << 10);
		write('\r');
	}
}

bool COBD::IsValidPID(byte pid)
{
	if (pid >= 0x7f)
		return false;
	pid--;
	byte i = pid >> 3;
	byte b = 0x80 >> (pid & 0x7);
	return pidmap[i] & b;
}

bool COBD::Init(bool passive)
{
	unsigned long currentMillis;
	unsigned char n;
	char prompted;
	char buffer[OBD_RECV_BUF_SIZE];

	for (unsigned char i = 0; i < INIT_CMD_COUNT; i++) {
		if (!passive) {
			char cmd[MAX_CMD_LEN];
			strcpy_P(cmd, s_initcmd[i]);
			write(cmd);
		}
		n = 0;
		prompted = 0;
		currentMillis = millis();
		for (;;) {
			if (available()) {
				char c = read();
				if (c == '>') {
				    buffer[n] = 0;
				    prompted++;
				} else if (n < OBD_RECV_BUF_SIZE - 1) {
				    buffer[n++] = c;
				}
			} else if (prompted) {
				break;
			} else {
				unsigned long elapsed = millis() - currentMillis;
				if (elapsed > OBD_TIMEOUT_INIT) {
					// init timeout
					//WriteData("\r");
					return false;
				}
				InitIdleLoop();
			}
		}
	}

	// load pid map
	memset(pidmap, 0, sizeof(pidmap));
	for (byte i = 0; i < 4; i++) {
	byte pid = i * 0x20;
	Query(pid);
	char* data = GetResponse(pid, buffer);
	if (!data) break;
	data--;
	for (byte n = 0; n < 4; n++) {
	    if (data[n * 3] != ' ')
	        break;
	    pidmap[i * 4 + n] = hex2uint8(data + n * 3 + 1);
	}
	}
	errors = 0;
	return true;
}