#!/bin/bash
# How to run this script
# sudo curl https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/upgrade_repeater_FW_M17_12MHz_BPiM2b_b20230606 | sudo sh
# Change firmware to your own build file if necessary mmdvm_f4_iz8gur_m17.hex


sudo mount -o remount,rw / ; 
cd /home/pi-star
hex_file="mmdvm_f4_m17_build20230606.hex"  
echo "hex_file:${hex_file}"
rm -f ./${hex_file}
sudo curl -OL https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/${hex_file};
sudo curl -OL https://www.bi7jta.org/files/MMDVM_Firmware/repeater_HAT/stm32flashV5; 

sudo chmod +x stm32flashV5;

echo "Stopping Pi-Star Services..." 

sudo systemctl stop pistar-watchdog.timer
sudo systemctl stop pistar-watchdog.service
sudo systemctl stop mmdvmhost.timer
sudo systemctl stop nextiondriver.service #Must stop NextionDriver
sudo systemctl stop mmdvmhost.service
sleep 1

echo "Killing any remaining MMDVMHost processes..."
sudo killall MMDVMHost
sudo killall MMDVMHost_NoOLED
sudo killall MMDVMHost_Adafruit

echo "Starting Flashing..."

sudo sh -c 'echo "230" > /sys/class/gpio/export'   #230对应树莓派20
sudo sh -c 'echo "229" > /sys/class/gpio/export'   #229对应树莓派21

sudo sh -c 'echo "out" > /sys/class/gpio/gpio230/direction'  #230对应树莓派20
sudo sh -c 'echo "out" > /sys/class/gpio/gpio229/direction'  #229对应树莓派21

sudo sh -c 'echo "1" > /sys/class/gpio/gpio230/value' #（反过来，20写入高电平）
sudo sh -c 'echo "0" > /sys/class/gpio/gpio229/value' #（高电平1v？反过来，21写入低电平） #229对应树莓派21
#####执行到这一步，进入reset状态，PWR/COS灯亮

#等待1s 中继板电容充分放电
#whait enough to discharge C8
sleep 1
sudo sh -c 'echo "1" > /sys/class/gpio/gpio229/value' #再将21写入高电平,进入刷机状态，标志“ACT红灯亮” #229对应树莓派21
#whait enough to charge C8
sleep 1
#####注意：b5有些板子，无法进入刷机状态，如果  -R  -i 20,-21,21:-20,-21,21 /dev/ttyAMA0; 无法刷，这种方法也不行

echo “现在：GPIO20，G PIO21所有脚处于高电平，开始写固件...”

echo "Flashing BPiM2u BPiM2b  ..."
sudo systemctl stop mmdvmhost.service #STOP MDMVMHost again

sudo /home/pi-star/stm32flashV5 -v -w /home/pi-star/${hex_file}  -R /dev/ttyAMA0;

#RPi_GPIO20—>BPiM2u_230;
#RPi_GPIO21—>BPiM2u_229;
sleep 1


########以下是GPIO复位，避免重启才生效##########
sudo sh -c 'echo "0" > /sys/class/gpio/gpio229/value'  #229对应树莓派21
sudo sh -c 'echo "0" > /sys/class/gpio/gpio230/value' #230对应树莓派20
#whait enough to discharge C8
sleep 1
##这里gpio21高电平就重置，所有灯全部亮了 ，要复位，需要将GPIO21 20都设置为0，再将GPIO21置为1
sudo sh -c 'echo "1" > /sys/class/gpio/gpio229/value' #230对应树莓派20
#whait enough to charge C8
sleep 1

sudo sh -c 'echo "in" > /sys/class/gpio/gpio230/direction'  #230对应树莓派20
sudo sh -c 'echo "in" > /sys/class/gpio/gpio229/direction'  #229对应树莓派21
sudo sh -c 'echo "230" > /sys/class/gpio/unexport' #230对应树莓派20
sudo sh -c 'echo "229" > /sys/class/gpio/unexport' #229对应树莓派21


echo "Starting Pi-Star Services..."
sudo mount -o remount,ro /


sudo systemctl start pistar-watchdog.timer
sudo systemctl start pistar-watchdog
sudo systemctl start mmdvmhost.timer
sudo systemctl start nextiondriver.service #Must stop NextionDriver
sudo systemctl start mmdvmhost

echo "Finnished…"