aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Embedded_SW/Embedded/Common/SWUpdate/FileSystem.c
blob: d7592ccbae60cc234c3c26d301b10e0581232f33 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
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
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Tango.Scripting.Parsing
{
    public class ScriptParser
    {
        private const string fakeScript = "CurrentScript";
        private string fakeScriptName = "CurrentScript.";

        private String ReplaceFakeScript(String str)
        {
            if (str != null)
            {
                return str.Replace(fakeScriptName, "").Replace(fakeScript, "");
            }

            return str;
        }

        private CompilationUnitSyntax GetRoot(String code)
        {
            SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
            var root = (CompilationUnitSyntax)tree.GetRoot();
            return root;
        }

        private SemanticModel GetSemanticModel(String code)
        {
            SyntaxTree tree = CSharpSyntaxTree.ParseText(code);
            CompilationUnitSyntax root = 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 */
/*
 * 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/Flash_Memory.h"
#include "drivers/Flash_Memory/fatfs/ff.h"
#include "drivers/FPGA/FPGA_GPIO/FPGA_GPIO.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 5500
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;

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

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

    FRESULT Fresult = FR_OK;

    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;
    else
    {
        UploadFileHandle = my_malloc(sizeof(FIL));
        if (UploadFileHandle == 0)
            Fresult = FR_DENIED;
        else
        {
            if (Semaphore_pend(FFS_Sem, BIOS_NO_WAIT))
            {
                CommRxTaskHandle = Task_self();
                Task_setPri(CommRxTaskHandle, 3);
               // Report("Task_setPri", __FILE__, __LINE__, 4, 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)
                {
                    Report("FileUploadRequestFunc 3", __FILE__, __LINE__, msec_millisecondCounter, RpWarning,   (int)0, 0);
                    FileLength = request->length;
                    FileReceivedLength = 0;
                    REPORT_MSG (FileLength,"file upload request");
                    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(FFS_Sem);
                }
            }
            else
            {
                Fresult = FR_DENIED;
                Report("Semaphore_pend failed", __FILE__, __LINE__, 4, RpWarning,   (int)0, 0);
            }
        }
    }

    responseContainer = createContainer(MESSAGE_TYPE__FileUploadResponse,  requestContainer->token, false, &response, &file_upload_response__pack, &file_upload_response__get_packed_size);
    if (Fresult!= FR_OK)
    {
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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    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;
    KeepAliveOneSecondCounter = 0;
    save_milisec = msec_millisecondCounter;
    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__,WrittenBytes,FileReceivedLength, RpMessage,msec_millisecondCounter-save_milisec, 0);

            //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;
                }
            }
        }
    /*}
    else
    {
        LOG_ERROR (ReceivedFileHandle,"file id error");
        f_close(FileHandle);
        free (FileHandle);
        status = ERROR_CODE__FILE_NOT_FOUND;
    }*/

    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.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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, 9);
        Semaphore_post(FFS_Sem);
        //Report("Task_setPri", __FILE__, __LINE__, 9, 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);
        UploadFileHandle = 0;
        FileReceivedLength = 0;
        FileDone = true;
        Task_setPri(CommRxTaskHandle, 9);
        Semaphore_post(FFS_Sem);
    }
}
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
        {
            Semaphore_pend(FFS_Sem, BIOS_WAIT_FOREVER);
            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.
            }

        }
    }


    responseContainer = createContainer(MESSAGE_TYPE__FileDownloadResponse,  requestContainer->token, false, &response, &file_download_response__pack, &file_download_response__get_packed_size);
    if (Fresult!= FR_OK)
    {
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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,2000,&ReadBytes );
        if(Fresult != FR_OK)
        {
            LOG_ERROR (Fresult,"f_write error");
        }
        else
        {
            response.has_buffer = true;
            response.buffer.len = ReadBytes;
            response.buffer.data = Buffer;
            FileSentLength += ReadBytes;
            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.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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.error = ERROR_CODE__GENERAL_ERROR;//getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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.error = ERROR_CODE__GENERAL_ERROR;//getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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);
    }
    else
    {
        UploadFileHandle = my_malloc(sizeof(FIL));
        if (UploadFileHandle == 0)
            Fresult = FR_DENIED;
        else
        {
            Semaphore_pend(FFS_Sem, BIOS_WAIT_FOREVER);
            Fresult = f_open(UploadFileHandle,request->path,FA_CREATE_NEW);
            if (Fresult == FR_OK)
            {
                if (f_close (UploadFileHandle)!= FR_OK)
                {
                    Fresult = FR_LOCKED;
                }
            }
            Semaphore_post(FFS_Sem);
        }
    }
    if (Fresult != FR_OK)
    {
        //status = ERROR_CODE__FILE_NOT_FOUND;
        usnprintf(ErrorMsg, 100, "File Operation failed error code %d",Fresult);

    }
    free (UploadFileHandle);

    responseContainer = createContainer(MESSAGE_TYPE__CreateResponse,  requestContainer->token, false, &response, &create_response__pack, &create_response__get_packed_size);
    if (Fresult!= OK)
    {
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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;

    Semaphore_pend(FFS_Sem, BIOS_WAIT_FOREVER);
    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!= OK)
    {
        usnprintf(ErrorMsg, 100, "File Operation failed error code %d",Fresult);
        responseContainer.error = getErrorCode(Fresult);
        responseContainer.errormessage = ErrorMsg;
    }
    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.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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;

    #define MAX_NUM_OF_FILES 20
    DIR dir;
    FILINFO* fno[MAX_NUM_OF_FILES];
    char FullPath[MAX_NUM_OF_FILES][60];
    int i,NumOfFiles = 0;
    FRESULT Fresult = FR_OK;
    /*
    time_t t;
    struct tm *ltm;
    char *curTime;
    t = time(NULL);
    ltm = localtime(&t);
    curTime = asctime(ltm);
    Report(curTime, __FILE__, ltm->tm_hour,ltm->tm_min , RpWarning,  ltm->tm_sec, 0);
     */

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

    memset (fno,0,sizeof(fno));
    FileInfo **FilesInfo = (FileInfo**)my_malloc(sizeof(FileInfo *)*(MAX_NUM_OF_FILES));
    FileInfo Data[MAX_NUM_OF_FILES];
    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);

    if ((Fresult == FR_OK)&&(NumOfFiles))
    {
        for (i = 0;i < NumOfFiles;i++)
        {
           file_info__init(&Data[i]);
           FilesInfo[i] = &Data[i];
           Data[i].has_attribute = true;
           Data[i].attribute = fno[i]->fattrib;
           Data[i].name = fno[i]->fname;
           Data[i].has_length = true;
           Data[i].length = fno[i]->fsize;
           Data[i].has_lastmodifieddate = true;
           Data[i].lastmodifieddate = fno[i]->fdate;
           Data[i].has_lastmodifiedtime = true;
           Data[i].lastmodifiedtime = fno[i]->ftime;
           /*
           t = (fno[i]->fdate<<16)+fno[i]->ftime;
           ltm = localtime(&t);
           curTime = asctime(ltm);
           usnprintf(&Datestr, 100, "File info %s %s",fno[i]->fname, curTime);
           Report(Datestr, __FILE__, __LINE__, t, RpWarning,   (int)Data[i].lastmodifiedtime, 0);
           Task_sleep(50);
            */

           if (i==0)
               usnprintf(&FullPath[i], 50,  "%s", request->path);
           else
              if (strlen(request->path)==1) //info under the root
                  usnprintf(&FullPath[i], 50,  "%s%s", request->path, fno[i]->fname);
              else
               usnprintf(&FullPath[i], 50,  "%s%s%s", request->path,"/", fno[i]->fname);
           Data[i].fullpath = &FullPath[i];

        }
        response.n_items = NumOfFiles;
        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.error = getErrorCode(Fresult);
        responseContainer.errormessage = "File operation 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);
    }
    my_free(responseContainer.data.data);
    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 (Semaphore_pend(FFS_Sem, timeout) == false)
           {
               LOG_ERROR (false,"file system busy error");
               return FR_TIMEOUT;
           }

            Fresult = f_open(FileHandle,path,FA_WRITE |  FA_OPEN_ALWAYS);
            if (Fresult == FR_OK)
            {
                Fresult = f_write(FileHandle,buffer,size,&Bytes );
                if(Fresult != FR_OK)
                {
                    LOG_ERROR (Fresult,"fread error");
                }
                f_close(FileHandle);
            }
            else
            {
                LOG_ERROR (Fresult,"fopen error");
            }
            Semaphore_post(FFS_Sem);
            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
            {
                Semaphore_pend(FFS_Sem, BIOS_WAIT_FOREVER);
                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;
                    }
                    else
                    {
                        LOG_ERROR (Fresult,"fread error");
                        my_free (buffer);
                    }
                    f_close(FileHandle);
                    Semaphore_post(FFS_Sem);
                }
                else
                {
                    LOG_ERROR (Fresult,"fopen error");
                    my_free (buffer);
                }
                my_free(FileHandle);
            }
        }
        else
        {
            LOG_ERROR (Fresult,"malloc error");
        }
    }
    else
    {
        LOG_ERROR (Fresult,"f_stat error");
    }
    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
            Semaphore_pend(FFS_Sem, BIOS_WAIT_FOREVER);
            Fresult = f_open(FileHandle,path,FA_READ);
    }
    else
    {
        LOG_ERROR (Fresult,"f_stat error");
    }
    my_free(fno);
    return Fresult;
}