/* **MEMBER**=NONE **CMS**=PKNOBS ============================================================================== Abs: Top level routines to process PC <--> Knob box messages. Name: drvKnobScpBox.c Module. No routine by this name. PKNmsg_Init_Line PKNmsg_Clear_Count PKNmsg_Rqst_Count PKNmsg_Reply_Count PKNmsg_Legend_Update PKNmsg_Rqst_Reset static PKNmsg_Send static PKNmsg_Recv static PKNmsg_Checksum Proto: drvKnobScpBox.h Auth: 18-Oct-1995, Robert C. Sass (RCS) Rev: 07-Dec-1995, Ron Chestnut (RON) -------------------------------------------------------------------------------- Mod: (newest to oldest) 29-Feb-2014, Sonya Hoobler (SONYA): Modify to communicate with knobs over network instead of serial. Many associated changes. Modify to run in context of EPICS IOC and added support for EPICS records. 16-Jan-2014, Changes to communicate with knob boxes over ethernet instead of RS485. Incorporated turns Rply_Cnt into Rqst_Cnt in order to verify reply is for correct CPU before passing turns onto VAX. 27-Sep-1996, Robert C. Sass (RCS): Call PKUtil_Errline before error message printouts. ============================================================================== */ #include /* strncpy */ #include /* abs */ #include /* printf & friends */ #include /* NULL */ #include /* time, ctime */ #include /* abs */ #include #include #include #include #include #include /* close */ #include #include "slc_macr.h" /* vmsstat_t etc. */ #include "drvKnobScp.h" #include "drvKnobScpAlpha.h" #include "drvKnobScpBox.h" #include #include #include /* ** Local prototypes. Not referenced outside of this module. */ static vmsstat_t PKNmsg_Send (const char *node, charu *bufo_p, int count, unsigned *osstatus_p, box_ts *box_ps); static vmsstat_t PKNmsg_Recv (const char *node, charu *bufi_p, int ecount, unsigned *osstatus_p, box_ts *box_ps, charu *recvknobcpu); static charu PKNmsg_Checksum (charu *buf_p, int count); #define UDP 0 #define TCP 1 static int PROTO = TCP; /* UDP should work, but unable to get terminal server UDP server working with knobs */ /*============================================================================= Abs: Exit handler for us. Name: PKMain_Exit_Handler Args: None. Rem: Close our socket. This is to cover the possibility of someone doing a while we're running. We must close the socket else if we're started up again we'll get a bind error at initialize time. Side: None. Ret: Void. ============================================================================= */ static void PKN_Exit_Handler (int *socknum_p) { int status; char blocking = 0; /*--------------------------- Code ---------------------------------------*/ /* ** Set the socket to blocking so the sclose is synchronous. */ status = ioctl(*socknum_p, FIONBIO, &blocking); status = close(*socknum_p); return; } /*============================================================================= Abs: Initialize a knob box connection Name: PKNmsg_Init_Box Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only box box number to initialize Use: integer Type: int Acc: read only Mech: by value socknum_p pointer to created socket number Use: pointer Type: int * Acc: write only Mech: by reference sockaddr_ps pointer to our socket Use: pointer Type: struct sockaddr_in * Acc: write only Mech: by reference servaddr_ps pointer to server socket Use: pointer Type: struct sockaddr_in * Acc: write only Mech: by reference connected pointer to connected flag Use: pointer Type: char * Acc: write only Mech: by reference Rem: Create a socket for communicating with the knob box and bind it. Fill in the servaddr socket structure, then connect to it. Side: None. Ret: int C logical true (OK) false (error) ============================================================================= */ int PKNmsg_Init_Box (const char *node, int box, int *socknum_p, struct sockaddr_in *sockaddr_ps, struct sockaddr_in *servaddr_ps, char *connected) { int ostatus = 1; /* Output C logical status; assume OK */ int status; /* Status from bind & sioctl */ int reuseon = 1; /* For socket reuse option */ struct hostent *hp; int tmp, i; char str[100]; char lconnected = *connected; /* Last connection status */ /*--------------------------- Code -----------------------------------------*/ if ( debug >= MED ) printf("PKNmsg_Init_Box: init box %i node %s\n", box, node); /* ** Assume we won't connect to terminal server ** Do not need to lock (devGenVar) because this is running ** in single thread */ *connected = 0; /* ** Create a TCP or UDP socket to send and receive knob box msgs */ if ( PROTO == UDP ) *socknum_p = socket(AF_INET, SOCK_DGRAM, 0); else *socknum_p = socket(AF_INET, SOCK_STREAM, 0); if(*socknum_p < 0) { errlogPrintf("SCP Knobs: FATAL error %d. Can't create a socket\n", errno); ostatus = 0; // Bad news bears goto egress; } if ( PROTO == TCP ) { /* ** Set TCP socket to NODELAY to send individual packets instead of ** queuing them up */ status = setsockopt (*socknum_p, IPPROTO_TCP, TCP_NODELAY, &reuseon, sizeof(reuseon)); if(status < 0) { errlogPrintf("SCP Knobs: FATAL error %d. Can't set TCP to NODELAY\n", errno); ostatus = 0; // Tell caller we failed goto egress; } } /* ** Set the socket to reuse the address in case we're ** aborted by a scurrilous operator. - this is probably not needed for this socket */ status = setsockopt (*socknum_p, SOL_SOCKET, SO_REUSEADDR, &reuseon, sizeof(reuseon)); if(status < 0) { errlogPrintf("SCP Knobs: FATAL error %d. Can't set socket to reuse\n", errno); ostatus = 0; // Tell caller we failed goto egress; } /* ** Fill in the server's address and data */ memset((char*)servaddr_ps, 0, sizeof(*servaddr_ps)); servaddr_ps->sin_family = AF_INET; servaddr_ps->sin_port = htons(2100 + box); // Box number = TS port number = COW number /* ** Look up the address of the server given its name */ hp = gethostbyname(node); if (!hp) { errlogPrintf("SCP Knobs: FATAL: Could not obtain address of %s\n", node); ostatus = 0; goto egress; } if ( debug >= MED ) { printf("PKNmsg_Init_Box: server port %i host order %i. Knob box IPs:\n", servaddr_ps->sin_port, ntohs( servaddr_ps->sin_port)); for (i=0; hp->h_addr_list[i] != 0; i++) printf("addr %i is %u\n", i, htonl(*(int *) hp->h_addr_list[i] )); } tmp = *(int *)hp->h_addr_list[0]; /* ** Put the host's address into the server address structure */ memcpy((void *)&servaddr_ps->sin_addr, &tmp, hp->h_length ); /* ** Connect to server. Failure to connect is not fatal; we can try again later. */ if (connect(*socknum_p, (struct sockaddr *)servaddr_ps, sizeof(*servaddr_ps)) < 0) { sprintf(str, "Warning: Failed to connect to Box %i terminal server port", box); perror(str); PKN_Exit_Handler(socknum_p); goto egress; } *connected = 1; egress: if ( *connected != lconnected ) { if ( boxVarScan ) scanIoRequest( boxVarScan ); } return(ostatus); } /*============================================================================= Abs: Clear counter on specified knob. Name: PKNmsg_Clear_Count Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only knobcpu cpuid of knob Use: integer Type: charu Acc: read only Mech: by value osstatus_p Output final serial status Use: pointer Type: unsigned * Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: read only Rem: Construct message to set knob count to zero and send it. Side: None. Ret: status from PKNmsg_Send ============================================================================= */ vmsstat_t PKNmsg_Clear_Count (const char *node, charu knobcpu, unsigned *osstatus_p, box_ts *box_ps) { tkset_count_ts tkset_count_s = {{CTRL_B, 0, TKSET_COUNT}, 0, 0, {0, CR}}; vmsstat_t iss; /*-------------------------- code ---------------------------------------*/ tkset_count_s.pkhead.knobcpu = knobcpu; // Knob cpu to message if ( debug >= HIGH ) printf("PKNmsg_Clear_Count: before send msg to box\n"); iss = PKNmsg_Send (node, (charu *) &tkset_count_s, sizeof(tkset_count_s), osstatus_p, box_ps); return (iss); } /*============================================================================= Abs: Request counter on specified knob and optionally get reply Name: PKNmsg_Rqst_Count Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only knobcpu cpuid of knob Use: integer Type: charu Acc: read only Mech: by value osstatus_p Output final serial status Use: pointer Type: unsigned * Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: read only ocount_p Output knob count Use: pointer If 0, do not return turns count. Type: unsigned * Acc: write only Mech: by reference Rem: Build knobs message to request a readout of the counter value for a knob, then read the count reply message. The count in the message is 2 charu so use local pointer to insert the 2 bytes into the callers unsigned. (If ocount_p is NULL, still read reply to clear input queue, but then return.) Side: None Ret: status from PKNmsg_Send. ============================================================================= */ vmsstat_t PKNmsg_Rqst_Count (const char *node, charu knobcpu, unsigned *osstatus_p, box_ts *box_ps, int16_t *ocount_p) { tkrqst_ts tkrqst_count_s = {{CTRL_B, 0, TKRQST_COUNT}, {0, CR}}; vmsstat_t iss; fkreply_count_ts fkreply_count_s = {{CTRL_B, 0, FKREPLY_COUNT}, 0, 0, 0, {0, CR}}; charu *lowhi_p; // char pointer to move lo and hi bytes charu recvknobcpu; int i = 0; /*-------------------------- code ---------------------------------------*/ tkrqst_count_s.pkhead.knobcpu = knobcpu; // Insert knobcpu if ( debug >= HIGH ) printf("PKNmsg_Rqst_Count: before send msg to box\n"); iss = PKNmsg_Send (node, (charu *) &tkrqst_count_s, sizeof(tkrqst_count_s), osstatus_p, box_ps); if ( !SUCCESS(iss) ) return (iss); /* ** Limit of turn counts we'll accept as valid. */ #define TURNLIMIT 175 fkreply_count_s.pkhead.knobcpu = knobcpu; // Insert knobcpu lowhi_p = (charu *) ocount_p; // Make local char * if (SUCCESS(iss = PKNmsg_Recv (node, (charu *) &fkreply_count_s, sizeof(fkreply_count_s), osstatus_p, box_ps, &recvknobcpu))) { if ( knobcpu != recvknobcpu ) { printf("Turns rqst reply out of order, expected cpu 0x%02x but received 0x%02x\n", knobcpu, recvknobcpu); iss = PK_BADPARAM; /* update this to be code */ /* ** To break out of condition of out-of-order messages */ if ( debug >= LOW ) printf("Before entering while loop to break condition of out-of-order messages\n"); while( (iss != PK_READ_TIMEOUT) && (i++ < MAX_KNOBS_BOX) ) { iss = PKNmsg_Recv (node, (charu *) &fkreply_count_s, sizeof(fkreply_count_s), osstatus_p, box_ps, &recvknobcpu); if ( debug >= LOW ) printf(" Received knob CPU 0x%02x iss %x\n", recvknobcpu, iss); } if ( debug >= LOW ) printf("After exiting while loop to break condition of out-of-order messages\n"); goto egress; } if ( !ocount_p ) goto egress; *lowhi_p = fkreply_count_s.low; lowhi_p++; *lowhi_p = fkreply_count_s.hi; if (abs (*ocount_p) > TURNLIMIT) { printf ("Turn count %d too large node %s knob %d\n", *ocount_p, node, (int)knobcpu); *ocount_p = 0; } } egress: return (iss); } /*============================================================================= Abs: Read count reply on specified knob; not currently used, was incorporated into PKNmsg_Request_Count Name: PKNmsg_Reply_Count Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only knobcpu cpuid of knob Use: integer Type: charu Acc: read only Mech: by value ocount_p Output knob count Use: pointer Type: unsigned * Acc: write only Mech: by reference osstatus_p Output final serial status Use: pointer Type: unsigned * Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: read only Rem: Read an expected count reply message from the specified knob. The count in the message is 2 charu so use local pointer to insert the 2 bytes into the callers unsigned. Side: None. Ret: status from PKNmsg_Recv ============================================================================= */ vmsstat_t PKNmsg_Reply_Count (const char *node, charu knobcpu, int16_t *ocount_p, unsigned *osstatus_p, box_ts *box_ps) { /* ** Limit of turn counts we'll accept as valid. */ #define TURNLIMIT 175 fkreply_count_ts fkreply_count_s = {{CTRL_B, 0, FKREPLY_COUNT}, 0, 0, 0, {0, CR}}; vmsstat_t iss; charu *lowhi_p; // char pointer to move lo and hi bytes /*-------------------------- code ---------------------------------------*/ fkreply_count_s.pkhead.knobcpu = knobcpu; // Insert knobcpu lowhi_p = (charu *) ocount_p; // Make local char * if (SUCCESS(iss = PKNmsg_Recv (node, (charu *) &fkreply_count_s, sizeof(fkreply_count_s), osstatus_p, box_ps, 0))) { *lowhi_p = fkreply_count_s.low; lowhi_p++; *lowhi_p = fkreply_count_s.hi; } if (abs (*ocount_p) > TURNLIMIT) { printf ("Turn count %d too large node %s knob %d\n", *ocount_p, node, (int)knobcpu); *ocount_p = 0; } return (iss); } /*============================================================================= Abs: Update legend on specified knob. Name: PKNmsg_Legend_Update Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only firstcpu cpu of first knob on box Use: integer Type: charu Acc: read only Mech: by value ledset ledset # (0-3) on box Use: integer Type: char Acc: read only Mech: by value ledindex index (0-15) of starting LED to update Use: integer Type: char Acc: read only Mech: by value ibuf_p buffer of chars to write Use: ASCII Type: char * Acc: read only Mech: by reference osstatus_p Output final serial status Use: pointer Type: unsigned Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: pass as arg Rem: The legend update (led display) message requires the cpuid of the first knob on the box in the cpu part of the message. The ledset to update is given by the ledset # in the message body. The ledindex is the character number at which the update starts. The characters are numbered 0-15 starting from the left. Thus the ledindex determines the starting character and the # of characters in the message. After filling in the cpu, set and index in the message, calculate the length and copy the characters to the message. Insert the final CR and send the resulting message. Side: None. Ret: Status from PKNmsg_Send ============================================================================= */ vmsstat_t PKNmsg_Legend_Update (const char *node, charu firstcpu, char ledset, char ledindex, char *ibuf_p, unsigned *osstatus_p, box_ts *box_ps) { tklegend_update_ts tklegend_update_s = {{CTRL_B, 0, TKLEGEND_UPDATE}, 0}; vmsstat_t iss; int numchars; // # LED chars to update int msgsize; // Actual msg size sent /*-------------------------- code ---------------------------------------*/ tklegend_update_s.pkhead.knobcpu = firstcpu; // For update use firstcpu tklegend_update_s.ledset = ledset; // Which set of LEDs tklegend_update_s.ledindex = ledindex; // Index of starting LED /* ** Each LED in a 16 character legend is numbered 0 based from the left-most ** i.e. 0-15. All characters to the right of the indexed LED are updated thus the ** ledindex determines both the starting char and # of chars to send. */ numchars = LEGEND_SIZE - ledindex; strncpy ( (void *) &tklegend_update_s.legend, (void *) ibuf_p, numchars); // Chars to msg /* ** The tklegend_update_s message is variable length depending on the ** # of characters sent. Insert the trailing CR based on the size and ** send just the number required for the update. */ tklegend_update_s.legend[numchars - 1 + sizeof(pktail_ts)] = CR; msgsize = sizeof(tklegend_update_s) - ledindex; if ( debug >= HIGH ) printf("PKNmsg_Legend_Update: before update ledset %i ledindex %i to %s\n", ledset, ledindex, ibuf_p); iss = PKNmsg_Send (node, (charu *) &tklegend_update_s, msgsize, osstatus_p, box_ps); epicsThreadSleep(.02); // extra wait after legend update - consider changing this; only knob 0 should be affected return (iss); } /*============================================================================= Abs: Reset a specified knob. Name: PKNmsg_Rqst_Reset Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only knobcpu cpuid of knob Use: integer Type: charu Acc: read only Mech: by value osstatus_p Output final serial status Use: pointer Type: unsigned * Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: pass as arg Rem: Build and send reset message to the specified knob. This is usually done when a knob communication error is encountered. Side: None. Ret: status from PKNmsg_Send ============================================================================= */ vmsstat_t PKNmsg_Rqst_Reset (const char *node, charu knobcpu, unsigned *osstatus_p, box_ts *box_ps) { tkrqst_ts tkrqst_reset_s = {{CTRL_B, 0, TKRQST_RESET}, {0, CR}}; vmsstat_t iss; /*-------------------------- code ---------------------------------------*/ tkrqst_reset_s.pkhead.knobcpu = knobcpu; // Insert knobcpu iss = PKNmsg_Send (node, (charu *) &tkrqst_reset_s, sizeof(tkrqst_reset_s), osstatus_p, box_ps); return (iss); } /*============================================================================= Abs: Send a message to a knob. Name: PKNmsg_Send Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only bufo_p message to send to knob Use: pointer Type: charu * Acc: read only Mech: by reference count # chars in message Use: integer Type: int Acc: read only Mech: by value osstatus_p Output final serial status Use: pointer Type: unsigned * Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: read and write Rem: Send the specified message after filling in the checksum. If we're not connected to box socket, try to connect. If we succeed, clear knob turn and proceed with message. If we fail, return error. If broken pipe error, set connected status to 0. Regardless of our success in the above endeavor, we wait for the timeout bit to go away after the last char is sent to re-enable the receiver. Side: None. Ret: PK_OKOK - All went well PK_WCHAR_TIMEOUT - Exceded MAX_SERIAL_RETRIES trying to send the message PK_RECVON_TIMEOUT - Exceded MAX_SERIAL_RETRIES waiting for the receiver to go ready after message sent. ============================================================================= */ static vmsstat_t PKNmsg_Send (const char *node, charu *bufo_p, int count, unsigned *osstatus_p, box_ts *box_ps) { vmsstat_t iss = PK_OKOK; struct sockaddr_in *servaddr_ps = &box_ps->boxsocket_s; int i, outlen; // Number of bytes sent /*-------------------------- code ---------------------------------------*/ /* ** If we have not yet successfully connected to the box, try again */ if (!box_ps->connected) { PKNmsg_Init_Box (node, box_ps->box, &box_ps->socknum, &box_ps->socket_s, &box_ps->boxsocket_s, &box_ps->connected); if (!box_ps->connected) { iss = PK_READ_TIMEOUT; goto egress; } /* ** Clear the knob counters in case anyone fiddled with them while we were not ** connected */ for ( i = 0; i < MAX_KNOBS_BOX; i++ ) { iss = PKNmsg_Rqst_Count (node, box_ps->knobs_as[i].ledcpu, osstatus_p, box_ps, 0); if ( !SUCCESS(iss) ) goto egress; } } bufo_p[1] |= 0x80; // CPU address [1] is biased by 0x80 bufo_p[count-2] = PKNmsg_Checksum(bufo_p, count-2); // Fill in checksum if ( debug >= HIGH ) { printf("PKNmsg_Send: msg to knobs, count %i:\n", count); for ( i = 0; i < count; i++ ) printf("0x%02x ", bufo_p[i]); printf("\n"); } outlen = sendto (box_ps->socknum, (void *)bufo_p, count, 0, (struct sockaddr *)servaddr_ps, sizeof(struct sockaddr_in)); if (outlen != count) { printf ("UDP to Knob Box Send Error %d!! Actual length = %d expected length = %d, sock num %i\n", errno, outlen, count, box_ps->socknum); if (errno == EPIPE) { box_ps->connected = 0; printf("Broken pipe. Set connected flag to 0\n"); } iss = 0; // set error (change code?) } egress: /* ** Return last known serial status */ *osstatus_p = 1; // update this - assume status good (look into what value to put here) return(iss); } /*============================================================================= Abs: Receive a message. Name: PKNmsg_Recv Args: node node name of device that comm with this knob box Use: string Type: const char * Acc: read only inmsgbuf input message received Use: pointer Type: charu * Acc: write only Mech: by reference elen expected # chars in message Use: integer Type: int Acc: read only Mech: by value osstatus_p Output final serial status Use: pointer Type: unsigned * Acc: write only Mech: by reference box_ps Pointer to box struct Use: pointer Type: box_ts Acc: read only recvknobcpu Pointer to knob CPU char Use: pointer Type: charu * Acc: write only Rem: Wait MAX_SERIAL_RETRIES for the first char to be ready. Read each char to the number specified retrying MAX_SERIAL_RETRIES for the entire message. Calculate and verify the checksum of the incoming message. Side: None. Ret: PK_OKOK - Message received OK PK_BADPARAM - Failed to set socket timeout option PK_READ_TIMEOUT - No reply from box PK_CKSUM - Checksum error in received message. ============================================================================= */ static vmsstat_t PKNmsg_Recv (const char *node, charu *inmsgbuf, int elen, unsigned *osstatus_p, box_ts *box_ps, charu *recvknobcpu) { int inmsglen; // Length of VAX message vmsstat_t iss = PK_OKOK; // The usual static unsigned fromlen = sizeof(struct sockaddr_in); // For recvfrom struct sockaddr_in *insocket_s = &box_ps->boxsocket_s; // Socket info of sender struct timeval timeout; // Receive message timeout int status, i; /*--------------------------- Code -----------------------------------------*/ /* ** Set timeout for receiving messages */ timeout.tv_sec = 0; timeout.tv_usec = box_timeout*1e3; status = setsockopt (box_ps->socknum, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(struct timeval)); if(status < 0) { printf ("Aaack!! Error %d. Can't set socket recv timeout!! I Give up!!\n", errno); iss = PK_BADPARAM; // Tell caller we failed goto egress; } inmsglen = recvfrom (box_ps->socknum, (void *)inmsgbuf, elen, 0, (struct sockaddr *)insocket_s, &fromlen); if ( debug >= HIGH ) { printf("PKNmsg_Recv: inmsglen %i msg from box:\n", inmsglen); for (i = 0; i < inmsglen; i++) printf("0x%02x ",inmsgbuf[i]); printf("\n"); } if (inmsglen > 0) status = 1; // Tell caller ve haf a msg else // If no msg, check if not std error { printf ("From Knob Receive Error %d!! Actual length = %d\n", errno, inmsglen); iss = PK_READ_TIMEOUT; goto egress; } if ( recvknobcpu ) *recvknobcpu = inmsgbuf[1] & ~0x80; /* ** If we get here we seem to have read the desired number of ** characters so check the checksum. */ if (PKNmsg_Checksum (inmsgbuf, elen-2) != inmsgbuf[elen-2]) { if ( debug >= LOW ) printf ("Checksum error on input message.\n"); iss = PK_CKSUM; } egress: *osstatus_p = status; // Give user our last status return (iss); } /*============================================================================= h Abs: Compute checksum for a message. Name: PKNmsg_Checksum Args: buf_p message for which to compute checksum Use: pointer Type: charu * Acc: read/write Mech: by reference count # chars for which to calc checksum Use: integer Type: int Acc: read only Mech: by value Rem: Return the XOR of the bytes in the message buffer. Side: None. Ret: Unsigned byte checksum. ============================================================================= */ static charu PKNmsg_Checksum (charu *buf_p, int count) { int i; // Usual looper charu cksum; // Our output /*-------------------------- code ---------------------------------------*/ /* ** Return XOR of all bytes as function output. */ for (i=1, cksum=buf_p[0]; i