aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Embedded_SW/Embedded/StateMachines/Printing/JobSTM.c
blob: 08233ce9a6a6f5b0ea5e0b6d808de3a5832cb69e (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
0'>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 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
/************************************************************************************************************************
 * Printing.c
 * High managment logical unit of slow motors in the system ( 6 dispensers and the screw motor)
 * profile run up begins from screw homing to begin position and only then from fast motors activation.
 * when every slow motor tuches the limit switch (no matter whether its screw or dispenser)
 * an interrupt occures in the system and as long as its pushing the limit switch all the system is prevented from operation.
 * because of that the work flow with interrupts must be :
	 * design a function handle (what to do in the moment the interrupt arrives)
	 * configure the wanted interrupt in the cfg file (according to the defined port and pin and its interrupt number and the handler)
	 * enable interupt for predefined gpio in the application
	 * when the interrupt arrives the handle will be automatically called
	 * in case of the limit switches since the operation is continuess the interrupt must be disabled in order to continue the application running.
	 * then the operation is not continues (like butten pushing) there is no need in disabling the interrupts

 * Printing module is responsible for :
 	 * operating diffrent winding algorithms with predefined parameters from the UI
 	 * operating the dispensers according to predefined dispensing rate from the UI
 **************************************************************************************************************************/

////////////////////////////////State machine operation////////////////////////////////////
//the state machine operation is used to operate in runtime correct profile flow execution
//by recieved esign flow of the user from the UI
///////////////////////////////////////////////////////////////////////////////////////////
#include <Container.h>
#include <DataDef.h>
#include "include.h"
#include <ti/sysbios/knl/mailbox.h>
#include <ti/sysbios/knl/Clock.h>
#include <ti/sysbios/knl/task.h>

#include "Common/report/report.h"

#include "PMR/Printing/JobSegment.pb-c.h"
#include "PMR/Printing/JobRequest.pb-c.h"
#include "PMR/Printing/JobResponse.pb-c.h"
#include "PMR/Printing/CurrentJobRequest.pb-c.h"
#include "PMR/Printing/CurrentJobResponse.pb-c.h"
#include "PMR/Printing/ResumeCurrentJobRequest.pb-c.h"
#include "PMR/Printing/ResumeCurrentJobResponse.pb-c.h"
#include "PMR/Printing/JobStatus.pb-c.h"
#include "PMR/Printing/AbortJobRequest.pb-c.h"
#include "PMR/Printing/AbortJobResponse.pb-c.h"
#include "PMR/Hardware/Hardwaremotor.pb-c.h"
#include "PMR/Hardware/HardwareWinder.pb-c.h"
#include "PMR/common/MessageContainer.pb-c.h"
#include "Modules/General/process.h"
#include "modules/Diagnostics/Diagnostics.h"

#include "PMR/Stubs/StubJobRequest.pb-c.h"
#include "PMR/Stubs/StubJobResponse.pb-c.h"
#include "PMR/Stubs/StubAbortJobRequest.pb-c.h"
#include "PMR/Stubs/StubAbortJobResponse.pb-c.h"

#include "PMR/Diagnostics/ThreadJoggingRequest.pb-c.h"
#include "PMR/Diagnostics/ThreadJoggingResponse.pb-c.h"
#include "PMR/Diagnostics/ThreadAbortJoggingRequest.pb-c.h"
#include "PMR/Diagnostics/ThreadAbortJoggingResponse.pb-c.h"


#include "./printingSTM.h"
#include "modules/thread/thread_ex.h"
#include "modules/AlarmHandling/AlarmHandling.h"
#include "modules/ids/ids_ex.h"
#include "Modules/heaters/heaters_ex.h"
#include "Modules/control/control.h"


#define MAX_TICKET_SIZE  10000

Mailbox_Handle JobmsgQ = NULL;

JobEndReasonEnum JobEndReason = JOB_OK;
ErrorCode JobError_to_ErrorCode[JOB_ERRORS_MAX+1] = {ERROR_CODE__NONE,ERROR_CODE__JOB_UNSPECIFIED_ERROR,ERROR_CODE__JOB_THREAD_BREAK,ERROR_CODE__JOB_WINDER_DANCER_FAIL,
                                                      ERROR_CODE__JOB_POOLER_DANCER_FAIL,ERROR_CODE__JOB_FEEDER_DANCER_FAIL,ERROR_CODE__JOB_OUT_OF_DYE,ERROR_CODE__JOB_OTHER_ALARM,
                                                      ERROR_CODE__JOB_TEMPERATURE_ALARM,ERROR_CODE__JOB_LS_ALARM,ERROR_CODE__JOB_PRESSURE_ALARM,ERROR_CODE__JOB_CURRENT_ALARM,
                                                      ERROR_CODE__JOB_MOTOR_ALARM,ERROR_CODE__JOB_OTHER_ALARM};

JobTicket *CurrentJob = NULL;
JobRequest *CurrentRequest  = NULL;

double previousJobLength;
uint32_t    StubControlId = 0xFF;
double StubLengthCounter = 0,StubLength = 0,StubSpeed=0;
JobTicket Ticket;
JobSegment *TSegment;
JobSpool *Tspool;
bool CopyConfigured[MAX_SYSTEM_MODULES];
char ErrorMsg[100];


ModuleStateEnum PrepareWaiting[MAX_SYSTEM_MODULES] = {ModuleIdle,ModuleIdle,ModuleIdle,ModuleIdle,ModuleIdle};

/********************************************************************************************
* functions describes motor operation flow and movement state during profile execution
* used to operate in runtime correct profileflow execution
*********************************************************************************************/
//static ReturnCode IdleState(void *JobDetails);
//static ReturnCode ValidateState(void *JobDetails);
static ReturnCode PrepareState(void *JobDetails);
static ReturnCode PrintState(void *JobDetails);
//static ReturnCode CleanState(void *JobDetails);
static ReturnCode ExitState(void *JobDetails);
/**********************************************************************
* the array and enum of JobState_t below must be in sync order
***********************************************************************/
//static ReturnCode (* state[])(void *JobDetails) = { IdleState, ValidateState, PrepareState,  PrintState, CleanState};
void AbortJob(char *Msg);


typedef enum
{
    Idle= 0,
	Validate,
	PrepareJob,
	Print,
	Clean,
	ExitJob
} JobState_t;

typedef struct
{
    JobState_t	m_sourceState;
    ReturnCode   		m_returnCode;
    JobState_t 	m_destinationState;
} Transition_t;


////////////////////////Slow Motor State////////////////////////////////////
char JobToken[36+1]={0};
bool JobAbortedByUser = false;

bool JobActive = false;
bool JobResumed = false;
////////////////////////////////////////////////////////////////////////////
void StartJob(void *JobDetails);


//********************************************************************************************************************
bool JobIsActive(void)
{
    return JobActive;
}
/********************************************************************************************************************
*function describes entry point of motor in profile execution - accelerate from stop position
*function described above used to operate motor operation flow and movement state during profile execution
*********************************************************************************************************************/
/*static ReturnCode IdleState(void *JobDetails)
{
    ReturnCode retcode;
    retcode = JobSuccess;

    return retcode;
}*/
//********************************************************************************************************************
/*static ReturnCode ValidateState(void *JobDetails)
{
    ReturnCode retcode;
    retcode = JobSuccess;

    return retcode;
}*/
//********************************************************************************************************************
bool GetHeatersPrepareWaiting(void)
{
    if (PrepareWaiting[Module_Heaters] == ModuleWaiting)
        return true;
    else
        return false;

}
//********************************************************************************************************************
static ReturnCode PrepareState(void *JobDetails)
{
    ReturnCode retcode;
    retcode = JobSuccess;
    //start (fast??) heating
    DiagnosticsStart();

    if (Configured[Module_IDS])
    {
        PrepareWaiting[Module_IDS] = ModuleWaiting;
    }
    if (Configured[Module_Thread])
    {
        PrepareWaiting[Module_Thread] = ModuleWaiting;
    }
    if (Configured[Module_Winder])
    {
        PrepareWaiting[Module_Winder] = ModuleWaiting;
    }
    if (Configured[Module_Heaters])
    {
        if (HeaterCheckReady() == false) // if heaters are in heating / cooling state we must wait for them
            PrepareWaiting[Module_Heaters] = ModuleWaiting;
    }
    //wait for fast heating to end
    //start other peripheral systems: chiller, waist handling
    //check thread type
    if (Configured[Module_IDS])
    {
        IDSPrepareState(JobDetails);
    }
/*    if (Configured[Module_Heaters])
    {
        //heaters preparation starts on process parameters handling
    }*/
    if (Configured[Module_Thread])
    {
        ThreadPrepareState(CurrentJob);
    }
    if (Configured[Module_Winder])
    {
       if( Winder_Prepare()!= OK)
       {
           SendJobProgress(0.0, 0, false, "Winder prepare failed !!!!");
       }
    }

	return retcode;
}
//********************************************************************************************************************
uint32_t PrepareReady(int ModuleId, ModuleStateEnum result)
{
    int i;
    bool ready = true;
    uint32_t retcode = 0,status = OK;

    JobMessageStruc Message;

    assert (ModuleId<MAX_SYSTEM_MODULES);
    assert (result<=ModuleFail);

    if (JobActive == false)
        return ERROR;
    if (PrepareWaiting[ModuleId] != ModuleWaiting)
    {
        LOG_ERROR (ModuleId, "Message from unrelated module!!");
        return ERROR;
    }

    PrepareWaiting[ModuleId] = result;
    //if (result == ModuleFail) status = ERROR;
    for (i=0;i<MAX_SYSTEM_MODULES ;i++)
    {
        if (PrepareWaiting[i] == ModuleWaiting)
            ready = false;
        if (PrepareWaiting[i] == ModuleFail)
            status = ERROR;
    }
    if ((ready == false)&&(status == OK))
        return OK;
    else
    {
        for (i=0;i<MAX_SYSTEM_MODULES ;i++)
        {
            if (PrepareWaiting[ModuleId] == ModuleWaiting)
                PrepareWaiting[ModuleId] = ModuleDone;
        }
        SendJobProgress(0.0, 0, false, "Prepare Ready");
        if (status == OK)    Message.messageId = PreparationResultsOk;
        else Message.messageId = PreparationResultsFail;
        //memcpy(Message.messageData,JobDetails,MAX_MSG_LEN);
        Message.msglen = 10;
        if (JobmsgQ != NULL)
            retcode = Mailbox_post(JobmsgQ , &Message, BIOS_NO_WAIT);
    }
    return retcode;
}

//********************************************************************************************************************
static ReturnCode PrintState(void *JobDetails)
{
    ReturnCode retcode;
    retcode = JobSuccess;
    JobMessageStruc Message;
    PrintMessageStruc *PrtMessage = (PrintMessageStruc *)Message.messageData;

        Message.messageId = PrintMessage;
        PrtMessage->messageId = PrintRequest;
        Message.msglen = 10;
        if (JobmsgQ != NULL)
            Mailbox_post(JobmsgQ , &Message, BIOS_NO_WAIT);

    return retcode;
}

//********************************************************************************************************************
/*static ReturnCode CleanState(void *JobDetails)
{
    ReturnCode retcode;
    retcode = JobSuccess;

    return retcode;
}*/
//********************************************************************************************************************
static ReturnCode ExitState(void *JobDetails)
{
    ReturnCode retcode;
    retcode = JobStop;

    return retcode;
}

/*static void JobClockHandle(UArg arg0)
{
    //Clock_setTimeout(JobClock, 1000);
    //Clock_start(JobClock);

}*/

//********************************************************************************************************************

/*void JobInit(void)
{
    Clock_Params_init(&jobclkParams);
    jobclkParams.period = 0;
    jobclkParams.startFlag = FALSE;
    JobClock = Clock_create(JobClockHandle, 0, &jobclkParams, NULL);
    return ;
}*/
//********************************************************************************************************************
void JobAbortFunc(MessageContainer* requestContainer)
{
    MessageContainer responseContainer;
    uint8_t* container_buffer;


    AbortJobRequest* request = abort_job_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    //AbortJob();
    AbortJobResponse response = ABORT_JOB_RESPONSE__INIT;
    responseContainer = createContainer(MESSAGE_TYPE__AbortJobResponse, requestContainer->token, false, &response, &abort_job_response__pack, &abort_job_response__get_packed_size);
    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);
    SendChars((char*)container_buffer, container_size);
    abort_job_request__free_unpacked(request,NULL);
    JobAbortedByUser = true;
    AbortJob("Job Aborted by user");
    //We keep the job request until it is done


}
//********************************************************************************************************************
uint32_t ThreadJoggingFunc(int speed)
{
    ProcessParameters ProcessParametersCopy;
    uint32_t status = OK;
    if (JobIsActive() == true)
    {
        status = ERROR;
        LOG_ERROR(JobIsActive(),"Jog JobIsActive");
    }
    else
    {
        memcpy(&CopyConfigured,&Configured,sizeof(CopyConfigured));
        //set the job handler to ignore heaters, ids and waste in the state machine
        Configured[Module_Thread] = true;
        Configured[Module_Winder] = true;
        Configured[Module_IDS] = false;
        Configured[Module_Heaters] = false;
        Configured[Module_Waste] = false;
        //set the requested speed without changing other process parameters
        memcpy (&ProcessParametersCopy,&ProcessParametersKeep,sizeof(ProcessParameters));
        if(speed)
            ProcessParametersCopy.dyeingspeed = speed;
        else
            ProcessParametersCopy.dyeingspeed = 40;
        if (HandleProcessParameters(&ProcessParametersCopy)!= OK)
        {
            status = FAILED;
        }
        else
        {
        //load essential job prameters to enable thread running
            Ticket.n_segments = 1;
            Ticket.segments = my_malloc(sizeof(Ticket.segments));
            TSegment = my_malloc(sizeof(JobSegment));
            Tspool = my_malloc(sizeof(JobSpool));
            TSegment->length = 5000.0;
            TSegment->n_brushstops = 0;
            Ticket.segments[0] = TSegment;
            Tspool->backingrate = 30;
            Tspool->bottombackingrate = 18;
            Tspool->segmentoffsetpulses = 1000;
            Tspool->startoffsetpulses = 240;
            Tspool->rotationsperpassage = 6;
            Ticket.spool = Tspool;
            CurrentJob = &Ticket;
            InternalWindingConfigMessage(Tspool);
            StartJob(&Ticket);
        }
    }
    return status;
}
void ThreadJoggingRequestFunc(MessageContainer* requestContainer)
{
    uint32_t status = OK;

    MessageContainer responseContainer;
    ThreadJoggingRequest* request = thread_jogging_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    ThreadJoggingResponse response = THREAD_JOGGING_RESPONSE__INIT;

    status = ThreadJoggingFunc(request->speed);

    responseContainer = createContainer(MESSAGE_TYPE__ThreadJoggingResponse, requestContainer->token, true, &response, &thread_jogging_response__pack, &thread_jogging_response__get_packed_size);
    if (status!= OK)
    {
        responseContainer.error = ERROR_CODE__INVALID_PARAMETER;
        responseContainer.errormessage = "JOb Active or incorrect parameters";
    }
//    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);
    SendChars(container_buffer, container_size);
    my_free(responseContainer.data.data);

    return ;

}
void ThreadAbortJoggingFunc(void)
{
    AbortJob(0);
    //set the job handler to handle heaters, ids and waste in the state machine
    Task_sleep(100); //let the job end procedure role before returning the configuration to normal.
    memcpy(&Configured,&CopyConfigured,sizeof(CopyConfigured));
    my_free(Ticket.segments);
    my_free(TSegment);
    my_free(Tspool);

}
void ThreadAbortJoggingRequestFunc(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    MessageContainer responseContainer;

    ThreadAbortJoggingRequest* request = thread_abort_jogging_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    ThreadAbortJoggingResponse response = THREAD_ABORT_JOGGING_RESPONSE__INIT;

    ThreadAbortJoggingFunc();

    responseContainer = createContainer(MESSAGE_TYPE__ThreadAbortJoggingResponse,  requestContainer->token, false, &response, &thread_abort_jogging_response__pack, &thread_abort_jogging_response__get_packed_size);

    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);

    return ;

}

//********************************************************************************************************************
uint32_t SendStubJobProgress(uint32_t IfIndex, uint32_t readValue)
{
    MessageContainer responseContainer;
    uint8_t* container_buffer;
    bool done = false;
//


    //REPORT_MSG(msdid++,logmsg);
    Report("Stub Job",__FILE__,__LINE__,StubLengthCounter,RpWarning,StubLength,  StubSpeed);

    if (JobToken[0] == 0)
        return OK;


    StubJobResponse response = STUB_JOB_RESPONSE__INIT;
    JobStatus jobStatus = JOB_STATUS__INIT;

    jobStatus.has_progress = true;
    jobStatus.progress = StubLengthCounter/100;
    StubLengthCounter += StubSpeed;
    if (StubLengthCounter>=StubLength)
    {
        done = true;
        RemoveControlCallback(StubControlId, SendStubJobProgress);
    }

    jobStatus.has_currentsegmentindex = true;
    jobStatus.currentsegmentindex = 0;

    response.status = &jobStatus;
    responseContainer = createContainer(MESSAGE_TYPE__StubJobResponse, JobToken, done, &response, &stub_job_response__pack, &stub_job_response__get_packed_size);

    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);

    return OK;
}

void Stub_JobRequest(MessageContainer* requestContainer)
{
    uint32_t status = OK;

    MessageContainer responseContainer;

    StubJobRequest* request = stub_job_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);
    JobTicket *Ticket = request->jobticket;

    StubJobResponse response = STUB_JOB_RESPONSE__INIT;
    JobStatus jobStatus = JOB_STATUS__INIT;
    StubSpeed = Ticket->processparameters->dyeingspeed;
    StubLength  = Ticket->length*100;
    StubLengthCounter = 0;
    ustrncpy (JobToken, requestContainer->token,36);
    StubControlId =  AddControlCallback( SendStubJobProgress, eOneSecond,TemplateDataReadCBFunction,0,0,0);

    jobStatus.has_progress = true;
    jobStatus.progress = 0.0;
    jobStatus.has_currentsegmentindex = false;
    response.status = &jobStatus;
    responseContainer = createContainer(MESSAGE_TYPE__StubJobResponse, JobToken, false, &response, &stub_job_response__pack, &stub_job_response__get_packed_size);
    if (status!= OK)
    {
        responseContainer.error = ERROR_CODE__INVALID_PROCESS_ID;
        responseContainer.errormessage = "JOb Active or incorrect parameters";
    }
//    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);

    return ;

}
void Stub_AbortJobRequest(MessageContainer* requestContainer)
{
    //uint32_t status = OK;

    MessageContainer responseContainer;

    StubAbortJobRequest* request = stub_abort_job_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    StubAbortJobResponse response = STUB_ABORT_JOB_RESPONSE__INIT;


    //RemoveControlCallback(StubControlId, SendStubJobProgress);
    StubLength  = 0;
    StubLengthCounter = 10;  //trigger job end message;

    responseContainer = createContainer(MESSAGE_TYPE__StubAbortJobResponse,  requestContainer->token, false, &response, &stub_abort_job_response__pack, &stub_abort_job_response__get_packed_size);

    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);

    return ;

}

//********************************************************************************************************************
void JobRequestFunc(MessageContainer* requestContainer)
{
    uint32_t status = NOT_SUPPORTED;
    MessageContainer responseContainer;
    uint8_t* container_buffer;
    ErrorCode error = ERROR_CODE__NONE;
    JobEndReasonEnum JobAlarmReason = JOB_OK;

    JobRequest* request = job_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);
    if (request != NULL)
    {
        ustrncpy (JobToken, requestContainer->token,36);
        previousJobLength = 0.0;
        JobTicket *Ticket = request->jobticket;
        int TicketSize = job_ticket__get_packed_size(Ticket);
        if (TicketSize >= MAX_TICKET_SIZE)
        {
            LOG_ERROR (TicketSize, "job ticket message too long");
            status = FAILED;
            error = ERROR_CODE__BAD_CRC;
            usnprintf(ErrorMsg, 100, "job ticket message too long");
        }
        else
        {
            //memcpy(CurrentJob, Ticket,TicketSize);
            CurrentJob = Ticket;
            if (CurrentRequest!= NULL)
                job_request__free_unpacked(CurrentRequest,NULL);
            CurrentRequest = request;

            status  = PASSED;
            JobEndReason = JOB_OK;
            JobAlarmReason = AlarmHandlingPrepareJob(CurrentJob);
            if (JobAlarmReason ==OK)
            {
#warning Process parameters in job request are not handled. push separately for now
                /*if (Ticket->processparameters)
                {
                    if (HandleProcessParameters(Ticket->processparameters)!= OK)
                    {
                        status = FAILED;
                        error = ERROR_CODE__INVALID_PARAMETER;
                        usnprintf(ErrorMsg, 100, "Hardware Parameters Not Set");
                    }
                }*/
                REPORT_MSG(0,"Process parameters in job request are not handled. push separately for now");
                if (Ticket->spool)
                {
                    if (InternalWindingConfigMessage(Ticket->spool)!= OK)
                    {
                        status = FAILED;
                        error = ERROR_CODE__INVALID_PARAMETER;
                        usnprintf(ErrorMsg, 100, "spool parameters error");
                    }
                }

            }
            else
            {
                status = FAILED;
                error = JobError_to_ErrorCode[JobAlarmReason];
                usnprintf(ErrorMsg, 100, "Existing alarms prevent running");
            }
        }
        if (status == PASSED)
        {
            Report("Job Request ",__FILE__,__LINE__,Ticket->processparameters->dyeingspeed,RpWarning,Ticket->n_segments, Ticket->intersegmentlength);
            StartJob(CurrentJob);
        }
    }
    else
        status = FAILED;

    JobResponse response = JOB_RESPONSE__INIT;
    JobStatus jobStatus = JOB_STATUS__INIT;
    if (status == PASSED)
    {
        JobResumed = false;
        usnprintf(ErrorMsg, 100, "Job Accepted");

        jobStatus.message =ErrorMsg;
        jobStatus.has_progress = true;
        jobStatus.progress = 0.0;
        jobStatus.has_currentsegmentindex = false;
        response.status = &jobStatus;
        response.has_canceled = false;
        responseContainer = createContainer(MESSAGE_TYPE__JobResponse, JobToken, false, &response, &job_response__pack, &job_response__get_packed_size);
        container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    }
    else
    {
        jobStatus.message = ErrorMsg;
        jobStatus.has_progress = true;
        jobStatus.progress = 0.0;
        jobStatus.has_currentsegmentindex = false;
        response.status = &jobStatus;
        response.has_canceled = true;
        response.canceled = true;
        responseContainer = createContainer(MESSAGE_TYPE__JobResponse, JobToken, true, &response, &job_response__pack, &job_response__get_packed_size);
        responseContainer.has_error = true;
        responseContainer.error = error;
        container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
    }
    if (container_buffer)
    {
        size_t container_size = message_container__pack(&responseContainer, container_buffer);
        my_free(responseContainer.data.data);
        SendChars((char*)container_buffer, container_size);
        //We keep the job request until it is done
        //    job_request__free_unpacked(request,NULL);
    }
}
//********************************************************************************************************************
char logmsg[254];
char infomsg[254];
uint8_t JobStatusBuffer[400];

void SendJobProgress(double ProcessedLength, int SegmentId, bool done, char *Message)
{
    MessageContainer responseContainer;
    uint8_t* container_buffer;

    //int len;
    //static msdid = 0;
    //int length = (int)(ProcessedLength*100);
    //len = usnprintf(logmsg, 254, "MSG: Job Progress Length %d, Seg %d Done %d ",length,  SegmentId,  done);

    //REPORT_MSG(msdid++,logmsg);
    //Report(logmsg,__FILE__,__LINE__,SegmentId,RpWarning,SegmentId,  done);
    /*if (Message)
    {
        strcpy (infomsg,Message);
        Report(infomsg,__FILE__,__LINE__,55,RpWarning,33,  44);
    }*/

    if (JobToken[0] != 0)
    {
        ResumeCurrentJobResponse resumeresponse = RESUME_CURRENT_JOB_RESPONSE__INIT;
        JobResponse response = JOB_RESPONSE__INIT;
        JobStatus jobStatus = JOB_STATUS__INIT;

        if (Message)
        {
            jobStatus.message = Message;
        }
        //previousJobLength =  ProcessedLength;
        jobStatus.has_progress = true;
        jobStatus.progress = TotalProcessedLength;
        jobStatus.has_currentsegmentindex = true;
        jobStatus.currentsegmentindex = SegmentId;

        if (JobResumed == true)
        {
            resumeresponse.status = &jobStatus;
            //responseContainer = createContainer(MESSAGE_TYPE__ResumeCurrentJobResponse,  JobToken, done, &resumeresponse, &resume_current_job_response__pack, &resume_current_job_response__get_packed_size);
            responseContainer = createAllocatedContainer(MESSAGE_TYPE__ResumeCurrentJobResponse,  JobToken, done, &resumeresponse, &resume_current_job_response__pack, &resume_current_job_response__get_packed_size,&JobStatusBuffer);
        }
        else
        {
            response.status = &jobStatus;
            //responseContainer = createContainer(MESSAGE_TYPE__JobResponse, JobToken, done, &response, &job_response__pack, &job_response__get_packed_size);
            responseContainer = createAllocatedContainer(MESSAGE_TYPE__JobResponse, JobToken, done, &response, &job_response__pack, &job_response__get_packed_size,&JobStatusBuffer);
        }

        container_buffer = my_malloc(message_container__get_packed_size(&responseContainer));
        if (done == true)
        {
            if(JobEndReason != JOB_OK)
            {
                responseContainer.has_error = true;
                responseContainer.error = JobError_to_ErrorCode[JobEndReason];
            }
            if (JobAbortedByUser == true)
            {
                JobAbortedByUser = false;
                responseContainer.has_error = true;
                responseContainer.error = ERROR_CODE__CONTINUOUS_RESPONSE_ABORTED;
            }
        }
        if (container_buffer)
        {
            size_t container_size = message_container__pack(&responseContainer, container_buffer);
            //        if (SendChars(container_buffer, container_size) == false) //comm tx mailbox full
            if (SendCharsWithType(container_buffer, container_size,MESSAGE_TYPE__JobResponse) == false) //comm tx mailbox full
            {
                //AlarmHandlingToken[0] = 0;
                my_free(container_buffer);
            }
        }
    }

    if (done == true)
    {
        if (CurrentRequest!= NULL)
            job_request__free_unpacked(CurrentRequest,NULL);
        JobStopReporting();
        JobMessageStruc JobMessage;

        JobMessage.messageId = PrintingResultsOk;
        JobMessage.msglen = MAX_MSG_LEN;
        if (JobmsgQ != NULL)
            Mailbox_post(JobmsgQ , &JobMessage, BIOS_NO_WAIT);
    }
//    if (responseContainer.data.data)
//        my_free(responseContainer.data.data);
}
void JobStopReporting(void)
{
    JobToken[0] = 0;
}

void AbortJob(char *Msg)
{
    //ReturnCode retcode;
    //retcode = JobSuccess;
    JobMessageStruc Message;
    PrintMessageStruc *PrtMessage = (PrintMessageStruc *)Message.messageData;

        Message.messageId = Abort;
        PrtMessage->messageId = PrintSystemFailure;
        strcpy(PrtMessage->messageData,Msg);
        Message.msglen = 10;
        if (JobmsgQ != NULL)
            Mailbox_post(JobmsgQ , &Message, BIOS_NO_WAIT);
}
uint32_t    CurrentJobRequestFunc(MessageContainer* requestContainer)
{
    uint32_t status = OK;

    MessageContainer responseContainer;

    CurrentJobRequest* request = current_job_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    CurrentJobResponse response = CURRENT_JOB_RESPONSE__INIT;


    if (JobActive == true)
    {
        response.has_isjobinprogress = true;
        response.isjobinprogress = true;
        response.jobticket = CurrentJob;
    }
    else
    {
        response.has_isjobinprogress = true;
        response.isjobinprogress = false;
        response.jobticket = NULL;
    }
    responseContainer = createContainer(MESSAGE_TYPE__CurrentJobResponse,  requestContainer->token, false, &response, &current_job_response__pack, &current_job_response__get_packed_size);
    if (status!= OK)
    {
        responseContainer.error = ERROR_CODE__INVALID_PROCESS_ID;
        responseContainer.errormessage = "JOb Active or incorrect parameters";
    }
    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);

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

    MessageContainer responseContainer;

    ResumeCurrentJobRequest* request = resume_current_job_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    ResumeCurrentJobResponse response = RESUME_CURRENT_JOB_RESPONSE__INIT;
    JobStatus jobStatus = JOB_STATUS__INIT;

    ustrncpy (JobToken, requestContainer->token,36);
    JobResumed = true;
    usnprintf(ErrorMsg, 100, "Job Resumeded");

    jobStatus.message =ErrorMsg;
    jobStatus.has_progress = true;
    jobStatus.progress = 0.0;
    jobStatus.has_currentsegmentindex = false;
    response.status = &jobStatus;
    response.has_canceled = false;

    responseContainer = createContainer(MESSAGE_TYPE__ResumeCurrentJobResponse,  JobToken, false, &response, &resume_current_job_response__pack, &resume_current_job_response__get_packed_size);
    if (status!= OK)
    {
        responseContainer.error = ERROR_CODE__INVALID_PROCESS_ID;
        responseContainer.errormessage = "JOb Active or incorrect parameters";
    }
    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);

    return OK;
}


void StartJob(void *JobDetails)
{
    JobMessageStruc Message;

    Message.messageId = JobRequestMsg;
    Message.msglen = MAX_MSG_LEN;
    if (JobmsgQ != NULL)
       Mailbox_post(JobmsgQ , &Message, BIOS_NO_WAIT);
}

/******************************************************************************
 *  ======== messageTsk ========
 *  Task for this function is created statically. See the project's .cfg file.
 *  this message task is created statically in system initialization,
 ******************************************************************************/
Void jobTask(UArg arg0, UArg arg1)
{
    JobMessageStruc Message;
    //char str[60];
    //uint16_t length;
    //Clock_setTimeout(HostKAClock, 1000);
    //Clock_start(HostKAClock);
    JobmsgQ = Mailbox_create(MAX_MSG_LEN, 20, NULL,NULL);


    while(1)
    {
        Mailbox_pend(JobmsgQ , &Message, BIOS_WAIT_FOREVER);
        switch (Message.messageId)
        {
            case JobRequestMsg:
                JobEndReason = JOB_OK;
                JobActive = true;
                /*ValidateState (CurrentJob);
                break;
            case ValidationResultsOk:*/
                PrepareState (CurrentJob);
                break;
            case ValidationResultsFail:
                //send message data as a validation error message to host
                ExitState(Message.messageData);
                break;
            case PreparationResultsOk:
                PrintState(CurrentJob);
                break;
            case PreparationResultsFail:
                //send message data as a validation error message to host
                EndState(CurrentJob, "Prepare Failed");
                //ExitState(Message.messageData);
                break;
            case PrintMessage:
                //send message data as a validation error message to host
                PrintSTMMsgHandler(&Message);
                break;
            case PrintingResultsOk:
                JobActive = false;
                CurrentJob = NULL;
                  //if (CurrentRequest!= NULL)
                  //    job_request__free_unpacked(CurrentRequest,NULL);
                  CurrentRequest = NULL;
                  SuspendLargeMessages = false;
                  LOG_ERROR(4,"ResumeLargeMessages PrintingResultsOk");
                  //DiagnosticsStart();
                //CleanState(CurrentJob);
                break;
            case PrintingResultsFail:
                JobActive = false;
                CurrentJob = NULL;
                  //if (CurrentRequest!= NULL)
                  //    job_request__free_unpacked(CurrentRequest,NULL);
                  CurrentRequest = NULL;
                  SuspendLargeMessages = false;
                  LOG_ERROR(3,"ResumeLargeMessages PrintingResultsFail");
                  //DiagnosticsStart();

                //send message data as a validation error message to host
                ExitState(Message.messageData);
                break;
            case CleaningResultsOk:
                //send message data as a validation error message to host
                ExitState(Message.messageData);
                break;
            case CleaningResultsFail:
                //send message data as a validation error message to host
                ExitState(Message.messageData);
                break;
            case SystemFailure:
                //send message data as a validation error message to host
                ExitState(Message.messageData);
                break;
            case Abort:
                PrintSTMMsgHandler(&Message);
                break;
            default:
                break;
        }
    }
}