aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Embedded_SW/Embedded/StateMachines/Initialization/PowerOffSequence.c
blob: b5ebdee1794c32f5339509cc736216ccc403702e (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
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 */
/* Generated by the protocol buffer compiler.  DO NOT EDIT! */
/* Generated from: ExternalClientLoginResponse.proto */

#ifndef PROTOBUF_C_ExternalClientLoginResponse_2eproto__INCLUDED
#define PROTOBUF_C_ExternalClientLoginResponse_2eproto__INCLUDED

#include <protobuf-c/protobuf-c.h>

PROTOBUF_C__BEGIN_DECLS

#if PROTOBUF_C_VERSION_NUMBER < 1003000
# error This file was generated by a newer version of protoc-c which is incompatible with your libprotobuf-c headers. Please update your headers.
#elif 1003000 < PROTOBUF_C_MIN_COMPILER_VERSION
# error This file was generated by an older version of protoc-c which is incompatible with your libprotobuf-c headers. Please regenerate this file with a newer version of protoc-c.
#endif


typedef struct _ExternalClientLoginResponse ExternalClientLoginResponse;


/* --- enums --- */


/* --- messages --- */

struct  _ExternalClientLoginResponse
{
  ProtobufCMessage base;
  protobuf_c_boolean has_authenticated;
  protobuf_c_boolean authenticated;
  char *serialnumber;
};
#define EXTERNAL_CLIENT_LOGIN_RESPONSE__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&external_client_login_response__descriptor) \
    , 0, 0, NULL }


/* ExternalClientLoginResponse methods */
void   external_client_login_response__init
                     (ExternalClientLoginResponse         *message);
size_t external_client_login_response__get_packed_size
                     (const ExternalClientLoginResponse   *message);
size_t external_client_login_response__pack
                     (const ExternalClientLoginResponse   *message,
                      uint8_t             *out);
size_t external_client_login_response__pack_to_buffer
                     (const ExternalClientLoginResponse   *message,
                      ProtobufCBuffer     *buffer);
ExternalClientLoginResponse *
       external_client_login_response__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   external_client_login_response__free_unpacked
                     (ExternalClientLoginResponse *message,
                      ProtobufCAllocator *allocator);
/* --- per-message closures --- */

typedef void (*ExternalClientLoginResponse_Closure)
                 (const ExternalClientLoginResponse *message,
                  void *closure_data);

/* --- services --- */


/* --- descriptors --- */

extern const ProtobufCMessageDescriptor external_client_login_response__descriptor;

PROTOBUF_C__END_DECLS


#endif  /* PROTOBUF_C_ExternalClientLoginResponse_2eproto__INCLUDED */
a id='n455' href='#n455'>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
/*
 * PowerOffSequence.c
 *
 *  Created on: Apr 2, 2019
 *      Author: shlomo
 */

#include "PMR/Power/StartPowerDownRequest.pb-c.h"
#include "PMR/Power/AbortPowerDownRequest.pb-c.h"
#include "PMR/Power/StartPowerDownResponse.pb-c.h"
#include "PMR/Power/AbortPowerDownResponse.pb-c.h"
#include "PMR/Power/PowerDownState.pb-c.h"
#include "PMR/MachineStatus/MachineStatus.pb-c.h"

#include "modules/General/GeneralHardware.h"
#include "modules/General/Safety.h"
#include "modules/thread/thread.h"
#include "modules/ids/ids.h"
#include "modules/control/control.h"
#include "modules/AlarmHandling/AlarmHandling.h"
#include "modules/heaters/heaters_ex.h"
#include "modules/Diagnostics/Diagnostics.h"
#include "Modules/General/process.h"
#include "Modules/General/MachineStatus.h"
#include "Modules/Thread/Thread_ex.h"
#include "Modules/Control/MillisecTask.h"
#include "Modules/heaters/heaters_ex.h"

#include "Common/SWUpdate/FirmwareUpgrade.h"


#include "drivers/I2C_Communication/DAC/Blower.h"
#include "drivers/I2C_Communication/ADC_MUX/ADC_MUX.h"
#include "drivers/Heater/TemperatureSensor.h"
#include "drivers/Valves/Valve.h"
#include <Drivers/I2C_Communication/I2C.h>
#include <Drivers/I2C_Communication/WHS_Card/D_Max5805_ADC_Blower/WHS_Blower.h>

#include "StateMachines/Printing/PrintingSTM.h"
#include "PowerIdle.h"
#include "InitSequence.h"
#include "PowerOffSequence.h"
#include "modules/waste/waste_ex.h"
#include "modules/ifs/ifs.h"
/*
    typedef enum
    {
        POWER_OFF_INIT,
        POWER_OFF_STOP_RUNNING_JOB,
        POWER_OFF_HEAD_CLEAN,
        POWER_OFF_MIXER_FLUSH,
        POWER_OFF_HEATERS_OFF,
        POWER_OFF_STORE_DATA,
        POWER_OFF_SET_VALVE_POSITION,
        POWER_OFF_WAIT_FOR_TEMPERATURE,
        POWER_OFF_WAIT_FOR_PROCESSES,//wait for waste emptying, ink filling, thread loading
        POWER_OFF_TURN_OFF_DRYER_FAN,
        POWER_OFF_TURN_OFF_COOLER,
        POWER_OFF_TURN_OFF_BLOWER,
        POWER_OFF_POWER_OFF,
        POWER_OFF_MAX,
    }POWER_OFF_STAGES_ENUM;
*/

POWER_OFF_STAGES_ENUM PowerOffMachineState = POWER_OFF_INIT,StoredMachineState = POWER_OFF_INIT;
uint32_t PowerOffControlId = 0xFF;
uint32_t WaitForProcessControlId = 0xFF;
uint32_t PowerOffSequenceStateMachine( POWER_OFF_STAGES_ENUM ReadValue);
uint32_t PowerDownUpdate(POWER_OFF_STAGES_ENUM stage);
bool PowerOffInProcess = false;
#define POWER_OFF_TEMP_THRESHOLD 5000  //50 celsious
int32_t PowerOffTemperatureThreshold = POWER_OFF_TEMP_THRESHOLD;

bool PowerOffDisableCleaning = false;
void setPowerOffDisableCleaning (bool value)
{
    PowerOffDisableCleaning = value;
    REPORT_MSG(PowerOffDisableCleaning, "Set PowerOffDisableCleaning");
}
bool PowerOffInProcessGetState(void)
{
    return PowerOffInProcess;
}
void PowerOffSetTemperatureThreshold (int32_t temperature)
{
    if (temperature)
    {
        PowerOffTemperatureThreshold =  temperature*100;
        Report("PowerOff Set Temperature",__FILE__,__LINE__,(int)PowerOffTemperatureThreshold,RpWarning,(int)3600,0);
    }
}
#define UPDATE_TIMEOUT 2
uint8_t UpdateCounter = 0;
/*******************************************************************************************************/
uint32_t PowerOffScheduler(uint32_t IfIndex, uint32_t BusyFlag)
{
    if (PowerOffMachineState > StoredMachineState)
    {
        StoredMachineState = PowerOffMachineState;
        PowerOffSequenceStateMachine (PowerOffMachineState);
    }
    PowerDownUpdate(PowerOffMachineState);
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffInit(void)
{
    if (PowerOffInProcess==true)
    {
        LOG_ERROR(0,"Power Off already active");
        return OK;
    }
    LOG_ERROR(0,"Power Off Init");
    PowerOffMachineState++;
    StopInitSequence();
    setmachineActive(true);
    PowerIdleOutOfIdleState();
    PowerOffInProcess = true;
    PowerOffControlId = AddControlCallback("PowerOff", PowerOffScheduler, eOneSecond, TemplateDataReadCBFunction,0,0, 0 );
    SetMachineStatus(MACHINE_STATE__PowerOff);
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffCancel(void)
{
    if (PowerOffMachineState >= POWER_OFF_HEAD_CLEAN)
        PowerOffMachineState = POWER_OFF_CANCELLED;
    PowerOffInProcess = false;
    return OK;
}
/************************************************************************shlomo

 */
uint32_t PowerOffHeadCleanControlId = 0xff;
uint32_t PowerOffHeadCleanCallback(uint32_t DispenserId, uint32_t ReadValue)
{
    if ( JobIsActive()== false)
       {
           //abort this control loop
           SafeRemoveControlCallback(PowerOffHeadCleanControlId, PowerOffHeadCleanCallback );
           PowerOffHeadCleanControlId = 0xFF;
           PowerOffMachineState++;
           SetMachineStatus(MACHINE_STATE__PowerOff);
       }
    return OK;
}

/*******************************************************************************************************/
uint32_t PowerOffHeadClean(void)
{
    //TBD
    if (AutoHoming_Config >= AutoHoming_PowerOff )
        AutoHoming_Config = AutoHoming_JobEnd_PowerOn_off;
    if (PowerOffDisableCleaning == true)
    {
        LOG_ERROR(0,"Clean job skipped!!!!!!!");
        PowerOffMachineState++;
        SetMachineStatus(MACHINE_STATE__PowerOff);
        return OK;
    }
    if (ThreadCleaningJob(50) == OK)
    {
        if (PowerOffHeadCleanControlId != 0xFF)
        {
            RemoveControlCallback(PowerOffHeadCleanControlId, PowerOffHeadCleanCallback );
            PowerOffHeadCleanControlId = 0xFF;
            //return ERROR;
        }
        PowerOffHeadCleanControlId = AddControlCallback(NULL, PowerOffHeadCleanCallback,eOneSecond , TemplateDataReadCBFunction,0,0, 0 );
    }
    else
    {
        LOG_ERROR(0,"Clean job failed");
        PowerOffMachineState++;
        SetMachineStatus(MACHINE_STATE__PowerOff);
    }
//    if ( PowerOffHeadCleanControlId == 0xFF)
//        return ERROR;

    return OK;
}
/*******************************************************************************************************/
bool DispenserHomingActive[MAX_SYSTEM_DISPENSERS] = {false,false,false,false,false,false,false,false};
uint32_t PowerOffDispenserHomingCallback(uint32_t DispenserId, uint32_t ReadValue)
{
    DispenserHomingActive[DispenserId] = false;
    REPORT_MSG (DispenserId, "PowerOffDispenserHomingCallback");

    return OK;
}
#define TI_DISPENSER_ID 4
#define DEFAULT_MIXER_CLEANING_SPEED 1000
#define DEFAULT_MIXER_CLEANING_TIMEOUT 10000

uint32_t PowerOffMixerFlushCallback(void)
{
    //TBD
    int i;
    REPORT_MSG (PowerOffMachineState, "PowerOffMixerFlushCallback");
    SafeRemoveControlCallback(PowerOffHeadCleanControlId, PowerOffMixerFlushCallback );

    Control3WayValvesWithCallback ((Valves_t)TI_DISPENSER_ID, MidTank_Dispenser, NULL); //direction: MidTank_Dispenser or Dispenser_Mixer
    TimerMotors_t  HW_Motor_Id = DispenserIdToMotorId[TI_DISPENSER_ID];
    MotorStop(HW_Motor_Id,Hard_Hiz);
    CurrentDispenserSpeed[TI_DISPENSER_ID] = 0;


    Task_sleep (20);
    if (AutoHoming_Config >= AutoHoming_PowerOff )
    {
        for (i=0;i<MAX_SYSTEM_DISPENSERS;i++)
        {
            if(IDS_HomeDispenser(i,1000,PowerOffDispenserHomingCallback) == OK)
            {
                DispenserHomingActive[i] = true;
                REPORT_MSG (i, "PowerOffDispenserHomingCallback");
            }
        }
    }
    PowerOffMachineState++;
    return OK;
}
uint32_t PowerOffMixerFlushDispenserStopCallback(void)
{
    REPORT_MSG (PowerOffMachineState, "PowerOffMixerFlushDispenserStopCallback");
    IDS_Dispenser_Start_Motor_and_Open_Valve(TI_DISPENSER_ID,DEFAULT_MIXER_CLEANING_SPEED,NULL);
    PowerOffHeadCleanControlId = AddControlCallback("Poweroff cleaning", PowerOffMixerFlushCallback,DEFAULT_MIXER_CLEANING_TIMEOUT , TemplateDataReadCBFunction,0,0, 0 );
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffMixerFlush(void)
{
    int i;
    REPORT_MSG (PowerOffMachineState, "PowerOffMixerFlush");
    Valve_Set(VALVE_MIXCHIP_WASTECH, Mixer_Waste); //if intersegment is defined throw the ink away
    for (i=0;i<MAX_SYSTEM_DISPENSERS;i++)
    {
        if (i!=TI_DISPENSER_ID)
            IDS_StopHomeDispenser(i);
        else
        {
            IDS_Dispenser_Close_Valve_And_Stop_Motor(i, PowerOffMixerFlushDispenserStopCallback);
            IDS_StopHomeDispenser(i);
        }
    }

    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffHeatersOff(void)
{
    ProcessParameters ProcessParametersClear;
    ProcessParametersClear.dryerzone1temp = 0;
    ProcessParametersClear.dryerzone2temp = 0;
    ProcessParametersClear.dryerzone3temp = 0;
    ProcessParametersClear.mixertemp      = 0;
    ProcessParametersClear.headzone1temp  = 0;
    ProcessParametersClear.headzone2temp  = 0;
    ProcessParametersClear.headzone3temp  = 0;
    ProcessParametersClear.headzone4temp  = 0;
    ProcessParametersClear.headzone5temp  = 0;
    ProcessParametersClear.headzone6temp  = 0;
    ProcessParametersClear.headzone7temp  = 0;
    ProcessParametersClear.headzone8temp  = 0;
    ProcessParametersClear.headzone9temp  = 0;
    ProcessParametersClear.headzone10temp  = 0;
    ProcessParametersClear.headzone11temp  = 0;
    ProcessParametersClear.headzone12temp  = 0;
    ProcessParametersClear.rblowertemp  = 0;
    ProcessParametersClear.lblowertemp  = 0;
    ProcessParametersClear.rblowerflow  = 0;
    ProcessParametersClear.rblowerflow  = 0;
    ProcessParametersClear.dyeingspeed = 40;
    ProcessParametersClear.headairflow = 8.0;
    if (HandleProcessParameters(&ProcessParametersClear,false)!= OK)
    {
        LOG_ERROR (PowerOffMachineState, "Turn Off Heaters  failed");
    }
    HeadBlowersOff(1);
    PowerOffMachineState++;

    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffStoreData(void)
{
    //TBD
    REPORT_MSG (PowerOffMachineState, "Store Data");
    IDS_Dispenser_Store_Data();
    PowerOffMachineState++;
    return OK;
}
/*******************************************************************************************************/
int WaitForProcessCounter = 0;
uint32_t PowerOffWaitForProcessesCallback(uint32_t IfIndex, uint32_t BusyFlag)
{
    int i;
    bool HomingActive = false;
    for (i=0;i<MAX_SYSTEM_DISPENSERS;i++)
    {
        if (DispenserHomingActive[i] ==true)
        {
            HomingActive = true;
        }
    }
    if ((WHS_IsEmptying()||
        IFS_MidTankFilling()||
        ThreadLoadingActive()||
        SwUpgradeActive()||
        (HomingActive == true))&&
        (WaitForProcessCounter++<900))
    {
        REPORT_MSG (PowerOffMachineState, "Ongoing processes calback, wait for end of process");
        resetIdleCounter();
    }
    else
    {
        PowerOffMachineState++;
        SafeRemoveControlCallback(WaitForProcessControlId, PowerOffWaitForProcessesCallback);
        WaitForProcessControlId = 0xFF;
    }
 return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffWaitForProcesses(void)
{
    int i;
    REPORT_MSG (PowerOffMachineState, "Stop dispensers homing");
    bool HomingActive = false;
    for (i=0;i<MAX_SYSTEM_DISPENSERS;i++)
    {
        if (DispenserHomingActive[i] ==true)
        {
            HomingActive = true;
            IDS_StopHomeDispenser(i);
            REPORT_MSG (i, "IDS_StopHomeDispenser");
            IDS_HomeDispenserWaitForHomingEnd(i,  2*eOneMinute /*2 minutes*/ , PowerOffDispenserHomingCallback);
        }
    }

    if (WHS_IsEmptying()||
        IFS_MidTankFilling()||
        ThreadLoadingActive()||
        SwUpgradeActive()||
        (HomingActive == true))
    {
        WaitForProcessCounter = 0; //15 minutes wait
        REPORT_MSG (PowerOffMachineState, "Ongoing processes, wait for end of process");
        WaitForProcessControlId = AddControlCallback("ongoing processes", PowerOffWaitForProcessesCallback, eOneSecond, TemplateDataReadCBFunction,0,0, 0 );
    }
    else
    {
        PowerOffMachineState++;
    }
    //TBD
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffStopRunningJob(void)
{
    if (JobIsActive())
    {
        REPORT_MSG (PowerOffMachineState, "Stop running job");
        JobEndReason = JOB_ABORTED_BY_USER;
        usnprintf(AlarmReasonStr, 100, "Power off pressed");
        AbortJob("Power off pressed");
    }
    PowerOffMachineState++;
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffSetValvePosition(void)
{
    //TBD
    PowerOffMachineState++;
    return OK;
}
double StoreMax = 500;
uint32_t MaxTemp = 0;
/*******************************************************************************************************/
uint32_t PowerOffWaitForTemperatureCallback(uint32_t IfIndex, uint32_t BusyFlag)
{
    uint32_t readTemp;
    MaxTemp = 0;
    /*if (Head_Type == HEAD_TYPE_SYLKO_WITHOUT_CARD)
    {
        readTemp = MillisecGetTemperatures( MIXER_PT100);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(TEMP_SENSE_ANALOG_DYEINGH_TEMP1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(TEMP_SENSE_ANALOG_DYEINGH_TEMP2);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(TEMP_SENSE_ANALOG_DYEINGH_TEMP3);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(TEMP_SENSE_ANALOG_DYEINGH_TEMP4);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(TEMP_SENSE_ANALOG_DYEINGH_TEMP5);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD6_PT100);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
    }
    if (Head_Type == HEAD_TYPE_SYLKO)
    {
        readTemp = MillisecGetTemperatures( HEAD_PT100_MIXER_0X8E_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_1_0X80_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_2_0X80_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_3_0X82_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_4_0X82_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_5_0X84_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_6_0X84_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_7_0X86_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_8_0X86_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_9_0X88_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_10_0X88_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_11_0X8A_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_12_0X8A_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
    }
    if (Head_Type == HEAD_TYPE_ARC)
    {
        readTemp = MillisecGetTemperatures( HEAD_PT100_MIXER_0X8E_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_1_0X80_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_2_0X80_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_ZONE_3_0X82_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_AIR_HEATER_2_0X8C_1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
        readTemp = MillisecGetTemperatures(HEAD_PT100_AIR_HEATER_1_0X8C_0);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;
    }*/
    readTemp = MillisecGetTemperatures(TEMP_SENSE_ANALOG_DRYER_TEMP1);
        if ((readTemp>= MaxTemp)&&(readTemp < 27000))        MaxTemp = readTemp;

    if (StoreMax == 500)
        StoreMax = MaxTemp;
    if ((MaxTemp>PowerOffTemperatureThreshold)&&(WaitForProcessCounter++<3600))
    {
        Report("On going cooling down, wait for end of cooling",__FILE__,__LINE__,(int)MaxTemp,RpWarning,(int)WaitForProcessCounter,0);
        resetIdleCounter();
        //if (WaitForProcessCounter%UPDATE_TIMEOUT == 2)
        //    PowerDownUpdate(POWER_OFF_WAIT_FOR_TEMPERATURE);
    }
    else
    {
        Report("ended cooling down, wait for end of cooling",__FILE__,__LINE__,(int)MaxTemp,RpWarning,(int)WaitForProcessCounter,0);
        PowerOffMachineState = POWER_OFF_TURN_OFF_DRYER_FAN;
        SafeRemoveControlCallback(WaitForProcessControlId, PowerOffWaitForTemperatureCallback);
        WaitForProcessControlId = 0xFF;
    }
 return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffWaitForTemperature(void)
{
    Report("PowerOff Wait For Temperature",__FILE__,__LINE__,(int)PowerOffTemperatureThreshold,RpWarning,(int)3600,0);
    StoreMax = 500;
    WHS_Set_IFS_Clearing_Suction(NUM_OF_MIDTANKS);
    if (WaitForProcessControlId == 0xFF)
    {
        WaitForProcessCounter = 0;
        WaitForProcessControlId = AddControlCallback("poweroff cooling", PowerOffWaitForTemperatureCallback, eOneSecond, TemplateDataReadCBFunction,0,0, 0 );
    }
    //TBD
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffTurnOffDryerFan(void)
{
    int i;
    Control_Dryer_Fan(STOP,75);//use START or STOP,  0 - 100%
    PowerOffMachineState++;
    if (Special_Dispensers == false)
    {
        for (i=0;i<MAX_SYSTEM_DISPENSERS;i++)
            Control3WayValvesWithCallback ((Valves_t)i, Dispenser_Mixer, NULL); //direction: MidTank_Dispenser or Dispenser_Mixer
    }

    //TBD
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffTurnOffCooler(void)
{
    uint32_t DeActivateChiller();
    PowerOffMachineState++;
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffTurnOffBlower(void)
{
    WHS_Set_SetPoint_Q_value(0);
    Control_Voltage_To_Blower(500);
    Turn_the_Blower_Off();//Turn off
    PowerOffMachineState++;
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffPowerOff(void)
{
    int i;
    Task_setPri (I2C_Task_Handle,-1);

    for (i = 0;i<10;i++)
    {
        REPORT_MSG (10-i, "Power off in x seconds");
        Task_sleep (1000);
    }
    CloseLogFile();

    ControlStop();
    MillisecStop();
    HeatersEnd();
    ROM_IntMasterDisable();
    Power_Off();
    return OK;
}
/*******************************************************************************************************/
uint32_t PowerOffSequenceStateMachine( POWER_OFF_STAGES_ENUM ReadValue)
{
    uint32_t status = OK;

    REPORT_MSG(ReadValue,"PowerOffSequenceStateMachine");
    PowerDownUpdate(ReadValue);
    switch (ReadValue)
    {
    case POWER_OFF_INIT:
        break;
    case POWER_OFF_HEAD_CLEAN:
        status = PowerOffHeadClean();
        break;
    case POWER_OFF_MIXER_FLUSH:
        status = PowerOffMixerFlush();
        break;
    case POWER_OFF_HEATERS_OFF:
        status = PowerOffHeatersOff();
        break;
    case POWER_OFF_STORE_DATA:
        status = PowerOffStoreData();
        break;
    case POWER_OFF_WAIT_FOR_PROCESSES: //wait for waste emptying: ink filling: thread loading
        status = PowerOffWaitForProcesses();
        break;
    case POWER_OFF_STOP_RUNNING_JOB:
        status = PowerOffStopRunningJob();
        break;
    case POWER_OFF_SET_VALVE_POSITION:
        status = PowerOffSetValvePosition();
        break;
    case POWER_OFF_WAIT_FOR_TEMPERATURE:
        status = PowerOffWaitForTemperature();
        break;
    case POWER_OFF_TURN_OFF_DRYER_FAN:
        status = PowerOffTurnOffDryerFan();
        break;
    case POWER_OFF_TURN_OFF_COOLER:
        status = PowerOffTurnOffCooler();
        break;
    case POWER_OFF_TURN_OFF_BLOWER:
        status = PowerOffTurnOffBlower();
        break;
    case POWER_OFF_POWER_OFF:
        status = PowerOffPowerOff();
        break;
    case POWER_OFF_ERROR:
    case POWER_OFF_CANCELLED:
        RemoveControlCallback( PowerOffControlId,PowerOffScheduler);
        PowerOffControlId = 0xFF;
        RemoveControlCallback(WaitForProcessControlId, PowerOffWaitForProcessesCallback);
        RemoveControlCallback(WaitForProcessControlId, PowerOffWaitForTemperatureCallback);
        WaitForProcessControlId = 0xFF;
        LOG_ERROR(ReadValue,"POWER OFF Cancelled");
        break;
    default:
        LOG_ERROR(ReadValue,"ERROR IN POWER OFF STATE MACHINE");
        break;
    }
return status;
}

char PowerDownToken[36+1] = {0};
uint32_t PowerDownUpdate(POWER_OFF_STAGES_ENUM stage)
{
    uint32_t status = NOT_SUPPORTED;

    double calculate;
    int result;
    MessageContainer responseContainer;

    StartPowerDownResponse response = START_POWER_DOWN_RESPONSE__INIT;
    bool last = false;

    if (PowerDownToken[0] == 0)
        return OK;
    response.has_state = true;
    response.has_progresspercentage = true;
    switch (stage)
    {
    case POWER_OFF_INIT:
        response.state = stage +1;
        response.progresspercentage = 0.0;
        response.message = "Initializing";
        break;
    case POWER_OFF_STOP_RUNNING_JOB:
        response.state = stage +1;
        response.progresspercentage = 2.0;
        response.message = "Stop running job";
        break;
    case POWER_OFF_HEAD_CLEAN:
        response.state = stage +1;
        response.message = "Head Cleaning running";
        response.progresspercentage = 10.0;
        if ((HeaterCheckReady()==false)&&(PoolerTotalProcessedLength < 1.0))
        {
            response.message = "Head Cleaning heating up";
            response.progresspercentage = 5.0;
        }
        calculate = (double)((PoolerTotalProcessedLength/job_length)*10);
        result = (int)calculate;
        response.progresspercentage += result;
        Report("Job calculation",__FILE__,(int)response.progresspercentage,(int)PoolerTotalProcessedLength,RpWarning,(int)job_length,0);
        if (response.progresspercentage > 20.0)
            response.progresspercentage = 20.0;
        break;
    case POWER_OFF_MIXER_FLUSH:
        response.state = stage +1;
        response.progresspercentage = 20.0;
        response.message = "Flush mixer";
        break;
    case POWER_OFF_HEATERS_OFF:
        response.state = stage +1;
        response.progresspercentage = 22.0;
        response.message = "Heaters off";
        break;
    case POWER_OFF_STORE_DATA:
        response.state = stage +1;
        response.progresspercentage = 23.0;
        response.message = "Store data";
        break;
    case POWER_OFF_WAIT_FOR_PROCESSES: //wait for waste emptying: ink filling: thread loading
        response.state = stage +1;
        response.progresspercentage = 30.0;
        response.message = "Wait for processes";
        break;
    case POWER_OFF_SET_VALVE_POSITION:
        response.state = stage +1;
        response.progresspercentage = 32.0;
        response.message = "Valves";
        break;
    case POWER_OFF_WAIT_FOR_TEMPERATURE:
        response.state = stage +1;
        calculate = (double)((StoreMax-MaxTemp)/(StoreMax-PowerOffTemperatureThreshold))*64.0;
        result = (int)calculate;
        response.progresspercentage = 33.0 + result;
        Report("Wait calculation",__FILE__,MaxTemp,(int)response.progresspercentage,RpWarning,(int)result,0);
        response.message = "Wait for cooling down";
        break;
    case POWER_OFF_TURN_OFF_DRYER_FAN:
        response.state = stage +1;
        response.progresspercentage = 97.0;
        response.message = "Dryer fan off";
        break;
    case POWER_OFF_TURN_OFF_COOLER:
        response.state = stage +1;
        response.progresspercentage = 98.0;
        response.message = "Cooler off";
        break;
    case POWER_OFF_TURN_OFF_BLOWER:
        response.state = stage +1;
        response.progresspercentage = 99.0;
        response.message = "Blower off";
        break;
    case POWER_OFF_POWER_OFF:
    case POWER_OFF_ERROR:
    case POWER_OFF_CANCELLED:
        response.state = stage +1;
        response.progresspercentage = 100.0;
        last = true;
        response.message = "end of process";
        break;
    }
    Report("PowerDownUpdate",__FILE__,last,(int)response.progresspercentage,RpWarning,(int)stage,0);
    responseContainer = createContainer(MESSAGE_TYPE__StartPowerDownResponse, PowerDownToken, last, &response, &start_power_down_response__pack, &start_power_down_response__get_packed_size);
    responseContainer.has_continuous = true;
    responseContainer.continuous = true;
    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);
    //USBCDCD_sendData(container_buffer, container_size,10);

    SendChars((char*)container_buffer, container_size);
    //MessageContainer responseContainer;

    return status;
}
uint32_t PowerDownUpdateFunc(MessageContainer* requestContainer)
{
    uint32_t status = NOT_SUPPORTED;
    //MessageContainer responseContainer;

//    MachineUpdateInitParams InitParams;

    Report("PowerDownUpdateFunc",__FILE__,__LINE__,(int)0,RpWarning,(int)0,0);
    StartPowerDownRequest* request = start_power_down_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);
    ustrncpy (PowerDownToken, requestContainer->token,36);

    PowerDownUpdate(POWER_OFF_INIT);
    if (PowerOffInProcessGetState()==false)
        PowerOffInit();
    start_power_down_request__free_unpacked(request,NULL);
    return status;
}
void PowerDownStopReporting(void)
{
    PowerDownToken[0] = 0;
}
uint32_t ctlId;
uint32_t AbortPowerDownResetCallBackFunction(uint32_t IfIndex, uint32_t BusyFlag)
{
    SafeRemoveControlCallback(ctlId, AbortPowerDownResetCallBackFunction );
    /*volatile short *ptr = (volatile short *)(0x60000800 | 0x3D0);
    *ptr =  0;*/
    Power_Reset();
    return OK;
}

uint32_t AbortPowerDownFunc(MessageContainer* requestContainer)
{

    MessageContainer responseContainer;

    AbortPowerDownRequest* request = abort_power_down_request__unpack(NULL, requestContainer->data.len, requestContainer->data.data);

    AbortPowerDownResponse response = ABORT_POWER_DOWN_RESPONSE__INIT;

//TODO Handle the request!!!!
    //PowerDownStopReporting();
    responseContainer = createContainer(MESSAGE_TYPE__AbortPowerDownResponse, requestContainer->token, false, &response, &abort_power_down_response__pack, &abort_power_down_response__get_packed_size);
    responseContainer.has_continuous = true;
    responseContainer.continuous = true;
    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);
    //USBCDCD_sendData(container_buffer, container_size,10);

    SendChars((char*)container_buffer, container_size);
    PowerOffMachineState = POWER_OFF_CANCELLED;
    PowerDownUpdate(POWER_OFF_CANCELLED);

    ctlId = AddControlCallback("Abort", AbortPowerDownResetCallBackFunction, 2* eOneSecond, TemplateDataReadCBFunction,0,0, 0 );
    Report("HWSystemResetRequest", __FILE__,__LINE__,0, RpMessage, 2, 0);


return OK;
}