aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Embedded_SW/Embedded/Common/SWUpdate/FileSystem.c
blob: efc156da3692f84d58e065abda01e30d87cf7142 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
#include "stdafx.h"
#include "ProgressForm.h"

using namespace System::Windows::Forms;

namespace Tango
{
	namespace FirmwareUpdateLib
	{

	}
}
14'>214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
/*
 * FileSystem.c
 *
 *  Created on: Oct 23, 2018
 *      Author: shlomo
 */
#include "include.h"
#include "Communication/CommunicationTask.h"
#include "Communication/connection.h"
#include <DataDef.h>

#include  <Communication/PMR/IO/FileUploadRequest.pb-c.h>
#include  <Communication/PMR/IO/FileUploadResponse.pb-c.h>
#include  <Communication/PMR/IO/FileChunkUploadRequest.pb-c.h>
#include  <Communication/PMR/IO/FileChunkUploadResponse.pb-c.h>
#include  <Communication/PMR/IO/FileDownloadRequest.pb-c.h>
#include  <Communication/PMR/IO/FileDownloadResponse.pb-c.h>
#include  <Communication/PMR/IO/FileChunkDownloadRequest.pb-c.h>
#include  <Communication/PMR/IO/FileChunkDownloadResponse.pb-c.h>
#include  <Communication/PMR/IO/ExecuteProcessRequest.pb-c.h>
#include  <Communication/PMR/IO/ExecuteProcessResponse.pb-c.h>
#include  <Communication/PMR/IO/KillProcessRequest.pb-c.h>
#include  <Communication/PMR/IO/KillProcessResponse.pb-c.h>
#include  <Communication/PMR/IO/CreateRequest.pb-c.h>
#include  <Communication/PMR/IO/CreateResponse.pb-c.h>
#include  <Communication/PMR/IO/DeleteRequest.pb-c.h>
#include  <Communication/PMR/IO/DeleteResponse.pb-c.h>
#include  <Communication/PMR/IO/GetStorageInfoRequest.pb-c.h>
#include  <Communication/PMR/IO/GetStorageInfoResponse.pb-c.h>
#include  <Communication/PMR/IO/GetFilesRequest.pb-c.h>
#include  <Communication/PMR/IO/GetFilesResponse.pb-c.h>
#include  <Communication/PMR/IO/FileAttribute.pb-c.h>


#include "drivers/Flash_Memory/fatfs/ff.h"
#include "drivers/FPGA/FPGA_GPIO/FPGA_GPIO.h"

#include "Modules/Control/Control.h"
#include "StateMachines/Printing/PrintingSTM.h"


ErrorCode FileError_to_ErrorCode[FR_INVALID_PARAMETER+1] = {ERROR_CODE__NONE,ERROR_CODE__FILE_REQUEST_DISK_ERR,ERROR_CODE__FILE_REQUEST_INT_ERR,ERROR_CODE__FILE_REQUEST_NOT_READY,ERROR_CODE__FILE_REQUEST_NO_FILE,
                                                       ERROR_CODE__FILE_REQUEST_NO_PATH,ERROR_CODE__FILE_REQUEST_INVALID_NAME,ERROR_CODE__FILE_REQUEST_DENIED,ERROR_CODE__FILE_REQUEST_EXIST,ERROR_CODE__FILE_REQUEST_INVALID_OBJECT,
                                                       ERROR_CODE__FILE_REQUEST_WRITE_PROTECTED,ERROR_CODE__FILE_REQUEST_INVALID_DRIVE,ERROR_CODE__FILE_REQUEST_NOT_ENABLED,ERROR_CODE__FILE_REQUEST_NO_FILESYSTEM,
                                                       ERROR_CODE__FILE_REQUEST_MKFS_ABORTED,ERROR_CODE__FILE_REQUEST_TIMEOUT,ERROR_CODE__FILE_REQUEST_LOCKED,ERROR_CODE__FILE_REQUEST_NOT_ENOUGH_CORE,ERROR_CODE__FILE_REQUEST_TOO_MANY_OPEN_FILES,
                                                       ERROR_CODE__FILE_REQUEST_INVALID_PARAMETER};


FIL *UploadFileHandle = 0;  //the system supports a single active file
FIL *DownloadFileHandle = 0;  //the system supports a single active file
char FileHandleChar[5];
char ErrorMsg[100];
#define MAX_CHUNK_LENGTH 4096
int32_t FileLength = 0;
int32_t FileReceivedLength = 0;
int32_t FileSentLength = 0;
static char g_cCwdBuf[50] = "/";
uint32_t WrittenBytes = 0;
uint32_t ReadBytes = 0;
Task_Handle CommRxTaskHandle;

extern Semaphore_Handle FFS_Sem;
extern Semaphore_Handle FileUpload_sem_param;

ErrorCode getErrorCode(FRESULT Fresult)
{
    return  FileError_to_ErrorCode[Fresult];
}
bool isDirectory(FileAttribute FileAtt)
{
    if (FileAtt&&FILE_ATTRIBUTE__Directory)
        return true;
    return false;
}
bool FileDone = true;
bool FileUploadGetState(void)
{
    return FileDone;
}
int CommRxpri;

uint32_t    FileUploadRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    FRESULT Fresult = FR_OK;
    bool sem_ok = false;
    MessageContainer responseContainer;

    FileUploadRequest* request = file_upload_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    FileUploadResponse response = FILE_UPLOAD_RESPONSE__INIT;

    WrittenBytes=0;
    if (JobIsActive())
    {
        Fresult = FR_DENIED;
        Report("file uplad rejected - job is running", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
    }
    else
    {
        UploadFileHandle = my_malloc(sizeof(FIL));
        if (UploadFileHandle == 0)
            Fresult = FR_DENIED;
        else
        {
            if (1)//(Semaphore_pend(FileUpload_sem_param, BIOS_NO_WAIT))
            {
                sem_ok = true;
            }
            else
            {
                Semaphore_post(FileUpload_sem_param);
                Report("semaphore was not free", __FILE__, __LINE__, request->length, RpWarning,   (int)MAX_CHUNK_LENGTH, 0);
                sem_ok = true;
            }
            if (sem_ok == true)
            {
                CommRxTaskHandle = Task_self();
                CommRxpri = Task_getPri(CommRxTaskHandle);
                Task_setPri(CommRxTaskHandle, 11);
                Report("Task_setPri", __FILE__, __LINE__, 11, RpWarning,   (int)CommRxTaskHandle, 0);
                //Report("FileUploadRequestFunc 2", __FILE__, __LINE__, msec_millisecondCounter, RpWarning,   (int)0, 0);
                Fresult = f_open(UploadFileHandle,request->path,FA_READ | FA_WRITE | FA_OPEN_ALWAYS | FA_CREATE_ALWAYS);
                if (Fresult == FR_OK)
                {
                    usnprintf(ErrorMsg, 100, "file upload request %s %d",request->path,request->length);

                    Report(ErrorMsg, __FILE__, __LINE__, request->length, RpWarning,   (int)MAX_CHUNK_LENGTH, 0);
                    FileLength = request->length;
                    FileReceivedLength = 0;
                    response.has_maxchunklength = true;
                    response.maxchunklength = MAX_CHUNK_LENGTH;
                    strcpy(FileHandleChar, "1234");
                    response.uploadid = FileHandleChar; //supporting only single file at each time.
                    FileDone = false;
                }
                else
                {
                    my_free (UploadFileHandle);
                    UploadFileHandle = 0;
                    Semaphore_post(FileUpload_sem_param);
                }
            }
            else
            {
                Fresult = FR_DENIED;
                Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
            }
        }
    }

    responseContainer = createContainer(MESSAGE_TYPE__FileUploadResponse,  requestContainer->token, true, &response, &file_upload_response__pack, &file_upload_response__get_packed_size);
    if (Fresult!= FR_OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation upload request error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    my_free(responseContainer.data.data);
    file_upload_request__free_unpacked(request,NULL);
    SendChars(container_buffer, container_size);

    return OK;
}
FRESULT lFresult = FR_OK;
uint32_t Chunk_ControlId = 0xFF;
uint32_t FileChunkUploadCallBackFunction(uint32_t IfIndex, uint32_t BusyFlag)
{
    Report("chunk timeout error",__FILE__,IfIndex,FileReceivedLength,RpWarning,BusyFlag,0);
    f_close(UploadFileHandle);
    my_free (UploadFileHandle);
    UploadFileHandle = 0;
    FileReceivedLength = 0;
    FileDone = true;
    Task_setPri(CommRxTaskHandle, CommRxpri);
    Semaphore_post(FileUpload_sem_param);
    Report("Task_setPri", __FILE__, __LINE__, CommRxpri, RpWarning,   (int)CommRxTaskHandle, 0);
    if (SafeRemoveControlCallback(Chunk_ControlId, FileChunkUploadCallBackFunction )==OK)
        Chunk_ControlId = 0xFF;

    return OK;

}

uint32_t    FileChunkUploadRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;
    FRESULT Fresult = FR_OK;


    MessageContainer responseContainer;

    FileChunkUploadRequest* request = file_chunk_upload_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    FileChunkUploadResponse response = FILE_CHUNK_UPLOAD_RESPONSE__INIT;

    FIL *ReceivedFileHandle;  //the system supports a single active file

    uint32_t save_milisec = 0;
  //  if (request->uploadid == 1)
    ReceivedFileHandle = UploadFileHandle;
//    memcpy (&ReceivedFileHandle,request->uploadid,sizeof(ReceivedFileHandle));
    //if (ReceivedFileHandle == FileHandle)
    //{
    //Control_WD(ENABLE,55);  //activate heaters/dispenser watchdog, 0.5 seconds
    //GeneralHwReady = false;
    if (ReceivedFileHandle==NULL)
    {
        Fresult = FR_DENIED;
        Report("file chunk upload rejected - file not created", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
        FileDone = true;
    }
    else
    {
        KeepAliveOneSecondCounter = 0;
        save_milisec = msec_millisecondCounter;
        Chunk_ControlId = AddControlCallback("chunk", FileChunkUploadCallBackFunction, eOneSecond, TemplateDataReadCBFunction,0,request->buffer.len, WrittenBytes );

        Fresult = f_write(ReceivedFileHandle,request->buffer.data,request->buffer.len,&WrittenBytes );
        lFresult = Fresult;
        if(Fresult != FR_OK)
        {
            Report("f_write error",__FILE__,Fresult,FileReceivedLength,RpWarning,request->buffer.len,0);
            FileDone = true;
        }
        else
        {
            FileReceivedLength += WrittenBytes;
            ReportWithPackageFilter(CommFilter,"Chunk received", __FILE__,FileLength,FileReceivedLength, RpMessage,msec_millisecondCounter-save_milisec, 0);
            RemoveControlCallback(Chunk_ControlId, FileChunkUploadCallBackFunction );
            Chunk_ControlId = 0xFF;

            //REPORT_MSG (FileReceivedLength,"file upload chunk");
            if (FileReceivedLength == FileLength)
            {
                REPORT_MSG (FileReceivedLength,"file upload ended successfully");
                f_close(ReceivedFileHandle);
                my_free (UploadFileHandle);
                UploadFileHandle = 0;
                FileReceivedLength = 0;
                FileDone = true;
            }
            else
            {
                if (FileReceivedLength > FileLength)
                {
                    REPORT_MSG (FileReceivedLength,"file upload too much data!");
                    f_close(ReceivedFileHandle);
                    my_free (UploadFileHandle);
                    UploadFileHandle = 0;
                    FileReceivedLength = 0;
                    FileDone = true;
                }
            }
        }
    }

    responseContainer = createContainer(MESSAGE_TYPE__FileChunkUploadResponse,  requestContainer->token, FileDone, &response, &file_chunk_upload_response__pack, &file_chunk_upload_response__get_packed_size);
    if (Fresult!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation chunk upload error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    //my_free(request->buffer.data);
    file_chunk_upload_request__free_unpacked(request,NULL);
    my_free(responseContainer.data.data);
    SendCharsWithType(container_buffer, container_size,MESSAGE_TYPE__FileChunkUploadResponse);
    if (FileDone == true)
    {
        Task_setPri(CommRxTaskHandle, CommRxpri);
        Semaphore_post(FileUpload_sem_param);
        Report("Task_setPri", __FILE__, __LINE__, CommRxpri, RpWarning,   (int)CommRxTaskHandle, 0);
    }
    return OK;
}
void FileChunkUploadError(void)
{
    if (FileDone == false)
    {
        REPORT_MSG (FileReceivedLength,"file upload too much data!");
        f_close(UploadFileHandle);
        //my_free (UploadFileHandle); CAN NOT CALL FREE() FROM INTERRUPT
        UploadFileHandle = 0;
        FileReceivedLength = 0;
        FileDone = true;
        Task_setPri(CommRxTaskHandle, CommRxpri);
        Semaphore_post(FileUpload_sem_param);
    }
}
uint32_t    FileDownloadRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    FRESULT Fresult = FR_OK;
    FILINFO* fno;

    MessageContainer responseContainer;

    FileDownloadRequest* request = file_download_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    FileDownloadResponse response = FILE_DOWNLOAD_RESPONSE__INIT;

    ReadBytes=0;
    FileSentLength = 0;

    fno = my_malloc(sizeof(FILINFO));
    if (fno == 0)
        Fresult = FR_DENIED;
    else
    {
        memset (fno,0,sizeof(FILINFO));
        Fresult = f_stat(request->filename,fno);
        FileLength = fno->fsize;
        DownloadFileHandle = my_malloc(sizeof(FIL));
        if (DownloadFileHandle == 0)
            Fresult = FR_DENIED;
        else
        {
            if (1)//(Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
            {
                Fresult = f_open(DownloadFileHandle,request->filename,FA_READ  );
                if (Fresult == FR_OK)
                {
                    response.has_maxchunklength = true;
                    response.maxchunklength = MAX_CHUNK_LENGTH;
                    strcpy(FileHandleChar, "1234");
                    response.downloadid = FileHandleChar; //supporting only single file at each time.
                    Report("data request", __FILE__, 1234, MAX_CHUNK_LENGTH, RpWarning,   (int)fno->fsize, 0);
                }
                else
                {
                    Semaphore_post(FFS_Sem);
                }
            }
            else
            {
                Fresult = FR_DENIED;
                Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
            }
        }
    }


    responseContainer = createContainer(MESSAGE_TYPE__FileDownloadResponse,  requestContainer->token, false, &response, &file_download_response__pack, &file_download_response__get_packed_size);
    if (Fresult!= FR_OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation download request error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    my_free(responseContainer.data.data);
    file_download_request__free_unpacked(request,NULL);
    SendChars(container_buffer, container_size);
    my_free(fno);

    return OK;
}
uint32_t    FileChunkDownloadRequestFunc(MessageContainer* requestContainer)
{
    MessageContainer responseContainer;
    FileChunkDownloadRequest* request = file_chunk_download_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);
    FileChunkDownloadResponse response = FILE_CHUNK_DOWNLOAD_RESPONSE__INIT;
    FRESULT Fresult = FR_OK;
    FIL *SentFileHandle;  //the system supports a single active file

    SentFileHandle = DownloadFileHandle;
    uint8_t *Buffer = 0;
    Buffer = my_malloc (MAX_CHUNK_LENGTH);
    if (Buffer != NULL)
    {
        Fresult = f_read(SentFileHandle,Buffer,MAX_CHUNK_LENGTH,&ReadBytes );
        if(Fresult != FR_OK)
        {
            LOG_ERROR (Fresult,"f_read error");
            Semaphore_post(FFS_Sem);
        }
        else
        {
            response.has_buffer = true;
            response.buffer.len = ReadBytes;
            response.buffer.data = Buffer;
            FileSentLength += ReadBytes;
            Report("sending data to MS", __FILE__, ReadBytes, FileSentLength, RpWarning,   (int)FileLength, 0);
            if (FileSentLength == FileLength)
            {
                REPORT_MSG (FileSentLength,"file download ended successfully");
                f_close(SentFileHandle);
                Semaphore_post(FFS_Sem);
                my_free (DownloadFileHandle);
                FileSentLength = 0;
            }
            else
            {
                if (FileSentLength > FileLength)
                {
                    REPORT_MSG (FileSentLength,"file download too much data!");
                    f_close(SentFileHandle);
                    Semaphore_post(FFS_Sem);
                    my_free (DownloadFileHandle);
                    FileSentLength = 0;
                }
            }
        }
    }

    responseContainer = createContainer(MESSAGE_TYPE__FileChunkDownloadResponse,  requestContainer->token, false, &response, &file_chunk_download_response__pack, &file_chunk_download_response__get_packed_size);
    if (Fresult!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation chunk download error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    file_chunk_download_request__free_unpacked(request,NULL);
    my_free(responseContainer.data.data);
    my_free(Buffer);
    SendChars(container_buffer, container_size);

    return OK;
}
uint32_t    ExecuteProcessRequestFunc(MessageContainer* requestContainer)
{
    uint32_t status = OK;

    MessageContainer responseContainer;

    ExecuteProcessRequest* request = execute_process_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    ExecuteProcessResponse response = EXECUTE_PROCESS_RESPONSE__INIT;


    responseContainer = createContainer(MESSAGE_TYPE__ExecuteProcessResponse,  requestContainer->token, false, &response, &execute_process_response__pack, &execute_process_response__get_packed_size);
    if (status!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = ERROR_CODE__GENERAL_ERROR;//getErrorCode(Fresult);
        responseContainer.errormessage = "File operation execute error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    execute_process_request__free_unpacked(request,NULL);
    my_free(responseContainer.data.data);
    SendChars(container_buffer, container_size);

    return OK;
}
uint32_t    KillProcessRequestFunc(MessageContainer* requestContainer)
{
    uint32_t status = OK;

    MessageContainer responseContainer;

    KillProcessRequest* request = kill_process_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    KillProcessResponse response = KILL_PROCESS_RESPONSE__INIT;


    responseContainer = createContainer(MESSAGE_TYPE__KillProcessResponse,  requestContainer->token, false, &response, &kill_process_response__pack, &kill_process_response__get_packed_size);
    if (status!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = ERROR_CODE__GENERAL_ERROR;//getErrorCode(Fresult);
        responseContainer.errormessage = "File operation kill error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    my_free(responseContainer.data.data);
    kill_process_request__free_unpacked(request,NULL);
    SendChars(container_buffer, container_size);

    return OK;
}
uint32_t    CreateRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;
    FRESULT Fresult = FR_OK;
    MessageContainer responseContainer;

    CreateRequest* request = create_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    CreateResponse response = CREATE_RESPONSE__INIT;

    if (isDirectory(request->attribute))
    {
        Fresult = f_mkdir(request->path);
        if (Fresult == FR_EXIST)
            Fresult = FR_OK; //ingnore f_exist in directory create
    }
    else
    {
        UploadFileHandle = my_malloc(sizeof(FIL));
        if (UploadFileHandle == 0)
            Fresult = FR_DENIED;
        else
        {
            if (1)//(Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
            {
                Fresult = f_open(UploadFileHandle,request->path,FA_READ | FA_WRITE | FA_OPEN_ALWAYS | FA_CREATE_ALWAYS);
                if (Fresult == FR_OK)
                {
                    if (f_close (UploadFileHandle)!= FR_OK)
                    {
                        Fresult = FR_LOCKED;
                    }
                }
                Semaphore_post(FFS_Sem);
            }
            else
            {
                Fresult = FR_DENIED;
                Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
            }
        }
    }
    if (Fresult != FR_OK)
    {
        //status = ERROR_CODE__FILE_NOT_FOUND;
        //usnprintf(ErrorMsg, 100, "File Operation failed error code %d",Fresult);
        Report("File Operation failed error code", __FILE__, __LINE__, Fresult, RpWarning,   (int)0, 0);

    }
    free (UploadFileHandle);

    responseContainer = createContainer(MESSAGE_TYPE__CreateResponse,  requestContainer->token, false, &response, &create_response__pack, &create_response__get_packed_size);
    if (Fresult!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation create error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    my_free(responseContainer.data.data);
    create_request__free_unpacked(request,NULL);
    SendChars(container_buffer, container_size);

    return OK;
}
uint32_t    DeleteRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    MessageContainer responseContainer;

    DeleteRequest* request = delete_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    DeleteResponse response = DELETE_RESPONSE__INIT;

    FILINFO* fno = 0;
    //int NumOfFiles = 0;
    FRESULT Fresult = FR_OK;

    Fresult = f_unlink(request->path);
    Semaphore_post(FFS_Sem);

    REPORT_MSG(Fresult, "File Delete");
    responseContainer = createContainer(MESSAGE_TYPE__DeleteResponse,  requestContainer->token, false, &response, &delete_response__pack, &delete_response__get_packed_size);
    if ((Fresult!= FR_OK)&&(Fresult!= FR_NO_FILE))
    {
        //usnprintf(ErrorMsg, 100, "File Operation failed error code %d",Fresult);
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation delete error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    my_free(responseContainer.data.data);
    my_free(fno);
    delete_request__free_unpacked(request,NULL);
    SendChars(container_buffer, container_size);

    return OK;
}
uint32_t    GetStorageInfoRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    MessageContainer responseContainer;

    GetStorageInfoRequest* request = get_storage_info_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    GetStorageInfoResponse response = GET_STORAGE_INFO_RESPONSE__INIT;
    FATFS *fs;
    DWORD fre_clust, fre_sect, tot_sect;
    FRESULT Fresult = FR_OK;


    /* Get volume information and free clusters of drive 1 */
    Fresult = f_getfree("0:", &fre_clust, &fs);
     if (Fresult == FR_OK)
     {

    /* Get total sectors and free sectors */
         tot_sect = (fs->n_fatent - 2) * fs->csize;
         fre_sect = fre_clust * fs->csize;
         response.has_capacity = true;
         response.capacity = tot_sect/2*1024;
         response.has_freespace = true;
         response.freespace = fre_sect/2*1024;
         response.root = "/";
     }


    responseContainer = createContainer(MESSAGE_TYPE__GetStorageInfoResponse,  requestContainer->token, false, &response, &get_storage_info_response__pack, &get_storage_info_response__get_packed_size);
    if (Fresult!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation get storage info error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    size_t container_size = message_container__pack(&responseContainer, container_buffer);
    my_free(responseContainer.data.data);
    get_storage_info_request__free_unpacked(request,NULL);
    SendChars(container_buffer, container_size);

    return OK;
}
//char Datestr[100];

uint32_t    GetFilesRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    MessageContainer responseContainer;

    GetFilesRequest* request = get_files_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    GetFilesResponse response = GET_FILES_RESPONSE__INIT;
    //struct tm RTC_time;
    #define MAX_NUM_OF_FILES 40
    DIR dir;
    FILINFO* fno[MAX_NUM_OF_FILES];
    char FullPath[MAX_NUM_OF_FILES][60];
    int i,NumOfFiles = 0, ListedFiles = 0;
    FRESULT Fresult = FR_OK;
    FileInfo **FilesInfo = (FileInfo**)my_malloc(sizeof(FileInfo *)*(MAX_NUM_OF_FILES));
    FileInfo Data[MAX_NUM_OF_FILES];

    if (1)//(Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
    {
        Fresult |= f_opendir(&dir, g_cCwdBuf);
        if(Fresult != FR_OK)
        {
            Semaphore_post(FFS_Sem);
            return(Fresult);
        }

        memset (fno,0,sizeof(fno));
        memset(fno,0,sizeof(fno));
        fno[0] = my_malloc(sizeof(FILINFO));
        memset (fno[0],0,sizeof(FILINFO));

        //============================
        Fresult = f_opendir(&dir, request->path);                       /* Open the directory */
         if (Fresult == FR_OK)
         {
             for (NumOfFiles = 1;NumOfFiles < MAX_NUM_OF_FILES;NumOfFiles++)
             {
                 fno[NumOfFiles] = my_malloc(sizeof(FILINFO));
                 memset (fno[NumOfFiles],0,sizeof(FILINFO));
                 Fresult = f_readdir(&dir, fno[NumOfFiles]);                   /* Read a directory item */
                 if (Fresult == FR_OK)
                 {
                     if(fno[NumOfFiles]->fname[0] ==0)
                     {
                         break;
                     }
                 }
             }
         }
         Semaphore_post(FFS_Sem);
    }
    else
    {
        Fresult = FR_DENIED;
        Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
    }

    if ((Fresult == FR_OK)&&(NumOfFiles))
    {
        for (i = 0;i < NumOfFiles;i++)
        {
            if (i==0)
                usnprintf(&FullPath[ListedFiles], 50,  "%s", request->path);
            else
               if (strlen(request->path)==1) //info under the root
                   usnprintf(&FullPath[ListedFiles], 50,  "%s%s", request->path, fno[i]->fname);
               else
                usnprintf(&FullPath[ListedFiles], 50,  "%s%s%s", request->path,"/", fno[i]->fname);
           if (fno[i]->fattrib != 0xFF) //garbage
           {
               file_info__init(&Data[ListedFiles]);
               FilesInfo[ListedFiles] = &Data[ListedFiles];
               Data[ListedFiles].has_attribute = true;
               Data[ListedFiles].attribute = fno[i]->fattrib;
               Data[ListedFiles].name = fno[i]->fname;
               Data[ListedFiles].has_length = true;
               Data[ListedFiles].length = fno[i]->fsize;
               Data[ListedFiles].has_lastmodifieddate = true;
               Data[ListedFiles].lastmodifieddate = fno[i]->fdate;
               Data[ListedFiles].has_lastmodifiedtime = true;
               Data[ListedFiles].lastmodifiedtime = fno[i]->ftime;
               Data[ListedFiles].fullpath = &FullPath[i][0];
               ListedFiles++;
           }
           else
           {
              // f_unlink(Data[ListedFiles].fullpath);
		        Report("file system error - format FFS", __FILE__, __LINE__, 255, RpWarning,   (int)0, 0);
           }
           /*RTC_time.tm_year=(fno[i]->fdate>>9)+1980;//populate the time struct (FAT start==1980, RTC.year==0)
           RTC_time.tm_mon=(fno[i]->fdate>>5)&0x000F;
           RTC_time.tm_mday=fno[i]->fdate&0x001F;
           RTC_time.tm_hour=(fno[i]->ftime>>11)&0x001F;
           RTC_time.tm_min=(fno[i]->ftime>>5)&0x003F;
           RTC_time.tm_sec=(fno[i]->ftime<<1)&0x003E;*/


        }
        response.n_items = ListedFiles;
        response.items = FilesInfo;
    }
    else
    {
        response.n_items = 0;
        response.items = NULL;
    }
    responseContainer = createContainer(MESSAGE_TYPE__GetFilesResponse,  requestContainer->token, false, &response, &get_files_response__pack, &get_files_response__get_packed_size);

    if (Fresult!= OK)
    {
        responseContainer.has_error = true;
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation get files error";
    }
    responseContainer.continuous = false;
    uint8_t* container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    if (container_buffer)
    {
        size_t container_size = message_container__pack(&responseContainer, container_buffer);
        SendChars(container_buffer, container_size);
    }
    if (responseContainer.data.data)
        my_free(responseContainer.data.data);
    if (FilesInfo)
        my_free(FilesInfo);
    get_files_request__free_unpacked(request,NULL);
    for (i = 0;i < NumOfFiles;i++)
    {
        if (fno[i])
               my_free (fno[i]);
    }
    return Fresult;
}
FRESULT FileWrite(void * buffer, uint16_t size,char *path, uint32_t timeout)
{
    FRESULT Fresult = FR_OK;
    FIL *FileHandle = 0;  //the system supports a single active file
    uint32_t Bytes = 0;

    if (buffer)
    {
        FileHandle = my_malloc(sizeof(FIL));
        if (FileHandle == 0)
            Fresult = FR_DENIED;
        else
        {
            if (1)//(Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
            {
                Fresult = f_open(FileHandle,path,FA_WRITE |  FA_OPEN_ALWAYS|FA_CREATE_ALWAYS);
                if (Fresult == FR_OK)
                {
                    Fresult = f_write(FileHandle,buffer,size,&Bytes );
                    if(Fresult != FR_OK)
                    {
                        LOG_ERROR (Fresult,"fwrite error");
                    }
                    else
                    {
                        //LOG_ERROR (Bytes,"f_write ok no of bytes");
                         Report("f_write ok no of bytes", __FILE__, __LINE__, Bytes, RpWarning,   (int)size, 0);
                    }
                    f_close(FileHandle);
                }
                else
                {
                    LOG_ERROR (Fresult,"fopen error");
                }
                Semaphore_post(FFS_Sem);
            }
            else
            {
                Fresult = FR_DENIED;
                Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
            }

            my_free(FileHandle);
        }
    }
    return Fresult;
}
FRESULT FileRead(char *path, uint32_t *Size, void **Buffer)
{
    FRESULT Fresult = FR_OK;
    FIL *FileHandle = 0;  //the system supports a single active file
    FILINFO* fno = 0;
    void* buffer = NULL;
    uint32_t Bytes = 0;
    //uint32_t status  = 0;

    fno = my_malloc(sizeof(FILINFO));
    if (fno == 0)
        return ERROR;
    memset (fno,0,sizeof(FILINFO));
    Fresult = f_stat(path,fno);
    if (Fresult == FR_OK)
    {
        buffer = my_malloc (fno->fsize);
        if (buffer)
        {
            FileHandle = my_malloc(sizeof(FIL));
            if (FileHandle == 0)
                Fresult = FR_DENIED;
            else
            {
                if (1)//(Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
                {
                    Fresult = f_open(FileHandle,path,FA_READ);
                    if (Fresult == FR_OK)
                    {
                        Fresult = f_read(FileHandle,buffer,fno->fsize,&Bytes );
                        if(Fresult == FR_OK)
                        {
                            *Buffer = buffer;
                            *Size = (uint32_t)fno->fsize;
                            Report("f_read ok no of bytes", __FILE__, __LINE__, Bytes, RpWarning,   (int)fno->fsize, 0);
                        }
                        else
                        {
                            LOG_ERROR (Fresult,"fread error");
                            my_free (buffer);
                        }
                        f_close(FileHandle);
                    }
                    else
                    {
                        LOG_ERROR (Fresult,"fopen error");
                        my_free (buffer);
                    }
                    Semaphore_post(FFS_Sem);
                }
                else
                {
                    Fresult = FR_DENIED;
                    Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
                }
                my_free(FileHandle);
            }
        }
        else
        {
            Report("malloc error", __FILE__, __LINE__, Fresult, RpWarning,   (int)fno->fsize, 0);
            Fresult = FR_DENIED;
        }
    }
    else
    {
        Report("f_stat error", __FILE__, __LINE__, Fresult, RpWarning,   (int)0, 0);
        Fresult = FR_DENIED;
    }
    my_free(fno);
    return Fresult;
}
FRESULT FileOpen(char *path, uint32_t *Size, FIL *FileHandle)
{
    FRESULT Fresult = FR_OK;
    FILINFO* fno = 0;

    fno = my_malloc(sizeof(FILINFO));
    if (fno == 0)
        return ERROR;
    memset (fno,0,sizeof(FILINFO));
    Fresult = f_stat(path,fno);
    *Size = (uint32_t)fno->fsize;
    if (Fresult == FR_OK)
    {
        //FileHandle = my_malloc(sizeof(FIL));
        if (FileHandle == 0)
            Fresult = FR_DENIED;
        else
            if (1)//(Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
            {
                Fresult = f_open(FileHandle,path,FA_READ);
                Semaphore_post(FFS_Sem); //will be closed with the f_close, in the job
            }
            else
            {
                Fresult = FR_DENIED;
                Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
            }
    }
    else
    {
        Report("f_stat error", __FILE__, __LINE__,Fresult, RpWarning,   (int)0, 0);
    }
    my_free(fno);
    return Fresult;
}