summaryrefslogtreecommitdiff
path: root/src/hal/components/streamer_usr.c
blob: 18c4988a5e570e5537422b8d99ea0cc7796a8b50 (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
/********************************************************************
* Description:  streamer_usr.c
*               User space part of "streamer", a HAL component that
*		can be used to stream data from a file onto HAL pins
*		 at a specific realtime sample rate.
*
* Author: John Kasunich <jmkasunich at sourceforge dot net>
* License: GPL Version 2
*    
* Copyright (c) 2006 All rights reserved.
*
********************************************************************/
/** This file, 'streamer_usr.c', is the user part of a HAL component
    that allows numbers stored in a file to be "streamed" onto HAL
    pins at a uniform realtime sample rate.  When the realtime module
    is loaded, it creates a fifo in shared memory.  Then, the user
    space program 'hal_streamer' is invoked.  'hal_streamer' takes 
    input from stdin and writes it to the fifo, and the realtime
    part transfers the data from the fifo to HAL pins.

    Invoking:

    halstreamer [chan_num]

    'chan_num', if present, specifies the streamer channel to use.
    The default is channel zero.  Since hal_streamer takes its data
    from stdin, it will almost always either need to have stdin 
    redirected from a file, or have data piped into it from some
    other program.
*/

/** This program is free software; you can redistribute it and/or
    modify it under the terms of version 2 of the GNU General
    Public License as published by the Free Software Foundation.
    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111 USA

    THE AUTHORS OF THIS LIBRARY ACCEPT ABSOLUTELY NO LIABILITY FOR
    ANY HARM OR LOSS RESULTING FROM ITS USE.  IT IS _EXTREMELY_ UNWISE
    TO RELY ON SOFTWARE ALONE FOR SAFETY.  Any machinery capable of
    harming persons must have provisions for completely removing power
    from all motors, etc, before persons enter any danger area.  All
    machinery must be designed to comply with local and national safety
    codes, and the authors of this software can not, and do not, take
    any responsibility for such compliance.

    This code was written as part of the EMC HAL project.  For more
    information, go to www.linuxcnc.org.
*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#include "rtapi.h"		/* RTAPI realtime OS API */
#include "hal.h"                /* HAL public API decls */
#include "streamer.h"

/***********************************************************************
*                  LOCAL FUNCTION DECLARATIONS                         *
************************************************************************/

/***********************************************************************
*                         GLOBAL VARIABLES                             *
************************************************************************/

int comp_id = -1;	/* -1 means hal_init() not called yet */
int shmem_id = -1;
int exitval = 1;	/* program return code - 1 means error */
int ignore_sig = 0;	/* used to flag critical regions */
int linenumber=0;	/* used to print linenumber on errors */
char comp_name[HAL_NAME_LEN+1];	/* name for this instance of streamer */

/***********************************************************************
*                            MAIN PROGRAM                              *
************************************************************************/

/* signal handler */
static void quit(int sig)
{
    if ( ignore_sig ) {
	return;
    }
    if ( shmem_id >= 0 ) {
	rtapi_shmem_delete(shmem_id, comp_id);
    }
    if ( comp_id >= 0 ) {
	hal_exit(comp_id);
    }
    exit(exitval);
}

#define BUF_SIZE 4000

int main(int argc, char **argv)
{
    int n, channel, retval, size, line;
    char *cp, *cp2;
    void *shmem_ptr;
    fifo_t *fifo;
    shmem_data_t *data, *dptr;
    char buf[BUF_SIZE];
	const char *errmsg;
    int tmpin, newin;
    struct timespec delay;

    /* set return code to "fail", clear it later if all goes well */
    exitval = 1;
    channel = 0;
    for ( n = 1 ; n < argc ; n++ ) {
	cp = argv[n];
	if ( *cp != '-' ) {
	    break;
	}
	switch ( *(++cp) ) {
	case 'c':
	    if (( *(++cp) == '\0' ) && ( ++n < argc )) { 
		cp = argv[n];
	    }
	    channel = strtol(cp, &cp2, 10);
	    if (( *cp2 ) || ( channel < 0 ) || ( channel >= MAX_STREAMERS )) {
		fprintf(stderr,"ERROR: invalid channel number '%s'\n", cp );
		exit(1);
	    }
	    break;
	default:
	    fprintf(stderr,"ERROR: unknown option '%s'\n", cp );
	    exit(1);
	    break;
	}
    }
    if(n < argc) {
	int fd;
	if(argc > n+1) {
	    fprintf(stderr, "ERROR: At most one filename may be specified\n");
	    exit(1);
	}
	// make stdin be the named file
	fd = open(argv[n], O_RDONLY);
	close(0);
	dup2(fd, 0);
    }
    /* register signal handlers - if the process is killed
       we need to call hal_exit() to free the shared memory */
    signal(SIGINT, quit);
    signal(SIGTERM, quit);
    signal(SIGPIPE, SIG_IGN);
    /* connect to HAL */
    /* create a unique module name, to allow for multiple streamers */
    snprintf(comp_name, sizeof(comp_name), "halstreamer%d", getpid());
    /* connect to the HAL */
    ignore_sig = 1;
    comp_id = hal_init(comp_name);
    ignore_sig = 0;
    /* check result */
    if (comp_id < 0) {
	fprintf(stderr, "ERROR: hal_init() failed: %d\n", comp_id );
	goto out;
    }
    hal_ready(comp_id);
    /* open shmem for user/RT comms (fifo) */
    /* initial size is unknown, assume only the fifo structure */
    shmem_id = rtapi_shmem_new(STREAMER_SHMEM_KEY+channel, comp_id, sizeof(fifo_t));
    if ( shmem_id < 0 ) {
	fprintf(stderr, "ERROR: couldn't allocate user/RT shared memory\n");
	goto out;
    }
    retval = rtapi_shmem_getptr(shmem_id, &shmem_ptr);
    if ( retval < 0 ) {
	fprintf(stderr, "ERROR: couldn't map user/RT shared memory\n");
	goto out;
    }
    fifo = shmem_ptr;
    if ( fifo->magic != FIFO_MAGIC_NUM ) {
	fprintf(stderr, "ERROR: channel %d realtime part is not loaded\n", channel );
	goto out;
    }
    /* now use data in fifo structure to calculate proper shmem size */
    size = sizeof(fifo_t) + fifo->num_pins * fifo->depth * sizeof(shmem_data_t);
    /* close shmem, re-open with proper size */
    rtapi_shmem_delete(shmem_id, comp_id);
    shmem_id = rtapi_shmem_new(STREAMER_SHMEM_KEY+channel, comp_id, size);
    if ( shmem_id < 0 ) {
	fprintf(stderr, "ERROR: couldn't re-allocate user/RT shared memory\n");
	goto out;
    }
    retval = rtapi_shmem_getptr(shmem_id, &shmem_ptr);
    if ( retval < 0 ) {
	fprintf(stderr, "ERROR: couldn't re-map user/RT shared memory\n");
	goto out;
    }
    line = 1;
    fifo = shmem_ptr;
    data = fifo->data;
    while ( fgets(buf, BUF_SIZE, stdin) ) {
	/* calculate _next_ value for in */
	tmpin = fifo->in;
	newin = tmpin + 1;
	if ( newin >= fifo->depth ) {
	    newin = 0;
	}
	/* wait until there is space in the buffer */
	while ( newin == fifo->out ) {
            /* fifo full, sleep for 10mS */
	    delay.tv_sec = 0;
	    delay.tv_nsec = 10000000;
	    nanosleep(&delay,NULL);
	}
	/* make pointer fifo entry */
	dptr = &data[tmpin*fifo->num_pins];
	/* parse input line, write results to fifo */
	cp = buf;
	errmsg = NULL;
	for ( n = 0 ; n < fifo->num_pins ; n++ ) {
	    /* strip leading whitespace */
	    while ( isspace(*cp) ) {
		cp++;
	    }
	    switch ( fifo->type[n] ) {
	    case HAL_FLOAT:
		dptr->f = strtod(cp, &cp2);
		break;
	    case HAL_BIT:
		if ( *cp == '0' ) {
		    dptr->b = 0;
		    cp2 = cp + 1;
		} else if ( *cp == '1' ) {
		    dptr->b = 1;
		    cp2 = cp + 1;
		} else {
		    errmsg = "bit value not 0 or 1";
		    cp2 = cp;
		}
		break;
	    case HAL_U32:
		dptr->u = strtoul(cp, &cp2, 10);
		break;
	    case HAL_S32:
		dptr->s = strtol(cp, &cp2, 10);
		break;
	    default:
		/* better not happen */
		goto out;
	    }
	    if ( errmsg == NULL ) {
		/* no error yet, check for other possibilties */
		/* whitespace separates fields, and there is a newline
		   at the end... so if there is not space or newline at
		   the end of a field, something is wrong. */
		if ( *cp2 == '\0' ) {
		    errmsg = "premature end of line";
		} else if ( ! isspace(*cp2) ) {
		    errmsg = "bad character";
		}
	    }
	    /* test for any error */
	    if ( errmsg != NULL ) {
		/* abort loop on error */
		break;
	    }
	    /* advance pointers for next field */
	    dptr++;
	    cp = cp2;
	}
	if ( errmsg != NULL ) {
	    /* print message */
	    fprintf (stderr, "line %d, field %d: %s, skipping the line\n", line, n, errmsg );
	    /** TODO - decide whether to skip this line and continue, or 
		abort the program.  Right now it skips the line. */
	} else {
	    /* good data, keep it */
	    fifo->in = newin;
	}
	line++;
    }
    /* run was succesfull */
    exitval = 0;

out:
    ignore_sig = 1;
    if ( shmem_id >= 0 ) {
	rtapi_shmem_delete(shmem_id, comp_id);
    }
    if ( comp_id >= 0 ) {
	hal_exit(comp_id);
    }
    return exitval;
}