Ejemplo n.º 1
0
DRESULT sflash_disk_init (void) {
    _i32 fileHandle;
    SlFsFileInfo_t FsFileInfo;

    if (!sflash_init_done) {
        // Allocate space for the block cache
        ASSERT ((sflash_block_cache = mem_Malloc(SFLASH_BLOCK_SIZE)) != NULL);
        sflash_init_done = true;
        sflash_prblock = UINT32_MAX;
        sflash_cache_is_dirty = false;

        // In order too speed up booting, check the last block, if exists, then
        // it means that the file system has been already created
        print_block_name (SFLASH_BLOCK_COUNT - 1);
        sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
        if (!sl_FsGetInfo(sflash_block_name, 0, &FsFileInfo)) {
            sl_LockObjUnlock (&wlan_LockObj);
            return RES_OK;
        }
        sl_LockObjUnlock (&wlan_LockObj);

        // Proceed to format the memory
        for (int i = 0; i < SFLASH_BLOCK_COUNT; i++) {
            print_block_name (i);
            sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
            // Create the block file if it doesn't exist
            if (sl_FsGetInfo(sflash_block_name, 0, &FsFileInfo) != 0) {
                if (!sl_FsOpen(sflash_block_name, FS_MODE_OPEN_CREATE(SFLASH_BLOCK_SIZE, 0), NULL, &fileHandle)) {
                    sl_FsClose(fileHandle, NULL, NULL, 0);
                    sl_LockObjUnlock (&wlan_LockObj);
                    memset(sflash_block_cache, 0xFF, SFLASH_BLOCK_SIZE);
                    if (!sflash_access(FS_MODE_OPEN_WRITE, sl_FsWrite)) {
                        return RES_ERROR;
                    }
                }
                else {
                    // Unexpected failure while creating the file
                    sl_LockObjUnlock (&wlan_LockObj);
                    return RES_ERROR;
                }
            }
            sl_LockObjUnlock (&wlan_LockObj);
        }
    }
    return RES_OK;
}
Ejemplo n.º 2
0
bool updater_start (void) {
    _u32 AccessModeAndMaxSize = FS_MODE_OPEN_WRITE;
    SlFsFileInfo_t FsFileInfo;
    bool result = false;

    sl_LockObjLock (&wlan_LockObj, SL_OS_WAIT_FOREVER);
    if (0 != sl_FsGetInfo((_u8 *)updater_data.path, 0, &FsFileInfo)) {
        // file doesn't exist, create it
        AccessModeAndMaxSize = FS_MODE_OPEN_CREATE(updater_data.fsize, 0);
    }
    if (!sl_FsOpen((_u8 *)updater_data.path, AccessModeAndMaxSize, NULL, &updater_data.fhandle)) {
        updater_data.foffset = 0;
        result = true;
    }
    sl_LockObjUnlock (&wlan_LockObj);
    return result;
}
Ejemplo n.º 3
0
_i32 sl_extlib_FlcOpenFile(_u8 *file_name, _i32 file_size, _u32 *ulToken, _i32 *lFileHandle, _i32 open_flags)
{
	char uclocalFilename[100];

	if(open_flags == _FS_MODE_OPEN_READ)
	{
		return sl_FsOpen((_u8 *)file_name,
				_FS_MODE_OPEN_READ, ulToken, lFileHandle);
	}
	else
	{
		/* MCU image name should be changed */
		if(strstr((char *)file_name, "/sys/mcuimgA") != NULL)
		{
			switch(_McuImageGetNewIndex())
			{
			case IMG_ACT_USER1:
				strcpy(uclocalFilename,IMG_USER_1);
				break;

			case IMG_ACT_USER2:
				strcpy(uclocalFilename,IMG_USER_2);
				break;
			}

			/* make sure that the file is not opened as
			fail-safe since it might fill the entire SFLASH and
	      		it is not required for the MCU image */

			open_flags &= ~_FS_FILE_OPEN_FLAG_COMMIT;
			Report("sl_extlib_FlcOpenFile: MCU image"
					"name converted to %s \r\n", uclocalFilename);
		}
		else
		{
			strcpy(uclocalFilename,(char *)file_name);
		}
		return sl_FsOpen((_u8 *)uclocalFilename,
				FS_MODE_OPEN_CREATE(file_size, open_flags),
				ulToken, lFileHandle);
	}
}
Ejemplo n.º 4
0
Archivo: main.c Proyecto: dlugaz/All
//****************************************************************************
//
//! \brief Obtain the file from the server
//!
//!  This function requests the file from the server and save it on serial flash.
//!  To request a different file for different user needs to modify the
//!  PREFIX_BUFFER macros.
//!
//! \param[in] cli - Instance of the HTTP connection
//!
//! \return         0 for success and negative for error
//
//****************************************************************************
static int GetData(HTTPCli_Handle cli)
{
    long          lRetVal = 0;
    long          fileHandle = -1;
    unsigned long Token = 0;
    int id;
    int len=0;
    bool moreFlag = 0;
    HTTPCli_Field fields[3] = {
                                {HTTPCli_FIELD_NAME_HOST, HOST_NAME},
                                {HTTPCli_FIELD_NAME_ACCEPT, "text/html, application/xhtml+xml, */*"},
                                {NULL, NULL}
                              };

    const char *ids[4] = {
                            HTTPCli_FIELD_NAME_CONTENT_LENGTH,
                            HTTPCli_FIELD_NAME_TRANSFER_ENCODING,
                            HTTPCli_FIELD_NAME_CONNECTION,
                            NULL
                         };


    UART_PRINT("Start downloading the file\r\n");

    // Set request fields
    HTTPCli_setRequestFields(cli, fields);

    memset(g_buff, 0, sizeof(g_buff));

    // Make HTTP 1.1 GET request
    lRetVal = HTTPCli_sendRequest(cli, HTTPCli_METHOD_GET, PREFIX_BUFFER, 0);
    if (lRetVal < 0)
    {
        // error
        ASSERT_ON_ERROR(TCP_SEND_ERROR);
    }

    // Test getResponseStatus: handle
    lRetVal = HTTPCli_getResponseStatus(cli);
    if (lRetVal != 200)
    {
        FlushHTTPResponse(cli);
        if(lRetVal == 404)
        {
            ASSERT_ON_ERROR(FILE_NOT_FOUND_ERROR);
        }
        ASSERT_ON_ERROR(INVALID_SERVER_RESPONSE);
    }

    HTTPCli_setResponseFields(cli, ids);

    // Read response headers
    while ((id = HTTPCli_getResponseField(cli, (char *)g_buff, sizeof(g_buff), &moreFlag)) 
               != HTTPCli_FIELD_ID_END)
    {

        if(id == 0)
        {
            UART_PRINT("Content length: %s\n\r", g_buff);
        }
        else if(id == 1)
        {
            if(!strncmp((const char *)g_buff, "chunked", sizeof("chunked")))
            {
                UART_PRINT("Chunked transfer encoding\n\r");
            }
        }
        else if(id == 2)
        {
            if(!strncmp((const char *)g_buff, "close", sizeof("close")))
            {
                ASSERT_ON_ERROR(FORMAT_NOT_SUPPORTED);
            }
        }

    }

    // Open file to save the downloaded file
    lRetVal = sl_FsOpen((_u8 *)FILE_NAME, FS_MODE_OPEN_WRITE, &Token, &fileHandle);
    if(lRetVal < 0)
    {
        // File Doesn't exit create a new of 40 KB file
        lRetVal = sl_FsOpen((unsigned char *)FILE_NAME, \
                           FS_MODE_OPEN_CREATE(SIZE_40K, \
                           _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
                           &Token, &fileHandle);
        ASSERT_ON_ERROR(lRetVal);

    }



    while(1)
    {
        len = HTTPCli_readResponseBody(cli, (char *)g_buff, sizeof(g_buff) - 1, &moreFlag);
        if(len < 0)
        {
            // Close file without saving
            lRetVal = sl_FsClose(fileHandle, 0, (unsigned char*) "A", 1);
            return lRetVal;
        }

        lRetVal = sl_FsWrite(fileHandle, bytesReceived,
                                (unsigned char *)g_buff, len);

        if(lRetVal < len)
        {
            UART_PRINT("Failed during writing the file, Error-code: %d\r\n", \
                         FILE_WRITE_ERROR);
            // Close file without saving
            lRetVal = sl_FsClose(fileHandle, 0, (unsigned char*) "A", 1);
            return lRetVal;
        }
        bytesReceived +=len;

        if ((len - 2) >= 0 && g_buff[len - 2] == '\r' && g_buff [len - 1] == '\n'){
            break;
        }

        if(!moreFlag)
        {
            break;
        }
    }

    //
    // If user file has checksum which can be used to verify the temporary
    // file then file should be verified
    // In case of invalid file (FILE_NAME) should be closed without saving to
    // recover the previous version of file
    //

    // Save and close file
    UART_PRINT("Total bytes received: %d\n\r", bytesReceived);
    lRetVal = sl_FsClose(fileHandle, 0, 0, 0);
    ASSERT_ON_ERROR(lRetVal);

    return SUCCESS;
}
Ejemplo n.º 5
0
//*****************************************************************************
//
//!  This funtion includes the following steps:
//!  -open a user file for writing
//!  -write "Old MacDonalds" child song 37 times to get just below a 64KB file
//!  -close the user file
//!
//!  /param[out] ulToken : file token
//!  /param[out] lFileHandle : file handle
//!
//!  /return  0:Success, -ve: failure
//
//*****************************************************************************
long WriteFileToDevice(unsigned long *ulToken, long *lFileHandle)
{
    long lRetVal = -1;
    int iLoopCnt = 0;

    //
    //  create a user file
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                FS_MODE_OPEN_CREATE(65536, \
                          _FS_FILE_OPEN_FLAG_COMMIT|_FS_FILE_PUBLIC_WRITE),
                        ulToken,
                        lFileHandle);
    if(lRetVal < 0)
    {
        //
        // File may already be created
        //
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        ASSERT_ON_ERROR(lRetVal);
    }
    else
    {
        //
        // close the user file
        //
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        if (SL_RET_CODE_OK != lRetVal)
        {
            ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
        }
    }
    
    //
    //  open a user file for writing
    //
    lRetVal = sl_FsOpen((unsigned char *)USER_FILE_NAME,
                        FS_MODE_OPEN_WRITE, 
                        ulToken,
                        lFileHandle);
    if(lRetVal < 0)
    {
        lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
        ASSERT_ON_ERROR(FILE_OPEN_WRITE_FAILED);
    }
    
    //
    // write "Old MacDonalds" child song as many times to get just below a 64KB file
    //
    for (iLoopCnt = 0; 
            iLoopCnt < (SL_MAX_FILE_SIZE / sizeof(gaucOldMacDonald)); 
            iLoopCnt++)
    {
        lRetVal = sl_FsWrite(*lFileHandle,
                    (unsigned int)(iLoopCnt * sizeof(gaucOldMacDonald)), 
                    (unsigned char *)gaucOldMacDonald, sizeof(gaucOldMacDonald));
        if (lRetVal < 0)
        {
            lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
            ASSERT_ON_ERROR(FILE_WRITE_FAILED);
        }
    }
    
    //
    // close the user file
    //
    lRetVal = sl_FsClose(*lFileHandle, 0, 0, 0);
    if (SL_RET_CODE_OK != lRetVal)
    {
        ASSERT_ON_ERROR(FILE_CLOSE_ERROR);
    }

    return SUCCESS;
}
Ejemplo n.º 6
0
short saveConfig() {
    long status = 0;
    long configFile = -1;

    UART_PRINT("[Blink] Saving configuration\r\n");

    status = sl_FsOpen((unsigned char *) CONFIG_FILENAME,
                       FS_MODE_OPEN_CREATE(65536, _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
                       NULL, &configFile);
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }

        return status;
    }

    sl_FsClose(configFile, 0, 0, 0);

    configFile = -1;
    status = sl_FsOpen((unsigned char *) CONFIG_FILENAME, FS_MODE_OPEN_WRITE, NULL, &configFile);
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Application Id            : %s\r\n", g_ApplicationID);
    long readOffset = 0;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_ApplicationID, sizeof(g_ApplicationID));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Client key                : %s\r\n", g_ClientKey);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_ClientKey, sizeof(g_ClientKey));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Installation Id           : %s\r\n", g_InstallationID);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_InstallationID, sizeof(g_InstallationID));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Session token             : %s\r\n", g_SessionToken);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_SessionToken, sizeof(g_SessionToken));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    UART_PRINT("[Blink] Device name               : %s\r\n", g_DeviceName);
    readOffset = readOffset + status;
    status = sl_FsWrite(configFile, readOffset, (unsigned char *)g_DeviceName, sizeof(g_DeviceName));
    if (status < 0) {
        ERR_PRINT(status);
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
            UART_PRINT("[Blink] No available blocks. Need to flash your device file system...\r\n");
        }
        sl_FsClose(configFile, 0, 0, 0);
        return status;
    }

    sl_FsClose(configFile, 0, 0, 0);

    return status;
}
Ejemplo n.º 7
0
Archivo: main.cpp Proyecto: hangc2/wif
static void TFTPTask(void *pvParameters)
{
    SlSecParams_t secParams;
    unsigned char *pucFileBuffer = NULL;  // Data read or to be written
    unsigned long uiFileSize;

    const char *FileRead = "readFromServer.txt";  // File to be read using TFTP. Change string to filename
    const char *FileWrite = "writeToServer.txt"; // File to be written using TFTP. Change string to filename.

    long pFileHandle;			// Pointer to file handle
    SlFsFileInfo_t pFsFileInfo;
    long lRetVal = -1;
    unsigned short uiTftpErrCode;


//get wifi information
  //  get_wifi_info(ap_ssid, secPrams);

    // Configuring security parameters for the AP
    secParams.Key = (_i8*)SSID_KEY;
    secParams.KeyLen = 30;
    secParams.Type = SL_SEC_TYPE_WPA_WPA2;

    lRetVal = Network_IF_InitDriver(ROLE_STA);


    // Connecting to WLAN AP - Set with static parameters defined at the top
    // After this call we will be connected and have IP address
    lRetVal = Network_IF_ConnectAP((char*)SSID,secParams);

    UART_PRINT("Connecting to TFTP server %d.%d.%d.%d\n\r",\
                  SL_IPV4_BYTE(TFTP_IP, 3),SL_IPV4_BYTE(TFTP_IP, 2),
                  SL_IPV4_BYTE(TFTP_IP, 1),SL_IPV4_BYTE(TFTP_IP, 0));
    if(TFTP_READ)
    {
        uiFileSize = FILE_SIZE_MAX;

        pucFileBuffer = new unsigned char[uiFileSize];
        if(NULL == pucFileBuffer)
        {
            UART_PRINT("Can't Allocate Resources\r\n");
            LOOP_FOREVER();
        }

        memset(pucFileBuffer,'\0',uiFileSize);

        lRetVal = sl_TftpRecv(TFTP_IP, FileRead, (char *)pucFileBuffer,\
                                &uiFileSize, &uiTftpErrCode );
        UART_PRINT("file read is %s\n", pucFileBuffer);

        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsGetInfo((unsigned char *)FileRead, 0, &pFsFileInfo);

        if(lRetVal < 0 )
            lRetVal = sl_FsOpen((unsigned char *)FileRead,\
                    FS_MODE_OPEN_CREATE(FILE_SIZE_MAX,_FS_FILE_OPEN_FLAG_COMMIT|\
                      _FS_FILE_PUBLIC_WRITE), NULL,&pFileHandle);
        else
            lRetVal = sl_FsOpen((unsigned char *)FileRead,FS_MODE_OPEN_WRITE, \
                                NULL,&pFileHandle);

        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsWrite(pFileHandle,0, pucFileBuffer, uiFileSize);

        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            lRetVal = sl_FsClose(pFileHandle,0,0,0);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        UART_PRINT("TFTP Read Successful \r\n");

        lRetVal = sl_FsClose(pFileHandle,0,0,0);

    }

    if(TFTP_WRITE)
    {
    	/* open same file which has been written with the server's file content */
        lRetVal = sl_FsOpen((unsigned char *)FileRead,FS_MODE_OPEN_READ, \
                                NULL,&pFileHandle);
        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsGetInfo((unsigned char *)FileRead, 0, &pFsFileInfo);
        if(lRetVal < 0)
        {
            lRetVal = sl_FsClose(pFileHandle,0,0,0);
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        uiFileSize = (&pFsFileInfo)->FileLen;

        lRetVal = sl_FsRead(pFileHandle, 0,  pucFileBuffer, uiFileSize);
        if(lRetVal < 0)
        {
            lRetVal = sl_FsClose(pFileHandle,0,0,0);
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        lRetVal = sl_FsClose(pFileHandle,0,0,0);
        /* write to server with different file name */
        lRetVal = sl_TftpSend(TFTP_IP, FileWrite,(char *) pucFileBuffer,\
                            &uiFileSize, &uiTftpErrCode  );
        if(lRetVal < 0)
        {
            free(pucFileBuffer);
            ERR_PRINT(lRetVal);
            LOOP_FOREVER();
        }

        UART_PRINT("TFTP Write Successful \r\n");
    }

    LOOP_FOREVER();
}
short saveClientState(ParseClientInternal *parseClient) {
#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Saving client state\r\n");
#endif /* CLIENT_DEBUG */

    snprintf(clientStateFileName, CLIENT_STATE_FILENAME_LEN, CLIENT_STATE_FILENAME, parseClient->applicationId);

    long clientStateFile = -1;

    sl_FsDel((unsigned char *)clientStateFileName, 0);

    short status = sl_FsOpen((unsigned char *)clientStateFileName,
            FS_MODE_OPEN_CREATE(65536, _FS_FILE_OPEN_FLAG_COMMIT | _FS_FILE_PUBLIC_WRITE),
            NULL, &clientStateFile);
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        return status;
    }

    sl_FsClose(clientStateFile, 0, 0, 0);

    clientStateFile = -1;
    status = sl_FsOpen((unsigned char *)clientStateFileName, FS_MODE_OPEN_WRITE, NULL, &clientStateFile);
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Installation Id: %s\r\n", parseClient->installationId);
#endif /* CLIENT_DEBUG */
    long writeOffset = 0;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->installationId, sizeof(parseClient->installationId));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Session token: %s\r\n", parseClient->sessionToken);
#endif /* CLIENT_DEBUG */
    writeOffset = writeOffset + status;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->sessionToken, sizeof(parseClient->sessionToken));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

#ifdef CLIENT_DEBUG
    DEBUG_PRINT("[Parse] Last push hash: %s\r\n", parseClient->lastPushHash);
#endif /* CLIENT_DEBUG */
    writeOffset = writeOffset + status;
    status = sl_FsWrite(clientStateFile, writeOffset, (unsigned char *)parseClient->lastPushHash, sizeof(parseClient->lastPushHash));
    if (status < 0) {
#ifdef CLIENT_DEBUG
        if (status == SL_FS_ERR_NO_AVAILABLE_BLOCKS) {
             DEBUG_PRINT("[Parse] No available blocks. Need to flash your device file system...\r\n");
        }
#endif /* CLIENT_DEBUG */
        sl_FsClose(clientStateFile, 0, 0, 0);
        return status;
    }

    sl_FsClose(clientStateFile, 0, 0, 0);

    return status;
}
Ejemplo n.º 9
0
int GetFileFromServer(const int socket, const char* filename, const char* filenameInFlash) {
	int transfer_len = 0;
	long retVal = 0;
	long fileHandle = -1;
	unsigned long Token = 0, bytesReceived = 0;
	unsigned char *pBuff = 0;
	unsigned long file_size = 0;
	unsigned char buffer[MAX_BUFF_SIZE + 1];

	UART_PRINT("Start downloading the file %s\r\n", filename);

	memset(buffer, 0, sizeof(buffer));

	// Puts together the HTTP GET string.
	strcpy((char *) buffer, PREFIX_BUFFER);
	strcat((char *) buffer, filename);
	strcat((char *) buffer, POST_BUFFER);

	// Send the HTTP GET string to the opened TCP/IP socket.
	transfer_len = sl_Send(socket, buffer, strlen((const char *) buffer), 0);
	if (transfer_len < 0) {
		// error
		UART_PRINT("Socket Send Error\r\n");
		return -1;
	}

	memset(buffer, 0, sizeof(buffer));

	// get the reply from the server in buffer.
	transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0);

	if (transfer_len > 0) {
		// Check for 404 return code
		if (strstr((const char *) buffer, HTTP_FILE_NOT_FOUND) != 0) {
			UART_PRINT("File not found, check the file and try again\r\n");
			return -1;
		}

		// if not "200 OK" return error
		if (strstr((const char *) buffer, HTTP_STATUS_OK) == 0) {
			UART_PRINT("Error during downloading the file\r\n");
			return -1;
		}

		// check if content length is transfered with headers
		pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_CONTENT_LENGTH);
		if (pBuff != 0) {
			pBuff += strlen(HTTP_CONTENT_LENGTH);

			while (*pBuff != 0x0d)
				pBuff++;
			unsigned long multiplicant = 1;

			pBuff--;
			while (*pBuff != ' ') {
				file_size += (*pBuff - '0') * multiplicant;
				multiplicant *= 10;
				pBuff--;
			}

			if (file_size == 0) {
				UART_PRINT("\nContent Length not detected.\r\n");
				return -1;
			}

			UART_PRINT("Content Length %d\r\n", file_size);
		} else {
			UART_PRINT("\nContent Length not detected.\r\n");
			return -1;
		}

		// "\r\n\r\n" marks the end of headers
		pBuff = (unsigned char *) strstr((const char *) buffer, HTTP_END_OF_HEADER);
		if (pBuff == 0) {
			UART_PRINT("Invalid response\r\n");
			return -1;
		}
		// Increment by 4 to skip "\r\n\r\n"
		pBuff += 4;

		// Adjust buffer data length for header size
		transfer_len -= (pBuff - buffer);
	}

	// Delete eventually existing temporary file
	sl_FsDel((unsigned char *) filenameInFlash, Token);
	// Create a temporary file to save the downloaded file
	// open a user file for writing
	retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_WRITE, &Token, &fileHandle);
	if (retVal < 0) {
		// File Doesn't exit create a new of file_size KB file
		retVal = sl_FsOpen((unsigned char *) filenameInFlash, FS_MODE_OPEN_CREATE(file_size, _FS_FILE_PUBLIC_WRITE), &Token, &fileHandle);
		if (retVal < 0) {
			UART_PRINT("Error during opening the temporary file\r\n");
			return -1;
		}
	}
	while (bytesReceived < file_size) {
		retVal = sl_FsWrite(fileHandle, bytesReceived, (unsigned char *) pBuff, transfer_len);
		if (retVal < 0) {
			retVal = sl_FsClose(fileHandle, 0, 0, 0);
			retVal = sl_FsDel((unsigned char *) filenameInFlash, Token);
			UART_PRINT("Error during writing the file\r\n");
			return -1;
		}
		bytesReceived += transfer_len;
		if (bytesReceived == file_size) break;

		memset(buffer, 0, sizeof(buffer));
		transfer_len = sl_Recv(socket, buffer, MAX_BUFF_SIZE, 0);
		pBuff = buffer;
	}

	// Close the opened file
	retVal = sl_FsClose(fileHandle, 0, 0, 0);

	if (bytesReceived != file_size) {
		UART_PRINT("Error While File Download\r\n");
		retVal = sl_FsDel((unsigned char *) filenameInFlash, Token);
		return -1;
	} else {
		UART_PRINT("\nDownloading File Completed\r\n");
	}
	return 0;
}