 
/*  wrmsg.c
    used by tm40.c
    Stephen D. Anderson --- October 29, 1994

    Function writes a message to the field instrum scratch memory.
    It does the following in order:

    Checks whether field instrum exists, does search if not.

    Opens a window to get user input of up to 32 bytes.  Pads
    remaining locations with spaces.  Packs bytes to 24.

    Writes the packed bytes to the field instrument using HART command 17.
    Indicates error, if any, or success.

    ON ENTRY:   no arguments.

    ON EXIT:    nothing is returned.

    REVISION LOG:


*/

#include "tm40.h"
#include "pup.h"

void wrmsg()
{
    extern byte status1,status2;
    extern byte addr[];     /*  info needed to talk to field instrum. */
    extern byte polling_addr;
    extern byte found;     /*  indicates field instrument has been found. */
    extern byte search(void);    
    extern void err(byte);
    extern void err1(byte);
    extern int hartcmd(byte *, byte, byte *, byte, byte *, byte);
    extern void pup(byte, byte *, byte *, byte);

    int i,j;
    byte msg_data[41];  /*  field instrum internal message. */
    byte message[40];
    byte dump[30];

    /*  need field intr info? */
    if (!found) found = search();
    if (!found) return;

    /*  get user message.  */
    Wopen(5,12,18,68,2,WHITE|_BROWN,WHITE|_BROWN);
    WputCen("\n\nEnter Message to Store in Field");
    WputCen("\nInstrument (up to 32 characters):");
    Wputs("\n\n       ");
    KwGetFmt(message, "!U!????????????????????????????????");

    /*  quit?  */
    if (TcxlErr == W_ESCPRESS)
    {
        Wclose(); return;
    }

    /*  pad remaining 32 positions with spaces. */
    i = 32 - strlen(message);
    for (j=1; j<=i; ++j) strcat(message, " ");

    /*  pack it. */
    PACK(message, msg_data, 32);

    /*  send it. */
    i = hartcmd(msg_data, 24, dump, 24, addr, 17);

    /*  command succeed?  */
    if ((i & 1) != 0)
    {
        /*  didn't succeed. */
        delay(1000); err1(17); Wclose(); return;
    }

    /*  correct number of received bytes?  */
    if ((i/256) != 24)
    {
        /*  command didn't succeed.  */
        err(17); Wclose(); return;
    }

    /*  report error or sucess.  */
    Wclear();
    if (status1 != 0)
    {
        /*  error.  */
        err(17);
        WputCen("\n\nMessage may not");
        WputCen("\nhave been written.");
    }
    else
    {
        /*  success.  */
        WputCen("\n\nMessage Written");
    }
    WputCen("\n\nHit any key to resume");
    KeyWait(); Wclose(); return;
}

