; CONSTANTS
; DO NOT ALTER NAMES/VALUES IN THIS SECTION
;==============================================================================
ON=1
OFF=0 
USB=1    ;Port types: 
RS232=2
OPEN=1   ;Port status
CLOSED=0
LOCAL=0  ;File Source 
FTP=1
;==============================================================================
; CONFIGURATION VARIABLES 
; Edit these variables for your test

;port parameters
PORT_TYPE=RS232  ;Valid values: USB, RS232 (currently this script only supports RS232)
COM_PORT="1"     ;Com port to access modem

;FTP parameters
FTP_SERV=""     ;Address of FTP Server
FTP_USER=""     ;Username for FTP account
FTP_PASS=""     ;Password for FTP account
FTP_DIR=""      ;Directory (sub folder) where FOTA files are stored
FTP_TIMEOUT="5000" ;
CID="1"          ;PDP Context profile  

;delta file parameters
DELTA_FILE=""   ; set to empty string to use fota test files for MVW1
FILE_SOURCE=FTP
LOG=ON                         ;
UPDATE_TIMEOUT=200             ;
TRY_HIGH_SPEED=OFF             ;[ON/OFF] try 230K if RS232 PORT_TYPE

;look for external config file
getdir my_dir
makepath config_file my_dir 'fota_demo_cfg.ttl'
filesearch config_file
if result = 1 include config_file
setsync 1
goto main


;SUBROUTINES
;###############################################################################
;
:get_port_status
;--------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> get_port_status
 PORT_STATUS = CLOSED
 PORT_ICON = '[-]'
 testlink
 if result = 2 then
    if PORT_TYPE = USB then
       PORT_STATUS = OPEN
       PORT_ICON = '[+]'
    else
       getmodemstatus mdm_status
       if mdm_status % 2 = 1 then
       PORT_STATUS = OPEN
       PORT_ICON = '[+]'
    endif
 endif
return

:open_com_port
;------------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> open_com_port
 sprintf2 COM_STR "/C=%s" COM_PORT
 connect COM_STR
 mpause 500
 call get_port_status
return

:baud_detect
;----------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>baud_detect
 mtimeout = 100
 save_timeout = timeout
 timeout = 0
 for b 0 9
     if b = 1 setbaud 921600
     if b = 2 setbaud 460800
     if b = 3 setbaud 230400
     if b = 4 setbaud 115200
     if b = 5 setbaud 57600
     if b = 6 setbaud 38400
     if b = 7 setbaud 19200
     if b = 8 setbaud 9600
     sendln 'AT'
     waitln 'OK'
     if result=1 break
 next
 if b = 9 then
    setbaud 115200
    exit_message = "NO MODEM RESPONSE"
    goto quit_script
 endif
 mpause 100
 flushrecv
 timeout = save_timeout
 mtimeout = 0
return

:open_log
;-------->>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> open_log
; Use IMEI for file name
 SENDLN 'AT#CGSN'
 WAITLN '#CGSN:'
 STRCOPY inputstr 8 255 CGSN         ;Strip '#CGSN: ' characters, save IMEI in CGSN
 SPRINTF2 LOGFILE '%s.log' CGSN      ;Format log file name
 MAKEPATH LOGFILE my_dir LOGFILE     ;Add path 
 LOGOPEN LOGFILE 0 0 0 1 1
 MPAUSE 20
 SENDLN 'AT#CGSN'                    ;Resend +CGSN command so the result is logged
 WAITLN 'OK'
 MPAUSE 100
 FLUSHRECV
return


:main 
;====>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> main
; Open COM Port
;--------------
call open_com_port
if PORT_STATUS=CLOSED then
   sprintf2 exit_message "ERROR OPENING COM %s" COM_PORT
   goto quit_script
endif
call baud_detect
if LOG = ON call open_log

; Query module type 
;------------------
timeout = 1
CID = "1"
SENDLN 'AT+CGMM'
waitln 'ME910C1-NV' 'ME910C1-NA'
if result = 0 then
   exit_message = 'Unknown Module'
   goto quit_script
   endif
if result = 1 then
   CID = "3"
   MODULE_SUFFIX = 'NV'
   endif
if result = 2 then
   sendln 'AT#FWSWITCH?'
   waitln 'ERROR' '#FWSWITCH: 0' '#FWSWITCH: 1'
   if result = 1 MODULE_SUFFIX = 'NA'
   if result > 1 MODULE_SUFFIX = 'NANV'
   if result = 3 CID = '3'
   endif
CGMM = inputstr

;set FTP directory - in this example the ftp server has a different folder for each module
if FILE_SOURCE = FTP sprintf2 FTP_DIR 'ME910C1-%s' MODULE_SUFFIX 


;Query firmware revision
;-----------------------
SENDLN 'AT+CGMR'
WAITLN '.'
CGMR = inputstr
MPAUSE 50

;Query patch version
;-----------------
SENDLN 'AT#CFVR'
WAITLN '#CFVR:'               ;example response: #CFVR: 0
STRCOPY inputstr 8 255 CFVR   ;strip '#CFVR: ' from response and save in CFVR
MPAUSE 50
FLUSHRECV

strlen DELTA_FILE
; this script only supports xx3 --> xx8 updates
; Sample Filename: outUpdPkg_30.00.003.0_M0B.000003_to_30.00.008.2_M0B.000005_ME910C1_NANV.bin
if result = 0 then
   ;formate delta file name according to #CFVR response from module
   strcompare CGMR 'M0B.100003'
   if result = 0 sprintf2 DELTA_FILE 'outUpdPkg_30.00.003.%s_M0B.000003_to_30.00.008.2_M0B.000005_ME910C1_NANV.bin' CFVR
   strlen DELTA_FILE
   ; if still empty exit script
   if result = 0 then
      messagebox 'Unknown Firmware Revision' 'Exit Script'
      end
   endif
endif   
logwrite DELTA_FILE

; Currently the Cat-M1 modules don't support serial upload of delta files, only FTP

;                                       IF DOWNLOADING FIRMWARE FROM FTP SERVER
;==============================================================================
;Format commands used for FTP download
;-------------------------------------
SPRINTF2 ACTIVATE_CONTEXT   'AT#SGACT=%s,1' CID
SPRINTF2 DEACTIVATE_CONTEXT 'AT#SGACT=%s,0' CID
SPRINTF2 SCFG_CMD           'AT#SCFG=1,%s,1500,90,600,1' CID
SPRINTF2 FTP_OPEN_CMD       'AT#FTPOPEN="%s",%s,%s,1' FTP_SERV FTP_USER FTP_PASS
SPRINTF2 FTP_CWD_CMD        'AT#FTPCWD=%s' FTP_DIR
SPRINTF2 FTP_GET_CMD        'AT#FTPGETOTA="%s",1' DELTA_FILE
SPRINTF2 FTP_TO_CMD         'AT#FTPTO=%s' FTP_TIMEOUT

;Check registration and signal strength
;--------------------------------------
timeout = 5
SENDLN 'AT+CEREG=1;&W'
WAITLN 'OK'
MPAUSE 50
:wait_reg
 SENDLN 'AT+CEREG?'
 WAIT '1,1' '1,5'
 MPAUSE 50
 if result = 0 goto wait_reg
timeout = 0
FLUSHRECV
SENDLN 'AT+CSQ'
WAITLN 'OK'
MPAUSE 50

;Initialize modem and try download
;--------------------------------------
SENDLN 'AT+CMEE=2'
WAIT 'OK'
MPAUSE 50

SENDLN SCFG_CMD
WAIT 'OK'
MPAUSE 50

SENDLN ACTIVATE_CONTEXT
WAIT 'OK' 'context already activated'
MPAUSE 500

SENDLN FTP_TO_CMD
WAIT 'OK'
MPAUSE 50

SENDLN FTP_OPEN_CMD
WAIT 'OK'
MPAUSE 50

SENDLN 'AT#FTPTYPE=0'
WAIT 'OK'
MPAUSE 20

STRLEN FTP_DIR 
if result >0 then 
    SENDLN FTP_CWD_CMD
    WAIT 'OK'
    MPAUSE 50
endif

SENDLN FTP_GET_CMD
send 10
WAIT 'OK' 'ERROR'
if result = 2 end
MPAUSE 50

SENDLN 'AT#FTPCLOSE'
WAIT 'OK'
MPAUSE 50

SENDLN DEACTIVATE_CONTEXT
WAIT 'OK'
MPAUSE 200



:start_update
PAUSE 1
FLUSHRECV
SENDLN 'AT#OTAUP=0'
WAIT 'OK'
timeout = 1
exit_message=''
reset_count = 0
sprintf2 status_title 'UPDATING MODULE: %s' DELTA_FILE
for i 1 UPDATE_TIMEOUT
    call get_port_status
    SPRINTF2 status_txt '%s [%i] FLASHING FIRMWARE - Please Wait  ' PORT_ICON  i
    statusbox status_txt status_title
    ;NOTE - If USB model port will close during update this re-opens the port
    if PORT_STATUS = CLOSED then
       pause 1
       call open_com_port
       if PORT_STATUS = OPEN then
	      pause 5 
		  send 13
		  reset_count = reset_count + 1
	   endif
    else
       waitln  '#OTAEV: Module Upgraded To New Fw' 'Failed' 'Error'
       if result > 1 then
          exit_message = inputstr
          break
       endif
       if result = 1 break
    endif
    if i % 15 = 0 send 13
next
pause 5
if i = UPDATE_TIMEOUT exit_message='TIMEOUT'
strlen exit_message
if result = 0 exit_message = 'Finished'
timeout = 0
closesbox
sendln 'AT+CGMR'
:quit_script
messagebox exit_message 'Terminating Script'
logclose
end