
/*  wrpoll.c
    used by tm40.c
    Stephen D. Anderson --- December 20, 1994

    Function changes field instrument polling address.  Does this in
    order:

    Checks whether field instrum exists, searches if not.
    
    Displays existing polling address, asks for new polling address,
    waits for user entry.

    Checks whether entry is number from 0 to 15.  If not, repeats
    previous step.  If so, sends HART command 6.

    If command fails, indicates error.  If sucess, indicates polling
    address has been rewritten and sets global variable "found" to 0
    to force another search for field instruments.


    ON ENTRY:   no arguments.

    ON EXIT:    returns nothing.

    REVISION LOG:

*/

#include "tm40.h"

void wrpoll()
{

    typedef unsigned char byte;

    extern byte polling_addr;
    extern byte found;
    extern byte addr[];
    extern byte status1;

    extern byte search(void);
    extern int hartcmd(byte *, byte, byte *, byte, byte *, byte);
    extern void err(byte);
    extern void err1(byte);

    int i;
    byte s[5];
    byte new_addr;

    /*  find field instrum if necessary. */
    if (!found) found = search();
    if (!found) return;

    /*  display old address and get new one. */
    Wopen(5,15,12,50,2,WHITE|_BLUE,WHITE|_BLUE);
    while (1)
    {
        Wclear();
        Wputf("\n\n    Address is now %d\n\n",polling_addr);
        KwGetFmt(s, "'    New Address (0 - 15): '!R!#!R!# ");

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

        new_addr = (byte)atoi(s);
        if ((new_addr < 0) || (new_addr > 15))
            Wperror("  Bad Number  ");
        else
            break;
    } 

    /*  send the command. */
    i = hartcmd(&new_addr, 1, s, 1, addr, 6);

    if (( i & 1) != 0)
    {
        /*  command failed.  */
        delay(1000); err1(6); Wclose(); return;
    }

    /*  report success or any error.  */
    Wopen(5,20,15,60,2,WHITE|_BLACK,WHITE|_BLACK);
    if (status1 != 0)
    {
        /*  error  */
        err(6);
        Wputs("\n\n    Polling Address may");
        Wputs("\n    not have been changed.");
    }
    else
    {
        /*  success. */
        Wputs("\n\n   Polling Address Changed");
        Wputf("\n\n   From %d To %d",polling_addr,new_addr);
    }
    WputCen("\n\nHit any key to resume");
    KeyWait(); Wclose(); Wclose();

    /*  force another search for field instruments.  */
    found = 0;
}

