Exemplo n.º 1
0
QVariant JExtractorPlugin::getPersistentVariable(QString key)
{
	return static_cast<JavaExtractor*>(transfer())->getPersistentVariable(key);
}
Exemplo n.º 2
0
static tlog_grc
run(const char *progname, struct json_object *conf)
{
    tlog_grc grc;
    struct json_object *obj;
    int64_t num;
    unsigned int latency;
    unsigned int log_mask;
    const char *shell_path;
    char **shell_argv = NULL;
    const struct timespec delay_min = TLOG_DELAY_MIN_TIMESPEC;
    clockid_t clock_id;
    struct timespec timestamp;
    struct tlog_sink *log_sink = NULL;
    struct tlog_sink *tty_sink = NULL;
    struct tlog_source *tty_source = NULL;
    ssize_t rc;
    int master_fd;
    pid_t child_pid;
    bool term_attrs_set = false;
    struct termios orig_termios;
    struct termios raw_termios;
    struct winsize winsize;

    assert(progname != NULL);

    /* Check for the help flag */
    if (json_object_object_get_ex(conf, "help", &obj)) {
        if (json_object_get_boolean(obj)) {
            tlog_rec_conf_cmd_help(stdout, progname);
            grc = TLOG_RC_OK;
            goto cleanup;
        }
    }

    /* Prepare shell command line */
    grc = get_shell(conf, &shell_path, &shell_argv);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed building shell command line: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /* Read the log latency */
    if (!json_object_object_get_ex(conf, "latency", &obj)) {
        fprintf(stderr, "Log latency is not specified\n");
        grc = TLOG_RC_FAILURE;
        goto cleanup;
    }
    num = json_object_get_int64(obj);
    latency = (unsigned int)num;

    /* Read log mask */
    if (!json_object_object_get_ex(conf, "log", &obj)) {
        fprintf(stderr, "Logged data set parameters are not specified\n");
        grc = TLOG_RC_FAILURE;
        goto cleanup;
    }
    grc = get_log_mask(obj, &log_mask);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed reading log mask: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /* Create the log sink */
    grc = create_log_sink(&log_sink, conf);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed creating log sink: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /*
     * Choose the clock: try to use coarse monotonic clock (which is faster),
     * if it provides the required resolution.
     */
    if (clock_getres(CLOCK_MONOTONIC_COARSE, &timestamp) == 0 &&
        tlog_timespec_cmp(&timestamp, &delay_min) <= 0) {
        clock_id = CLOCK_MONOTONIC_COARSE;
    } else if (clock_getres(CLOCK_MONOTONIC, NULL) == 0) {
        clock_id = CLOCK_MONOTONIC;
    } else {
        fprintf(stderr, "No clock to use\n");
        goto cleanup;
    }

    /* Get terminal attributes */
    rc = tcgetattr(STDOUT_FILENO, &orig_termios);
    if (rc < 0) {
        fprintf(stderr, "Failed retrieving tty attributes: %s\n",
                strerror(errno));
        goto cleanup;
    }

    /* Get terminal window size */
    rc = ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
    if (rc < 0) {
        fprintf(stderr, "Failed retrieving tty window size: %s\n",
                strerror(errno));
        goto cleanup;
    }

    /* Fork a child under a slave pty */
    child_pid = forkpty(&master_fd, NULL, &orig_termios, &winsize);
    if (child_pid < 0) {
        grc = TLOG_GRC_ERRNO;
        fprintf(stderr, "Failed forking a pty: %s\n", tlog_grc_strerror(grc));
        goto cleanup;
    } else if (child_pid == 0) {
        /*
         * Child
         */
        execv(shell_path, shell_argv);
        grc = TLOG_GRC_ERRNO;
        fprintf(stderr, "Failed executing the shell: %s",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /*
     * Parent
     */
    /* Read and output the notice */
    if (json_object_object_get_ex(conf, "notice", &obj)) {
        fprintf(stderr, "%s", json_object_get_string(obj));
    }

    /* Switch the terminal to raw mode */
    raw_termios = orig_termios;
    raw_termios.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO);
    raw_termios.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
                             INPCK | ISTRIP | IXON | PARMRK);
    raw_termios.c_oflag &= ~OPOST;
    raw_termios.c_cc[VMIN] = 1;
    raw_termios.c_cc[VTIME] = 0;
    rc = tcsetattr(STDOUT_FILENO, TCSAFLUSH, &raw_termios);
    if (rc < 0) {
        grc = TLOG_GRC_ERRNO;
        fprintf(stderr, "Failed setting tty attributes: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }
    term_attrs_set = true;

    /* Create the TTY source */
    grc = tlog_tty_source_create(&tty_source, STDIN_FILENO,
                                 master_fd, STDOUT_FILENO,
                                 4096, clock_id);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed creating TTY source: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /* Create the TTY sink */
    grc = tlog_tty_sink_create(&tty_sink, master_fd,
                               STDOUT_FILENO, master_fd);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed creating TTY sink: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    /* Transfer and log the data until interrupted or either end is closed */
    grc = transfer(tty_source, log_sink, tty_sink, latency, log_mask);
    if (grc != TLOG_RC_OK) {
        fprintf(stderr, "Failed transferring TTY data: %s\n",
                tlog_grc_strerror(grc));
        goto cleanup;
    }

    grc = TLOG_RC_OK;

cleanup:

    tlog_sink_destroy(log_sink);
    tlog_sink_destroy(tty_sink);
    tlog_source_destroy(tty_source);

    /* Free shell argv list */
    if (shell_argv != NULL) {
        for (size_t i = 0; shell_argv[i] != NULL; i++) {
            free(shell_argv[i]);
        }
        free(shell_argv);
    }

    /* Restore terminal attributes */
    if (term_attrs_set) {
        rc = tcsetattr(STDOUT_FILENO, TCSAFLUSH, &orig_termios);
        if (rc < 0 && errno != EBADF) {
            fprintf(stderr, "Failed restoring tty attributes: %s\n",
                    strerror(errno));
            return 1;
        }
    }

    return grc;
}
Exemplo n.º 3
0
int
LPS22HB_I2C::read(unsigned address, void *data, unsigned count)
{
	uint8_t cmd = address;
	return transfer(&cmd, 1, (uint8_t *)data, count);
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
    // a global variable defined in errno.h that's "set by system 
    // calls and some library functions [to a nonzero value]
    // in the event of an error to indicate what went wrong"
    errno = 0;

    // default to port 8080
    int port = 8080;

    // usage
    const char* usage = "Usage: server [-p port] /path/to/root";

    // parse command-line arguments
    int opt;
    while ((opt = getopt(argc, argv, "hp:")) != -1)
    {
        switch (opt)
        {
            // -h
            case 'h':
                printf("%s\n", usage);
                return 0;

            // -p port
            case 'p':
                port = atoi(optarg);
                break;
        }
    }

    // ensure port is a non-negative short and path to server's root is specified
    if (port < 0 || port > SHRT_MAX || argv[optind] == NULL || strlen(argv[optind]) == 0)
    {
        // announce usage
        printf("%s\n", usage);

        // return 2 just like bash's builtins
        return 2;
    }

    // start server
    start(port, argv[optind]);

    // listen for SIGINT (aka control-c)
    struct sigaction act;
    act.sa_handler = handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGINT, &act, NULL);

    // a message and its length
    char* message = NULL;
    size_t length = 0;

    // path requested
    char* path = NULL;

    // accept connections one at a time
    while (true)
    {
        // free last path, if any
        if (path != NULL)
        {
            free(path);
            path = NULL;
        }

        // free last message, if any
        if (message != NULL)
        {
            free(message);
            message = NULL;
        }
        length = 0;

        // close last client's socket, if any
        if (cfd != -1)
        {
            close(cfd);
            cfd = -1;
        }

        // check for control-c
        if (signaled)
        {
            stop();
        }

        // check whether client has connected
        if (connected())
        {
            // check for request
            if (request(&message, &length))
            {
                // extract message's request-line
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html
                const char* haystack = message;
                const char* needle = strstr(haystack, "\r\n");
                if (needle == NULL)
                {
                    error(500);
                    continue;
                }
                char line[needle - haystack + 2 + 1];
                strncpy(line, haystack, needle - haystack + 2);
                line[needle - haystack + 2] = '\0';

                // log request-line
                printf("%s", line);

                // parse request-line
                char abs_path[LimitRequestLine + 1];
                char query[LimitRequestLine + 1];
                if (parse(line, abs_path, query))
                {
                    // URL-decode absolute-path
                    char* p = urldecode(abs_path);
                    if (p == NULL)
                    {
                        error(500);
                        continue;
                    }

                    // resolve absolute-path to local path
                    path = malloc(strlen(root) + strlen(p) + 1);
                    if (path == NULL)
                    {
                        error(500);
                        continue;
                    }
                    strcpy(path, root);
                    strcat(path, p);
                    free(p);

                    // ensure path exists
                    if (access(path, F_OK) == -1)
                    {
                        error(404);
                        continue;
                    }

                    // if path to directory
                    struct stat sb;
                    if (stat(path, &sb) == 0 && S_ISDIR(sb.st_mode))
                    {
                        // redirect from absolute-path to absolute-path/
                        if (abs_path[strlen(abs_path) - 1] != '/')
                        {
                            char uri[strlen(abs_path) + 1 + 1];
                            strcpy(uri, abs_path);
                            strcat(uri, "/");
                            redirect(uri);
                            continue;
                        }

                        // use path/index.php or path/index.html, if present, instead of directory's path
                        char* index = indexes(path);
                        if (index != NULL)
                        {
                            free(path);
                            path = index;
                        }

                        // list contents of directory
                        else
                        {
                            list(path);
                            continue;
                        }
                    }

                    // look up MIME type for file at path
                    const char* type = lookup(path);
                    if (type == NULL)
                    {
                        error(501);
                        continue;
                    }

                    // interpret PHP script at path
                    if (strcasecmp("text/x-php", type) == 0)
                    {
                        interpret(path, query);
                    }

                    // transfer file at path
                    else
                    {
                        transfer(path, type);
                    }
                }
            }
        }
    }
}
Exemplo n.º 5
0
int MtpDataPacket::write(struct usb_request *request,
                         UrbPacketDivisionMode divisionMode,
                         int fd,
                         size_t payloadSize) {
    // Obtain the greatest multiple of minimum packet size that is not greater than
    // MTP_BUFFER_SIZE.
    if (request->max_packet_size <= 0) {
        ALOGE("Cannot determine bulk transfer size due to illegal max packet size %d.",
              request->max_packet_size);
        return -1;
    }
    const size_t maxBulkTransferSize =
            MTP_BUFFER_SIZE - (MTP_BUFFER_SIZE % request->max_packet_size);
    const size_t containerLength = payloadSize + MTP_CONTAINER_HEADER_SIZE;
    size_t processedBytes = 0;
    bool readError = false;

    // Bind the packet with given request.
    request->buffer = mBuffer;
    allocate(maxBulkTransferSize);

    while (processedBytes < containerLength) {
        size_t bulkTransferSize = 0;

        // prepare header.
        const bool headerSent = processedBytes != 0;
        if (!headerSent) {
            MtpPacket::putUInt32(MTP_CONTAINER_LENGTH_OFFSET, containerLength);
            MtpPacket::putUInt16(MTP_CONTAINER_TYPE_OFFSET, MTP_CONTAINER_TYPE_DATA);
            bulkTransferSize += MTP_CONTAINER_HEADER_SIZE;
        }

        // Prepare payload.
        if (headerSent || divisionMode == FIRST_PACKET_HAS_PAYLOAD) {
            const size_t processedPayloadBytes =
                    headerSent ? processedBytes - MTP_CONTAINER_HEADER_SIZE : 0;
            const size_t maxRead = payloadSize - processedPayloadBytes;
            const size_t maxWrite = maxBulkTransferSize - bulkTransferSize;
            const size_t bulkTransferPayloadSize = std::min(maxRead, maxWrite);
            // prepare payload.
            if (!readError) {
                const ssize_t result = readExactBytes(
                        fd,
                        mBuffer + bulkTransferSize,
                        bulkTransferPayloadSize);
                if (result < 0) {
                    ALOGE("Found an error while reading data from FD. Send 0 data instead.");
                    readError = true;
                }
            }
            if (readError) {
                memset(mBuffer + bulkTransferSize, 0, bulkTransferPayloadSize);
            }
            bulkTransferSize += bulkTransferPayloadSize;
        }

        // Bulk transfer.
        mPacketSize = bulkTransferSize;
        request->buffer_length = bulkTransferSize;
        const int result = transfer(request);
        if (result != static_cast<ssize_t>(bulkTransferSize)) {
            // Cannot recover writing error.
            ALOGE("Found an error while write data to MtpDevice.");
            return -1;
        }

        // Update variables.
        processedBytes += bulkTransferSize;
    }

    return readError ? -1 : processedBytes;
}
Exemplo n.º 6
0
void List<T, Allocator>::splice(const_iterator pos, List& other, const_iterator first, const_iterator last)  
{  
    if(this == &other)  
        return;   
    transfer(pos, first, last);  
}  
Exemplo n.º 7
0
void
MPU9250::measure()
{
	if (hrt_absolute_time() < _reset_wait) {
		// we're waiting for a reset to complete
		return;
	}

	struct MPUReport mpu_report;

	struct Report {
		int16_t		accel_x;
		int16_t		accel_y;
		int16_t		accel_z;
		int16_t		temp;
		int16_t		gyro_x;
		int16_t		gyro_y;
		int16_t		gyro_z;
	} report;

	/* start measuring */
	perf_begin(_sample_perf);

	/*
	 * Fetch the full set of measurements from the MPU9250 in one pass.
	 */
	mpu_report.cmd = DIR_READ | MPUREG_INT_STATUS;

	// sensor transfer at high clock speed
	set_frequency(MPU9250_HIGH_BUS_SPEED);

	if (OK != transfer((uint8_t *)&mpu_report, ((uint8_t *)&mpu_report), sizeof(mpu_report))) {
		return;
	}

	//check_registers();

	if (check_duplicate(&mpu_report.accel_x[0])) {
		return;
	}

	/* remember the time, to use later */
	uint64_t mpu_time = hrt_absolute_time();

	_mag->measure(mpu_report.mag);

	/*
	 * Convert from big to little endian
	 */
	report.accel_x = int16_t_from_bytes(mpu_report.accel_x);
	report.accel_y = int16_t_from_bytes(mpu_report.accel_y);
	report.accel_z = int16_t_from_bytes(mpu_report.accel_z);
	report.temp    = int16_t_from_bytes(mpu_report.temp);
	report.gyro_x  = int16_t_from_bytes(mpu_report.gyro_x);
	report.gyro_y  = int16_t_from_bytes(mpu_report.gyro_y);
	report.gyro_z  = int16_t_from_bytes(mpu_report.gyro_z);

	if (check_null_data((uint32_t *)&report, sizeof(report) / 4)) {
		return;
	}

	if (_register_wait != 0) {
		// we are waiting for some good transfers before using the sensor again
		// We still increment _good_transfers, but don't return any data yet
		_register_wait--;
		return;
	}

	/*
	 * Swap axes and negate y
	 */
	int16_t accel_xt = report.accel_y;
	int16_t accel_yt = ((report.accel_x == -32768) ? 32767 : -report.accel_x);

	int16_t gyro_xt = report.gyro_y;
	int16_t gyro_yt = ((report.gyro_x == -32768) ? 32767 : -report.gyro_x);

	/*
	 * Apply the swap
	 */
	report.accel_x = accel_xt;
	report.accel_y = accel_yt;
	report.gyro_x = gyro_xt;
	report.gyro_y = gyro_yt;

	/*
	 * Report buffers.
	 */
	accel_report		arb;
	gyro_report		grb;

	/*
	 * Adjust and scale results to m/s^2.
	 */
	//grb.timestamp = arb.timestamp = hrt_absolute_time();
	grb.timestamp = arb.timestamp = mpu_time;

	// report the error count as the sum of the number of bad
	// transfers and bad register reads. This allows the higher
	// level code to decide if it should use this sensor based on
	// whether it has had failures
	grb.error_count = arb.error_count = perf_event_count(_bad_transfers) + perf_event_count(_bad_registers);

	/*
	 * 1) Scale raw value to SI units using scaling from datasheet.
	 * 2) Subtract static offset (in SI units)
	 * 3) Scale the statically calibrated values with a linear
	 *    dynamically obtained factor
	 *
	 * Note: the static sensor offset is the number the sensor outputs
	 * 	 at a nominally 'zero' input. Therefore the offset has to
	 * 	 be subtracted.
	 *
	 *	 Example: A gyro outputs a value of 74 at zero angular rate
	 *	 	  the offset is 74 from the origin and subtracting
	 *		  74 from all measurements centers them around zero.
	 */

	/* NOTE: Axes have been swapped to match the board a few lines above. */

	arb.x_raw = report.accel_x;
	arb.y_raw = report.accel_y;
	arb.z_raw = report.accel_z;

	float xraw_f = report.accel_x;
	float yraw_f = report.accel_y;
	float zraw_f = report.accel_z;

	// apply user specified rotation
	rotate_3f(_rotation, xraw_f, yraw_f, zraw_f);

	float x_in_new = ((xraw_f * _accel_range_scale) - _accel_scale.x_offset) * _accel_scale.x_scale;
	float y_in_new = ((yraw_f * _accel_range_scale) - _accel_scale.y_offset) * _accel_scale.y_scale;
	float z_in_new = ((zraw_f * _accel_range_scale) - _accel_scale.z_offset) * _accel_scale.z_scale;

	arb.x = _accel_filter_x.apply(x_in_new);
	arb.y = _accel_filter_y.apply(y_in_new);
	arb.z = _accel_filter_z.apply(z_in_new);

	math::Vector<3> aval(x_in_new, y_in_new, z_in_new);
	math::Vector<3> aval_integrated;

	bool accel_notify = _accel_int.put(arb.timestamp, aval, aval_integrated, arb.integral_dt);
	arb.x_integral = aval_integrated(0);
	arb.y_integral = aval_integrated(1);
	arb.z_integral = aval_integrated(2);

	arb.scaling = _accel_range_scale;
	arb.range_m_s2 = _accel_range_m_s2;

	_last_temperature = (report.temp) / 361.0f + 35.0f;

	arb.temperature_raw = report.temp;
	arb.temperature = _last_temperature;

	grb.x_raw = report.gyro_x;
	grb.y_raw = report.gyro_y;
	grb.z_raw = report.gyro_z;

	xraw_f = report.gyro_x;
	yraw_f = report.gyro_y;
	zraw_f = report.gyro_z;

	// apply user specified rotation
	rotate_3f(_rotation, xraw_f, yraw_f, zraw_f);

	float x_gyro_in_new = ((xraw_f * _gyro_range_scale) - _gyro_scale.x_offset) * _gyro_scale.x_scale;
	float y_gyro_in_new = ((yraw_f * _gyro_range_scale) - _gyro_scale.y_offset) * _gyro_scale.y_scale;
	float z_gyro_in_new = ((zraw_f * _gyro_range_scale) - _gyro_scale.z_offset) * _gyro_scale.z_scale;

	grb.x = _gyro_filter_x.apply(x_gyro_in_new);
	grb.y = _gyro_filter_y.apply(y_gyro_in_new);
	grb.z = _gyro_filter_z.apply(z_gyro_in_new);

	math::Vector<3> gval(x_gyro_in_new, y_gyro_in_new, z_gyro_in_new);
	math::Vector<3> gval_integrated;

	bool gyro_notify = _gyro_int.put(arb.timestamp, gval, gval_integrated, grb.integral_dt);
	grb.x_integral = gval_integrated(0);
	grb.y_integral = gval_integrated(1);
	grb.z_integral = gval_integrated(2);

	grb.scaling = _gyro_range_scale;
	grb.range_rad_s = _gyro_range_rad_s;

	grb.temperature_raw = report.temp;
	grb.temperature = _last_temperature;

	_accel_reports->force(&arb);
	_gyro_reports->force(&grb);

	/* notify anyone waiting for data */
	if (accel_notify) {
		poll_notify(POLLIN);
	}

	if (gyro_notify) {
		_gyro->parent_poll_notify();
	}

	if (accel_notify && !(_pub_blocked)) {
		/* log the time of this report */
		perf_begin(_controller_latency_perf);
		/* publish it */
		orb_publish(ORB_ID(sensor_accel), _accel_topic, &arb);
	}

	if (gyro_notify && !(_pub_blocked)) {
		/* publish it */
		orb_publish(ORB_ID(sensor_gyro), _gyro->_gyro_topic, &grb);
	}

	/* stop measuring */
	perf_end(_sample_perf);
}
Exemplo n.º 8
0
int
HMC5883::read_reg(uint8_t reg, uint8_t &val)
{
	return transfer(&reg, 1, &val, 1);
}
Exemplo n.º 9
0
int
HMC5883::collect()
{
#pragma pack(push, 1)
	struct { /* status register and data as read back from the device */
		uint8_t		x[2];
		uint8_t		z[2];
		uint8_t		y[2];
	}	hmc_report;
#pragma pack(pop)
	struct {
		int16_t		x, y, z;
	} report;
	int	ret = -EIO;
	uint8_t	cmd;


	perf_begin(_sample_perf);

	/* this should be fairly close to the end of the measurement, so the best approximation of the time */
	_reports[_next_report].timestamp = hrt_absolute_time();

	/*
	 * @note  We could read the status register here, which could tell us that
	 *        we were too early and that the output registers are still being
	 *        written.  In the common case that would just slow us down, and
	 *        we're better off just never being early.
	 */

	/* get measurements from the device */
	cmd = ADDR_DATA_OUT_X_MSB;
	ret = transfer(&cmd, 1, (uint8_t *)&hmc_report, sizeof(hmc_report));

	if (ret != OK) {
		perf_count(_comms_errors);
		debug("data/status read error");
		goto out;
	}

	/* swap the data we just received */
	report.x = (((int16_t)hmc_report.x[0]) << 8) + hmc_report.x[1];
	report.y = (((int16_t)hmc_report.y[0]) << 8) + hmc_report.y[1];
	report.z = (((int16_t)hmc_report.z[0]) << 8) + hmc_report.z[1];

	/*
	 * If any of the values are -4096, there was an internal math error in the sensor.
	 * Generalise this to a simple range check that will also catch some bit errors.
	 */
	if ((abs(report.x) > 2048) ||
	    (abs(report.y) > 2048) ||
	    (abs(report.z) > 2048))
		goto out;

	/*
	 * RAW outputs
	 *
	 * to align the sensor axes with the board, x and y need to be flipped
	 * and y needs to be negated
	 */
	_reports[_next_report].x_raw = report.y;
	_reports[_next_report].y_raw = ((report.x == -32768) ? 32767 : -report.x);
	/* z remains z */
	_reports[_next_report].z_raw = report.z;

	/* scale values for output */

	/*
	 * 1) Scale raw value to SI units using scaling from datasheet.
	 * 2) Subtract static offset (in SI units)
	 * 3) Scale the statically calibrated values with a linear
	 *    dynamically obtained factor
	 *
	 * Note: the static sensor offset is the number the sensor outputs
	 * 	 at a nominally 'zero' input. Therefore the offset has to
	 * 	 be subtracted.
	 *
	 *	 Example: A gyro outputs a value of 74 at zero angular rate
	 *	 	  the offset is 74 from the origin and subtracting
	 *		  74 from all measurements centers them around zero.
	 */

#ifdef PX4_I2C_BUS_ONBOARD
	if (_bus == PX4_I2C_BUS_ONBOARD) {
		/* to align the sensor axes with the board, x and y need to be flipped */
		_reports[_next_report].x = ((report.y * _range_scale) - _scale.x_offset) * _scale.x_scale;
		/* flip axes and negate value for y */
		_reports[_next_report].y = ((((report.x == -32768) ? 32767 : -report.x) * _range_scale) - _scale.y_offset) * _scale.y_scale;
		/* z remains z */
		_reports[_next_report].z = ((report.z * _range_scale) - _scale.z_offset) * _scale.z_scale;
	} else {
#endif
		/* XXX axis assignment of external sensor is yet unknown */
		_reports[_next_report].x = ((report.y * _range_scale) - _scale.x_offset) * _scale.x_scale;
		/* flip axes and negate value for y */
		_reports[_next_report].y = ((((report.x == -32768) ? 32767 : -report.x) * _range_scale) - _scale.y_offset) * _scale.y_scale;
		/* z remains z */
		_reports[_next_report].z = ((report.z * _range_scale) - _scale.z_offset) * _scale.z_scale;
#ifdef PX4_I2C_BUS_ONBOARD
	}
#endif

	/* publish it */
	orb_publish(ORB_ID(sensor_mag), _mag_topic, &_reports[_next_report]);

	/* post a report to the ring - note, not locked */
	INCREMENT(_next_report, _num_reports);

	/* if we are running up against the oldest report, toss it */
	if (_next_report == _oldest_report) {
		perf_count(_buffer_overflows);
		INCREMENT(_oldest_report, _num_reports);
	}

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

out:
	perf_end(_sample_perf);
	return ret;
}
Exemplo n.º 10
0
void AI(void)
{
//Makes appropriate moves for the computer by analysing certain factors
	if(won || lost)
	{
		return;
	}
	working=true;
	turn=0;
	strphase="Defense Phase";
	PrintPhase();
	for(int i=0;i<NCountry;i++)
	{	
		if(all[i].ownership==1 || all[i].nos==1)
			continue;
		int sum=0;
		for(int j=0;j<all[i].non;j++)
		{	if(all[all[i].neigh[j]].ownership==0)
				continue;
			if(getNOppNeighbours(all[i].neigh[j])>all[all[i].neigh[j]].nos+6 )
			{
				multipleAttackAI(all[i].neigh[j]);
				AI();
				return;
			}
			if(all[i].nos>all[all[i].neigh[j]].nos+4 && willBeBlocked(i,all[i].neigh[j])==false)
			{
				attack(i,all[i].neigh[j]);
				//attack if no. of soldiers is more by 4 in the attacker country and comp is not getting blocked
				//after the attack
				if(aimode==false)
				{
					AI();
				}
				return;
			}
			sum+=all[all[i].neigh[j]].nos;
		}
		//sum contains total number of opponent soldiers in the neighbourhood
		if(sum!=0 && (((float)all[i].nos)/sum)>=0.5 )
		{
			for(int j=0;j<all[i].non;j++)
			{	
				if(all[all[i].neigh[j]].ownership==1 && all[i].nos>=all[all[i].neigh[j]].nos && willBeBlocked(i,all[i].neigh[j])==false)
				{
					attack(i,all[i].neigh[j]);
					if(aimode==false)
					{
						AI();
					}
					return;
				}
			}
		}
	}
	
	refresh();
	strphase="Reinforcement Phase";
	PrintPhase();
	int reinf=reinforcement(0);
//	refresh2();
	aireinforce(reinf);
	
	refresh2();
	usleep(100000);
	//transfers
	int co,ci;
	// country pair with maximum sum of no. of opponent soldiers as neighbours of ci -(minus) that for co
	if(getMaxNCountry(co,ci,1) && co>=0 && co<=42 && ci>=0 && ci<=42 && all[co].nos>1)
	{
	// get country pair with maximum (sum of no. of opponent soldiers as neighbours of ci -(minus) that for co)
	// and transfer maximum possible sodiers from co to ci 
		PrintLeft("Transferring soldiers from " + all[co].name+ " to " + all[ci].name);
		highlight(co);
		flush();
		usleep(300000);
		highlight(ci);
		flush();
		usleep(300000);
		createTriangle(Red,co,ci);
		flush();
		sleep(1);
		transfer(co,ci,all[co].nos-1);
		refresh();
	} 
	working=false;
	turn=1;
	focus=1;
	c1=-1;c2=-1;
	strphase="Attack Phase";
	PrintLeft("Computer's turn is over. Your chance...  ");
	//being ready for player 1's attack phase
	showmsg.msg="Computer's Reinforcement Phase is over. ^ It's Your turn...^ Attack Phase Begins ";
	PrintRein();
	showmsg.show();
	PrintPhase();
	return;
}
Exemplo n.º 11
0
int
PX4FLOW::collect()
{
	int ret = -EIO;

	/* read from the sensor */
	uint8_t val[I2C_FRAME_SIZE + I2C_INTEGRAL_FRAME_SIZE] = { 0 };

	perf_begin(_sample_perf);

	if (PX4FLOW_REG == 0x00) {
		ret = transfer(nullptr, 0, &val[0], I2C_FRAME_SIZE + I2C_INTEGRAL_FRAME_SIZE);
	}

	if (PX4FLOW_REG == 0x16) {
		ret = transfer(nullptr, 0, &val[0], I2C_INTEGRAL_FRAME_SIZE);
	}

	if (ret < 0) {
		DEVICE_DEBUG("error reading from sensor: %d", ret);
		perf_count(_comms_errors);
		perf_end(_sample_perf);
		return ret;
	}

	if (PX4FLOW_REG == 0) {
		memcpy(&f, val, I2C_FRAME_SIZE);
		memcpy(&f_integral, &(val[I2C_FRAME_SIZE]), I2C_INTEGRAL_FRAME_SIZE);
	}

	if (PX4FLOW_REG == 0x16) {
		memcpy(&f_integral, val, I2C_INTEGRAL_FRAME_SIZE);
	}


	struct optical_flow_s report;

	report.timestamp = hrt_absolute_time();

	report.pixel_flow_x_integral = static_cast<float>(f_integral.pixel_flow_x_integral) / 10000.0f;//convert to radians

	report.pixel_flow_y_integral = static_cast<float>(f_integral.pixel_flow_y_integral) / 10000.0f;//convert to radians

	report.frame_count_since_last_readout = f_integral.frame_count_since_last_readout;

	report.ground_distance_m = static_cast<float>(f_integral.ground_distance) / 1000.0f;//convert to meters

	report.quality = f_integral.qual; //0:bad ; 255 max quality

	report.gyro_x_rate_integral = static_cast<float>(f_integral.gyro_x_rate_integral) / 10000.0f; //convert to radians

	report.gyro_y_rate_integral = static_cast<float>(f_integral.gyro_y_rate_integral) / 10000.0f; //convert to radians

	report.gyro_z_rate_integral = static_cast<float>(f_integral.gyro_z_rate_integral) / 10000.0f; //convert to radians

	report.integration_timespan = f_integral.integration_timespan; //microseconds

	report.time_since_last_sonar_update = f_integral.sonar_timestamp;//microseconds

	report.gyro_temperature = f_integral.gyro_temperature;//Temperature * 100 in centi-degrees Celsius

	report.sensor_id = 0;

	/* rotate measurements according to parameter */
	float zeroval = 0.0f;

	rotate_3f(_sensor_rotation, report.pixel_flow_x_integral, report.pixel_flow_y_integral, zeroval);

	rotate_3f(_sensor_rotation, report.gyro_x_rate_integral, report.gyro_y_rate_integral, report.gyro_z_rate_integral);

	if (_px4flow_topic == nullptr) {
		_px4flow_topic = orb_advertise(ORB_ID(optical_flow), &report);

	} else {
		/* publish it */
		orb_publish(ORB_ID(optical_flow), _px4flow_topic, &report);
	}

	/* publish to the distance_sensor topic as well */
	struct distance_sensor_s distance_report;
	distance_report.timestamp = report.timestamp;
	distance_report.min_distance = PX4FLOW_MIN_DISTANCE;
	distance_report.max_distance = PX4FLOW_MAX_DISTANCE;
	distance_report.current_distance = report.ground_distance_m;
	distance_report.covariance = 0.0f;
	distance_report.type = distance_sensor_s::MAV_DISTANCE_SENSOR_ULTRASOUND;
	/* TODO: the ID needs to be properly set */
	distance_report.id = 0;
	distance_report.orientation = 8;

	orb_publish(ORB_ID(distance_sensor), _distance_sensor_topic, &distance_report);

	/* post a report to the ring */
	if (_reports->force(&report)) {
		perf_count(_buffer_overflows);
	}

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

	perf_end(_sample_perf);
	return ret;
}
Exemplo n.º 12
0
void
L3GD20::measure()
{
	/* status register and data as read back from the device */
#pragma pack(push, 1)
	struct {
		uint8_t		cmd;
		uint8_t		temp;
		uint8_t		status;
		int16_t		x;
		int16_t		y;
		int16_t		z;
	} raw_report;
#pragma pack(pop)

	gyro_report		*report = &_reports[_next_report];

	/* start the performance counter */
	perf_begin(_sample_perf);

	/* fetch data from the sensor */
	raw_report.cmd = ADDR_OUT_TEMP | DIR_READ | ADDR_INCREMENT;
	transfer((uint8_t *)&raw_report, (uint8_t *)&raw_report, sizeof(raw_report));

	/*
	 * 1) Scale raw value to SI units using scaling from datasheet.
	 * 2) Subtract static offset (in SI units)
	 * 3) Scale the statically calibrated values with a linear
	 *    dynamically obtained factor
	 *
	 * Note: the static sensor offset is the number the sensor outputs
	 * 	 at a nominally 'zero' input. Therefore the offset has to
	 * 	 be subtracted.
	 *
	 *	 Example: A gyro outputs a value of 74 at zero angular rate
	 *	 	  the offset is 74 from the origin and subtracting
	 *		  74 from all measurements centers them around zero.
	 */
	report->timestamp = hrt_absolute_time();
	
	/* swap x and y and negate y */
	report->x_raw = raw_report.y;
	report->y_raw = ((raw_report.x == -32768) ? 32767 : -raw_report.x);
	report->z_raw = raw_report.z;

	report->x = ((report->x_raw * _gyro_range_scale) - _gyro_scale.x_offset) * _gyro_scale.x_scale;
	report->y = ((report->y_raw * _gyro_range_scale) - _gyro_scale.y_offset) * _gyro_scale.y_scale;
	report->z = ((report->z_raw * _gyro_range_scale) - _gyro_scale.z_offset) * _gyro_scale.z_scale;
	report->scaling = _gyro_range_scale;
	report->range_rad_s = _gyro_range_rad_s;

	/* post a report to the ring - note, not locked */
	INCREMENT(_next_report, _num_reports);

	/* if we are running up against the oldest report, fix it */
	if (_next_report == _oldest_report)
		INCREMENT(_oldest_report, _num_reports);

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	/* publish for subscribers */
	if (_gyro_topic > 0)
		orb_publish(ORB_ID(sensor_gyro), _gyro_topic, report);

	/* stop the perf counter */
	perf_end(_sample_perf);
}
Exemplo n.º 13
0
int
MEASAirspeed::collect()
{
	int	ret = -EIO;

	/* read from the sensor */
	uint8_t val[4] = {0, 0, 0, 0};


	perf_begin(_sample_perf);

	ret = transfer(nullptr, 0, &val[0], 4);

	if (ret < 0) {
		perf_count(_comms_errors);
		perf_end(_sample_perf);
		return ret;
	}

	uint8_t status = (val[0] & 0xC0) >> 6;

	switch (status) {
	case 0:
		// Normal Operation. Good Data Packet
		break;

	case 1:
		// Reserved
		return -EAGAIN;

	case 2:
		// Stale Data. Data has been fetched since last measurement cycle.
		return -EAGAIN;

	case 3:
		// Fault Detected
		perf_count(_comms_errors);
		perf_end(_sample_perf);
		return -EAGAIN;
	}

	int16_t dp_raw = 0, dT_raw = 0;
	dp_raw = (val[0] << 8) + val[1];
	/* mask the used bits */
	dp_raw = 0x3FFF & dp_raw;
	dT_raw = (val[2] << 8) + val[3];
	dT_raw = (0xFFE0 & dT_raw) >> 5;

	// dT max is almost certainly an invalid reading
	if (dT_raw == 2047) {
		perf_count(_comms_errors);
		return -EAGAIN;
	}

	float temperature = ((200.0f * dT_raw) / 2047) - 50;

	// Calculate differential pressure. As its centered around 8000
	// and can go positive or negative
	const float P_min = -1.0f;
	const float P_max = 1.0f;
	const float PSI_to_Pa = 6894.757f;
	/*
	  this equation is an inversion of the equation in the
	  pressure transfer function figure on page 4 of the datasheet

	  We negate the result so that positive differential pressures
	  are generated when the bottom port is used as the static
	  port on the pitot and top port is used as the dynamic port
	 */
	float diff_press_PSI = -((dp_raw - 0.1f * 16383) * (P_max - P_min) / (0.8f * 16383) + P_min);
	float diff_press_pa_raw = diff_press_PSI * PSI_to_Pa;

	// correct for 5V rail voltage if possible
	voltage_correction(diff_press_pa_raw, temperature);

	/*
	  With the above calculation the MS4525 sensor will produce a
	  positive number when the top port is used as a dynamic port
	  and bottom port is used as the static port
	 */

	struct differential_pressure_s report;

	report.timestamp = hrt_absolute_time();
	report.error_count = perf_event_count(_comms_errors);
	report.temperature = temperature;
	report.differential_pressure_filtered_pa =  _filter.apply(diff_press_pa_raw) - _diff_pres_offset;
	report.differential_pressure_raw_pa = diff_press_pa_raw - _diff_pres_offset;
	report.device_id = _device_id.devid;

	if (_airspeed_pub != nullptr && !(_pub_blocked)) {
		/* publish it */
		orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);
	}

	ret = OK;

	perf_end(_sample_perf);

	return ret;
}
Exemplo n.º 14
0
    void handleUpdates() {
        for (conn* c : connections_to_handle) {
            c->need_be_handled = false;

            try {
                if (c->errorOccurred) {
                    destroyConnection(*c);
                    continue;
                }

                if (c->socketRemoteClosed) {
                    // Send all read data to pty

                    if (c->pipeClosed) {
                        destroyConnection(*c);
                        continue;
                    }

                    if (!c->socketCloseHandled) {
                        c->socketCloseHandled = true;

                        // Ignore pty IN
                        group.modifyRegistration(c->pty.getMasterFd(), EPOLLOUT, const_cast<epoll_tag*>(&c->tagPipe));
                    }

                    if (transferLeft(c->receiveBuffer, c->socket, c->pty)) {
                        destroyConnection(*c);
                    }

                } else if (c->pipeClosed) {
                    // Send all unsent data

                    if (!c->pipeCloseHandled) {
                        c->pipeCloseHandled = true;

                        // Don't receive HUP again
                        group.removeRegistration(c->pty.getMasterFd());

                        // Ignore socket IN
                        group.modifyRegistration(c->socket.getFd(), EPOLLOUT | EPOLLRDHUP, const_cast<epoll_tag*>(&c->tagSocket));
                    }

                    if(transferLeft(c->sendBuffer, c->pty, c->socket)) {
                        destroyConnection(*c);
                    }

                    continue;
                } else {
                    if (c->socketReadReady) {
                        // Network -> Receive buffer
                        c->socketReadReady = false;

                        transfer(c->socket, c->receiveBuffer);
                    }

                    if (c->pipeReadReady) {
                        // Pipe -> Send buffer
                        c->pipeReadReady = false;

                        transfer(c->pty, c->sendBuffer);
                    }

                    if (c->pipeWriteReady) {
                        // Receive buffer -> Pipe
                        c->pipeWriteReady = false;

                        transfer(c->receiveBuffer, c->pty);
                    }

                    if (c->socketWriteReady) {
                        // Send buffer -> Network
                        c->socketWriteReady = false;

                        transfer(c->sendBuffer, c->socket);
                    }

                    uint32_t ptyEvents =
                            (!c->sendBuffer.isFull() ? EPOLLIN : 0u) | (!c->receiveBuffer.isEmpty() ? EPOLLOUT : 0u);
                    uint32_t socketEvents =
                            (!c->sendBuffer.isEmpty() ? EPOLLOUT : 0u) | (!c->receiveBuffer.isFull() ? EPOLLIN : 0u) |
                            EPOLLRDHUP;

                    group.modifyRegistration(c->socket.getFd(), socketEvents, const_cast<epoll_tag *>(&c->tagSocket));
                    group.modifyRegistration(c->pty.getMasterFd(), ptyEvents, const_cast<epoll_tag *>(&c->tagPipe));

                    if (c->socketRemoteClosed || c->pipeClosed) {
                        destroyConnection(*c);
                        continue;
                    }
                }
            } catch (const errno_exception& ex) {
                fprintf(stdout, "Error while handling updates, %s: %s\n", ex.description.data(), strerror(ex.err));
                destroyConnection(*c);
            }
        }
    }
Exemplo n.º 15
0
int main (int argc, char *argv[])
{

	int ret, i;
	pthread_t recv_thread;
	struct timeval tv;
	int nSendBufLen = 256*1024;

	if (signal(SIGPIPE, sig_pipe) == SIG_ERR)
	{
		fprintf(stderr, "can't catch SIGPIPE\n");
		exit(1);
	}
	/*	if (signal(SIGQUIT, sig_quit) == SIG_ERR)
	{
		fprintf(stderr, "can't catch SIGQUIT\n");
		exit(1);
	}
	 */
	pthread_mutex_init(&dac_lock, NULL);
	pthread_mutex_init(&adc_lock, NULL);
	pthread_mutex_init(&lock, NULL);

	/**
	 * Memory Mapping
	 */
	adc_mem_addr = map_memory(S2MM_DST_ADDR, S2MM_BUF_SIZE);
	memset(adc_mem_addr, 0x0, S2MM_BUF_SIZE);
	dac_mem_addr = map_memory(MM2S_SRC_ADDR, MM2S_BUF_SIZE);
	memset(dac_mem_addr, 0,  MM2S_BUF_SIZE);

	dma_reg_addr_wr = map_memory(AXI_DMA_BASE_WR, REG_SIZE);
	dma_reg_addr_rd = map_memory(AXI_DMA_BASE_RD, REG_SIZE);

	/*snowleo lms6002 clock set*/
	snowleo_sdr_set_clock(I2C_DEV);
	/*snowleo lms6002 spi init*/
	spi_fd = snowleo_sdr_spi_init(SPI_DEV);
	transfer(spi_fd);

	/**
	 * Simple ring buffer
	 */
	p = (struct ring_buf *)malloc(sizeof(struct ring_buf));
	p->front=p->rear=0;
	for(i = 0; i < MaxSize; i++)
		p->data[i] = dac_mem_addr + (i * BUFFER_MAX_SIZE);

	/**
	 * Tcp server
	 * TODO Support two client connections, one to do the receiving, one to do transmitting
	 */
	if((listenfd = socket(PF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("fail to socket!");
		exit(-1);
	}

	bzero(&myaddr, sizeof(myaddr));
	myaddr.sin_family = PF_INET;
	myaddr.sin_port = htons(8000);
	myaddr.sin_addr.s_addr = htons(INADDR_ANY);

	if(bind(listenfd, (SA *)&myaddr, sizeof(myaddr)) < 0)
	{
		perror("fail to bind!");
		exit(-1);
	}

	listen(listenfd, 1);

	while(1)
	{
		if((connfd = accept(listenfd, (SA *)&peeraddr, &peerlen)) < 0)
		{
			perror("fail to accept!");
			exit(-1);
		}
#if 1
		tv.tv_sec = 10;
		tv.tv_usec = 0;
#define  RECV_TIMEOUT
#ifdef  RECV_TIMEOUT
		setsockopt(connfd, SOL_SOCKET, SO_RCVTIMEO|SO_SNDTIMEO, &tv, sizeof(tv));
#else
		setsockopt(connfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
#endif
		setsockopt(connfd, SOL_SOCKET, SO_SNDBUF, (const char *)&nSendBufLen, sizeof(int) );
#endif
		dma_dbg(MSG_DEBUG,"Connection from [%s:%d]\n", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
		//sprintf(file_name, "/mnt/%d.dat", ntohs(peeraddr.sin_port));
		ret = pthread_create(&recv_thread, NULL, &thread_recv_func, NULL);
		if (ret)
		{
			dma_dbg(MSG_ERROR,"ERROR; return code from pthread_create() is %d\n", ret);
			return -1;
		}

		pthread_join(recv_thread,NULL);
		memset((unsigned char *)cmd_buff, 0, sizeof(unsigned int)*2);

		dma_dbg(MSG_DEBUG,"Connection from [%s:%d] is closed\n", inet_ntoa(peeraddr.sin_addr), ntohs(peeraddr.sin_port));
		close(connfd);
	}

	return 0;
}
Exemplo n.º 16
0
void
BMI055_accel::measure()
{
	uint8_t index = 0, accel_data[7];
	uint16_t lsb, msb, msblsb;
	uint8_t status_x, status_y, status_z;

	if (hrt_absolute_time() < _reset_wait) {
		// we're waiting for a reset to complete
		return;
	}

	struct Report {
		int16_t     accel_x;
		int16_t     accel_y;
		int16_t     accel_z;
		int16_t     temp;
	} report;

	/* start measuring */
	perf_begin(_sample_perf);

	/*
	 * Fetch the full set of measurements from the BMI055 in one pass.
	 */
	accel_data[index] = BMI055_ACC_X_L | DIR_READ;

	if (OK != transfer(accel_data, accel_data, sizeof(accel_data))) {
		return;
	}

	check_registers();

	/* Extracting accel data from the read data */
	index = 1;
	lsb = (uint16_t)accel_data[index++];
	status_x = (lsb & BMI055_NEW_DATA_MASK);
	msb = (uint16_t)accel_data[index++];
	msblsb = (msb << 8) | lsb;
	report.accel_x = ((int16_t)msblsb >> 4); /* Data in X axis */

	lsb = (uint16_t)accel_data[index++];
	status_y = (lsb & BMI055_NEW_DATA_MASK);
	msb = (uint16_t)accel_data[index++];
	msblsb = (msb << 8) | lsb;
	report.accel_y = ((int16_t)msblsb >> 4); /* Data in Y axis */

	lsb = (uint16_t)accel_data[index++];
	status_z = (lsb & BMI055_NEW_DATA_MASK);
	msb = (uint16_t)accel_data[index++];
	msblsb = (msb << 8) | lsb;
	report.accel_z = ((int16_t)msblsb >> 4); /* Data in Z axis */

	// Checking the status of new data
	if ((!status_x) || (!status_y) || (!status_z)) {
		perf_end(_sample_perf);
		perf_count(_duplicates);
		_got_duplicate = true;
		return;
	}


	_got_duplicate = false;

	uint8_t temp = read_reg(BMI055_ACC_TEMP);
	report.temp = temp;

	if (report.accel_x == 0 &&
	    report.accel_y == 0 &&
	    report.accel_z == 0 &&
	    report.temp == 0) {
		// all zero data - probably a SPI bus error
		perf_count(_bad_transfers);
		perf_end(_sample_perf);
		// note that we don't call reset() here as a reset()
		// costs 20ms with interrupts disabled. That means if
		// the bmi055 accel does go bad it would cause a FMU failure,
		// regardless of whether another sensor is available,
		return;
	}


	perf_count(_good_transfers);

	if (_register_wait != 0) {
		// we are waiting for some good transfers before using
		// the sensor again. We still increment
		// _good_transfers, but don't return any data yet
		_register_wait--;
		return;
	}

	/*
	 * Report buffers.
	 */
	accel_report        arb;


	arb.timestamp = hrt_absolute_time();


	// report the error count as the sum of the number of bad
	// transfers and bad register reads. This allows the higher
	// level code to decide if it should use this sensor based on
	// whether it has had failures
	arb.error_count = perf_event_count(_bad_transfers) + perf_event_count(_bad_registers);

	/*
	 * 1) Scale raw value to SI units using scaling from datasheet.
	 * 2) Subtract static offset (in SI units)
	 * 3) Scale the statically calibrated values with a linear
	 *    dynamically obtained factor
	 *
	 * Note: the static sensor offset is the number the sensor outputs
	 *   at a nominally 'zero' input. Therefore the offset has to
	 *   be subtracted.
	 *
	 */

	arb.x_raw = report.accel_x;
	arb.y_raw = report.accel_y;
	arb.z_raw = report.accel_z;

	float xraw_f = report.accel_x;
	float yraw_f = report.accel_y;
	float zraw_f = report.accel_z;

	// apply user specified rotation
	rotate_3f(_rotation, xraw_f, yraw_f, zraw_f);

	float x_in_new = ((xraw_f * _accel_range_scale) - _accel_scale.x_offset) * _accel_scale.x_scale;
	float y_in_new = ((yraw_f * _accel_range_scale) - _accel_scale.y_offset) * _accel_scale.y_scale;
	float z_in_new = ((zraw_f * _accel_range_scale) - _accel_scale.z_offset) * _accel_scale.z_scale;

	arb.x = _accel_filter_x.apply(x_in_new);
	arb.y = _accel_filter_y.apply(y_in_new);
	arb.z = _accel_filter_z.apply(z_in_new);

	math::Vector<3> aval(x_in_new, y_in_new, z_in_new);
	math::Vector<3> aval_integrated;

	bool accel_notify = _accel_int.put(arb.timestamp, aval, aval_integrated, arb.integral_dt);
	arb.x_integral = aval_integrated(0);
	arb.y_integral = aval_integrated(1);
	arb.z_integral = aval_integrated(2);

	arb.scaling = _accel_range_scale;
	arb.range_m_s2 = _accel_range_m_s2;

	_last_temperature = 23 + report.temp * 1.0f / 512.0f;

	arb.temperature_raw = report.temp;
	arb.temperature = _last_temperature;
	arb.device_id = _device_id.devid;

	_accel_reports->force(&arb);

	/* notify anyone waiting for data */
	if (accel_notify) {
		poll_notify(POLLIN);
	}

	if (accel_notify && !(_pub_blocked)) {
		/* log the time of this report */
		perf_begin(_controller_latency_perf);
		/* publish it */
		orb_publish(ORB_ID(sensor_accel), _accel_topic, &arb);
	}

	/* stop measuring */
	perf_end(_sample_perf);
}
Exemplo n.º 17
0
void List<T, Allocator>::splice(const_iterator pos, List& other)  
{  
    if(this == &other)  
        return;  
    transfer(pos, other.begin(), other.end());  
}  
 static void write(uint8_t b) { transfer(b); }
Exemplo n.º 19
0
int main(int argc, char * argv[])
{

        int sendsock, recvsock, ret;
        unsigned int val;       
        struct sockaddr_in addr;
        struct sock_fprog fprog;
        struct sock_filter filters[5];

        if (argc != 2) {
                printf("[*] Usage: %s offset (0-63)\n", argv[0]);
                return -1;
        }

        val = atoi(argv[1]);

        if (val > 63) {
                printf("[*] Invalid byte offset (must be 0-63)\n");
                return -1;
        }

        recvsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
        sendsock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

        if (recvsock < 0 || sendsock < 0) {
                printf("[*] Could not create sockets.\n");
                return -1;
        }

        memset(&addr, 0, sizeof(addr));
        addr.sin_family = AF_INET;
        addr.sin_port = htons(PORT);
        addr.sin_addr.s_addr = htonl(INADDR_ANY);

        if (bind(recvsock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
                printf("[*] Could not bind socket.\n");
                return -1;
        }

        memset(&fprog, 0, sizeof(fprog));
        memset(filters, 0, sizeof(filters));

        filters[0].code = BPF_LD|BPF_MEM;
        filters[0].k = (val & ~0x3) / 4;

        filters[1].code = BPF_ALU|BPF_AND|BPF_K;
        filters[1].k = 0xff << ((val % 4) * 8);

        filters[2].code = BPF_ALU|BPF_RSH|BPF_K;
        filters[2].k = (val % 4) * 8;

        filters[3].code = BPF_ALU|BPF_ADD|BPF_K;
        filters[3].k = 256;

        filters[4].code = BPF_RET|BPF_A;

        fprog.len = 5;
        fprog.filter = filters;

        if (setsockopt(recvsock, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog)) < 0) {
                printf("[*] Failed to install filter.\n");
                return -1;
        }

        ret = transfer(sendsock, recvsock);

        printf("[*] Your byte: 0x%.02x\n", ret - 248);

}
Exemplo n.º 20
0
int
AK8963_I2C::read(unsigned reg_speed, void *data, unsigned count)
{
	uint8_t cmd = MPU9250_REG(reg_speed);
	return transfer(&cmd, 1, (uint8_t *)data, count);
}
Exemplo n.º 21
0
Arquivo: gs0.c Projeto: YHUCD/NEKCEM
gs_data *gs_data_setup(uint n, const ulong *label,
                       uint maxv, crystal_data *crystal)
{
  gs_data *data=tmalloc(gs_data,1);
  tuple_list nonzero, primary;
  const int nz_index=0, nz_size=1, nz_label=0;
  const int pr_nzindex=0, pr_index=1, pr_count=2, pr_size=3, pr_label=0;
#ifdef MPI
  tuple_list shared;
  const int pr_proc=0;
  const int sh_dproc=0, sh_proc2=1, sh_index=2, sh_size=3, sh_label=0;
#else
  buffer buf;
#endif
#ifdef MPI
  MPI_Comm_dup(crystal->comm,&data->comm);
#else
  buffer_init(&buf,1024);
#endif

  /* construct list of nonzeros: (index ^, label) */
  tuple_list_init_max(&nonzero,nz_size,1,0,n);
  {
    uint i; sint *nzi = nonzero.vi; slong *nzl = nonzero.vl;
    for(i=0;i<n;++i)
      if(label[i]!=0) 
        nzi[nz_index]=i,
        nzl[nz_label]=label[i],
        nzi+=nz_size, ++nzl, nonzero.n++;
  }

  /* sort nonzeros by label: (index ^2, label ^1) */
#ifndef MPI
  tuple_list_sort(&nonzero,nz_size+nz_label,&buf);
#else
  tuple_list_sort(&nonzero,nz_size+nz_label,&crystal->all->buf);
#endif

  /* build list of unique labels w/ lowest associated index:
     (index in nonzero ^, primary (lowest) index in label, count, label) */
  tuple_list_init_max(&primary,pr_size,1,0,nonzero.n);
  {
    uint i;
    sint  *nzi=nonzero.vi, *pi=primary.vi;
    slong *nzl=nonzero.vl, *pl=primary.vl;
    sint last=-1;
    for(i=0;i<nonzero.n;++i,nzi+=nz_size,++nzl) {
      if(nzl[nz_label]==last) {
        ++pi[-pr_size+pr_count];
        continue;
      }
      last=nzl[nz_label];
      pi[pr_nzindex]=i;
      pi[pr_index]=nzi[nz_index];
      pl[pr_label]=nzl[nz_label];
      pi[pr_count]=1;
      pi+=pr_size, ++pl; primary.n++;
    }
  }

  /* calculate size of local condense map */
  {
    uint i, count=1; sint *pi=primary.vi;
    for(i=primary.n;i;--i,pi+=pr_size)
      if(pi[pr_count]>1) count+=pi[pr_count]+1;
    data->local_cm = tmalloc(sint,count);
  }

  /* sort unique labels by primary index:
     (nonzero index ^2, primary index ^1, count, label ^2) */
#ifndef MPI
  tuple_list_sort(&primary,pr_index,&buf);
  buffer_free(&buf);
#else
  tuple_list_sort(&primary,pr_index,&crystal->all->buf);
#endif
  
  /* construct local condense map */
  {
    uint i, n; sint *pi=primary.vi;
    sint *cm = data->local_cm;
    for(i=primary.n;i;--i,pi+=pr_size) if((n=pi[pr_count])>1) {
      uint j; sint *nzi=nonzero.vi+nz_size*pi[pr_nzindex];
      for(j=n;j;--j,nzi+=nz_size) *cm++ = nzi[nz_index];
      *cm++ = -1;
    }
    *cm++ = -1;
  }
  tuple_list_free(&nonzero);
  
#ifndef MPI
  tuple_list_free(&primary);
#else
  /* assign work proc by label modulo np */
  {
    uint i; sint *pi=primary.vi; slong *pl=primary.vl;
    for(i=primary.n;i;--i,pi+=pr_size,++pl)
      pi[pr_proc]=pl[pr_label]%crystal->num;
  }
  transfer(1,&primary,pr_proc,crystal); /* transfer to work procs */
  /* primary: (source proc, index on src, useless, label) */
  /* sort by label */
  tuple_list_sort(&primary,pr_size+pr_label,&crystal->all->buf);
  /* add sentinel to primary list */
  if(primary.n==primary.max) tuple_list_grow(&primary);
  primary.vl[primary.n] = -1;
  /* construct shared list: (proc1, proc2, index1, label) */
  tuple_list_init_max(&shared,sh_size,1,0,primary.n);
  {
    sint *pi1=primary.vi, *si=shared.vi;
    slong lbl, *pl1=primary.vl, *sl=shared.vl;
    for(;(lbl=pl1[pr_label])!=-1;pi1+=pr_size,++pl1) {
      sint *pi2=pi1+pr_size; slong *pl2=pl1+1;
      for(;pl2[pr_label]==lbl;pi2+=pr_size,++pl2) {
        if(shared.n+2>shared.max)
          tuple_list_grow(&shared),
          si=shared.vi+shared.n*sh_size, sl=shared.vl+shared.n;
        si[sh_dproc] = pi1[pr_proc];
        si[sh_proc2] = pi2[pr_proc];
        si[sh_index] = pi1[pr_index];
        sl[sh_label] = lbl;
        si+=sh_size, ++sl, shared.n++;
        si[sh_dproc] = pi2[pr_proc];
        si[sh_proc2] = pi1[pr_proc];
        si[sh_index] = pi2[pr_index];
        sl[sh_label] = lbl;
        si+=sh_size, ++sl, shared.n++;
      }
    }
  }
  tuple_list_free(&primary);
  transfer(1,&shared,sh_dproc,crystal); /* transfer to dest procs */
  /* shared list: (useless, proc2, index, label) */
  /* sort by label */
  tuple_list_sort(&shared,sh_size+sh_label,&crystal->all->buf);
  /* sort by partner proc */
  tuple_list_sort(&shared,sh_proc2,&crystal->all->buf);
  /* count partner procs */
  {
    uint i, count=0; sint proc=-1,*si=shared.vi;
    for(i=shared.n;i;--i,si+=sh_size)
      if(si[sh_proc2]!=proc) ++count, proc=si[sh_proc2];
    data->nlinfo = nlinfo_alloc(count,shared.n,maxv);
    { int i; MPI_Comm_rank(data->comm,&i); data->nlinfo->id=i; }
  }
  /* construct non-local info */
  {
    uint i; sint proc=-1,*si=shared.vi;
    uint *target  = data->nlinfo->target;
    uint *nshared = data->nlinfo->nshared;
    uint *sh_ind  = data->nlinfo->sh_ind;
    for(i=shared.n;i;--i,si+=sh_size) {
      if(si[sh_proc2]!=proc)
        proc=si[sh_proc2], *target++ = proc, *nshared++ = 0;
      ++nshared[-1], *sh_ind++=si[sh_index];
    }
  }
  tuple_list_free(&shared);
#endif
  return data;
}
Exemplo n.º 22
0
int
MEASAirspeed::collect()
{
	int	ret = -EIO;

	/* read from the sensor */
	uint8_t val[4] = {0, 0, 0, 0};


	perf_begin(_sample_perf);

	ret = transfer(nullptr, 0, &val[0], 4);

	if (ret < 0) {
		log("error reading from sensor: %d", ret);
		return ret;
	}

	uint8_t status = val[0] & 0xC0;

	if (status == 2) {
		log("err: stale data");

	} else if (status == 3) {
		log("err: fault");
	}

	//uint16_t diff_pres_pa = (val[1]) | ((val[0] & ~(0xC0)) << 8);
	uint16_t temp = (val[3] & 0xE0) << 8 | val[2];

	// XXX leaving this in until new calculation method has been cross-checked
	//diff_pres_pa = abs(diff_pres_pa - (16384 / 2.0f));
	//diff_pres_pa -= _diff_pres_offset;
	int16_t dp_raw = 0, dT_raw = 0;
	dp_raw = (val[0] << 8) + val[1];
	dp_raw = 0x3FFF & dp_raw;
	dT_raw = (val[2] << 8) + val[3];
	dT_raw = (0xFFE0 & dT_raw) >> 5;
	float temperature = ((200 * dT_raw) / 2047) - 50;

	// XXX we may want to smooth out the readings to remove noise.

	// Calculate differential pressure. As its centered around 8000
	// and can go positive or negative, enforce absolute value
	uint16_t diff_press_pa = abs(dp_raw - (16384 / 2.0f));

	_reports[_next_report].timestamp = hrt_absolute_time();
	_reports[_next_report].temperature = temperature;
	_reports[_next_report].differential_pressure_pa = diff_press_pa;

	// Track maximum differential pressure measured (so we can work out top speed).
	if (diff_press_pa > _reports[_next_report].max_differential_pressure_pa) {
		_reports[_next_report].max_differential_pressure_pa = diff_press_pa;
	}

	/* announce the airspeed if needed, just publish else */
	orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &_reports[_next_report]);

	/* post a report to the ring - note, not locked */
	INCREMENT(_next_report, _num_reports);

	/* if we are running up against the oldest report, toss it */
	if (_next_report == _oldest_report) {
		perf_count(_buffer_overflows);
		INCREMENT(_oldest_report, _num_reports);
	}

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

	perf_end(_sample_perf);

	return ret;
}
Exemplo n.º 23
0
// Lua: mcu.read( pin )
static int mcu_in_read( lua_State* L )
{
    static uint8_t adc_inc = 0, len;
    uint8_t txdata[32], txbuf[16], rxdata[32], rxbuf[16], ret = 0, i;
    uint16_t phVal, vrefVal;
    float oph = 4.8387, vref, pHvalue, pHvolt;

    txdata[0] = CMD_READ_ANALOG;
    txdata[1] = lua_tointeger( L, 1 );
    txdata[2] = adc_inc ++;

    len = proto_create(txdata, txbuf, 3);
    transfer(txbuf, NULL, 16);
    os_delay_us(2000);
    txbuf[0] = 0x7E;
    txbuf[1] = 0xFF;
    txbuf[2] = 0x7F;
    transfer(txbuf, rxbuf, 16);  /*begin transfer*/

    for(i=0; i<16; i++)
        proto_parse(rxbuf[i], rxdata);

    //lua_pushinteger( L, rxdata[10]);


    switch(rxdata[1]) {
    case IN_WATER:
        lua_pushinteger( L, *(uint16_t *) &rxdata[2]);
        lua_pushinteger( L, *(uint16_t *) &rxdata[4]);
        ret += 2;
        break;
    case IN_PH:
        phVal = *(uint16_t *) &rxdata[6];
        vrefVal = *(uint16_t *) &rxdata[10];


        vref = (((float)4096*1.2)/vrefVal);
        pHvolt = ((float)phVal*vref)/4096;

        // pH 7.0 -> pHvolt = 1.75
        if(pHvolt >= 1.75)
        {
            pHvalue = 7.0 - ((pHvolt-1.75)*oph);
        }
        else
        {
            pHvalue = 7.0 + ((1.75-pHvolt)*oph);
        }
        //lua_pushinteger( L, phVal);
        //lua_pushinteger( L, vrefVal);
        lua_pushnumber( L, pHvalue);
        ret += 1;
        break;
    case IN_EC:
        lua_pushinteger( L, *(uint16_t *) &rxdata[8]);
        ret += 1;
        break;
    case IN_TEMP:
        lua_pushinteger( L, *(uint8_t *) &rxdata[2]);
        ret = 1;
        break;
    case IN_HUM:
        lua_pushinteger( L, *(uint8_t *) &rxdata[3]);
        ret = 1;
        break;
    case IN_ENV_TEMP:
        lua_pushinteger( L, *(uint8_t *) &rxdata[4]);
        ret = 1;
        break;
    default:
        lua_pushinteger( L, 0);
        ret = 1;
    }
    //while(platform_gpio_read( PIN_GPIO2 ) == 0);
    return ret;
}
Exemplo n.º 24
0
bool use_case_5_driver(stk::ParallelMachine  comm)
{
  stk::diag::Timer timer("Transfer Use Case 5",
                          use_case::TIMER_TRANSFER,
                          use_case::timer());
  stk::diag::Timer timer_point_to_point(" Point To Point", timer);
  use_case::timerSet().setEnabledTimerMask(use_case::TIMER_ALL);

  bool status = true;

  const double TOLERANCE = 0.000001;
  const double  rand_max = RAND_MAX;
  enum {           DIM = 3  };
  enum { FROMNUMPOINTS = 100  };
  enum {   TONUMPOINTS = 100  };

  typedef Intrepid::FieldContainer<double>  MDArray;

  MDArray FromPoints (FROMNUMPOINTS,DIM),
          ToPoints   (  TONUMPOINTS,DIM),
          FromValues (FROMNUMPOINTS,  2),
          ToValues   (  TONUMPOINTS,  2);
  for (unsigned i=0 ; i<FROMNUMPOINTS; ++i) {
    double l=0, q=0;
    for (unsigned j=0 ; j<DIM; ++j) {
      FromPoints(i,j) = rand()/rand_max;
      l +=   FromPoints(i,j);
      q += j*FromPoints(i,j);
    }
    FromValues(i,0) = l;
    FromValues(i,1) = q;
  }
  for (unsigned i=0 ; i<TONUMPOINTS; ++i) {
    for (unsigned j=0 ; j<DIM; ++j) {
      ToPoints(i,j) = rand()/rand_max;
    }
  }

  const double initial_radius   = .05;
  boost::shared_ptr<stk::transfer::MDMesh >
    transfer_domain_mesh (new stk::transfer::MDMesh(FromValues, FromPoints, initial_radius, comm));
  boost::shared_ptr<stk::transfer::MDMesh >
    transfer_range_mesh  (new stk::transfer::MDMesh(  ToValues, ToPoints,   initial_radius, comm));

  stk::transfer::GeometricTransfer<
    class stk::transfer::LinearInterpolate<
      class stk::transfer::MDMesh,
      class stk::transfer::MDMesh
    >
  >
  transfer(transfer_domain_mesh, transfer_range_mesh, "STK Transfer test Use case 5");
  {
    stk::diag::TimeBlock __timer_point_to_point(timer_point_to_point);
    try {
      transfer.initialize();
      transfer.apply();
    } catch (std::exception &e) {
      std::cout <<__FILE__<<":"<<__LINE__
                <<" Caught an std::exception with what string:"
                <<e.what()
                <<"      rethrowing....."
                <<std::endl;
      status = status && false;
    } catch (...) {
      std::cout <<__FILE__<<":"<<__LINE__
                <<" Caught an exception, rethrowing..."
                <<std::endl;
      status = status && false;
    }
  }

  if (status) {
    bool success = true;
    for (unsigned i=0 ; i<TONUMPOINTS; ++i) {
      double check_l = 0;
      double check_q = 0;
      for (unsigned j=0 ; j<DIM; ++j) {
        check_l +=   ToPoints(i,j);
        check_q += j*ToPoints(i,j);
      }
      if (TOLERANCE < fabs(check_l-ToValues(i,0)) ) {
        std::cout <<__FILE__<<":"<<__LINE__
                  <<" ToValues:"<<ToValues(i,0)
                  <<" check:"<<check_l
                  <<" error:"<<fabs(check_l-ToValues(i,0))
                  <<std::endl;
        success = false;
      }
      if (TOLERANCE < fabs(check_q-ToValues(i,1)) ) {
        std::cout <<__FILE__<<":"<<__LINE__
                  <<" ToValues:"<<ToValues(i,1)
                  <<" check:"<<check_q
                  <<" error:"<<fabs(check_q-ToValues(i,1))
                  <<std::endl;
        success = false;
      }
    }
    status = status && success;
  }
  timer.stop();

  const bool collective_result = use_case::print_status(comm, status);
  return collective_result;
}
Exemplo n.º 25
0
int
ETSAirspeed::collect()
{
	int	ret = -EIO;

	/* read from the sensor */
	uint8_t val[2] = {0, 0};

	perf_begin(_sample_perf);

	ret = transfer(nullptr, 0, &val[0], 2);

	if (ret < 0) {
		perf_count(_comms_errors);
		return ret;
	}

	uint16_t diff_pres_pa_raw = val[1] << 8 | val[0];
	uint16_t diff_pres_pa;
        if (diff_pres_pa_raw == 0) {
		// a zero value means the pressure sensor cannot give us a
		// value. We need to return, and not report a value or the
		// caller could end up using this value as part of an
		// average
		perf_count(_comms_errors);
		log("zero value from sensor"); 
		return -1;
        }

	if (diff_pres_pa_raw < _diff_pres_offset + MIN_ACCURATE_DIFF_PRES_PA) {
		diff_pres_pa = 0;
	} else {
		diff_pres_pa = diff_pres_pa_raw - _diff_pres_offset;
	}

	// The raw value still should be compensated for the known offset
	diff_pres_pa_raw -= _diff_pres_offset;

	// Track maximum differential pressure measured (so we can work out top speed).
	if (diff_pres_pa > _max_differential_pressure_pa) {
		_max_differential_pressure_pa = diff_pres_pa;
	}

	differential_pressure_s report;
	report.timestamp = hrt_absolute_time();
        report.error_count = perf_event_count(_comms_errors);
	report.differential_pressure_pa = (float)diff_pres_pa;

	// XXX we may want to smooth out the readings to remove noise.
	report.differential_pressure_filtered_pa = (float)diff_pres_pa;
	report.differential_pressure_raw_pa = (float)diff_pres_pa_raw;
	report.temperature = -1000.0f;
	report.max_differential_pressure_pa = _max_differential_pressure_pa;

	if (_airspeed_pub > 0 && !(_pub_blocked)) {
		/* publish it */
		orb_publish(ORB_ID(differential_pressure), _airspeed_pub, &report);
	}

	new_report(report);

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	ret = OK;

	perf_end(_sample_perf);

	return ret;
}
Exemplo n.º 26
0
void
LSM303D::measure()
{
	// if the accel doesn't have any data ready then re-schedule
	// for 100 microseconds later. This ensures we don't double
	// read a value and then miss the next value
	if (stm32_gpioread(GPIO_EXTI_ACCEL_DRDY) == 0) {
		perf_count(_accel_reschedules);
		hrt_call_delay(&_accel_call, 100);
		return;
	}
	if (read_reg(ADDR_CTRL_REG1) != _reg1_expected) {
		perf_count(_reg1_resets);
		reset();
		return;
	}

	/* status register and data as read back from the device */

#pragma pack(push, 1)
	struct {
		uint8_t		cmd;
		uint8_t		status;
		int16_t		x;
		int16_t		y;
		int16_t		z;
	} raw_accel_report;
#pragma pack(pop)

	accel_report accel_report;

	/* start the performance counter */
	perf_begin(_accel_sample_perf);

	/* fetch data from the sensor */
	memset(&raw_accel_report, 0, sizeof(raw_accel_report));
	raw_accel_report.cmd = ADDR_STATUS_A | DIR_READ | ADDR_INCREMENT;
	transfer((uint8_t *)&raw_accel_report, (uint8_t *)&raw_accel_report, sizeof(raw_accel_report));

	/*
	 * 1) Scale raw value to SI units using scaling from datasheet.
	 * 2) Subtract static offset (in SI units)
	 * 3) Scale the statically calibrated values with a linear
	 *    dynamically obtained factor
	 *
	 * Note: the static sensor offset is the number the sensor outputs
	 * 	 at a nominally 'zero' input. Therefore the offset has to
	 * 	 be subtracted.
	 *
	 *	 Example: A gyro outputs a value of 74 at zero angular rate
	 *	 	  the offset is 74 from the origin and subtracting
	 *		  74 from all measurements centers them around zero.
	 */


	accel_report.timestamp = hrt_absolute_time();
        accel_report.error_count = 0; // not reported

	accel_report.x_raw = raw_accel_report.x;
	accel_report.y_raw = raw_accel_report.y;
	accel_report.z_raw = raw_accel_report.z;

	float x_in_new = ((accel_report.x_raw * _accel_range_scale) - _accel_scale.x_offset) * _accel_scale.x_scale;
	float y_in_new = ((accel_report.y_raw * _accel_range_scale) - _accel_scale.y_offset) * _accel_scale.y_scale;
	float z_in_new = ((accel_report.z_raw * _accel_range_scale) - _accel_scale.z_offset) * _accel_scale.z_scale;

	accel_report.x = _accel_filter_x.apply(x_in_new);
	accel_report.y = _accel_filter_y.apply(y_in_new);
	accel_report.z = _accel_filter_z.apply(z_in_new);

	accel_report.scaling = _accel_range_scale;
	accel_report.range_m_s2 = _accel_range_m_s2;

	_accel_reports->force(&accel_report);

	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	if (_accel_topic != -1) {
		/* publish for subscribers */
		orb_publish(ORB_ID(sensor_accel), _accel_topic, &accel_report);
	}

	_accel_read++;

	/* stop the perf counter */
	perf_end(_accel_sample_perf);
}
Exemplo n.º 27
0
void postMiscProduction::sPost()
{
  _qty = _qtyToPost->toDouble();
  if (_disassembly->isChecked())
    _qty = _qty * -1;
  
  if (_qty == 0)
  {
    QMessageBox::warning( this, tr("Invalid Quantity"),
                        tr( "The quantity may not be zero." ) );
    return;
  }
  
  if (_immediateTransfer->isChecked())
  {
    if (_warehouse->id() == _transferWarehouse->id())
    {
      QMessageBox::warning( this, tr("Cannot Post Immediate Transfer"),
                            tr( "Transaction canceled. Cannot post an immediate transfer for the newly posted production as the\n"
                                "transfer Site is the same as the production Site.  You must manually\n"
                                "transfer the production to the intended Site." ) );
      return;
    }
  }
  
  q.prepare( "SELECT itemsite_id "
             "FROM itemsite "
             "WHERE ( (itemsite_item_id=:item_id)"
             " AND (itemsite_warehous_id=:warehous_id) );" );
  q.bindValue(":item_id", _item->id());
  if (_qty > 0)
    q.bindValue(":warehous_id", _warehouse->id());
  else
    q.bindValue(":warehous_id", _transferWarehouse->id());
  q.exec();
  if (q.first())
  {
    _itemsiteid = q.value("itemsite_id").toInt();

    XSqlQuery rollback;
    rollback.prepare("ROLLBACK;");

    q.exec("BEGIN;");	// because of possible lot, serial, or location distribution cancelations
    
    if (_qty > 0)
    {
      if (post())
      {
        if (_immediateTransfer->isChecked())
        {
          if (transfer())
            q.exec("COMMIT;");
          else
            rollback.exec();
        }
        else
          q.exec("COMMIT;");
      }
      else
        rollback.exec();
    }
    else
    {
      _sense = -1;
      if (_immediateTransfer->isChecked())
      {
        if (transfer())
        {
          if (post())
            q.exec("COMMIT;");
          else
            rollback.exec();
        }
        else
          rollback.exec();
      }
      else
      {
        if (post())
          q.exec("COMMIT;");
        else
          rollback.exec();
      }
    }

    if (_captive)
      accept();
    else
    {
      _item->setId(-1);
      _qtyToPost->clear();
      _documentNum->clear();
      _comments->clear();
      _close->setText(tr("&Close"));

      _item->setFocus();
    }
  }
  else
    systemError(this, tr("A System Error occurred at %1::%2, Item Number %3.")
                      .arg(__FILE__)
                      .arg(__LINE__)
                      .arg(_item->itemNumber()) );
}
Exemplo n.º 28
0
void
LSM303D::mag_measure()
{
	if (read_reg(ADDR_CTRL_REG7) != _reg7_expected) {
		perf_count(_reg7_resets);
		reset();
		return;
	}

	/* status register and data as read back from the device */
#pragma pack(push, 1)
	struct {
		uint8_t		cmd;
		uint8_t		status;
		int16_t		x;
		int16_t		y;
		int16_t		z;
	} raw_mag_report;
#pragma pack(pop)

	mag_report mag_report;

	/* start the performance counter */
	perf_begin(_mag_sample_perf);

	/* fetch data from the sensor */
	memset(&raw_mag_report, 0, sizeof(raw_mag_report));
	raw_mag_report.cmd = ADDR_STATUS_M | DIR_READ | ADDR_INCREMENT;
	transfer((uint8_t *)&raw_mag_report, (uint8_t *)&raw_mag_report, sizeof(raw_mag_report));

	/*
	 * 1) Scale raw value to SI units using scaling from datasheet.
	 * 2) Subtract static offset (in SI units)
	 * 3) Scale the statically calibrated values with a linear
	 *    dynamically obtained factor
	 *
	 * Note: the static sensor offset is the number the sensor outputs
	 * 	 at a nominally 'zero' input. Therefore the offset has to
	 * 	 be subtracted.
	 *
	 *	 Example: A gyro outputs a value of 74 at zero angular rate
	 *	 	  the offset is 74 from the origin and subtracting
	 *		  74 from all measurements centers them around zero.
	 */


	mag_report.timestamp = hrt_absolute_time();

	mag_report.x_raw = raw_mag_report.x;
	mag_report.y_raw = raw_mag_report.y;
	mag_report.z_raw = raw_mag_report.z;
	mag_report.x = ((mag_report.x_raw * _mag_range_scale) - _mag_scale.x_offset) * _mag_scale.x_scale;
	mag_report.y = ((mag_report.y_raw * _mag_range_scale) - _mag_scale.y_offset) * _mag_scale.y_scale;
	mag_report.z = ((mag_report.z_raw * _mag_range_scale) - _mag_scale.z_offset) * _mag_scale.z_scale;
	mag_report.scaling = _mag_range_scale;
	mag_report.range_ga = (float)_mag_range_ga;

	_mag_reports->force(&mag_report);

	/* XXX please check this poll_notify, is it the right one? */
	/* notify anyone waiting for data */
	poll_notify(POLLIN);

	if (_mag->_mag_topic != -1) {
		/* publish for subscribers */
		orb_publish(ORB_ID(sensor_mag), _mag->_mag_topic, &mag_report);
	}

	_mag_read++;

	/* stop the perf counter */
	perf_end(_mag_sample_perf);
}
Exemplo n.º 29
0
int main(int argc, char **argv)
{
    int c, v = 0;
    int fd, fd_done, fd_int_b, fd_prog_b;
    char *name;
    char *spidev = DEFAULT_SPIDEV;
    char byte[2], mode = SPI_MODE_2;

    while ((c = getopt(argc, argv, "hm:d:v")) != EOF) {
        switch (c) {
        case 'd':
            spidev = optarg;
            continue;
        case 'm':
            mode = atoi(optarg);
            continue;
        case 'v':
            v++;
            break;
        case 'h':
        case '?':
usage:
            fprintf(stderr,
                    "usage: %s [-hv] [-d /dev/spidevB.D] [-m SPI_MODE] infile\n",
                    argv[0]);
            return 1;
        }
    }

    if ((optind + 1) != argc)
        goto usage;
    name = argv[optind];

    if (v) {
        printf("Config File\t\t: %s\n", name);
        printf("SPI device\t\t: %s\n", spidev);
    }

    fd = open(spidev, O_RDWR);
    if (fd < 0) {
        perror(spidev);
        return errno;
    }

    ioctl(fd, SPI_IOC_WR_MODE, &mode);

    fd_done = open(DEFAULT_DONE, O_RDWR);
    if (fd_done < 0) {
        perror(DEFAULT_DONE);
        return errno;
    }

    fd_int_b = open(DEFAULT_INT_B, O_RDWR);
    if (fd_int_b < 0) {
        perror(DEFAULT_INT_B);
        return errno;
    }

    fd_prog_b = open(DEFAULT_PROG_B, O_RDWR);
    if (fd_prog_b < 0) {
        perror(DEFAULT_PROG_B);
        return errno;
    }

    dumpstat(spidev, fd);

    write(fd_int_b, "I", 1);
    write(fd_done, "I", 1);

    /*
     * PROG_B should never be driven high by Blackfin.
     * Simulate open drain output. Configure as input
     * for HI and drive 0 for LOW.
     */

    write(fd_prog_b, "O0", 2);

    /*
     * Pulse PROG_B to initiate configuration sequence
     */

    usleep(1);
    write(fd_prog_b, "I", 1);
    close(fd_prog_b);

    if (v)
        printf("Waiting INT_B -> HIGH\n");

    alarm(TIMEOUT);

    /*
     * Monitor INIT_B pin goes High,
     * indicating that the FPGA is ready to receive its first data.
     */

    while (1) {
        if (read(fd_int_b, byte, 1) != 1)
            perror("unable to read device");

        if (byte[0] == '1')
            break;
        usleep(10);
    }

    close(fd_int_b);

    transfer(fd, name); /* Send FPGA bitfile by SPI */

    alarm(TIMEOUT);

    /*
     * Continue supplying data and clock signals
     * until either the DONE pin goes High, indicating a successful
     * configuration, or until the INIT_B pin goes Low, indicating a
     * configuration error.
     */

    if (v)
        printf("\nWaiting CONFIG DONE\n");

    while (1) {
        if (read(fd_done, byte, 1) != 1)
            perror("unable to read device");

        if (byte[0] == '1')
            break;
        /*
         * The configuration process requires
         * more clock cycles than indicated from the configuration file
         * size. Additional clocks are required during the FPGA's
         * start-up sequence.
         */

        write(fd, copybuf, sizeof(copybuf));
    }

    close(fd);
    close(fd_done);

    alarm(0);

    if (v)
        printf(" DONE!\n");
    else
        printf("\n");

    return 0;
}
Exemplo n.º 30
0
void JExtractorPlugin::setPersistentVariable(QString key, QVariant value)
{
	static_cast<JavaExtractor*>(transfer())->setPersistentVariable(key, value);
}