void vGSM_GPRS_Task(void *arg) { Timeout_Type tApp_100MS; uint32_t timer100msCnt = 0; InitTimeout(&tApp_100MS,SYSTICK_TIME_MS(100)); AMPM_GSM_Init("internet","mms","mms",vTcpIpTask,vTcpIpTaskInit); while(1) { AMPM_GSM_MainTask(); //Call and dtmf test if(incomingCall.state == CALL_INCOMING) { if(ampm_GotIncomingNumberFlag) { if(Ampm_ComparePhoneNumber((char *)ampm_IncomingCallPhoneNo,BOSS_PHONE_NUMBER)) { incomingCall.dtmf = &dtmfRingBuf; Ampm_VoiceCallSetAction(&incomingCall,CALL_PICKUP_WHEN_INCOMING); } else { Ampm_VoiceCallCancel(&incomingCall); } } } if(incomingCall.state == CALL_ACTIVE) { if(RINGBUF_Get(&dtmfRingBuf,&c) == 0) { DbgCfgPrintf("\r\nDTMF:%c",c); if(c == '1') { Ampm_VoiceCallCancel(&incomingCall); Ampm_VoiceCallSetup(&callUser,(uint8_t *)BOSS_PHONE_NUMBER,&dtmfRingBuf,CALL_HANGUP_WHEN_ALERTING,NULL,6,60,1); //Ampm_VoiceCallSetup(&callUser,BOSS_PHONE_NUMBER,&dtmfRingBuf,CALL_HANGUP_WHEN_ACTIVE,NULL,6,60,1); } } } //SMS test //Send Sms with interval = 3600s if(CheckTimeout(&tSendSmsTime) == SYSTICK_TIMEOUT) { InitTimeout(&tSendSmsTime,SYSTICK_TIME_SEC(3600)); smsLen = sprintf((char *)pdu2uniBuf,"Xin chào!\n"); smsLen = utf8s_to_ucs2s((int16_t *)replySmsBuf,pdu2uniBuf); big2litel_endian((uint16_t *)replySmsBuf,unilen((uint16_t *)replySmsBuf)); smsLen *= 2; Ampm_Sms_SendMsg(&smsUser,(uint8_t *)BOSS_PHONE_NUMBER,(uint8_t *)replySmsBuf,smsLen,SMS_PDU16_MODE,30/*interval resend*/,3/*resend times*/); } // 0.1 sec process if(CheckTimeout(&tApp_100MS) == SYSTICK_TIMEOUT) { InitTimeout(&tApp_100MS,SYSTICK_TIME_MS(100)); timer100msCnt += 100; CtrLed(timer100msCnt); } } }
/* +UULOC: 27/09/2012,18:26:13.363,21.0213870,105.8091050,0,127,0,0� nmea_scanf((char *)buff,128,"%d/%d/%d,%d:%d:%d.%d,%f,%f,%f,%f,%f,%f",&t1,&t2,&t3,&t4,&t5,&t6,&t7, cellLocateType.lat,cellLocateType.lon,cellLocateType.alt,cellLocateType.uncertainty, cellLocateType.speed,cellLocateType.dir; ); */ uint8_t GetCellLocate(uint8_t *buff) { COMPARE_TYPE cmp1; Timeout_Type tOut; uint8_t c,i; uint32_t t1,t2,t3,t4,t5,t6,t7; DelayMs(100); MODEM_FlushBuffer(); MODEM_Info("\r\nGSM->GET CELL LOCATE\r\n"); sprintf((char *)buff, "AT+ULOC=2,2,1,500,1\r"); COMM_Puts(buff); InitFindData(&cmp1,"+UULOC: "); InitTimeout(&tOut,TIME_SEC(3)); i = 0; while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { i = 1; break; } } } if(i) { InitFindData(&cmp1,"\r\n"); InitTimeout(&tOut,TIME_SEC(3)); i = 0; while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { buff[i++] = c; if(FindData(&cmp1,c) == 0) { nmea_scanf((char *)buff,128,"%d/%d/%d,%d:%d:%d.%d,%f,%f,%f,%f,%f,%f",&t1,&t2,&t3,&t4,&t5,&t6,&t7, &cellLocate.lat,&cellLocate.lon,&cellLocate.alt,&cellLocate.uncertainty, &cellLocate.speed,&cellLocate.dir); cellLocate.ew = 'E'; cellLocate.ns = 'N'; if(cellLocate.lat < 0) cellLocate.ns = 'S'; if(cellLocate.lon < 0) cellLocate.ew = 'W'; cellLocate.lon = neamFormatLatLng(cellLocate.lon); cellLocate.lat = neamFormatLatLng(cellLocate.lat); cellLocate.time.mday = t1; cellLocate.time.month = t2; cellLocate.time.year = t3; cellLocate.time.hour = t4; cellLocate.time.min = t5; cellLocate.time.sec = t6; return 0; } } } } return 0xff; }
uint16_t MODEM_CheckGPRSDataOut(uint8_t socket) { COMPARE_TYPE cmp1,cmp2; Timeout_Type tOut; uint8_t buf[32],c; DelayMs(100); MODEM_FlushBuffer(); MODEM_Info("\r\nGSM->CHECK OUTCOMING UNACK SOCKET:%d\r\n",socket); sprintf((char *)buf, "AT+USOCTL=%d,11\r",socketMask[socket]); COMM_Puts(buf); InitFindData(&cmp1,"OK"); InitFindData(&cmp2,"ERROR"); InitTimeout(&tOut,TIME_MS(1000)); while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { MODEM_Info("\r\nGPRS->UNACK:%dBytes\r\n",GPRS_dataUnackLength[socket]); return GPRS_dataUnackLength[socket]; } if(FindData(&cmp2,c) == 0) { MODEM_Info("\r\nGPRS->ERROR\r\n"); //tcpSocketStatus[socket] = SOCKET_CLOSE; break; } } } //num of data will check in at_command_parser.c // return GPRS_dataUnackLength MODEM_Info("\r\nGPRS->UNACK:%dBytes\r\n",GPRS_dataUnackLength[socket]); return 0xffff; }
uint8_t MODEM_CloseSocket(uint8_t socket) { COMPARE_TYPE cmp1,cmp2; Timeout_Type tOut; uint8_t c; uint8_t buf[32]; DelayMs(100); MODEM_FlushBuffer(); MODEM_Info("\r\nGSM->CLOSE SOCKET:%d\r\n",socket); sprintf((char *)buf, "AT+USOCL=%d\r",socket); COMM_Puts(buf); InitFindData(&cmp1,"OK"); InitFindData(&cmp2,"ERROR"); InitTimeout(&tOut,TIME_MS(3000)); while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { //MODEM_Info("\r\nGSM->CLOSE SOCKET OK\r\n"); return 0; } if(FindData(&cmp2,c) == 0) { break; } } } //MODEM_Info("\r\nGSM->CLOSE SOCKET FAILS\r\n"); return 0xff; }
static void SdCardWaitReady(void) { if( QueryMessageStatus(SD_u32CurrentMsgToken) == COMPLETE ) { if( *SD_pu8RxBufferParser != 0xFF ) { SD_u32CurrentMsgToken = SspReadByte(SD_Ssp); if( !SD_u32CurrentMsgToken ) { /* We didn't get a return token, so abort */ SD_u8ErrorCode = SD_ERROR_NO_TOKEN; SD_pfnStateMachine = SdError; } AdvanceSD_pu8RxBufferParser(1); } /* The card is ready for the command */ else { SD_u32CurrentMsgToken = SspWriteData(SD_Ssp, SD_CMD_SIZE, SD_NextCommand); /* Pre-emptively move RxBufferParser so it will point to command response */ AdvanceSD_pu8RxBufferParser(SD_CMD_SIZE); /* Set up time-outs and next state */ SD_u32Timeout = G_u32SystemTime1ms; SD_pfnStateMachine = SdCardWaitCommand; } } /* Watch for SSP timeout */ CheckTimeout(SD_SPI_WAIT_TIME_MS); } /* end SdCardWaitReady() */
bool C4Network2IO::Execute(int iTimeout, pollfd *) { tLastExecute = C4TimeMilliseconds::Now(); // check for timeout CheckTimeout(); // ping all open connections if (!Inside(tLastPing, tLastExecute - C4NetPingFreq, tLastExecute)) { Ping(); tLastPing = tLastExecute; } // do statistics if (!Inside(tLastStatistic, tLastExecute - C4NetStatisticsFreq, tLastExecute)) { GenerateStatistics(tLastExecute - tLastStatistic); tLastStatistic = tLastExecute; } // resources ::Network.ResList.OnTimer(); // ok return true; }
/* Wait for a response to CMD8. */ static void SdCardReadCMD8(void) { /* Check to see if the SSP peripheral has sent the data request */ if( QueryMessageStatus(SD_u32CurrentMsgToken) == COMPLETE ) { /* Process the four response bytes (only the last two matter) */ AdvanceSD_pu8RxBufferParser(2); if(*SD_pu8RxBufferParser == SD_VHS_VALUE) { AdvanceSD_pu8RxBufferParser(1); if(*SD_pu8RxBufferParser == SD_CHECK_PATTERN) { /* Card supports VCC 2.7 - 3.6V so we're good to go */ SdCommand(&SD_au8CMD55[0]); SD_WaitReturnState = SdCardACMD41; } AdvanceSD_pu8RxBufferParser(1); } else { /* The card does not support the voltage range so is not usable */ SD_u8ErrorCode = SD_ERROR_CARD_VOLTAGE; SD_pfnStateMachine = SdError; } } /* Watch for SSP timeout */ CheckTimeout(SD_SPI_WAIT_TIME_MS); } /* end SdCardReadCMD8() */
LONG CSerial::Write (LPCSTR pString, DWORD* pdwWritten, LPOVERLAPPED lpOverlapped, DWORD dwTimeout) { // Check if time-outs are supported CheckTimeout(dwTimeout); // Determine the length of the string return Write(pString,strlen(pString),pdwWritten,lpOverlapped,dwTimeout); }
int QuiesceChecks(POS *p, int ply, int alpha, int beta, int *pv) { int stand_pat, best, score, move, new_pv[MAX_PLY]; int is_pv = (beta > alpha + 1); MOVES m[1]; UNDO u[1]; if (InCheck(p)) return QuiesceFlee(p, ply, alpha, beta, pv); nodes++; CheckTimeout(); if (abort_search) return 0; *pv = 0; if (IsDraw(p)) return DrawScore(p); if (ply >= MAX_PLY - 1) return Eval.Return(p, 1); best = stand_pat = Eval.Return(p, 1); if (best >= beta) return best; if (best > alpha) alpha = best; if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, 0, ply)) return score; InitCaptures(p, m); while ((move = NextCaptureOrCheck(m))) { p->DoMove(move, u); if (Illegal(p)) { p->UndoMove(move, u); continue; } score = -Quiesce(p, ply + 1, -beta, -alpha, new_pv); p->UndoMove(move, u); if (abort_search) return 0; if (score >= beta) { TransStore(p->hash_key, move, score, LOWER, 0, ply); return score; } if (score > best) { best = score; if (score > alpha) { alpha = score; BuildPv(pv, new_pv, move); } } } if (*pv) TransStore(p->hash_key, *pv, best, EXACT, 0, ply); else TransStore(p->hash_key, 0, best, UPPER, 0, ply); return best; }
//========================================================================================== // ExecHolder::WaitForBallToEnter() //========================================================================================== // - Wait for ball to enter // - Then delay to give the ball time to settle // - Then pinch the ball (goto forward limit)z //========================================================================================== void ExecHolder::WaitForBallToEnter() { Robot::holder->CloseGate(); if(Robot::holder->IsBallPresent()){ if(!Timing()){ SetDeltaTimeout(BALLDETECTIONDELAY); DEBUG_PRINT("New Ball Detected - Waiting Settling Period.."); } else if(CheckTimeout()){ DEBUG_PRINT("Opening Gate .."); state=GO_TO_FORWARD_LIMIT; } } }
//========================================================================================== // ExecHolder::RemoveBall() //========================================================================================== // - Try to remove a stuck ball by reversing the push and gate motors // - Start a timer // - If the timeout expires and the ball is still stuck go to an error state // - Else close the gate //========================================================================================== void ExecHolder::RemoveBall() { Robot::holder->RemoveBall(); if(!Timing()) SetDeltaTimeout(BALLDETECTIONDELAY); else if(CheckTimeout()){ if(Robot::holder->IsBallPresent()){ DEBUG_PRINT("Remove Ball Failed - Entering Error State"); state=PUSH_ERROR; } else { DEBUG_PRINT("Remove Ball Succeeded - Closing Gate"); state=GO_TO_REVERSE_LIMIT; } } }
//========================================================================================== // ExecHolder::WaitForBallToLeave() //========================================================================================== // - After a push request, enable the push wheel (forward push) // - Start a timer to detect when the ball leaves // - If the ball is still present after the timeout, assume it is stuck and try to remove it // - Else close the gate and wait for a new ball to enter //========================================================================================== void ExecHolder::WaitForBallToLeave() { Robot::holder->PushBall(); if(!Timing()) SetDeltaTimeout(BALLDETECTIONDELAY); else if(CheckTimeout()){ if(Robot::holder->IsBallPresent()){ DEBUG_PRINT("Push Failed - Attempting to remove the ball"); state=REMOVE_BALL; } else{ DEBUG_PRINT("Push Succeeded - Closing Gate"); state=GO_TO_REVERSE_LIMIT; } } }
/* Wait for a data for CMD58. RxBuffer pointer is at first of four response bytes when SSP is complete. */ static void SdCardReadCMD58(void) { /* Check to see if the SSP peripheral has sent the command */ if( QueryMessageStatus(SD_u32CurrentMsgToken) == COMPLETE ) { /* Determine card capacity */ SD_u32Flags &= ~_SD_CARD_HC; if(*SD_pu8RxBufferParser & _SD_OCR_CCS_BIT) { SD_u32Flags |= _SD_CARD_HC; /* Success! Card is ready for read/write operations */ SspDeAssertCS(SD_Ssp); SspRelease(SD_Ssp); SD_CardState = SD_IDLE; //SD_CardStatusLed.eBlinkRate = LED_ON; //LedRequest(&SD_CardStatusLed); DebugPrintf(SD_au8CardReady); SD_pfnStateMachine = SdCardReadyIdle; } /* For standard capacity, make sure block size is 512 */ else { SdCommand(&SD_au8CMD16[0]); SD_WaitReturnState = SdCardResponseCMD16; } /* Ignore the other 3 response bytes */ AdvanceSD_pu8RxBufferParser(4); } /* Watch for SSP timeout */ CheckTimeout(SD_SPI_WAIT_TIME_MS); } /* end SdCardReadCMD58() */
uint8_t MODEM_CreateSocket(uint8_t socket) { COMPARE_TYPE cmp1,cmp2; Timeout_Type tOut; uint8_t c; DelayMs(100); MODEM_FlushBuffer(); socketMask[socket] = 0xff; createSocketNow = socket; MODEM_Info("\r\nGSM->CREATE SOCKET\r\n"); COMM_Puts("AT+USOCR=6\r"); InitFindData(&cmp1,"OK"); InitFindData(&cmp2,"ERROR"); InitTimeout(&tOut,TIME_MS(3000)); while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { if((socketMask[socket] == 0xff)) { break; } MODEM_Info("\r\nGSM->CREATE SOCKET OK\r\n"); return 0; } if(FindData(&cmp2,c) == 0) { break; } } } MODEM_Info("\r\nGSM->CREATE SOCKET FAILS\r\n"); return 0xff; }
LONG CSerial::WaitEvent (LPOVERLAPPED lpOverlapped, DWORD dwTimeout) { // Check if time-outs are supported CheckTimeout(dwTimeout); // Reset error state m_lLastError = ERROR_SUCCESS; // Check if the device is open if (m_hFile == 0) { // Set the internal error code m_lLastError = ERROR_INVALID_HANDLE; // Issue an error and quit _RPTF0(_CRT_WARN,"CSerial::WaitEvent - Device is not opened\n"); return m_lLastError; } // Wait for the event to happen OVERLAPPED ovInternal; if (lpOverlapped == 0) { // Setup our own overlapped structure memset(&ovInternal,0,sizeof(ovInternal)); ovInternal.hEvent = m_hevtOverlapped; // Use our internal overlapped structure lpOverlapped = &ovInternal; } // Make sure the overlapped structure isn't busy _ASSERTE(HasOverlappedIoCompleted(lpOverlapped)); // Wait for the COM event if (!::WaitCommEvent(m_hFile,LPDWORD(&m_eEvent),lpOverlapped)) { // Set the internal error code long lLastError = ::GetLastError(); // Overlapped operation in progress is not an actual error if (lLastError != ERROR_IO_PENDING) { // Save the error m_lLastError = lLastError; // Issue an error and quit _RPTF0(_CRT_WARN,"CSerial::WaitEvent - Unable to wait for COM event\n"); return m_lLastError; } // We need to block if the client didn't specify an overlapped structure if (lpOverlapped == &ovInternal) { // Wait for the overlapped operation to complete switch (::WaitForSingleObject(lpOverlapped->hEvent,dwTimeout)) { case WAIT_OBJECT_0: // The overlapped operation has completed break; case WAIT_TIMEOUT: // Cancel the I/O operation CancelIo(); // The operation timed out. Set the internal error code and quit m_lLastError = ERROR_TIMEOUT; return m_lLastError; default: // Set the internal error code m_lLastError = ::GetLastError(); // Issue an error and quit _RPTF0(_CRT_WARN,"CSerial::WaitEvent - Unable to wait until COM event has arrived\n"); return m_lLastError; } } } else { // The operation completed immediatly. Just to be sure // we'll set the overlapped structure's event handle. ::SetEvent(lpOverlapped->hEvent); } // Return successfully return m_lLastError; }
// Write method using select NetRetCode NetSocket::WriteData(void *bufAsVoid, int bufLen, int *numActualBytes) { NetRetCode ret = NetOk; char *buf = (char *)bufAsVoid; int bytesLeft = bufLen; int bytesSent = 0; int err = 0; unsigned int timeout = 0; unsigned int timedout = 0; int haveAllData = 0; struct timeval timeVal; long timeoutSeconds = (long)((m_polltime*1000) / 100000); long timeoutUSeconds = (long)((m_polltime*1000) % 100000); while ((bytesLeft > 0) && (!timedout)) { FD_ZERO(&m_listener); FD_SET(m_sockfd, &m_listener); timeVal.tv_sec = timeoutSeconds; timeVal.tv_usec = timeoutUSeconds; haveAllData = -1; switch (select(m_sockfd + 1, (fd_set *)0, &m_listener, (fd_set *)0, &timeVal)) { case NET_SOCKET_ERROR: NetDebugOut("WriteData select call failed"); return NetFailed; case 0: if (numActualBytes) { haveAllData = ((*numActualBytes == bufLen) ? 1 : 0); } ret = CheckTimeout(&timeout, &timedout, haveAllData); continue; default: if (!FD_ISSET(m_sockfd, &m_listener)) { return NetFailed; } bytesSent = sendto(m_sockfd, (char *)buf, bytesLeft, 0, (struct sockaddr *)&m_to, sizeof(m_to)); err = NetGetLastError(); if (NetIsSocketError(bytesSent) && NetIsReset(err)) { bytesLeft = 0; shutdown(m_sockfd, NCSD_SEND); ret = NetClientDisconnect; } else if ((bytesSent > 0) || NetIsBlockingError(err)) { bytesLeft -= bytesSent; buf += bytesSent; if (numActualBytes) { *numActualBytes += bytesSent; haveAllData = ((*numActualBytes == bufLen) ? 1 : 0); } ret = CheckTimeout(&timeout, &timedout, haveAllData); } else { NetDebugOut("WriteData write call failed"); bytesLeft = 0; shutdown(m_sockfd, NCSD_SEND); ret = NetFailed; } break; } } return ret; }
uint8_t MODEM_ConnectSocket(uint8_t socket,uint8_t *ip,uint16_t port,uint8_t useIp) { COMPARE_TYPE cmp1,cmp2; Timeout_Type tOut; uint8_t c,i; uint8_t buf[32]; DelayMs(100); MODEM_FlushBuffer(); socketMask[socket] = 0; for(i = 0; i < SOCKET_NUM;) { if(tcpSocketStatus[i] == SOCKET_OPEN) { if((socketMask[i] == socketMask[socket]) && (i != socket)) { socketMask[socket]++; i = 0; continue; } } i++; } MODEM_CloseSocket(socketMask[socket]); if(MODEM_CreateSocket(socket)) return 0xff; DelayMs(500); if(useIp == 0) { MODEM_Info("\r\nGSM->GET DOMAIN\r\n"); sprintf((char *)buf, "AT+UDNSRN=0,\"%s\"\r",ip); COMM_Puts(buf); if(MODEM_CheckResponse("OK", 5000)) { MODEM_Info("\r\nGSM->GET DOMAIN FAILS\r\n"); return 0xff; } ip = DNS_serverIp; } MODEM_Info("\r\nGSM->IP:%s\r\n",ip); MODEM_Info("\r\nGSM->CONNECT SOCKET:%d:%s:%d\r\n",socketMask[socket],ip,port); sprintf((char *)buf, "AT+USOCO=%d,\"%s\",%d\r",socketMask[socket],ip,port); COMM_Puts(buf); InitFindData(&cmp1,"OK"); InitFindData(&cmp2,"ERROR"); InitTimeout(&tOut,TIME_SEC(10)); while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { MODEM_Info("\r\nGSM->CONNECT SOCKET OK\r\n"); return 0; } if(FindData(&cmp2,c) == 0) { break; } } } MODEM_Info("\r\nGSM->CONNECT SOCKET FAILS\r\n"); return 0xff; }
int Search(POS *p, int ply, int alpha, int beta, int depth, int was_null, int last_move, int last_capt_sq, int *pv) { int best, score, null_score, move, new_depth, new_pv[MAX_PLY]; int fl_check, fl_prunable_node, fl_prunable_move, mv_type, reduction; int is_pv = (beta > alpha + 1); int mv_tried = 0, quiet_tried = 0, fl_futility = 0; int mv_played[MAX_MOVES]; int mv_hist_score; int victim, last_capt; MOVES m[1]; UNDO u[1]; assert(ply > 0); // Quiescence search entry point if (depth <= 0) return QuiesceChecks(p, ply, alpha, beta, pv); // Periodically check for timeout, ponderhit or stop command nodes++; CheckTimeout(); // Quick exit on a timeout or on a statically detected draw if (abort_search) return 0; if (ply) *pv = 0; if (IsDraw(p)) return DrawScore(p); // Mate distance pruning int checkmatingScore = MATE - ply; if (checkmatingScore < beta) { beta = checkmatingScore; if (alpha >= checkmatingScore) return alpha; } int checkmatedScore = -MATE + ply; if (checkmatedScore > alpha) { alpha = checkmatedScore; if (beta <= checkmatedScore) return beta; } // Retrieving data from transposition table. We hope for a cutoff // or at least for a move to improve move ordering. move = 0; if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, depth, ply)) { // For move ordering purposes, a cutoff from hash is treated // exactly like a cutoff from search if (score >= beta) UpdateHistory(p, last_move, move, depth, ply); // In pv nodes only exact scores are returned. This is done because // there is much more pruning and reductions in zero-window nodes, // so retrieving such scores in pv nodes works like retrieving scores // from slightly lower depth. if (!is_pv || (score > alpha && score < beta)) return score; } // Safeguard against exceeding ply limit if (ply >= MAX_PLY - 1) return Eval.Return(p, 1); // Are we in check? Knowing that is useful when it comes // to pruning/reduction decisions fl_check = InCheck(p); // INTERNAL ITERATIVE DEEPENING - we try to get a hash move to improve move ordering if (!move && is_pv && depth >= 6 && !fl_check) { Search(p, ply, alpha, beta, depth - 2, 0, 0, -1, new_pv); if (abort_search) return 0; TransRetrieve(p->hash_key, &move, &score, alpha, beta, depth, ply); } // Can we prune this node? fl_prunable_node = !fl_check && !is_pv && alpha > -MAX_EVAL && beta < MAX_EVAL; // Beta pruning / static null move if (use_beta_pruning && fl_prunable_node && depth <= 3 && !was_null) { int sc = Eval.Return(p, 1) - 120 * depth; // TODO: Tune me! if (sc > beta) return sc; } // Null move if (use_nullmove && fl_prunable_node && depth > 1 && !was_null && MayNull(p) ) { int eval = Eval.Return(p, 1); if (eval > beta) { new_depth = depth - ((823 + 67 * depth) / 256); // simplified Stockfish formula // omit null move search if normal search to the same depth wouldn't exceed beta // (sometimes we can check it for free via hash table) if (TransRetrieve(p->hash_key, &move, &null_score, alpha, beta, new_depth, ply)) { if (null_score < beta) goto avoid_null; } p->DoNull(u); if (new_depth > 0) score = -Search(p, ply + 1, -beta, -beta + 1, new_depth, 1, 0, -1, new_pv); else score = -QuiesceChecks(p, ply + 1, -beta, -beta + 1, new_pv); p->UndoNull(u); // Verification search (nb. immediate null move within it is prohibited) if (new_depth > 6 && score >= beta && use_null_verification) score = Search(p, ply, alpha, beta, new_depth - 5, 1, move, -1, new_pv); if (abort_search ) return 0; if (score >= beta) return score; } } avoid_null: // end of null move code // Razoring based on Toga II 3.0 if (use_razoring && fl_prunable_node && !move && !was_null && !(p->Pawns(p->side) & bbRelRank[p->side][RANK_7]) // no pawns to promote in one move && depth <= 3) { int threshold = beta - razor_margin[depth]; int eval = Eval.Return(p, 1); if (eval < threshold) { score = QuiesceChecks(p, ply, alpha, beta, pv); if (score < threshold) return score; } } // end of razoring code // Init moves and variables before entering main loop best = -INF; InitMoves(p, m, move, Refutation(last_move), ply); // Main loop while ((move = NextMove(m, &mv_type))) { // Gather data about the move mv_hist_score = history[p->pc[Fsq(move)]][Tsq(move)]; victim = TpOnSq(p, Tsq(move)); if (victim != NO_TP) last_capt = Tsq(move); else last_capt = -1; // Set futility pruning flag before the first applicable move is tried if (mv_type == MV_NORMAL && quiet_tried == 0) { if (use_futility && fl_prunable_node && depth <= 6) { if (Eval.Return(p, 1) + fut_margin[depth] < beta) fl_futility = 1; } } p->DoMove(move, u); if (Illegal(p)) { p->UndoMove(move, u); continue; } // Update move statistics // (needed for reduction/pruning decisions and for updating history score) mv_played[mv_tried] = move; mv_tried++; if (mv_type == MV_NORMAL) quiet_tried++; // Can we prune this move? fl_prunable_move = !InCheck(p) && (mv_type == MV_NORMAL) && (mv_hist_score < hist_limit); // Set new search depth new_depth = depth - 1; // Check extension (pv node or low depth) if (is_pv || depth < 9) { new_depth += InCheck(p); if (is_pv && Tsq(move) == last_capt_sq) new_depth += 1; } // Futility pruning if (fl_futility && fl_prunable_move && mv_tried > 1) { p->UndoMove(move, u); continue; } // Late move pruning if (use_lmp && fl_prunable_node && fl_prunable_move && quiet_tried > lmp_limit[depth] && depth <= 3 && MoveType(move) != CASTLE ) { p->UndoMove(move, u); continue; } // Late move reduction reduction = 0; if (use_lmr && depth >= 2 && mv_tried > 3 && alpha > -MAX_EVAL && beta < MAX_EVAL && !fl_check && fl_prunable_move && lmr_size[is_pv][depth][mv_tried] > 0 && MoveType(move) != CASTLE ) { // read reduction size from the table reduction = lmr_size[is_pv][depth][mv_tried]; // increase reduction on bad history score if (mv_hist_score < 0 && new_depth - reduction > 2 && lmr_hist_adjustement) reduction++; // reduce search depth new_depth -= reduction; } // a place to come back if reduction looks suspect re_search: // PVS if (best == -INF) score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv); else { score = -Search(p, ply + 1, -alpha - 1, -alpha, new_depth, 0, move, last_capt, new_pv); if (!abort_search && score > alpha && score < beta) score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv); } // Reduced move scored above alpha - we need to re-search it if (reduction && score > alpha) { new_depth += reduction; reduction = 0; goto re_search; } // Undo move p->UndoMove(move, u); if (abort_search) return 0; // Beta cutoff if (score >= beta) { if (!fl_check) { UpdateHistory(p, last_move, move, depth, ply); for (int mv = 0; mv < mv_tried; mv++) DecreaseHistory(p, mv_played[mv], depth); } TransStore(p->hash_key, move, score, LOWER, depth, ply); return score; } // Updating score and alpha if (score > best) { best = score; if (score > alpha) { alpha = score; BuildPv(pv, new_pv, move); } } } // end of the main loop // Return correct checkmate/stalemate score if (best == -INF) return InCheck(p) ? -MATE + ply : DrawScore(p); // Save score in the transposition table if (*pv) { if (!fl_check) { UpdateHistory(p, last_move, *pv, depth, ply); for (int mv = 0; mv < mv_tried; mv++) DecreaseHistory(p, mv_played[mv], depth); } TransStore(p->hash_key, *pv, best, EXACT, depth, ply); } else TransStore(p->hash_key, 0, best, UPPER, depth, ply); return best; }
void Gprs_Task(void) { uint16_t i,j; GPRS_PHASE_TYPE gprs_TaskPhaseOld = gprs_TaskPhase; if(GsmTask_GetPhase() == MODEM_TURN_ON) { gprs_TaskPhase = GPRS_TASK_IDLE; return; } if(GsmTask_GetPhase() != MODEM_SYS_COVERAGE_OK) { memset(gprsSocketStatus,0x00,sizeof(gprsSocketStatus)); memset(gprsSocketMask,0x00,sizeof(gprsSocketMask)); return; } if(modemIsBusy == 1 && modemIsBusySource != AT_U_BLOX_GPRS_TASK) return; switch(gprs_TaskPhase) { case GPRS_TASK_LOCATION_SEND_CMD: if(ModemCmdTask_SendCmd(NULL,NULL,500, modemOk, modemError, 5000, 0, "AT+ULOC=2,2,0,100,5000\r") == MODEM_RES_OK) { gprs_TaskPhase = TASK_GPRS_GET_CELL_LOCATION; } break; case TASK_GPRS_GET_CELL_LOCATION: if (ModemCmdTask_IsIdle()) { gprs_TaskPhase = GPRS_TASK_IDLE; } break; case GPRS_TASK_CLOSE_BEFORE_CREATE_SOCKET: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} gprsSocketStatus[tcpIpConn->socketId] = SOCKET_CLOSE; GPRS_CheckSocketFree(tcpIpConn->socketId); createSocketNow = tcpIpConn->socketId; if(ModemCmdTask_SendCmd(NULL,NULL,100, modemOk, modemError, 3000, 2, "AT+USOCL=%d\r", gprsSocketMask[tcpIpConn->socketId]) == MODEM_RES_OK) { tcpIpConn->socketStatus = SOCKET_DISCONNECTED; gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET; } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET; } break; case GPRS_TASK_CREATE_SOCKET: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(gprsEnableFlag == 0) { gprs_TaskPhase = GPRS_TASK_IDLE; break; } if(gprsSocketStatus[tcpIpConn->socketId] == SOCKET_OPEN) { COMM_Putc(0x1B); gprs_TaskPhase = GPRS_TASK_CLOSE_BEFORE_CREATE_SOCKET; break; } if(ModemCmdTask_IsIdle()) { COMM_Putc(0x1B); createSocketNow = tcpIpConn->socketId; ModemCmdTask_SendCmd(GPRS_TCPCreateSocket,"+USOCR: ",100, modemOk, modemError, 5000, 1, "AT+USOCR=6\r"); gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET_1; } break; case GPRS_TASK_CREATE_SOCKET_1: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} tcpIpConn->socketStatus = SOCKET_DISCONNECTED; if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { if(Domain_IpCheck(tcpIpConn->ip) == IS_IP) { ModemCmdTask_SendCmd(NULL,NULL,100, modemOk, modemError, 15000, 0, "AT+USOCO=%d,\"%s\",%d\r",gprsSocketMask[tcpIpConn->socketId],tcpIpConn->ip,tcpIpConn->port); gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET_3; } else { DNS_serverIp[0] = 0; ModemCmdTask_SendCmd(GPRS_GetIpFromDNS,"+UDNSRN: \"",100, modemOk, modemError, 60000, 0, "AT+UDNSRN=0,\"%s\"\r", tcpIpConn->ip); gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET_2; } } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { if(tcpIpConn->tryNum++ >= 3) { GsmTask_Init(); gprs_TaskPhase = GPRS_TASK_IDLE; tcpIpConn->error = CONN_OPEN_SOCKET_FAIL; tcpIpConn->cmd = CONN_CMD_EMPTY; break; } COMM_Putc(0x1B); gprs_TaskPhase = GPRS_TASK_CLOSE_BEFORE_CREATE_SOCKET; } break; case GPRS_TASK_CREATE_SOCKET_2: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { ModemCmdTask_SendCmd(NULL,NULL,100, modemOk, modemError, 15000, 0,"AT+USOCO=%d,\"%s\",%d\r",gprsSocketMask[tcpIpConn->socketId],DNS_serverIp,tcpIpConn->port); gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET_3; } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { gprsDisable = 1; tcpIpConn = list_item_next(tcpIpConn); gprs_TaskPhase = GPRS_TASK_IDLE; } break; case GPRS_TASK_CREATE_SOCKET_3: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { tcpIpConn->tryNum = 1; gprsSocketStatus[tcpIpConn->socketId] = SOCKET_OPEN; tcpIpConn->socketStatus = SOCKET_CONNECTED; tcpIpConn->cmd = CONN_CMD_EMPTY; gprs_TaskPhase = GPRS_TASK_IDLE; tcpIpConn = list_item_next(tcpIpConn); } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { if(tcpIpConn->tryNum != 0) { tcpIpConn->tryNum--; tcpIpConn = list_item_next(tcpIpConn); gprs_TaskPhase = GPRS_TASK_IDLE; break; } else { tcpIpConn->error = CONN_CREATE_TCP_CONNECTION_FAIL; tcpIpConn->cmd = CONN_CMD_EMPTY; tcpIpConn = list_item_next(tcpIpConn); gprs_TaskPhase = GPRS_TASK_IDLE; break; } COMM_Putc(0x1B); gprs_TaskPhase = GPRS_TASK_CLOSE_BEFORE_CREATE_SOCKET; } break; case GPRS_TASK_READ_DATA: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_SendCmd(NULL,NULL,100, modemOk, modemError, 1000, 0, "AT+USORD=%d,%d\r",gprsSocketMask[tcpIpConn->socketId],TCP_IP_BUF_SIZE-32) == MODEM_RES_OK) { tcpIpConn->cmd = CONN_CMD_EMPTY; gprs_TaskPhase = GPRS_TASK_GET_DATA; } break; case GPRS_TASK_GET_DATA: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { gprs_TaskPhase = GPRS_TASK_IDLE; } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { if(tcpIpConn->tryNum != 0) { tcpIpConn->tryNum--; tcpIpConn = list_item_next(tcpIpConn); gprs_TaskPhase = GPRS_TASK_IDLE; } else { tcpIpConn->error = CONN_CREATE_TCP_CONNECTION_FAIL; tcpIpConn->socketStatus = SOCKET_DISCONNECTED; tcpIpConn->cmd = CONN_CMD_EMPTY; tcpIpConn = list_item_next(tcpIpConn); gprs_TaskPhase = GPRS_TASK_IDLE; break; } } break; case GPRS_TASK_SEND_DATA: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_SendCmd(NULL,NULL,500, "@", modemError, 5000, 0, "AT+USOWR=%d,%d\r", gprsSocketMask[tcpIpConn->socketId], tcpIpConn->dataOutLen) == MODEM_RES_OK) { gprs_TaskPhase = GPRS_TASK_SEND_OUT_DATA; } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { gprs_TaskPhase = GPRS_TASK_SEND_OUT_DATA; } break; case GPRS_TASK_SEND_OUT_DATA: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { for(i = 0;i < tcpIpConn->dataOutLen;i ++) { COMM_Putc(tcpIpConn->dataOutPt[i]); } ModemCmdTask_SendCmd(NULL,NULL,100,modemOk, modemError, 2000, 0,NULL); gprs_TaskPhase = GPRS_TASK_CHECK_DATA_SENT; gprsCheckDataCnt = 0; } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { COMM_Putc(0x1A); tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpConn->cmd = CONN_CMD_EMPTY; gprs_TaskPhase = GPRS_TASK_IDLE; } break; case GPRS_TASK_CHECK_DATA_SENT: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { ModemCmdTask_SendCmd(GPRS_TcpSocketControl,"+USOCTL: ",100, modemOk, modemError, 1000, 0, "AT+USOCTL=%d,11\r",gprsSocketMask[tcpIpConn->socketId]); InitTimeout(&tGprsTaskPhaseTimeOut, SYSTICK_TIME_SEC(1)); gprs_TaskPhase = GPRS_TASK_CHECK_DATA_SENT1; } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpConn->cmd = CONN_CMD_EMPTY; gprs_TaskPhase = GPRS_TASK_IDLE; } break; case GPRS_TASK_CHECK_DATA_SENT1: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} if(ModemCmdTask_GetPhase() == MODEM_CMD_OK) { if(GPRS_dataUnackLength == 0) { tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpConn->cmd = CONN_CMD_EMPTY; tcpIpConn->error = CONN_NO_ERROR; tcpIpConn->sentDataFlag = 1; gprs_TaskPhase = GPRS_TASK_IDLE; } else if(GPRS_dataUnackLength >= 2000) { gprsDisable = 1; tcpIpConn = list_item_next(tcpIpConn); gprs_TaskPhase = GPRS_TASK_IDLE; } else { if(CheckTimeout(&tGprsTaskPhaseTimeOut) == SYSTICK_TIMEOUT) { gprs_TaskPhase = GPRS_TASK_CHECK_DATA_SENT; if(gprsCheckDataCnt++ > 3) { tcpIpConn->error = CONN_SEND_DATA_FAIL; tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpConn->cmd = CONN_CMD_EMPTY; gprsCheckDataCnt = 0; gprs_TaskPhase = GPRS_TASK_IDLE; } } } } else if( ModemCmdTask_GetPhase() == MODEM_CMD_ERROR) { tcpIpConn->error = CONN_SEND_DATA_FAIL; tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpConn->cmd = CONN_CMD_EMPTY; gprs_TaskPhase = GPRS_TASK_IDLE; } break; case GPRS_TASK_CLOSE_CONNECTION: if(tcpIpConn == NULL){gprs_TaskPhase = GPRS_TASK_IDLE; break;} gprsSocketStatus[tcpIpConn->socketId] = SOCKET_CLOSE; GPRS_CheckSocketFree(tcpIpConn->socketId); createSocketNow = tcpIpConn->socketId; if(ModemCmdTask_SendCmd(NULL,NULL,100, modemOk, modemError, 3000, 0, "AT+USOCL=%d\r", gprsSocketMask[tcpIpConn->socketId]) == MODEM_RES_OK) { tcpIpConn->socketStatus = SOCKET_DISCONNECTED; gprs_TaskPhase = GPRS_TASK_WAIT_CONNECTION_CLOSE; } break; case GPRS_TASK_WAIT_CONNECTION_CLOSE: if(ModemCmdTask_IsIdle()) { tcpIpConn->cmd = CONN_CMD_EMPTY; gprs_TaskPhase = GPRS_TASK_IDLE; } break; case GPRS_TASK_IDLE: if(gprsEnableFlag == 0) { memset(gprsSocketStatus,0x00,sizeof(gprsSocketStatus)); memset(gprsSocketMask,0x00,sizeof(gprsSocketMask)); tcpIpBuf.flag = TCPIP_NO_DATA; } for(i = 0;i < GPRS_MAX_SOCKET_NUM;i++) { if(tcpIpBuf.dataUnReadLen[i] && tcpIpBuf.flag == TCPIP_NO_DATA) { tcpIpConn = list_head(gprsConnList); for(j = 0; j < GPRS_MAX_SOCKET_NUM;j++) { if(tcpIpConn != NULL) if(tcpIpConn->socketId == i ) { if(tcpIpConn->socketStatus == SOCKET_DISCONNECTED) { tcpIpBuf.dataUnReadLen[i] = 0; } else break; } tcpIpConn = list_item_next(tcpIpConn); } if(tcpIpConn != NULL) gprs_TaskPhase = GPRS_TASK_READ_DATA; break; } else if(tcpIpBuf.flag == TCPIP_NEW_DATA_RECV && i == tcpIpBuf.socket) { tcpIpConn = list_head(gprsConnList); for(j = 0; j < GPRS_MAX_SOCKET_NUM;j++) { if(tcpIpConn != NULL) if(tcpIpConn->socketId == i) { if(tcpIpConn->socketStatus == SOCKET_DISCONNECTED) { tcpIpBuf.flag = TCPIP_NO_DATA; } else break; } tcpIpConn = list_item_next(tcpIpConn); } if(tcpIpConn != NULL) { if(tcpIpConn->echo) { tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpConn->newDataFlag = 0; tcpIpConn->dataOutPt = tcpIpBuf.data; tcpIpConn->dataOutLen = tcpIpBuf.len; gprs_TaskPhase = GPRS_TASK_SEND_DATA; tcpIpBuf.len = 0; break; } else tcpIpConn->newDataFlag = 1; } } } if(gprs_TaskPhase != GPRS_TASK_IDLE) break; if(tcpIpConn != NULL) { if(tcpIpConn->cmd == CONN_CMD_EMPTY) { tcpIpBuf.flag = TCPIP_NO_DATA; } if(gprs_TaskPhase == GPRS_TASK_IDLE) { if(tcpIpConn->socketStatus == SOCKET_CONNECTED) { if(gprsSocketStatus[tcpIpConn->socketId] == SOCKET_CLOSE) tcpIpConn->socketStatus = SOCKET_DISCONNECTED; } if(tcpIpConn->socketStatus == SOCKET_CONNECTED) { if(tcpIpBuf.flag == TCPIP_NO_DATA && CheckTimeout(&tcpIpConn->periodDataRecvCheck) == SYSTICK_TIMEOUT && tcpIpBuf.dataUnReadLen[tcpIpConn->socketId] == 0) { InitTimeout(&tcpIpConn->periodDataRecvCheck,tcpIpConn->periodDataRecvValue); gprs_TaskPhase = GPRS_TASK_READ_DATA; break; } } else { InitTimeout(&tcpIpConn->periodDataRecvCheck,tcpIpConn->periodDataRecvValue); } switch(tcpIpConn->cmd) { case CONN_CMD_START: if(tcpIpConn->tryNum) { tryOpenSocketNum = 0; gprsCheckDataCnt = 0; socketTryToConnectCnt = 0; tryToCreateSocketCnt = 0; gprs_TaskPhase = GPRS_TASK_CREATE_SOCKET; if(gprsEnableFlag == 0) { gprsEnableCmd = 1; } } else tcpIpConn->cmd = CONN_CMD_EMPTY; break; case CONN_CMD_STOP: break; case CONN_SEND_DATA: gprs_TaskPhase = GPRS_TASK_SEND_DATA; break; case CONN_READ_DATA: gprs_TaskPhase = GPRS_TASK_READ_DATA; break; case CONN_CMD_PAUSE: break; case CONN_CMD_EMPTY: break; case CONN_CMD_CLOSE: gprs_TaskPhase = GPRS_TASK_CLOSE_CONNECTION; break; default: break; } if(gprs_TaskPhase == GPRS_TASK_IDLE) { tcpIpConn = list_item_next(tcpIpConn); } } } else { tcpIpConn = list_head(gprsConnList); } break; default: // re-init modem gprs_TaskPhase = GPRS_TASK_IDLE; break; } if(gprs_TaskPhase != GPRS_TASK_IDLE) { modemIsBusy = 1; modemIsBusySource = AT_U_BLOX_GPRS_TASK; } else if(modemIsBusy && modemIsBusySource == AT_U_BLOX_GPRS_TASK) { modemIsBusy = 0; } if(gprs_TaskPhaseOld != GPRS_TASK_IDLE && gprs_TaskPhase == GPRS_TASK_IDLE) modemIsBusy = 0; if((atCmdCallParser.incomingCall || VoiceCallTask_GetPhase() != CALL_IDLE) && modemIsBusy) { modemIsBusy = 0; memset(gprsSocketStatus,NULL,sizeof(gprsSocketStatus)); memset(gprsSocketMask,NULL,sizeof(gprsSocketMask)); tcpIpBuf.flag = TCPIP_NO_DATA; tcpIpBuf.socket = 0; tcpIpBuf.len = 0; gprs_TaskPhase = GPRS_TASK_IDLE; } }
int QuiesceFlee(POS *p, int ply, int alpha, int beta, int *pv) { int best, score, move, new_pv[MAX_PLY]; int fl_check, mv_type; int is_pv = (beta > alpha + 1); MOVES m[1]; UNDO u[1]; // Periodically check for timeout, ponderhit or stop command nodes++; CheckTimeout(); // Quick exit on a timeout or on a statically detected draw if (abort_search) return 0; if (ply) *pv = 0; if (IsDraw(p) ) return DrawScore(p); // Retrieving data from transposition table. We hope for a cutoff // or at least for a move to improve move ordering. move = 0; if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, 0, ply)) return score; // Safeguard against exceeding ply limit if (ply >= MAX_PLY - 1) return Eval.Return(p, 1); // Are we in check? Knowing that is useful when it comes // to pruning/reduction decisions fl_check = InCheck(p); // Init moves and variables before entering main loop best = -INF; InitMoves(p, m, move, -1, ply); // Main loop while ((move = NextMove(m, &mv_type))) { p->DoMove(move, u); if (Illegal(p)) { p->UndoMove(move, u); continue; } score = -Quiesce(p, ply, -beta, -alpha, new_pv); p->UndoMove(move, u); if (abort_search) return 0; // Beta cutoff if (score >= beta) { TransStore(p->hash_key, move, score, LOWER, 0, ply); return score; } // Updating score and alpha if (score > best) { best = score; if (score > alpha) { alpha = score; BuildPv(pv, new_pv, move); } } } // end of the main loop // Return correct checkmate/stalemate score if (best == -INF) return InCheck(p) ? -MATE + ply : DrawScore(p); // Save score in the transposition table if (*pv) TransStore(p->hash_key, *pv, best, EXACT, 0, ply); else TransStore(p->hash_key, 0, best, UPPER, 0, ply); return best; }
/*-----------------------------------------------------------------------------*/ void SerialCortex::serialRxTask() { static int serialRxState = 0; static int serialDataReceived = 0; static long timeout = 0; int cs; int c; // check for a received character if( (c = serialRxChar()) < 0 ) { // no received char // Check for inter char timeout if( CheckTimeout(&timeout) == 1 ) serialRxState = 0; // done return; } // A new character has been received so process it. // Start inter char timeout StartTimeout( &timeout ); // Where are we in the message parsing process ? switch( serialRxState ) { case kRxStateIdle: // look for first header byte if( c == HEADER_PREAMBLE_1 ) serialRxState = kRxStateHeader; else StopTimeout(&timeout); // for debug MyVexDataRx.header.header_p1 = c; break; case kRxStateHeader: // look for second header byte if( c == HEADER_PREAMBLE_2 ) serialRxState = kRxStateMessageType; else { // Bad message StopTimeout(&timeout); serialRxState = kRxStateIdle; } // for debug MyVexDataRx.header.header_p2 = c; break; case kRxStateMessageType: // We have a good header so next is message type MyVexDataRx.header.message_type = c; serialRxState = kRxStateDatalen; break; case kRxStateDatalen: // next is data length byte MyVexDataRx.header.datalen = c; serialDataReceived = 0; serialRxState = kRxStateId; break; case kRxStateId: // next is packet id byte MyVexDataRx.header.id = c; serialRxState = kRxStatePad; break; case kRxStatePad: // next is an unused word alignment byte serialRxState = kRxStateData; break; case kRxStateData: // receive the data packet MyVexDataRx.buffer[ serialDataReceived ] = c; if( ++serialDataReceived == MyVexDataRx.header.datalen ) serialRxState = kRxStateChecksum; // check for buffer overflow if( serialDataReceived >= sizeof(MyVexDataRx.buffer) ) { // Error StopTimeout(&timeout); serialRxState = kRxStateIdle; } break; case kRxStateChecksum: // Received checksum byte // stop timeout StopTimeout( &timeout ); // calculate received checksum cs = VexDataChecksum( &MyVexDataRx ); // comapare checksums if( cs == c ) { // Good data #ifdef DEBUG VexDataPrint(&MyVexDataRx); #endif serialRxDecode(&MyVexDataRx); } else { // Bad data #ifdef DEBUG Serial.write("bad data\n"); #endif } // done serialRxState = kRxStateIdle; break; default: break; } }
uint8_t MODEM_GprsSendData(uint8_t socket,uint8_t *data,uint32_t length) { COMPARE_TYPE cmp1; Timeout_Type tOut; uint8_t buf[32],c; uint32_t i; uint32_t tryNum = 5; MODEM_FlushBuffer(); sprintf((char *)buf, "AT+USOWR=%d,%d\r",socketMask[socket],length); for(;;) { DelayMs(100); COMM_Puts(buf); InitTimeout(&tOut,TIME_MS(5000)); InitFindData(&cmp1,"@"); while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { break; } } } if(CheckTimeout(&tOut) == TIMEOUT) { tryNum --; if(tryNum == 0) { tcpSocketStatus[socket] = SOCKET_CLOSE; return 0xff; } continue; } i = length; for(i = 0; i < length ;i++) { COMM_Putc(data[i]); } InitTimeout(&tOut,TIME_MS(5000)); InitFindData(&cmp1,"OK"); while(CheckTimeout(&tOut)) { if(RINGBUF_Get(&commBuf,&c) == 0) { if(FindData(&cmp1,c) == 0) { MODEM_Info("\r\nGSM->%s OK\r\n",buf); DelayMs(100); return 0; } } } MODEM_Info("\r\nGSM->%s FAILS\r\n",buf); tryNum --; if(tryNum == 0) { tcpSocketStatus[socket] = SOCKET_CLOSE; return 0xff; } } }
void TrackerTask(void) { float currentSpeed = 0,gpsCurrentSpeed; static float speedSamples[5]; uint32_t i; DATE_TIME timeTemp; uint32_t gpsTimeSec; // if(trackerTaskRun) { trackerTaskCnt++; //GPS get info GPS_GetInfo(); TIME_FromGps(&timeTemp,&nmeaInfo); gpsTimeSec = TIME_GetSec(&timeTemp); if(nmeaInfo.fix == 1 || nmeaInfo.fix == 2) { if(nmeaInfo.satinfo.inuse && nmeaInfo.satinfo.inview) UpdateRtcTime(gpsTimeSec); } else if((nmeaInfo.fix == 3) && (nmeaInfo.utc.year >= 113) && (nmeaInfo.sig > 0) && (nmeaInfo.lat != 0) && (nmeaInfo.lon != 0) && (nmeaInfo.lat <= 90 || nmeaInfo.lat >= -90) && (nmeaInfo.lon <= 180 || nmeaInfo.lon >= -180) ) { if(nmeaInfo.speed >= sysCfg.speedLimit && (CheckTimeout(&tSpeedAlarmTimeout) == SYSTICK_TIMEOUT)) { InitTimeout(&tSpeedAlarmTimeout,SYSTICK_TIME_SEC(30)); alarmFlag |= SPEED_ALARM_FLAG; } newUpdateGps = 1; lastNmeaInfo = nmeaInfo; UpdateRtcTime(gpsTimeSec); } if(trackerTaskCnt % 30 == 0) { if(lastNmeaInfo.fix == 3 && newUpdateGps) { newUpdateGps = 0; gpsLat.value = DB_FloatToU32(lastNmeaInfo.lat); gpsLon.value = DB_FloatToU32(lastNmeaInfo.lon); gpsHDOP.value = DB_FloatToU32(lastNmeaInfo.HDOP); gpsDir.value = DB_FloatToU32(lastNmeaInfo.direction); DB_U32Save(&gpsLat,GPS_LAT_ADDR); DB_U32Save(&gpsLon,GPS_LON_ADDR); DB_U32Save(&gpsHDOP,GPS_HDOP_ADDR); DB_U32Save(&gpsDir,GPS_DIR_ADDR); } } TIME_FromSec(&sysTime,rtcTimeSec); // Speed gpsCurrentSpeed = nmeaInfo.speed; if(gpsCurrentSpeed < CONFIG_SPEED_STOP || nmeaInfo.fix < 3 || nmeaInfo.utc.year < 111 || nmeaInfo.sig < 1 || nmeaInfo.lat == 0 || nmeaInfo.lon == 0 || nmeaInfo.HDOP == 0) { gpsCurrentSpeed = 0; } speedSamples[sizeof speedSamples / sizeof speedSamples[0] - 1] = gpsCurrentSpeed; if(speedSamples[0] == 0 && speedSamples[sizeof speedSamples / sizeof speedSamples[0] - 1] == 0) { for(i=1;i<sizeof speedSamples / sizeof speedSamples[0] - 1;i++) speedSamples[i] = 0; } for(i=1;i<sizeof speedSamples / sizeof speedSamples[0]; i++) speedSamples[i-1] = speedSamples[i]; gpsCurrentSpeed = speedSamples[0]; currentSpeed = gpsCurrentSpeed; mileage += currentSpeed / 3600; if(trackerSaveLog) { trackerSaveLog = 0; logRecord.time = TIME_GetSec(&sysTime); logRecord.drvIndex = 0; logRecord.adc1Value = (uint16_t)(ADC1_10_Value*1000); logRecord.adc2Value = (uint16_t)(ADC1_11_Value*1000); logRecord.gpsLat = lastNmeaInfo.lat; logRecord.gpsLon = lastNmeaInfo.lon; logRecord.gpsHdop = lastNmeaInfo.HDOP; logRecord.cellLat = lastNmeaInfo.lat; logRecord.cellLon = lastNmeaInfo.lon; logRecord.cellHdop = lastNmeaInfo.HDOP; logRecord.gpsSpeed = currentSpeed; logRecord.pulseSpeed = 0; logRecord.gpsDir = lastNmeaInfo.direction; logRecord.drivingTime = 0; logRecord.totalDrivingTime = 0; logRecord.overSpeedCnt = 0; logRecord.parkCnt = 0; logRecord.openDoorCnt = 0; logRecord.onOffEngineCnt = 0; logRecord.parkingTime = 0; logRecord.mileage = mileage; logRecord.totalPulse = rtcCnt; logRecord.speedFreq = 0; logRecord.batteryPercent = batteryPercent;//ADC1_11_Value*100/4.2; logRecord.gsmSignal = (uint8_t)csqValue; logRecord.IOStatus = 0; logRecord.satinuse = lastNmeaInfo.satinfo.inuse; logRecord.IOStatus = 0; if(GET_AVLIO1_PIN) logRecord.IOStatus |= 1<<0; //ACC if(GET_AVLIO2_PIN) logRecord.IOStatus |= 1<<1; if(GET_AVLIO3_PIN) logRecord.IOStatus |= 1<<2; if(GET_AVLIO4_PIN) logRecord.IOStatus |= 1<<3; if((!ACC_IS_ON) && currentSpeed > 15/*km/h*/) //ACC logRecord.IOStatus |= 1<<4; //chuyen dong bat thuong //logRecordTemp = logRecord; //newestLog = logRecord; //newestLog.serverSent = 0; DB_SaveLog(&logRecord); } } }
int Quiesce(POS *p, int ply, int alpha, int beta, int *pv) { int best, score, move, new_pv[MAX_PLY]; MOVES m[1]; UNDO u[1]; int op = Opp(p->side); // Statistics and attempt at quick exit if (InCheck(p)) return QuiesceFlee(p, ply, alpha, beta, pv); nodes++; CheckTimeout(); if (abort_search) return 0; *pv = 0; if (IsDraw(p)) return DrawScore(p); if (ply >= MAX_PLY - 1) return Eval.Return(p, 1); // Get a stand-pat score and adjust bounds // (exiting if eval exceeds beta) best = Eval.Return(p, 1); if (best >= beta) return best; if (best > alpha) alpha = best; #ifdef USE_QS_HASH // Transposition table read if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, 0, ply)) return score; #endif InitCaptures(p, m); // Main loop while ((move = NextCapture(m))) { // Pruning in quiescence search // (not applicable if we are capturing last enemy piece) if (p->cnt[op][N] + p->cnt[op][B] + p->cnt[op][R] + p->cnt[op][Q] > 1) { // 1. Delta pruning if (best + tp_value[TpOnSq(p, Tsq(move))] + 300 < alpha) continue; // 2. SEE-based pruning of bad captures if (BadCapture(p, move)) continue; } p->DoMove(move, u); if (Illegal(p)) { p->UndoMove(move, u); continue; } score = -Quiesce(p, ply + 1, -beta, -alpha, new_pv); p->UndoMove(move, u); if (abort_search) return 0; // Beta cutoff if (score >= beta) { #ifdef USE_QS_HASH TransStore(p->hash_key, *pv, best, LOWER, 0, ply); #endif return score; } // Adjust alpha and score if (score > best) { best = score; if (score > alpha) { alpha = score; BuildPv(pv, new_pv, move); } } } #ifdef USE_QS_HASH if (*pv) TransStore(p->hash_key, *pv, best, EXACT, 0, ply); else TransStore(p->hash_key, 0, best, UPPER, 0, ply); #endif return best; }
int SearchRoot(POS *p, int ply, int alpha, int beta, int depth, int *pv) { int best, score, move, new_depth, new_pv[MAX_PLY]; int fl_check, fl_prunable_move, mv_type, reduction; int mv_tried = 0, quiet_tried = 0; int mv_played[MAX_MOVES]; int mv_hist_score; int victim, last_capt; int move_change = 0; fl_has_choice = 0; MOVES m[1]; UNDO u[1]; // Periodically check for timeout, ponderhit or stop command nodes++; CheckTimeout(); // Quick exit if (abort_search) return 0; // Retrieving data from transposition table. We hope for a cutoff // or at least for a move to improve move ordering. move = 0; if (TransRetrieve(p->hash_key, &move, &score, alpha, beta, depth, ply)) { // For move ordering purposes, a cutoff from hash is treated // exactly like a cutoff from search if (score >= beta) UpdateHistory(p, -1, move, depth, ply); // Root node is a pv node, so we return only exact scores if (score > alpha && score < beta) return score; } // Are we in check? Knowing that is useful when it comes // to pruning/reduction decisions fl_check = InCheck(p); // Init moves and variables before entering main loop best = -INF; InitMoves(p, m, move, Refutation(-1), ply); // Main loop while ((move = NextMove(m, &mv_type))) { mv_hist_score = history[p->pc[Fsq(move)]][Tsq(move)]; victim = TpOnSq(p, Tsq(move)); if (victim != NO_TP) last_capt = Tsq(move); else last_capt = -1; p->DoMove(move, u); if (Illegal(p)) { p->UndoMove(move, u); continue; } // Update move statistics (needed for reduction/pruning decisions) mv_played[mv_tried] = move; mv_tried++; if (mv_tried > 1) fl_has_choice = 1; // we have a choice between at least two root moves if (depth > 16 && verbose) DisplayCurrmove(move, mv_tried); if (mv_type == MV_NORMAL) quiet_tried++; fl_prunable_move = !InCheck(p) && (mv_type == MV_NORMAL); // Set new search depth new_depth = depth - 1 + InCheck(p); // Late move reduction reduction = 0; if (use_lmr && depth >= 2 && mv_tried > 3 && mv_hist_score < hist_limit && alpha > -MAX_EVAL && beta < MAX_EVAL && !fl_check && fl_prunable_move && lmr_size[1][depth][mv_tried] > 0 && MoveType(move) != CASTLE ) { reduction = lmr_size[1][depth][mv_tried]; // increase reduction on bad history score if (mv_hist_score < 0 && new_depth - reduction > 2 && lmr_hist_adjustement) reduction++; new_depth -= reduction; } re_search: // PVS if (best == -INF) score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv); else { score = -Search(p, ply + 1, -alpha - 1, -alpha, new_depth, 0, move, last_capt, new_pv); if (!abort_search && score > alpha && score < beta) score = -Search(p, ply + 1, -beta, -alpha, new_depth, 0, move, last_capt, new_pv); } // Reduced move scored above alpha - we need to re-search it if (reduction && score > alpha) { new_depth += reduction; reduction = 0; goto re_search; } p->UndoMove(move, u); if (abort_search) return 0; // Beta cutoff if (score >= beta) { if (!fl_check) { UpdateHistory(p, -1, move, depth, ply); for (int mv = 0; mv < mv_tried; mv++) DecreaseHistory(p, mv_played[mv], depth); } TransStore(p->hash_key, move, score, LOWER, depth, ply); // Update search time depending on whether the first move has changed if (depth > 4) { if (pv[0] != move) Timer.OnNewRootMove(); else Timer.OnOldRootMove(); } // Change the best move and show the new pv BuildPv(pv, new_pv, move); DisplayPv(score, pv); return score; } // Updating score and alpha if (score > best) { best = score; if (score > alpha) { alpha = score; // Update search time depending on whether the first move has changed if (depth > 4) { if (pv[0] != move) Timer.OnNewRootMove(); else Timer.OnOldRootMove(); } // Change the best move and show the new pv BuildPv(pv, new_pv, move); DisplayPv(score, pv); } } } // end of the main loop // Return correct checkmate/stalemate score if (best == -INF) return InCheck(p) ? -MATE + ply : DrawScore(p); // Save score in the transposition table if (*pv) { if (!fl_check) { UpdateHistory(p, -1, *pv, depth, ply); for (int mv = 0; mv < mv_tried; mv++) DecreaseHistory(p, mv_played[mv], depth); } TransStore(p->hash_key, *pv, best, EXACT, depth, ply); } else TransStore(p->hash_key, 0, best, UPPER, depth, ply); return best; }
LONG CSerial::Read (void* pData, size_t iLen, DWORD* pdwRead, LPOVERLAPPED lpOverlapped, DWORD dwTimeout) { // Check if time-outs are supported CheckTimeout(dwTimeout); // Overlapped operation should specify the pdwRead variable _ASSERTE(!lpOverlapped || pdwRead); // Reset error state m_lLastError = ERROR_SUCCESS; // Use our own variable for read count DWORD dwRead; if (pdwRead == 0) { pdwRead = &dwRead; } // Reset the number of bytes read *pdwRead = 0; // Check if the device is open if (m_hFile == 0) { // Set the internal error code m_lLastError = ERROR_INVALID_HANDLE; // Issue an error and quit _RPTF0(_CRT_WARN,"CSerial::Read - Device is not opened\n"); return m_lLastError; } // Wait for the event to happen OVERLAPPED ovInternal; if (lpOverlapped == 0) { // Setup our own overlapped structure memset(&ovInternal,0,sizeof(ovInternal)); ovInternal.hEvent = m_hevtOverlapped; // Use our internal overlapped structure lpOverlapped = &ovInternal; } // Make sure the overlapped structure isn't busy _ASSERTE(HasOverlappedIoCompleted(lpOverlapped)); #ifdef _DEBUG // The debug version fills the entire data structure with // 0xDC bytes, to catch buffer errors as soon as possible. memset(pData,0xDC,iLen); #endif // Read the data if (!::ReadFile(m_hFile,pData,iLen,pdwRead,lpOverlapped)) { // Set the internal error code long lLastError = ::GetLastError(); // Overlapped operation in progress is not an actual error if (lLastError != ERROR_IO_PENDING) { // Save the error m_lLastError = lLastError; // Issue an error and quit _RPTF0(_CRT_WARN,"CSerial::Read - Unable to read the data\n"); return m_lLastError; } // We need to block if the client didn't specify an overlapped structure if (lpOverlapped == &ovInternal) { // Wait for the overlapped operation to complete switch (::WaitForSingleObject(lpOverlapped->hEvent,dwTimeout)) { case WAIT_OBJECT_0: // The overlapped operation has completed if (!::GetOverlappedResult(m_hFile,lpOverlapped,pdwRead,FALSE)) { // Set the internal error code m_lLastError = ::GetLastError(); _RPTF0(_CRT_WARN,"CSerial::Read - Overlapped completed without result\n"); return m_lLastError; } break; case WAIT_TIMEOUT: // Cancel the I/O operation CancelIo(); // The operation timed out. Set the internal error code and quit m_lLastError = ERROR_TIMEOUT; return m_lLastError; default: // Set the internal error code m_lLastError = ::GetLastError(); // Issue an error and quit _RPTF0(_CRT_WARN,"CSerial::Read - Unable to wait until data has been read\n"); return m_lLastError; } } } else { // The operation completed immediatly. Just to be sure // we'll set the overlapped structure's event handle. ::SetEvent(lpOverlapped->hEvent); } // Return successfully return m_lLastError; }
int main(void) { uint32_t *u32Pt = (uint32_t *)buff; uint8_t *u8pt,u8temp; int32_t i = 10000000,j = 0; uint32_t u32temp; uint16_t u16temp; uint32_t res; uint8_t c; uint32_t timeOut = 3000000; uint8_t tryNum,exit; SysInit(); // RS232_PIN_SET_OUTPUT; // RS232_PIN_CLR; USART3_PutString("\r\n************************AMPM*********************\r\n"); USART3_PutString("\r\nHello!\r\n"); USART3_PutString("\r\nI'm GSM_STM32_BOOTLOADER\r\n"); USART3_PutString("\r\nMy Ver:V1.0\r\n"); USART3_PutString("\r\nhttp://ampm.com.vn\r\n"); USART3_PutString("\r\n************************START MAIN***************\r\n"); DelayMs(1000); InitTimeout(&bootDisTimeout,TIME_SEC(3)); InitTimeout(&bootLoginTimeout,TIME_SEC(1)); InitTimeout(&bootExitTimeout,TIME_SEC(10)); UART_ProtoRecv.dataPt = &USB_rxBuff[4]; UART_parserPacket.state = CFG_CMD_WAITING_SATRT_CODE; UART_parserPacket.lenMax = UART_PACKET_SIZE; FLASH_Unlock(); while((CheckTimeout(&bootDisTimeout) != TIMEOUT || bootMode) && CheckTimeout(&bootExitTimeout) != TIMEOUT ) // while(0) { if(bootMode == 0 && CheckTimeout(&bootLoginTimeout) == TIMEOUT) { USB_txBuff[0] = 0xCA; USB_txBuff[1] = 4; //length USB_txBuff[3] = 0x88; //opcode USB_txBuff[4] = 0xA5; USB_txBuff[5] = 0xA5; USB_txBuff[6] = 0xA5; USB_txBuff[7] = 0xA5; USB_txBuff[USB_txBuff[1] + 4] = CfgCalcCheckSum((uint8_t *)&USB_txBuff[4],USB_txBuff[1]); for(i = 0;i < USB_txBuff[1] + 4 + 1; i++) { USART3_PutChar(USB_txBuff[i]); } USB_rxBuff[0] = 0; InitTimeout(&bootLoginTimeout,TIME_SEC(2)); } while(RINGBUF_Get(&USART3_RxRingBuff,&c) == 0) { if(CfgParserPacket(&UART_parserPacket,&UART_ProtoRecv,c) == 0) { USB_rxBuff[0] = 0xCA; USB_rxBuff[1] = ((uint8_t *)&UART_ProtoRecv.length)[0]; USB_rxBuff[2] = ((uint8_t *)&UART_ProtoRecv.length)[1]; USB_rxBuff[3] = UART_ProtoRecv.opcode; UART_ProtoRecv.dataPt = &USB_rxBuff[4]; UART_parserPacket.state = CFG_CMD_WAITING_SATRT_CODE; UART_parserPacket.lenMax = UART_PACKET_SIZE; break; } } if(USB_rxBuff[0] == 0xCA) { USB_txBuff[1] = 0; USB_txBuff[2] = 0; USB_txBuff[3] = 0; switch(USB_rxBuff[3]) { case 0x12: InitTimeout(&bootExitTimeout,TIME_SEC(60)); u32Pt = (uint32_t *)&USB_rxBuff[4]; packetNo = *u32Pt; if(packetNo == 0xA5A5A5A5) { firmwareFileOffSet = 0; u32Pt = (uint32_t *)&USB_rxBuff[8]; firmwareFileSize = *u32Pt; USB_txBuff[1] = 12; //length USB_txBuff[3] = 0x12; //opcode USB_txBuff[4] = USB_rxBuff[4]; USB_txBuff[5] = USB_rxBuff[5]; USB_txBuff[6] = USB_rxBuff[6]; USB_txBuff[7] = USB_rxBuff[7]; //Max file size USB_txBuff[8] = USB_rxBuff[8]; USB_txBuff[9] = USB_rxBuff[9]; USB_txBuff[10] = USB_rxBuff[10]; USB_txBuff[11] = USB_rxBuff[11]; //Max packet size u16temp = UART_PACKET_SIZE - 4; USB_txBuff[12] = ((uint8_t *)&u16temp)[0]; //max packet size USB_txBuff[13] = ((uint8_t *)&u16temp)[1]; //max packet size USB_txBuff[14] = 0; //max packet size USB_txBuff[15] = 0; //max packet size } else { InitTimeout(&bootExitTimeout,TIME_SEC(10)); if(packetNo == firmwareFileOffSet) { firmwareFileOffSet += (UART_ProtoRecv.length - 4); u32temp = firmwareFileOffSet % FLASH_BUF_SIZE; for(i = 0;i < (UART_ProtoRecv.length - 4);i++) { flashBuff[(packetNo % FLASH_BUF_SIZE) + i] = USB_rxBuff[i + 8]; } if(u32temp == 0) { u32temp = USER_FLASH_START + firmwareFileOffSet - FLASH_BUF_SIZE; phase = 5; u32Pt = (uint32_t *)flashBuff; __disable_irq(); myFMC_Erase(u32temp); FMC_ProgramPage(u32temp,u32Pt); __enable_irq(); phase = 6; for(i = 0;i < FLASH_BUF_SIZE; i++) flashBuff[i] = 0xff; } else if(firmwareFileOffSet >= firmwareFileSize) { i = (firmwareFileOffSet / FLASH_BUF_SIZE)*FLASH_BUF_SIZE; u32temp = USER_FLASH_START + i; u32Pt = (uint32_t *)flashBuff; __disable_irq(); myFMC_Erase(u32temp); FMC_ProgramPage(u32temp,u32Pt); __enable_irq(); } } packetNo = firmwareFileOffSet; if(firmwareFileOffSet >= firmwareFileSize) { firmwareFileOffSet = 0; packetNo = 0x5A5A5A5A; InitTimeout(&bootExitTimeout,TIME_SEC(1)); } u8pt = (uint8_t *)&packetNo; USB_txBuff[1] = 4; //length USB_txBuff[3] = 0x12; //opcode USB_txBuff[4] = u8pt[0]; USB_txBuff[5] = u8pt[1]; USB_txBuff[6] = u8pt[2]; USB_txBuff[7] = u8pt[3]; } break; case 0xA5: FLASH_Lock(); SysDeInit(); execute_user_code(); break; case 0x88: bootMode = 1; break; default: USB_txBuff[1] = 4; //length USB_txBuff[3] = 0x33; //opcode USB_txBuff[4] = 0xA5; USB_txBuff[5] = 0xA5; USB_txBuff[6] = 0xA5; USB_txBuff[7] = 0xA5; break; } if(USB_txBuff[3]) { USB_txBuff[0] = 0xCA; USB_txBuff[USB_txBuff[1] + 4] = CfgCalcCheckSum((uint8_t *)&USB_txBuff[4],USB_txBuff[1]); for(i = 0;i < USB_txBuff[1] + 4 + 1; i++) { USART3_PutChar(USB_txBuff[i]); } } USB_rxBuff[0] = 0; UART_ProtoRecv.opcode = 0; } } u32Pt = (uint32_t *)buff; SST25_Init(); SST25_Read(FIRMWARE_INFO_ADDR + FIRMWARE_STATUS_OFFSET*4,buff,4); if(*u32Pt != 0x5A5A5A5A) { execute_user_code(); } USART3_PutString("\r\nPROGRAM NEW FIRMWARE*\r\n"); tryNum = 10; exit = 0; while(!exit && tryNum--) { SST25_Read(FIRMWARE_INFO_ADDR + FIRMWARE_CRC_OFFSET*4,buff,4); fileCrc = *u32Pt; SST25_Read(FIRMWARE_INFO_ADDR + FIRMWARE_FILE_SIZE_OFFSET*4,buff,4); fileSize = *u32Pt; if(fileSize < FIRMWARE_MAX_SIZE) { flashCheckSum = 0; for(i = 0; i < fileSize;i += PAGE_SIZE) { USART3_PutChar('*'); SST25_Read(i + FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); for(j = 0 ; j < PAGE_SIZE;j++) { if(i + j < fileSize) flashCheckSum += buff[j]; else break; } myFMC_Erase(USER_FLASH_START + i); FMC_ProgramPage(USER_FLASH_START + i,u32Pt); SST25_Read(i + FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); memAddr = USER_FLASH_START + i; if(memcmp(buff, (void*)memAddr , PAGE_SIZE) != NULL) break; } if(flashCheckSum == fileCrc) { USART3_PutString("\r\nFINISHED!\r\n"); SST25_Read(BASE_FIRMWARE_INFO_ADDR + FIRMWARE_STATUS_OFFSET*4,buff,4); if(*u32Pt != 0x5A5A5A5A) { tryNum = 10; while(tryNum--) { flashCheckSum = 0; for(i = 0; i < fileSize;i += 256) { SST25_Read(i + FIRMWARE_BASE_ADDR,buff, 256); SST25_Write(i + BASE_FIRMWARE_BASE_ADDR,buff, 256); SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,flashBuff, 256); if(memcmp(buff,flashBuff,256) != NULL) { break; } } if(i >= fileSize) for(i = 0; i < fileSize;i += 256) { SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,buff, 256); for(j = 0 ; j < 256;j++) { if(i + j < fileSize) flashCheckSum += buff[j]; else break; } } if(flashCheckSum == fileCrc) { SST25_Read(FIRMWARE_INFO_ADDR,buff, 256); SST25_Write(BASE_FIRMWARE_INFO_ADDR,buff, 256); SST25_Read(BASE_FIRMWARE_INFO_ADDR,flashBuff, 256); if(memcmp(buff,flashBuff,256) == NULL) { break; } } } } exit = 1; } } } if(exit == 0 && tryNum == 0xff) { USART3_PutString("\r\nFAIL!\r\n"); USART3_PutString("\r\nDOWNLOAD BACKUP FIRMWARE*\r\n"); tryNum = 10; exit = 0; while(!exit && tryNum--) { SST25_Read(BASE_FIRMWARE_INFO_ADDR + FIRMWARE_CRC_OFFSET*4,buff,4); fileCrc = *u32Pt; SST25_Read(BASE_FIRMWARE_INFO_ADDR + FIRMWARE_FILE_SIZE_OFFSET*4,buff,4); fileSize = *u32Pt; if(fileSize < FIRMWARE_MAX_SIZE) { flashCheckSum = 0; for(i = 0; i < fileSize;i += PAGE_SIZE) { USART3_PutChar('*'); SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); for(j = 0 ; j < PAGE_SIZE;j++) { if(i + j < fileSize) flashCheckSum += buff[j]; else break; } myFMC_Erase(USER_FLASH_START + i); FMC_ProgramPage(USER_FLASH_START + i,u32Pt); SST25_Read(i + BASE_FIRMWARE_BASE_ADDR,buff, PAGE_SIZE); memAddr = USER_FLASH_START + i; if(memcmp(buff, (void*)memAddr , PAGE_SIZE) != NULL) break; } if(flashCheckSum == fileCrc) { exit = 1; USART3_PutString("\r\nDOWNLOAD BACKUP FINISHED!\r\n"); } } } } SST25_Erase(FIRMWARE_INFO_ADDR,block4k); execute_user_code(); while(1) { } }