0

I have a command

for i in {1..9} ; do cansend slcan0 "7e0#02090"$i"0000000000"

How can I send the same command but for $i send 4 bytes of HEX instead. Sort of like a brute force ?

BoarGules
  • 16,440
  • 2
  • 27
  • 44

2 Answers2

2

You can use the printf utility and %04x as a format specifier (0 pad, 4 characters, format as hex):

for i in {1..9}; do
  command=$(printf "7e0#02090%04x0000000000" $i)
  echo cansend slcan0 "$command"  # remove `echo` here :)
done

prints out

cansend slcan0 7e0#0209000010000000000
cansend slcan0 7e0#0209000020000000000
cansend slcan0 7e0#0209000030000000000
cansend slcan0 7e0#0209000040000000000
cansend slcan0 7e0#0209000050000000000
cansend slcan0 7e0#0209000060000000000
cansend slcan0 7e0#0209000070000000000
cansend slcan0 7e0#0209000080000000000
cansend slcan0 7e0#0209000090000000000
AKX
  • 152,115
  • 15
  • 115
  • 172
0

You could use brace expansion to generate a list of all 4-byte hex code sequences (00000000, 00000001, 00000002, …, FFFFFFFF).

{{0..9},{A..F}} generates the list 0 1 2 … F.
{{0..9},{A..F}}{{0..9},{A..F}} generates the list 00 0 02 … FF.
And so on.
For 4 bytes you have to repeat {{0..9},{A..F}} 8 times as every byte has two hex digits.

for i in {{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}{{0..9},{A..F}}; do
   cansend slcan0 "7e0#02090${i}0000000000"
done

While this approach might be viable for two or three digits I would strongly advise against using it in this case. Above script is not readable and very slow.

The next better thing in bash would be …

bytes=4
((max=2**(bytes*8)-1))
for ((i=0; i<max; i++)); do
   printf -v hex %08x "$i"
   cansend slcan0 "7e0#02090${hex}0000000000"
done

… but please keep in mind that this will be magnitudes slower than sending sequences from a (for instance) python program which doesn't have to start a new process each time you want to send something to slccan0.

Socowi
  • 25,550
  • 3
  • 32
  • 54
  • ok i appreciate the guidance. i am trying to achieve this in a much more efficient manner. i wasnt getting the connection to the ECU using slcan and python. but if you can offer any guidance on how to do it i am happy to try it – Faheem Adam Mar 14 '19 at 12:46
  • @FaheemAdam I cannot help you further than this. I have no idea what an ECU or any of that stuff is. I just thought, that maybe `cansend` offers a library interface to do the same thing from inside a regular program which would be faster than calling `cansend` over and over again from a bash script. – Socowi Mar 14 '19 at 13:10