1 /*
2  * Copyright (c) 2018 Prevas A/S
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <zephyr/drivers/i2c.h>
8 #include <zephyr/shell/shell.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <zephyr/sys/byteorder.h>
12 #include <zephyr/sys/util.h>
13 
14 #include <zephyr/logging/log.h>
15 LOG_MODULE_REGISTER(i2c_shell, CONFIG_LOG_DEFAULT_LEVEL);
16 
17 #define MAX_BYTES_FOR_REGISTER_INDEX	4
18 #define ARGV_DEV	1
19 #define ARGV_ADDR	2
20 #define ARGV_REG	3
21 
22 /* Maximum bytes we can write or read at once */
23 #define MAX_I2C_BYTES	16
24 
get_bytes_count_for_hex(char * arg)25 static int get_bytes_count_for_hex(char *arg)
26 {
27 	int length = (strlen(arg) + 1) / 2;
28 
29 	if (length > 1 && arg[0] == '0' && (arg[1] == 'x' || arg[1] == 'X')) {
30 		length -= 1;
31 	}
32 
33 	return MIN(MAX_BYTES_FOR_REGISTER_INDEX, length);
34 }
35 
36 /*
37  * This sends I2C messages without any data (i.e. stop condition after
38  * sending just the address). If there is an ACK for the address, it
39  * is assumed there is a device present.
40  *
41  * WARNING: As there is no standard I2C detection command, this code
42  * uses arbitrary SMBus commands (namely SMBus quick write and SMBus
43  * receive byte) to probe for devices.  This operation can confuse
44  * your I2C bus, cause data loss, and is known to corrupt the Atmel
45  * AT24RF08 EEPROM found on many IBM Thinkpad laptops.
46  *
47  * https://manpages.debian.org/buster/i2c-tools/i2cdetect.8.en.html
48  */
49 /* i2c scan <device> */
cmd_i2c_scan(const struct shell * shell_ctx,size_t argc,char ** argv)50 static int cmd_i2c_scan(const struct shell *shell_ctx,
51 			size_t argc, char **argv)
52 {
53 	const struct device *dev;
54 	uint8_t cnt = 0, first = 0x04, last = 0x77;
55 
56 	dev = device_get_binding(argv[ARGV_DEV]);
57 
58 	if (!dev) {
59 		shell_error(shell_ctx, "I2C: Device driver %s not found.",
60 			    argv[ARGV_DEV]);
61 		return -ENODEV;
62 	}
63 
64 	shell_print(shell_ctx,
65 		    "     0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f");
66 	for (uint8_t i = 0; i <= last; i += 16) {
67 		shell_fprintf(shell_ctx, SHELL_NORMAL, "%02x: ", i);
68 		for (uint8_t j = 0; j < 16; j++) {
69 			if (i + j < first || i + j > last) {
70 				shell_fprintf(shell_ctx, SHELL_NORMAL, "   ");
71 				continue;
72 			}
73 
74 			struct i2c_msg msgs[1];
75 			uint8_t dst;
76 
77 			/* Send the address to read from */
78 			msgs[0].buf = &dst;
79 			msgs[0].len = 0U;
80 			msgs[0].flags = I2C_MSG_WRITE | I2C_MSG_STOP;
81 			if (i2c_transfer(dev, &msgs[0], 1, i + j) == 0) {
82 				shell_fprintf(shell_ctx, SHELL_NORMAL,
83 					      "%02x ", i + j);
84 				++cnt;
85 			} else {
86 				shell_fprintf(shell_ctx, SHELL_NORMAL, "-- ");
87 			}
88 		}
89 		shell_print(shell_ctx, "");
90 	}
91 
92 	shell_print(shell_ctx, "%u devices found on %s",
93 		    cnt, argv[ARGV_DEV]);
94 
95 	return 0;
96 }
97 
98 /* i2c recover <device> */
cmd_i2c_recover(const struct shell * shell_ctx,size_t argc,char ** argv)99 static int cmd_i2c_recover(const struct shell *shell_ctx,
100 			   size_t argc, char **argv)
101 {
102 	const struct device *dev;
103 	int err;
104 
105 	dev = device_get_binding(argv[ARGV_DEV]);
106 	if (!dev) {
107 		shell_error(shell_ctx, "I2C: Device driver %s not found.",
108 			    argv[1]);
109 		return -ENODEV;
110 	}
111 
112 	err = i2c_recover_bus(dev);
113 	if (err) {
114 		shell_error(shell_ctx, "I2C: Bus recovery failed (err %d)",
115 			    err);
116 		return err;
117 	}
118 
119 	return 0;
120 }
121 
i2c_write_from_buffer(const struct shell * shell_ctx,char * s_dev_name,char * s_dev_addr,char * s_reg_addr,char ** data,uint8_t data_length)122 static int i2c_write_from_buffer(const struct shell *shell_ctx,
123 		char *s_dev_name, char *s_dev_addr, char *s_reg_addr,
124 		char **data, uint8_t data_length)
125 {
126 	/* This buffer must preserve 4 bytes for register address, as it is
127 	 * filled using put_be32 function and we don't want to lower available
128 	 * space when using 1 byte address.
129 	 */
130 	uint8_t buf[MAX_I2C_BYTES + MAX_BYTES_FOR_REGISTER_INDEX - 1];
131 	const struct device *dev;
132 	int reg_addr_bytes;
133 	int reg_addr;
134 	int dev_addr;
135 	int ret;
136 	int i;
137 
138 	dev = device_get_binding(s_dev_name);
139 	if (!dev) {
140 		shell_error(shell_ctx, "I2C: Device driver %s not found.",
141 			    s_dev_name);
142 		return -ENODEV;
143 	}
144 
145 	dev_addr = strtol(s_dev_addr, NULL, 16);
146 	reg_addr = strtol(s_reg_addr, NULL, 16);
147 
148 	reg_addr_bytes = get_bytes_count_for_hex(s_reg_addr);
149 	sys_put_be32(reg_addr, buf);
150 
151 	if (data_length + reg_addr_bytes > MAX_I2C_BYTES) {
152 		data_length = MAX_I2C_BYTES - reg_addr_bytes;
153 		shell_info(shell_ctx, "Too many bytes provided, limit is %d",
154 			   MAX_I2C_BYTES - reg_addr_bytes);
155 	}
156 
157 	for (i = 0; i < data_length; i++) {
158 		buf[MAX_BYTES_FOR_REGISTER_INDEX + i] =
159 			(uint8_t)strtol(data[i], NULL, 16);
160 	}
161 
162 	ret = i2c_write(dev,
163 			buf + MAX_BYTES_FOR_REGISTER_INDEX - reg_addr_bytes,
164 			reg_addr_bytes + data_length, dev_addr);
165 	if (ret < 0) {
166 		shell_error(shell_ctx, "Failed to write to device: %s",
167 			    s_dev_addr);
168 		return -EIO;
169 	}
170 
171 	return 0;
172 }
173 
174 /* i2c write <device> <dev_addr> <reg_addr> [<byte1>, ...] */
cmd_i2c_write(const struct shell * shell_ctx,size_t argc,char ** argv)175 static int cmd_i2c_write(const struct shell *shell_ctx,
176 			 size_t argc, char **argv)
177 {
178 	return i2c_write_from_buffer(shell_ctx, argv[ARGV_DEV],
179 				     argv[ARGV_ADDR], argv[ARGV_REG],
180 				     &argv[4], argc - 4);
181 }
182 
183 /* i2c write_byte <device> <dev_addr> <reg_addr> <value> */
cmd_i2c_write_byte(const struct shell * shell_ctx,size_t argc,char ** argv)184 static int cmd_i2c_write_byte(const struct shell *shell_ctx,
185 			      size_t argc, char **argv)
186 {
187 	return i2c_write_from_buffer(shell_ctx, argv[ARGV_DEV],
188 				     argv[ARGV_ADDR], argv[ARGV_REG],
189 				     &argv[4], 1);
190 }
191 
i2c_read_to_buffer(const struct shell * shell_ctx,char * s_dev_name,char * s_dev_addr,char * s_reg_addr,uint8_t * buf,uint8_t buf_length)192 static int i2c_read_to_buffer(const struct shell *shell_ctx,
193 			      char *s_dev_name,
194 			      char *s_dev_addr, char *s_reg_addr,
195 			      uint8_t *buf, uint8_t buf_length)
196 {
197 	const struct device *dev;
198 	int dev_addr;
199 	int ret;
200 
201 	dev = device_get_binding(s_dev_name);
202 	if (!dev) {
203 		shell_error(shell_ctx, "I2C: Device driver %s not found.",
204 			    s_dev_name);
205 		return -ENODEV;
206 	}
207 
208 	dev_addr = strtol(s_dev_addr, NULL, 16);
209 
210 	if (s_reg_addr != NULL) {
211 		uint8_t reg_addr_buf[MAX_BYTES_FOR_REGISTER_INDEX];
212 		int reg_addr_bytes;
213 		int reg_addr;
214 
215 		reg_addr = strtol(s_reg_addr, NULL, 16);
216 		reg_addr_bytes = get_bytes_count_for_hex(s_reg_addr);
217 		sys_put_be32(reg_addr, reg_addr_buf);
218 
219 		ret = i2c_write_read(dev, dev_addr,
220 				     reg_addr_buf + MAX_BYTES_FOR_REGISTER_INDEX - reg_addr_bytes,
221 				     reg_addr_bytes, buf, buf_length);
222 	} else {
223 		ret = i2c_read(dev, buf, buf_length, dev_addr);
224 	}
225 
226 	if (ret < 0) {
227 		shell_error(shell_ctx, "Failed to read from device: %s",
228 			    s_dev_addr);
229 		return -EIO;
230 	}
231 
232 	return 0;
233 }
234 
235 /* i2c read_byte <device> <dev_addr> <reg_addr> */
cmd_i2c_read_byte(const struct shell * shell_ctx,size_t argc,char ** argv)236 static int cmd_i2c_read_byte(const struct shell *shell_ctx,
237 			     size_t argc, char **argv)
238 {
239 	uint8_t out;
240 	int ret;
241 
242 
243 	ret = i2c_read_to_buffer(shell_ctx, argv[ARGV_DEV],
244 				 argv[ARGV_ADDR], argv[ARGV_REG], &out, 1);
245 	if (ret == 0) {
246 		shell_print(shell_ctx, "Output: 0x%x", out);
247 	}
248 
249 	return ret;
250 }
251 
252 /* i2c read <device> <dev_addr> <reg_addr> [<numbytes>] */
cmd_i2c_read(const struct shell * shell_ctx,size_t argc,char ** argv)253 static int cmd_i2c_read(const struct shell *shell_ctx, size_t argc, char **argv)
254 {
255 	uint8_t buf[MAX_I2C_BYTES];
256 	int num_bytes;
257 	int ret;
258 
259 	if (argc > 4) {
260 		num_bytes = strtol(argv[4], NULL, 16);
261 		if (num_bytes > MAX_I2C_BYTES) {
262 			num_bytes = MAX_I2C_BYTES;
263 		}
264 	} else {
265 		num_bytes = MAX_I2C_BYTES;
266 	}
267 
268 	ret = i2c_read_to_buffer(shell_ctx, argv[ARGV_DEV],
269 				 argv[ARGV_ADDR], argv[ARGV_REG],
270 				 buf, num_bytes);
271 	if (ret == 0) {
272 		shell_hexdump(shell_ctx, buf, num_bytes);
273 	}
274 
275 	return ret;
276 }
277 
278 /* i2c direct_read <device> <dev_addr> [<numbytes>] */
cmd_i2c_direct_read(const struct shell * shell_ctx,size_t argc,char ** argv)279 static int cmd_i2c_direct_read(const struct shell *shell_ctx, size_t argc, char **argv)
280 {
281 	uint8_t buf[MAX_I2C_BYTES];
282 	int num_bytes;
283 	int ret;
284 
285 	if (argc > 3) {
286 		num_bytes = strtol(argv[3], NULL, 16);
287 		if (num_bytes > MAX_I2C_BYTES) {
288 			num_bytes = MAX_I2C_BYTES;
289 		}
290 	} else {
291 		num_bytes = MAX_I2C_BYTES;
292 	}
293 
294 	ret = i2c_read_to_buffer(shell_ctx, argv[ARGV_DEV], argv[ARGV_ADDR], NULL, buf, num_bytes);
295 	if (ret == 0) {
296 		shell_hexdump(shell_ctx, buf, num_bytes);
297 	}
298 
299 	return ret;
300 }
301 
302 /* i2c speed <device> <speed>
303  * For: speed see constants like I2C_SPEED_STANDARD
304  */
cmd_i2c_speed(const struct shell * shell_ctx,size_t argc,char ** argv)305 static int cmd_i2c_speed(const struct shell *shell_ctx, size_t argc, char **argv)
306 {
307 	char *s_dev_name = argv[ARGV_DEV];
308 	const struct device *dev;
309 	uint32_t dev_config = 0;
310 	uint32_t speed;
311 	int ret;
312 
313 	dev = device_get_binding(s_dev_name);
314 	if (!dev) {
315 		shell_error(shell_ctx, "I2C: Device driver %s not found.",
316 			    s_dev_name);
317 		return -ENODEV;
318 	}
319 
320 	speed = strtol(argv[ARGV_DEV + 1], NULL, 10);
321 	ret = i2c_get_config(dev, &dev_config);
322 	if (ret == 0) {
323 		dev_config &= ~I2C_SPEED_MASK;
324 		dev_config |= I2C_SPEED_SET(speed);
325 	} else {
326 		/* Can't get current config. Fallback to something reasonable */
327 		dev_config = I2C_MODE_CONTROLLER | I2C_SPEED_SET(speed);
328 	}
329 
330 	ret = i2c_configure(dev, dev_config);
331 	if (ret < 0) {
332 		shell_error(shell_ctx, "I2C: Failed to configure device: %s",
333 			    s_dev_name);
334 		return -EIO;
335 	}
336 	return 0;
337 }
338 
device_name_get(size_t idx,struct shell_static_entry * entry)339 static void device_name_get(size_t idx, struct shell_static_entry *entry)
340 {
341 	const struct device *dev = shell_device_lookup(idx, NULL);
342 
343 	entry->syntax = (dev != NULL) ? dev->name : NULL;
344 	entry->handler = NULL;
345 	entry->help = NULL;
346 	entry->subcmd = NULL;
347 }
348 
349 SHELL_DYNAMIC_CMD_CREATE(dsub_device_name, device_name_get);
350 
351 SHELL_STATIC_SUBCMD_SET_CREATE(sub_i2c_cmds,
352 	SHELL_CMD_ARG(scan, &dsub_device_name,
353 		      "Scan I2C devices\n"
354 		      "Usage: scan <device>",
355 		      cmd_i2c_scan, 2, 0),
356 	SHELL_CMD_ARG(recover, &dsub_device_name,
357 		      "Recover I2C bus\n"
358 		      "Usage: recover <device>",
359 		      cmd_i2c_recover, 2, 0),
360 	SHELL_CMD_ARG(read, &dsub_device_name,
361 		      "Read bytes from an I2C device\n"
362 		      "Usage: read <device> <addr> <reg> [<bytes>]",
363 		      cmd_i2c_read, 4, 1),
364 	SHELL_CMD_ARG(read_byte, &dsub_device_name,
365 		      "Read a byte from an I2C device\n"
366 		      "Usage: read_byte <device> <addr> <reg>",
367 		      cmd_i2c_read_byte, 4, 0),
368 	SHELL_CMD_ARG(direct_read, &dsub_device_name,
369 		      "Read byte stream directly from an I2C device without "
370 		      "writing a register address first\n"
371 		      "Usage: direct_read <device> <addr> [<bytes>]",
372 		      cmd_i2c_direct_read, 3, 1),
373 	SHELL_CMD_ARG(write, &dsub_device_name,
374 		      "Write bytes to an I2C device\n"
375 		      "Usage: write <device> <addr> <reg> [<byte1>, ...]",
376 		      cmd_i2c_write, 4, MAX_I2C_BYTES),
377 	SHELL_CMD_ARG(write_byte, &dsub_device_name,
378 		      "Write a byte to an I2C device\n"
379 		      "Usage: write_byte <device> <addr> <reg> <value>",
380 		      cmd_i2c_write_byte, 5, 0),
381 	SHELL_CMD_ARG(speed, &dsub_device_name,
382 		      "Configure I2C bus speed\n"
383 		      "Usage: speed <device> <speed>",
384 		      cmd_i2c_speed, 3, 0),
385 	SHELL_SUBCMD_SET_END     /* Array terminated. */
386 );
387 
388 SHELL_CMD_REGISTER(i2c, &sub_i2c_cmds, "I2C commands", NULL);
389