Пример #1
0
HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
{
	hid_device *dev;
	HIDP_CAPS caps;
	HIDP_PREPARSED_DATA *pp_data = NULL;
	BOOLEAN res;
	NTSTATUS nt_res;

#ifndef HIDAPI_USE_DDK
	if (!initialized)
		lookup_functions();
#endif

	dev = new_hid_device();

	// Open a handle to the device
	dev->device_handle = CreateFileA(path,
			GENERIC_WRITE |GENERIC_READ,
			FILE_SHARE_READ | FILE_SHARE_WRITE, /*share mode*/
			NULL,
			OPEN_EXISTING,
			FILE_FLAG_OVERLAPPED,
			/* FILE_ATTRIBUTE_NORMAL, */
			0);

	// Check validity of write_handle.
	if (dev->device_handle == INVALID_HANDLE_VALUE) {
		// Unable to open the device.
		register_error(dev, "CreateFile");
		goto err;
	}

	// Get the Input Report length for the device.
	res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
	if (!res) {
		register_error(dev, "HidD_GetPreparsedData");
		goto err;
	}
	nt_res = HidP_GetCaps(pp_data, &caps);
	if (nt_res != HIDP_STATUS_SUCCESS) {
		register_error(dev, "HidP_GetCaps");	
		goto err_pp_data;
	}
	dev->input_report_length = caps.InputReportByteLength;
	HidD_FreePreparsedData(pp_data);

	return dev;

err_pp_data:
		HidD_FreePreparsedData(pp_data);
err:	
		CloseHandle(dev->device_handle);
		free(dev);
		return NULL;
}
Пример #2
0
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
{
	DWORD bytes_written;
	BOOL res;

	OVERLAPPED ol;
	unsigned char *buf;
	memset(&ol, 0, sizeof(ol));

	/* Make sure the right number of bytes are passed to WriteFile. Windows
	   expects the number of bytes which are in the _longest_ report (plus
	   one for the report number) bytes even if the data is a report
	   which is shorter than that. Windows gives us this value in
	   caps.OutputReportByteLength. If a user passes in fewer bytes than this,
	   create a temporary buffer which is the proper size. */
	if (length >= dev->output_report_length) {
		/* The user passed the right number of bytes. Use the buffer as-is. */
		buf = (unsigned char *) data;
	} else {
		/* Create a temporary buffer and copy the user's data
		   into it, padding the rest with zeros. */
		buf = (unsigned char *) malloc(dev->output_report_length);
		memcpy(buf, data, length);
		memset(buf + length, 0, dev->output_report_length - length);
		length = dev->output_report_length;
	}

	res = WriteFile(dev->device_handle, buf, length, NULL, &ol);
	
	if (!res) {
		if (GetLastError() != ERROR_IO_PENDING) {
			/* WriteFile() failed. Return error. */
			register_error(dev, "WriteFile");
			bytes_written = -1;
			goto end_of_function;
		}
	}

	/* Wait here until the write is done. This makes
	   hid_write() synchronous. */
	res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, TRUE/*wait*/);
	if (!res) {
		/* The Write operation failed. */
		register_error(dev, "WriteFile");
		bytes_written = -1;
		goto end_of_function;
	}

end_of_function:
	if (buf != data)
		free(buf);

	return bytes_written;
}
Пример #3
0
int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
{
        DWORD bytes_written;
        BOOL res;

        static OVERLAPPED ol;

Check_For_Result:
        if(!dev->blocking && dev->ioPending)
        {
            res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, FALSE/*don't wait*/);
            if(!res)
            {
                return 0;
            }
            else
            {
                dev->ioPending = false;
                return bytes_written;
            }
        }

        memset(&ol, 0, sizeof(ol));

        res = WriteFile(dev->device_handle, data, length, &bytes_written, &ol);

        if (!res) {
            if (GetLastError() != ERROR_IO_PENDING) {
                // WriteFile() failed. Return error.
                register_error(dev, "WriteFile");
                return -1;
            }
        }

        if(!dev->blocking)
        {
            dev->ioPending = true;
            goto Check_For_Result;
        }
        else
        {
            // Wait here until the write is done. This makes
            // hid_write() synchronous.
            res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, TRUE/*wait*/);
            if (!res) {
                    // The Write operation failed.
                    register_error(dev, "WriteFile");
                    return -1;
            }
        }

        return bytes_written;
}
Пример #4
0
HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
{

	hid_device *dev;
	HIDP_CAPS caps;
	HIDP_PREPARSED_DATA *pp_data = NULL;
	BOOLEAN res;
	NTSTATUS nt_res;

#ifndef HIDAPI_USE_DDK
	if (!initialized)
		lookup_functions();
#endif

	dev = new_hid_device();

	// Open a handle to the device
	dev->device_handle = open_device(path);

	// Check validity of write_handle.
	if (dev->device_handle == INVALID_HANDLE_VALUE) {
		// Unable to open the device.
		register_error(dev, "CreateFile");
		goto err;
	}

	// Get the Input Report length for the device.
	res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
	if (!res) {
		register_error(dev, "HidD_GetPreparsedData");
		goto err;
	}
	nt_res = HidP_GetCaps(pp_data, &caps);
	if (nt_res != HIDP_STATUS_SUCCESS) {
		register_error(dev, "HidP_GetCaps");	
		goto err_pp_data;
	}
	dev->input_report_length = caps.InputReportByteLength;
	HidD_FreePreparsedData(pp_data);

	dev->read_buf = (char*) malloc(dev->input_report_length);

	return dev;

err_pp_data:
		HidD_FreePreparsedData(pp_data);
err:	
		CloseHandle(dev->device_handle);
		free(dev);
		return NULL;
}
Пример #5
0
Pfstream_handle *pfstream_start_write_thread(char *fname)
{
    Pfstream_handle *pfh;  /* Handle downstream functions can use to
			access data from the pfstream */
    Pfstream_control *pfsc;  /* control structure passed to new thread */

    /*These need to be created fromt he free store.  If we
    used a local variable in this function these would disappear when
    this routine went out of scope screwing up the thread it was passed
    to, and the return handle would get dropped.*/
    allot(Pfstream_handle *,pfh,1);
    allot(Pfstream_control *, pfsc, 1);

    /* brttutil routine to create a multithreaded, posix compatible thread */
    pfh->mtf = pmtfifo_create(PFSTREAM_MAXQUEUE,1,0);
    if(pfh->mtf == NULL)
    {
        register_error(1,"pfstream_start_write_thead:  Could not create mtfifo\n");
        free(pfh);
        free(pfsc);
        return(NULL);
    }
    pfsc->mtf=pfh->mtf;

    /* open the stream and put the fp into the control structure */
    pfsc->fp = fopen(fname,"r+");
    if(pfsc->fp==NULL)
    {
        register_error(1,"pfstream_start_write_thread:  Cannot open output stream %s\n",
                       fname);
        pmtfifo_destroy(pfh->mtf,free);
        free(pfh);
        free(pfsc);
        return(NULL);
    }
    /* This launches the write thread.  This is assumed to do the
    opposite of the read thread.  That is, processing modules will
    push data onto this mtfifo and the write routine handled by
    this thread will pop them off and send the contents down the
    stream now open as fp */
    if(pthread_create(&(pfh->thread_id),NULL,pfstream_write_data,(void *)pfsc)!=0)
    {
        register_error(1,"pfstream_start_write_thread: cannot create write thread\n");
        pmtfifo_destroy(pfh->mtf,free);
        fclose(pfsc->fp);
        free(pfh);
        free(pfsc);
        return(NULL);
    }
    return(pfh);
}
Пример #6
0
HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
{
	hid_device *dev;
	HIDP_CAPS caps;
	PHIDP_PREPARSED_DATA pp_data = NULL;
	BOOLEAN res;
	NTSTATUS nt_res;

	if (hid_init() < 0) {
		return NULL;
	}

	dev = new_hid_device();

	/* Open a handle to the device */
	dev->device_handle = open_device(path, FALSE);

	/* Check validity of write_handle. */
	if (dev->device_handle == INVALID_HANDLE_VALUE) {
		/* Unable to open the device. */
		register_error(dev, "CreateFile");
		goto err;
	}

	/* Get the Input Report length for the device. */
	res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
	if (!res) {
		register_error(dev, "HidD_GetPreparsedData");
		goto err;
	}
	nt_res = HidP_GetCaps(pp_data, &caps);
	if (nt_res != HIDP_STATUS_SUCCESS) {
		register_error(dev, "HidP_GetCaps");	
		goto err_pp_data;
	}
	dev->output_report_length = caps.OutputReportByteLength;
	dev->input_report_length = caps.InputReportByteLength;
	HidD_FreePreparsedData(pp_data);

	dev->read_buf = (char*) malloc(dev->input_report_length);

	return dev;

err_pp_data:
		HidD_FreePreparsedData(pp_data);
err:	
		CloseHandle(dev->device_handle);
		free(dev);
		return NULL;
}
Пример #7
0
/* Creates a new thread to read pfstream data from fname.  Returns
a handle that defines the interface into the pfstream.  This is implementd
here by Brtt's pmtfifo.

This function mostly just creates the data objects used for the interface
and then sets up and creates the read thread passed to pthread_create.

Author: Gary Pavlis
Written:  october 2002
*/
#define PFSTREAM_MAXQUEUE 10  /* size of stack in pmtfifo queue */
Pfstream_handle *pfstream_start_read_thread(char *fname)
{
    Pfstream_handle *pfh;  /* Handle downstream functions can use to
			access data from the pfstream */
    Pfstream_control *pfsc;  /* control structure passed to new thread */

    /*These need to be created fromt he free store.  If we
    used a local variable in this function these would disappear when
    this routine went out of scope screwing up the thread it was passed
    to, and the return handle would get dropped.*/
    allot(Pfstream_handle *,pfh,1);
    allot(Pfstream_control *, pfsc, 1);

    /* brttutil routine to create a multithreaded, posix compatible thread */
    pfh->mtf = pmtfifo_create(PFSTREAM_MAXQUEUE,1,0);
    if(pfh->mtf == NULL)
    {
        register_error(1,"pfstream_start_read_thead:  Could not create mtfifo\n");
        free(pfh);
        free(pfsc);
        return(NULL);
    }
    pfsc->mtf=pfh->mtf;

    /* open the stream and put the fp into the control structure */
    pfsc->fp = fopen(fname,"r");
    if(pfsc->fp==NULL)
    {
        register_error(1,"pfstream_start_read_thread:  Cannot open input stream %s\n",
                       fname);
        pmtfifo_destroy(pfh->mtf,free);
        free(pfh);
        free(pfsc);
        return(NULL);
    }
    /* This launches the i/o thread. It is assumed that all it does is
    read data and push objects onto the Pmtfifo for downstream processors
    to pop off and use. */
    if(pthread_create(&(pfh->thread_id),NULL,
                      pfstream_read_data,(void *)pfsc)!=0)
    {
        register_error(1,"pfstream_start_read_thread: cannot create read thread\n");
        pmtfifo_destroy(pfh->mtf,free);
        fclose(pfsc->fp);
        free(pfh);
        free(pfsc);
        return(NULL);
    }
    return(pfh);
}
Пример #8
0
int 
log2orbpkt (char *comment, char **packet, int *nbytes, int *bufsize)

{
	int comment_length;
	unsigned short hdrsiz;
	unsigned short pktsiz;
	int bsize;
	unsigned short int usi;
	char *ptr;

	comment_length = strlen(comment);
	hdrsiz = 2 + 2 + 2 + 2;
	pktsiz = hdrsiz + comment_length + 1;
	*nbytes = pktsiz;
	bsize = *nbytes + 1;
	if (*packet == NULL) {
		*packet = (char *) malloc (bsize);
		if (*packet == NULL) {
			register_error (1, "log2orbpkt: malloc() error.\n");
			return (-1);
		}
		*bufsize = bsize;
	} else if (bsize > *bufsize) {
		*packet = (char *) realloc (*packet, bsize);
		if (*packet == NULL) {
			register_error (1, "log2orbpkt: realloc() error.\n");
			return (-1);
		}
		*bufsize = bsize;
	}

	ptr = *packet;
	H2N2 (ptr, &hdrsiz, 1);
	ptr += 2;
	H2N2 (ptr, &pktsiz, 1);
	ptr += 2;
	usi = (unsigned short int)QUANTERRA_LOG_HDR_TYPE;
	H2N2 (ptr, &usi, 1);
	ptr += 2;
	usi = (unsigned short int)QUANTERRA_LOG_PKT_TYPE;
	H2N2 (ptr, &usi, 1);
	ptr += 2;
	memcpy (ptr, comment, (int)comment_length + 1);

	/* normal exit */

	return (0);
}
Пример #9
0
int
setupqorbpkt ()

{
	if (register_pkt_handler (QUANTERRA_DATA_PKT_TYPE, NULL, unstuffqorbpkt) < 0) {
		register_error (0, "setupqorbpkt: register_pkt_handler() error.\n");
		return (-1);
	}
	if (register_pkt_handler (QUANTERRA_DATA_PKT_TYPE2, NULL, unstuffqorbpkt) < 0) {
		register_error (0, "setupqorbpkt: register_pkt_handler() error.\n");
		return (-1);
	}

	return (0);
}
Пример #10
0
int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
{
	BOOL res;
#if 0
	res = HidD_GetFeature(dev->device_handle, (PVOID)data, (ULONG)length);
	if (!res) {
		register_error(dev, "HidD_GetFeature");
		return -1;
	}
	return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
#else
	DWORD bytes_returned;

	OVERLAPPED ol;
	memset(&ol, 0, sizeof(ol));

	res = DeviceIoControl(dev->device_handle,
		IOCTL_HID_GET_FEATURE,
		data, (DWORD)length,
		data, (DWORD)length,
		&bytes_returned, &ol);

	if (!res) {
		if (GetLastError() != ERROR_IO_PENDING) {
			/* DeviceIoControl() failed. Return error. */
			register_error(dev, "Send Feature Report DeviceIoControl");
			return -1;
		}
	}

	/* Wait here until the write is done. This makes
	   hid_get_feature_report() synchronous. */
	res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
	if (!res) {
		/* The operation failed. */
		register_error(dev, "Send Feature Report GetOverLappedResult");
		return -1;
	}

	/* bytes_returned does not include the first byte which contains the
	   report ID. The data buffer actually contains one more byte than
	   bytes_returned. */
	bytes_returned++;


	return bytes_returned;
#endif
}
Пример #11
0
int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
{
	DWORD bytes_read = 0;
	size_t copy_len = 0;
	BOOL res;

	/* Copy the handle for convenience. */
	HANDLE ev = dev->ol.hEvent;

	if (!dev->read_pending) {
		/* Start an Overlapped I/O read. */
		dev->read_pending = TRUE;
		memset(dev->read_buf, 0, dev->input_report_length);
		ResetEvent(ev);
		res = ReadFile(dev->device_handle, dev->read_buf, dev->input_report_length, &bytes_read, &dev->ol);

        if (!res) {
            DWORD er = GetLastError();
            if (GetLastError() != ERROR_IO_PENDING) {
                /* ReadFile() has failed.
                   Clean up and return error. */
                CancelIo(dev->device_handle);
                dev->read_pending = FALSE;
                goto end_of_function;
            }
        }
	}

	if (milliseconds >= 0) {
		/* See if there is any data yet. */
		res = WaitForSingleObject(ev, milliseconds);
		if (res != WAIT_OBJECT_0) {
			/* There was no data this time. Return zero bytes available,
			   but leave the Overlapped I/O running. */
			return 0;
		}
	}

	/* Either WaitForSingleObject() told us that ReadFile has completed, or
	   we are in non-blocking mode. Get the number of bytes read. The actual
	   data has been copied to the data[] array which was passed to ReadFile(). */
	res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);

	/* Set pending back to false, even if GetOverlappedResult() returned error. */
	dev->read_pending = FALSE;

	if (res && bytes_read > 0) {
		/* Copy the whole buffer, report number and all. */
		copy_len = length > bytes_read ? bytes_read : length;
		memcpy(data, dev->read_buf, copy_len);
	}

end_of_function:
	if (!res) {
		register_error(dev, "GetOverlappedResult");
		return -1;
	}

	return copy_len;
}
Пример #12
0
int 
open_socket ( char *name, int default_port ) 
{
    int fd ; 
    struct sockaddr_in serv_addr ; 
    char server[256] ;
    char ipc[32] ;
    int port ;

    memset ( (char *) &serv_addr, 0, sizeof(serv_addr) ) ; 
    parsename ( name, default_port, server, &port ) ;
    
    name2ip(server, (struct in_addr *)&serv_addr.sin_addr.s_addr, ipc ) ;
    serv_addr.sin_family = AF_INET ; 
    serv_addr.sin_port = htons ( port ) ; 

    if ( (fd = socket(PF_INET, SOCK_STREAM, 0 )) < 0 ) {
	register_error ( 1, "Can't open stream socket\n" ) ; 
	fd = -1 ;
    } else if ( connect(fd, 
		(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0 ) {
	close ( fd ) ; 
	fd = -1 ;
    } else { 
	ignoreSIGPIPE() ;
    }

    return fd ;
}
Пример #13
0
int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
{
	BOOL res;
#if 0
	res = HidD_GetFeature(dev->device_handle, data, length);
	if (!res) {
		register_error(dev, "HidD_GetFeature");
		return -1;
	}
	return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
#else
	DWORD bytes_returned;

	OVERLAPPED ol;
	memset(&ol, 0, sizeof(ol));

	res = DeviceIoControl(dev->device_handle,
		IOCTL_HID_GET_FEATURE,
		data, length,
		data, length,
		&bytes_returned, &ol);

	if (!res) {
		if (GetLastError() != ERROR_IO_PENDING) {
			// DeviceIoControl() failed. Return error.
			register_error(dev, "Send Feature Report DeviceIoControl");
			return -1;
		}
	}

	// Wait here until the write is done. This makes
	// hid_get_feature_report() synchronous.
	res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
	if (!res) {
		// The operation failed.
		register_error(dev, "Send Feature Report GetOverLappedResult");
		return -1;
	}

    // Get HID Stick messages
    HID_GetStick20ReceiveData (data);

    return bytes_returned;
#endif


}
Пример #14
0
int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
{
	BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, length);
	if (!res) {
		register_error(dev, "HidD_SetFeature");
		return -1;
	}

	return length;
}
Пример #15
0
int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
	BOOL res;

	res = HidD_GetProductString(dev->device_handle, string, (ULONG)(sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS)));
	if (!res) {
		register_error(dev, "HidD_GetProductString");
		return -1;
	}

	return 0;
}
Пример #16
0
int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
{
	BOOL res;

	res = HidD_GetIndexedString(dev->device_handle, string_index, string, sizeof(wchar_t) * maxlen);
	if (!res) {
		register_error(dev, "HidD_GetIndexedString");
		return -1;
	}

	return 0;
}
Пример #17
0
int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
	BOOL res;

	res = HidD_GetProductString(dev->device_handle, string, 2 * maxlen);
	if (!res) {
		register_error(dev, "HidD_GetProductString");
		return -1;
	}

	return 0;
}
Пример #18
0
int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
{
	BOOL res;

	res = HidD_GetSerialNumberString(dev->device_handle, string, sizeof(wchar_t) * maxlen);
	if (!res) {
		register_error(dev, "HidD_GetSerialNumberString");
		return -1;
	}

	return 0;
}
Пример #19
0
int 
qcomment2qorbpkt (unsigned char *qdata_pkt,
			double *time, char *srcname,
			char **packet, int *nbytes, int *bufsize)

{
	int i, n;
	char network[32], station[32];
	char comment[512];
	char *ptr;
	unsigned char comment_length;
	int year, month, day, doy, hour, minute;
	double second;

	comment_length = qdata_pkt[14];
	memcpy (comment, &(qdata_pkt[15]), (int)comment_length);
	comment[comment_length] = '\0';

	ptr = (char *)qdata_pkt + 15 + comment_length;
	for (i=0; i<2; i++) if (ptr[4+i] != ' ' && ptr[4+i] != '\0') break;
	n = 2-i;
	memcpy (network, &(ptr[4+i]), n);
	for (i=0; i<n; i++) if (network[i] == ' ' || network[i] == '\0') break;
	network[i] = '\0';
	for (i=0; i<4; i++) if (ptr[i] != ' ' && ptr[i] != '\0') break;
	n = 4-i;
	memcpy (station, &(ptr[i]), n);
	for (i=0; i<n; i++) if (station[i] == ' ' || station[i] == '\0') break;
	station[i] = '\0';
	sprintf (srcname, "/log/%s_%s", network, station);

	year = qdata_pkt[8];
	month = qdata_pkt[9];
	day = qdata_pkt[10];
	hour = qdata_pkt[11];
	minute = qdata_pkt[12];
	second = qdata_pkt[13];
	if (year < 50) year += 2000; else year += 1900;
	doy = mday2doy (year, month, day);
	*time = h2e (year, doy, hour, minute, second);

	if (log2orbpkt (comment, packet, nbytes, bufsize) < 0) {
		register_error (0, "qcomment2qorbpkt: log2orbpkt() error.\n");
		return (-1);
	}

	/* normal exit */

	return (0);
}
Пример #20
0
/* Special function used in orbgenloc for repeated task sending a db record 
to the orb.  It basicially implements a standard error message if this
fails.  

Arguments:
	db - input db pointer.  It is ASSUMED that db.record is dbSCRATCH
		and the relevant record has been copied onto the scratch
		record before calling this function. 
	orb - orb descriptor to send the scratch record of db to.  
Returns 0 if all worked.  Returns negative of number of failures 
otherwise with messages placed in error log.  
Author:  Gary L. Pavlis
Written:  May 1997
*/
int save_dbrecord(Dbptr db, int orb)
{
	char *table_name;
	int ret_code=0;


	if(db2orbpkt(db,orb)) 
	{
		dbquery(db,dbTABLE_NAME,table_name);
		register_error(0,"Error writing a record for table %s to orb\n",
			table_name);
		--ret_code;
	}
	return(ret_code);
}
Пример #21
0
int grdb_sc_getstachan(Dbptr dbscgr, int record, char *sta, char *chan,
        int *nsegs, double *time, double *endtime)
{
	Dbptr db;
	long is, ie;

	if (record >= 0) dbscgr.record = record;
	if (dbgetv (dbscgr, 0, "sta", sta, "chan", chan, "bundle", &db, 0) == dbINVALID) {
        	register_error (0, "grdb_sc_getstachan: dbgetv() error.\n");
        	return (-1);
	}
        dbget_range (db, &is, &ie);
	*nsegs = (int)(ie - is);
        db.record = is;
	dbgetv (db, 0, "time", time, 0);
        db.record = ie-1;
	dbgetv (db, 0, "endtime", endtime, 0);

	/* Normal exit. */

	return (0);
}
Пример #22
0
static int
autodrm_response (Dbptr db)
{

    Dbptr           dbstage;
    static Hook    *hook = 0;
    char            sta[MAX_STA_SIZE],
                    chan[MAX_CHAN_SIZE];
    double          time,
                    endtime;
    long            stageid;
    char           *s;
    Response       *response;
    Response_group *group;
    char            iunits[96],
                    ounits[96];
    char            gtype[100];
    long            i,
                    j;
    Paz            *paz;
    Fir            *fir;
    Fap            *fap;
    Fap2           *fap2;
    FILE           *file;
    double          samprate,
                    gnom,
                    gcalib;
    double          calper=0.0;
    long            decifac;
    char            dir[100],
                    dfile[100];
    char            filename[STRSZ];
    long            nmatches;
    int             errors = 0;
    Tbl            *tbl,
                   *stbl;
    double          mintime=0,
                    maxtime=0;
    char            segtype;
    static Tbl     *keys1 = 0,
                   *keys2 = 0;

    if (keys1 == 0) {
	keys1 = strtbl ("sta", "chan", "time", NULL);
	keys2 = strtbl ("sta", "chan", "time::endtime", NULL);
    }
    dbstage = dblookup (db, 0, "stage", 0, 0);
    nmatches = dbmatches (db, dbstage, &keys1, &keys2, &hook, &tbl);

    switch (nmatches) {
      case dbINVALID:
      case 0:
	dbgetv (db, 0, "sta", sta, "chan", chan, "time", &time, NULL);
	complain (0, "Can't match record for %s:%s @ %s in stage table",
		  sta, chan, s = strydtime (time));
	free (s);
	errors++;
	break;

      default:
	stbl = newtbl (maxtbl (tbl));
	for (i = 0; i < nmatches; i++) {
	    dbstage.record = (long) gettbl (tbl, i);
	    dbgetv (dbstage, 0,
		    "stageid", &stageid,
		    "time", &time,
		    "endtime", &endtime,
		    NULL);
	    if (i == 0) {
		mintime = time;
		maxtime = endtime;
	    } else {
		mintime = MAX (time, mintime);
		maxtime = MIN (endtime, maxtime);
	    }
	    settbl (stbl, stageid - 1, (char *) i);
	}
	if (maxtbl (tbl) != maxtbl (stbl)) {
	    dbgetv (db, 0, "sta", sta, "chan", chan, "time", &time, NULL);
	    complain (0, "stageid numbers for %s:%s @ %s don't add up.",
		      sta, chan, s = strydtime (time));
	    free (s);
	    errors++;
	} else {
	    errors += write_cal2 (db, mintime, maxtime, &calper);

	    for (i = 0; i < nmatches; i++) {
		j = (long) gettbl (stbl, i);
		dbstage.record = (long) gettbl (tbl, j);
		dbgetv (dbstage, 0,
			"sta", sta,
			"chan", chan,
			"time", &time,
			"endtime", &endtime,
			"stageid", &stageid,
			"decifac", &decifac,
			"samprate", &samprate,
			"gnom", &gnom,
			"gcalib", &gcalib,
			"dir", dir,
			"dfile", dfile,
			"gtype", gtype,
			"iunits", iunits,
			"ounits", ounits,
			NULL);

		if (gcalib > 0.0) {
		    gnom *= gcalib;
		} else if (gcalib < 0.0) {
		    complain (0, "gcalib = %10.3f < 0. is invalid for %s:%s @ %s.\n",
			      gcalib, sta, chan, s = strydtime (time));
		    free (s);
		    errors++;
		}
		if (*dir != '-' || *dfile != '-') {
		    long            mark;
		    dbextfile (dbstage, "stage", filename);
		    mark = elog_mark ();
		    elog_log (0, "response file is '%s'", filename);
		    if ((file = fopen (filename, "r")) == 0
			    || read_response (file, &response) < 0) {
			register_error (0,
			      "Can't read response file %s  for %s_%s @ %s",
				 filename, sta, chan, s = strydtime (time));
			free (s);
			fclose (file);
			errors++;
		    } else {
			fclose (file);
			if (response->ngroups > 1) {
			    register_error (0,
			      "stage response file %s has %d stages, not 1",
					    filename, response->ngroups);
			    errors++;
			} else {

			    group = response->groups;

			    switch (group->id) {

			      case PAZ:
				/* The normalization frequency chosen in the
				 * response file may not necessarily be the
				 * same as the one chosen by calibration
				 * table for insertion into the seed volumes.
				 * Consequently, we have to adjust the
				 * specified gnom to be correct for the seed
				 * normalization frequency.  Since the gain
				 * is
				 * 
				 * G(f) = gnom_db * A_response_file * P(f) =
				 * gnom_seed * A_seed * P(f)
				 * 
				 * We have
				 * 
				 * gnom_seed = gnom_db * A_response_file /
				 * A_seed
				 * 
				 * gnom_db is just the gnom from the stage
				 * table. A_response_file is the
				 * normalization from the response file, left
				 * in the stage structure. Below, we
				 * calculate A_seed by setting
				 * A_response_file to 1.0.
				 * 
				 */

				paz = (Paz *) group->pvt;
				for (j = 0; j < strlen (iunits); j++) {
				    iunits[j] = tolower (iunits[j]);
				}
				s = getarr (Segtype, iunits);
				if (s == 0) {
				    segtype = 'D';
				} else {
				    segtype = *s;
				}
				adwrite_paz (stageid, 0, gnom, segtype, ounits, paz);
				break;

			      case IIR:
				paz = (Paz *) group->pvt;
				for (j = 0; j < strlen (iunits); j++) {
				    iunits[j] = tolower (iunits[j]);
				}
				s = getarr (Segtype, iunits);
				if (s == 0) {
				    segtype = 'D';
				} else {
				    segtype = *s;
				}
				adwrite_paz (stageid, 1, gnom, segtype, ounits, paz);
				break;

			      case FIR:
				fir = (Fir *) group->pvt;
				errors += adwrite_fir (stageid, gnom, fir);
				break;

			      case FAP:
				fap = (Fap *) group->pvt;
				errors += adwrite_fap (stageid, ounits, fap);
				break;

			      case FAP2:
				fap2 = (Fap2 *) group->pvt;
				errors += adwrite_fap2 (stageid, ounits, fap2);
				break;


			      default:
				complain (0, "Unknown filter type %d in response file %s\n",
					  group->id, filename);
				errors++;
				break;

			    }
			}
		    }
		    elog_flush (mark, 0);
		} else {
		    char           *desc = "";

		    if (gcalib > 0.0) {
			gnom *= gcalib;
		    } else if (gcalib < 0.0) {
			complain (0, "gcalib = %10.3f < 0. is an invalid value.\n", gcalib);
			errors++;
		    }
		    if (strcmp (gtype, "digitizer") == 0
		    /* following hack for psd2db */
			    || strcmp (gtype, "sensor") == 0) {
			fprintf (stdout, "DIG2 %2ld %15.8e %11.5f %s\n",
				 stageid, gnom, samprate, desc);
		    } else if (strcmp (gtype, "amplifier") == 0) {
			/* no corners */
			fprintf (stdout, "GEN2 %2ld %c %15.8e %7.3f                 0 %s\n",
				 stageid, *ounits, gnom, calper, desc);
		    } else {
			complain (0, "Unrecognized gtype='%s' for %s:%s @ %s",
				  gtype, sta, chan, s = strydtime (time));
			free (s);
			errors++;
		    }
		}
	    }
	}
	freetbl (stbl, 0);
	break;

    }
    freetbl (tbl, 0);
    return errors;
}
Пример #23
0
int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
{
	DWORD bytes_read = 0;
	BOOL res;

	// Copy the handle for convenience.
	HANDLE ev = dev->ol.hEvent;

	if (!dev->read_pending) {
		// Start an Overlapped I/O read.
		dev->read_pending = TRUE;
		ResetEvent(ev);
		res = ReadFile(dev->device_handle, dev->read_buf, dev->input_report_length, &bytes_read, &dev->ol);
		
		if (!res) {
			if (GetLastError() != ERROR_IO_PENDING) {
				// ReadFile() has failed.
				// Clean up and return error.
				CancelIo(dev->device_handle);
				dev->read_pending = FALSE;
				goto end_of_function;
			}
		}
	}

	if (milliseconds >= 0) {
		// See if there is any data yet.
		res = WaitForSingleObject(ev, milliseconds);
		if (res != WAIT_OBJECT_0) {
			// There was no data this time. Return zero bytes available,
			// but leave the Overlapped I/O running.
			return 0;
		}
	}

	// Either WaitForSingleObject() told us that ReadFile has completed, or
	// we are in non-blocking mode. Get the number of bytes read. The actual
	// data has been copied to the data[] array which was passed to ReadFile().
	res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
	
	// Set pending back to false, even if GetOverlappedResult() returned error.
	dev->read_pending = FALSE;

	if (res && bytes_read > 0) {
		if (dev->read_buf[0] == 0x0) {
			/* If report numbers aren't being used, but Windows sticks a report
			   number (0x0) on the beginning of the report anyway. To make this
			   work like the other platforms, and to make it work more like the
			   HID spec, we'll skip over this byte. */
			bytes_read--;
			memcpy(data, dev->read_buf+1, length);
		}
		else {
			/* Copy the whole buffer, report number and all. */
			memcpy(data, dev->read_buf, length);
		}
	}
	
end_of_function:
	if (!res) {
		register_error(dev, "GetOverlappedResult");
		return -1;
	}
	
	return bytes_read;
}
Пример #24
0
static int
is_dbprogram( char *what, char *dbprogram, char *dbpath ) 
{
	static Pf *pflib = 0;
	static Morphtbl *morphmap = 0;
	Tbl	*morphlist;
	int	rc;
	char	result[STRSZ];
	Tbl	*parts;

	rc = pfupdate( "libpforbstat", &pflib );

	if( rc < 0 || pflib == NULL ) {

		register_error( 0, "pforbstat: failed to load libpforbstat.pf "
				   "during database analysis\n" );
		return 0;

	}  else if( rc == 0 && morphmap == NULL ) {

		register_error( 0, "pforbstat: no morphmap present for database analysis\n" );
		return 0;
	}

	if( rc > 0 ) {

		if( morphmap != (Morphtbl *) NULL ) {

			freemorphtbl( morphmap );
			
			morphmap = 0;
		}

		morphlist = pfget_tbl( pflib, "dbprograms_morph" );

		if( morphlist == NULL ) {
			
			register_error( 0, "pforbstat: failed to get dbprograms_morph "
					"from libpforbstat.pf during database analysis\n" );
			return 0;
		}
		
		rc = newmorphtbl( morphlist, &morphmap );

		freetbl( morphlist, 0 );

		if( rc != 0 ) {

			register_error( 0, "pforbstat: %d errors translating dbprograms_morph "
					"from libpforbstat.pf during database analysis\n" );
			return 0;
		}
	} 
	
	rc = morphtbl( what, morphmap, 0, result );

	if( rc <= 0 ) {

		strcpy( dbprogram, "" );
		strcpy( dbpath, "" );

		return 0;

	} else {

		parts = split( result, ' ' );

		strcpy( dbprogram, gettbl( parts, 0 ) );
		strcpy( dbpath, gettbl( parts, 1 ) );
		
		freetbl( parts, 0 );

		return 1;
	} 
}
Пример #25
0
int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
{
	DWORD bytes_read;
	BOOL res;

	HANDLE ev;
	ev = CreateEvent(NULL, FALSE, FALSE /*inital state f=nonsignaled*/, NULL);

	OVERLAPPED ol;
	memset(&ol, 0, sizeof(ol));
	ol.hEvent = ev;

	// Limit the data to be returned. This ensures we get
	// only one report returned per call to hid_read().
	length = (length < dev->input_report_length)? length: dev->input_report_length;

	res = ReadFile(dev->device_handle, data, length, &bytes_read, &ol);
	
	
	if (!res) {
		if (GetLastError() != ERROR_IO_PENDING) {
			// ReadFile() has failed.
			// Clean up and return error.
			CloseHandle(ev);
			goto end_of_function;
		}
	}

	if (!dev->blocking) {
		// See if there is any data yet.
		res = WaitForSingleObject(ev, 0);
		CloseHandle(ev);
		if (res != WAIT_OBJECT_0) {
			// There was no data. Cancel this read and return.
			CancelIo(dev->device_handle);
			// Zero bytes available.
			return 0;
		}
	}

	// Either WaitForSingleObject() told us that ReadFile has completed, or
	// we are in non-blocking mode. Get the number of bytes read. The actual
	// data has been copied to the data[] array which was passed to ReadFile().
	res = GetOverlappedResult(dev->device_handle, &ol, &bytes_read, TRUE/*wait*/);

	if (bytes_read > 0 && data[0] == 0x0) {
		/* If report numbers aren't being used, but Windows sticks a report
		   number (0x0) on the beginning of the report anyway. To make this
		   work like the other platforms, and to make it work more like the
		   HID spec, we'll skip over this byte. */
		bytes_read--;
		memmove(data, data+1, bytes_read);
	}
	
end_of_function:
	if (!res) {
		register_error(dev, "ReadFile");
		return -1;
	}
	
	return bytes_read;
}
Пример #26
0
int grdb_sc_loadcss (Dbptr dbin, char *net_expr, char *sta_expr,
        char *chan_expr, double tstart, double tend, 
        int coords, int ir, int orient, Dbptr *dbscgr, Dbptr *dbsc)
{
	Dbptr dbout, db, dbout2;
	char string[1024];
	char string2[1024];
	char sta_wfdisc[32], chan_wfdisc[32];
	int i, j, n, sensor=0, ok;
	Tbl *pat1, *pat2;
	Tbl *sortfields, *groupfields;
	FILE *file;
	Response *resp;
	int is_view=0;
	Dbptr db_to_clear;

	/* Subset the wfdisc by station-channel-time sifters. */

	dbout = dblookup (dbin, 0, "wfdisc", 0, 0);
	strcpy (string, "");
	if (sta_expr) {
		strcpy (string, "( ");
        	sprintf (string2, "sta =~ /%s/", sta_expr);
        	strcat (string, string2);
	}
	if (chan_expr) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "chan =~ /%s/", chan_expr);
        	strcat (string, string2);
	}
	if (tstart != 0.0 || tend != 0.0) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "(time < %.5f && endtime > %.5f)", tend, tstart);
        	strcat (string, string2);
	}
	if (string[0]) {
		strcat (string, " )");
		dbout = dbsubset (dbout, string, 0);
		is_view=1;
	}
        dbquery (dbout, dbRECORD_COUNT, &n);
        if (n < 1) {
		register_error (0, "grdb_sc_loadcss: No wfdisc rows to process.\n");
		return (-1);
        }

        /* Make the necessary joins and check for completeness. */

        if (coords) {
        	db = dblookup (dbin, 0, "site", 0, 0);
		if(is_view)db_to_clear=dbout;
        	dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		if(is_view) dbfree(db_to_clear);
		is_view=1;
		
        	dbquery (dbout, dbRECORD_COUNT, &n);
        	if (n < 1) {
			register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
			return (-1);
        	}
        	for (dbout.record=0; dbout.record<n; dbout.record++) {
        		if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"site.sta", string, 0) == dbINVALID) {
			    register_error (0, "grdb_sc_loadcss: dbgetv() error while checking site.\n");
			    return (-1);
			}
        		if (coords > 1 && strcmp(string, sta_wfdisc)) {
        			register_error (0, "grdb_sc_loadcss: Cannot find site parameters for %s %s.\n", 
        									sta_wfdisc, chan_wfdisc);
        			return (-1);
        		}
        	}
        }
        if (ir) {
        	db = dblookup (dbin, 0, "sensor", 0, 0);
		if(is_view)db_to_clear=dbout;
        	dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		if(is_view) dbfree(db_to_clear);
		is_view=1;
        	dbquery (dbout, dbRECORD_COUNT, &n);
        	if (n < 1) {
			register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
			return (-1);
        	}
        	for (dbout.record=0; dbout.record<n; dbout.record++) {
        		if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"sensor.sta", string, 0) == dbINVALID) {
			    register_error (0, "grdb_sc_loadcss: dbgetv() error while checking sensor.\n");
			    return (-1);
			}
        		if (ir > 1 && strcmp(string, sta_wfdisc)) {
        			register_error (0, "grdb_sc_loadcss: Cannot find sensor parameters for %s %s.\n", 
        									sta_wfdisc, chan_wfdisc);
        			return (-1);
        		}
        	}
        	sensor = 1;
		if(is_view)db_to_clear=dbout;
        	db = dblookup (dbin, 0, "instrument", 0, 0);
        	dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		if(is_view) dbfree(db_to_clear);
		is_view=1;
        	dbquery (dbout, dbRECORD_COUNT, &n);
        	if (n < 1) {
			register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
			return (-1);
        	}
        	for (dbout.record=0; dbout.record<n; dbout.record++) {
        		if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"sensor.inid", &j,
        				"instrument.insname", string2,
        				"instrument.inid", &i, 0) == dbINVALID) {
			    register_error (0, "grdb_sc_loadcss: dbgetv() error while checking instrument.\n");
			    return (-1);
			}
        		if (ir > 1 && (i != j)) {
        			register_error (0, "grdb_sc_loadcss: Cannot find instrument parameters for %s %s.\n", 
        									sta_wfdisc, chan_wfdisc);
        			return (-1);
        		}
        		if (i >= 0) {
				if (resp_arr == NULL) {
					resp_arr = newarr (0);
					if (resp_arr == NULL) {
        					register_error (0, "grdb_sc_loadcss: newarr() error.\n");
        					return (-1);
					}
				}
				dbextfile (dbout, "instrument", string);
				resp = (Response *) getarr (resp_arr, string);
				if (resp == NULL) {
					file = fopen (string, "r");
					if (file == NULL) {
						if (ir > 1) {
        						register_error (1, "grdb_sc_loadcss: fopen('%s') error.\n", string);
        						return (-1);
						}
					} else {
						if (read_response (file, &resp)) {
        						register_error (0, "grdb_sc_loadcss: read_response('%s') error.\n", string);
        						return (-1);
						}
						fclose (file);
						resp->insname = strdup(string2);
					}
					setarr (resp_arr, string, resp);
				}
			}
        	}
        }
        if (orient) {
        	ok = 1;
		if(is_view)db_to_clear=dbout;
        	db = dblookup (dbin, 0, "sitechan", 0, 0);
        	dbout2 = dbjoin (dbout, db, 0, 0, 1, 0, 0);
		is_view=1;
        	dbquery (dbout2, dbRECORD_COUNT, &n);
        	if (n < 1) {
        		ok = 0;
        	} else {
        		for (dbout2.record=0; dbout2.record<n; dbout2.record++) {
        			dbgetv (dbout2, 0, "wfdisc.sta", sta_wfdisc,
        				"wfdisc.chan", chan_wfdisc,
        				"sitechan.sta", string, 0);
        			if (strcmp(string, sta_wfdisc)) {
        				ok = 0;
        				break;
        			}
        		}
		}
		if (ok) {
			dbout = dbout2;
			if(is_view) dbfree(db_to_clear);
		} else {
			if (!sensor) {
        			db = dblookup (dbin, 0, "sensor", 0, 0);
				if(is_view)db_to_clear=dbout;
	       			dbout = dbjoin (dbout, db, 0, 0, 1, 0, 0);
				if(is_view) 
				{
					dbfree(dbout2);
					dbfree(db_to_clear);
				}
				is_view=1;
        			dbquery (dbout, dbRECORD_COUNT, &n);
        			if (n < 1) {
					register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
					return (-1);
        			}
        			for (dbout.record=0; dbout.record<n; dbout.record++) {
        				if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        						"wfdisc.chan", chan_wfdisc,
        						"sensor.sta", string, 0) == dbINVALID) {
			    			register_error (0, "grdb_sc_loadcss: dbgetv() error while checking sensor.\n");
			    			return (-1);
					}
        				if (orient > 1 && strcmp(string, sta_wfdisc)) {
        					register_error (0, "grdb_sc_loadcss: Cannot find sensor parameters for %s %s.\n", 
        											sta_wfdisc, chan_wfdisc);
        					return (-1);
        				}
        			}
			}
        		db = dblookup (dbin, 0, "sitechan", 0, 0);
        		pat1 = newtbl(1);
        		if (pat1 == NULL) {
        			register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
        			return (-1);
        		}
        		pat2 = newtbl(1);
        		if (pat2 == NULL) {
        			register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
        			return (-1);
        		}
			if(is_view)db_to_clear=dbout;
        		settbl (pat1, 0, strdup("sensor.chanid"));
        		settbl (pat2, 0, strdup("sitechan.chanid"));
        		dbout = dbjoin (dbout, db, &pat1, &pat2, 1, 0, 0);
			if(is_view) dbfree(db_to_clear);
			is_view=1;
        		freetbl (pat1, free);
        		freetbl (pat2, free);
        		dbquery (dbout, dbRECORD_COUNT, &n);
        		if (n < 1) {
				register_error (0, "grdb_sc_loadcss: No data rows to process.\n");
				return (-1);
        		} else {
        			for (dbout.record=0; dbout.record<n; dbout.record++) {
        				if (dbgetv (dbout, 0, "wfdisc.sta", sta_wfdisc,
        					"wfdisc.chan", chan_wfdisc,
        					"sitechan.sta", string, 0) == dbINVALID) {
			    		   register_error (0, "grdb_sc_loadcss: dbgetv() error while checking sitechan.\n");
			    		   return (-1);
					}
        				if (orient > 1 && strcmp(string, sta_wfdisc)) {
        					register_error (0, "grdb_sc_loadcss: Cannot find sitechan parameters for %s %s.\n", 
        											sta_wfdisc, chan_wfdisc);
        					return (-1);
        				}
        			}
			}
		}
        }

        /* Sort and group the output view. */

	if(is_view)db_to_clear=dbout;
	sortfields = newtbl (3);
	if (sortfields == NULL) {
		register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
		return (-1);
	}
	settbl (sortfields, 0, strdup("wfdisc.sta"));
	settbl (sortfields, 1, strdup("wfdisc.chan"));
	settbl (sortfields, 2, strdup("wfdisc.time"));
        *dbsc = dbsort (dbout, sortfields, 0, 0);
	if(is_view) dbfree(db_to_clear);
	groupfields = newtbl (2);
	if (groupfields == NULL) {
		register_error (0, "grdb_sc_loadcss: newtbl() error.\n");
		return (-1);
	}
	settbl (groupfields, 0, strdup("sta"));
	settbl (groupfields, 1, strdup("chan"));
	*dbscgr = dbgroup (*dbsc, groupfields, 0, 1);
	freetbl (sortfields, free);
	freetbl (groupfields, free);

	/* Normal exit */

	return (0);
}
Пример #27
0
int grtr_sc_create(Dbptr dbsc, char *net_expr, char *sta_expr, 
        char *chan_expr, double tstart, double tend, char *gap,
        int calib, int ir, Dbptr *trscgr)
{
	char time_str[100];
	char endtime_str[100];
	int ret, n, n2, i;
	double time, time2, endtime, endtime2;
	char sta[32], chan[32];
	char sta2[32], chan2[32];
	char string[1024];
	char string2[64];
	int new_view = 0;
	int is, crunch;
	Response *resp;
	Dbptr db;

	/* Subset input view */

	strcpy (string, "");
	if (sta_expr) {
		strcpy (string, "( ");
        	sprintf (string2, "sta =~ /%s/", sta_expr);
        	strcat (string, string2);
	}
	if (chan_expr) {
		if (string[0]) strcat (string, " && ");
		else strcpy (string, "( ");
        	sprintf (string2, "chan =~ /%s/", chan_expr);
        	strcat (string, string2);
	}
	if (string[0]) {
		strcat (string, " )");
		dbsc = dbsubset (dbsc, string, 0);
		new_view = 1;
	}
        dbquery (dbsc, dbRECORD_COUNT, &n);
        if (n < 1) {
		register_error (0, "grtr_sc_create: No data to process.\n");
		if (new_view) dbfree (dbsc);
		return (-1);
        }

	/* Read in data */

	if (tstart == 0.0 && tend == 0.0) {
		dbquery (dbsc, dbRECORD_COUNT, &n);
		for (dbsc.record = 0; dbsc.record < n; dbsc.record++) {
			if (dbgetv (dbsc, 0, "time", &time, "endtime", &endtime, 0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
        		if (tstart == 0.0 && tend == 0.0) {
        			tstart = time;
        			tend = endtime;
			} else {
				if (time < tstart) tstart = time;
				if (endtime > tend) tend = endtime;
			}
		}
	}
        sprintf (time_str, "(%.5f)", tstart);
        sprintf (endtime_str, "(%.5f)", tend);
	dbsc.record = dbALL;
        ret = trload_css (dbsc, time_str, endtime_str, trscgr, "wfdisc", 0);

	/* Split, splice, apply calib */

	if (gap == NULL) strcpy (string, "seg");
	else strcpy (string, gap);
	if (!strcmp(string, "leave")) {
	} else if (!strcmp(string, "seg")) {
		trsplit (*trscgr, 0, 0);
		trsplice (*trscgr, 0.5, 0, 0);
	} else if (!strcmp(string, "interp")) {
		register_error (0, "grtr_sc_create: gap value '%s' not implemented yet.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	} else if (!strcmp(string, "zero")) {
		register_error (0, "grtr_sc_create: gap value '%s' not implemented yet.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	} else if (!strcmp(string, "drop")) {
		trsplit (*trscgr, 0, 0);
		trsplice (*trscgr, 0.5, 0, 0);
		crunch = 0;
		dbquery (*trscgr, dbRECORD_COUNT, &n);
		strcpy (sta2, "");
		strcpy (chan2, "");
		n2 = 0;
		db = *trscgr;
		for (trscgr->record=0; trscgr->record<n; (trscgr->record)++) {
			if (dbgetv (*trscgr, 0, "sta", sta, "chan", chan,
					0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
			if (strcmp(sta, sta2) || strcmp(chan, chan2)) {
				if (n2 > 1) {
        				for (db.record = is; db.record < is+n2; db.record++) {
        					trfree (db);
        					crunch = 1;
        				}
				}
				n2 = 1;
				is = trscgr->record;
				strcpy (sta2, sta);
				strcpy (chan2, chan);
				continue;
        		}
        		n2++;
		}
		if (n2 > 1) {
       			for (db.record = is; db.record < is+n2; db.record++) {
       				trfree (db);
       				crunch = 1;
       			}
		}
		if (crunch) {
			dbcrunch (db);
		}
	} else {
		register_error (0, "grtr_sc_create: Illegal gap value '%s'.\n", string);
		if (new_view) dbfree (dbsc);
		return (-1);
	}
	if (calib) trapply_calib (*trscgr);

	/* Read in instrument responses. */

	if (ir )
	{
	/* Run this section if instrument response is to be loaded */
	    dbsc.record = 0;
	    if (dbgetv (dbsc, 0, "instrument.inid", &i, 0) != dbINVALID && i >= 0) {
		dbquery (*trscgr, dbRECORD_COUNT, &n);
		dbquery (dbsc, dbRECORD_COUNT, &n2);
		for (trscgr->record=0; trscgr->record<n; (trscgr->record)++) {
			if (dbgetv (*trscgr, 0, "sta", sta, "chan", chan,
					"time", &time, 0) == dbINVALID) {
        			register_error (0, "grtr_sc_create: dbgetv() error.\n");
				if (new_view) dbfree (dbsc);
        			return (-1);
			}
			for (dbsc.record=0; dbsc.record<n2; dbsc.record++) {
				if (dbgetv (dbsc, 0, "sta", sta2, "chan", chan2,
					"time", &time2, "endtime", &endtime2, 0) == dbINVALID) {
        				register_error (0, "grtr_sc_create: dbgetv() error.\n");
					if (new_view) dbfree (dbsc);
        				return (-1);
				}
				if (strcmp(sta, sta2)) continue;
				if (strcmp(chan, chan2)) continue;
				if (time < time2) continue;
				if (time >= endtime2) continue;
				dbextfile (dbsc, "instrument", string);
				resp = (Response *) getarr (resp_arr, string);
				dbputv (*trscgr, 0, "response", resp, 0);
				break;
			}
		}
	    }
	}
	clear_register (0);
	if (new_view) dbfree (dbsc);

	/* Normal exit. */

	return (0);
}
Пример #28
0
int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
{
    DWORD bytes_read;
    BOOL res;

    static OVERLAPPED ol;

Check_For_Result:
    if(!dev->blocking && dev->ioPending)
    {
        res = GetOverlappedResult(dev->device_handle, &ol, &bytes_read, FALSE/*don't wait*/);
        if(!res)
        {
            return 0;
        }
        else
        {
            dev->ioPending = false;
            if (bytes_read > 0 && data[0] == 0x0) {
                /* If report numbers aren't being used, but Windows sticks a report
                   number (0x0) on the beginning of the report anyway. To make this
                   work like the other platforms, and to make it work more like the
                   HID spec, we'll skip over this byte. */
                bytes_read--;
                memmove(data, data+1, bytes_read);
            }
            return bytes_read;
        }
    }

    memset(&ol, 0, sizeof(ol));

    // Limit the data to be returned. This ensures we get
    // only one report returned per call to hid_read().
    length = (length < dev->input_report_length)? length: dev->input_report_length;

    res = ReadFile(dev->device_handle, data, length, &bytes_read, &ol);

    if (!res) {
        if (GetLastError() != ERROR_IO_PENDING) {
            // ReadFile() failed. Return error.
            register_error(dev, "ReadFile");
            return -1;
        }
    }

    if(!dev->blocking)
    {
        dev->ioPending = true;
        goto Check_For_Result;
    }
    else
    {
        // Wait here until the write is done. This makes
        // hid_write() synchronous.
        res = GetOverlappedResult(dev->device_handle, &ol, &bytes_read, TRUE/*wait*/);
        if (!res) {
            // The Read operation failed.
            register_error(dev, "ReadFile");
            return -1;
        }
    }

    return bytes_read;
}
Пример #29
0
static void
process_job_status(Job *job, int status)
{
	int reason, code;
	bool	 done;

	debug_printf("Process %ld (%s) exited with status %d.\n",
	    (long)job->pid, job->node->name, status);
	/* parse status */
	if (WIFEXITED(status)) {
		reason = JOB_EXITED;
		code = WEXITSTATUS(status);
	} else if (WIFSIGNALED(status)) {
		reason = JOB_SIGNALED;
		code = WTERMSIG(status);
	} else {
		/* can't happen, set things to be bad. */
		reason = UNKNOWN;
		code = status;
	}

	if ((reason == JOB_EXITED &&
	     code != 0 && !(job->node->type & OP_IGNORE)) ||
	    reason == JOB_SIGNALED) {
		/*
		 * If it exited non-zero and either we're doing things our
		 * way or we're not ignoring errors, the job is finished.
		 * Similarly, if the shell died because of a signal
		 * the job is also finished. In these
		 * cases, finish out the job's output before printing the exit
		 * status...
		 */
		close_job_pipes(job);
		done = true;
	} else if (reason == JOB_EXITED) {
		/*
		 * Deal with ignored errors. We need to print a message telling
		 * of the ignored error as well as setting status.w_status to 0
		 * so the next command gets run. To do this, we set done to be
		 * true and the job exited non-zero.
		 */
		done = code != 0;
		close_job_pipes(job);
	} else {
		/*
		 * No need to close things down or anything.
		 */
		done = false;
	}

	if (done || DEBUG(JOB)) {
		if (reason == JOB_EXITED) {
			debug_printf("Process %ld (%s) exited.\n",
			    (long)job->pid, job->node->name);
			if (code != 0) {
				banner(job, stdout);
				(void)fprintf(stdout, "*** Error code %d %s\n",
				    code,
				    (job->node->type & OP_IGNORE) ?
				    "(ignored)" : "");

				if (job->node->type & OP_IGNORE) {
					reason = JOB_EXITED;
					code = 0;
				}
			} else if (DEBUG(JOB)) {
				(void)fprintf(stdout,
				    "*** %ld (%s) Completed successfully\n",
				    (long)job->pid, job->node->name);
			}
		} else {
			banner(job, stdout);
			(void)fprintf(stdout, "*** Signal %d\n", code);
		}

		(void)fflush(stdout);
	}

	done = true;

	if (done &&
	    aborting != ABORT_ERROR &&
	    aborting != ABORT_INTERRUPT &&
	    reason == JOB_EXITED && code == 0) {
		/* As long as we aren't aborting and the job didn't return a
		 * non-zero status that we shouldn't ignore, we call
		 * Make_Update to update the parents. */
		job->node->built_status = MADE;
		Make_Update(job->node);
	} else if (!(reason == JOB_EXITED && code == 0)) {
		register_error(reason, code, job);
	}
	free(job);

	if (errors && !keepgoing &&
	    aborting != ABORT_INTERRUPT)
		aborting = ABORT_ERROR;

	if (aborting == ABORT_ERROR && Job_Empty())
		Finish(errors);
}
Пример #30
0
int 
qdata2qorbpkt (unsigned char *qdata_pkt, int ndata,
			double timein, double calib, double calper,
			char *netsta, double *time, char *srcname,
			char **packet, int *nbytes, int *bufsize, char *segtype)

{
	int *idata, npts;
	unsigned short level;
	int i, n;
	char *ptr;
	int bsize;
	unsigned char msg_type;
	unsigned char soh_flags;
	unsigned char clock_flags;
	unsigned char *data;
	int nsamp;
	char sampratec;
	float samprate;
	char station[8];
	char channel[8];
	char network[8];
	int year, month, day, doy, hour, minute, isec, millisec, microsec;
	double second;
	unsigned short hdrsiz;
	unsigned short pktsiz;
	short int si;
	unsigned short usi;
	float flt;

	/* grok the quanterra data packet */

	msg_type = qdata_pkt[6];
	switch (msg_type) {
	case 0:
		level = 0;
		break;
	case 1:
		level = 1;
		break;
	case 2:
		level = 2;
		break;
	default:
		register_error (0, "qdata2qorbpkt: Unknown Quanterra message or compression level (%d).\n", 
						msg_type);
		return (-1);
	}
	soh_flags = qdata_pkt[9];
	clock_flags = qdata_pkt[49];
	data = &(qdata_pkt[66]);
	N2H2(&usi, &(qdata_pkt[24]), 1);
	nsamp = usi;
	sampratec = qdata_pkt[26];
	if (nsamp == 0) return (1);
	if (sampratec == 0) return (1);
	if (sampratec > 0) {
		samprate = (float)sampratec;
	} else {
		samprate = 1.0/(float)(-sampratec);
	}
	for (i=0; i<2; i++) if (qdata_pkt[50+i] != ' ' && qdata_pkt[50+i] != '\0') break;
	n = 2-i;
	memcpy (network, &(qdata_pkt[50+i]), n);
	for (i=0; i<n; i++) if (network[i] == ' ' || network[i] == '\0') break;
	network[i] = '\0';
	for (i=0; i<4; i++) if (qdata_pkt[10+i] != ' ' && qdata_pkt[10+i] != '\0') break;
	n = 4-i;
	memcpy (station, &(qdata_pkt[10+i]), n);
	for (i=0; i<n; i++) if (station[i] == ' ' || station[i] == '\0') break;
	station[i] = '\0';
	for (i=0; i<3; i++) if (qdata_pkt[46+i] != ' ' && qdata_pkt[46+i] != '\0') break;
	n = 3-i;
	memcpy (channel, &(qdata_pkt[46+i]), n);
	for (i=0; i<n; i++) if (channel[i] == ' ' || channel[i] == '\0') break;
	channel[i] = '\0';
	sprintf (srcname, "%s_%s/QCDAT", netsta, channel);
	if (timein == 0.0) {
		year = qdata_pkt[28];
		month = qdata_pkt[29];
		day = qdata_pkt[30];
		hour = qdata_pkt[31];
		minute = qdata_pkt[32];
		isec = qdata_pkt[33];
		N2H2(&si, &(qdata_pkt[14]), 1);
		millisec = si;
		N2H2(&si, &(qdata_pkt[56]), 1);
		microsec = si;
		if (year < 50) year += 2000; else year += 1900;
		doy = mday2doy (year, month, day);
		second = (double)isec + 0.001*millisec + 0.000001*microsec;
		*time = h2e (year, doy, hour, minute, second);
	} else {
		*time = timein;
	}

	/* allocate the output packet */

	hdrsiz = 36;
	pktsiz = hdrsiz + ndata;
	*nbytes = pktsiz;
	bsize = *nbytes + 1;
	if (*packet == NULL) {
		*packet = (char *) malloc (bsize);
		if (*packet == NULL) {
			register_error (1, "qdata2qorbpkt: malloc() error.\n");
			return (-1);
		}
		*bufsize = bsize;
	} else if (bsize > *bufsize) {
		*packet = (char *) realloc (*packet, bsize);
		if (*packet == NULL) {
			register_error (1, "qdata2qorbpkt: realloc() error.\n");
			return (-1);
		}
		*bufsize = bsize;
	}

	/* fill the output packet */

	ptr = *packet;
	H2N2 (ptr, &hdrsiz, 1);
	ptr += 2;
	H2N2 (ptr, &pktsiz, 1);
	ptr += 2;
	usi = (unsigned short int)QUANTERRA_DATA_HDR_TYPE2;
	H2N2 (ptr, &usi, 1);
	ptr += 2;
	usi = (unsigned short int)QUANTERRA_DATA_PKT_TYPE2;
	H2N2 (ptr, &usi, 1);
	ptr += 2;
	memcpy (ptr, &soh_flags, 1);
	ptr += 1;
	memcpy (ptr, &clock_flags, 1);
	ptr += 1;
	H2N2 (ptr, &level, 1);
	ptr += 2;
	H2N4 (ptr, &nsamp, 1);
	ptr += 4;
	H2N4 (ptr, &samprate, 1);
	ptr += 4;
	flt = calib;
	H2N4 (ptr, &flt, 1);
	ptr += 4;
	flt = calper;
	H2N4 (ptr, &flt, 1);
	ptr += 4;
	memcpy (ptr, station, 4);
	ptr += 4;
	memcpy (ptr, segtype, 4);
	ptr += 4;
	memcpy (ptr, &(qdata_pkt[66]), ndata);

	/* normal exit */

	return (0);
}