#!/bin/bash

case "$1" in
	-w)
	if [ $# -ne 4 ]; then
  		echo "错误：需要提供4个参数，当前参数数量为 $#"
		echo "正确用法应该是: ./saturn-device-id.sh -w offsetaddress serialNo length"
  		exit 1
	fi

	input_address="$2"
	input_string="$3"
	input_length="$4"

	hex_string=$(printf "%s" "$input_string" | xxd -p)

	declare -a values

	for ((i = 0; i < ${#hex_string}; i += 2)); do
	        two_chars="${hex_string:i:2}"
		values+=("0x$two_chars")
	done

	i2cset_command="i2cset -y -f 3 0x50 $input_address"

	for element in "${values[@]}"; do
		i2cset_command="$i2cset_command $element"
	done


	i2cset_command="$i2cset_command i"

	eval "$i2cset_command"
	;;

	-r)
	if [ $# -ne 3 ]; then
  		echo "错误：需要提供3个参数，当前参数数量为 $#"
		echo "正确用法应该是: ./saturn-device-id.sh -r offsetaddress length"
  		exit 1
	fi
	input_address="$2"
	input_length="$3"	
	result=$(i2cget -y -f 3 0x50 $input_address i)
	ascii_chars=$(echo "$result" | xxd -r -p)
	serial=$(echo "$ascii_chars" | cut -c 1-"$input_length")
	echo "$serial"
	;;

	*)
	echo "参数错误 !!!"
	echo "正确用法应该是:"
	echo "./saturn-device-id.sh -w offsetaddress serialNo length"
	echo "./saturn-device-id.sh -r offsetaddress length"
	;;
esac	
