# STM32MP2x, version V1.0, Phytec 01.2026

detect_sensor_type() {

	if [ -z "$1" ] ; then
		INTERFACE="DCMIPP"
	else
		INTERFACE="$1"
	fi

	if [ -z "$2" ] ; then
		PIPE="ISP"
	else
		PIPE="$2"
	fi

	IFACE="$(echo "$INTERFACE" | awk '{print tolower($0)}')"
	IPIPE="$(echo "$PIPE" | awk '{print tolower($0)}')"

	CAM_DEV="/dev/cam-dcmipp"

	if [ -z "${CAM_DEV}" ] ; then
        	echo "No camera detected on interface ${IFACE}"
		exit 1
	fi

	CAP_DEVICE="/dev/video-${IFACE}-${IPIPE}"

	if [ -z "$CAP_DEVICE" ] ; then
		echo "Video device not found: ${CAP_DEVICE}"
		exit 1
	fi

	CAM_ENT="$(cat /sys/class/video4linux/$(readlink ${CAM_DEV})/name)"
	CAM_NAME="$(echo ${CAM_ENT} | cut -d" " -f1)"

	COLOR="$(v4l2-ctl -d ${CAM_DEV} --get-subdev-fmt 0 | \
		grep "Mediabus Code" | \
		sed 's/.*BUS_FMT_\([A-Z]*\).*/\1/g')"
	if [ "$COLOR" = "Y" ]; then
		CAM_COLOR="BW"
	else
		CAM_COLOR="COL"
	fi

	echo "Detected ${CAM_NAME} ${CAM_COLOR} Sensor on ${INTERFACE}"
	echo ""

	CONFIG_PATH="/usr/local/phytec-camera-examples/phytec-gstreamer-examples/tools/"
	case $CAM_NAME in
		ar0144 )
			CONFIG_FILE="ar0144.conf"
			;;
		* ) echo "Unknown camera: ${CAM_NAME}" ; exit 1
	esac

	if [ -f "${CONFIG_PATH}${CONFIG_FILE}" ] ; then
		source ${CONFIG_PATH}${CONFIG_FILE}
	else
		echo "Camera Sensor Configuration File not found:"
		echo "${CONFIG_PATH}${CONFIG_FILE}"
		exit 1
	fi

}

select_format_interactive() {
	camera_select_format_interactive $1
}

select_format() {
	camera_select_format $1 $2
}

select_mode_interactive() {
	camera_select_mode_interactive

	if [ -n "$GST_FMT" ] ; then
		GST_FMT="${GST_FMT},width=${CAP_WIDTH},height=${CAP_HEIGHT}"
	fi

	if [ -n "$CAM_FMT_CTRLS" ] ; then
		CAM_CTRLS="$CAM_FMT_CTRLS,$CAM_MODE_CTRLS"
	else
		CAM_CTRLS="$CAM_MODE_CTRLS"
	fi
}

select_mode() {
	camera_select_mode $1

	if [ -n "$GST_FMT" ] ; then
		GST_FMT="${GST_FMT},width=${CAP_WIDTH},height=${CAP_HEIGHT}"
	fi

	if [ -n "$CAM_FMT_CTRLS" ] ; then
		CAM_CTRLS="$CAM_FMT_CTRLS,$CAM_MODE_CTRLS"
	else
		CAM_CTRLS="$CAM_MODE_CTRLS"
	fi
}

set_controls() {

	if [ -n "$CAM_CTRLS" ] ; then
		echo " Setting Sensor V4L2 Controls:"
		echo " -----------------------------"
		CTRLS=$(echo "$CAM_CTRLS" | sed 's/,/ /g')
		for CTRL in ${CTRLS} ; do
			echo "  v4l2-ctl -d ${CAM_DEV} -c ${CTRL}"
		done
		echo ""
		v4l2-ctl -d ${CAM_DEV} -c ${CAM_CTRLS}
	fi
}

